Skip to main content

day_part_wakelock/
lib.rs

1// Copyright © The Daybrite Project
2// SPDX-License-Identifier: MPL-2.0
3
4//! day-part-wakelock is headless: it keeps the screen on while something is showing.
5//!
6//! ```no_run
7//! let lock = day_part_wakelock::keep_screen_on();
8//! // The screen stays on, whatever the device's auto-lock setting, until the lock is dropped.
9//! drop(lock);
10//! ```
11//!
12//! Locks nest: the screen may sleep again once the last one is dropped. In a Day app, tie a lock to
13//! the page's scope so a page that closes releases it:
14//!
15//! ```ignore
16//! let lock = day_part_wakelock::keep_screen_on();
17//! day_reactive::Scope::current().on_cleanup(move || drop(lock));
18//! ```
19//!
20//! | Platform | Mechanism |
21//! |---|---|
22//! | iOS | `UIApplication.isIdleTimerDisabled` |
23//! | macOS | an IOKit power assertion, `PreventUserIdleDisplaySleep` |
24//! | Windows | `SetThreadExecutionState(ES_CONTINUOUS \| ES_DISPLAY_REQUIRED)` |
25//! | Android | `FLAG_KEEP_SCREEN_ON` on the activity's window |
26//! | HarmonyOS | `Window.setWindowKeepScreenOn` |
27//! | web | the Screen Wake Lock API, taken again each time the page becomes visible |
28//! | Linux | none yet: [`is_supported`] is false and a lock does nothing |
29//!
30//! Take and drop locks on the UI thread, where a Day app's code runs: UIKit and Windows tie the
31//! setting to it, so [`ScreenLock`] is not `Send`. Nothing here returns an error or panics; a
32//! platform that cannot keep the screen on lets it sleep.
33
34use std::marker::PhantomData;
35use std::sync::{Mutex, MutexGuard};
36
37/// How many [`ScreenLock`]s are alive. One process-wide lock rather than a thread-local: each
38/// `thread_local!` costs Android a pthread key, and bionic has only 128 for the whole process.
39static HELD: Mutex<u32> = Mutex::new(0);
40
41fn held() -> MutexGuard<'static, u32> {
42    // A counter cannot be left half-written, so a poisoned lock is still usable.
43    HELD.lock()
44        .unwrap_or_else(std::sync::PoisonError::into_inner)
45}
46
47/// Whether this platform can keep the screen on.
48#[must_use]
49pub fn is_supported() -> bool {
50    imp::supported()
51}
52
53/// Whether a [`ScreenLock`] is alive anywhere in the app.
54#[must_use]
55pub fn is_held() -> bool {
56    *held() > 0
57}
58
59/// Keep the screen on until the returned lock is dropped.
60#[must_use = "the screen may sleep again as soon as the lock is dropped"]
61pub fn keep_screen_on() -> ScreenLock {
62    let mut n = held();
63    *n += 1;
64    if *n == 1 {
65        imp::hold(true);
66    }
67    ScreenLock {
68        _ui_thread: PhantomData,
69    }
70}
71
72/// The screen stays on while this lives ([`keep_screen_on`]).
73pub struct ScreenLock {
74    /// Not `Send`: the platform setting is released on the thread that took it.
75    _ui_thread: PhantomData<*const ()>,
76}
77
78impl Drop for ScreenLock {
79    fn drop(&mut self) {
80        let mut n = held();
81        *n = n.saturating_sub(1);
82        if *n == 0 {
83            imp::hold(false);
84        }
85    }
86}
87
88#[cfg(target_os = "ios")]
89mod imp {
90    use objc2::MainThreadMarker;
91    use objc2_ui_kit::UIApplication;
92
93    pub fn supported() -> bool {
94        true
95    }
96
97    pub fn hold(on: bool) {
98        // UIApplication is main-thread only. Day runs app code there; a call from anywhere else is
99        // skipped rather than risking UIKit off its thread.
100        if let Some(mtm) = MainThreadMarker::new() {
101            UIApplication::sharedApplication(mtm).setIdleTimerDisabled(on);
102        }
103    }
104}
105
106#[cfg(target_os = "macos")]
107mod imp {
108    use std::ffi::{c_char, c_void};
109    use std::sync::Mutex;
110
111    type CFStringRef = *const c_void;
112
113    #[link(name = "CoreFoundation", kind = "framework")]
114    unsafe extern "C" {
115        fn CFStringCreateWithCString(
116            alloc: *const c_void,
117            text: *const c_char,
118            encoding: u32,
119        ) -> CFStringRef;
120        fn CFRelease(value: *const c_void);
121    }
122
123    #[link(name = "IOKit", kind = "framework")]
124    unsafe extern "C" {
125        fn IOPMAssertionCreateWithName(
126            kind: CFStringRef,
127            level: u32,
128            name: CFStringRef,
129            id: *mut u32,
130        ) -> i32;
131        fn IOPMAssertionRelease(id: u32) -> i32;
132    }
133
134    const UTF8: u32 = 0x0800_0100;
135    /// `kIOPMAssertionLevelOn`.
136    const LEVEL_ON: u32 = 255;
137
138    /// The assertion while one is held; `pmset -g assertions` lists it under the app's process.
139    static ASSERTION: Mutex<Option<u32>> = Mutex::new(None);
140
141    pub fn supported() -> bool {
142        true
143    }
144
145    pub fn hold(on: bool) {
146        let mut held = ASSERTION
147            .lock()
148            .unwrap_or_else(std::sync::PoisonError::into_inner);
149        if on && held.is_none() {
150            // SAFETY: both strings are NUL-terminated literals; each CFString made here is released
151            // here, and IOKit copies what it keeps. `id` is written only on success.
152            unsafe {
153                let kind = CFStringCreateWithCString(
154                    std::ptr::null(),
155                    c"PreventUserIdleDisplaySleep".as_ptr(),
156                    UTF8,
157                );
158                let name = CFStringCreateWithCString(
159                    std::ptr::null(),
160                    c"Keeping the screen on while the app shows something".as_ptr(),
161                    UTF8,
162                );
163                let mut id = 0u32;
164                if !kind.is_null()
165                    && !name.is_null()
166                    && IOPMAssertionCreateWithName(kind, LEVEL_ON, name, &raw mut id) == 0
167                {
168                    *held = Some(id);
169                }
170                for s in [kind, name] {
171                    if !s.is_null() {
172                        CFRelease(s);
173                    }
174                }
175            }
176        } else if !on && let Some(id) = held.take() {
177            // SAFETY: `id` came from a successful IOPMAssertionCreateWithName and is released once.
178            unsafe {
179                IOPMAssertionRelease(id);
180            }
181        }
182    }
183}
184
185#[cfg(windows)]
186mod imp {
187    use windows::Win32::System::Power::{
188        ES_CONTINUOUS, ES_DISPLAY_REQUIRED, SetThreadExecutionState,
189    };
190
191    pub fn supported() -> bool {
192        true
193    }
194
195    pub fn hold(on: bool) {
196        let state = if on {
197            ES_CONTINUOUS | ES_DISPLAY_REQUIRED
198        } else {
199            ES_CONTINUOUS
200        };
201        // SAFETY: a plain Win32 call with documented flags. The state belongs to the calling
202        // thread, which is why ScreenLock is not Send.
203        unsafe {
204            SetThreadExecutionState(state);
205        }
206    }
207}
208
209#[cfg(any(
210    target_os = "android",
211    all(target_os = "linux", target_env = "ohos"),
212    target_arch = "wasm32"
213))]
214mod imp {
215    use day_bridge::Support;
216
217    pub fn supported() -> bool {
218        super::ready_native_support() != Support::Unsupported
219            && super::ready_native().unwrap_or(false)
220    }
221
222    pub fn hold(on: bool) {
223        super::hold_native(on);
224    }
225}
226
227#[cfg(not(any(
228    target_os = "ios",
229    target_os = "macos",
230    windows,
231    target_os = "android",
232    all(target_os = "linux", target_env = "ohos"),
233    target_arch = "wasm32"
234)))]
235mod imp {
236    pub fn supported() -> bool {
237        false
238    }
239
240    pub fn hold(_on: bool) {}
241}
242
243day_bridge::bridge! {
244    // The contract the foreign arms implement.
245    #[day_bridge::declare]
246    extern "day" {
247        /// Keep the screen on, or let it sleep again.
248        fn hold_native(on: bool);
249        /// Whether this platform can keep the screen on.
250        fn ready_native() -> Result<bool, day_bridge::Error>;
251    }
252
253    // Android: a window flag, which holds only while that window is showing, so leaving the app
254    // lets the screen sleep with no bookkeeping here. `DayRuntime.ctx` is the running activity.
255    #[day_bridge::impl(java, platforms = [android])]
256    java!(
257        prelude = r#"
258            import android.app.Activity;
259            import android.content.Context;
260            import android.view.WindowManager;
261            import dev.daybrite.day.bridge.DayRuntime;
262        "#,
263        body = r#"
264            public static void hold_native(boolean on) {
265                Context ctx = DayRuntime.ctx;
266                if (!(ctx instanceof Activity)) {
267                    return;
268                }
269                Activity activity = (Activity) ctx;
270                // Window flags belong to the UI thread.
271                DayRuntime.main.post(() -> {
272                    if (on) {
273                        activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
274                    } else {
275                        activity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
276                    }
277                });
278            }
279
280            public static boolean ready_native() {
281                return DayRuntime.ctx instanceof Activity;
282            }
283        "#,
284    );
285
286    // HarmonyOS: the window's keep-screen-on switch, like Android's flag.
287    #[day_bridge::impl(arkts, platforms = [ohos])]
288    arkts!(
289        prelude = r#"
290            import { window } from '@kit.ArkUI';
291            import { common } from '@kit.AbilityKit';
292        "#,
293        body = r#"
294            export function hold_native(on: boolean): void {
295                const ctx = getContext() as common.UIAbilityContext;
296                window.getLastWindow(ctx).then((win: window.Window) => {
297                    return win.setWindowKeepScreenOn(on);
298                }).catch((e: Error) => {
299                    console.warn(`day-part-wakelock: ${e.message}`);
300                });
301            }
302
303            export function ready_native(): boolean {
304                return true;
305            }
306        "#,
307    );
308
309    // The web: the Screen Wake Lock API. The browser releases the lock whenever the page is hidden,
310    // so it is taken again each time the page comes back while the app still wants it.
311    #[day_bridge::impl(js, platforms = [web])]
312    js!(r#"
313        let dayLock = null;
314        let dayWanted = false;
315        let dayListening = false;
316
317        async function dayTake() {
318            if (!dayWanted || dayLock !== null || document.visibilityState !== "visible") {
319                return;
320            }
321            try {
322                const lock = await navigator.wakeLock.request("screen");
323                if (!dayWanted) {
324                    lock.release();
325                    return;
326                }
327                dayLock = lock;
328                lock.addEventListener("release", () => {
329                    if (dayLock === lock) {
330                        dayLock = null;
331                    }
332                });
333            } catch (e) {
334                console.warn(`day-part-wakelock: ${e}`);
335            }
336        }
337
338        export function hold_native(on) {
339            if (!("wakeLock" in navigator)) {
340                return;
341            }
342            dayWanted = Boolean(on);
343            if (!dayListening) {
344                dayListening = true;
345                document.addEventListener("visibilitychange", () => {
346                    dayTake();
347                });
348            }
349            if (dayWanted) {
350                dayTake();
351            } else if (dayLock !== null) {
352                dayLock.release();
353                dayLock = null;
354            }
355        }
356
357        export function ready_native() {
358            return "wakeLock" in navigator;
359        }
360    "#);
361
362    // Everywhere else, and the arm `cargo test` and day-mock compile against: the screen sleeps as
363    // usual.
364    #[day_bridge::impl(rust, platforms = [other])]
365    fn hold_native(_on: bool) {}
366
367    #[day_bridge::impl(rust, platforms = [other])]
368    fn ready_native() -> Result<bool, day_bridge::Error> {
369        Ok(false)
370    }
371}
372
373#[cfg(test)]
374mod tests {
375    use super::*;
376
377    #[test]
378    fn locks_nest() {
379        assert!(!is_held());
380        let first = keep_screen_on();
381        let second = keep_screen_on();
382        assert!(is_held());
383        drop(first);
384        assert!(is_held(), "the second lock still holds the screen");
385        drop(second);
386        assert!(!is_held());
387    }
388}