Skip to main content

tauri_nspanel/
lib.rs

1pub mod builder;
2pub mod common;
3pub mod event;
4pub mod panel;
5
6// Re-export for macro usage
7#[doc(hidden)]
8pub use objc2;
9#[doc(hidden)]
10pub use objc2_app_kit;
11#[doc(hidden)]
12pub use objc2_foundation;
13#[doc(hidden)]
14pub use pastey;
15
16use std::{
17    any::Any,
18    collections::HashMap,
19    fmt,
20    sync::{Arc, Mutex},
21};
22
23use objc2::runtime::ProtocolObject;
24use objc2_app_kit::NSWindowDelegate;
25use tauri::{
26    plugin::{Builder, TauriPlugin},
27    Manager, Runtime, WebviewWindow,
28};
29
30pub use builder::{
31    CollectionBehavior, PanelBuilder, PanelLevel, ResizeDirection, StyleMask, TrackingAreaOptions,
32};
33
34// Re-export commonly used types for convenience
35pub use objc2::runtime::AnyObject;
36pub use objc2_app_kit::{NSPanel, NSResponder, NSView, NSWindow};
37pub use objc2_foundation::{NSNotification, NSObject, NSPoint, NSRect, NSSize};
38
39/// An error raised by AppKit while changing a panel's style mask.
40#[derive(Debug, Clone, PartialEq, Eq)]
41#[non_exhaustive]
42pub enum StyleMaskError {
43    /// AppKit rejected the requested style mask with an Objective-C exception.
44    ObjectiveCException(String),
45    /// AppKit raised an Objective-C exception without an exception object.
46    UnknownObjectiveCException,
47}
48
49impl fmt::Display for StyleMaskError {
50    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
51        match self {
52            Self::ObjectiveCException(reason) => {
53                write!(formatter, "AppKit rejected the panel style mask: {reason}")
54            }
55            Self::UnknownObjectiveCException => {
56                formatter.write_str("AppKit rejected the panel style mask")
57            }
58        }
59    }
60}
61
62impl std::error::Error for StyleMaskError {}
63
64#[doc(hidden)]
65pub fn catch_style_mask_exception(operation: impl FnOnce()) -> Result<(), StyleMaskError> {
66    match objc2::exception::catch(std::panic::AssertUnwindSafe(operation)) {
67        Ok(()) => Ok(()),
68        Err(Some(exception)) => Err(StyleMaskError::ObjectiveCException(exception.to_string())),
69        Err(None) => Err(StyleMaskError::UnknownObjectiveCException),
70    }
71}
72
73/// Trait for event handlers that can be used with panels
74pub trait EventHandler {
75    /// Get the NSWindowDelegate protocol object
76    fn as_delegate(&self) -> ProtocolObject<dyn NSWindowDelegate>;
77}
78
79/// Common trait for all panel types
80pub trait Panel<R: tauri::Runtime = tauri::Wry>: Send + Sync {
81    /// Show the panel
82    fn show(&self);
83
84    /// Hide the panel
85    fn hide(&self);
86
87    /// Convert the panel back to a regular Tauri window.
88    ///
89    /// This restores Tauri-compatible native window ownership before returning the window.
90    fn to_window(&self) -> Option<tauri::WebviewWindow<R>>;
91
92    /// Get a reference to the underlying NSPanel
93    fn as_panel(&self) -> &objc2_app_kit::NSPanel;
94
95    /// Get the panel label
96    fn label(&self) -> &str;
97
98    /// Downcast to concrete type
99    fn as_any(&self) -> &dyn Any;
100
101    /// Set the event handler (window delegate).
102    ///
103    /// The panel retains the handler until it is replaced or cleared, so the caller does not
104    /// need to keep its own `Retained` handle alive. Pass `None` to restore the original Tauri
105    /// window delegate.
106    ///
107    /// For behavior that changes at runtime, prefer installing one handler whose callbacks read
108    /// shared state instead of repeatedly replacing the delegate.
109    fn set_event_handler(&self, handler: Option<&ProtocolObject<dyn NSWindowDelegate>>);
110
111    // Query methods
112    /// Check if the panel is visible
113    fn is_visible(&self) -> bool;
114
115    /// Check if this is a floating panel
116    fn is_floating_panel(&self) -> bool;
117
118    /// Check if panel becomes key only if needed
119    fn becomes_key_only_if_needed(&self) -> bool;
120
121    /// Check if panel can become key window
122    fn can_become_key_window(&self) -> bool;
123
124    /// Check if panel can become main window
125    fn can_become_main_window(&self) -> bool;
126
127    /// Check if panel hides on deactivate
128    fn hides_on_deactivate(&self) -> bool;
129
130    // Window state methods
131    /// Make the panel key window
132    fn make_key_window(&self);
133
134    /// Make the panel main window
135    fn make_main_window(&self);
136
137    /// Resign key window status
138    fn resign_key_window(&self);
139
140    /// Make key and order front
141    fn make_key_and_order_front(&self);
142
143    /// Order front regardless
144    fn order_front_regardless(&self);
145
146    /// Show and make key
147    fn show_and_make_key(&self);
148
149    // Configuration methods
150    /// Set the window level
151    fn set_level(&self, level: i64);
152
153    /// Set whether this is a floating panel
154    fn set_floating_panel(&self, value: bool);
155
156    /// Set whether panel becomes key only if needed
157    fn set_becomes_key_only_if_needed(&self, value: bool);
158
159    /// Set whether panel hides on deactivate
160    fn set_hides_on_deactivate(&self, value: bool);
161
162    /// Set whether panel works when modal
163    fn set_works_when_modal(&self, value: bool);
164
165    /// Set the alpha value
166    fn set_alpha_value(&self, value: f64);
167
168    /// Set whether AppKit should release the panel when it closes.
169    ///
170    /// Keep this `false` when Tauri owns the window. [`Panel::to_window`] resets it to `false`
171    /// before returning ownership to Tauri.
172    fn set_released_when_closed(&self, released: bool);
173
174    /// Set the content size
175    fn set_content_size(&self, width: f64, height: f64);
176
177    /// Set whether panel has shadow
178    fn set_has_shadow(&self, value: bool);
179
180    /// Set whether panel is opaque
181    fn set_opaque(&self, value: bool);
182
183    /// Set whether panel accepts mouse moved events
184    fn set_accepts_mouse_moved_events(&self, value: bool);
185
186    /// Set whether panel ignores mouse events
187    fn set_ignores_mouse_events(&self, value: bool);
188
189    /// Set whether panel is movable by window background
190    fn set_movable_by_window_background(&self, value: bool);
191
192    /// Set the collection behavior
193    fn set_collection_behavior(&self, behavior: objc2_app_kit::NSWindowCollectionBehavior);
194
195    /// Get the content view
196    fn content_view(&self) -> objc2::rc::Retained<objc2_app_kit::NSView>;
197
198    /// Resign main window status
199    fn resign_main_window(&self);
200
201    /// Replace the panel's style mask.
202    ///
203    /// Synchronizes application activation prevention with the nonactivating panel flag when
204    /// AppKit provides the corresponding selector. Removing the flag restores normal activation.
205    ///
206    /// AppKit may reject structural changes to a live window. Such Objective-C exceptions are
207    /// caught and returned instead of crossing into Rust and aborting the process.
208    fn set_style_mask(
209        &self,
210        style_mask: objc2_app_kit::NSWindowStyleMask,
211    ) -> Result<(), StyleMaskError>;
212
213    /// Add flags to the panel's current style mask.
214    ///
215    /// Prefer this when enabling behavior such as
216    /// [`NSWindowStyleMask::NonactivatingPanel`](objc2_app_kit::NSWindowStyleMask::NonactivatingPanel)
217    /// without removing Tauri's existing structural window styles.
218    fn add_style_mask(
219        &self,
220        style_mask: objc2_app_kit::NSWindowStyleMask,
221    ) -> Result<(), StyleMaskError> {
222        self.set_style_mask(self.as_panel().styleMask() | style_mask)
223    }
224
225    /// Make a view the first responder
226    fn make_first_responder(&self, responder: Option<&objc2_app_kit::NSResponder>) -> bool;
227
228    /// Set the corner radius for the panel
229    fn set_corner_radius(&self, radius: f64);
230
231    /// Set the panel background to be transparent
232    fn set_transparent(&self, transparent: bool);
233}
234
235/// Trait for panels that can be created from a window
236pub trait FromWindow<R: Runtime>: Panel<R> + Sized {
237    /// Create panel from a Tauri window
238    fn from_window(window: WebviewWindow<R>, label: String) -> tauri::Result<Self>;
239}
240
241/// Type alias for shared panel references
242pub type PanelHandle<R> = Arc<dyn Panel<R>>;
243
244pub struct Store<R: Runtime> {
245    panels: HashMap<String, PanelHandle<R>>,
246}
247
248impl<R: Runtime> Default for Store<R> {
249    fn default() -> Self {
250        Self {
251            panels: HashMap::new(),
252        }
253    }
254}
255
256pub struct WebviewPanelManager<R: Runtime>(pub Mutex<Store<R>>);
257
258impl<R: Runtime> Default for WebviewPanelManager<R> {
259    fn default() -> Self {
260        Self(Mutex::new(Store::default()))
261    }
262}
263
264pub trait ManagerExt<R: Runtime> {
265    fn get_webview_panel(&self, label: &str) -> Result<PanelHandle<R>, Error>;
266    fn remove_webview_panel(&self, label: &str) -> Option<PanelHandle<R>>;
267}
268
269#[derive(Debug)]
270pub enum Error {
271    PanelNotFound,
272}
273
274impl<R: Runtime, T: Manager<R>> ManagerExt<R> for T {
275    fn get_webview_panel(&self, label: &str) -> Result<PanelHandle<R>, Error> {
276        let manager = self.state::<self::WebviewPanelManager<R>>();
277        let manager = manager.0.lock().unwrap();
278
279        match manager.panels.get(label) {
280            Some(panel) => Ok(panel.clone()),
281            None => Err(Error::PanelNotFound),
282        }
283    }
284
285    fn remove_webview_panel(&self, label: &str) -> Option<PanelHandle<R>> {
286        self.state::<self::WebviewPanelManager<R>>()
287            .0
288            .lock()
289            .unwrap()
290            .panels
291            .remove(label)
292    }
293}
294
295pub trait WebviewWindowExt<R: Runtime> {
296    /// Convert window to specific panel type
297    fn to_panel<P: FromWindow<R> + 'static>(&self) -> tauri::Result<PanelHandle<R>>;
298}
299
300impl<R: Runtime> WebviewWindowExt<R> for WebviewWindow<R> {
301    fn to_panel<P: FromWindow<R> + 'static>(&self) -> tauri::Result<PanelHandle<R>> {
302        let label = self.label().to_string();
303        let panel = P::from_window(self.clone(), label.clone())?;
304        let arc_panel = Arc::new(panel) as PanelHandle<R>;
305
306        let manager = self.state::<WebviewPanelManager<R>>();
307        manager
308            .0
309            .lock()
310            .unwrap()
311            .panels
312            .insert(label, arc_panel.clone());
313
314        Ok(arc_panel)
315    }
316}
317
318/// Initializes the plugin.
319pub fn init<R: Runtime>() -> TauriPlugin<R> {
320    Builder::new("nspanel")
321        .setup(|app, _api| {
322            app.manage(self::WebviewPanelManager::<R>::default());
323
324            Ok(())
325        })
326        .build()
327}
328
329#[cfg(test)]
330mod tests {
331    use objc2::rc::Retained;
332    use objc2_foundation::{NSException, NSInternalInconsistencyException, NSString};
333
334    use super::{catch_style_mask_exception, StyleMaskError};
335
336    #[test]
337    fn objective_c_exceptions_become_style_mask_errors() {
338        let reason = NSString::from_str("invalid test style mask");
339        let exception = unsafe {
340            NSException::exceptionWithName_reason_userInfo(
341                NSInternalInconsistencyException,
342                Some(&reason),
343                None,
344            )
345        };
346        let exception =
347            unsafe { Retained::cast_unchecked::<objc2::exception::Exception>(exception) };
348
349        let error = catch_style_mask_exception(|| objc2::exception::throw(exception))
350            .expect_err("the Objective-C exception should be returned as an error");
351
352        assert_eq!(
353            error,
354            StyleMaskError::ObjectiveCException("invalid test style mask".into())
355        );
356    }
357}