Skip to main content

euv_core/system/capabilities/
fn.rs

1use super::*;
2
3/// Registers a platform-host native OS capability bridge (haptics, notifications, permissions, fullscreen, Dynamic Island).
4///
5/// # Arguments
6///
7/// - `fn(&str, &str, &str) -> bool` - Host callback handling `(kind, arg1, arg2)` and returning whether native OS execution succeeded.
8pub fn register_native_action_bridge(bridge: fn(&str, &str, &str) -> bool) {
9    EXTERNAL_NATIVE_ACTION_BRIDGE.store(bridge as *mut (), Ordering::Release);
10}
11
12/// Dispatches a native OS capability action `(kind, arg1, arg2)` to the registered host bridge, if any.
13///
14/// # Arguments
15///
16/// - `&str` - Action category (`"haptic"`, `"notify"`, `"island"`, `"permission"`, `"fullscreen"`, `"protocol"`).
17/// - `&str` - Primary payload argument (e.g. title or permission key).
18/// - `&str` - Secondary payload argument (e.g. body or rationale).
19///
20/// # Returns
21///
22/// - `bool` - `true` when handled by an active native OS host bridge.
23pub fn dispatch_native_action(kind: &str, arg1: &str, arg2: &str) -> bool {
24    let raw: *mut () = EXTERNAL_NATIVE_ACTION_BRIDGE.load(Ordering::Acquire);
25    if raw.is_null() {
26        return false;
27    }
28    // SAFETY: `raw` is stored exclusively via `register_native_action_bridge` from a `fn(&str, &str, &str) -> bool` pointer.
29    let func: fn(&str, &str, &str) -> bool =
30        unsafe { transmute::<*mut (), fn(&str, &str, &str) -> bool>(raw) };
31    func(kind, arg1, arg2)
32}
33
34/// Copies `text` to the active OS or browser clipboard via direct platform hooks and any registered native action bridge.
35///
36/// # Arguments
37///
38/// - `&str` - UTF-8 text string to place on the system clipboard.
39///
40/// # Returns
41///
42/// - `bool` - `true` when at least one native or host clipboard sink accepted `text`.
43pub fn write_system_clipboard(text: &str) -> bool {
44    if let Ok(mut cache_guard) = NATIVE_CLIPBOARD_CACHE.lock() {
45        *cache_guard = Some(text.to_string());
46    }
47    let bridge_ok: bool =
48        dispatch_native_action(NATIVE_ACTION_CLIPBOARD, CLIPBOARD_ACTION_WRITE, text);
49    let mut accepted: bool = false;
50    #[cfg(target_os = "macos")]
51    {
52        accepted |= macos_write_pasteboard_pooled(text);
53    }
54    #[cfg(target_os = "windows")]
55    {
56        accepted |= windows_write_clipboard(text);
57    }
58    #[cfg(target_os = "linux")]
59    {
60        accepted |= linux_write_clipboard(text);
61    }
62    #[cfg(target_arch = "wasm32")]
63    {
64        accepted |= web_write_clipboard(text);
65    }
66    accepted |= bridge_ok;
67    accepted
68}
69
70/// Registers an optional host callback providing live OS clipboard reads on embedded or mobile runtimes.
71///
72/// # Arguments
73///
74/// - `fn() -> Option<String>` - Host callback returning current UTF-8 clipboard text.
75pub fn register_clipboard_read_bridge(bridge: fn() -> Option<String>) {
76    EXTERNAL_CLIPBOARD_READ_BRIDGE.store(bridge as *mut (), Ordering::Release);
77}
78
79/// Clears any registered host clipboard read callback.
80pub fn clear_clipboard_read_bridge() {
81    EXTERNAL_CLIPBOARD_READ_BRIDGE.store(null_mut(), Ordering::Release);
82}
83
84/// Registers an optional host callback providing live OS light/dark theme detection.
85///
86/// # Arguments
87///
88/// - `fn() -> ThemeMode` - Host callback returning the current system appearance mode.
89pub fn register_theme_query_bridge(bridge: fn() -> ThemeMode) {
90    EXTERNAL_THEME_QUERY_BRIDGE.store(bridge as *mut (), Ordering::Release);
91}
92
93/// Clears any registered host theme query callback.
94pub fn clear_theme_query_bridge() {
95    EXTERNAL_THEME_QUERY_BRIDGE.store(null_mut(), Ordering::Release);
96}
97
98/// Clears the process-local clipboard fallback cache for isolated tests.
99pub fn clear_clipboard_cache() {
100    if let Ok(mut cache_guard) = NATIVE_CLIPBOARD_CACHE.lock() {
101        *cache_guard = None;
102    }
103}
104
105/// Reads UTF-8 plain text from the host OS system clipboard, preferring registered host bridges and native FFI with safe cache fallback.
106///
107/// # Returns
108///
109/// - `Option<String>` - Current clipboard UTF-8 string, if available.
110#[must_use]
111pub fn read_system_clipboard() -> Option<String> {
112    let raw_bridge: *mut () = EXTERNAL_CLIPBOARD_READ_BRIDGE.load(Ordering::Acquire);
113    if !raw_bridge.is_null() {
114        // SAFETY: `raw_bridge` is stored exclusively via `register_clipboard_read_bridge` from a `fn() -> Option<String>` pointer.
115        let bridge_fn: fn() -> Option<String> =
116            unsafe { transmute::<*mut (), fn() -> Option<String>>(raw_bridge) };
117        if let Some(bridged_text) = bridge_fn() {
118            return Some(bridged_text);
119        }
120    }
121    #[cfg(target_os = "macos")]
122    {
123        if let Some(native_text) = macos_read_pasteboard_pooled() {
124            return Some(native_text);
125        }
126    }
127    #[cfg(target_os = "windows")]
128    {
129        if let Some(native_text) = windows_read_clipboard() {
130            return Some(native_text);
131        }
132    }
133    #[cfg(target_os = "linux")]
134    {
135        if let Some(native_text) = linux_read_clipboard() {
136            return Some(native_text);
137        }
138    }
139    NATIVE_CLIPBOARD_CACHE
140        .lock()
141        .ok()
142        .and_then(|guard: MutexGuard<'_, Option<String>>| guard.clone())
143}
144
145/// Maps the Windows registry `AppsUseLightTheme` DWORD value into `ThemeMode`.
146///
147/// # Arguments
148///
149/// - `u32` - Registry DWORD value (`0` denotes Dark mode, non-zero denotes Light mode).
150///
151/// # Returns
152///
153/// - `ThemeMode` - Resolved `ThemeMode::Dark` or `ThemeMode::Light`.
154#[must_use]
155pub const fn parse_windows_apps_use_light_theme(dword_value: u32) -> ThemeMode {
156    if dword_value == 0 {
157        ThemeMode::Dark
158    } else {
159        ThemeMode::Light
160    }
161}
162
163/// Parses a Linux desktop theme string (such as `GTK_THEME`, `gsettings color-scheme`, or `gtk-theme`) into a `ThemeMode`.
164///
165/// # Arguments
166///
167/// - `&str` - Raw theme hint string.
168///
169/// # Returns
170///
171/// - `Option<ThemeMode>` - Detected `Dark` or `Light` preference when recognized.
172#[must_use]
173pub fn parse_linux_theme_hint(raw_hint: &str) -> Option<ThemeMode> {
174    let normalized: String = raw_hint
175        .trim()
176        .trim_matches('\'')
177        .trim_matches('"')
178        .to_ascii_lowercase();
179    if normalized.is_empty() {
180        return None;
181    }
182    if normalized.contains(THEME_HINT_DARK_MARKER) {
183        return Some(ThemeMode::Dark);
184    }
185    if normalized.contains(THEME_HINT_LIGHT_MARKER) {
186        return Some(ThemeMode::Light);
187    }
188    None
189}
190
191/// Parses a `COLORFGBG` (`"fg;bg"`) hint string into `ThemeMode` (`bg < 7` indicates dark background).
192///
193/// # Arguments
194///
195/// - `&str` - Raw `COLORFGBG` environment string.
196///
197/// # Returns
198///
199/// - `Option<ThemeMode>` - Detected appearance mode when the background ANSI index parses cleanly.
200#[must_use]
201pub fn parse_colorfgbg_theme_hint(raw_value: &str) -> Option<ThemeMode> {
202    let bg_segment: &str = raw_value.trim().rsplit(';').next()?;
203    let bg_index: u32 = bg_segment.trim().parse::<u32>().ok()?;
204    if bg_index < 7 || bg_index == 8 {
205        Some(ThemeMode::Dark)
206    } else {
207        Some(ThemeMode::Light)
208    }
209}
210
211/// Queries the active host OS light/dark appearance mode via registered bridge or native platform FFI.
212///
213/// # Returns
214///
215/// - `ThemeMode` - Live OS light or dark appearance preference.
216#[must_use]
217pub fn query_system_theme_mode() -> ThemeMode {
218    let raw_bridge: *mut () = EXTERNAL_THEME_QUERY_BRIDGE.load(Ordering::Acquire);
219    if !raw_bridge.is_null() {
220        // SAFETY: `raw_bridge` is stored exclusively via `register_theme_query_bridge` from a `fn() -> ThemeMode` pointer.
221        let bridge_fn: fn() -> ThemeMode =
222            unsafe { transmute::<*mut (), fn() -> ThemeMode>(raw_bridge) };
223        return bridge_fn();
224    }
225    let mut resolved: Option<ThemeMode> = None;
226    #[cfg(target_os = "macos")]
227    {
228        if resolved.is_none() {
229            resolved = Some(macos_system_theme());
230        }
231    }
232    #[cfg(target_os = "windows")]
233    {
234        if resolved.is_none() {
235            resolved = Some(windows_query_system_theme());
236        }
237    }
238    #[cfg(target_os = "linux")]
239    {
240        if resolved.is_none() {
241            resolved = Some(linux_query_system_theme());
242        }
243    }
244    #[cfg(target_arch = "wasm32")]
245    {
246        if resolved.is_none() {
247            resolved = Some(web_system_theme());
248        }
249    }
250    *resolved.get_or_insert(ThemeMode::Light)
251}
252
253#[cfg(target_os = "macos")]
254#[link(name = "objc")]
255unsafe extern "C" {
256    /// Pushes an Objective-C autorelease pool frame for temporary pasteboard strings.
257    ///
258    /// # Returns
259    ///
260    /// - `*mut c_void` - Autorelease pool token passed to `objc_autoreleasePoolPop`.
261    fn objc_autoreleasePoolPush() -> *mut c_void;
262    /// Pops and drains an Objective-C autorelease pool frame.
263    ///
264    /// # Arguments
265    ///
266    /// - `*mut c_void` - Pool token returned by `objc_autoreleasePoolPush`.
267    fn objc_autoreleasePoolPop(pool: *mut c_void);
268}
269
270/// Writes `text` to macOS `NSPasteboard` inside a scoped Objective-C autorelease pool.
271///
272/// # Arguments
273///
274/// - `&str` - UTF-8 text to place on the general pasteboard.
275///
276/// # Returns
277///
278/// - `bool` - `true` when `NSPasteboard.setString:forType:` succeeded.
279#[cfg(target_os = "macos")]
280fn macos_write_pasteboard_pooled(text: &str) -> bool {
281    // SAFETY: Balanced `objc_autoreleasePoolPush` / `objc_autoreleasePoolPop` pair on the calling thread.
282    let pool: *mut c_void = unsafe { objc_autoreleasePoolPush() };
283    let written: bool = macos_write_pasteboard(text);
284    // SAFETY: `pool` was returned by `objc_autoreleasePoolPush` above.
285    unsafe { objc_autoreleasePoolPop(pool) };
286    written
287}
288
289/// Reads UTF-8 plain text directly from the macOS general `NSPasteboard` via `stringForType:`.
290///
291/// # Returns
292///
293/// - `Option<String>` - Current macOS pasteboard text when available.
294#[cfg(target_os = "macos")]
295fn macos_read_pasteboard_pooled() -> Option<String> {
296    // SAFETY: Balanced `objc_autoreleasePoolPush` / `objc_autoreleasePoolPop` pair on the calling thread.
297    let pool: *mut c_void = unsafe { objc_autoreleasePoolPush() };
298    let mut result: Option<String> = None;
299    let pb_cls: *mut c_void = objc_class(CAP_OBJC_CLS_NS_PASTEBOARD);
300    let pb: *mut c_void = objc_send_ptr0(pb_cls, objc_sel(CAP_OBJC_SEL_GENERAL_PASTEBOARD));
301    if !pb.is_null() {
302        let str_for_type_sel: *mut c_void = objc_sel(CAP_OBJC_SEL_STRING_FOR_TYPE);
303        let utf8_type_ns: *mut c_void = macos_ns_string(CAP_PASTEBOARD_TYPE_UTF8);
304        let mut value_ns: *mut c_void = if utf8_type_ns.is_null() {
305            null_mut()
306        } else {
307            objc_send_ptr1(pb, str_for_type_sel, utf8_type_ns)
308        };
309        if value_ns.is_null() {
310            let legacy_type_ns: *mut c_void = macos_ns_string(CAP_PASTEBOARD_TYPE_LEGACY);
311            if !legacy_type_ns.is_null() {
312                value_ns = objc_send_ptr1(pb, str_for_type_sel, legacy_type_ns);
313            }
314        }
315        if !value_ns.is_null() {
316            let utf8_ptr: *const c_char =
317                objc_send_ptr0(value_ns, objc_sel(CAP_OBJC_SEL_UTF8_STRING)).cast::<c_char>();
318            if !utf8_ptr.is_null() {
319                // SAFETY: `NSString.UTF8String` returns a valid null-terminated UTF-8 C string while `pool` is live.
320                let extracted: String =
321                    unsafe { CStr::from_ptr(utf8_ptr).to_string_lossy().into_owned() };
322                result = Some(extracted);
323            }
324        }
325    }
326    // SAFETY: `pool` was returned by `objc_autoreleasePoolPush` above.
327    unsafe { objc_autoreleasePoolPop(pool) };
328    result
329}
330
331#[cfg(target_os = "windows")]
332#[link(name = "user32")]
333unsafe extern "system" {
334    /// Opens the Win32 clipboard for the current process.
335    ///
336    /// # Arguments
337    ///
338    /// - `isize` - Optional owner window handle (`0` for current task).
339    ///
340    /// # Returns
341    ///
342    /// - `i32` - Non-zero on success.
343    fn OpenClipboard(h_wnd_new_owner: isize) -> i32;
344    /// Closes the Win32 clipboard previously opened by `OpenClipboard`.
345    ///
346    /// # Returns
347    ///
348    /// - `i32` - Non-zero on success.
349    fn CloseClipboard() -> i32;
350    /// Empties the Win32 clipboard and transfers ownership prior to `SetClipboardData`.
351    ///
352    /// # Returns
353    ///
354    /// - `i32` - Non-zero on success.
355    fn EmptyClipboard() -> i32;
356    /// Checks whether the specified clipboard format is currently available.
357    ///
358    /// # Arguments
359    ///
360    /// - `u32` - Win32 clipboard format identifier (`CF_UNICODETEXT`).
361    ///
362    /// # Returns
363    ///
364    /// - `i32` - Non-zero when format is available.
365    fn IsClipboardFormatAvailable(format: u32) -> i32;
366    /// Retrieves a handle to Win32 clipboard data in `format`.
367    ///
368    /// # Arguments
369    ///
370    /// - `u32` - Win32 clipboard format identifier.
371    ///
372    /// # Returns
373    ///
374    /// - `*mut c_void` - Global memory handle or null.
375    fn GetClipboardData(format: u32) -> *mut c_void;
376    /// Places a global memory handle onto the Win32 clipboard in `format`.
377    ///
378    /// # Arguments
379    ///
380    /// - `u32` - Win32 clipboard format identifier.
381    /// - `*mut c_void` - Movable global memory handle allocated via `GlobalAlloc`.
382    ///
383    /// # Returns
384    ///
385    /// - `*mut c_void` - Clipboard handle on success or null on failure.
386    fn SetClipboardData(format: u32, h_mem: *mut c_void) -> *mut c_void;
387}
388
389#[cfg(target_os = "windows")]
390#[link(name = "kernel32")]
391unsafe extern "system" {
392    /// Allocates movable global memory for Win32 clipboard ownership transfer.
393    ///
394    /// # Arguments
395    ///
396    /// - `u32` - Allocation flags (`GMEM_MOVEABLE`).
397    /// - `usize` - Requested byte size.
398    ///
399    /// # Returns
400    ///
401    /// - `*mut c_void` - Global memory handle or null.
402    fn GlobalAlloc(flags: u32, bytes: usize) -> *mut c_void;
403    /// Locks a movable Win32 global memory handle and returns its writable base pointer.
404    ///
405    /// # Arguments
406    ///
407    /// - `*mut c_void` - Global memory handle.
408    ///
409    /// # Returns
410    ///
411    /// - `*mut c_void` - Base pointer or null.
412    fn GlobalLock(h_mem: *mut c_void) -> *mut c_void;
413    /// Unlocks a previously locked Win32 global memory handle.
414    ///
415    /// # Arguments
416    ///
417    /// - `*mut c_void` - Global memory handle.
418    ///
419    /// # Returns
420    ///
421    /// - `i32` - Lock status.
422    fn GlobalUnlock(h_mem: *mut c_void) -> i32;
423    /// Frees an unowned Win32 global memory handle on error paths.
424    ///
425    /// # Arguments
426    ///
427    /// - `*mut c_void` - Global memory handle.
428    ///
429    /// # Returns
430    ///
431    /// - `*mut c_void` - Null on success.
432    fn GlobalFree(h_mem: *mut c_void) -> *mut c_void;
433    /// Returns the allocated byte length of a Win32 global memory object.
434    ///
435    /// # Arguments
436    ///
437    /// - `*mut c_void` - Global memory handle.
438    ///
439    /// # Returns
440    ///
441    /// - `usize` - Allocated byte length.
442    fn GlobalSize(h_mem: *mut c_void) -> usize;
443}
444
445#[cfg(target_os = "windows")]
446#[link(name = "advapi32")]
447unsafe extern "system" {
448    /// Reads a typed registry value (`RRF_RT_REG_DWORD`) directly from a Windows registry key.
449    ///
450    /// # Arguments
451    ///
452    /// - `isize` - Root `HKEY` handle (`HKEY_CURRENT_USER`).
453    /// - `*const u16` - Null-terminated UTF-16 subkey path.
454    /// - `*const u16` - Null-terminated UTF-16 value name.
455    /// - `u32` - Type filter flags (`RRF_RT_REG_DWORD`).
456    /// - `*mut u32` - Optional output type pointer.
457    /// - `*mut c_void` - Output value buffer pointer.
458    /// - `*mut u32` - In-out buffer byte length pointer.
459    ///
460    /// # Returns
461    ///
462    /// - `i32` - `ERROR_SUCCESS` (`0`) on success.
463    fn RegGetValueW(
464        hkey: isize,
465        sub_key: *const u16,
466        value: *const u16,
467        flags: u32,
468        pdw_type: *mut u32,
469        pv_data: *mut c_void,
470        pcb_data: *mut u32,
471    ) -> i32;
472}
473
474/// Writes `text` as UTF-16LE `CF_UNICODETEXT` to the Win32 system clipboard.
475///
476/// # Arguments
477///
478/// - `&str` - UTF-8 text to place on the Windows clipboard.
479///
480/// # Returns
481///
482/// - `bool` - `true` when Win32 `SetClipboardData` succeeded.
483#[cfg(target_os = "windows")]
484fn windows_write_clipboard(text: &str) -> bool {
485    let mut wide: Vec<u16> = text.encode_utf16().collect();
486    wide.push(0);
487    let byte_len: usize = wide.len().saturating_mul(size_of::<u16>());
488    // SAFETY: Standard Win32 `GlobalAlloc` for `CF_UNICODETEXT`.
489    let h_mem: *mut c_void = unsafe { GlobalAlloc(WIN32_GMEM_MOVEABLE, byte_len) };
490    if h_mem.is_null() {
491        return false;
492    }
493    // SAFETY: `h_mem` is a valid newly allocated movable block of `byte_len` bytes.
494    let dst_ptr: *mut c_void = unsafe { GlobalLock(h_mem) };
495    if dst_ptr.is_null() {
496        // SAFETY: Unlock not needed because lock failed; free unowned block.
497        let _: *mut c_void = unsafe { GlobalFree(h_mem) };
498        return false;
499    }
500    // SAFETY: `dst_ptr` has `wide.len()` writable `u16` elements.
501    let dst_slice: &mut [u16] = unsafe { from_raw_parts_mut(dst_ptr.cast::<u16>(), wide.len()) };
502    dst_slice.copy_from_slice(wide.as_slice());
503    // SAFETY: Balanced unlock matching `GlobalLock` above.
504    let _: i32 = unsafe { GlobalUnlock(h_mem) };
505    // SAFETY: Open Win32 clipboard for current task.
506    if unsafe { OpenClipboard(0) } == 0 {
507        // SAFETY: Clipboard was not opened so `h_mem` remains process-owned.
508        let _: *mut c_void = unsafe { GlobalFree(h_mem) };
509        return false;
510    }
511    // SAFETY: Clipboard is open and owned by this thread.
512    let _: i32 = unsafe { EmptyClipboard() };
513    // SAFETY: Transfers ownership of `h_mem` to Windows on non-null return.
514    let set_res: *mut c_void = unsafe { SetClipboardData(WIN32_CF_UNICODETEXT, h_mem) };
515    // SAFETY: Always close clipboard after `OpenClipboard` succeeded.
516    let _: i32 = unsafe { CloseClipboard() };
517    if set_res.is_null() {
518        // SAFETY: `SetClipboardData` failed, so we still own `h_mem` and must free it.
519        let _: *mut c_void = unsafe { GlobalFree(h_mem) };
520        false
521    } else {
522        true
523    }
524}
525
526/// Reads UTF-16LE `CF_UNICODETEXT` directly from the Win32 system clipboard.
527///
528/// # Returns
529///
530/// - `Option<String>` - Decoded UTF-8 clipboard text when present.
531#[cfg(target_os = "windows")]
532fn windows_read_clipboard() -> Option<String> {
533    // SAFETY: Queries whether `CF_UNICODETEXT` exists on the system clipboard.
534    if unsafe { IsClipboardFormatAvailable(WIN32_CF_UNICODETEXT) } == 0 {
535        return None;
536    }
537    // SAFETY: Opens Win32 clipboard for reading.
538    if unsafe { OpenClipboard(0) } == 0 {
539        return None;
540    }
541    let mut output: Option<String> = None;
542    // SAFETY: Clipboard is open; handle belongs to the clipboard and must not be freed.
543    let handle: *mut c_void = unsafe { GetClipboardData(WIN32_CF_UNICODETEXT) };
544    if !handle.is_null() {
545        // SAFETY: `handle` is a valid clipboard global memory handle.
546        let total_bytes: usize = unsafe { GlobalSize(handle) };
547        let max_units: usize = total_bytes / size_of::<u16>();
548        // SAFETY: Lock clipboard handle while copying UTF-16 units.
549        let src_ptr: *mut c_void = unsafe { GlobalLock(handle) };
550        if !src_ptr.is_null() && max_units > 0 {
551            // SAFETY: `src_ptr` points to `max_units` valid `u16` elements while locked.
552            let units: &[u16] = unsafe { from_raw_parts(src_ptr.cast::<u16>(), max_units) };
553            let nul_pos: usize = units
554                .iter()
555                .position(|unit: &u16| *unit == 0)
556                .unwrap_or(units.len());
557            output = Some(String::from_utf16_lossy(&units[..nul_pos]));
558            // SAFETY: Balanced unlock matching `GlobalLock`.
559            let _: i32 = unsafe { GlobalUnlock(handle) };
560        }
561    }
562    // SAFETY: Balanced close matching `OpenClipboard`.
563    let _: i32 = unsafe { CloseClipboard() };
564    output
565}
566
567/// Queries the Windows `AppsUseLightTheme` registry DWORD via `RegGetValueW`.
568///
569/// # Returns
570///
571/// - `ThemeMode` - Detected Windows light or dark app theme preference.
572#[cfg(target_os = "windows")]
573fn windows_query_system_theme() -> ThemeMode {
574    let mut subkey_wide: Vec<u16> = WIN32_REG_THEME_SUBKEY.encode_utf16().collect();
575    subkey_wide.push(0);
576    let mut value_wide: Vec<u16> = WIN32_REG_APPS_USE_LIGHT_THEME.encode_utf16().collect();
577    value_wide.push(0);
578    let mut dword_val: u32 = 1;
579    let mut byte_len: u32 = size_of::<u32>() as u32;
580    // SAFETY: Null-terminated UTF-16 strings and properly sized `u32` output buffer.
581    let status: i32 = unsafe {
582        RegGetValueW(
583            WIN32_HKEY_CURRENT_USER,
584            subkey_wide.as_ptr(),
585            value_wide.as_ptr(),
586            WIN32_RRF_RT_REG_DWORD,
587            null_mut(),
588            (&mut dword_val as *mut u32).cast::<c_void>(),
589            &mut byte_len,
590        )
591    };
592    if status == 0 {
593        parse_windows_apps_use_light_theme(dword_val)
594    } else {
595        ThemeMode::Light
596    }
597}
598
599/// Pipes `text` to a Linux clipboard helper command and reports whether it exited cleanly.
600///
601/// # Arguments
602///
603/// - `&str` - Executable name (`wl-copy`, `xclip`, or `xsel`).
604/// - `&[&str]` - Command-line arguments.
605/// - `&str` - UTF-8 payload written to standard input.
606///
607/// # Returns
608///
609/// - `bool` - `true` when the helper command exited with status 0.
610#[cfg(target_os = "linux")]
611fn linux_run_clipboard_writer(program: &str, args: &[&str], text: &str) -> bool {
612    let Ok(mut child) = Command::new(program)
613        .args(args)
614        .stdin(Stdio::piped())
615        .stdout(Stdio::null())
616        .stderr(Stdio::null())
617        .spawn()
618    else {
619        return false;
620    };
621    if let Some(mut stdin_pipe) = child.stdin.take()
622        && stdin_pipe.write_all(text.as_bytes()).is_err()
623    {
624        return false;
625    }
626    let Ok(exit_status) = child.wait() else {
627        return false;
628    };
629    exit_status.success()
630}
631
632/// Writes `text` to the active Linux Wayland (`wl-copy`) or X11 (`xclip` / `xsel`) clipboard.
633///
634/// # Arguments
635///
636/// - `&str` - UTF-8 text to place on the clipboard.
637///
638/// # Returns
639///
640/// - `bool` - `true` when a desktop clipboard utility accepted the payload.
641#[cfg(target_os = "linux")]
642fn linux_write_clipboard(text: &str) -> bool {
643    if cfg!(test) || env::var_os(ENV_EUV_HEADLESS).is_some() {
644        return false;
645    }
646    if env::var_os(ENV_WAYLAND_DISPLAY).is_some()
647        && linux_run_clipboard_writer(LINUX_CMD_WL_COPY, &[], text)
648    {
649        return true;
650    }
651    if env::var_os(ENV_X11_DISPLAY).is_some() {
652        if linux_run_clipboard_writer(
653            LINUX_CMD_XCLIP,
654            &[LINUX_ARG_SELECTION, LINUX_ARG_CLIPBOARD],
655            text,
656        ) {
657            return true;
658        }
659        return linux_run_clipboard_writer(
660            LINUX_CMD_XSEL,
661            &[LINUX_ARG_XSEL_CLIPBOARD, LINUX_ARG_XSEL_INPUT],
662            text,
663        );
664    }
665    false
666}
667
668/// Runs a Linux clipboard read helper and returns its UTF-8 stdout on zero exit status.
669///
670/// # Arguments
671///
672/// - `&str` - Executable name (`wl-paste`, `xclip`, or `xsel`).
673/// - `&[&str]` - Command-line arguments.
674///
675/// # Returns
676///
677/// - `Option<String>` - Read clipboard string on success.
678#[cfg(target_os = "linux")]
679fn linux_run_clipboard_reader(program: &str, args: &[&str]) -> Option<String> {
680    let Ok(output) = Command::new(program)
681        .args(args)
682        .stdin(Stdio::null())
683        .stderr(Stdio::null())
684        .output()
685    else {
686        return None;
687    };
688    if !output.status.success() {
689        return None;
690    }
691    String::from_utf8(output.stdout).ok()
692}
693
694/// Reads UTF-8 plain text from the Linux Wayland (`wl-paste`) or X11 (`xclip` / `xsel`) clipboard.
695///
696/// # Returns
697///
698/// - `Option<String>` - Current desktop clipboard text when available.
699#[cfg(target_os = "linux")]
700fn linux_read_clipboard() -> Option<String> {
701    if cfg!(test) || env::var_os(ENV_EUV_HEADLESS).is_some() {
702        return None;
703    }
704    if env::var_os(ENV_WAYLAND_DISPLAY).is_some()
705        && let Some(text) = linux_run_clipboard_reader(LINUX_CMD_WL_PASTE, &[LINUX_ARG_NO_NEWLINE])
706    {
707        return Some(text);
708    }
709    if env::var_os(ENV_X11_DISPLAY).is_some() {
710        if let Some(text) = linux_run_clipboard_reader(
711            LINUX_CMD_XCLIP,
712            &["-o", LINUX_ARG_SELECTION, LINUX_ARG_CLIPBOARD],
713        ) {
714            return Some(text);
715        }
716        return linux_run_clipboard_reader(
717            LINUX_CMD_XSEL,
718            &[LINUX_ARG_XSEL_CLIPBOARD, LINUX_ARG_XSEL_OUTPUT],
719        );
720    }
721    None
722}
723
724/// Queries the Linux desktop appearance mode via `GTK_THEME`, `COLORFGBG`, and GNOME `gsettings`.
725///
726/// # Returns
727///
728/// - `ThemeMode` - Detected Linux light or dark theme preference.
729#[cfg(target_os = "linux")]
730fn linux_query_system_theme() -> ThemeMode {
731    if let Ok(gtk_theme) = env::var(ENV_GTK_THEME)
732        && let Some(mode) = parse_linux_theme_hint(&gtk_theme)
733    {
734        return mode;
735    }
736    if !cfg!(test) && env::var_os(ENV_EUV_HEADLESS).is_none() {
737        if let Some(scheme) = linux_run_clipboard_reader(
738            LINUX_CMD_GSETTINGS,
739            &["get", LINUX_GSETTINGS_SCHEMA, LINUX_GSETTINGS_COLOR_SCHEME],
740        ) && let Some(mode) = parse_linux_theme_hint(&scheme)
741        {
742            return mode;
743        }
744        if let Some(theme_name) = linux_run_clipboard_reader(
745            LINUX_CMD_GSETTINGS,
746            &["get", LINUX_GSETTINGS_SCHEMA, LINUX_GSETTINGS_GTK_THEME],
747        ) && let Some(mode) = parse_linux_theme_hint(&theme_name)
748        {
749            return mode;
750        }
751    }
752    if let Ok(colorfgbg) = env::var(ENV_COLORFGBG)
753        && let Some(mode) = parse_colorfgbg_theme_hint(&colorfgbg)
754    {
755        return mode;
756    }
757    ThemeMode::Light
758}
759
760/// Validates that `url` is a safe external `http://` or `https://` URL without whitespace or control characters.
761///
762/// # Arguments
763///
764/// - `&str` - Candidate external URL string.
765///
766/// # Returns
767///
768/// - `bool` - `true` when `url` has a valid `http://` or `https://` prefix, a non-empty host authority, and no control or whitespace characters.
769#[must_use]
770pub fn is_valid_external_url(url: &str) -> bool {
771    let trimmed: &str = url.trim();
772    if trimmed.is_empty() {
773        return false;
774    }
775    let rest: &str = if let Some(after_https) = trimmed.strip_prefix(URL_SCHEME_HTTPS) {
776        after_https
777    } else if let Some(after_http) = trimmed.strip_prefix(URL_SCHEME_HTTP) {
778        after_http
779    } else {
780        return false;
781    };
782    if rest.is_empty() || rest.starts_with('/') {
783        return false;
784    }
785    !trimmed
786        .chars()
787        .any(|ch: char| ch.is_control() || ch.is_whitespace())
788}
789
790/// Spawns the host desktop OS browser launcher for a validated URL outside test and headless runs.
791///
792/// # Arguments
793///
794/// - `&str` - Validated external URL string.
795///
796/// # Returns
797///
798/// - `bool` - `true` when the desktop launcher process spawned successfully.
799#[cfg(not(target_arch = "wasm32"))]
800fn open_external_url_desktop(target: &str) -> bool {
801    if cfg!(test) || env::var_os(ENV_EUV_HEADLESS).is_some() {
802        return false;
803    }
804    #[cfg(target_os = "macos")]
805    {
806        Command::new(OS_CMD_OPEN)
807            .arg(target)
808            .stdin(Stdio::null())
809            .stdout(Stdio::null())
810            .stderr(Stdio::null())
811            .spawn()
812            .is_ok()
813    }
814    #[cfg(target_os = "linux")]
815    {
816        Command::new(OS_CMD_XDG_OPEN)
817            .arg(target)
818            .stdin(Stdio::null())
819            .stdout(Stdio::null())
820            .stderr(Stdio::null())
821            .spawn()
822            .is_ok()
823    }
824    #[cfg(target_os = "windows")]
825    {
826        Command::new(OS_CMD_WIN_SHELL)
827            .args([OS_CMD_WIN_EXEC, OS_CMD_WIN_START, "", target])
828            .stdin(Stdio::null())
829            .stdout(Stdio::null())
830            .stderr(Stdio::null())
831            .spawn()
832            .is_ok()
833    }
834    #[cfg(not(any(target_os = "macos", target_os = "linux", target_os = "windows")))]
835    {
836        let _: &str = target;
837        false
838    }
839}
840
841/// Opens a validated `http://` or `https://` URL externally via the registered host bridge, browser `window.open`, or native desktop launcher.
842///
843/// # Arguments
844///
845/// - `&str` - External URL to open (`https://...` or `http://...`).
846///
847/// # Returns
848///
849/// - `bool` - `true` when the URL passed validation and was accepted by a host bridge or OS/browser launcher.
850pub fn open_external_url(url: &str) -> bool {
851    if !is_valid_external_url(url) {
852        return false;
853    }
854    let target: &str = url.trim();
855    if let Ok(mut guard) = LAST_EXTERNAL_URL.lock() {
856        *guard = Some(target.to_string());
857    }
858    let bridge_ok: bool = dispatch_native_action(NATIVE_ACTION_OPEN_URL, target, "");
859    #[cfg(target_arch = "wasm32")]
860    {
861        bridge_ok || web_open_external_url(target)
862    }
863    #[cfg(not(target_arch = "wasm32"))]
864    {
865        let desktop_ok: bool = open_external_url_desktop(target);
866        let headless_recorded: bool = cfg!(test) || env::var_os(ENV_EUV_HEADLESS).is_some();
867        let host_ok: bool = bridge_ok || desktop_ok;
868        host_ok || headless_recorded
869    }
870}
871
872/// Returns whether two embedded WebView `(rect, alpha)` snapshots are equivalent within deduplication tolerances.
873///
874/// # Arguments
875///
876/// - `Rect` - Previously dispatched viewport rectangle.
877/// - `f32` - Previously dispatched opacity.
878/// - `f32` - Candidate left coordinate in logical pixels.
879/// - `f32` - Candidate top coordinate in logical pixels.
880/// - `f32` - Candidate width in logical pixels.
881/// - `f32` - Candidate height in logical pixels.
882/// - `f32` - Candidate opacity in `0.0..=1.0`.
883///
884/// # Returns
885///
886/// - `bool` - `true` when position, size, and opacity all fall within deduplication thresholds.
887fn webview_frames_nearly_equal(
888    prev_rect: Rect,
889    prev_alpha: f32,
890    left_px: f32,
891    top_px: f32,
892    width_px: f32,
893    height_px: f32,
894    alpha_val: f32,
895) -> bool {
896    let same_pos: bool = (prev_rect.get_x() - left_px).abs() <= WEBVIEW_FRAME_POS_EPSILON
897        && (prev_rect.get_y() - top_px).abs() <= WEBVIEW_FRAME_POS_EPSILON;
898    let same_size: bool = (prev_rect.get_width() - width_px).abs() <= WEBVIEW_FRAME_POS_EPSILON
899        && (prev_rect.get_height() - height_px).abs() <= WEBVIEW_FRAME_POS_EPSILON;
900    let same_alpha: bool = (prev_alpha - alpha_val).abs() <= WEBVIEW_FRAME_ALPHA_EPSILON;
901    same_pos && same_size && same_alpha
902}
903
904/// Dispatches an immediate native host WebView open/navigate command across registered bridges and platform backends.
905///
906/// # Arguments
907///
908/// - `&str` - Trimmed, validated `http://` or `https://` target URL.
909/// - `&str` - Sheet header title.
910///
911/// # Returns
912///
913/// - `bool` - `true` when any host bridge or platform backend accepted the open command.
914fn dispatch_webview_native_open(target: &str, title: &str) -> bool {
915    let bridge_ok: bool = dispatch_native_action(NATIVE_ACTION_WEBVIEW, target, title);
916    #[cfg(target_arch = "wasm32")]
917    {
918        web_webview_open(target, title) || bridge_ok
919    }
920    #[cfg(target_os = "macos")]
921    {
922        if !bridge_ok && !cfg!(test) && env::var_os(ENV_EUV_HEADLESS).is_none() {
923            macos_webview_open(target, title) || bridge_ok
924        } else {
925            bridge_ok
926        }
927    }
928    #[cfg(not(any(target_arch = "wasm32", target_os = "macos")))]
929    {
930        bridge_ok
931    }
932}
933
934/// Dispatches an immediate native host WebView viewport frame update across registered bridges and platform backends.
935///
936/// # Arguments
937///
938/// - `f32` - Left coordinate in logical pixels.
939/// - `f32` - Top coordinate in logical pixels.
940/// - `f32` - Width in logical pixels.
941/// - `f32` - Height in logical pixels.
942/// - `f32` - Opacity in `0.0..=1.0`.
943///
944/// # Returns
945///
946/// - `bool` - `true` when any host bridge or platform backend accepted the frame update.
947fn dispatch_webview_native_frame(
948    left_px: f32,
949    top_px: f32,
950    width_px: f32,
951    height_px: f32,
952    alpha_val: f32,
953) -> bool {
954    let payload_csv: String =
955        format!("{left_px:.2},{top_px:.2},{width_px:.2},{height_px:.2},{alpha_val:.3}");
956    let bridge_ok: bool =
957        dispatch_native_action(NATIVE_ACTION_WEBVIEW, WEBVIEW_ACTION_FRAME, &payload_csv);
958    #[cfg(target_arch = "wasm32")]
959    {
960        web_webview_frame(left_px, top_px, width_px, height_px, alpha_val) || bridge_ok
961    }
962    #[cfg(target_os = "macos")]
963    {
964        if !bridge_ok && !cfg!(test) && env::var_os(ENV_EUV_HEADLESS).is_none() {
965            macos_webview_frame(left_px, top_px, width_px, height_px, alpha_val) || bridge_ok
966        } else {
967            bridge_ok
968        }
969    }
970    #[cfg(not(any(target_arch = "wasm32", target_os = "macos")))]
971    {
972        bridge_ok
973    }
974}
975
976/// Dispatches an immediate native host WebView reload command across registered bridges and platform backends.
977///
978/// # Arguments
979///
980/// - `&str` - Active URL fallback passed to host reload handlers.
981///
982/// # Returns
983///
984/// - `bool` - `true` when any host bridge or platform backend accepted the reload command.
985fn dispatch_webview_native_reload(target_url: &str) -> bool {
986    let bridge_ok: bool =
987        dispatch_native_action(NATIVE_ACTION_WEBVIEW, WEBVIEW_ACTION_RELOAD, target_url);
988    #[cfg(target_arch = "wasm32")]
989    {
990        web_webview_reload(target_url) || bridge_ok
991    }
992    #[cfg(target_os = "macos")]
993    {
994        if !bridge_ok && !cfg!(test) && env::var_os(ENV_EUV_HEADLESS).is_none() {
995            macos_webview_reload(target_url) || bridge_ok
996        } else {
997            bridge_ok
998        }
999    }
1000    #[cfg(not(any(target_arch = "wasm32", target_os = "macos")))]
1001    {
1002        bridge_ok
1003    }
1004}
1005
1006/// Dispatches an immediate native host WebView close/hide command across registered bridges and platform backends.
1007///
1008/// # Returns
1009///
1010/// - `bool` - `true` when any host bridge or platform backend accepted the close command.
1011fn dispatch_webview_native_close() -> bool {
1012    let bridge_ok: bool = dispatch_native_action(NATIVE_ACTION_WEBVIEW, WEBVIEW_ACTION_CLOSE, "");
1013    #[cfg(target_arch = "wasm32")]
1014    {
1015        web_webview_close() || bridge_ok
1016    }
1017    #[cfg(target_os = "macos")]
1018    {
1019        if !bridge_ok && !cfg!(test) && env::var_os(ENV_EUV_HEADLESS).is_none() {
1020            macos_webview_close() || bridge_ok
1021        } else {
1022            bridge_ok
1023        }
1024    }
1025    #[cfg(not(any(target_arch = "wasm32", target_os = "macos")))]
1026    {
1027        bridge_ok
1028    }
1029}
1030
1031/// Dispatches an immediate embedded bottom-sheet WebView open/navigate request to any active native host bridge and records telemetry for simulator verification.
1032///
1033/// # Arguments
1034///
1035/// - `&str` - Validated `http://` or `https://` target URL.
1036/// - `&str` - Sheet header title.
1037///
1038/// # Returns
1039///
1040/// - `bool` - `true` when `url` passed validation and the WebView sheet state updated.
1041pub fn open_webview_sheet_bridge(url: &str, title: &str) -> bool {
1042    if !is_valid_external_url(url) {
1043        return false;
1044    }
1045    let target: &str = url.trim();
1046    LAST_WEBVIEW_SHEET.with(|cell: &RefCell<Option<(String, String)>>| {
1047        if let Ok(mut guard) = cell.try_borrow_mut() {
1048            *guard = Some((target.to_string(), title.to_string()));
1049        }
1050    });
1051    LAST_WEBVIEW_FRAME.with(|cell: &RefCell<Option<(Rect, f32)>>| {
1052        if let Ok(mut frame_guard) = cell.try_borrow_mut() {
1053            *frame_guard = None;
1054        }
1055    });
1056    WEBVIEW_NATIVE_STATE.with(|cell: &RefCell<WebViewNativeLifecycle>| {
1057        if let Ok(mut state_guard) = cell.try_borrow_mut() {
1058            let was_attached: bool = state_guard.get_native_attached();
1059            let _: &mut WebViewNativeLifecycle = state_guard
1060                .set_pending_open(None)
1061                .set_native_attached(true)
1062                .set_attached_target(Some((target.to_string(), title.to_string())));
1063            if !was_attached {
1064                let _: &mut WebViewNativeLifecycle = state_guard.set_last_native_frame(None);
1065            }
1066            let next_opens: u64 = state_guard.get_native_open_count().saturating_add(1);
1067            let _: &mut WebViewNativeLifecycle = state_guard.set_native_open_count(next_opens);
1068        }
1069    });
1070    let _: bool = dispatch_webview_native_open(target, title);
1071    true
1072}
1073
1074/// Stages an embedded bottom-sheet WebView open request without blocking Frame 0, attaching the native host WebView once the half-sheet slide-up settles.
1075///
1076/// # Arguments
1077///
1078/// - `&str` - Validated `http://` or `https://` target URL.
1079/// - `&str` - Sheet header title.
1080///
1081/// # Returns
1082///
1083/// - `bool` - `true` when `url` passed validation and the deferred WebView open was staged.
1084pub fn open_webview_sheet_bridge_deferred(url: &str, title: &str) -> bool {
1085    if !is_valid_external_url(url) {
1086        return false;
1087    }
1088    let target: &str = url.trim();
1089    LAST_WEBVIEW_SHEET.with(|cell: &RefCell<Option<(String, String)>>| {
1090        if let Ok(mut guard) = cell.try_borrow_mut() {
1091            *guard = Some((target.to_string(), title.to_string()));
1092        }
1093    });
1094    LAST_WEBVIEW_FRAME.with(|cell: &RefCell<Option<(Rect, f32)>>| {
1095        if let Ok(mut frame_guard) = cell.try_borrow_mut() {
1096            *frame_guard = None;
1097        }
1098    });
1099    WEBVIEW_NATIVE_STATE.with(|cell: &RefCell<WebViewNativeLifecycle>| {
1100        if let Ok(mut state_guard) = cell.try_borrow_mut() {
1101            let already_matches: bool = state_guard.get_native_attached()
1102                && state_guard.try_get_attached_target().is_some_and(
1103                    |(cur_url, cur_title): &(String, String)| {
1104                        cur_url == target && cur_title == title
1105                    },
1106                );
1107            if already_matches {
1108                let _: &mut WebViewNativeLifecycle = state_guard.set_pending_open(None);
1109            } else {
1110                let _: &mut WebViewNativeLifecycle =
1111                    state_guard.set_pending_open(Some((target.to_string(), title.to_string())));
1112                if !state_guard.get_native_attached() {
1113                    let _: &mut WebViewNativeLifecycle = state_guard.set_last_native_frame(None);
1114                }
1115            }
1116        }
1117    });
1118    true
1119}
1120
1121/// Cancels any pending deferred native WebView open when the half-sheet closes before settling.
1122pub fn cancel_pending_webview_sheet_open() {
1123    WEBVIEW_NATIVE_STATE.with(|cell: &RefCell<WebViewNativeLifecycle>| {
1124        if let Ok(mut state_guard) = cell.try_borrow_mut() {
1125            let _: &mut WebViewNativeLifecycle = state_guard.set_pending_open(None);
1126        }
1127    });
1128}
1129
1130/// Synchronizes the screen-space logical viewport rectangle and opacity of the active embedded WebView sheet with the host overlay.
1131///
1132/// # Arguments
1133///
1134/// - `Rect` - Screen-space logical viewport rectangle covering the embedded WebView content container.
1135/// - `f32` - Effective composed opacity in `0.0..=1.0`.
1136///
1137/// # Returns
1138///
1139/// - `bool` - `true` when the geometry or opacity changed and was dispatched to the host overlay.
1140pub fn sync_webview_sheet_frame(bounds: Rect, opacity: f32) -> bool {
1141    let left_px: f32 = if bounds.get_x().is_finite() {
1142        bounds.get_x()
1143    } else {
1144        0.0
1145    };
1146    let top_px: f32 = if bounds.get_y().is_finite() {
1147        bounds.get_y()
1148    } else {
1149        0.0
1150    };
1151    let width_px: f32 = if bounds.get_width().is_finite() {
1152        bounds.get_width().max(0.0)
1153    } else {
1154        0.0
1155    };
1156    let height_px: f32 = if bounds.get_height().is_finite() {
1157        bounds.get_height().max(0.0)
1158    } else {
1159        0.0
1160    };
1161    let alpha_val: f32 = if opacity.is_finite() {
1162        opacity.clamp(0.0, 1.0)
1163    } else {
1164        0.0
1165    };
1166    let next_rect: Rect = Rect::new(left_px, top_px, width_px, height_px);
1167    let next_frame: (Rect, f32) = (next_rect, alpha_val);
1168    let logical_changed: bool = LAST_WEBVIEW_FRAME.with(|cell: &RefCell<Option<(Rect, f32)>>| {
1169        if let Ok(mut frame_guard) = cell.try_borrow_mut() {
1170            if let Some((prev_rect, prev_alpha)) = *frame_guard
1171                && webview_frames_nearly_equal(
1172                    prev_rect, prev_alpha, left_px, top_px, width_px, height_px, alpha_val,
1173                )
1174            {
1175                return false;
1176            }
1177            *frame_guard = Some(next_frame);
1178        }
1179        true
1180    });
1181    let is_settled_visible: bool =
1182        width_px >= 1.0 && height_px >= 1.0 && alpha_val >= WEBVIEW_ATTACH_ALPHA_THRESHOLD;
1183    let (promoted_open, should_dispatch_frame): (Option<(String, String)>, bool) =
1184        WEBVIEW_NATIVE_STATE.with(|cell: &RefCell<WebViewNativeLifecycle>| {
1185            if let Ok(mut state_guard) = cell.try_borrow_mut() {
1186                let staged: Option<(String, String)> = if is_settled_visible {
1187                    if let Some((pending_url, pending_title)) =
1188                        state_guard.get_mut_pending_open().take()
1189                    {
1190                        let _: &mut WebViewNativeLifecycle = state_guard
1191                            .set_native_attached(true)
1192                            .set_attached_target(Some((pending_url.clone(), pending_title.clone())))
1193                            .set_last_native_frame(None);
1194                        let next_opens: u64 = state_guard.get_native_open_count().saturating_add(1);
1195                        let _: &mut WebViewNativeLifecycle =
1196                            state_guard.set_native_open_count(next_opens);
1197                        Some((pending_url, pending_title))
1198                    } else {
1199                        None
1200                    }
1201                } else {
1202                    None
1203                };
1204                let dispatch_frame: bool = if state_guard.get_native_attached() {
1205                    let same_native: bool = state_guard.try_get_last_native_frame().is_some_and(
1206                        |(prev_rect, prev_alpha): (Rect, f32)| {
1207                            webview_frames_nearly_equal(
1208                                prev_rect, prev_alpha, left_px, top_px, width_px, height_px,
1209                                alpha_val,
1210                            )
1211                        },
1212                    );
1213                    if same_native {
1214                        false
1215                    } else {
1216                        let _: &mut WebViewNativeLifecycle =
1217                            state_guard.set_last_native_frame(Some(next_frame));
1218                        let next_frames: u64 =
1219                            state_guard.get_native_frame_count().saturating_add(1);
1220                        let _: &mut WebViewNativeLifecycle =
1221                            state_guard.set_native_frame_count(next_frames);
1222                        true
1223                    }
1224                } else {
1225                    false
1226                };
1227                (staged, dispatch_frame)
1228            } else {
1229                (None, false)
1230            }
1231        });
1232    if let Some((pending_url, pending_title)) = promoted_open.as_ref() {
1233        let _: bool = dispatch_webview_native_open(pending_url, pending_title);
1234    }
1235    if should_dispatch_frame {
1236        let _: bool =
1237            dispatch_webview_native_frame(left_px, top_px, width_px, height_px, alpha_val);
1238    }
1239    logical_changed || promoted_open.is_some() || should_dispatch_frame
1240}
1241
1242/// Reloads the active webpage inside any hosted native embedded bottom-sheet WebView.
1243///
1244/// # Returns
1245///
1246/// - `bool` - `true` when an active WebView target existed and a reload command was dispatched.
1247pub fn reload_webview_sheet_bridge() -> bool {
1248    let active_target: Option<(String, String)> =
1249        LAST_WEBVIEW_SHEET.with(|cell: &RefCell<Option<(String, String)>>| {
1250            cell.try_borrow()
1251                .ok()
1252                .and_then(|guard: Ref<'_, Option<(String, String)>>| guard.clone())
1253        });
1254    let Some((active_url, active_title)) = active_target else {
1255        return false;
1256    };
1257    let cached_frame: Option<(Rect, f32)> =
1258        LAST_WEBVIEW_FRAME.with(|cell: &RefCell<Option<(Rect, f32)>>| {
1259            cell.try_borrow()
1260                .ok()
1261                .and_then(|guard: Ref<'_, Option<(Rect, f32)>>| *guard)
1262        });
1263    let mut promote_open: Option<(String, String)> = None;
1264    let mut sync_frame: Option<(Rect, f32)> = None;
1265    WEBVIEW_NATIVE_STATE.with(|cell: &RefCell<WebViewNativeLifecycle>| {
1266        if let Ok(mut state_guard) = cell.try_borrow_mut() {
1267            let pending_opt: Option<(String, String)> = state_guard.get_mut_pending_open().take();
1268            if !state_guard.get_native_attached() || pending_opt.is_some() {
1269                let (target_url, target_title): (String, String) =
1270                    pending_opt.unwrap_or_else(|| (active_url.clone(), active_title.clone()));
1271                let _: &mut WebViewNativeLifecycle = state_guard
1272                    .set_native_attached(true)
1273                    .set_attached_target(Some((target_url.clone(), target_title.clone())))
1274                    .set_last_native_frame(None);
1275                let next_opens: u64 = state_guard.get_native_open_count().saturating_add(1);
1276                let _: &mut WebViewNativeLifecycle = state_guard.set_native_open_count(next_opens);
1277                let frame_to_sync: Option<(Rect, f32)> =
1278                    cached_frame.filter(|(rect, _): &(Rect, f32)| {
1279                        rect.get_width() >= 1.0 && rect.get_height() >= 1.0
1280                    });
1281                if let Some(frame_pair) = frame_to_sync {
1282                    let _: &mut WebViewNativeLifecycle =
1283                        state_guard.set_last_native_frame(Some(frame_pair));
1284                    let next_frames: u64 = state_guard.get_native_frame_count().saturating_add(1);
1285                    let _: &mut WebViewNativeLifecycle =
1286                        state_guard.set_native_frame_count(next_frames);
1287                }
1288                promote_open = Some((target_url, target_title));
1289                sync_frame = frame_to_sync;
1290            }
1291        }
1292    });
1293    if let Some((target_url, target_title)) = promote_open {
1294        let _: bool = dispatch_webview_native_open(&target_url, &target_title);
1295        if let Some((rect, alpha)) = sync_frame {
1296            let _: bool = dispatch_webview_native_frame(
1297                rect.get_x(),
1298                rect.get_y(),
1299                rect.get_width(),
1300                rect.get_height(),
1301                alpha,
1302            );
1303        }
1304        return true;
1305    }
1306    let _: bool = dispatch_webview_native_reload(&active_url);
1307    true
1308}
1309
1310/// Notifies any active native host bridge that the embedded bottom-sheet WebView was dismissed.
1311///
1312/// # Returns
1313///
1314/// - `bool` - `true` when handled by an active native host bridge.
1315pub fn close_webview_sheet_bridge() -> bool {
1316    LAST_WEBVIEW_SHEET.with(|cell: &RefCell<Option<(String, String)>>| {
1317        if let Ok(mut guard) = cell.try_borrow_mut() {
1318            *guard = None;
1319        }
1320    });
1321    LAST_WEBVIEW_FRAME.with(|cell: &RefCell<Option<(Rect, f32)>>| {
1322        if let Ok(mut frame_guard) = cell.try_borrow_mut() {
1323            *frame_guard = None;
1324        }
1325    });
1326    let was_attached: bool = WEBVIEW_NATIVE_STATE.with(|cell: &RefCell<WebViewNativeLifecycle>| {
1327        if let Ok(mut state_guard) = cell.try_borrow_mut() {
1328            let prev_attached: bool = state_guard.get_native_attached();
1329            let _: &mut WebViewNativeLifecycle = state_guard
1330                .set_pending_open(None)
1331                .set_attached_target(None)
1332                .set_last_native_frame(None)
1333                .set_native_attached(false);
1334            if prev_attached {
1335                let next_closes: u64 = state_guard.get_native_close_count().saturating_add(1);
1336                let _: &mut WebViewNativeLifecycle =
1337                    state_guard.set_native_close_count(next_closes);
1338            }
1339            prev_attached
1340        } else {
1341            false
1342        }
1343    });
1344    if was_attached {
1345        dispatch_webview_native_close()
1346    } else {
1347        false
1348    }
1349}
1350
1351/// Returns whether the native OS WebView has been attached for the active sheet session.
1352///
1353/// # Returns
1354///
1355/// - `bool` - `true` once the native WebView has been opened/attached and not yet closed.
1356#[must_use]
1357pub fn is_webview_sheet_native_attached() -> bool {
1358    WEBVIEW_NATIVE_STATE.with(|cell: &RefCell<WebViewNativeLifecycle>| {
1359        cell.try_borrow()
1360            .map(|guard: Ref<'_, WebViewNativeLifecycle>| guard.get_native_attached())
1361            .unwrap_or(false)
1362    })
1363}
1364
1365/// Returns whether a deferred native WebView open is currently staged awaiting slide-up settle.
1366///
1367/// # Returns
1368///
1369/// - `bool` - `true` while a deferred open is pending attachment.
1370#[must_use]
1371pub fn has_pending_webview_sheet_open() -> bool {
1372    WEBVIEW_NATIVE_STATE.with(|cell: &RefCell<WebViewNativeLifecycle>| {
1373        cell.try_borrow()
1374            .map(|guard: Ref<'_, WebViewNativeLifecycle>| guard.has_pending_open())
1375            .unwrap_or(false)
1376    })
1377}
1378
1379/// Returns cumulative `(native_open_count, native_frame_count, native_close_count)` dispatches emitted on this UI thread since the last history reset.
1380///
1381/// # Returns
1382///
1383/// - `(u64, u64, u64)` - Tuple of `(open_dispatches, frame_dispatches, close_dispatches)`.
1384#[must_use]
1385pub fn webview_sheet_native_dispatch_counts() -> (u64, u64, u64) {
1386    WEBVIEW_NATIVE_STATE.with(|cell: &RefCell<WebViewNativeLifecycle>| {
1387        cell.try_borrow()
1388            .map(|guard: Ref<'_, WebViewNativeLifecycle>| {
1389                (
1390                    guard.get_native_open_count(),
1391                    guard.get_native_frame_count(),
1392                    guard.get_native_close_count(),
1393                )
1394            })
1395            .unwrap_or((0, 0, 0))
1396    })
1397}
1398
1399/// Returns the most recently synchronized embedded WebView `(bounds, opacity)` frame, or `None` after close.
1400///
1401/// # Returns
1402///
1403/// - `Option<(Rect, f32)>` - Last dispatched embedded WebView viewport rectangle and opacity.
1404#[must_use]
1405pub fn last_webview_sheet_frame() -> Option<(Rect, f32)> {
1406    LAST_WEBVIEW_FRAME.with(|cell: &RefCell<Option<(Rect, f32)>>| {
1407        cell.try_borrow()
1408            .ok()
1409            .and_then(|guard: Ref<'_, Option<(Rect, f32)>>| *guard)
1410    })
1411}
1412
1413/// Returns the most recently validated URL passed to `open_external_url` in this process.
1414///
1415/// # Returns
1416///
1417/// - `Option<String>` - Last external browser URL, if any.
1418#[must_use]
1419pub fn last_opened_external_url() -> Option<String> {
1420    LAST_EXTERNAL_URL
1421        .lock()
1422        .ok()
1423        .and_then(|guard: MutexGuard<'_, Option<String>>| guard.clone())
1424}
1425
1426/// Returns the currently active `(url, title)` pair opened via `open_webview_sheet_bridge`, or `None` after close.
1427///
1428/// # Returns
1429///
1430/// - `Option<(String, String)>` - Active WebView sheet URL and title, if open.
1431#[must_use]
1432pub fn active_webview_sheet_target() -> Option<(String, String)> {
1433    LAST_WEBVIEW_SHEET.with(|cell: &RefCell<Option<(String, String)>>| {
1434        cell.try_borrow()
1435            .ok()
1436            .and_then(|guard: Ref<'_, Option<(String, String)>>| guard.clone())
1437    })
1438}
1439
1440/// Clears recorded `open_external_url` and `open_webview_sheet_bridge` telemetry for isolated test runs.
1441pub fn clear_link_action_history() {
1442    if let Ok(mut ext_guard) = LAST_EXTERNAL_URL.lock() {
1443        *ext_guard = None;
1444    }
1445    LAST_WEBVIEW_SHEET.with(|cell: &RefCell<Option<(String, String)>>| {
1446        if let Ok(mut wv_guard) = cell.try_borrow_mut() {
1447            *wv_guard = None;
1448        }
1449    });
1450    LAST_WEBVIEW_FRAME.with(|cell: &RefCell<Option<(Rect, f32)>>| {
1451        if let Ok(mut frame_guard) = cell.try_borrow_mut() {
1452            *frame_guard = None;
1453        }
1454    });
1455    WEBVIEW_NATIVE_STATE.with(|cell: &RefCell<WebViewNativeLifecycle>| {
1456        if let Ok(mut state_guard) = cell.try_borrow_mut() {
1457            *state_guard = WebViewNativeLifecycle::default();
1458        }
1459    });
1460}