1use super::*;
2
3pub fn register_native_action_bridge(bridge: fn(&str, &str, &str) -> bool) {
9 EXTERNAL_NATIVE_ACTION_BRIDGE.store(bridge as *mut (), Ordering::Release);
10}
11
12pub 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 let func: fn(&str, &str, &str) -> bool =
30 unsafe { transmute::<*mut (), fn(&str, &str, &str) -> bool>(raw) };
31 func(kind, arg1, arg2)
32}
33
34pub 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
70pub fn register_clipboard_read_bridge(bridge: fn() -> Option<String>) {
76 EXTERNAL_CLIPBOARD_READ_BRIDGE.store(bridge as *mut (), Ordering::Release);
77}
78
79pub fn clear_clipboard_read_bridge() {
81 EXTERNAL_CLIPBOARD_READ_BRIDGE.store(null_mut(), Ordering::Release);
82}
83
84pub fn register_theme_query_bridge(bridge: fn() -> ThemeMode) {
90 EXTERNAL_THEME_QUERY_BRIDGE.store(bridge as *mut (), Ordering::Release);
91}
92
93pub fn clear_theme_query_bridge() {
95 EXTERNAL_THEME_QUERY_BRIDGE.store(null_mut(), Ordering::Release);
96}
97
98pub fn clear_clipboard_cache() {
100 if let Ok(mut cache_guard) = NATIVE_CLIPBOARD_CACHE.lock() {
101 *cache_guard = None;
102 }
103}
104
105#[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 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#[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#[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#[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#[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 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 fn objc_autoreleasePoolPush() -> *mut c_void;
262 fn objc_autoreleasePoolPop(pool: *mut c_void);
268}
269
270#[cfg(target_os = "macos")]
280fn macos_write_pasteboard_pooled(text: &str) -> bool {
281 let pool: *mut c_void = unsafe { objc_autoreleasePoolPush() };
283 let written: bool = macos_write_pasteboard(text);
284 unsafe { objc_autoreleasePoolPop(pool) };
286 written
287}
288
289#[cfg(target_os = "macos")]
295fn macos_read_pasteboard_pooled() -> Option<String> {
296 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 let extracted: String =
321 unsafe { CStr::from_ptr(utf8_ptr).to_string_lossy().into_owned() };
322 result = Some(extracted);
323 }
324 }
325 }
326 unsafe { objc_autoreleasePoolPop(pool) };
328 result
329}
330
331#[cfg(target_os = "windows")]
332#[link(name = "user32")]
333unsafe extern "system" {
334 fn OpenClipboard(h_wnd_new_owner: isize) -> i32;
344 fn CloseClipboard() -> i32;
350 fn EmptyClipboard() -> i32;
356 fn IsClipboardFormatAvailable(format: u32) -> i32;
366 fn GetClipboardData(format: u32) -> *mut c_void;
376 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 fn GlobalAlloc(flags: u32, bytes: usize) -> *mut c_void;
403 fn GlobalLock(h_mem: *mut c_void) -> *mut c_void;
413 fn GlobalUnlock(h_mem: *mut c_void) -> i32;
423 fn GlobalFree(h_mem: *mut c_void) -> *mut c_void;
433 fn GlobalSize(h_mem: *mut c_void) -> usize;
443}
444
445#[cfg(target_os = "windows")]
446#[link(name = "advapi32")]
447unsafe extern "system" {
448 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#[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 let h_mem: *mut c_void = unsafe { GlobalAlloc(WIN32_GMEM_MOVEABLE, byte_len) };
490 if h_mem.is_null() {
491 return false;
492 }
493 let dst_ptr: *mut c_void = unsafe { GlobalLock(h_mem) };
495 if dst_ptr.is_null() {
496 let _: *mut c_void = unsafe { GlobalFree(h_mem) };
498 return false;
499 }
500 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 let _: i32 = unsafe { GlobalUnlock(h_mem) };
505 if unsafe { OpenClipboard(0) } == 0 {
507 let _: *mut c_void = unsafe { GlobalFree(h_mem) };
509 return false;
510 }
511 let _: i32 = unsafe { EmptyClipboard() };
513 let set_res: *mut c_void = unsafe { SetClipboardData(WIN32_CF_UNICODETEXT, h_mem) };
515 let _: i32 = unsafe { CloseClipboard() };
517 if set_res.is_null() {
518 let _: *mut c_void = unsafe { GlobalFree(h_mem) };
520 false
521 } else {
522 true
523 }
524}
525
526#[cfg(target_os = "windows")]
532fn windows_read_clipboard() -> Option<String> {
533 if unsafe { IsClipboardFormatAvailable(WIN32_CF_UNICODETEXT) } == 0 {
535 return None;
536 }
537 if unsafe { OpenClipboard(0) } == 0 {
539 return None;
540 }
541 let mut output: Option<String> = None;
542 let handle: *mut c_void = unsafe { GetClipboardData(WIN32_CF_UNICODETEXT) };
544 if !handle.is_null() {
545 let total_bytes: usize = unsafe { GlobalSize(handle) };
547 let max_units: usize = total_bytes / size_of::<u16>();
548 let src_ptr: *mut c_void = unsafe { GlobalLock(handle) };
550 if !src_ptr.is_null() && max_units > 0 {
551 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 let _: i32 = unsafe { GlobalUnlock(handle) };
560 }
561 }
562 let _: i32 = unsafe { CloseClipboard() };
564 output
565}
566
567#[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 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#[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#[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#[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#[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#[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(>k_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#[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#[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
841pub 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
872fn 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
904fn 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
934fn 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
976fn 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
1006fn 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
1031pub 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
1074pub 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
1121pub 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
1130pub 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
1242pub 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
1310pub 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#[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#[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#[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#[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#[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#[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
1440pub 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}