Skip to main content

day_core/
services.rs

1// Copyright © The Daybrite Project
2// SPDX-License-Identifier: MPL-2.0
3
4//! Process services that must initialize before a window or reactive tree exists.
5//!
6//! Optional parts register initializers at link time. Initializers run on the native startup
7//! thread once per process and must return promptly. They may register OS callbacks; they must
8//! not access UI signals or mount widgets. Android services can initialize this registry after
9//! attaching the JVM without starting an Activity.
10
11use std::sync::Once;
12
13/// A process initializer supplied by an optional part.
14pub struct Service {
15    pub name: &'static str,
16    pub initialize: fn(),
17}
18
19#[cfg(not(target_arch = "wasm32"))]
20#[linkme::distributed_slice]
21pub static SERVICES: [Service];
22
23/// Initialize linked process services. A native host calls this after its runtime is ready.
24pub fn initialize() {
25    static ONCE: Once = Once::new();
26    ONCE.call_once(|| {
27        #[cfg(not(target_arch = "wasm32"))]
28        for service in SERVICES {
29            (service.initialize)();
30        }
31    });
32}
33
34/// Native notification delivery before or after a window exists. Handlers must return promptly
35/// and use a main-thread setter to update UI state. Payloads are JSON from the platform.
36#[derive(Clone)]
37pub enum NotificationEvent {
38    Registered(Vec<u8>),
39    RegistrationFailed(String),
40    Received { payload: String, opened: bool },
41}
42
43impl std::fmt::Debug for NotificationEvent {
44    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
45        match self {
46            Self::Registered(_) => f.debug_tuple("Registered").finish_non_exhaustive(),
47            Self::RegistrationFailed(error) => {
48                f.debug_tuple("RegistrationFailed").field(error).finish()
49            }
50            Self::Received { opened, .. } => f
51                .debug_struct("Received")
52                .field("opened", opened)
53                .finish_non_exhaustive(),
54        }
55    }
56}
57
58#[cfg(not(target_arch = "wasm32"))]
59#[linkme::distributed_slice]
60pub static NOTIFICATION_HANDLERS: [fn(&NotificationEvent)];
61
62/// Forward a native delegate callback to linked optional parts.
63pub fn notification(event: NotificationEvent) {
64    #[cfg(not(target_arch = "wasm32"))]
65    for handler in NOTIFICATION_HANDLERS {
66        handler(&event);
67    }
68    #[cfg(target_arch = "wasm32")]
69    let _ = event;
70}
71
72/// Android's headless host has a JVM and application Context but no widget tree.
73#[cfg(target_os = "android")]
74#[unsafe(no_mangle)]
75pub extern "system" fn Java_dev_daybrite_day_bridge_DayRuntime_initializeServices(
76    mut env: day_platform_android::jni::EnvUnowned,
77    class: day_platform_android::jni::objects::JClass,
78) {
79    env.with_env(|env| -> day_platform_android::jni::errors::Result<()> {
80        day_platform_android::init(env, &class)?;
81        initialize();
82        Ok(())
83    })
84    .resolve::<day_platform_android::jni::errors::ThrowRuntimeExAndDefault>();
85}