Skip to main content

rio_window/platform/
macos.rs

1//! # macOS / AppKit
2//!
3//! Winit has an OS requirement of macOS 10.11 or higher (same as Rust
4//! itself), and is regularly tested on macOS 10.14.
5//!
6//! A lot of functionality expects the application to be ready before you
7//! start doing anything; this includes creating windows, fetching monitors,
8//! drawing, and so on, see issues [#2238], [#2051] and [#2087].
9//!
10//! If you encounter problems, you should try doing your initialization inside
11//! `Event::Resumed`.
12//!
13//! [#2238]: https://github.com/rust-windowing/winit/issues/2238
14//! [#2051]: https://github.com/rust-windowing/winit/issues/2051
15//! [#2087]: https://github.com/rust-windowing/winit/issues/2087
16
17use std::os::raw::c_void;
18
19use crate::event_loop::{ActiveEventLoop, EventLoopBuilder};
20use crate::monitor::MonitorHandle;
21use crate::window::{Window, WindowAttributes};
22
23/// Colorspace options for macOS windows.
24#[derive(Clone, Copy, Debug, PartialEq)]
25pub enum Colorspace {
26    /// Standard sRGB colorspace
27    Srgb,
28    /// Display P3 wide color gamut
29    DisplayP3,
30    /// Rec. 2020 ultra-wide color gamut
31    Rec2020,
32}
33
34/// Additional methods on [`Window`] that are specific to MacOS.
35pub trait WindowExtMacOS {
36    /// Returns whether or not the window is in simple fullscreen mode.
37    fn simple_fullscreen(&self) -> bool;
38
39    /// Toggles a fullscreen mode that doesn't require a new macOS space.
40    /// Returns a boolean indicating whether the transition was successful (this
41    /// won't work if the window was already in the native fullscreen).
42    ///
43    /// This is how fullscreen used to work on macOS in versions before Lion.
44    /// And allows the user to have a fullscreen window without using another
45    /// space or taking control over the entire monitor.
46    fn set_simple_fullscreen(&self, fullscreen: bool) -> bool;
47
48    /// Returns whether or not the window has shadow.
49    fn has_shadow(&self) -> bool;
50
51    /// Sets whether or not the window has shadow.
52    fn set_has_shadow(&self, has_shadow: bool);
53
54    /// Sets background color.
55    fn set_background_color(&self, _r: f64, _g: f64, _b: f64, _a: f64);
56
57    /// Group windows together by using the same tabbing identifier.
58    ///
59    /// <https://developer.apple.com/documentation/appkit/nswindow/1644704-tabbingidentifier>
60    fn set_tabbing_identifier(&self, identifier: &str);
61
62    /// Returns the window's tabbing identifier.
63    fn tabbing_identifier(&self) -> String;
64
65    /// Select next tab.
66    fn select_next_tab(&self);
67
68    /// Select previous tab.
69    fn select_previous_tab(&self);
70
71    /// Select the tab with the given index.
72    ///
73    /// Will no-op when the index is out of bounds.
74    fn select_tab_at_index(&self, index: usize);
75
76    /// Get the number of tabs in the window tab group.
77    fn num_tabs(&self) -> usize;
78
79    /// Get the window's edit state.
80    ///
81    /// # Examples
82    ///
83    /// ```ignore
84    /// WindowEvent::CloseRequested => {
85    ///     if window.is_document_edited() {
86    ///         // Show the user a save pop-up or similar
87    ///     } else {
88    ///         // Close the window
89    ///         drop(window);
90    ///     }
91    /// }
92    /// ```
93    fn is_document_edited(&self) -> bool;
94
95    /// Put the window in a state which indicates a file save is required.
96    fn set_document_edited(&self, edited: bool);
97
98    /// Set option as alt behavior as described in [`OptionAsAlt`].
99    ///
100    /// This will ignore diacritical marks and accent characters from
101    /// being processed as received characters. Instead, the input
102    /// device's raw character will be placed in event queues with the
103    /// Alt modifier set.
104    fn set_option_as_alt(&self, option_as_alt: OptionAsAlt);
105
106    /// Getter for the [`WindowExtMacOS::set_option_as_alt`].
107    fn option_as_alt(&self) -> OptionAsAlt;
108
109    /// Makes the titlebar bigger, effectively adding more space around the
110    /// window controls if the titlebar is invisible.
111    fn set_unified_titlebar(&self, unified_titlebar: bool);
112    /// Getter for the [`WindowExtMacOS::set_unified_titlebar`].
113    fn unified_titlebar(&self) -> bool;
114
115    /// Sets the window's colorspace for wide color gamut support.
116    fn set_colorspace(&self, colorspace: Colorspace);
117
118    /// Sets the position of the traffic light buttons (close, minimize, maximize).
119    /// The position is specified as (x, y) coordinates in points from the top-left corner.
120    /// Pass None to reset to the default position.
121    fn set_traffic_light_position(&self, position: Option<(f64, f64)>);
122}
123
124impl WindowExtMacOS for Window {
125    #[inline]
126    fn simple_fullscreen(&self) -> bool {
127        self.window.maybe_wait_on_main(|w| w.simple_fullscreen())
128    }
129
130    #[inline]
131    fn set_simple_fullscreen(&self, fullscreen: bool) -> bool {
132        self.window
133            .maybe_wait_on_main(move |w| w.set_simple_fullscreen(fullscreen))
134    }
135
136    #[inline]
137    fn has_shadow(&self) -> bool {
138        self.window.maybe_wait_on_main(|w| w.has_shadow())
139    }
140
141    #[inline]
142    fn set_has_shadow(&self, has_shadow: bool) {
143        self.window
144            .maybe_queue_on_main(move |w| w.set_has_shadow(has_shadow))
145    }
146
147    #[inline]
148    fn set_background_color(&self, r: f64, g: f64, b: f64, a: f64) {
149        self.window
150            .maybe_queue_on_main(move |w| w.set_background_color(r, g, b, a))
151    }
152
153    #[inline]
154    fn set_tabbing_identifier(&self, identifier: &str) {
155        self.window
156            .maybe_wait_on_main(|w| w.set_tabbing_identifier(identifier))
157    }
158
159    #[inline]
160    fn tabbing_identifier(&self) -> String {
161        self.window.maybe_wait_on_main(|w| w.tabbing_identifier())
162    }
163
164    #[inline]
165    fn select_next_tab(&self) {
166        self.window.maybe_queue_on_main(|w| w.select_next_tab())
167    }
168
169    #[inline]
170    fn select_previous_tab(&self) {
171        self.window.maybe_queue_on_main(|w| w.select_previous_tab())
172    }
173
174    #[inline]
175    fn select_tab_at_index(&self, index: usize) {
176        self.window
177            .maybe_queue_on_main(move |w| w.select_tab_at_index(index))
178    }
179
180    #[inline]
181    fn num_tabs(&self) -> usize {
182        self.window.maybe_wait_on_main(|w| w.num_tabs())
183    }
184
185    #[inline]
186    fn is_document_edited(&self) -> bool {
187        self.window.maybe_wait_on_main(|w| w.is_document_edited())
188    }
189
190    #[inline]
191    fn set_document_edited(&self, edited: bool) {
192        self.window
193            .maybe_queue_on_main(move |w| w.set_document_edited(edited))
194    }
195
196    #[inline]
197    fn set_option_as_alt(&self, option_as_alt: OptionAsAlt) {
198        self.window
199            .maybe_queue_on_main(move |w| w.set_option_as_alt(option_as_alt))
200    }
201
202    #[inline]
203    fn option_as_alt(&self) -> OptionAsAlt {
204        self.window.maybe_wait_on_main(|w| w.option_as_alt())
205    }
206
207    #[inline]
208    fn set_unified_titlebar(&self, unified_titlebar: bool) {
209        self.window
210            .maybe_wait_on_main(|w| w.set_unified_titlebar(unified_titlebar))
211    }
212
213    #[inline]
214    fn unified_titlebar(&self) -> bool {
215        self.window.maybe_wait_on_main(|w| w.unified_titlebar())
216    }
217
218    #[inline]
219    fn set_colorspace(&self, colorspace: Colorspace) {
220        self.window
221            .maybe_queue_on_main(move |w| w.set_colorspace(colorspace))
222    }
223
224    #[inline]
225    fn set_traffic_light_position(&self, position: Option<(f64, f64)>) {
226        self.window
227            .maybe_queue_on_main(move |w| w.set_traffic_light_position(position))
228    }
229}
230
231/// Corresponds to `NSApplicationActivationPolicy`.
232#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)]
233pub enum ActivationPolicy {
234    /// Corresponds to `NSApplicationActivationPolicyRegular`.
235    #[default]
236    Regular,
237
238    /// Corresponds to `NSApplicationActivationPolicyAccessory`.
239    Accessory,
240
241    /// Corresponds to `NSApplicationActivationPolicyProhibited`.
242    Prohibited,
243}
244
245/// Additional methods on [`WindowAttributes`] that are specific to MacOS.
246///
247/// **Note:** Properties dealing with the titlebar will be overwritten by the
248/// [`WindowAttributes::with_decorations`] method:
249/// - `with_titlebar_transparent`
250/// - `with_title_hidden`
251/// - `with_titlebar_hidden`
252/// - `with_titlebar_buttons_hidden`
253/// - `with_fullsize_content_view`
254pub trait WindowAttributesExtMacOS {
255    /// Enables click-and-drag behavior for the entire window, not just the titlebar.
256    fn with_movable_by_window_background(
257        self,
258        movable_by_window_background: bool,
259    ) -> Self;
260    /// Makes the titlebar transparent and allows the content to appear behind it.
261    fn with_titlebar_transparent(self, titlebar_transparent: bool) -> Self;
262    /// Hides the window title.
263    fn with_title_hidden(self, title_hidden: bool) -> Self;
264    /// Hides the window titlebar.
265    fn with_titlebar_hidden(self, titlebar_hidden: bool) -> Self;
266    /// Hides the window titlebar buttons.
267    fn with_titlebar_buttons_hidden(self, titlebar_buttons_hidden: bool) -> Self;
268    /// Makes the window content appear behind the titlebar.
269    fn with_fullsize_content_view(self, fullsize_content_view: bool) -> Self;
270    fn with_disallow_hidpi(self, disallow_hidpi: bool) -> Self;
271    fn with_has_shadow(self, has_shadow: bool) -> Self;
272    /// Window accepts click-through mouse events.
273    fn with_accepts_first_mouse(self, accepts_first_mouse: bool) -> Self;
274    /// Defines the window tabbing identifier.
275    ///
276    /// <https://developer.apple.com/documentation/appkit/nswindow/1644704-tabbingidentifier>
277    fn with_tabbing_identifier(self, identifier: &str) -> Self;
278    /// Set how the <kbd>Option</kbd> keys are interpreted.
279    ///
280    /// See [`WindowExtMacOS::set_option_as_alt`] for details on what this means if set.
281    fn with_option_as_alt(self, option_as_alt: OptionAsAlt) -> Self;
282    /// See [`WindowExtMacOS::set_unified_titlebar`] for details on what this means if set.
283    fn with_unified_titlebar(self, unified_titlebar: bool) -> Self;
284    /// Sets the window's colorspace for wide color gamut support.
285    fn with_colorspace(self, colorspace: Colorspace) -> Self;
286    /// Sets the position of the traffic light buttons (close, minimize, maximize).
287    /// The position is specified as (x, y) coordinates in points from the top-left corner.
288    fn with_traffic_light_position(self, x: f64, y: f64) -> Self;
289}
290
291impl WindowAttributesExtMacOS for WindowAttributes {
292    #[inline]
293    fn with_movable_by_window_background(
294        mut self,
295        movable_by_window_background: bool,
296    ) -> Self {
297        self.platform_specific.movable_by_window_background =
298            movable_by_window_background;
299        self
300    }
301
302    #[inline]
303    fn with_titlebar_transparent(mut self, titlebar_transparent: bool) -> Self {
304        self.platform_specific.titlebar_transparent = titlebar_transparent;
305        self
306    }
307
308    #[inline]
309    fn with_titlebar_hidden(mut self, titlebar_hidden: bool) -> Self {
310        self.platform_specific.titlebar_hidden = titlebar_hidden;
311        self
312    }
313
314    #[inline]
315    fn with_titlebar_buttons_hidden(mut self, titlebar_buttons_hidden: bool) -> Self {
316        self.platform_specific.titlebar_buttons_hidden = titlebar_buttons_hidden;
317        self
318    }
319
320    #[inline]
321    fn with_title_hidden(mut self, title_hidden: bool) -> Self {
322        self.platform_specific.title_hidden = title_hidden;
323        self
324    }
325
326    #[inline]
327    fn with_fullsize_content_view(mut self, fullsize_content_view: bool) -> Self {
328        self.platform_specific.fullsize_content_view = fullsize_content_view;
329        self
330    }
331
332    #[inline]
333    fn with_disallow_hidpi(mut self, disallow_hidpi: bool) -> Self {
334        self.platform_specific.disallow_hidpi = disallow_hidpi;
335        self
336    }
337
338    #[inline]
339    fn with_has_shadow(mut self, has_shadow: bool) -> Self {
340        self.platform_specific.has_shadow = has_shadow;
341        self
342    }
343
344    #[inline]
345    fn with_accepts_first_mouse(mut self, accepts_first_mouse: bool) -> Self {
346        self.platform_specific.accepts_first_mouse = accepts_first_mouse;
347        self
348    }
349
350    #[inline]
351    fn with_tabbing_identifier(mut self, tabbing_identifier: &str) -> Self {
352        self.platform_specific
353            .tabbing_identifier
354            .replace(tabbing_identifier.to_string());
355        self
356    }
357
358    #[inline]
359    fn with_option_as_alt(mut self, option_as_alt: OptionAsAlt) -> Self {
360        self.platform_specific.option_as_alt = option_as_alt;
361        self
362    }
363
364    #[inline]
365    fn with_unified_titlebar(mut self, unified_titlebar: bool) -> Self {
366        self.platform_specific.unified_titlebar = unified_titlebar;
367        self
368    }
369
370    #[inline]
371    fn with_colorspace(mut self, colorspace: Colorspace) -> Self {
372        self.platform_specific.colorspace = Some(colorspace);
373        self
374    }
375
376    #[inline]
377    fn with_traffic_light_position(mut self, x: f64, y: f64) -> Self {
378        self.platform_specific.traffic_light_position = Some((x, y));
379        self
380    }
381}
382
383pub trait EventLoopBuilderExtMacOS {
384    /// Sets the activation policy for the application.
385    ///
386    /// It is set to [`ActivationPolicy::Regular`] by default.
387    ///
388    /// # Example
389    ///
390    /// Set the activation policy to "accessory".
391    ///
392    /// ```
393    /// use rio_window::event_loop::EventLoopBuilder;
394    /// #[cfg(target_os = "macos")]
395    /// use rio_window::platform::macos::{ActivationPolicy, EventLoopBuilderExtMacOS};
396    ///
397    /// let mut builder = EventLoopBuilder::new();
398    /// #[cfg(target_os = "macos")]
399    /// builder.with_activation_policy(ActivationPolicy::Accessory);
400    /// # if false { // We can't test this part
401    /// let event_loop = builder.build();
402    /// # }
403    /// ```
404    fn with_activation_policy(
405        &mut self,
406        activation_policy: ActivationPolicy,
407    ) -> &mut Self;
408
409    /// Used to control whether a default menubar menu is created.
410    ///
411    /// Menu creation is enabled by default.
412    ///
413    /// # Example
414    ///
415    /// Disable creating a default menubar.
416    ///
417    /// ```
418    /// use rio_window::event_loop::EventLoopBuilder;
419    /// #[cfg(target_os = "macos")]
420    /// use rio_window::platform::macos::EventLoopBuilderExtMacOS;
421    ///
422    /// let mut builder = EventLoopBuilder::new();
423    /// #[cfg(target_os = "macos")]
424    /// builder.with_default_menu(false);
425    /// # if false { // We can't test this part
426    /// let event_loop = builder.build();
427    /// # }
428    /// ```
429    fn with_default_menu(&mut self, enable: bool) -> &mut Self;
430
431    /// Used to prevent the application from automatically activating when launched if
432    /// another application is already active.
433    ///
434    /// The default behavior is to ignore other applications and activate when launched.
435    fn with_activate_ignoring_other_apps(&mut self, ignore: bool) -> &mut Self;
436}
437
438impl<T> EventLoopBuilderExtMacOS for EventLoopBuilder<T> {
439    #[inline]
440    fn with_activation_policy(
441        &mut self,
442        activation_policy: ActivationPolicy,
443    ) -> &mut Self {
444        self.platform_specific.activation_policy = activation_policy;
445        self
446    }
447
448    #[inline]
449    fn with_default_menu(&mut self, enable: bool) -> &mut Self {
450        self.platform_specific.default_menu = enable;
451        self
452    }
453
454    #[inline]
455    fn with_activate_ignoring_other_apps(&mut self, ignore: bool) -> &mut Self {
456        self.platform_specific.activate_ignoring_other_apps = ignore;
457        self
458    }
459}
460
461/// Additional methods on [`MonitorHandle`] that are specific to MacOS.
462pub trait MonitorHandleExtMacOS {
463    /// Returns the identifier of the monitor for Cocoa.
464    fn native_id(&self) -> u32;
465    /// Returns a pointer to the NSScreen representing this monitor.
466    fn ns_screen(&self) -> Option<*mut c_void>;
467}
468
469impl MonitorHandleExtMacOS for MonitorHandle {
470    #[inline]
471    fn native_id(&self) -> u32 {
472        self.inner.native_identifier()
473    }
474
475    fn ns_screen(&self) -> Option<*mut c_void> {
476        // SAFETY: We only use the marker to get a pointer
477        let mtm = unsafe { objc2_foundation::MainThreadMarker::new_unchecked() };
478        self.inner
479            .ns_screen(mtm)
480            .map(|s| objc2::rc::Retained::as_ptr(&s) as _)
481    }
482}
483
484/// Additional methods on [`ActiveEventLoop`] that are specific to macOS.
485pub trait ActiveEventLoopExtMacOS {
486    /// Hide the entire application. In most applications this is typically triggered with
487    /// Command-H.
488    fn hide_application(&self);
489    /// Hide the other applications. In most applications this is typically triggered with
490    /// Command+Option-H.
491    fn hide_other_applications(&self);
492    /// Set whether the system can automatically organize windows into tabs.
493    ///
494    /// <https://developer.apple.com/documentation/appkit/nswindow/1646657-allowsautomaticwindowtabbing>
495    fn set_allows_automatic_window_tabbing(&self, enabled: bool);
496    /// Returns whether the system can automatically organize windows into tabs.
497    fn allows_automatic_window_tabbing(&self) -> bool;
498}
499
500impl ActiveEventLoopExtMacOS for ActiveEventLoop {
501    fn hide_application(&self) {
502        self.p.hide_application()
503    }
504
505    fn hide_other_applications(&self) {
506        self.p.hide_other_applications()
507    }
508
509    fn set_allows_automatic_window_tabbing(&self, enabled: bool) {
510        self.p.set_allows_automatic_window_tabbing(enabled);
511    }
512
513    fn allows_automatic_window_tabbing(&self) -> bool {
514        self.p.allows_automatic_window_tabbing()
515    }
516}
517
518/// Option as alt behavior.
519///
520/// The default is `None`.
521#[derive(Default, Debug, Clone, Copy, PartialEq, Eq)]
522pub enum OptionAsAlt {
523    /// The left `Option` key is treated as `Alt`.
524    OnlyLeft,
525
526    /// The right `Option` key is treated as `Alt`.
527    OnlyRight,
528
529    /// Both `Option` keys are treated as `Alt`.
530    Both,
531
532    /// No special handling is applied for `Option` key.
533    #[default]
534    None,
535}