tauri-nspanel 2.1.0

A plugin for subclassing Tauri's NSWindow to NSPanel
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
// Re-export commonly used types
pub use objc2_app_kit::{
    NSAutoresizingMaskOptions, NSTrackingAreaOptions, NSWindowCollectionBehavior, NSWindowStyleMask,
};

#[doc(hidden)]
pub fn resolve_tracking_area_options(
    mut options: objc2_app_kit::NSTrackingAreaOptions,
    auto_resize: bool,
) -> objc2_app_kit::NSTrackingAreaOptions {
    if auto_resize {
        options |= objc2_app_kit::NSTrackingAreaOptions::InVisibleRect;
    }

    options
}

/// Teach elevated WebKit text input clients to report their containing window's level.
///
/// AppKit uses the optional `NSTextInputClient::windowLevel` method to place input-method UI
/// above text clients whose windows are higher than `NSFloatingWindowLevel`. `WKWebView` does
/// not currently implement that method, so candidate windows can otherwise appear behind an
/// elevated panel.
#[doc(hidden)]
pub fn install_text_input_client_window_level(root: &objc2_app_kit::NSView) {
    use std::ffi::CStr;

    use objc2::runtime::AnyProtocol;

    let protocol_name = CStr::from_bytes_with_nul(b"NSTextInputClient\0")
        .expect("NSTextInputClient protocol name must be NUL-terminated");
    let Some(text_input_client) = AnyProtocol::get(protocol_name) else {
        return;
    };

    install_text_input_client_window_level_in_subtree(root, text_input_client);
}

fn install_text_input_client_window_level_in_subtree(
    root: &objc2_app_kit::NSView,
    text_input_client: &objc2::runtime::AnyProtocol,
) {
    use objc2_foundation::NSObjectProtocol;

    if root.conformsToProtocol(text_input_client) {
        let _ = install_window_level_method(stable_text_input_client_class(root.class()));
    }

    let subviews = root.subviews();
    for subview in subviews.iter() {
        install_text_input_client_window_level_in_subtree(&subview, text_input_client);
    }
}

fn stable_text_input_client_class(
    runtime_class: &objc2::runtime::AnyClass,
) -> &objc2::runtime::AnyClass {
    let mut candidate = runtime_class;

    while let Some(superclass) = candidate.superclass() {
        if superclass.name().to_bytes() == b"WKWebView" {
            return candidate;
        }
        candidate = superclass;
    }

    runtime_class
}

fn install_window_level_method(class: &objc2::runtime::AnyClass) -> bool {
    use objc2::runtime::{Imp, Sel};

    let selector = objc2::sel!(windowLevel);
    if class.instance_method(selector).is_some() {
        return false;
    }

    unsafe extern "C-unwind" fn window_level(
        view: &objc2_app_kit::NSView,
        _selector: Sel,
    ) -> objc2::ffi::NSInteger {
        view.window().map_or(0, |window| window.level())
    }

    let implementation: unsafe extern "C-unwind" fn(
        &objc2_app_kit::NSView,
        Sel,
    ) -> objc2::ffi::NSInteger = window_level;

    // SAFETY: Objective-C method implementations erase their concrete function signature to
    // `Imp`. The `q@:` encoding below matches `(id, SEL) -> NSInteger` on 64-bit macOS.
    let implementation: Imp = unsafe { std::mem::transmute(implementation) };
    let type_encoding = b"q@:\0";

    // SAFETY: `class` is a registered Objective-C class, the selector has no explicit arguments,
    // and the implementation and type encoding agree. Adding a method is safe for the lifetime of
    // the process because Objective-C classes are never deallocated.
    unsafe {
        objc2::ffi::class_addMethod(
            class as *const _ as *mut _,
            selector,
            implementation,
            type_encoding.as_ptr().cast(),
        )
        .as_bool()
    }
}

/// Macro to create a custom NSPanel class
///
/// This macro generates a custom NSPanel subclass with the specified configuration.
/// The first parameter is the name of your custom panel class.
///
/// **Implementation Details**:
/// - The macro generates an internal `Raw{ClassName}` Objective-C class
/// - A public `{ClassName}` wrapper type that implements `Send` and `Sync`
/// - All methods are implemented on the wrapper type
///
/// **Thread Safety**: The wrapper type implements `Send` and `Sync` to allow
/// passing references through Tauri's command system. However, all actual panel
/// operations must be performed on the main thread.
///
/// ## Sections:
/// - `config`: Override NSPanel methods that return boolean values (use snake_case names)
/// - `with`: Optional configurations (tracking_area, etc.)
///
/// ## Mouse Tracking:
/// When you enable tracking_area in the `with` section, mouse event callbacks become available
/// on your event handler. You can set callbacks for:
/// - `on_mouse_entered()` - Called when mouse enters the panel
/// - `on_mouse_exited()` - Called when mouse exits the panel
/// - `on_mouse_moved()` - Called when mouse moves within the panel
/// - `on_cursor_update()` - Called when cursor needs to be updated
///
/// ## Usage:
/// ```no_run
/// use tauri_nspanel::{tauri_panel, Panel, TrackingAreaOptions};
///
/// tauri_panel! {
///     panel!(MyCustomPanel {
///         config: {
///             can_become_key_window: true,
///             can_become_main_window: false
///         }
///         with: {
///             tracking_area: {
///                 options: TrackingAreaOptions::new()
///                     .active_always()
///                     .mouse_entered_and_exited()
///                     .mouse_moved(),
///                 auto_resize: true
///             }
///         }
///     })
///
///     panel_event!(MyPanelEventHandler {
///         window_did_become_key(notification: &NSNotification) -> ()
///     })
/// }
///
/// // In your Tauri app:
/// fn create_panel(window: &tauri::WebviewWindow) -> tauri::Result<()> {
///     // Convert existing Tauri window to your custom panel
///     let panel = MyCustomPanel::from_window(window)?;
///
///     // Use control methods
///     panel.show();
///     panel.set_level(5i64); // NSStatusWindowLevel
///     panel.set_floating_panel(true);
///
///     // Create and attach an event handler
///     let handler = MyPanelEventHandler::new();
///     handler.window_did_become_key(|_notification| {
///         println!("Panel became key window");
///     });
///
///     // If tracking_area is enabled, you can set mouse event callbacks
///     handler.on_mouse_entered(|_event| {
///         println!("Mouse entered the panel");
///     });
///
///     handler.on_mouse_moved(|event| {
///         let location = event.locationInWindow();
///         println!("Mouse moved to: x={}, y={}", location.x, location.y);
///     });
///
///     panel.set_event_handler(Some(handler.as_ref()));
///
///     Ok(())
/// }
/// ```
///
/// ## Available Methods:
/// - `show()`, `hide()`, `to_window()`
/// - `make_key_window()`, `resign_key_window()`
/// - `set_level()`, `set_alpha_value()`, `set_content_size()`
/// - `set_floating_panel()`, `set_has_shadow()`, `set_opaque()`
/// - `set_accepts_mouse_moved_events()`, `set_ignores_mouse_events()`
/// - And many more...
#[macro_export]
macro_rules! panel {
    (
        $class_name:ident {
            $(config: {
                $($method:ident: $value:expr),* $(,)?
            })?
            $(with: {
                $(tracking_area: {
                    options: $tracking_options:expr,
                    auto_resize: $auto_resize:expr $(,)?
                })?
            })?
        }
    ) => {
        $crate::pastey::paste! {
            struct [<$class_name Ivars>];

            $crate::objc2::define_class!(
                #[unsafe(super = $crate::objc2_app_kit::NSPanel)]
                #[name = stringify!($class_name)]
                #[ivars = [<$class_name Ivars>]]

                struct [<Raw $class_name>];

                unsafe impl NSObjectProtocol for [<Raw $class_name>] {}

                impl [<Raw $class_name>] {
                    $($(
                        #[doc = concat!(" Returns whether panels of this class ", stringify!([<$method:lower_camel>]))]
                        #[unsafe(method([<$method:lower_camel>]))]
                        fn [<__ $method:snake>]() -> bool {
                            $value
                        }

                        #[doc = concat!(" Returns whether this specific panel instance ", stringify!([<$method:lower_camel>]))]
                        #[unsafe(method([<$method:lower_camel>]))]
                        fn [<__ $method:snake _instance>](&self) -> bool {
                            $value
                        }
                    )*)?

                    // Mouse tracking methods - forward to delegate if set
                    #[unsafe(method(mouseEntered:))]
                    fn __mouse_entered(&self, event: &$crate::objc2_app_kit::NSEvent) {
                        unsafe {
                            // Get the delegate directly from the window
                            let delegate: Option<$crate::objc2::rc::Retained<$crate::objc2::runtime::ProtocolObject<dyn $crate::objc2_app_kit::NSWindowDelegate>>> = $crate::objc2::msg_send![self, delegate];
                            if let Some(ref d) = delegate {
                                // Check if delegate responds to selector before calling
                                let selector = $crate::objc2::sel!(mouseEntered:);
                                let responds: bool = $crate::objc2::msg_send![&**d, respondsToSelector: selector];
                                if responds {
                                    let _: () = $crate::objc2::msg_send![&**d, mouseEntered: event];
                                }
                            }
                        }
                    }

                    #[unsafe(method(mouseExited:))]
                    fn __mouse_exited(&self, event: &$crate::objc2_app_kit::NSEvent) {
                        unsafe {
                            // Get the delegate directly from the window
                            let delegate: Option<$crate::objc2::rc::Retained<$crate::objc2::runtime::ProtocolObject<dyn $crate::objc2_app_kit::NSWindowDelegate>>> = $crate::objc2::msg_send![self, delegate];
                            if let Some(ref d) = delegate {
                                // Check if delegate responds to selector before calling
                                let selector = $crate::objc2::sel!(mouseExited:);
                                let responds: bool = $crate::objc2::msg_send![&**d, respondsToSelector: selector];
                                if responds {
                                    let _: () = $crate::objc2::msg_send![&**d, mouseExited: event];
                                }
                            }
                        }
                    }

                    #[unsafe(method(mouseMoved:))]
                    fn __mouse_moved(&self, event: &$crate::objc2_app_kit::NSEvent) {
                        unsafe {
                            // Get the delegate directly from the window
                            let delegate: Option<$crate::objc2::rc::Retained<$crate::objc2::runtime::ProtocolObject<dyn $crate::objc2_app_kit::NSWindowDelegate>>> = $crate::objc2::msg_send![self, delegate];
                            if let Some(ref d) = delegate {
                                // Check if delegate responds to selector before calling
                                let selector = $crate::objc2::sel!(mouseMoved:);
                                let responds: bool = $crate::objc2::msg_send![&**d, respondsToSelector: selector];
                                if responds {
                                    let _: () = $crate::objc2::msg_send![&**d, mouseMoved: event];
                                }
                            }
                        }
                    }

                    #[unsafe(method(cursorUpdate:))]
                    fn __cursor_update(&self, event: &$crate::objc2_app_kit::NSEvent) {
                        unsafe {
                            // Get the delegate directly from the window
                            let delegate: Option<$crate::objc2::rc::Retained<$crate::objc2::runtime::ProtocolObject<dyn $crate::objc2_app_kit::NSWindowDelegate>>> = $crate::objc2::msg_send![self, delegate];
                            if let Some(ref d) = delegate {
                                // Check if delegate responds to selector before calling
                                let selector = $crate::objc2::sel!(cursorUpdate:);
                                let responds: bool = $crate::objc2::msg_send![&**d, respondsToSelector: selector];
                                if responds {
                                    let _: () = $crate::objc2::msg_send![&**d, cursorUpdate: event];
                                }
                            }
                        }
                    }
                }
            );

            #[doc = " A public wrapper for `Raw" $class_name "` "]
            pub struct $class_name<R: tauri::Runtime = tauri::Wry> {
                panel: $crate::objc2::rc::Retained<[<Raw $class_name>]>,
                label: String,
                original_class: *const $crate::objc2::runtime::AnyClass,
                original_delegate: std::cell::OnceCell<$crate::objc2::rc::Retained<$crate::objc2::runtime::ProtocolObject<dyn $crate::objc2_app_kit::NSWindowDelegate>>>,
                app_handle: tauri::AppHandle<R>,
                event_handler: std::cell::RefCell<Option<$crate::objc2::rc::Retained<$crate::objc2::runtime::ProtocolObject<dyn $crate::objc2_app_kit::NSWindowDelegate>>>>,
            }

            // SAFETY: While NSPanel must only be used on the main thread, we implement Send + Sync
            // to allow passing references through Tauri's command system. Users must ensure
            // actual panel operations happen on the main thread.
            unsafe impl<R: tauri::Runtime> Send for $class_name<R> {}
            unsafe impl<R: tauri::Runtime> Sync for $class_name<R> {}

            impl<R: tauri::Runtime> $class_name<R> where $class_name<R>: $crate::Panel<R> {
                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 {
                    Self {
                        panel,
                        label,
                        original_class,
                        original_delegate: std::cell::OnceCell::new(),
                        app_handle,
                        event_handler: std::cell::RefCell::new(None),
                    }
                }

                /// Convert a Tauri window to this panel type (convenience method)
                pub fn from_window(window: &tauri::WebviewWindow<R>) -> tauri::Result<Self> {
                    let label = window.label().to_string();
                    <Self as $crate::FromWindow<R>>::from_window(window.clone(), label)
                }

            }

            // Implement Panel trait
            impl<R: tauri::Runtime> $crate::Panel<R> for $class_name<R> {
                fn show(&self) {
                    unsafe {
                        let _: () = $crate::objc2::msg_send![&*self.panel, orderFrontRegardless];
                    }
                }

                fn hide(&self) {
                    unsafe {
                        let _: () = $crate::objc2::msg_send![&*self.panel, orderOut: $crate::objc2::ffi::nil];
                    }
                }

                /// Convert panel back to a regular Tauri window
                fn to_window(&self) -> Option<tauri::WebviewWindow<R>> {
                    use tauri::Manager;
                    use $crate::ManagerExt;

                    unsafe extern "C" {
                        fn object_setClass(
                            obj: *mut $crate::objc2_foundation::NSObject,
                            cls: *const $crate::objc2::runtime::AnyClass,
                        ) -> *const $crate::objc2::runtime::AnyClass;
                    }

                    if let Some(_) = self.app_handle.remove_webview_panel(self.label.as_str()) {
                        self.set_event_handler(None);
                        // Tauri/Tao retains the native window and releases it during close.
                        // AppKit must not release the same window independently.
                        self.set_released_when_closed(false);

                        unsafe {
                            let target_class = if !self.original_class.is_null() {
                                self.original_class
                            } else {
                                $crate::objc2_app_kit::NSWindow::class()
                            };

                            object_setClass(
                                &*self.panel as *const [<Raw $class_name>] as *mut $crate::objc2_foundation::NSObject,
                                target_class,
                            );
                        }

                        self.app_handle.get_webview_window(&self.label)
                    } else {
                        None
                    }
                }

                fn as_panel(&self) -> &$crate::objc2_app_kit::NSPanel {
                    // SAFETY: Raw class inherits from NSPanel
                    unsafe { &*(&*self.panel as *const [<Raw $class_name>] as *const $crate::objc2_app_kit::NSPanel) }
                    // Cast the retained Raw panel to NSPanel reference
                }

                fn label(&self) -> &str {
                    &self.label
                }

                fn as_any(&self) -> &dyn std::any::Any {
                    self
                }

                fn set_event_handler(
                    &self,
                    handler: Option<&$crate::objc2::runtime::ProtocolObject<dyn $crate::objc2_app_kit::NSWindowDelegate>>,
                ) {
                    unsafe {
                        match handler {
                            Some(h) => {
                                // Store original delegate if this is the first time we're setting a custom one
                                if self.event_handler.borrow().is_none() && self.original_delegate.get().is_none() {
                                    if let Some(current_delegate) = unsafe { self.panel.delegate() } {
                                        let _ = self.original_delegate.set(current_delegate);
                                    }
                                }

                                // Store the retained handler
                                let retained_handler = h.retain();
                                *self.event_handler.borrow_mut() = Some(retained_handler);

                                // Set as window delegate
                                let _: () = $crate::objc2::msg_send![&*self.panel, setDelegate: h];
                            }
                            None => {
                                if self.original_delegate.get().is_none() {
                                    return;
                                }

                                // Clear stored handler (automatic cleanup when Option becomes None)
                                *self.event_handler.borrow_mut() = None;

                                // Restore original delegate
                                if let Some(orig_delegate) = self.original_delegate.get() {
                                    let _: () = $crate::objc2::msg_send![&*self.panel, setDelegate: &**orig_delegate];
                                }
                            }
                        }
                    }
                }

                // Query methods
                fn is_visible(&self) -> bool {
                    unsafe {
                        $crate::objc2::msg_send![&*self.panel, isVisible]
                    }
                }

                fn is_floating_panel(&self) -> bool {
                    unsafe {
                        $crate::objc2::msg_send![&*self.panel, isFloatingPanel]
                    }
                }

                fn becomes_key_only_if_needed(&self) -> bool {
                    unsafe {
                        $crate::objc2::msg_send![&*self.panel, becomesKeyOnlyIfNeeded]
                    }
                }

                fn can_become_key_window(&self) -> bool {
                    unsafe {
                        $crate::objc2::msg_send![&*self.panel, canBecomeKeyWindow]
                    }
                }

                fn can_become_main_window(&self) -> bool {
                    unsafe {
                        $crate::objc2::msg_send![&*self.panel, canBecomeMainWindow]
                    }
                }

                fn hides_on_deactivate(&self) -> bool {
                    unsafe {
                        $crate::objc2::msg_send![&*self.panel, hidesOnDeactivate]
                    }
                }

                // Window state methods
                fn make_key_window(&self) {
                    unsafe {
                        let _: () = $crate::objc2::msg_send![&*self.panel, makeKeyWindow];
                    }
                }

                fn make_main_window(&self) {
                    unsafe {
                        let _: () = $crate::objc2::msg_send![&*self.panel, makeMainWindow];
                    }
                }

                fn resign_key_window(&self) {
                    unsafe {
                        let _: () = $crate::objc2::msg_send![&*self.panel, resignKeyWindow];
                    }
                }

                fn make_key_and_order_front(&self) {
                    unsafe {
                        let _: () = $crate::objc2::msg_send![&*self.panel, makeKeyAndOrderFront: $crate::objc2::ffi::nil];
                    }
                }

                fn order_front_regardless(&self) {
                    unsafe {
                        let _: () = $crate::objc2::msg_send![&*self.panel, orderFrontRegardless];
                    }
                }

                fn show_and_make_key(&self) {
                    unsafe {
                        let content_view: $crate::objc2::rc::Retained<$crate::objc2_app_kit::NSView> =
                            $crate::objc2::msg_send![&*self.panel, contentView];
                        let _: bool = $crate::objc2::msg_send![&*self.panel, makeFirstResponder: &*content_view];
                        let _: () = $crate::objc2::msg_send![&*self.panel, orderFrontRegardless];
                        let _: () = $crate::objc2::msg_send![&*self.panel, makeKeyWindow];
                    }
                }

                // Configuration methods
                fn set_level(&self, level: i64) {
                    unsafe {
                        let _: () = $crate::objc2::msg_send![&*self.panel, setLevel: level];
                    }
                }

                fn set_floating_panel(&self, value: bool) {
                    unsafe {
                        let _: () = $crate::objc2::msg_send![&*self.panel, setFloatingPanel: value];
                    }
                }

                fn set_becomes_key_only_if_needed(&self, value: bool) {
                    unsafe {
                        let _: () = $crate::objc2::msg_send![&*self.panel, setBecomesKeyOnlyIfNeeded: value];
                    }
                }

                fn set_hides_on_deactivate(&self, value: bool) {
                    unsafe {
                        let _: () = $crate::objc2::msg_send![&*self.panel, setHidesOnDeactivate: value];
                    }
                }

                fn set_works_when_modal(&self, value: bool) {
                    unsafe {
                        let _: () = $crate::objc2::msg_send![&*self.panel, setWorksWhenModal: value];
                    }
                }

                fn set_alpha_value(&self, value: f64) {
                    unsafe {
                        let _: () = $crate::objc2::msg_send![&*self.panel, setAlphaValue: value];
                    }
                }

                fn set_released_when_closed(&self, released: bool) {
                    unsafe {
                        let _: () = $crate::objc2::msg_send![&*self.panel, setReleasedWhenClosed: released];
                    }
                }

                fn set_content_size(&self, width: f64, height: f64) {
                    unsafe {
                        let size = $crate::objc2_foundation::NSSize::new(width, height);
                        let _: () = $crate::objc2::msg_send![&*self.panel, setContentSize: size];
                    }
                }

                fn set_has_shadow(&self, value: bool) {
                    unsafe {
                        let _: () = $crate::objc2::msg_send![&*self.panel, setHasShadow: value];
                    }
                }

                fn set_opaque(&self, value: bool) {
                    unsafe {
                        let _: () = $crate::objc2::msg_send![&*self.panel, setOpaque: value];
                    }
                }

                fn set_accepts_mouse_moved_events(&self, value: bool) {
                    unsafe {
                        let _: () = $crate::objc2::msg_send![&*self.panel, setAcceptsMouseMovedEvents: value];
                    }
                }

                fn set_ignores_mouse_events(&self, value: bool) {
                    unsafe {
                        let _: () = $crate::objc2::msg_send![&*self.panel, setIgnoresMouseEvents: value];
                    }
                }

                fn set_movable_by_window_background(&self, value: bool) {
                    unsafe {
                        let _: () = $crate::objc2::msg_send![&*self.panel, setMovableByWindowBackground: value];
                    }
                }

                fn set_collection_behavior(&self, behavior: $crate::objc2_app_kit::NSWindowCollectionBehavior) {
                    unsafe {
                        let _: () = $crate::objc2::msg_send![&*self.panel, setCollectionBehavior: behavior];
                    }
                }

                fn content_view(&self) -> $crate::objc2::rc::Retained<$crate::objc2_app_kit::NSView> {
                    unsafe {
                        $crate::objc2::msg_send![&*self.panel, contentView]
                    }
                }

                fn resign_main_window(&self) {
                    unsafe {
                        let _: () = $crate::objc2::msg_send![&*self.panel, resignMainWindow];
                    }
                }

                fn set_style_mask(
                    &self,
                    style_mask: $crate::objc2_app_kit::NSWindowStyleMask,
                ) -> Result<(), $crate::StyleMaskError> {
                    $crate::catch_style_mask_exception(|| {
                        unsafe {
                            let _: () = $crate::objc2::msg_send![&*self.panel, setStyleMask: style_mask];
                        }
                    })
                }

                fn make_first_responder(&self, responder: Option<&$crate::objc2_app_kit::NSResponder>) -> bool {
                    unsafe {
                        let result: bool = match responder {
                            Some(resp) => $crate::objc2::msg_send![&*self.panel, makeFirstResponder: resp],
                            None => $crate::objc2::msg_send![&*self.panel, makeFirstResponder: $crate::objc2::ffi::nil],
                        };
                        result
                    }
                }

                fn set_corner_radius(&self, radius: f64) {
                    unsafe {
                        let content_view: $crate::objc2::rc::Retained<$crate::objc2_app_kit::NSView> = $crate::objc2::msg_send![&*self.panel, contentView];
                        let _: () = $crate::objc2::msg_send![&*content_view, setWantsLayer: true];
                        let content_layer: $crate::objc2::rc::Retained<$crate::objc2_foundation::NSObject> = $crate::objc2::msg_send![&*content_view, layer];
                        let _: () = $crate::objc2::msg_send![&*content_layer, setCornerRadius: radius];
                    }
                }

                fn set_transparent(&self, transparent: bool) {
                    unsafe {
                        if transparent {
                            let clear_color: $crate::objc2::rc::Retained<$crate::objc2_foundation::NSObject> = $crate::objc2::msg_send![$crate::objc2::class!(NSColor), clearColor];
                            let _: () = $crate::objc2::msg_send![&*self.panel, setBackgroundColor: &*clear_color];
                            let _: () = $crate::objc2::msg_send![&*self.panel, setOpaque: false];
                        } else {
                            let default_color: $crate::objc2::rc::Retained<$crate::objc2_foundation::NSObject> = $crate::objc2::msg_send![$crate::objc2::class!(NSColor), windowBackgroundColor];
                            let _: () = $crate::objc2::msg_send![&*self.panel, setBackgroundColor: &*default_color];
                            let _: () = $crate::objc2::msg_send![&*self.panel, setOpaque: true];
                        }
                    }
                }

            }

            // Implement FromWindow trait
            impl<R: tauri::Runtime> $crate::FromWindow<R> for $class_name<R> {
                fn from_window(window: tauri::WebviewWindow<R>, label: String) -> tauri::Result<Self> {
                    let ns_window = window.ns_window().map_err(|e| {
                        tauri::Error::Io(std::io::Error::new(
                            std::io::ErrorKind::Other,
                            format!("Failed to get NSWindow: {:?}", e),
                        ))
                    })?;

                    unsafe {
                        unsafe extern "C" {
                            fn object_setClass(
                                obj: *mut $crate::objc2_foundation::NSObject,
                                cls: *const $crate::objc2::runtime::AnyClass,
                            ) -> *const $crate::objc2::runtime::AnyClass;

                            fn object_getClass(
                                obj: *mut $crate::objc2_foundation::NSObject,
                            ) -> *const $crate::objc2::runtime::AnyClass;
                        }

                        let original_class = object_getClass(ns_window as *mut $crate::objc2_foundation::NSObject);

                        // Change the window class to our custom panel class
                        object_setClass(
                            ns_window as *mut $crate::objc2_foundation::NSObject,
                            [<Raw $class_name>]::class(),
                        );

                        // Now cast to our panel type
                        let panel_ptr = ns_window as *mut [<Raw $class_name>];

                        // Create a Retained from the raw pointer
                        let panel = $crate::objc2::rc::Retained::retain(panel_ptr).ok_or_else(|| {
                            tauri::Error::Io(std::io::Error::new(
                                std::io::ErrorKind::Other,
                                "Failed to retain panel",
                            ))
                        })?;

                        // Apply instance properties with class-level config after swizzling
                        // Only for properties that have setter methods available
                        $($(
                            Self::apply_instance_property(&panel, stringify!($method), $value);
                        )*)?

                        // Add tracking area if configured
                        $($(
                            Self::add_tracking_area(&panel, $tracking_options, $auto_resize);
                        )?)?

                        // Enable auto-resizing for all subviews
                        let content_view: $crate::objc2::rc::Retained<$crate::objc2_app_kit::NSView> =
                            $crate::objc2::msg_send![&panel, contentView];
                        $crate::panel::install_text_input_client_window_level(&content_view);
                        let subviews: $crate::objc2::rc::Retained<$crate::objc2_foundation::NSArray<$crate::objc2_app_kit::NSView>> =
                            $crate::objc2::msg_send![&content_view, subviews];
                        let count: usize = $crate::objc2::msg_send![&subviews, count];

                        let resize_mask = $crate::objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable
                            | $crate::objc2_app_kit::NSAutoresizingMaskOptions::ViewHeightSizable;

                        for i in 0..count {
                            let view: $crate::objc2::rc::Retained<$crate::objc2_app_kit::NSView> =
                                $crate::objc2::msg_send![&subviews, objectAtIndex: i];
                            let _: () = $crate::objc2::msg_send![&view, setAutoresizingMask: resize_mask];
                        }

                        Ok($class_name::with_label(
                            panel,
                            label,
                            original_class,
                            tauri::Manager::app_handle(&window).clone(),
                        ))
                    }
                }
            }

            // Helper methods
            impl<R: tauri::Runtime> $class_name<R> where $class_name<R>: $crate::Panel<R> {
                #[allow(unused)]
                fn apply_instance_property(panel: &$crate::objc2_app_kit::NSPanel, method: &str, value: bool) {
                    unsafe {
                        match method {
                            "hides_on_deactivate" | "hidesOnDeactivate" => {
                                let _: () = $crate::objc2::msg_send![panel, setHidesOnDeactivate: value];
                            },
                            "becomes_key_only_if_needed" | "becomesKeyOnlyIfNeeded" => {
                                let _: () = $crate::objc2::msg_send![panel, setBecomesKeyOnlyIfNeeded: value];
                            },
                            "works_when_modal" | "worksWhenModal" => {
                                let _: () = $crate::objc2::msg_send![panel, setWorksWhenModal: value];
                            },
                            "is_floating_panel" | "isFloatingPanel" => {
                                let _: () = $crate::objc2::msg_send![panel, setFloatingPanel: value];
                            },
                            // Properties like can_become_key_window, can_become_main_window don't have setters
                            // They are read-only and only affect behavior through method overrides
                            _ => {
                                // Skip properties without setters
                            }
                        }
                    }
                }

                #[allow(unused)]
                fn add_tracking_area(panel: &$crate::objc2_app_kit::NSPanel, options: impl Into<$crate::objc2_app_kit::NSTrackingAreaOptions>, auto_resize: bool) {
                    unsafe {
                        let content_view: $crate::objc2::rc::Retained<$crate::objc2_app_kit::NSView> =
                            $crate::objc2::msg_send![panel, contentView];
                        let bounds: $crate::objc2_foundation::NSRect =
                            $crate::objc2::msg_send![&content_view, bounds];
                        let options = $crate::panel::resolve_tracking_area_options(
                            options.into(),
                            auto_resize,
                        );

                        // Create tracking area
                        let tracking_area: $crate::objc2::rc::Retained<$crate::objc2_app_kit::NSTrackingArea> = {
                            let alloc: *mut $crate::objc2_app_kit::NSTrackingArea = $crate::objc2::msg_send![
                                $crate::objc2_app_kit::NSTrackingArea::class(),
                                alloc
                            ];
                            let area: *mut $crate::objc2_app_kit::NSTrackingArea = $crate::objc2::msg_send![
                                alloc,
                                initWithRect: bounds,
                                options: options,
                                owner: &*content_view,
                                userInfo: $crate::objc2::ffi::nil
                            ];
                            $crate::objc2::rc::Retained::from_raw(area).unwrap()
                        };

                        // Add tracking area
                        let _: () = $crate::objc2::msg_send![&content_view, addTrackingArea: &*tracking_area];
                    }
                }
            }
        }
    };
}

#[cfg(test)]
mod tests {
    use std::ffi::CStr;
    use std::sync::OnceLock;

    use objc2::{runtime::ClassBuilder, ClassType};
    use objc2_app_kit::{NSTrackingAreaOptions, NSView};

    use super::{
        install_window_level_method, resolve_tracking_area_options, stable_text_input_client_class,
    };

    #[test]
    fn auto_resize_tracks_the_visible_view_rect() {
        let base = NSTrackingAreaOptions::ActiveAlways
            | NSTrackingAreaOptions::MouseEnteredAndExited
            | NSTrackingAreaOptions::MouseMoved;

        let options = resolve_tracking_area_options(base, true);

        assert!(options.contains(NSTrackingAreaOptions::InVisibleRect));
        assert!(options.contains(base));
    }

    #[test]
    fn fixed_tracking_area_preserves_the_requested_options() {
        let base = NSTrackingAreaOptions::ActiveAlways
            | NSTrackingAreaOptions::MouseEnteredAndExited
            | NSTrackingAreaOptions::MouseMoved;

        assert_eq!(resolve_tracking_area_options(base, false), base);
    }

    #[test]
    fn window_level_method_is_installed_once() {
        static CLASS: OnceLock<&'static objc2::runtime::AnyClass> = OnceLock::new();
        let class = CLASS.get_or_init(|| {
            let name = CStr::from_bytes_with_nul(b"TauriNSPanelTextInputClientTest\0")
                .expect("test class name must be NUL-terminated");
            ClassBuilder::new(name, NSView::class())
                .expect("test class should only be registered once")
                .register()
        });

        assert!(install_window_level_method(class));
        assert!(class.instance_method(objc2::sel!(windowLevel)).is_some());
        assert!(!install_window_level_method(class));
    }

    #[test]
    fn window_level_method_targets_the_stable_webview_subclass() {
        static CLASSES: OnceLock<(
            &'static objc2::runtime::AnyClass,
            &'static objc2::runtime::AnyClass,
        )> = OnceLock::new();
        let (webview, notifying_webview) = CLASSES.get_or_init(|| {
            let wk_webview_name = CStr::from_bytes_with_nul(b"WKWebView\0").unwrap();
            let wk_webview = objc2::runtime::AnyClass::get(wk_webview_name)
                .expect("WebKit should be loaded by Tauri");
            let webview_name =
                CStr::from_bytes_with_nul(b"TauriNSPanelStableWebViewTest\0").unwrap();
            let webview = ClassBuilder::new(webview_name, wk_webview)
                .expect("stable test webview class should only be registered once")
                .register();
            let notifying_name =
                CStr::from_bytes_with_nul(b"TauriNSPanelNotifyingWebViewTest\0").unwrap();
            let notifying_webview = ClassBuilder::new(notifying_name, webview)
                .expect("notifying test webview class should only be registered once")
                .register();

            (webview, notifying_webview)
        });

        assert_eq!(stable_text_input_client_class(notifying_webview), *webview);
    }
}