Skip to main content

tauri_nspanel/
builder.rs

1use std::sync::Arc;
2
3use objc2_app_kit::{NSApplication, NSApplicationActivationPolicy, NSPanel};
4use objc2_foundation::{MainThreadMarker, NSSize};
5use tauri::{AppHandle, Position, Runtime, Size, WebviewUrl, WebviewWindowBuilder};
6
7use crate::{FromWindow, Panel, WebviewWindowExt};
8
9/// Type alias for window configuration function
10type WindowConfigFn<'a, R> = Box<
11    dyn FnOnce(
12        WebviewWindowBuilder<'a, R, AppHandle<R>>,
13    ) -> WebviewWindowBuilder<'a, R, AppHandle<R>>,
14>;
15
16/// Axes along which a resizable panel may be resized.
17#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
18pub enum ResizeDirection {
19    /// Allow the panel to be resized horizontally and vertically.
20    #[default]
21    Both,
22    /// Allow the panel width to change while keeping its current height fixed.
23    Horizontal,
24    /// Allow the panel height to change while keeping its current width fixed.
25    Vertical,
26}
27
28impl ResizeDirection {
29    fn apply(self, panel: &NSPanel) {
30        if self == Self::Both {
31            return;
32        }
33
34        let Some(content_view) = panel.contentView() else {
35            return;
36        };
37
38        let current_size = content_view.frame().size;
39        let (min_size, max_size) = resize_constraints(
40            self,
41            current_size,
42            panel.contentMinSize(),
43            panel.contentMaxSize(),
44        );
45
46        panel.setContentMinSize(min_size);
47        panel.setContentMaxSize(max_size);
48    }
49}
50
51fn resize_constraints(
52    direction: ResizeDirection,
53    current_size: NSSize,
54    mut min_size: NSSize,
55    mut max_size: NSSize,
56) -> (NSSize, NSSize) {
57    match direction {
58        ResizeDirection::Both => {}
59        ResizeDirection::Horizontal => {
60            min_size.height = current_size.height;
61            max_size.height = current_size.height;
62        }
63        ResizeDirection::Vertical => {
64            min_size.width = current_size.width;
65            max_size.width = current_size.width;
66        }
67    }
68
69    (min_size, max_size)
70}
71
72/// Window level constants for NSPanel
73/// Based on NSWindow.Level constants from macOS
74#[derive(Debug, Clone, Copy, PartialEq)]
75pub enum PanelLevel {
76    /// Normal window level (0)
77    Normal,
78    /// Submenu window level (3)
79    Submenu,
80    /// Torn-off menu window level (3)
81    TornOffMenu,
82    /// Floating window level (4)
83    Floating,
84    /// Modal panel window level (8)
85    ModalPanel,
86    /// Utility window level (19)
87    Utility,
88    /// Dock window level (20)
89    Dock,
90    /// Main menu window level (24)
91    MainMenu,
92    /// Status window level (25)
93    Status,
94    /// Pop-up menu window level (101)
95    PopUpMenu,
96    /// Screen saver window level (1000)
97    ScreenSaver,
98    /// Custom level value
99    Custom(i32),
100}
101
102impl PanelLevel {
103    /// Convert to the raw i64 value used by NSWindow
104    pub fn value(&self) -> i64 {
105        match self {
106            PanelLevel::Normal => 0,
107            PanelLevel::Submenu => 3,
108            PanelLevel::TornOffMenu => 3,
109            PanelLevel::Floating => 4,
110            PanelLevel::ModalPanel => 8,
111            PanelLevel::Utility => 19,
112            PanelLevel::Dock => 20,
113            PanelLevel::MainMenu => 24,
114            PanelLevel::Status => 25,
115            PanelLevel::PopUpMenu => 101,
116            PanelLevel::ScreenSaver => 1000,
117            PanelLevel::Custom(value) => *value as i64,
118        }
119    }
120}
121
122impl From<PanelLevel> for i64 {
123    fn from(level: PanelLevel) -> Self {
124        level.value()
125    }
126}
127
128impl From<i32> for PanelLevel {
129    fn from(value: i32) -> Self {
130        PanelLevel::Custom(value)
131    }
132}
133
134impl From<i64> for PanelLevel {
135    fn from(value: i64) -> Self {
136        PanelLevel::Custom(value as i32)
137    }
138}
139
140/// Window collection behavior builder for NSPanel
141///
142/// Allows combining multiple collection behaviors using the builder pattern.
143/// Collection behaviors control how a window participates in Spaces, Exposé, and fullscreen mode.
144///
145/// # Example
146/// ```no_run
147/// use tauri::AppHandle;
148/// use tauri_nspanel::{tauri_panel, CollectionBehavior, PanelBuilder};
149///
150/// tauri_panel! {
151///     panel!(SpacesPanel {})
152/// }
153///
154/// # fn create_panel(app: &AppHandle) -> tauri::Result<()> {
155///
156/// // Create a panel that appears on all spaces and ignores Cmd+Tab cycling
157/// let behavior = CollectionBehavior::new()
158///     .can_join_all_spaces()
159///     .ignores_cycle();
160///
161/// // Use with PanelBuilder
162/// let _panel = PanelBuilder::<_, SpacesPanel>::new(app, "my-panel")
163///     .collection_behavior(behavior)
164///     .build()?;
165/// # Ok(())
166/// # }
167/// ```
168#[derive(Debug, Clone, Copy, PartialEq)]
169pub struct CollectionBehavior(objc2_app_kit::NSWindowCollectionBehavior);
170
171impl CollectionBehavior {
172    /// Create an empty collection behavior
173    pub fn new() -> Self {
174        Self(objc2_app_kit::NSWindowCollectionBehavior::empty())
175    }
176
177    /// Window can be shown on another space
178    pub fn can_join_all_spaces(mut self) -> Self {
179        self.0 |= objc2_app_kit::NSWindowCollectionBehavior::CanJoinAllSpaces;
180        self
181    }
182
183    /// Window appears in all spaces
184    pub fn move_to_active_space(mut self) -> Self {
185        self.0 |= objc2_app_kit::NSWindowCollectionBehavior::MoveToActiveSpace;
186        self
187    }
188
189    /// Window is managed by Spaces
190    pub fn managed(mut self) -> Self {
191        self.0 |= objc2_app_kit::NSWindowCollectionBehavior::Managed;
192        self
193    }
194
195    /// Window participates in Spaces and Expose
196    pub fn transient(mut self) -> Self {
197        self.0 |= objc2_app_kit::NSWindowCollectionBehavior::Transient;
198        self
199    }
200
201    /// Window does not participate in Spaces or Expose
202    pub fn stationary(mut self) -> Self {
203        self.0 |= objc2_app_kit::NSWindowCollectionBehavior::Stationary;
204        self
205    }
206
207    /// Window participates in cycling
208    pub fn participates_in_cycle(mut self) -> Self {
209        self.0 |= objc2_app_kit::NSWindowCollectionBehavior::ParticipatesInCycle;
210        self
211    }
212
213    /// Window ignores cycling commands
214    pub fn ignores_cycle(mut self) -> Self {
215        self.0 |= objc2_app_kit::NSWindowCollectionBehavior::IgnoresCycle;
216        self
217    }
218
219    /// Window can be shown in full screen
220    pub fn full_screen_primary(mut self) -> Self {
221        self.0 |= objc2_app_kit::NSWindowCollectionBehavior::FullScreenPrimary;
222        self
223    }
224
225    /// Window can be shown alongside full screen window
226    pub fn full_screen_auxiliary(mut self) -> Self {
227        self.0 |= objc2_app_kit::NSWindowCollectionBehavior::FullScreenAuxiliary;
228        self
229    }
230
231    /// Window does not allow full screen
232    pub fn full_screen_none(mut self) -> Self {
233        self.0 |= objc2_app_kit::NSWindowCollectionBehavior::FullScreenNone;
234        self
235    }
236
237    /// Window can be shown in full screen for this space only
238    pub fn full_screen_allows_tiling(mut self) -> Self {
239        self.0 |= objc2_app_kit::NSWindowCollectionBehavior::FullScreenAllowsTiling;
240        self
241    }
242
243    /// Window does not allow full screen and hides on app deactivation
244    pub fn full_screen_disallows_tiling(mut self) -> Self {
245        self.0 |= objc2_app_kit::NSWindowCollectionBehavior::FullScreenDisallowsTiling;
246        self
247    }
248
249    /// Create from raw NSWindowCollectionBehavior flags
250    pub fn from_raw(flags: objc2_app_kit::NSWindowCollectionBehavior) -> Self {
251        Self(flags)
252    }
253
254    /// Get the raw NSWindowCollectionBehavior flags
255    pub fn value(&self) -> objc2_app_kit::NSWindowCollectionBehavior {
256        self.0
257    }
258}
259
260impl Default for CollectionBehavior {
261    fn default() -> Self {
262        Self::new()
263    }
264}
265
266impl From<CollectionBehavior> for objc2_app_kit::NSWindowCollectionBehavior {
267    fn from(behavior: CollectionBehavior) -> Self {
268        behavior.0
269    }
270}
271
272impl From<objc2_app_kit::NSWindowCollectionBehavior> for CollectionBehavior {
273    fn from(value: objc2_app_kit::NSWindowCollectionBehavior) -> Self {
274        CollectionBehavior(value)
275    }
276}
277
278/// Tracking area options builder for NSPanel
279///
280/// Allows combining multiple tracking area options using the builder pattern.
281/// Tracking areas enable mouse event tracking within a specific region of a view.
282///
283/// # Example
284/// ```
285/// use tauri_nspanel::{tauri_panel, TrackingAreaOptions};
286///
287/// tauri_panel! {
288///     panel!(TrackingPanel {
289///         with: {
290///             tracking_area: {
291///                 options: TrackingAreaOptions::new()
292///                     .active_always()
293///                     .mouse_entered_and_exited()
294///                     .mouse_moved(),
295///                 auto_resize: true
296///             }
297///         }
298///     })
299/// }
300/// ```
301#[derive(Debug, Clone, Copy, PartialEq)]
302pub struct TrackingAreaOptions(objc2_app_kit::NSTrackingAreaOptions);
303
304impl TrackingAreaOptions {
305    /// Create empty tracking area options
306    pub fn new() -> Self {
307        Self(objc2_app_kit::NSTrackingAreaOptions::empty())
308    }
309
310    /// Track mouse moved events
311    pub fn mouse_moved(mut self) -> Self {
312        self.0 |= objc2_app_kit::NSTrackingAreaOptions::MouseMoved;
313        self
314    }
315
316    /// Track mouse entered and exited events
317    pub fn mouse_entered_and_exited(mut self) -> Self {
318        self.0 |= objc2_app_kit::NSTrackingAreaOptions::MouseEnteredAndExited;
319        self
320    }
321
322    /// Track when mouse is active in any application
323    pub fn active_always(mut self) -> Self {
324        self.0 |= objc2_app_kit::NSTrackingAreaOptions::ActiveAlways;
325        self
326    }
327
328    /// Track when mouse is active in this application
329    pub fn active_in_active_app(mut self) -> Self {
330        self.0 |= objc2_app_kit::NSTrackingAreaOptions::ActiveInActiveApp;
331        self
332    }
333
334    /// Track when mouse is active in key window
335    pub fn active_in_key_window(mut self) -> Self {
336        self.0 |= objc2_app_kit::NSTrackingAreaOptions::ActiveInKeyWindow;
337        self
338    }
339
340    /// Track when window is key
341    pub fn active_when_first_responder(mut self) -> Self {
342        self.0 |= objc2_app_kit::NSTrackingAreaOptions::ActiveWhenFirstResponder;
343        self
344    }
345
346    /// Assumes tracking area is active
347    pub fn assume_inside(mut self) -> Self {
348        self.0 |= objc2_app_kit::NSTrackingAreaOptions::AssumeInside;
349        self
350    }
351
352    /// Keep the tracking area synchronized with the view's visible rectangle.
353    pub fn in_visible_rect(mut self) -> Self {
354        self.0 |= objc2_app_kit::NSTrackingAreaOptions::InVisibleRect;
355        self
356    }
357
358    /// Enable cursor update events
359    pub fn cursor_update(mut self) -> Self {
360        self.0 |= objc2_app_kit::NSTrackingAreaOptions::CursorUpdate;
361        self
362    }
363
364    /// Create from raw NSTrackingAreaOptions flags
365    pub fn from_raw(flags: objc2_app_kit::NSTrackingAreaOptions) -> Self {
366        Self(flags)
367    }
368
369    /// Get the raw NSTrackingAreaOptions flags
370    pub fn value(&self) -> objc2_app_kit::NSTrackingAreaOptions {
371        self.0
372    }
373}
374
375impl Default for TrackingAreaOptions {
376    fn default() -> Self {
377        Self::new()
378    }
379}
380
381impl From<TrackingAreaOptions> for objc2_app_kit::NSTrackingAreaOptions {
382    fn from(options: TrackingAreaOptions) -> Self {
383        options.0
384    }
385}
386
387impl From<objc2_app_kit::NSTrackingAreaOptions> for TrackingAreaOptions {
388    fn from(value: objc2_app_kit::NSTrackingAreaOptions) -> Self {
389        TrackingAreaOptions(value)
390    }
391}
392
393/// Window style mask builder for NSPanel
394///
395/// Allows combining multiple style masks using the builder pattern.
396/// Style masks control the appearance and behavior of the window frame.
397///
398/// # Example
399/// ```no_run
400/// use tauri::AppHandle;
401/// use tauri_nspanel::{tauri_panel, PanelBuilder, StyleMask};
402///
403/// tauri_panel! {
404///     panel!(BorderlessPanel {})
405/// }
406///
407/// # fn create_panel(app: &AppHandle) -> tauri::Result<()> {
408///
409/// // Create the borderless window through Tauri, then add non-activating panel behavior.
410/// let _panel = PanelBuilder::<_, BorderlessPanel>::new(app, "my-panel")
411///     .with_window(|window| window.decorations(false))
412///     .add_style_mask(StyleMask::empty().nonactivating_panel())
413///     .build()?;
414/// # Ok(())
415/// # }
416/// ```
417#[derive(Debug, Clone, Copy, PartialEq)]
418pub struct StyleMask(objc2_app_kit::NSWindowStyleMask);
419
420impl StyleMask {
421    /// Create with default style mask (Titled | Closable | Miniaturizable | Resizable)
422    pub fn new() -> Self {
423        Self(
424            objc2_app_kit::NSWindowStyleMask::Titled
425                | objc2_app_kit::NSWindowStyleMask::Closable
426                | objc2_app_kit::NSWindowStyleMask::Miniaturizable
427                | objc2_app_kit::NSWindowStyleMask::Resizable,
428        )
429    }
430
431    /// Create an empty style mask
432    pub fn empty() -> Self {
433        Self(objc2_app_kit::NSWindowStyleMask::empty())
434    }
435
436    /// Window has a title bar
437    pub fn titled(mut self) -> Self {
438        self.0 |= objc2_app_kit::NSWindowStyleMask::Titled;
439        self
440    }
441
442    /// Window has a close button
443    pub fn closable(mut self) -> Self {
444        self.0 |= objc2_app_kit::NSWindowStyleMask::Closable;
445        self
446    }
447
448    /// Window has a minimize button
449    pub fn miniaturizable(mut self) -> Self {
450        self.0 |= objc2_app_kit::NSWindowStyleMask::Miniaturizable;
451        self
452    }
453
454    /// Window can be resized
455    pub fn resizable(mut self) -> Self {
456        self.0 |= objc2_app_kit::NSWindowStyleMask::Resizable;
457        self
458    }
459
460    /// Window uses unified title and toolbar
461    pub fn unified_title_and_toolbar(mut self) -> Self {
462        self.0 |= objc2_app_kit::NSWindowStyleMask::UnifiedTitleAndToolbar;
463        self
464    }
465
466    /// Window uses full size content view
467    pub fn full_size_content_view(mut self) -> Self {
468        self.0 |= objc2_app_kit::NSWindowStyleMask::FullSizeContentView;
469        self
470    }
471
472    /// Window is a utility window
473    pub fn utility_window(mut self) -> Self {
474        self.0 |= objc2_app_kit::NSWindowStyleMask::UtilityWindow;
475        self
476    }
477
478    /// Window is a HUD window
479    pub fn hud_window(mut self) -> Self {
480        self.0 |= objc2_app_kit::NSWindowStyleMask::HUDWindow;
481        self
482    }
483
484    /// Window is a non-activating panel
485    pub fn nonactivating_panel(mut self) -> Self {
486        self.0 |= objc2_app_kit::NSWindowStyleMask::NonactivatingPanel;
487        self
488    }
489
490    /// Window has no title bar or border
491    pub fn borderless(mut self) -> Self {
492        self.0 = objc2_app_kit::NSWindowStyleMask::Borderless;
493        self
494    }
495
496    /// Create from raw NSWindowStyleMask flags
497    pub fn from_raw(flags: objc2_app_kit::NSWindowStyleMask) -> Self {
498        Self(flags)
499    }
500
501    /// Get the raw NSWindowStyleMask flags
502    pub fn value(&self) -> objc2_app_kit::NSWindowStyleMask {
503        self.0
504    }
505}
506
507impl Default for StyleMask {
508    fn default() -> Self {
509        Self::new()
510    }
511}
512
513impl From<StyleMask> for objc2_app_kit::NSWindowStyleMask {
514    fn from(mask: StyleMask) -> Self {
515        mask.0
516    }
517}
518
519impl From<objc2_app_kit::NSWindowStyleMask> for StyleMask {
520    fn from(value: objc2_app_kit::NSWindowStyleMask) -> Self {
521        StyleMask(value)
522    }
523}
524
525#[derive(Default)]
526pub(crate) struct PanelConfig {
527    pub floating: Option<bool>,
528    pub level: Option<PanelLevel>,
529    pub has_shadow: Option<bool>,
530    pub opaque: Option<bool>,
531    pub alpha_value: Option<f64>,
532    pub hides_on_deactivate: Option<bool>,
533    pub becomes_key_only_if_needed: Option<bool>,
534    pub accepts_mouse_moved_events: Option<bool>,
535    pub ignores_mouse_events: Option<bool>,
536    pub movable_by_window_background: Option<bool>,
537    pub released_when_closed: Option<bool>,
538    pub works_when_modal: Option<bool>,
539    pub content_size: Option<Size>,
540    pub style_mask: Option<StyleMaskConfig>,
541    pub collection_behavior: Option<CollectionBehavior>,
542    pub no_activate: Option<bool>,
543    pub corner_radius: Option<f64>,
544    pub transparent: Option<bool>,
545}
546
547pub(crate) enum StyleMaskConfig {
548    Replace(StyleMask),
549    Add(StyleMask),
550}
551
552/// Builder for creating panels with Tauri-like API
553///
554/// PanelBuilder provides a fluent interface that creates a Tauri window,
555/// converts it to an NSPanel, and applies panel-specific configurations.
556/// It works with custom panel classes created with the `panel!` macro.
557///
558/// # Type Parameters
559/// - `R`: The Tauri runtime type
560/// - `T`: The panel type (must implement `FromWindow<R>`)
561///
562/// # Example
563/// ```no_run
564/// use tauri::{AppHandle, WebviewUrl};
565/// use tauri_nspanel::{tauri_panel, PanelBuilder, PanelLevel};
566///
567/// tauri_panel! {
568///     panel!(ToolPanel {
569///         config: {
570///             can_become_key_window: false
571///         }
572///     })
573/// }
574///
575/// # fn create_panel(app: &AppHandle) -> tauri::Result<()> {
576/// let _panel = PanelBuilder::<_, ToolPanel>::new(app, "my-panel")
577///     .url(WebviewUrl::App("panel.html".into()))
578///     .title("Tool Panel")
579///     .level(PanelLevel::Floating)
580///     .build()?;
581/// # Ok(())
582/// # }
583/// ```
584pub struct PanelBuilder<'a, R: Runtime, T: FromWindow<R> + 'static> {
585    handle: &'a AppHandle<R>,
586    label: String,
587    url: Option<WebviewUrl>,
588    title: Option<String>,
589    position: Option<Position>,
590    size: Option<Size>,
591    min_size: Option<Size>,
592    max_size: Option<Size>,
593    resizable: Option<bool>,
594    resize_direction: ResizeDirection,
595    pub(crate) panel_config: PanelConfig,
596    window_fn: Option<WindowConfigFn<'a, R>>,
597    _phantom: std::marker::PhantomData<T>,
598}
599
600impl<'a, R: Runtime + 'a, T: FromWindow<R> + 'static> PanelBuilder<'a, R, T> {
601    /// Create a new PanelBuilder
602    pub fn new(handle: &'a AppHandle<R>, label: impl Into<String>) -> Self {
603        Self {
604            handle,
605            label: label.into(),
606            url: None,
607            title: None,
608            position: None,
609            size: None,
610            min_size: None,
611            max_size: None,
612            resizable: None,
613            resize_direction: ResizeDirection::Both,
614            panel_config: PanelConfig::default(),
615            window_fn: None,
616            _phantom: std::marker::PhantomData,
617        }
618    }
619
620    /// Set the webview URL
621    pub fn url(mut self, url: WebviewUrl) -> Self {
622        self.url = Some(url);
623        self
624    }
625
626    /// Set the window title
627    pub fn title(mut self, title: impl Into<String>) -> Self {
628        self.title = Some(title.into());
629        self
630    }
631
632    /// Set the window position
633    pub fn position(mut self, position: Position) -> Self {
634        self.position = Some(position);
635        self
636    }
637
638    /// Set the window size
639    pub fn size(mut self, size: Size) -> Self {
640        self.size = Some(size);
641        self
642    }
643
644    /// Set the minimum content size of the panel.
645    pub fn min_size(mut self, size: Size) -> Self {
646        self.min_size = Some(size);
647        self
648    }
649
650    /// Set the maximum content size of the panel.
651    pub fn max_size(mut self, size: Size) -> Self {
652        self.max_size = Some(size);
653        self
654    }
655
656    /// Set whether the panel can be resized by the user.
657    pub fn resizable(mut self, resizable: bool) -> Self {
658        self.resizable = Some(resizable);
659        self
660    }
661
662    /// Limit resizing to one axis.
663    ///
664    /// The dimension on the disabled axis is fixed to the panel's content size
665    /// after its minimum and maximum size constraints have been applied.
666    pub fn resize_direction(mut self, direction: ResizeDirection) -> Self {
667        self.resize_direction = direction;
668        self
669    }
670
671    /// Set whether the panel floats above other windows
672    pub fn floating(mut self, floating: bool) -> Self {
673        self.panel_config.floating = Some(floating);
674        self
675    }
676
677    /// Set the window level
678    ///
679    /// The window level determines the panel's position in the window hierarchy.
680    /// Higher levels appear above lower levels.
681    ///
682    /// # Example
683    /// ```no_run
684    /// use tauri::AppHandle;
685    /// use tauri_nspanel::{tauri_panel, PanelBuilder, PanelLevel};
686    ///
687    /// tauri_panel! {
688    ///     panel!(LevelPanel {})
689    /// }
690    ///
691    /// # fn create_panels(app: &AppHandle) -> tauri::Result<()> {
692    /// // Create a panel that floats above normal windows
693    /// let _floating = PanelBuilder::<_, LevelPanel>::new(app, "floating")
694    ///     .level(PanelLevel::Floating)
695    ///     .build()?;
696    ///
697    /// // Create a status-level panel (appears above floating panels)
698    /// let _status = PanelBuilder::<_, LevelPanel>::new(app, "status")
699    ///     .level(PanelLevel::Status)
700    ///     .build()?;
701    /// # Ok(())
702    /// # }
703    /// ```
704    pub fn level(mut self, level: PanelLevel) -> Self {
705        self.panel_config.level = Some(level);
706        self
707    }
708
709    /// Set whether the panel has a shadow
710    pub fn has_shadow(mut self, has_shadow: bool) -> Self {
711        self.panel_config.has_shadow = Some(has_shadow);
712        self
713    }
714
715    /// Set whether the panel is opaque
716    pub fn opaque(mut self, opaque: bool) -> Self {
717        self.panel_config.opaque = Some(opaque);
718        self
719    }
720
721    /// Set the alpha value (transparency)
722    pub fn alpha_value(mut self, alpha: f64) -> Self {
723        self.panel_config.alpha_value = Some(alpha);
724        self
725    }
726
727    /// Set whether the panel hides when the app is deactivated
728    pub fn hides_on_deactivate(mut self, hides: bool) -> Self {
729        self.panel_config.hides_on_deactivate = Some(hides);
730        self
731    }
732
733    /// Set whether the panel becomes key window only if needed
734    pub fn becomes_key_only_if_needed(mut self, value: bool) -> Self {
735        self.panel_config.becomes_key_only_if_needed = Some(value);
736        self
737    }
738
739    /// Set whether the panel accepts mouse moved events
740    pub fn accepts_mouse_moved_events(mut self, value: bool) -> Self {
741        self.panel_config.accepts_mouse_moved_events = Some(value);
742        self
743    }
744
745    /// Set whether the panel ignores mouse events
746    pub fn ignores_mouse_events(mut self, value: bool) -> Self {
747        self.panel_config.ignores_mouse_events = Some(value);
748        self
749    }
750
751    /// Set whether the panel is movable by its background
752    pub fn movable_by_window_background(mut self, value: bool) -> Self {
753        self.panel_config.movable_by_window_background = Some(value);
754        self
755    }
756
757    /// Set whether AppKit releases the panel when it closes.
758    ///
759    /// This should normally remain `false` for Tauri-managed panels. [`Panel::to_window`]
760    /// restores it to `false` before returning ownership to Tauri.
761    pub fn released_when_closed(mut self, value: bool) -> Self {
762        self.panel_config.released_when_closed = Some(value);
763        self
764    }
765
766    /// Set whether the panel works when modal dialogs are displayed
767    pub fn works_when_modal(mut self, value: bool) -> Self {
768        self.panel_config.works_when_modal = Some(value);
769        self
770    }
771
772    /// Set the content size (inner size excluding window decorations)
773    pub fn content_size(mut self, size: Size) -> Self {
774        self.panel_config.content_size = Some(size);
775        self
776    }
777
778    /// Replace the window style mask.
779    ///
780    /// Style masks control the appearance and behavior of the window frame. AppKit may reject
781    /// structural changes to a live window; [`Self::build`] returns that error instead of aborting
782    /// the process. Prefer [`Self::add_style_mask`] when only enabling additional behavior.
783    ///
784    /// # Example
785    /// ```no_run
786    /// use tauri::AppHandle;
787    /// use tauri_nspanel::{tauri_panel, PanelBuilder, StyleMask};
788    ///
789    /// tauri_panel! {
790    ///     panel!(StyledPanel {})
791    /// }
792    ///
793    /// # fn create_panels(app: &AppHandle) -> tauri::Result<()> {
794    /// // Create the native window without decorations before applying the exact mask.
795    /// let _borderless = PanelBuilder::<_, StyledPanel>::new(app, "borderless")
796    ///     .with_window(|window| window.decorations(false))
797    ///     .style_mask(StyleMask::empty().nonactivating_panel())
798    ///     .build()?;
799    /// # Ok(())
800    /// # }
801    /// ```
802    pub fn style_mask(mut self, style_mask: StyleMask) -> Self {
803        self.panel_config.style_mask = Some(StyleMaskConfig::Replace(style_mask));
804        self
805    }
806
807    /// Add flags to the window's existing style mask.
808    ///
809    /// This preserves the structural styles selected by Tauri and is the preferred way to enable
810    /// panel behavior such as [`StyleMask::nonactivating_panel`].
811    pub fn add_style_mask(mut self, style_mask: StyleMask) -> Self {
812        self.panel_config.style_mask = Some(StyleMaskConfig::Add(style_mask));
813        self
814    }
815
816    /// Set the collection behavior
817    ///
818    /// Collection behaviors control how the panel participates in Spaces, Exposé,
819    /// and fullscreen mode on macOS.
820    ///
821    /// # Example
822    /// ```no_run
823    /// use tauri::AppHandle;
824    /// use tauri_nspanel::{tauri_panel, CollectionBehavior, PanelBuilder};
825    ///
826    /// tauri_panel! {
827    ///     panel!(SpacesPanel {})
828    /// }
829    ///
830    /// # fn create_panel(app: &AppHandle) -> tauri::Result<()> {
831    /// // Create a panel that appears on all spaces and doesn't participate in cycling
832    /// let _panel = PanelBuilder::<_, SpacesPanel>::new(app, "tool-panel")
833    ///     .collection_behavior(
834    ///         CollectionBehavior::new()
835    ///             .can_join_all_spaces()
836    ///             .ignores_cycle()
837    ///     )
838    ///     .build()?;
839    /// # Ok(())
840    /// # }
841    /// ```
842    pub fn collection_behavior(mut self, behavior: CollectionBehavior) -> Self {
843        self.panel_config.collection_behavior = Some(behavior);
844        self
845    }
846
847    /// Prevent focus stealing during window creation
848    ///
849    /// Since PanelBuilder creates a regular window before converting it to a panel,
850    /// the window creation phase can steal focus. When set to true, the application's
851    /// activation policy is temporarily set to Prohibited during window creation,
852    /// preventing this focus interruption.
853    ///
854    /// This works particularly well with apps that use `ActivationPolicy::Accessory`,
855    /// ensuring the window is created silently before being converted to a panel.
856    ///
857    /// # Example
858    /// ```no_run
859    /// use tauri::{AppHandle, WebviewUrl};
860    /// use tauri_nspanel::{tauri_panel, PanelBuilder, PanelLevel};
861    ///
862    /// tauri_panel! {
863    ///     panel!(UtilityPanel {})
864    /// }
865    ///
866    /// # fn create_panel(app: &AppHandle) -> tauri::Result<()> {
867    /// // Create a utility panel that doesn't steal focus
868    /// let _panel = PanelBuilder::<_, UtilityPanel>::new(app, "utility")
869    ///     .url(WebviewUrl::App("utility.html".into()))
870    ///     .no_activate(true)
871    ///     .level(PanelLevel::Floating)
872    ///     .build()?;
873    /// # Ok(())
874    /// # }
875    /// ```
876    pub fn no_activate(mut self, no_activate: bool) -> Self {
877        self.panel_config.no_activate = Some(no_activate);
878        self
879    }
880
881    /// Set the corner radius for rounded corners
882    ///
883    /// This enables the layer-backed view and sets the corner radius on the panel's layer,
884    /// giving the panel rounded corners with the specified radius.
885    ///
886    /// # Example
887    /// ```no_run
888    /// use tauri::{AppHandle, WebviewUrl};
889    /// use tauri_nspanel::{tauri_panel, PanelBuilder};
890    ///
891    /// tauri_panel! {
892    ///     panel!(RoundedPanel {})
893    /// }
894    ///
895    /// # fn create_panel(app: &AppHandle) -> tauri::Result<()> {
896    /// let _panel = PanelBuilder::<_, RoundedPanel>::new(app, "rounded-panel")
897    ///     .url(WebviewUrl::App("index.html".into()))
898    ///     .corner_radius(10.0)  // 10pt corner radius
899    ///     .build()?;
900    /// # Ok(())
901    /// # }
902    /// ```
903    pub fn corner_radius(mut self, radius: f64) -> Self {
904        self.panel_config.corner_radius = Some(radius);
905        self
906    }
907
908    /// Set the panel background to be transparent
909    ///
910    /// This sets the window background color to clear and makes the panel non-opaque,
911    /// allowing content behind the panel to show through.
912    ///
913    /// # Example
914    /// ```no_run
915    /// use tauri::{AppHandle, WebviewUrl};
916    /// use tauri_nspanel::{tauri_panel, PanelBuilder};
917    ///
918    /// tauri_panel! {
919    ///     panel!(TransparentPanel {})
920    /// }
921    ///
922    /// # fn create_panel(app: &AppHandle) -> tauri::Result<()> {
923    /// let _panel = PanelBuilder::<_, TransparentPanel>::new(app, "transparent-panel")
924    ///     .url(WebviewUrl::App("index.html".into()))
925    ///     .transparent(true)  // Transparent background
926    ///     .build()?;
927    /// # Ok(())
928    /// # }
929    /// ```
930    pub fn transparent(mut self, transparent: bool) -> Self {
931        self.panel_config.transparent = Some(transparent);
932        self
933    }
934
935    /// Apply a custom configuration function to the WebviewWindowBuilder
936    ///
937    /// This allows access to any Tauri window configuration not exposed by the panel builder.
938    /// The closure receives the WebviewWindowBuilder and should return it after applying
939    /// any desired configurations.
940    ///
941    /// # Example
942    /// ```no_run
943    /// use tauri::{AppHandle, WebviewUrl};
944    /// use tauri_nspanel::{tauri_panel, PanelBuilder};
945    ///
946    /// tauri_panel! {
947    ///     panel!(ConfiguredPanel {})
948    /// }
949    ///
950    /// # fn create_panel(app: &AppHandle) -> tauri::Result<()> {
951    /// let _panel = PanelBuilder::<_, ConfiguredPanel>::new(app, "my-panel")
952    ///     .url(WebviewUrl::App("index.html".into()))
953    ///     .with_window(|window| {
954    ///         window
955    ///             .min_inner_size(300.0, 200.0)
956    ///             .max_inner_size(800.0, 600.0)
957    ///             .resizable(false)
958    ///             .decorations(false)
959    ///             .always_on_top(true)
960    ///             .skip_taskbar(true)
961    ///     })
962    ///     .build()?;
963    /// # Ok(())
964    /// # }
965    /// ```
966    pub fn with_window<F>(mut self, f: F) -> Self
967    where
968        F: FnOnce(
969                WebviewWindowBuilder<'a, R, AppHandle<R>>,
970            ) -> WebviewWindowBuilder<'a, R, AppHandle<R>>
971            + 'static,
972    {
973        self.window_fn = Some(Box::new(f) as WindowConfigFn<'a, R>);
974        self
975    }
976
977    /// Build the panel
978    ///
979    /// Creates a Tauri window using the configured properties, converts it to
980    /// an NSPanel, and applies all panel-specific settings.
981    pub fn build(self) -> tauri::Result<Arc<dyn Panel<R>>> {
982        // Handle no_activate option by temporarily changing activation policy
983        let original_policy = if self.panel_config.no_activate.unwrap_or(false) {
984            MainThreadMarker::new().map(|mtm| {
985                let app = NSApplication::sharedApplication(mtm);
986                let current_policy = app.activationPolicy();
987                let _success = app.setActivationPolicy(NSApplicationActivationPolicy::Prohibited);
988                current_policy
989            })
990        } else {
991            None
992        };
993
994        // Create a window first
995        let mut window_builder = WebviewWindowBuilder::new(
996            self.handle,
997            &self.label,
998            self.url.unwrap_or(WebviewUrl::App("index.html".into())),
999        );
1000
1001        if let Some(title) = self.title {
1002            window_builder = window_builder.title(title);
1003        }
1004
1005        if let Some(position) = self.position {
1006            match position {
1007                Position::Physical(pos) => {
1008                    window_builder = window_builder.position(pos.x as f64, pos.y as f64);
1009                }
1010                Position::Logical(pos) => {
1011                    window_builder = window_builder.position(pos.x, pos.y);
1012                }
1013            }
1014        }
1015
1016        if let Some(size) = self.size {
1017            match size {
1018                Size::Physical(s) => {
1019                    window_builder = window_builder.inner_size(s.width as f64, s.height as f64);
1020                }
1021                Size::Logical(s) => {
1022                    window_builder = window_builder.inner_size(s.width, s.height);
1023                }
1024            }
1025        }
1026
1027        if let Some(resizable) = self.resizable {
1028            window_builder = window_builder.resizable(resizable);
1029        }
1030
1031        // Apply custom configuration if provided
1032        if let Some(window_fn) = self.window_fn {
1033            window_builder = window_fn(window_builder);
1034        }
1035
1036        // Build the window while the temporary activation policy is in effect.
1037        let window = window_builder.build();
1038
1039        // The temporary policy is only needed while Tauri creates the native window. Restore it
1040        // before applying fallible panel configuration so errors cannot leave the app prohibited.
1041        if let Some(policy) = original_policy {
1042            if let Some(mtm) = MainThreadMarker::new() {
1043                let app = NSApplication::sharedApplication(mtm);
1044                let _success = app.setActivationPolicy(policy);
1045            }
1046        }
1047
1048        let window = window?;
1049
1050        // Convert to panel
1051        let panel = window.to_panel::<T>().unwrap();
1052
1053        // Apply panel configuration using the Panel trait methods
1054        if let Some(floating) = self.panel_config.floating {
1055            panel.set_floating_panel(floating);
1056        }
1057        if let Some(level) = self.panel_config.level {
1058            panel.set_level(level.value());
1059        }
1060        if let Some(has_shadow) = self.panel_config.has_shadow {
1061            panel.set_has_shadow(has_shadow);
1062        }
1063        if let Some(opaque) = self.panel_config.opaque {
1064            panel.set_opaque(opaque);
1065        }
1066        if let Some(alpha_value) = self.panel_config.alpha_value {
1067            panel.set_alpha_value(alpha_value);
1068        }
1069        if let Some(hides) = self.panel_config.hides_on_deactivate {
1070            panel.set_hides_on_deactivate(hides);
1071        }
1072        if let Some(value) = self.panel_config.becomes_key_only_if_needed {
1073            panel.set_becomes_key_only_if_needed(value);
1074        }
1075        if let Some(value) = self.panel_config.accepts_mouse_moved_events {
1076            panel.set_accepts_mouse_moved_events(value);
1077        }
1078        if let Some(value) = self.panel_config.ignores_mouse_events {
1079            panel.set_ignores_mouse_events(value);
1080        }
1081        if let Some(value) = self.panel_config.movable_by_window_background {
1082            panel.set_movable_by_window_background(value);
1083        }
1084        if let Some(value) = self.panel_config.released_when_closed {
1085            panel.set_released_when_closed(value);
1086        }
1087        if let Some(value) = self.panel_config.works_when_modal {
1088            panel.set_works_when_modal(value);
1089        }
1090        if let Some(style_mask) = self.panel_config.style_mask {
1091            let result = match style_mask {
1092                StyleMaskConfig::Replace(style_mask) => panel.set_style_mask(style_mask.0),
1093                StyleMaskConfig::Add(style_mask) => panel.add_style_mask(style_mask.0),
1094            };
1095
1096            if let Err(error) = result {
1097                if let Some(window) = panel.to_window() {
1098                    let _ = window.close();
1099                }
1100
1101                return Err(tauri::Error::Anyhow(error.into()));
1102            }
1103        }
1104        if let Some(behavior) = self.panel_config.collection_behavior {
1105            panel.set_collection_behavior(behavior.0);
1106        }
1107        if let Some(radius) = self.panel_config.corner_radius {
1108            panel.set_corner_radius(radius);
1109        }
1110        if let Some(transparent) = self.panel_config.transparent {
1111            panel.set_transparent(transparent);
1112        }
1113
1114        // Apply size constraints after the final style mask so they describe
1115        // the panel's final content area rather than its temporary window frame.
1116        if let Some(min_size) = self.min_size {
1117            window.set_min_size(Some(min_size))?;
1118        }
1119        if let Some(max_size) = self.max_size {
1120            window.set_max_size(Some(max_size))?;
1121        }
1122        self.resize_direction.apply(panel.as_panel());
1123
1124        Ok(panel)
1125    }
1126}
1127
1128#[cfg(test)]
1129mod tests {
1130    use super::{resize_constraints, ResizeDirection};
1131    use objc2_foundation::NSSize;
1132
1133    #[test]
1134    fn horizontal_resize_fixes_only_the_height() {
1135        let (min_size, max_size) = resize_constraints(
1136            ResizeDirection::Horizontal,
1137            NSSize::new(500.0, 300.0),
1138            NSSize::new(200.0, 100.0),
1139            NSSize::new(800.0, 600.0),
1140        );
1141
1142        assert_eq!(min_size, NSSize::new(200.0, 300.0));
1143        assert_eq!(max_size, NSSize::new(800.0, 300.0));
1144    }
1145
1146    #[test]
1147    fn vertical_resize_fixes_only_the_width() {
1148        let (min_size, max_size) = resize_constraints(
1149            ResizeDirection::Vertical,
1150            NSSize::new(500.0, 300.0),
1151            NSSize::new(200.0, 100.0),
1152            NSSize::new(800.0, 600.0),
1153        );
1154
1155        assert_eq!(min_size, NSSize::new(500.0, 100.0));
1156        assert_eq!(max_size, NSSize::new(500.0, 600.0));
1157    }
1158
1159    #[test]
1160    fn both_resize_axes_preserve_existing_constraints() {
1161        let min = NSSize::new(200.0, 100.0);
1162        let max = NSSize::new(800.0, 600.0);
1163
1164        let constraints =
1165            resize_constraints(ResizeDirection::Both, NSSize::new(500.0, 300.0), min, max);
1166
1167        assert_eq!(constraints, (min, max));
1168    }
1169}