Skip to main content

tauri_nspanel/
panel.rs

1// Re-export commonly used types
2pub use objc2_app_kit::{
3    NSAutoresizingMaskOptions, NSTrackingAreaOptions, NSWindowCollectionBehavior, NSWindowStyleMask,
4};
5
6#[doc(hidden)]
7pub fn resolve_tracking_area_options(
8    mut options: objc2_app_kit::NSTrackingAreaOptions,
9    auto_resize: bool,
10) -> objc2_app_kit::NSTrackingAreaOptions {
11    if auto_resize {
12        options |= objc2_app_kit::NSTrackingAreaOptions::InVisibleRect;
13    }
14
15    options
16}
17
18/// Teach elevated WebKit text input clients to report their containing window's level.
19///
20/// AppKit uses the optional `NSTextInputClient::windowLevel` method to place input-method UI
21/// above text clients whose windows are higher than `NSFloatingWindowLevel`. `WKWebView` does
22/// not currently implement that method, so candidate windows can otherwise appear behind an
23/// elevated panel.
24#[doc(hidden)]
25pub fn install_text_input_client_window_level(root: &objc2_app_kit::NSView) {
26    use std::ffi::CStr;
27
28    use objc2::runtime::AnyProtocol;
29
30    let protocol_name = CStr::from_bytes_with_nul(b"NSTextInputClient\0")
31        .expect("NSTextInputClient protocol name must be NUL-terminated");
32    let Some(text_input_client) = AnyProtocol::get(protocol_name) else {
33        return;
34    };
35
36    install_text_input_client_window_level_in_subtree(root, text_input_client);
37}
38
39fn install_text_input_client_window_level_in_subtree(
40    root: &objc2_app_kit::NSView,
41    text_input_client: &objc2::runtime::AnyProtocol,
42) {
43    use objc2_foundation::NSObjectProtocol;
44
45    if root.conformsToProtocol(text_input_client) {
46        let _ = install_window_level_method(stable_text_input_client_class(root.class()));
47    }
48
49    let subviews = root.subviews();
50    for subview in subviews.iter() {
51        install_text_input_client_window_level_in_subtree(&subview, text_input_client);
52    }
53}
54
55fn stable_text_input_client_class(
56    runtime_class: &objc2::runtime::AnyClass,
57) -> &objc2::runtime::AnyClass {
58    let mut candidate = runtime_class;
59
60    while let Some(superclass) = candidate.superclass() {
61        if superclass.name().to_bytes() == b"WKWebView" {
62            return candidate;
63        }
64        candidate = superclass;
65    }
66
67    runtime_class
68}
69
70fn install_window_level_method(class: &objc2::runtime::AnyClass) -> bool {
71    use objc2::runtime::{Imp, Sel};
72
73    let selector = objc2::sel!(windowLevel);
74    if class.instance_method(selector).is_some() {
75        return false;
76    }
77
78    unsafe extern "C-unwind" fn window_level(
79        view: &objc2_app_kit::NSView,
80        _selector: Sel,
81    ) -> objc2::ffi::NSInteger {
82        view.window().map_or(0, |window| window.level())
83    }
84
85    let implementation: unsafe extern "C-unwind" fn(
86        &objc2_app_kit::NSView,
87        Sel,
88    ) -> objc2::ffi::NSInteger = window_level;
89
90    // SAFETY: Objective-C method implementations erase their concrete function signature to
91    // `Imp`. The `q@:` encoding below matches `(id, SEL) -> NSInteger` on 64-bit macOS.
92    let implementation: Imp = unsafe { std::mem::transmute(implementation) };
93    let type_encoding = b"q@:\0";
94
95    // SAFETY: `class` is a registered Objective-C class, the selector has no explicit arguments,
96    // and the implementation and type encoding agree. Adding a method is safe for the lifetime of
97    // the process because Objective-C classes are never deallocated.
98    unsafe {
99        objc2::ffi::class_addMethod(
100            class as *const _ as *mut _,
101            selector,
102            implementation,
103            type_encoding.as_ptr().cast(),
104        )
105        .as_bool()
106    }
107}
108
109/// Macro to create a custom NSPanel class
110///
111/// This macro generates a custom NSPanel subclass with the specified configuration.
112/// The first parameter is the name of your custom panel class.
113///
114/// **Implementation Details**:
115/// - The macro generates an internal `Raw{ClassName}` Objective-C class
116/// - A public `{ClassName}` wrapper type that implements `Send` and `Sync`
117/// - All methods are implemented on the wrapper type
118///
119/// **Thread Safety**: The wrapper type implements `Send` and `Sync` to allow
120/// passing references through Tauri's command system. However, all actual panel
121/// operations must be performed on the main thread.
122///
123/// ## Sections:
124/// - `config`: Override NSPanel methods that return boolean values (use snake_case names)
125/// - `with`: Optional configurations (tracking_area, etc.)
126///
127/// ## Mouse Tracking:
128/// When you enable tracking_area in the `with` section, mouse event callbacks become available
129/// on your event handler. You can set callbacks for:
130/// - `on_mouse_entered()` - Called when mouse enters the panel
131/// - `on_mouse_exited()` - Called when mouse exits the panel
132/// - `on_mouse_moved()` - Called when mouse moves within the panel
133/// - `on_cursor_update()` - Called when cursor needs to be updated
134///
135/// ## Usage:
136/// ```no_run
137/// use tauri_nspanel::{tauri_panel, Panel, TrackingAreaOptions};
138///
139/// tauri_panel! {
140///     panel!(MyCustomPanel {
141///         config: {
142///             can_become_key_window: true,
143///             can_become_main_window: false
144///         }
145///         with: {
146///             tracking_area: {
147///                 options: TrackingAreaOptions::new()
148///                     .active_always()
149///                     .mouse_entered_and_exited()
150///                     .mouse_moved(),
151///                 auto_resize: true
152///             }
153///         }
154///     })
155///
156///     panel_event!(MyPanelEventHandler {
157///         window_did_become_key(notification: &NSNotification) -> ()
158///     })
159/// }
160///
161/// // In your Tauri app:
162/// fn create_panel(window: &tauri::WebviewWindow) -> tauri::Result<()> {
163///     // Convert existing Tauri window to your custom panel
164///     let panel = MyCustomPanel::from_window(window)?;
165///
166///     // Use control methods
167///     panel.show();
168///     panel.set_level(5i64); // NSStatusWindowLevel
169///     panel.set_floating_panel(true);
170///
171///     // Create and attach an event handler
172///     let handler = MyPanelEventHandler::new();
173///     handler.window_did_become_key(|_notification| {
174///         println!("Panel became key window");
175///     });
176///
177///     // If tracking_area is enabled, you can set mouse event callbacks
178///     handler.on_mouse_entered(|_event| {
179///         println!("Mouse entered the panel");
180///     });
181///
182///     handler.on_mouse_moved(|event| {
183///         let location = event.locationInWindow();
184///         println!("Mouse moved to: x={}, y={}", location.x, location.y);
185///     });
186///
187///     panel.set_event_handler(Some(handler.as_ref()));
188///
189///     Ok(())
190/// }
191/// ```
192///
193/// ## Available Methods:
194/// - `show()`, `hide()`, `to_window()`
195/// - `make_key_window()`, `resign_key_window()`
196/// - `set_level()`, `set_alpha_value()`, `set_content_size()`
197/// - `set_floating_panel()`, `set_has_shadow()`, `set_opaque()`
198/// - `set_accepts_mouse_moved_events()`, `set_ignores_mouse_events()`
199/// - And many more...
200#[macro_export]
201macro_rules! panel {
202    (
203        $class_name:ident {
204            $(config: {
205                $($method:ident: $value:expr),* $(,)?
206            })?
207            $(with: {
208                $(tracking_area: {
209                    options: $tracking_options:expr,
210                    auto_resize: $auto_resize:expr $(,)?
211                })?
212            })?
213        }
214    ) => {
215        $crate::pastey::paste! {
216            struct [<$class_name Ivars>];
217
218            $crate::objc2::define_class!(
219                #[unsafe(super = $crate::objc2_app_kit::NSPanel)]
220                #[name = stringify!($class_name)]
221                #[ivars = [<$class_name Ivars>]]
222
223                struct [<Raw $class_name>];
224
225                unsafe impl NSObjectProtocol for [<Raw $class_name>] {}
226
227                impl [<Raw $class_name>] {
228                    $($(
229                        #[doc = concat!(" Returns whether panels of this class ", stringify!([<$method:lower_camel>]))]
230                        #[unsafe(method([<$method:lower_camel>]))]
231                        fn [<__ $method:snake>]() -> bool {
232                            $value
233                        }
234
235                        #[doc = concat!(" Returns whether this specific panel instance ", stringify!([<$method:lower_camel>]))]
236                        #[unsafe(method([<$method:lower_camel>]))]
237                        fn [<__ $method:snake _instance>](&self) -> bool {
238                            $value
239                        }
240                    )*)?
241
242                    // Mouse tracking methods - forward to delegate if set
243                    #[unsafe(method(mouseEntered:))]
244                    fn __mouse_entered(&self, event: &$crate::objc2_app_kit::NSEvent) {
245                        unsafe {
246                            // Get the delegate directly from the window
247                            let delegate: Option<$crate::objc2::rc::Retained<$crate::objc2::runtime::ProtocolObject<dyn $crate::objc2_app_kit::NSWindowDelegate>>> = $crate::objc2::msg_send![self, delegate];
248                            if let Some(ref d) = delegate {
249                                // Check if delegate responds to selector before calling
250                                let selector = $crate::objc2::sel!(mouseEntered:);
251                                let responds: bool = $crate::objc2::msg_send![&**d, respondsToSelector: selector];
252                                if responds {
253                                    let _: () = $crate::objc2::msg_send![&**d, mouseEntered: event];
254                                }
255                            }
256                        }
257                    }
258
259                    #[unsafe(method(mouseExited:))]
260                    fn __mouse_exited(&self, event: &$crate::objc2_app_kit::NSEvent) {
261                        unsafe {
262                            // Get the delegate directly from the window
263                            let delegate: Option<$crate::objc2::rc::Retained<$crate::objc2::runtime::ProtocolObject<dyn $crate::objc2_app_kit::NSWindowDelegate>>> = $crate::objc2::msg_send![self, delegate];
264                            if let Some(ref d) = delegate {
265                                // Check if delegate responds to selector before calling
266                                let selector = $crate::objc2::sel!(mouseExited:);
267                                let responds: bool = $crate::objc2::msg_send![&**d, respondsToSelector: selector];
268                                if responds {
269                                    let _: () = $crate::objc2::msg_send![&**d, mouseExited: event];
270                                }
271                            }
272                        }
273                    }
274
275                    #[unsafe(method(mouseMoved:))]
276                    fn __mouse_moved(&self, event: &$crate::objc2_app_kit::NSEvent) {
277                        unsafe {
278                            // Get the delegate directly from the window
279                            let delegate: Option<$crate::objc2::rc::Retained<$crate::objc2::runtime::ProtocolObject<dyn $crate::objc2_app_kit::NSWindowDelegate>>> = $crate::objc2::msg_send![self, delegate];
280                            if let Some(ref d) = delegate {
281                                // Check if delegate responds to selector before calling
282                                let selector = $crate::objc2::sel!(mouseMoved:);
283                                let responds: bool = $crate::objc2::msg_send![&**d, respondsToSelector: selector];
284                                if responds {
285                                    let _: () = $crate::objc2::msg_send![&**d, mouseMoved: event];
286                                }
287                            }
288                        }
289                    }
290
291                    #[unsafe(method(cursorUpdate:))]
292                    fn __cursor_update(&self, event: &$crate::objc2_app_kit::NSEvent) {
293                        unsafe {
294                            // Get the delegate directly from the window
295                            let delegate: Option<$crate::objc2::rc::Retained<$crate::objc2::runtime::ProtocolObject<dyn $crate::objc2_app_kit::NSWindowDelegate>>> = $crate::objc2::msg_send![self, delegate];
296                            if let Some(ref d) = delegate {
297                                // Check if delegate responds to selector before calling
298                                let selector = $crate::objc2::sel!(cursorUpdate:);
299                                let responds: bool = $crate::objc2::msg_send![&**d, respondsToSelector: selector];
300                                if responds {
301                                    let _: () = $crate::objc2::msg_send![&**d, cursorUpdate: event];
302                                }
303                            }
304                        }
305                    }
306                }
307            );
308
309            #[doc = " A public wrapper for `Raw" $class_name "` "]
310            pub struct $class_name<R: tauri::Runtime = tauri::Wry> {
311                panel: $crate::objc2::rc::Retained<[<Raw $class_name>]>,
312                label: String,
313                original_class: *const $crate::objc2::runtime::AnyClass,
314                original_delegate: std::cell::OnceCell<$crate::objc2::rc::Retained<$crate::objc2::runtime::ProtocolObject<dyn $crate::objc2_app_kit::NSWindowDelegate>>>,
315                app_handle: tauri::AppHandle<R>,
316                event_handler: std::cell::RefCell<Option<$crate::objc2::rc::Retained<$crate::objc2::runtime::ProtocolObject<dyn $crate::objc2_app_kit::NSWindowDelegate>>>>,
317            }
318
319            // SAFETY: While NSPanel must only be used on the main thread, we implement Send + Sync
320            // to allow passing references through Tauri's command system. Users must ensure
321            // actual panel operations happen on the main thread.
322            unsafe impl<R: tauri::Runtime> Send for $class_name<R> {}
323            unsafe impl<R: tauri::Runtime> Sync for $class_name<R> {}
324
325            impl<R: tauri::Runtime> $class_name<R> where $class_name<R>: $crate::Panel<R> {
326                fn with_label(panel: $crate::objc2::rc::Retained<[<Raw $class_name>]>, label: String, original_class: *const $crate::objc2::runtime::AnyClass, app_handle: tauri::AppHandle<R>) -> Self {
327                    Self {
328                        panel,
329                        label,
330                        original_class,
331                        original_delegate: std::cell::OnceCell::new(),
332                        app_handle,
333                        event_handler: std::cell::RefCell::new(None),
334                    }
335                }
336
337                /// Convert a Tauri window to this panel type (convenience method)
338                pub fn from_window(window: &tauri::WebviewWindow<R>) -> tauri::Result<Self> {
339                    let label = window.label().to_string();
340                    <Self as $crate::FromWindow<R>>::from_window(window.clone(), label)
341                }
342
343            }
344
345            // Implement Panel trait
346            impl<R: tauri::Runtime> $crate::Panel<R> for $class_name<R> {
347                fn show(&self) {
348                    unsafe {
349                        let _: () = $crate::objc2::msg_send![&*self.panel, orderFrontRegardless];
350                    }
351                }
352
353                fn hide(&self) {
354                    unsafe {
355                        let _: () = $crate::objc2::msg_send![&*self.panel, orderOut: $crate::objc2::ffi::nil];
356                    }
357                }
358
359                /// Convert panel back to a regular Tauri window
360                fn to_window(&self) -> Option<tauri::WebviewWindow<R>> {
361                    use tauri::Manager;
362                    use $crate::ManagerExt;
363
364                    unsafe extern "C" {
365                        fn object_setClass(
366                            obj: *mut $crate::objc2_foundation::NSObject,
367                            cls: *const $crate::objc2::runtime::AnyClass,
368                        ) -> *const $crate::objc2::runtime::AnyClass;
369                    }
370
371                    if let Some(_) = self.app_handle.remove_webview_panel(self.label.as_str()) {
372                        self.set_event_handler(None);
373                        // Tauri/Tao retains the native window and releases it during close.
374                        // AppKit must not release the same window independently.
375                        self.set_released_when_closed(false);
376
377                        unsafe {
378                            let target_class = if !self.original_class.is_null() {
379                                self.original_class
380                            } else {
381                                $crate::objc2_app_kit::NSWindow::class()
382                            };
383
384                            object_setClass(
385                                &*self.panel as *const [<Raw $class_name>] as *mut $crate::objc2_foundation::NSObject,
386                                target_class,
387                            );
388                        }
389
390                        self.app_handle.get_webview_window(&self.label)
391                    } else {
392                        None
393                    }
394                }
395
396                fn as_panel(&self) -> &$crate::objc2_app_kit::NSPanel {
397                    // SAFETY: Raw class inherits from NSPanel
398                    unsafe { &*(&*self.panel as *const [<Raw $class_name>] as *const $crate::objc2_app_kit::NSPanel) }
399                    // Cast the retained Raw panel to NSPanel reference
400                }
401
402                fn label(&self) -> &str {
403                    &self.label
404                }
405
406                fn as_any(&self) -> &dyn std::any::Any {
407                    self
408                }
409
410                fn set_event_handler(
411                    &self,
412                    handler: Option<&$crate::objc2::runtime::ProtocolObject<dyn $crate::objc2_app_kit::NSWindowDelegate>>,
413                ) {
414                    unsafe {
415                        match handler {
416                            Some(h) => {
417                                // Store original delegate if this is the first time we're setting a custom one
418                                if self.event_handler.borrow().is_none() && self.original_delegate.get().is_none() {
419                                    if let Some(current_delegate) = unsafe { self.panel.delegate() } {
420                                        let _ = self.original_delegate.set(current_delegate);
421                                    }
422                                }
423
424                                // Store the retained handler
425                                let retained_handler = h.retain();
426                                *self.event_handler.borrow_mut() = Some(retained_handler);
427
428                                // Set as window delegate
429                                let _: () = $crate::objc2::msg_send![&*self.panel, setDelegate: h];
430                            }
431                            None => {
432                                if self.original_delegate.get().is_none() {
433                                    return;
434                                }
435
436                                // Clear stored handler (automatic cleanup when Option becomes None)
437                                *self.event_handler.borrow_mut() = None;
438
439                                // Restore original delegate
440                                if let Some(orig_delegate) = self.original_delegate.get() {
441                                    let _: () = $crate::objc2::msg_send![&*self.panel, setDelegate: &**orig_delegate];
442                                }
443                            }
444                        }
445                    }
446                }
447
448                // Query methods
449                fn is_visible(&self) -> bool {
450                    unsafe {
451                        $crate::objc2::msg_send![&*self.panel, isVisible]
452                    }
453                }
454
455                fn is_floating_panel(&self) -> bool {
456                    unsafe {
457                        $crate::objc2::msg_send![&*self.panel, isFloatingPanel]
458                    }
459                }
460
461                fn becomes_key_only_if_needed(&self) -> bool {
462                    unsafe {
463                        $crate::objc2::msg_send![&*self.panel, becomesKeyOnlyIfNeeded]
464                    }
465                }
466
467                fn can_become_key_window(&self) -> bool {
468                    unsafe {
469                        $crate::objc2::msg_send![&*self.panel, canBecomeKeyWindow]
470                    }
471                }
472
473                fn can_become_main_window(&self) -> bool {
474                    unsafe {
475                        $crate::objc2::msg_send![&*self.panel, canBecomeMainWindow]
476                    }
477                }
478
479                fn hides_on_deactivate(&self) -> bool {
480                    unsafe {
481                        $crate::objc2::msg_send![&*self.panel, hidesOnDeactivate]
482                    }
483                }
484
485                // Window state methods
486                fn make_key_window(&self) {
487                    unsafe {
488                        let _: () = $crate::objc2::msg_send![&*self.panel, makeKeyWindow];
489                    }
490                }
491
492                fn make_main_window(&self) {
493                    unsafe {
494                        let _: () = $crate::objc2::msg_send![&*self.panel, makeMainWindow];
495                    }
496                }
497
498                fn resign_key_window(&self) {
499                    unsafe {
500                        let _: () = $crate::objc2::msg_send![&*self.panel, resignKeyWindow];
501                    }
502                }
503
504                fn make_key_and_order_front(&self) {
505                    unsafe {
506                        let _: () = $crate::objc2::msg_send![&*self.panel, makeKeyAndOrderFront: $crate::objc2::ffi::nil];
507                    }
508                }
509
510                fn order_front_regardless(&self) {
511                    unsafe {
512                        let _: () = $crate::objc2::msg_send![&*self.panel, orderFrontRegardless];
513                    }
514                }
515
516                fn show_and_make_key(&self) {
517                    unsafe {
518                        let content_view: $crate::objc2::rc::Retained<$crate::objc2_app_kit::NSView> =
519                            $crate::objc2::msg_send![&*self.panel, contentView];
520                        let _: bool = $crate::objc2::msg_send![&*self.panel, makeFirstResponder: &*content_view];
521                        let _: () = $crate::objc2::msg_send![&*self.panel, orderFrontRegardless];
522                        let _: () = $crate::objc2::msg_send![&*self.panel, makeKeyWindow];
523                    }
524                }
525
526                // Configuration methods
527                fn set_level(&self, level: i64) {
528                    unsafe {
529                        let _: () = $crate::objc2::msg_send![&*self.panel, setLevel: level];
530                    }
531                }
532
533                fn set_floating_panel(&self, value: bool) {
534                    unsafe {
535                        let _: () = $crate::objc2::msg_send![&*self.panel, setFloatingPanel: value];
536                    }
537                }
538
539                fn set_becomes_key_only_if_needed(&self, value: bool) {
540                    unsafe {
541                        let _: () = $crate::objc2::msg_send![&*self.panel, setBecomesKeyOnlyIfNeeded: value];
542                    }
543                }
544
545                fn set_hides_on_deactivate(&self, value: bool) {
546                    unsafe {
547                        let _: () = $crate::objc2::msg_send![&*self.panel, setHidesOnDeactivate: value];
548                    }
549                }
550
551                fn set_works_when_modal(&self, value: bool) {
552                    unsafe {
553                        let _: () = $crate::objc2::msg_send![&*self.panel, setWorksWhenModal: value];
554                    }
555                }
556
557                fn set_alpha_value(&self, value: f64) {
558                    unsafe {
559                        let _: () = $crate::objc2::msg_send![&*self.panel, setAlphaValue: value];
560                    }
561                }
562
563                fn set_released_when_closed(&self, released: bool) {
564                    unsafe {
565                        let _: () = $crate::objc2::msg_send![&*self.panel, setReleasedWhenClosed: released];
566                    }
567                }
568
569                fn set_content_size(&self, width: f64, height: f64) {
570                    unsafe {
571                        let size = $crate::objc2_foundation::NSSize::new(width, height);
572                        let _: () = $crate::objc2::msg_send![&*self.panel, setContentSize: size];
573                    }
574                }
575
576                fn set_has_shadow(&self, value: bool) {
577                    unsafe {
578                        let _: () = $crate::objc2::msg_send![&*self.panel, setHasShadow: value];
579                    }
580                }
581
582                fn set_opaque(&self, value: bool) {
583                    unsafe {
584                        let _: () = $crate::objc2::msg_send![&*self.panel, setOpaque: value];
585                    }
586                }
587
588                fn set_accepts_mouse_moved_events(&self, value: bool) {
589                    unsafe {
590                        let _: () = $crate::objc2::msg_send![&*self.panel, setAcceptsMouseMovedEvents: value];
591                    }
592                }
593
594                fn set_ignores_mouse_events(&self, value: bool) {
595                    unsafe {
596                        let _: () = $crate::objc2::msg_send![&*self.panel, setIgnoresMouseEvents: value];
597                    }
598                }
599
600                fn set_movable_by_window_background(&self, value: bool) {
601                    unsafe {
602                        let _: () = $crate::objc2::msg_send![&*self.panel, setMovableByWindowBackground: value];
603                    }
604                }
605
606                fn set_collection_behavior(&self, behavior: $crate::objc2_app_kit::NSWindowCollectionBehavior) {
607                    unsafe {
608                        let _: () = $crate::objc2::msg_send![&*self.panel, setCollectionBehavior: behavior];
609                    }
610                }
611
612                fn content_view(&self) -> $crate::objc2::rc::Retained<$crate::objc2_app_kit::NSView> {
613                    unsafe {
614                        $crate::objc2::msg_send![&*self.panel, contentView]
615                    }
616                }
617
618                fn resign_main_window(&self) {
619                    unsafe {
620                        let _: () = $crate::objc2::msg_send![&*self.panel, resignMainWindow];
621                    }
622                }
623
624                fn set_style_mask(
625                    &self,
626                    style_mask: $crate::objc2_app_kit::NSWindowStyleMask,
627                ) -> Result<(), $crate::StyleMaskError> {
628                    $crate::catch_style_mask_exception(|| {
629                        unsafe {
630                            let _: () = $crate::objc2::msg_send![&*self.panel, setStyleMask: style_mask];
631
632                            // Class conversion skips NSPanel initialization, and setStyleMask:
633                            // does not synchronize WindowServer's activation-prevention tag.
634                            let selector = $crate::objc2::sel!(_setPreventsActivation:);
635                            let responds: bool = $crate::objc2::msg_send![&*self.panel, respondsToSelector: selector];
636                            if responds {
637                                let nonactivating = self.panel.styleMask().contains(
638                                    $crate::objc2_app_kit::NSWindowStyleMask::NonactivatingPanel,
639                                );
640                                let _: () = $crate::objc2::msg_send![&*self.panel, _setPreventsActivation: nonactivating];
641                            }
642                        }
643                    })
644                }
645
646                fn make_first_responder(&self, responder: Option<&$crate::objc2_app_kit::NSResponder>) -> bool {
647                    unsafe {
648                        let result: bool = match responder {
649                            Some(resp) => $crate::objc2::msg_send![&*self.panel, makeFirstResponder: resp],
650                            None => $crate::objc2::msg_send![&*self.panel, makeFirstResponder: $crate::objc2::ffi::nil],
651                        };
652                        result
653                    }
654                }
655
656                fn set_corner_radius(&self, radius: f64) {
657                    unsafe {
658                        let content_view: $crate::objc2::rc::Retained<$crate::objc2_app_kit::NSView> = $crate::objc2::msg_send![&*self.panel, contentView];
659                        let _: () = $crate::objc2::msg_send![&*content_view, setWantsLayer: true];
660                        let content_layer: $crate::objc2::rc::Retained<$crate::objc2_foundation::NSObject> = $crate::objc2::msg_send![&*content_view, layer];
661                        let _: () = $crate::objc2::msg_send![&*content_layer, setCornerRadius: radius];
662                    }
663                }
664
665                fn set_transparent(&self, transparent: bool) {
666                    unsafe {
667                        if transparent {
668                            let clear_color: $crate::objc2::rc::Retained<$crate::objc2_foundation::NSObject> = $crate::objc2::msg_send![$crate::objc2::class!(NSColor), clearColor];
669                            let _: () = $crate::objc2::msg_send![&*self.panel, setBackgroundColor: &*clear_color];
670                            let _: () = $crate::objc2::msg_send![&*self.panel, setOpaque: false];
671                        } else {
672                            let default_color: $crate::objc2::rc::Retained<$crate::objc2_foundation::NSObject> = $crate::objc2::msg_send![$crate::objc2::class!(NSColor), windowBackgroundColor];
673                            let _: () = $crate::objc2::msg_send![&*self.panel, setBackgroundColor: &*default_color];
674                            let _: () = $crate::objc2::msg_send![&*self.panel, setOpaque: true];
675                        }
676                    }
677                }
678
679            }
680
681            // Implement FromWindow trait
682            impl<R: tauri::Runtime> $crate::FromWindow<R> for $class_name<R> {
683                fn from_window(window: tauri::WebviewWindow<R>, label: String) -> tauri::Result<Self> {
684                    let ns_window = window.ns_window().map_err(|e| {
685                        tauri::Error::Io(std::io::Error::new(
686                            std::io::ErrorKind::Other,
687                            format!("Failed to get NSWindow: {:?}", e),
688                        ))
689                    })?;
690
691                    unsafe {
692                        unsafe extern "C" {
693                            fn object_setClass(
694                                obj: *mut $crate::objc2_foundation::NSObject,
695                                cls: *const $crate::objc2::runtime::AnyClass,
696                            ) -> *const $crate::objc2::runtime::AnyClass;
697
698                            fn object_getClass(
699                                obj: *mut $crate::objc2_foundation::NSObject,
700                            ) -> *const $crate::objc2::runtime::AnyClass;
701                        }
702
703                        let original_class = object_getClass(ns_window as *mut $crate::objc2_foundation::NSObject);
704
705                        // Change the window class to our custom panel class
706                        object_setClass(
707                            ns_window as *mut $crate::objc2_foundation::NSObject,
708                            [<Raw $class_name>]::class(),
709                        );
710
711                        // Now cast to our panel type
712                        let panel_ptr = ns_window as *mut [<Raw $class_name>];
713
714                        // Create a Retained from the raw pointer
715                        let panel = $crate::objc2::rc::Retained::retain(panel_ptr).ok_or_else(|| {
716                            tauri::Error::Io(std::io::Error::new(
717                                std::io::ErrorKind::Other,
718                                "Failed to retain panel",
719                            ))
720                        })?;
721
722                        // Apply instance properties with class-level config after swizzling
723                        // Only for properties that have setter methods available
724                        $($(
725                            Self::apply_instance_property(&panel, stringify!($method), $value);
726                        )*)?
727
728                        // Add tracking area if configured
729                        $($(
730                            Self::add_tracking_area(&panel, $tracking_options, $auto_resize);
731                        )?)?
732
733                        // Enable auto-resizing for all subviews
734                        let content_view: $crate::objc2::rc::Retained<$crate::objc2_app_kit::NSView> =
735                            $crate::objc2::msg_send![&panel, contentView];
736                        $crate::panel::install_text_input_client_window_level(&content_view);
737                        let subviews: $crate::objc2::rc::Retained<$crate::objc2_foundation::NSArray<$crate::objc2_app_kit::NSView>> =
738                            $crate::objc2::msg_send![&content_view, subviews];
739                        let count: usize = $crate::objc2::msg_send![&subviews, count];
740
741                        let resize_mask = $crate::objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable
742                            | $crate::objc2_app_kit::NSAutoresizingMaskOptions::ViewHeightSizable;
743
744                        for i in 0..count {
745                            let view: $crate::objc2::rc::Retained<$crate::objc2_app_kit::NSView> =
746                                $crate::objc2::msg_send![&subviews, objectAtIndex: i];
747                            let _: () = $crate::objc2::msg_send![&view, setAutoresizingMask: resize_mask];
748                        }
749
750                        Ok($class_name::with_label(
751                            panel,
752                            label,
753                            original_class,
754                            tauri::Manager::app_handle(&window).clone(),
755                        ))
756                    }
757                }
758            }
759
760            // Helper methods
761            impl<R: tauri::Runtime> $class_name<R> where $class_name<R>: $crate::Panel<R> {
762                #[allow(unused)]
763                fn apply_instance_property(panel: &$crate::objc2_app_kit::NSPanel, method: &str, value: bool) {
764                    unsafe {
765                        match method {
766                            "hides_on_deactivate" | "hidesOnDeactivate" => {
767                                let _: () = $crate::objc2::msg_send![panel, setHidesOnDeactivate: value];
768                            },
769                            "becomes_key_only_if_needed" | "becomesKeyOnlyIfNeeded" => {
770                                let _: () = $crate::objc2::msg_send![panel, setBecomesKeyOnlyIfNeeded: value];
771                            },
772                            "works_when_modal" | "worksWhenModal" => {
773                                let _: () = $crate::objc2::msg_send![panel, setWorksWhenModal: value];
774                            },
775                            "is_floating_panel" | "isFloatingPanel" => {
776                                let _: () = $crate::objc2::msg_send![panel, setFloatingPanel: value];
777                            },
778                            // Properties like can_become_key_window, can_become_main_window don't have setters
779                            // They are read-only and only affect behavior through method overrides
780                            _ => {
781                                // Skip properties without setters
782                            }
783                        }
784                    }
785                }
786
787                #[allow(unused)]
788                fn add_tracking_area(panel: &$crate::objc2_app_kit::NSPanel, options: impl Into<$crate::objc2_app_kit::NSTrackingAreaOptions>, auto_resize: bool) {
789                    unsafe {
790                        let content_view: $crate::objc2::rc::Retained<$crate::objc2_app_kit::NSView> =
791                            $crate::objc2::msg_send![panel, contentView];
792                        let bounds: $crate::objc2_foundation::NSRect =
793                            $crate::objc2::msg_send![&content_view, bounds];
794                        let options = $crate::panel::resolve_tracking_area_options(
795                            options.into(),
796                            auto_resize,
797                        );
798
799                        // Create tracking area
800                        let tracking_area: $crate::objc2::rc::Retained<$crate::objc2_app_kit::NSTrackingArea> = {
801                            let alloc: *mut $crate::objc2_app_kit::NSTrackingArea = $crate::objc2::msg_send![
802                                $crate::objc2_app_kit::NSTrackingArea::class(),
803                                alloc
804                            ];
805                            let area: *mut $crate::objc2_app_kit::NSTrackingArea = $crate::objc2::msg_send![
806                                alloc,
807                                initWithRect: bounds,
808                                options: options,
809                                owner: &*content_view,
810                                userInfo: $crate::objc2::ffi::nil
811                            ];
812                            $crate::objc2::rc::Retained::from_raw(area).unwrap()
813                        };
814
815                        // Add tracking area
816                        let _: () = $crate::objc2::msg_send![&content_view, addTrackingArea: &*tracking_area];
817                    }
818                }
819            }
820        }
821    };
822}
823
824#[cfg(test)]
825mod tests {
826    use std::ffi::CStr;
827    use std::sync::OnceLock;
828
829    use objc2::{runtime::ClassBuilder, ClassType};
830    use objc2_app_kit::{NSTrackingAreaOptions, NSView};
831
832    use super::{
833        install_window_level_method, resolve_tracking_area_options, stable_text_input_client_class,
834    };
835
836    #[test]
837    fn auto_resize_tracks_the_visible_view_rect() {
838        let base = NSTrackingAreaOptions::ActiveAlways
839            | NSTrackingAreaOptions::MouseEnteredAndExited
840            | NSTrackingAreaOptions::MouseMoved;
841
842        let options = resolve_tracking_area_options(base, true);
843
844        assert!(options.contains(NSTrackingAreaOptions::InVisibleRect));
845        assert!(options.contains(base));
846    }
847
848    #[test]
849    fn fixed_tracking_area_preserves_the_requested_options() {
850        let base = NSTrackingAreaOptions::ActiveAlways
851            | NSTrackingAreaOptions::MouseEnteredAndExited
852            | NSTrackingAreaOptions::MouseMoved;
853
854        assert_eq!(resolve_tracking_area_options(base, false), base);
855    }
856
857    #[test]
858    fn window_level_method_is_installed_once() {
859        static CLASS: OnceLock<&'static objc2::runtime::AnyClass> = OnceLock::new();
860        let class = CLASS.get_or_init(|| {
861            let name = CStr::from_bytes_with_nul(b"TauriNSPanelTextInputClientTest\0")
862                .expect("test class name must be NUL-terminated");
863            ClassBuilder::new(name, NSView::class())
864                .expect("test class should only be registered once")
865                .register()
866        });
867
868        assert!(install_window_level_method(class));
869        assert!(class.instance_method(objc2::sel!(windowLevel)).is_some());
870        assert!(!install_window_level_method(class));
871    }
872
873    #[test]
874    fn window_level_method_targets_the_stable_webview_subclass() {
875        static CLASSES: OnceLock<(
876            &'static objc2::runtime::AnyClass,
877            &'static objc2::runtime::AnyClass,
878        )> = OnceLock::new();
879        let (webview, notifying_webview) = CLASSES.get_or_init(|| {
880            let wk_webview_name = CStr::from_bytes_with_nul(b"WKWebView\0").unwrap();
881            let wk_webview = objc2::runtime::AnyClass::get(wk_webview_name)
882                .expect("WebKit should be loaded by Tauri");
883            let webview_name =
884                CStr::from_bytes_with_nul(b"TauriNSPanelStableWebViewTest\0").unwrap();
885            let webview = ClassBuilder::new(webview_name, wk_webview)
886                .expect("stable test webview class should only be registered once")
887                .register();
888            let notifying_name =
889                CStr::from_bytes_with_nul(b"TauriNSPanelNotifyingWebViewTest\0").unwrap();
890            let notifying_webview = ClassBuilder::new(notifying_name, webview)
891                .expect("notifying test webview class should only be registered once")
892                .register();
893
894            (webview, notifying_webview)
895        });
896
897        assert_eq!(stable_text_input_client_class(notifying_webview), *webview);
898    }
899}