Skip to main content

mitsuami_appkit/backend/
windows.rs

1//! Windows: resizing them as the user does, showing them, and their modal loops.
2
3use block2::RcBlock;
4use mitsuami_core::{Modality, NodeId, Size};
5use objc2::rc::Retained;
6use objc2_app_kit::{NSApplication, NSEvent, NSEventModifierFlags, NSEventType, NSWindow, NSWindowStyleMask};
7use objc2_core_foundation::{CFRunLoop, kCFRunLoopCommonModes};
8use objc2_foundation::{NSPoint, NSSize};
9
10use super::{AppKitHandle, Widget};
11
12impl AppKitHandle {
13    /// Resizes a window's content like the user would, between its minimum
14    /// and maximum, as a drag goes (`setContentSize:` alone would go past
15    /// them); the window delegate reports it back as a `WindowResized` event.
16    pub fn resize_window(&self, window: NodeId, size: Size) {
17        let state = self.state.borrow();
18        let Some(Widget::Window { window, _delegate, .. }) = state.nodes.get(&window).map(|n| &n.widget) else {
19            return;
20        };
21        // The user can't resize a window without the resizable style.
22        if !window.styleMask().contains(NSWindowStyleMask::Resizable) {
23            return;
24        }
25        let (window, extra) = (window.clone(), _delegate.extra(window));
26        drop(state);
27        // Not `clamp`, which panics on a maximum below the minimum (a
28        // tweak's): the minimum wins, as it does in `at_least_min`.
29        let (min, max) = (window.contentMinSize(), window.contentMaxSize());
30        window.setContentSize(NSSize::new(
31            (size.width as f64 + extra.width).min(max.width).max(min.width),
32            (size.height as f64 + extra.height).min(max.height).max(min.height),
33        ));
34    }
35
36    /// Orders front windows whose first layout has been applied: a sheet
37    /// on the window it belongs to, a window in the app's modal loop, or
38    /// an ordinary window.
39    pub fn show_pending_windows(&self) {
40        let (pending, activate) = {
41            let mut state = self.state.borrow_mut();
42            (std::mem::take(&mut state.pending_show), std::mem::take(&mut state.activate_on_show))
43        };
44        for id in pending {
45            let Some(window) = self.ns_window(id) else { continue };
46            let modal = self.state.borrow().nodes.get(&id).and_then(|n| n.modal);
47            let owner = modal.and_then(|(owner, _)| owner).and_then(|owner| self.ns_window(owner));
48            match (modal.map(|(_, modality)| modality), owner) {
49                (Some(Modality::Window), Some(owner)) => owner.beginSheet_completionHandler(&window, None),
50                (Some(_), owner) => {
51                    match owner {
52                        Some(owner) => centre_on(&window, &owner),
53                        None => window.center(),
54                    }
55                    self.run_modal(id, window.clone());
56                }
57                (None, _) => {
58                    window.center();
59                    // Opened from the tray's menu, it comes forward with
60                    // the app, as menu bar apps' windows do; it would
61                    // otherwise open behind the active app's.
62                    if activate {
63                        NSApplication::sharedApplication(self.state.borrow().mtm).activate();
64                    }
65                    window.makeKeyAndOrderFront(None);
66                }
67            }
68            // Full screen asked for before it was shown.
69            if let Some(Widget::Window { _delegate, .. }) = self.state.borrow().nodes.get(&id).map(|n| &n.widget) {
70                _delegate.apply_full_screen(&window);
71            }
72            // The dialogs asked for on it before it was shown.
73            let waiting = {
74                let mut state = self.state.borrow_mut();
75                let (waiting, kept) = std::mem::take(&mut state.on_shown).into_iter().partition(|(w, _)| *w == id);
76                state.on_shown = kept;
77                waiting
78            };
79            for (_, run) in waiting {
80                run();
81            }
82        }
83    }
84
85    /// The user chose a tray item: a window it opens in the next turn
86    /// activates the app.
87    pub(crate) fn activate_on_show(&self) {
88        self.state.borrow_mut().activate_on_show = true;
89    }
90
91    /// Runs `run` once the window `on` has been shown: at once if it has
92    /// (or there's no window), else right after its first layout puts it
93    /// on screen. A sheet begun on a window not yet shown orders it in
94    /// where AppKit put it, the screen's bottom-left corner, and the
95    /// window's centring then moves it under the sheet, which puts it back
96    /// in the corner as it ends; a dialog asked for as an app starts waits
97    /// for its window instead.
98    pub(crate) fn when_shown(&self, on: Option<NodeId>, run: impl FnOnce() + 'static) {
99        let mut state = self.state.borrow_mut();
100        match on.filter(|id| state.pending_show.contains(id)) {
101            Some(id) => state.on_shown.push((id, Box::new(run))),
102            None => {
103                drop(state);
104                run();
105            }
106        }
107    }
108
109    /// Runs the app's modal loop for the window, once the current run-loop
110    /// turn is over: it's a nested loop, which mustn't start inside a
111    /// tick. The UI keeps ticking in it (the app's observer runs in the
112    /// modal panel mode too). It ends when the window is destroyed. Queued
113    /// in the common modes: a dialog opened from an app-modal window is
114    /// asked for inside that window's loop, in the modal panel mode, where
115    /// a default-mode block waits until the outer loop ends.
116    fn run_modal(&self, id: NodeId, window: Retained<NSWindow>) {
117        let state = self.state.clone();
118        let block = RcBlock::new(move || {
119            // Destroyed before it got to run.
120            if !state.borrow().nodes.contains_key(&id) {
121                return;
122            }
123            let mtm = state.borrow().mtm;
124            NSApplication::sharedApplication(mtm).runModalForWindow(&window);
125        });
126        if let Some(run_loop) = CFRunLoop::main() {
127            unsafe { run_loop.perform_block(kCFRunLoopCommonModes.map(|m| &**m), Some(&block)) };
128            run_loop.wake_up();
129        }
130    }
131
132    /// Escape hatch: the native window of a window node.
133    pub fn ns_window(&self, id: NodeId) -> Option<Retained<NSWindow>> {
134        match &self.state.borrow().nodes.get(&id)?.widget {
135            Widget::Window { window, .. } => Some(window.clone()),
136            _ => None,
137        }
138    }
139
140    /// The window node showing this native window.
141    pub(crate) fn window_node(&self, ns_window: &NSWindow) -> Option<NodeId> {
142        self.state.borrow().nodes.iter().find_map(|(id, node)| match &node.widget {
143            Widget::Window { window, .. } if std::ptr::eq(&**window, ns_window) => Some(*id),
144            _ => None,
145        })
146    }
147}
148
149/// Centres a window on another, as dialogs open over their window.
150fn centre_on(window: &NSWindow, owner: &NSWindow) {
151    let (own, frame) = (owner.frame(), window.frame());
152    window.setFrameOrigin(NSPoint::new(
153        (own.origin.x + (own.size.width - frame.size.width) / 2.0).round(),
154        (own.origin.y + (own.size.height - frame.size.height) / 2.0).round(),
155    ));
156}
157
158/// Runs `run` in the main run loop's next turn.
159pub(super) fn soon(run: Box<dyn FnOnce()>) {
160    let run = std::cell::Cell::new(Some(run));
161    let block = RcBlock::new(move || {
162        if let Some(run) = run.take() {
163            run();
164        }
165    });
166    if let Some(run_loop) = CFRunLoop::main() {
167        unsafe { run_loop.perform_block(kCFRunLoopCommonModes.map(|m| &**m), Some(&block)) };
168        run_loop.wake_up();
169    }
170}
171
172/// An empty event, which wakes the app's event loop.
173pub(super) fn post_empty_event(app: &NSApplication) {
174    let event = NSEvent::otherEventWithType_location_modifierFlags_timestamp_windowNumber_context_subtype_data1_data2(
175        NSEventType::ApplicationDefined,
176        NSPoint::new(0.0, 0.0),
177        NSEventModifierFlags::empty(),
178        0.0,
179        0,
180        None,
181        0,
182        0,
183        0,
184    );
185    if let Some(event) = event {
186        app.postEvent_atStart(&event, false);
187    }
188}
189
190/// In full screen, or moving into or out of it.
191pub(super) fn in_full_screen(window: &NSWindow) -> bool {
192    window.styleMask().contains(NSWindowStyleMask::FullScreen)
193}