euv-core 0.52.0

Core cross-platform runtime for euv featuring arena-based fine-grained reactivity, deterministic layout, flat scene graph, multi-mode rendering, and direct OS platform adapters.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
use super::*;

/// Registers a platform-host native OS capability bridge (haptics, notifications, permissions, fullscreen, Dynamic Island).
///
/// # Arguments
///
/// - `fn(&str, &str, &str) -> bool` - Host callback handling `(kind, arg1, arg2)` and returning whether native OS execution succeeded.
pub fn register_native_action_bridge(bridge: fn(&str, &str, &str) -> bool) {
    EXTERNAL_NATIVE_ACTION_BRIDGE.store(bridge as *mut (), Ordering::Release);
}

/// Dispatches a native OS capability action `(kind, arg1, arg2)` to the registered host bridge, if any.
///
/// # Arguments
///
/// - `&str` - Action category (`"haptic"`, `"notify"`, `"island"`, `"permission"`, `"fullscreen"`, `"protocol"`).
/// - `&str` - Primary payload argument (e.g. title or permission key).
/// - `&str` - Secondary payload argument (e.g. body or rationale).
///
/// # Returns
///
/// - `bool` - `true` when handled by an active native OS host bridge.
pub fn dispatch_native_action(kind: &str, arg1: &str, arg2: &str) -> bool {
    let raw: *mut () = EXTERNAL_NATIVE_ACTION_BRIDGE.load(Ordering::Acquire);
    if raw.is_null() {
        return false;
    }
    // SAFETY: `raw` is stored exclusively via `register_native_action_bridge` from a `fn(&str, &str, &str) -> bool` pointer.
    let func: fn(&str, &str, &str) -> bool =
        unsafe { transmute::<*mut (), fn(&str, &str, &str) -> bool>(raw) };
    func(kind, arg1, arg2)
}

/// Copies `text` to the active OS or browser clipboard via direct platform hooks and any registered native action bridge.
///
/// # Arguments
///
/// - `&str` - UTF-8 text string to place on the system clipboard.
///
/// # Returns
///
/// - `bool` - `true` when at least one native or host clipboard sink accepted `text`.
pub fn write_system_clipboard(text: &str) -> bool {
    if let Ok(mut cache_guard) = NATIVE_CLIPBOARD_CACHE.lock() {
        *cache_guard = Some(text.to_string());
    }
    let bridge_ok: bool =
        dispatch_native_action(NATIVE_ACTION_CLIPBOARD, CLIPBOARD_ACTION_WRITE, text);
    let mut accepted: bool = false;
    #[cfg(target_os = "macos")]
    {
        accepted |= macos_write_pasteboard_pooled(text);
    }
    #[cfg(target_os = "windows")]
    {
        accepted |= windows_write_clipboard(text);
    }
    #[cfg(target_os = "linux")]
    {
        accepted |= linux_write_clipboard(text);
    }
    #[cfg(target_arch = "wasm32")]
    {
        accepted |= web_write_clipboard(text);
    }
    accepted |= bridge_ok;
    accepted
}

/// Registers an optional host callback providing live OS clipboard reads on embedded or mobile runtimes.
///
/// # Arguments
///
/// - `fn() -> Option<String>` - Host callback returning current UTF-8 clipboard text.
pub fn register_clipboard_read_bridge(bridge: fn() -> Option<String>) {
    EXTERNAL_CLIPBOARD_READ_BRIDGE.store(bridge as *mut (), Ordering::Release);
}

/// Clears any registered host clipboard read callback.
pub fn clear_clipboard_read_bridge() {
    EXTERNAL_CLIPBOARD_READ_BRIDGE.store(null_mut(), Ordering::Release);
}

/// Registers an optional host callback providing live OS light/dark theme detection.
///
/// # Arguments
///
/// - `fn() -> ThemeMode` - Host callback returning the current system appearance mode.
pub fn register_theme_query_bridge(bridge: fn() -> ThemeMode) {
    EXTERNAL_THEME_QUERY_BRIDGE.store(bridge as *mut (), Ordering::Release);
}

/// Clears any registered host theme query callback.
pub fn clear_theme_query_bridge() {
    EXTERNAL_THEME_QUERY_BRIDGE.store(null_mut(), Ordering::Release);
}

/// Clears the process-local clipboard fallback cache for isolated tests.
pub fn clear_clipboard_cache() {
    if let Ok(mut cache_guard) = NATIVE_CLIPBOARD_CACHE.lock() {
        *cache_guard = None;
    }
}

/// Reads UTF-8 plain text from the host OS system clipboard, preferring registered host bridges and native FFI with safe cache fallback.
///
/// # Returns
///
/// - `Option<String>` - Current clipboard UTF-8 string, if available.
#[must_use]
pub fn read_system_clipboard() -> Option<String> {
    let raw_bridge: *mut () = EXTERNAL_CLIPBOARD_READ_BRIDGE.load(Ordering::Acquire);
    if !raw_bridge.is_null() {
        // SAFETY: `raw_bridge` is stored exclusively via `register_clipboard_read_bridge` from a `fn() -> Option<String>` pointer.
        let bridge_fn: fn() -> Option<String> =
            unsafe { transmute::<*mut (), fn() -> Option<String>>(raw_bridge) };
        if let Some(bridged_text) = bridge_fn() {
            return Some(bridged_text);
        }
    }
    #[cfg(target_os = "macos")]
    {
        if let Some(native_text) = macos_read_pasteboard_pooled() {
            return Some(native_text);
        }
    }
    #[cfg(target_os = "windows")]
    {
        if let Some(native_text) = windows_read_clipboard() {
            return Some(native_text);
        }
    }
    #[cfg(target_os = "linux")]
    {
        if let Some(native_text) = linux_read_clipboard() {
            return Some(native_text);
        }
    }
    NATIVE_CLIPBOARD_CACHE
        .lock()
        .ok()
        .and_then(|guard: MutexGuard<'_, Option<String>>| guard.clone())
}

/// Maps the Windows registry `AppsUseLightTheme` DWORD value into `ThemeMode`.
///
/// # Arguments
///
/// - `u32` - Registry DWORD value (`0` denotes Dark mode, non-zero denotes Light mode).
///
/// # Returns
///
/// - `ThemeMode` - Resolved `ThemeMode::Dark` or `ThemeMode::Light`.
#[must_use]
pub const fn parse_windows_apps_use_light_theme(dword_value: u32) -> ThemeMode {
    if dword_value == 0 {
        ThemeMode::Dark
    } else {
        ThemeMode::Light
    }
}

/// Parses a Linux desktop theme string (such as `GTK_THEME`, `gsettings color-scheme`, or `gtk-theme`) into a `ThemeMode`.
///
/// # Arguments
///
/// - `&str` - Raw theme hint string.
///
/// # Returns
///
/// - `Option<ThemeMode>` - Detected `Dark` or `Light` preference when recognized.
#[must_use]
pub fn parse_linux_theme_hint(raw_hint: &str) -> Option<ThemeMode> {
    let normalized: String = raw_hint
        .trim()
        .trim_matches('\'')
        .trim_matches('"')
        .to_ascii_lowercase();
    if normalized.is_empty() {
        return None;
    }
    if normalized.contains(THEME_HINT_DARK_MARKER) {
        return Some(ThemeMode::Dark);
    }
    if normalized.contains(THEME_HINT_LIGHT_MARKER) {
        return Some(ThemeMode::Light);
    }
    None
}

/// Parses a `COLORFGBG` (`"fg;bg"`) hint string into `ThemeMode` (`bg < 7` indicates dark background).
///
/// # Arguments
///
/// - `&str` - Raw `COLORFGBG` environment string.
///
/// # Returns
///
/// - `Option<ThemeMode>` - Detected appearance mode when the background ANSI index parses cleanly.
#[must_use]
pub fn parse_colorfgbg_theme_hint(raw_value: &str) -> Option<ThemeMode> {
    let bg_segment: &str = raw_value.trim().rsplit(';').next()?;
    let bg_index: u32 = bg_segment.trim().parse::<u32>().ok()?;
    if bg_index < 7 || bg_index == 8 {
        Some(ThemeMode::Dark)
    } else {
        Some(ThemeMode::Light)
    }
}

/// Queries the active host OS light/dark appearance mode via registered bridge or native platform FFI.
///
/// # Returns
///
/// - `ThemeMode` - Live OS light or dark appearance preference.
#[must_use]
pub fn query_system_theme_mode() -> ThemeMode {
    let raw_bridge: *mut () = EXTERNAL_THEME_QUERY_BRIDGE.load(Ordering::Acquire);
    if !raw_bridge.is_null() {
        // SAFETY: `raw_bridge` is stored exclusively via `register_theme_query_bridge` from a `fn() -> ThemeMode` pointer.
        let bridge_fn: fn() -> ThemeMode =
            unsafe { transmute::<*mut (), fn() -> ThemeMode>(raw_bridge) };
        return bridge_fn();
    }
    let mut resolved: Option<ThemeMode> = None;
    #[cfg(target_os = "macos")]
    {
        if resolved.is_none() {
            resolved = Some(macos_system_theme());
        }
    }
    #[cfg(target_os = "windows")]
    {
        if resolved.is_none() {
            resolved = Some(windows_query_system_theme());
        }
    }
    #[cfg(target_os = "linux")]
    {
        if resolved.is_none() {
            resolved = Some(linux_query_system_theme());
        }
    }
    #[cfg(target_arch = "wasm32")]
    {
        if resolved.is_none() {
            resolved = Some(web_system_theme());
        }
    }
    *resolved.get_or_insert(ThemeMode::Light)
}

#[cfg(target_os = "macos")]
#[link(name = "objc")]
unsafe extern "C" {
    /// Pushes an Objective-C autorelease pool frame for temporary pasteboard strings.
    ///
    /// # Returns
    ///
    /// - `*mut c_void` - Autorelease pool token passed to `objc_autoreleasePoolPop`.
    fn objc_autoreleasePoolPush() -> *mut c_void;
    /// Pops and drains an Objective-C autorelease pool frame.
    ///
    /// # Arguments
    ///
    /// - `*mut c_void` - Pool token returned by `objc_autoreleasePoolPush`.
    fn objc_autoreleasePoolPop(pool: *mut c_void);
}

/// Writes `text` to macOS `NSPasteboard` inside a scoped Objective-C autorelease pool.
///
/// # Arguments
///
/// - `&str` - UTF-8 text to place on the general pasteboard.
///
/// # Returns
///
/// - `bool` - `true` when `NSPasteboard.setString:forType:` succeeded.
#[cfg(target_os = "macos")]
fn macos_write_pasteboard_pooled(text: &str) -> bool {
    // SAFETY: Balanced `objc_autoreleasePoolPush` / `objc_autoreleasePoolPop` pair on the calling thread.
    let pool: *mut c_void = unsafe { objc_autoreleasePoolPush() };
    let written: bool = macos_write_pasteboard(text);
    // SAFETY: `pool` was returned by `objc_autoreleasePoolPush` above.
    unsafe { objc_autoreleasePoolPop(pool) };
    written
}

/// Reads UTF-8 plain text directly from the macOS general `NSPasteboard` via `stringForType:`.
///
/// # Returns
///
/// - `Option<String>` - Current macOS pasteboard text when available.
#[cfg(target_os = "macos")]
fn macos_read_pasteboard_pooled() -> Option<String> {
    // SAFETY: Balanced `objc_autoreleasePoolPush` / `objc_autoreleasePoolPop` pair on the calling thread.
    let pool: *mut c_void = unsafe { objc_autoreleasePoolPush() };
    let mut result: Option<String> = None;
    let pb_cls: *mut c_void = objc_class(CAP_OBJC_CLS_NS_PASTEBOARD);
    let pb: *mut c_void = objc_send_ptr0(pb_cls, objc_sel(CAP_OBJC_SEL_GENERAL_PASTEBOARD));
    if !pb.is_null() {
        let str_for_type_sel: *mut c_void = objc_sel(CAP_OBJC_SEL_STRING_FOR_TYPE);
        let utf8_type_ns: *mut c_void = macos_ns_string(CAP_PASTEBOARD_TYPE_UTF8);
        let mut value_ns: *mut c_void = if utf8_type_ns.is_null() {
            null_mut()
        } else {
            objc_send_ptr1(pb, str_for_type_sel, utf8_type_ns)
        };
        if value_ns.is_null() {
            let legacy_type_ns: *mut c_void = macos_ns_string(CAP_PASTEBOARD_TYPE_LEGACY);
            if !legacy_type_ns.is_null() {
                value_ns = objc_send_ptr1(pb, str_for_type_sel, legacy_type_ns);
            }
        }
        if !value_ns.is_null() {
            let utf8_ptr: *const c_char =
                objc_send_ptr0(value_ns, objc_sel(CAP_OBJC_SEL_UTF8_STRING)).cast::<c_char>();
            if !utf8_ptr.is_null() {
                // SAFETY: `NSString.UTF8String` returns a valid null-terminated UTF-8 C string while `pool` is live.
                let extracted: String =
                    unsafe { CStr::from_ptr(utf8_ptr).to_string_lossy().into_owned() };
                result = Some(extracted);
            }
        }
    }
    // SAFETY: `pool` was returned by `objc_autoreleasePoolPush` above.
    unsafe { objc_autoreleasePoolPop(pool) };
    result
}

#[cfg(target_os = "windows")]
#[link(name = "user32")]
unsafe extern "system" {
    /// Opens the Win32 clipboard for the current process.
    ///
    /// # Arguments
    ///
    /// - `isize` - Optional owner window handle (`0` for current task).
    ///
    /// # Returns
    ///
    /// - `i32` - Non-zero on success.
    fn OpenClipboard(h_wnd_new_owner: isize) -> i32;
    /// Closes the Win32 clipboard previously opened by `OpenClipboard`.
    ///
    /// # Returns
    ///
    /// - `i32` - Non-zero on success.
    fn CloseClipboard() -> i32;
    /// Empties the Win32 clipboard and transfers ownership prior to `SetClipboardData`.
    ///
    /// # Returns
    ///
    /// - `i32` - Non-zero on success.
    fn EmptyClipboard() -> i32;
    /// Checks whether the specified clipboard format is currently available.
    ///
    /// # Arguments
    ///
    /// - `u32` - Win32 clipboard format identifier (`CF_UNICODETEXT`).
    ///
    /// # Returns
    ///
    /// - `i32` - Non-zero when format is available.
    fn IsClipboardFormatAvailable(format: u32) -> i32;
    /// Retrieves a handle to Win32 clipboard data in `format`.
    ///
    /// # Arguments
    ///
    /// - `u32` - Win32 clipboard format identifier.
    ///
    /// # Returns
    ///
    /// - `*mut c_void` - Global memory handle or null.
    fn GetClipboardData(format: u32) -> *mut c_void;
    /// Places a global memory handle onto the Win32 clipboard in `format`.
    ///
    /// # Arguments
    ///
    /// - `u32` - Win32 clipboard format identifier.
    /// - `*mut c_void` - Movable global memory handle allocated via `GlobalAlloc`.
    ///
    /// # Returns
    ///
    /// - `*mut c_void` - Clipboard handle on success or null on failure.
    fn SetClipboardData(format: u32, h_mem: *mut c_void) -> *mut c_void;
}

#[cfg(target_os = "windows")]
#[link(name = "kernel32")]
unsafe extern "system" {
    /// Allocates movable global memory for Win32 clipboard ownership transfer.
    ///
    /// # Arguments
    ///
    /// - `u32` - Allocation flags (`GMEM_MOVEABLE`).
    /// - `usize` - Requested byte size.
    ///
    /// # Returns
    ///
    /// - `*mut c_void` - Global memory handle or null.
    fn GlobalAlloc(flags: u32, bytes: usize) -> *mut c_void;
    /// Locks a movable Win32 global memory handle and returns its writable base pointer.
    ///
    /// # Arguments
    ///
    /// - `*mut c_void` - Global memory handle.
    ///
    /// # Returns
    ///
    /// - `*mut c_void` - Base pointer or null.
    fn GlobalLock(h_mem: *mut c_void) -> *mut c_void;
    /// Unlocks a previously locked Win32 global memory handle.
    ///
    /// # Arguments
    ///
    /// - `*mut c_void` - Global memory handle.
    ///
    /// # Returns
    ///
    /// - `i32` - Lock status.
    fn GlobalUnlock(h_mem: *mut c_void) -> i32;
    /// Frees an unowned Win32 global memory handle on error paths.
    ///
    /// # Arguments
    ///
    /// - `*mut c_void` - Global memory handle.
    ///
    /// # Returns
    ///
    /// - `*mut c_void` - Null on success.
    fn GlobalFree(h_mem: *mut c_void) -> *mut c_void;
    /// Returns the allocated byte length of a Win32 global memory object.
    ///
    /// # Arguments
    ///
    /// - `*mut c_void` - Global memory handle.
    ///
    /// # Returns
    ///
    /// - `usize` - Allocated byte length.
    fn GlobalSize(h_mem: *mut c_void) -> usize;
}

#[cfg(target_os = "windows")]
#[link(name = "advapi32")]
unsafe extern "system" {
    /// Reads a typed registry value (`RRF_RT_REG_DWORD`) directly from a Windows registry key.
    ///
    /// # Arguments
    ///
    /// - `isize` - Root `HKEY` handle (`HKEY_CURRENT_USER`).
    /// - `*const u16` - Null-terminated UTF-16 subkey path.
    /// - `*const u16` - Null-terminated UTF-16 value name.
    /// - `u32` - Type filter flags (`RRF_RT_REG_DWORD`).
    /// - `*mut u32` - Optional output type pointer.
    /// - `*mut c_void` - Output value buffer pointer.
    /// - `*mut u32` - In-out buffer byte length pointer.
    ///
    /// # Returns
    ///
    /// - `i32` - `ERROR_SUCCESS` (`0`) on success.
    fn RegGetValueW(
        hkey: isize,
        sub_key: *const u16,
        value: *const u16,
        flags: u32,
        pdw_type: *mut u32,
        pv_data: *mut c_void,
        pcb_data: *mut u32,
    ) -> i32;
}

/// Writes `text` as UTF-16LE `CF_UNICODETEXT` to the Win32 system clipboard.
///
/// # Arguments
///
/// - `&str` - UTF-8 text to place on the Windows clipboard.
///
/// # Returns
///
/// - `bool` - `true` when Win32 `SetClipboardData` succeeded.
#[cfg(target_os = "windows")]
fn windows_write_clipboard(text: &str) -> bool {
    let mut wide: Vec<u16> = text.encode_utf16().collect();
    wide.push(0);
    let byte_len: usize = wide.len().saturating_mul(size_of::<u16>());
    // SAFETY: Standard Win32 `GlobalAlloc` for `CF_UNICODETEXT`.
    let h_mem: *mut c_void = unsafe { GlobalAlloc(WIN32_GMEM_MOVEABLE, byte_len) };
    if h_mem.is_null() {
        return false;
    }
    // SAFETY: `h_mem` is a valid newly allocated movable block of `byte_len` bytes.
    let dst_ptr: *mut c_void = unsafe { GlobalLock(h_mem) };
    if dst_ptr.is_null() {
        // SAFETY: Unlock not needed because lock failed; free unowned block.
        let _: *mut c_void = unsafe { GlobalFree(h_mem) };
        return false;
    }
    // SAFETY: `dst_ptr` has `wide.len()` writable `u16` elements.
    let dst_slice: &mut [u16] = unsafe { from_raw_parts_mut(dst_ptr.cast::<u16>(), wide.len()) };
    dst_slice.copy_from_slice(wide.as_slice());
    // SAFETY: Balanced unlock matching `GlobalLock` above.
    let _: i32 = unsafe { GlobalUnlock(h_mem) };
    // SAFETY: Open Win32 clipboard for current task.
    if unsafe { OpenClipboard(0) } == 0 {
        // SAFETY: Clipboard was not opened so `h_mem` remains process-owned.
        let _: *mut c_void = unsafe { GlobalFree(h_mem) };
        return false;
    }
    // SAFETY: Clipboard is open and owned by this thread.
    let _: i32 = unsafe { EmptyClipboard() };
    // SAFETY: Transfers ownership of `h_mem` to Windows on non-null return.
    let set_res: *mut c_void = unsafe { SetClipboardData(WIN32_CF_UNICODETEXT, h_mem) };
    // SAFETY: Always close clipboard after `OpenClipboard` succeeded.
    let _: i32 = unsafe { CloseClipboard() };
    if set_res.is_null() {
        // SAFETY: `SetClipboardData` failed, so we still own `h_mem` and must free it.
        let _: *mut c_void = unsafe { GlobalFree(h_mem) };
        false
    } else {
        true
    }
}

/// Reads UTF-16LE `CF_UNICODETEXT` directly from the Win32 system clipboard.
///
/// # Returns
///
/// - `Option<String>` - Decoded UTF-8 clipboard text when present.
#[cfg(target_os = "windows")]
fn windows_read_clipboard() -> Option<String> {
    // SAFETY: Queries whether `CF_UNICODETEXT` exists on the system clipboard.
    if unsafe { IsClipboardFormatAvailable(WIN32_CF_UNICODETEXT) } == 0 {
        return None;
    }
    // SAFETY: Opens Win32 clipboard for reading.
    if unsafe { OpenClipboard(0) } == 0 {
        return None;
    }
    let mut output: Option<String> = None;
    // SAFETY: Clipboard is open; handle belongs to the clipboard and must not be freed.
    let handle: *mut c_void = unsafe { GetClipboardData(WIN32_CF_UNICODETEXT) };
    if !handle.is_null() {
        // SAFETY: `handle` is a valid clipboard global memory handle.
        let total_bytes: usize = unsafe { GlobalSize(handle) };
        let max_units: usize = total_bytes / size_of::<u16>();
        // SAFETY: Lock clipboard handle while copying UTF-16 units.
        let src_ptr: *mut c_void = unsafe { GlobalLock(handle) };
        if !src_ptr.is_null() && max_units > 0 {
            // SAFETY: `src_ptr` points to `max_units` valid `u16` elements while locked.
            let units: &[u16] = unsafe { from_raw_parts(src_ptr.cast::<u16>(), max_units) };
            let nul_pos: usize = units
                .iter()
                .position(|unit: &u16| *unit == 0)
                .unwrap_or(units.len());
            output = Some(String::from_utf16_lossy(&units[..nul_pos]));
            // SAFETY: Balanced unlock matching `GlobalLock`.
            let _: i32 = unsafe { GlobalUnlock(handle) };
        }
    }
    // SAFETY: Balanced close matching `OpenClipboard`.
    let _: i32 = unsafe { CloseClipboard() };
    output
}

/// Queries the Windows `AppsUseLightTheme` registry DWORD via `RegGetValueW`.
///
/// # Returns
///
/// - `ThemeMode` - Detected Windows light or dark app theme preference.
#[cfg(target_os = "windows")]
fn windows_query_system_theme() -> ThemeMode {
    let mut subkey_wide: Vec<u16> = WIN32_REG_THEME_SUBKEY.encode_utf16().collect();
    subkey_wide.push(0);
    let mut value_wide: Vec<u16> = WIN32_REG_APPS_USE_LIGHT_THEME.encode_utf16().collect();
    value_wide.push(0);
    let mut dword_val: u32 = 1;
    let mut byte_len: u32 = size_of::<u32>() as u32;
    // SAFETY: Null-terminated UTF-16 strings and properly sized `u32` output buffer.
    let status: i32 = unsafe {
        RegGetValueW(
            WIN32_HKEY_CURRENT_USER,
            subkey_wide.as_ptr(),
            value_wide.as_ptr(),
            WIN32_RRF_RT_REG_DWORD,
            null_mut(),
            (&mut dword_val as *mut u32).cast::<c_void>(),
            &mut byte_len,
        )
    };
    if status == 0 {
        parse_windows_apps_use_light_theme(dword_val)
    } else {
        ThemeMode::Light
    }
}

/// Pipes `text` to a Linux clipboard helper command and reports whether it exited cleanly.
///
/// # Arguments
///
/// - `&str` - Executable name (`wl-copy`, `xclip`, or `xsel`).
/// - `&[&str]` - Command-line arguments.
/// - `&str` - UTF-8 payload written to standard input.
///
/// # Returns
///
/// - `bool` - `true` when the helper command exited with status 0.
#[cfg(target_os = "linux")]
fn linux_run_clipboard_writer(program: &str, args: &[&str], text: &str) -> bool {
    let Ok(mut child) = Command::new(program)
        .args(args)
        .stdin(Stdio::piped())
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .spawn()
    else {
        return false;
    };
    if let Some(mut stdin_pipe) = child.stdin.take()
        && stdin_pipe.write_all(text.as_bytes()).is_err()
    {
        return false;
    }
    let Ok(exit_status) = child.wait() else {
        return false;
    };
    exit_status.success()
}

/// Writes `text` to the active Linux Wayland (`wl-copy`) or X11 (`xclip` / `xsel`) clipboard.
///
/// # Arguments
///
/// - `&str` - UTF-8 text to place on the clipboard.
///
/// # Returns
///
/// - `bool` - `true` when a desktop clipboard utility accepted the payload.
#[cfg(target_os = "linux")]
fn linux_write_clipboard(text: &str) -> bool {
    if cfg!(test) || env::var_os(ENV_EUV_HEADLESS).is_some() {
        return false;
    }
    if env::var_os(ENV_WAYLAND_DISPLAY).is_some()
        && linux_run_clipboard_writer(LINUX_CMD_WL_COPY, &[], text)
    {
        return true;
    }
    if env::var_os(ENV_X11_DISPLAY).is_some() {
        if linux_run_clipboard_writer(
            LINUX_CMD_XCLIP,
            &[LINUX_ARG_SELECTION, LINUX_ARG_CLIPBOARD],
            text,
        ) {
            return true;
        }
        return linux_run_clipboard_writer(
            LINUX_CMD_XSEL,
            &[LINUX_ARG_XSEL_CLIPBOARD, LINUX_ARG_XSEL_INPUT],
            text,
        );
    }
    false
}

/// Runs a Linux clipboard read helper and returns its UTF-8 stdout on zero exit status.
///
/// # Arguments
///
/// - `&str` - Executable name (`wl-paste`, `xclip`, or `xsel`).
/// - `&[&str]` - Command-line arguments.
///
/// # Returns
///
/// - `Option<String>` - Read clipboard string on success.
#[cfg(target_os = "linux")]
fn linux_run_clipboard_reader(program: &str, args: &[&str]) -> Option<String> {
    let Ok(output) = Command::new(program)
        .args(args)
        .stdin(Stdio::null())
        .stderr(Stdio::null())
        .output()
    else {
        return None;
    };
    if !output.status.success() {
        return None;
    }
    String::from_utf8(output.stdout).ok()
}

/// Reads UTF-8 plain text from the Linux Wayland (`wl-paste`) or X11 (`xclip` / `xsel`) clipboard.
///
/// # Returns
///
/// - `Option<String>` - Current desktop clipboard text when available.
#[cfg(target_os = "linux")]
fn linux_read_clipboard() -> Option<String> {
    if cfg!(test) || env::var_os(ENV_EUV_HEADLESS).is_some() {
        return None;
    }
    if env::var_os(ENV_WAYLAND_DISPLAY).is_some()
        && let Some(text) = linux_run_clipboard_reader(LINUX_CMD_WL_PASTE, &[LINUX_ARG_NO_NEWLINE])
    {
        return Some(text);
    }
    if env::var_os(ENV_X11_DISPLAY).is_some() {
        if let Some(text) = linux_run_clipboard_reader(
            LINUX_CMD_XCLIP,
            &["-o", LINUX_ARG_SELECTION, LINUX_ARG_CLIPBOARD],
        ) {
            return Some(text);
        }
        return linux_run_clipboard_reader(
            LINUX_CMD_XSEL,
            &[LINUX_ARG_XSEL_CLIPBOARD, LINUX_ARG_XSEL_OUTPUT],
        );
    }
    None
}

/// Queries the Linux desktop appearance mode via `GTK_THEME`, `COLORFGBG`, and GNOME `gsettings`.
///
/// # Returns
///
/// - `ThemeMode` - Detected Linux light or dark theme preference.
#[cfg(target_os = "linux")]
fn linux_query_system_theme() -> ThemeMode {
    if let Ok(gtk_theme) = env::var(ENV_GTK_THEME)
        && let Some(mode) = parse_linux_theme_hint(&gtk_theme)
    {
        return mode;
    }
    if !cfg!(test) && env::var_os(ENV_EUV_HEADLESS).is_none() {
        if let Some(scheme) = linux_run_clipboard_reader(
            LINUX_CMD_GSETTINGS,
            &["get", LINUX_GSETTINGS_SCHEMA, LINUX_GSETTINGS_COLOR_SCHEME],
        ) && let Some(mode) = parse_linux_theme_hint(&scheme)
        {
            return mode;
        }
        if let Some(theme_name) = linux_run_clipboard_reader(
            LINUX_CMD_GSETTINGS,
            &["get", LINUX_GSETTINGS_SCHEMA, LINUX_GSETTINGS_GTK_THEME],
        ) && let Some(mode) = parse_linux_theme_hint(&theme_name)
        {
            return mode;
        }
    }
    if let Ok(colorfgbg) = env::var(ENV_COLORFGBG)
        && let Some(mode) = parse_colorfgbg_theme_hint(&colorfgbg)
    {
        return mode;
    }
    ThemeMode::Light
}

/// Validates that `url` is a safe external `http://` or `https://` URL without whitespace or control characters.
///
/// # Arguments
///
/// - `&str` - Candidate external URL string.
///
/// # Returns
///
/// - `bool` - `true` when `url` has a valid `http://` or `https://` prefix, a non-empty host authority, and no control or whitespace characters.
#[must_use]
pub fn is_valid_external_url(url: &str) -> bool {
    let trimmed: &str = url.trim();
    if trimmed.is_empty() {
        return false;
    }
    let rest: &str = if let Some(after_https) = trimmed.strip_prefix(URL_SCHEME_HTTPS) {
        after_https
    } else if let Some(after_http) = trimmed.strip_prefix(URL_SCHEME_HTTP) {
        after_http
    } else {
        return false;
    };
    if rest.is_empty() || rest.starts_with('/') {
        return false;
    }
    !trimmed
        .chars()
        .any(|ch: char| ch.is_control() || ch.is_whitespace())
}

/// Spawns the host desktop OS browser launcher for a validated URL outside test and headless runs.
///
/// # Arguments
///
/// - `&str` - Validated external URL string.
///
/// # Returns
///
/// - `bool` - `true` when the desktop launcher process spawned successfully.
#[cfg(not(target_arch = "wasm32"))]
fn open_external_url_desktop(target: &str) -> bool {
    if cfg!(test) || env::var_os(ENV_EUV_HEADLESS).is_some() {
        return false;
    }
    #[cfg(target_os = "macos")]
    {
        Command::new(OS_CMD_OPEN)
            .arg(target)
            .stdin(Stdio::null())
            .stdout(Stdio::null())
            .stderr(Stdio::null())
            .spawn()
            .is_ok()
    }
    #[cfg(target_os = "linux")]
    {
        Command::new(OS_CMD_XDG_OPEN)
            .arg(target)
            .stdin(Stdio::null())
            .stdout(Stdio::null())
            .stderr(Stdio::null())
            .spawn()
            .is_ok()
    }
    #[cfg(target_os = "windows")]
    {
        Command::new(OS_CMD_WIN_SHELL)
            .args([OS_CMD_WIN_EXEC, OS_CMD_WIN_START, "", target])
            .stdin(Stdio::null())
            .stdout(Stdio::null())
            .stderr(Stdio::null())
            .spawn()
            .is_ok()
    }
    #[cfg(not(any(target_os = "macos", target_os = "linux", target_os = "windows")))]
    {
        let _: &str = target;
        false
    }
}

/// Opens a validated `http://` or `https://` URL externally via the registered host bridge, browser `window.open`, or native desktop launcher.
///
/// # Arguments
///
/// - `&str` - External URL to open (`https://...` or `http://...`).
///
/// # Returns
///
/// - `bool` - `true` when the URL passed validation and was accepted by a host bridge or OS/browser launcher.
pub fn open_external_url(url: &str) -> bool {
    if !is_valid_external_url(url) {
        return false;
    }
    let target: &str = url.trim();
    if let Ok(mut guard) = LAST_EXTERNAL_URL.lock() {
        *guard = Some(target.to_string());
    }
    let bridge_ok: bool = dispatch_native_action(NATIVE_ACTION_OPEN_URL, target, "");
    #[cfg(target_arch = "wasm32")]
    {
        bridge_ok || web_open_external_url(target)
    }
    #[cfg(not(target_arch = "wasm32"))]
    {
        let desktop_ok: bool = open_external_url_desktop(target);
        let headless_recorded: bool = cfg!(test) || env::var_os(ENV_EUV_HEADLESS).is_some();
        let host_ok: bool = bridge_ok || desktop_ok;
        host_ok || headless_recorded
    }
}

/// Dispatches an embedded bottom-sheet WebView open/navigate request to any active native host bridge and records telemetry for simulator verification.
///
/// # Arguments
///
/// - `&str` - Validated `http://` or `https://` target URL.
/// - `&str` - Sheet header title.
///
/// # Returns
///
/// - `bool` - `true` when `url` passed validation and the WebView sheet state updated.
pub fn open_webview_sheet_bridge(url: &str, title: &str) -> bool {
    if !is_valid_external_url(url) {
        return false;
    }
    let target: &str = url.trim();
    if let Ok(mut guard) = LAST_WEBVIEW_SHEET.lock() {
        *guard = Some((target.to_string(), title.to_string()));
    }
    if let Ok(mut frame_guard) = LAST_WEBVIEW_FRAME.lock() {
        *frame_guard = None;
    }
    let bridge_ok: bool = dispatch_native_action(NATIVE_ACTION_WEBVIEW, target, title);
    #[cfg(target_arch = "wasm32")]
    {
        let _: bool = web_webview_open(target, title) || bridge_ok;
    }
    #[cfg(target_os = "macos")]
    {
        if !bridge_ok && !cfg!(test) && env::var_os(ENV_EUV_HEADLESS).is_none() {
            let _: bool = macos_webview_open(target, title);
        }
    }
    #[cfg(not(any(target_arch = "wasm32", target_os = "macos")))]
    {
        let _: bool = bridge_ok;
    }
    true
}

/// Synchronizes the screen-space logical viewport rectangle and opacity of the active embedded WebView sheet with the host overlay.
///
/// # Arguments
///
/// - `Rect` - Screen-space logical viewport rectangle covering the embedded WebView content container.
/// - `f32` - Effective composed opacity in `0.0..=1.0`.
///
/// # Returns
///
/// - `bool` - `true` when the geometry or opacity changed and was dispatched to the host overlay.
pub fn sync_webview_sheet_frame(bounds: Rect, opacity: f32) -> bool {
    let left_px: f32 = if bounds.get_x().is_finite() {
        bounds.get_x()
    } else {
        0.0
    };
    let top_px: f32 = if bounds.get_y().is_finite() {
        bounds.get_y()
    } else {
        0.0
    };
    let width_px: f32 = if bounds.get_width().is_finite() {
        bounds.get_width().max(0.0)
    } else {
        0.0
    };
    let height_px: f32 = if bounds.get_height().is_finite() {
        bounds.get_height().max(0.0)
    } else {
        0.0
    };
    let alpha_val: f32 = if opacity.is_finite() {
        opacity.clamp(0.0, 1.0)
    } else {
        0.0
    };
    let next_rect: Rect = Rect::new(left_px, top_px, width_px, height_px);
    let next_frame: (Rect, f32) = (next_rect, alpha_val);
    if let Ok(mut frame_guard) = LAST_WEBVIEW_FRAME.lock() {
        if let Some((prev_rect, prev_alpha)) = *frame_guard {
            let same_pos: bool = (prev_rect.get_x() - left_px).abs() <= 0.25
                && (prev_rect.get_y() - top_px).abs() <= 0.25;
            let same_size: bool = (prev_rect.get_width() - width_px).abs() <= 0.25
                && (prev_rect.get_height() - height_px).abs() <= 0.25;
            let same_alpha: bool = (prev_alpha - alpha_val).abs() <= 0.005;
            if same_pos && same_size && same_alpha {
                return false;
            }
        }
        *frame_guard = Some(next_frame);
    }
    let payload_csv: String =
        format!("{left_px:.2},{top_px:.2},{width_px:.2},{height_px:.2},{alpha_val:.3}");
    let bridge_ok: bool =
        dispatch_native_action(NATIVE_ACTION_WEBVIEW, WEBVIEW_ACTION_FRAME, &payload_csv);
    #[cfg(target_arch = "wasm32")]
    {
        let _: bool =
            web_webview_frame(left_px, top_px, width_px, height_px, alpha_val) || bridge_ok;
    }
    #[cfg(target_os = "macos")]
    {
        if !bridge_ok && !cfg!(test) && env::var_os(ENV_EUV_HEADLESS).is_none() {
            let _: bool = macos_webview_frame(left_px, top_px, width_px, height_px, alpha_val);
        }
    }
    #[cfg(not(any(target_arch = "wasm32", target_os = "macos")))]
    {
        let _: bool = bridge_ok;
    }
    true
}

/// Reloads the active webpage inside any hosted native embedded bottom-sheet WebView.
///
/// # Returns
///
/// - `bool` - `true` when an active WebView target existed and a reload command was dispatched.
pub fn reload_webview_sheet_bridge() -> bool {
    let active_url: Option<String> = LAST_WEBVIEW_SHEET.lock().ok().and_then(
        |guard: MutexGuard<'_, Option<(String, String)>>| {
            guard.as_ref().map(|pair: &(String, String)| pair.0.clone())
        },
    );
    let Some(target_url) = active_url else {
        return false;
    };
    let bridge_ok: bool =
        dispatch_native_action(NATIVE_ACTION_WEBVIEW, WEBVIEW_ACTION_RELOAD, &target_url);
    #[cfg(target_arch = "wasm32")]
    {
        let _: bool = web_webview_reload(&target_url) || bridge_ok;
    }
    #[cfg(target_os = "macos")]
    {
        if !bridge_ok && !cfg!(test) && env::var_os(ENV_EUV_HEADLESS).is_none() {
            let _: bool = macos_webview_reload(&target_url);
        }
    }
    #[cfg(not(any(target_arch = "wasm32", target_os = "macos")))]
    {
        let _: bool = bridge_ok;
    }
    true
}

/// Notifies any active native host bridge that the embedded bottom-sheet WebView was dismissed.
///
/// # Returns
///
/// - `bool` - `true` when handled by an active native host bridge.
pub fn close_webview_sheet_bridge() -> bool {
    if let Ok(mut guard) = LAST_WEBVIEW_SHEET.lock() {
        *guard = None;
    }
    if let Ok(mut frame_guard) = LAST_WEBVIEW_FRAME.lock() {
        *frame_guard = None;
    }
    let bridge_ok: bool = dispatch_native_action(NATIVE_ACTION_WEBVIEW, WEBVIEW_ACTION_CLOSE, "");
    #[cfg(target_arch = "wasm32")]
    {
        web_webview_close() || bridge_ok
    }
    #[cfg(target_os = "macos")]
    {
        if !bridge_ok && !cfg!(test) && env::var_os(ENV_EUV_HEADLESS).is_none() {
            macos_webview_close() || bridge_ok
        } else {
            bridge_ok
        }
    }
    #[cfg(not(any(target_arch = "wasm32", target_os = "macos")))]
    {
        bridge_ok
    }
}

/// Returns the most recently synchronized embedded WebView `(bounds, opacity)` frame, or `None` after close.
///
/// # Returns
///
/// - `Option<(Rect, f32)>` - Last dispatched embedded WebView viewport rectangle and opacity.
#[must_use]
pub fn last_webview_sheet_frame() -> Option<(Rect, f32)> {
    LAST_WEBVIEW_FRAME
        .lock()
        .ok()
        .and_then(|guard: MutexGuard<'_, Option<(Rect, f32)>>| *guard)
}

/// Returns the most recently validated URL passed to `open_external_url` in this process.
///
/// # Returns
///
/// - `Option<String>` - Last external browser URL, if any.
#[must_use]
pub fn last_opened_external_url() -> Option<String> {
    LAST_EXTERNAL_URL
        .lock()
        .ok()
        .and_then(|guard: MutexGuard<'_, Option<String>>| guard.clone())
}

/// Returns the currently active `(url, title)` pair opened via `open_webview_sheet_bridge`, or `None` after close.
///
/// # Returns
///
/// - `Option<(String, String)>` - Active WebView sheet URL and title, if open.
#[must_use]
pub fn active_webview_sheet_target() -> Option<(String, String)> {
    LAST_WEBVIEW_SHEET
        .lock()
        .ok()
        .and_then(|guard: MutexGuard<'_, Option<(String, String)>>| guard.clone())
}

/// Clears recorded `open_external_url` and `open_webview_sheet_bridge` telemetry for isolated test runs.
pub fn clear_link_action_history() {
    if let Ok(mut ext_guard) = LAST_EXTERNAL_URL.lock() {
        *ext_guard = None;
    }
    if let Ok(mut wv_guard) = LAST_WEBVIEW_SHEET.lock() {
        *wv_guard = None;
    }
    if let Ok(mut frame_guard) = LAST_WEBVIEW_FRAME.lock() {
        *frame_guard = None;
    }
}