1use std::marker::PhantomData;
35use std::sync::{Mutex, MutexGuard};
36
37static HELD: Mutex<u32> = Mutex::new(0);
40
41fn held() -> MutexGuard<'static, u32> {
42 HELD.lock()
44 .unwrap_or_else(std::sync::PoisonError::into_inner)
45}
46
47#[must_use]
49pub fn is_supported() -> bool {
50 imp::supported()
51}
52
53#[must_use]
55pub fn is_held() -> bool {
56 *held() > 0
57}
58
59#[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
72pub struct ScreenLock {
74 _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 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 const LEVEL_ON: u32 = 255;
137
138 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 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 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 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 #[day_bridge::declare]
246 extern "day" {
247 fn hold_native(on: bool);
249 fn ready_native() -> Result<bool, day_bridge::Error>;
251 }
252
253 #[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 #[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 #[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 #[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}