use objc2::msg_send;
use objc2::runtime::AnyObject;
use objc2_app_kit::{NSApplication, NSColor, NSView, NSWindow, NSWindowStyleMask};
use objc2_foundation::{ns_string, MainThreadMarker, NSNumber};
pub fn set_transparent(app: &tauri::AppHandle, transparent: bool) {
let handle = app.clone();
let _ = handle.run_on_main_thread(move || apply_all_ns(transparent));
}
fn apply_all_ns(transparent: bool) {
let Some(mtm) = MainThreadMarker::new() else {
return;
};
let app = NSApplication::sharedApplication(mtm);
for window in app.windows().iter() {
if window.styleMask().contains(NSWindowStyleMask::Titled) {
apply_ns(&window, transparent);
}
}
}
fn apply_ns(window: &NSWindow, transparent: bool) {
window.setOpaque(!transparent);
let color = if transparent {
unsafe { NSColor::clearColor() }
} else {
unsafe { NSColor::windowBackgroundColor() }
};
window.setBackgroundColor(Some(&color));
if let Some(content) = window.contentView() {
set_webview_draws_background(&content, !transparent);
}
window.invalidateShadow();
}
fn set_webview_draws_background(view: &NSView, draws: bool) {
let is_webview = view.class().name().to_bytes().windows(9).any(|w| w == b"WKWebView");
if is_webview {
let value = NSNumber::numberWithBool(draws);
let _: () = unsafe {
msg_send![view, setValue: &*value as &AnyObject, forKey: ns_string!("drawsBackground")]
};
return;
}
for sub in view.subviews().iter() {
set_webview_draws_background(&sub, draws);
}
}