Skip to content

Commit ba51119

Browse files
bridge native logger at JVM.
1 parent 1200e8d commit ba51119

3 files changed

Lines changed: 80 additions & 37 deletions

File tree

wrywebview/src/main/rust/handle.rs

Lines changed: 23 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ use std::num::NonZeroIsize;
1818
use wry::raw_window_handle::Win32WindowHandle;
1919

2020
use crate::error::WebViewError;
21-
use crate::log_enabled;
21+
use crate::wry_log;
2222

2323
/// Wrapper around a raw window handle for WebView creation.
2424
pub struct RawWindow {
@@ -49,35 +49,42 @@ pub fn raw_window_handle_from(parent_handle: u64) -> Result<RawWindowHandle, Web
4949

5050
#[cfg(target_os = "windows")]
5151
{
52-
let hwnd = NonZeroIsize::new(parent_handle as isize)
53-
.ok_or(WebViewError::InvalidWindowHandle)?;
52+
let hwnd =
53+
NonZeroIsize::new(parent_handle as isize).ok_or(WebViewError::InvalidWindowHandle)?;
5454
let handle = RawWindowHandle::Win32(Win32WindowHandle::new(hwnd));
55-
if log_enabled() {
56-
eprintln!("[wrywebview] raw_window_handle Win32=0x{:x}", parent_handle);
57-
}
55+
wry_log!("[wrywebview] raw_window_handle Win32=0x{:x}", parent_handle);
56+
// if log_enabled() {
57+
// eprintln!("[wrywebview] raw_window_handle Win32=0x{:x}", parent_handle);
58+
// }
5859
return Ok(handle);
5960
}
6061

6162
#[cfg(target_os = "macos")]
6263
{
6364
let ns_view = crate::platform::macos::appkit_ns_view_from_handle(parent_handle)?;
6465
let handle = RawWindowHandle::AppKit(AppKitWindowHandle::new(ns_view));
65-
if log_enabled() {
66-
eprintln!(
67-
"[wrywebview] raw_window_handle AppKit=0x{:x} ns_view=0x{:x}",
68-
parent_handle,
69-
ns_view.as_ptr() as usize
70-
);
71-
}
66+
wry_log!(
67+
"[wrywebview] raw_window_handle AppKit=0x{:x} ns_view=0x{:x}",
68+
parent_handle,
69+
ns_view.as_ptr() as usize
70+
);
71+
// if log_enabled() {
72+
// eprintln!(
73+
// "[wrywebview] raw_window_handle AppKit=0x{:x} ns_view=0x{:x}",
74+
// parent_handle,
75+
// ns_view.as_ptr() as usize
76+
// );
77+
// }
7278
return Ok(handle);
7379
}
7480

7581
#[cfg(target_os = "linux")]
7682
{
7783
let handle = RawWindowHandle::Xlib(XlibWindowHandle::new(parent_handle as c_ulong));
78-
if log_enabled() {
79-
eprintln!("[wrywebview] raw_window_handle Xlib=0x{:x}", parent_handle);
80-
}
84+
// if log_enabled() {
85+
// eprintln!("[wrywebview] raw_window_handle Xlib=0x{:x}", parent_handle);
86+
// }
87+
wry_log!("[wrywebview] raw_window_handle Xlib=0x{:x}", handle);
8188
return Ok(handle);
8289
}
8390

wrywebview/src/main/rust/lib.rs

Lines changed: 41 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ mod state;
1010

1111
use std::str::FromStr;
1212
use std::sync::atomic::Ordering;
13-
use std::sync::Arc;
13+
use std::sync::{Arc, OnceLock, RwLock};
1414

1515
use wry::cookie::time::OffsetDateTime;
1616
use wry::cookie::{Cookie, Expiration, SameSite};
@@ -159,14 +159,47 @@ pub fn set_log_enabled(enabled: bool) {
159159
LOG_ENABLED.store(enabled, Ordering::Relaxed);
160160
}
161161

162+
#[uniffi::export(callback_interface)]
163+
pub trait NativeLogger: Send + Sync {
164+
fn handle_log(&self, data: String);
165+
}
166+
167+
static GLOBAL_LOGGER: OnceLock<RwLock<Option<Box<dyn NativeLogger>>>> = OnceLock::new();
168+
169+
fn get_logger_registry() -> &'static RwLock<Option<Box<dyn NativeLogger>>> {
170+
GLOBAL_LOGGER.get_or_init(|| RwLock::new(None))
171+
}
172+
173+
#[uniffi::export]
174+
pub fn set_native_logger(logger: Box<dyn NativeLogger>) {
175+
let mut lock = get_logger_registry().write().unwrap();
176+
*lock = Some(logger);
177+
}
178+
179+
#[macro_export]
162180
macro_rules! wry_log {
163181
($($arg:tt)*) => {
164-
if log_enabled() {
165-
eprintln!($($arg)*);
166-
}
182+
$crate::do_internal_log(format_args!($($arg)*));
167183
};
168184
}
169185

186+
#[doc(hidden)]
187+
pub fn do_internal_log(args: std::fmt::Arguments) {
188+
if !log_enabled() {
189+
return;
190+
}
191+
let log_string = args.to_string();
192+
193+
if let Ok(lock) = crate::get_logger_registry().read() {
194+
if let Some(ref logger) = *lock {
195+
// 执行回调
196+
logger.handle_log(log_string);
197+
return;
198+
}
199+
}
200+
eprintln!("{}", log_string);
201+
}
202+
170203
// ============================================================================
171204
// WebView Creation
172205
// ============================================================================
@@ -364,12 +397,10 @@ pub fn create_webview_with_user_agent(
364397
// ============================================================================
365398

366399
fn set_bounds_inner(id: u64, x: i32, y: i32, width: i32, height: i32) -> Result<(), WebViewError> {
367-
if log_enabled() {
368-
wry_log!(
369-
"[wrywebview] set_bounds id={} pos=({}, {}) size={}x{}",
370-
id, x, y, width, height
371-
);
372-
}
400+
wry_log!(
401+
"[wrywebview] set_bounds id={} pos=({}, {}) size={}x{}",
402+
id, x, y, width, height
403+
);
373404
let bounds = make_bounds(x, y, width, height);
374405
with_webview(id, |webview| webview.set_bounds(bounds).map_err(WebViewError::from))
375406
}

wrywebview/src/main/rust/platform/macos.rs

Lines changed: 16 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -5,13 +5,13 @@ use std::ffi::CStr;
55
use std::ptr::NonNull;
66

77
use dispatch2::run_on_main;
8+
pub use dispatch2::DispatchQueue;
89
use objc2::msg_send;
910
use objc2::runtime::{AnyClass, AnyObject};
1011
pub use objc2::MainThreadMarker;
11-
pub use dispatch2::DispatchQueue;
1212

1313
use crate::error::WebViewError;
14-
use crate::log_enabled;
14+
use crate::wry_log;
1515

1616
/// Runs a closure on the main thread using GCD.
1717
pub fn run_on_main_thread<F, R>(f: F) -> Result<R, WebViewError>
@@ -30,9 +30,10 @@ pub fn appkit_ns_view_from_handle(parent_handle: u64) -> Result<NonNull<c_void>,
3030
.ok_or(WebViewError::InvalidWindowHandle)?;
3131
let obj = unsafe { &*(ptr.as_ptr() as *mut AnyObject) };
3232
let class_name = obj.class().name().to_string_lossy();
33-
if log_enabled() {
34-
eprintln!("[wrywebview] appkit handle class={}", class_name);
35-
}
33+
// if log_enabled() {
34+
// eprintln!("[wrywebview] appkit handle class={}", class_name);
35+
// }
36+
wry_log!("[wrywebview] appkit handle class={}", class_name);
3637

3738
let nswindow_name = unsafe { CStr::from_bytes_with_nul_unchecked(b"NSWindow\0") };
3839
let nsview_name = unsafe { CStr::from_bytes_with_nul_unchecked(b"NSView\0") };
@@ -43,12 +44,16 @@ pub fn appkit_ns_view_from_handle(parent_handle: u64) -> Result<NonNull<c_void>,
4344
if msg_send![obj, isKindOfClass: nswindow_cls] {
4445
let view: *mut AnyObject = msg_send![obj, contentView];
4546
let view = NonNull::new(view).ok_or(WebViewError::InvalidWindowHandle)?;
46-
if log_enabled() {
47-
eprintln!(
48-
"[wrywebview] appkit handle is NSWindow, contentView=0x{:x}",
49-
view.as_ptr() as usize
50-
);
51-
}
47+
// if log_enabled() {
48+
// eprintln!(
49+
// "[wrywebview] appkit handle is NSWindow, contentView=0x{:x}",
50+
// view.as_ptr() as usize
51+
// );
52+
// }
53+
wry_log!(
54+
"[wrywebview] appkit handle is NSWindow, contentView=0x{:x}",
55+
view.as_ptr() as usize
56+
);
5257
return Ok(view.cast());
5358
}
5459
if msg_send![obj, isKindOfClass: nsview_cls] {

0 commit comments

Comments
 (0)