Skip to main content

mitsuami_appkit/backend/
mod.rs

1//! The [`Backend`] implementation.
2
3mod apply;
4mod capture;
5mod create;
6mod fonts;
7mod group;
8mod handle;
9mod images;
10mod input;
11mod measure;
12mod menus;
13mod native_state;
14mod perform;
15mod props;
16mod scrolling;
17mod selection;
18mod split_button;
19mod windows;
20
21use std::cell::RefCell;
22use std::collections::{HashMap, HashSet};
23use std::rc::Rc;
24
25use mitsuami_core::a11y::{A11yAction, ActionError};
26use mitsuami_core::backend::{
27    Appearance, Backend, CaptureError, EventSink, Image, MeasureRequest, NativeState, PlatformMetrics, SyntheticInput,
28};
29use mitsuami_core::services::MenuEntry;
30use mitsuami_core::{
31    AppIcon, AppInfo, ButtonRole, ButtonStyle, Color, Command, CustomProps, FontWeight, ImageFit, ImageSource,
32    Modality, NodeId, Opaque, Orientation, RowKey, ScrollAxes, Size, TabsStyle, TextStyle, Truncation, WidgetKind,
33};
34use objc2::rc::Retained;
35use objc2::{AnyThread, MainThreadMarker, Message};
36use objc2_app_kit::{
37    NSApplication, NSBox, NSButton, NSControl, NSImage, NSImageView, NSPopUpButton, NSProgressIndicator, NSSlider,
38    NSSwitch, NSTextField, NSView, NSWindow,
39};
40use objc2_foundation::{NSBundle, NSData, NSString};
41
42use crate::classes::{ActionTarget, ClosureTarget, DrawnView, EdgeScrollView, HostView, ViewMap, WindowDelegate};
43use crate::custom::ErasedRender;
44use crate::number_field::NumberField;
45use crate::radio::RadioGroup;
46use crate::sidebar::{Sidebar, Split};
47use crate::surface::SurfaceView;
48use crate::tabs::Tabs;
49use crate::toolbar::Toolbar;
50
51pub(crate) use capture::capturing;
52use fonts::metrics;
53use group::group_probe_like;
54pub(crate) use images::ns_image;
55pub(crate) use split_button::is_press as is_split_button_press;
56
57/// How the backend behaves; apps and tests want different things.
58#[derive(Clone, Debug)]
59pub struct BackendOptions {
60    /// Order windows front once their first layout is applied. Tests keep
61    /// windows offscreen: layout, events and capture all work without it.
62    pub show_windows: bool,
63    /// Keep a log of applied commands (for tests).
64    pub record_commands: bool,
65    /// Force this appearance, so captures are comparable across machines
66    /// regardless of system settings.
67    pub appearance: Option<Appearance>,
68    /// Use a private pasteboard instead of the system clipboard (tests).
69    pub private_clipboard: bool,
70    /// Take this as the user's language, and write numbers and dates as
71    /// its region does, in UTC, whatever the system's settings (tests).
72    pub locale: Option<String>,
73}
74
75impl Default for BackendOptions {
76    fn default() -> Self {
77        BackendOptions {
78            show_windows: true,
79            record_commands: false,
80            appearance: None,
81            private_clipboard: false,
82            locale: None,
83        }
84    }
85}
86
87enum Widget {
88    Window {
89        window: Retained<NSWindow>,
90        host: Retained<HostView>,
91        _delegate: Retained<WindowDelegate>,
92        /// Made when the first toolbar item arrives, or the sidebar.
93        toolbar: Option<Toolbar>,
94        /// The window's content beside its sidebar, while it has one.
95        split: Option<Split>,
96    },
97    Host(Retained<HostView>),
98    Popover(crate::popover::Popover),
99    /// A layout host with an `NSBox` behind its children, the box's size.
100    Group {
101        host: Retained<HostView>,
102        frame: Retained<NSBox>,
103    },
104    Sidebar(Sidebar),
105    SplitView(crate::split_view::SplitView),
106    Tabs(Tabs),
107    DocumentTabs(crate::document_tabs::DocumentTabs),
108    Label(Retained<NSTextField>),
109    Field(Retained<NSTextField>),
110    TextArea(crate::text_area::TextArea),
111    Button(Retained<NSButton>),
112    Checkbox(Retained<NSButton>),
113    Switch(Retained<NSSwitch>),
114    Select(Retained<NSPopUpButton>),
115    RadioGroup(RadioGroup),
116    /// A pull-down: its first item is the title it shows, then the app's
117    /// menu, whose items call the target. A menu built as it opens has
118    /// the opener as its delegate.
119    MenuButton {
120        popup: Retained<NSPopUpButton>,
121        target: Retained<ClosureTarget>,
122        sent: Vec<MenuEntry>,
123        opener: Option<Retained<crate::classes::MenuOpener>>,
124    },
125    SplitButton(split_button::SplitButton),
126    /// A slider, and the step it was given: AppKit steps by tick marks,
127    /// which only approximate one that doesn't divide the range.
128    Slider {
129        slider: Retained<NSSlider>,
130        step: Option<f64>,
131    },
132    NumberInput(Retained<NumberField>),
133    ColorWell(Retained<objc2_app_kit::NSColorWell>),
134    Progress(Retained<NSProgressIndicator>),
135    /// A spinning indicator, and whether it's animating: AppKit can't say.
136    Spinner {
137        indicator: Retained<NSProgressIndicator>,
138        running: bool,
139    },
140    Separator(Retained<NSBox>),
141    Image(Retained<NSImageView>),
142    Icon(Retained<NSImageView>),
143    FileIcon(Retained<NSImageView>),
144    GpuSurface(Retained<SurfaceView>),
145    Scroll(Retained<EdgeScrollView>),
146    List(crate::list::List),
147    /// A custom widget with an AppKit render, and the props it last got.
148    Custom {
149        view: Retained<NSView>,
150        render: Rc<dyn ErasedRender>,
151        props: CustomProps,
152    },
153    /// A drawn custom widget.
154    Drawn {
155        view: Retained<DrawnView>,
156        props: CustomProps,
157    },
158    /// A native view from app code, and the last `Prop::Native` it got.
159    Native {
160        view: Retained<NSView>,
161        measure: Option<NativeMeasure>,
162        last: Opaque,
163    },
164}
165
166type NativeMeasure = Rc<dyn Fn(&NSView, &MeasureRequest) -> Size>;
167
168impl Widget {
169    fn view(&self) -> &NSView {
170        match self {
171            Widget::Window { host, .. } => host,
172            Widget::Host(v) | Widget::Group { host: v, .. } => v,
173            Widget::Popover(popover) => &popover.host,
174            Widget::Label(v) | Widget::Field(v) => v,
175            Widget::TextArea(area) => &area.scroll,
176            Widget::Button(v) | Widget::Checkbox(v) => v,
177            Widget::Switch(v) => v,
178            Widget::Select(v) | Widget::MenuButton { popup: v, .. } => v,
179            Widget::SplitButton(b) => &b.control,
180            Widget::RadioGroup(group) => &group.stack,
181            Widget::Slider { slider, .. } => slider,
182            Widget::NumberInput(v) => v,
183            Widget::ColorWell(v) => v,
184            Widget::Progress(v) => v,
185            Widget::Spinner { indicator, .. } => indicator,
186            Widget::Separator(v) => v,
187            Widget::Image(v) | Widget::Icon(v) | Widget::FileIcon(v) => v,
188            Widget::GpuSurface(v) => v,
189            Widget::Scroll(v) => v,
190            Widget::List(list) => &list.scroll,
191            Widget::Sidebar(sidebar) => &sidebar.scroll,
192            Widget::Tabs(tabs) => &tabs.view,
193            Widget::SplitView(split) => &split.view,
194            Widget::DocumentTabs(tabs) => &tabs.view,
195            Widget::Custom { view, .. } | Widget::Native { view, .. } => view,
196            Widget::Drawn { view, .. } => view,
197        }
198    }
199
200    fn control(&self) -> Option<&NSControl> {
201        match self {
202            Widget::Label(v) | Widget::Field(v) => Some(v),
203            Widget::Button(v) | Widget::Checkbox(v) => Some(v),
204            Widget::Switch(v) => Some(v),
205            Widget::Select(v) | Widget::MenuButton { popup: v, .. } => Some(v),
206            Widget::SplitButton(b) => Some(&b.control),
207            Widget::Slider { slider, .. } => Some(slider),
208            Widget::ColorWell(v) => Some(v),
209            // Its field: what's focused, and what text styles apply to.
210            Widget::NumberInput(n) => Some(n.field()),
211            // Its buttons each: see `RadioGroup`.
212            // A text view isn't a control: see `enabled`.
213            Widget::Window { .. }
214            | Widget::RadioGroup(_)
215            | Widget::TextArea(_)
216            | Widget::Progress(_)
217            | Widget::Spinner { .. }
218            | Widget::Separator(_)
219            | Widget::Image(_)
220            | Widget::Icon(_)
221            | Widget::FileIcon(_)
222            | Widget::GpuSurface(_)
223            | Widget::Host(_)
224            | Widget::Popover(_)
225            | Widget::Group { .. }
226            | Widget::Scroll(_)
227            | Widget::List(_)
228            | Widget::Sidebar(_)
229            | Widget::Tabs(_)
230            | Widget::SplitView(_)
231            | Widget::DocumentTabs(_)
232            | Widget::Custom { .. }
233            | Widget::Drawn { .. }
234            | Widget::Native { .. } => None,
235        }
236    }
237
238    /// The view that takes keyboard focus: a list's table, not its scroll
239    /// view.
240    fn key_view(&self) -> Retained<NSView> {
241        match self {
242            Widget::List(list) => Retained::into_super(Retained::into_super(list.table.clone())),
243            Widget::Sidebar(sidebar) => Retained::into_super(Retained::into_super(sidebar.table.clone())),
244            Widget::NumberInput(n) => Retained::into_super(Retained::into_super(n.field().retain())),
245            Widget::RadioGroup(group) => group.key_view(),
246            Widget::TextArea(area) => Retained::into_super(Retained::into_super(area.text.clone())),
247            widget => widget.view().retain(),
248        }
249    }
250
251    /// Whether a control or text area takes input; `None` for the rest.
252    fn enabled(&self) -> Option<bool> {
253        match self {
254            Widget::TextArea(area) => Some(area.enabled()),
255            Widget::DocumentTabs(tabs) => Some(tabs.enabled()),
256            widget => widget.control().map(|c| c.isEnabled()),
257        }
258    }
259}
260
261struct Node {
262    kind: WidgetKind,
263    widget: Widget,
264    /// Controls only hold weak references to their target and delegate.
265    _target: Option<Retained<ActionTarget>>,
266    /// A search field's suggestions, made with the first.
267    suggestions: Option<std::rc::Rc<crate::suggestions::Suggestions>>,
268    /// A search field: the app said when it searches.
269    search_on_return: bool,
270    /// Action targets of native renders and native views.
271    _targets: Vec<Retained<ClosureTarget>>,
272    parent: Option<NodeId>,
273    /// Row hosts: which row of their list they show.
274    row: Option<RowKey>,
275    /// Cell hosts: which column of their table's row they show.
276    column: Option<usize>,
277    /// Props AppKit can't report back faithfully.
278    text_style: Option<TextStyle>,
279    /// Labels: what the app gave, which the font and colour are made of
280    /// (read back from the label, but only once given).
281    weight: Option<FontWeight>,
282    italic: Option<bool>,
283    text_color: Option<Color>,
284    align: bool,
285    /// Labels: where the app cut them off, which a label of several lines
286    /// doesn't show.
287    truncation: Option<Truncation>,
288    role: Option<ButtonRole>,
289    button_style: Option<ButtonStyle>,
290    /// Text fields: the error the app gave, which AppKit has no state
291    /// for, and the description it gave, which the error replaces as the
292    /// field's help while there is one.
293    error: Option<Option<String>>,
294    help: Option<String>,
295    /// Tabs: the style the app chose, which this platform doesn't have,
296    /// and the icons it gave, which an `NSTabView` doesn't draw.
297    tabs_style: Option<TabsStyle>,
298    tab_icons: Option<Vec<String>>,
299    /// Sliders: whether the app gave an `Orientation`. Separators: which
300    /// way they run, which an `NSBox` takes from its frame's shape.
301    orientation: Option<Orientation>,
302    /// Checkboxes: whether the app gave `Mixed`, and the `Checked` the box
303    /// shows when it isn't mixed.
304    mixed: Option<bool>,
305    checked: bool,
306    /// Scroll views: the axes they scroll, and whether they show scroll
307    /// bars. Without scrollers, AppKit can't tell which axes scroll.
308    scroll_axes: ScrollAxes,
309    scroll_bars: bool,
310    /// Images: what they show and how they fit, which AppKit can't give
311    /// back (the fit only if the app chose one).
312    image: Option<ImageSource>,
313    fit: Option<ImageFit>,
314    /// Icons and buttons: the icon's name and size, which AppKit can't
315    /// give back (a symbol image has no name), and whether the app gave
316    /// `IconOnly`.
317    icon: Option<String>,
318    /// The app's own icon, if the app set one (`None` inside: unset).
319    vector_icon: Option<Option<mitsuami_core::VectorIcon>>,
320    icon_size: Option<f32>,
321    icon_only: Option<bool>,
322    /// File icons: the file, whether the app asked for a thumbnail, and
323    /// where the icon comes from, which an image view can't give back.
324    file: Option<std::path::PathBuf>,
325    thumbnail: Option<bool>,
326    file_lookup: Option<mitsuami_core::FileLookup>,
327    /// Windows: modal, and the window they belong to.
328    modal: Option<(Option<NodeId>, Modality)>,
329    /// The app's raw settings, run after every other prop.
330    tweak: Option<Opaque>,
331    /// Hosts: whether the core set a `FileDrop` (the host has the rest).
332    file_drop: bool,
333    /// The context menu the app gave, if it gave one (AppKit can't tell
334    /// radio items from check items, nor keep roles), and the target of
335    /// its items, which only hold weak references to it.
336    context_menu: Option<(Vec<MenuEntry>, Retained<ClosureTarget>)>,
337    /// A context menu built as it opens: its delegate, and the menu the
338    /// views hold.
339    menu_on_open: Option<(Retained<crate::classes::MenuOpener>, Retained<objc2_app_kit::NSMenu>)>,
340    /// The owner of the tracking area that reports hover, and the area,
341    /// once the core asked for it.
342    hover: Option<(Retained<crate::classes::HoverTracker>, Retained<objc2_app_kit::NSTrackingArea>)>,
343    /// The target of the recognizer that reports double clicks, and the
344    /// recognizer, once the core asked for it.
345    double_click: Option<(Retained<crate::classes::Clicker>, Retained<objc2_app_kit::NSClickGestureRecognizer>)>,
346    click: Option<(Retained<crate::classes::Clicker>, Retained<objc2_app_kit::NSClickGestureRecognizer>)>,
347    /// Hosts: the app gave `Header`; its children are in the header's
348    /// own view (see `header`).
349    header: Option<crate::header::Header>,
350    /// Hosts: the header's edge, if the app chose one (it may come first).
351    header_edge: Option<mitsuami_core::HeaderEdge>,
352    /// Hosts: whether the app made it a sidebar pane, which this platform
353    /// leaves as it is.
354    sidebar_pane: Option<bool>,
355    /// Whether the app set `ClickThrough`, which the host holds.
356    click_through: bool,
357}
358
359struct State {
360    mtm: MainThreadMarker,
361    options: BackendOptions,
362    nodes: HashMap<NodeId, Node>,
363    /// Native view (by address) → node. Shared with window delegates, which
364    /// resolve the first responder; only ever borrowed briefly.
365    by_view: ViewMap,
366    events: EventSink,
367    log: Vec<Command>,
368    pending_show: Vec<NodeId>,
369    /// What waits for a window in `pending_show` to be shown: a dialog
370    /// asked for on it before its first layout (`when_shown`).
371    on_shown: Vec<(NodeId, Box<dyn FnOnce()>)>,
372    /// A window shown next activates the app: the user chose a tray item,
373    /// which doesn't activate it, or the app presented a window not shown
374    /// yet. Until the next windows are shown.
375    activate_on_show: bool,
376    /// The key view chain last built for each window.
377    focus_orders: HashMap<NodeId, Vec<NodeId>>,
378    /// The app's name, for the app menu.
379    app_name: Option<String>,
380    /// The app's id, which the tray icon's place is saved under.
381    pub(crate) app_id: Option<String>,
382    /// Where tab views put their pages, from the last metrics: measuring
383    /// one would otherwise make a tab view to probe each time.
384    tab_insets: std::cell::Cell<Option<mitsuami_core::Insets>>,
385    /// Where group boxes put their content, by how they're set up, from
386    /// probes made since the last metrics (see `group_probe_like`).
387    group_probes: RefCell<HashMap<group::ProbeKey, (mitsuami_core::Insets, f32)>>,
388    /// Each node's children, in no particular order (`Node::parent` the
389    /// other way).
390    children: HashMap<NodeId, Vec<NodeId>>,
391    /// The lists and windows the batch being applied touched, which are
392    /// laid out at its end (see `layout_touched`), and whether it touched
393    /// something that can bring any list into view (a tab view's page, a
394    /// scroll view's offset).
395    touched_lists: HashSet<NodeId>,
396    touched_windows: HashSet<NodeId>,
397    touched_all_lists: bool,
398}
399
400pub struct AppKitBackend {
401    state: Rc<RefCell<State>>,
402}
403
404/// Shared access to an [`AppKitBackend`] after it was moved into a `Ui`.
405#[derive(Clone)]
406pub struct AppKitHandle {
407    state: Rc<RefCell<State>>,
408}
409
410/// Where a checkbox or radio button puts its box: on the reading side,
411/// which AppKit takes from the app's direction, not the button's.
412pub(crate) fn toggle_image_position(
413    direction: objc2_app_kit::NSUserInterfaceLayoutDirection,
414) -> objc2_app_kit::NSCellImagePosition {
415    match direction {
416        objc2_app_kit::NSUserInterfaceLayoutDirection::RightToLeft => objc2_app_kit::NSCellImagePosition::ImageRight,
417        _ => objc2_app_kit::NSCellImagePosition::ImageLeft,
418    }
419}
420
421/// A field's text starts on its reading side; natural alignment would
422/// take the app's direction, not the field's.
423pub(crate) fn field_alignment(
424    direction: objc2_app_kit::NSUserInterfaceLayoutDirection,
425) -> objc2_app_kit::NSTextAlignment {
426    match direction {
427        objc2_app_kit::NSUserInterfaceLayoutDirection::RightToLeft => objc2_app_kit::NSTextAlignment::Right,
428        _ => objc2_app_kit::NSTextAlignment::Left,
429    }
430}
431
432pub(crate) fn ns(s: &str) -> Retained<NSString> {
433    NSString::from_str(s)
434}
435
436fn key(view: &NSView) -> usize {
437    view as *const NSView as usize
438}
439
440fn violation(command: &Command, problem: &str) -> ! {
441    panic!("appkit backend: protocol violation in {command:?}: {problem}")
442}
443
444impl AppKitBackend {
445    pub fn new(mtm: MainThreadMarker, options: BackendOptions) -> AppKitBackend {
446        AppKitBackend {
447            state: Rc::new(RefCell::new(State {
448                mtm,
449                options,
450                nodes: HashMap::new(),
451                by_view: ViewMap::default(),
452                events: EventSink::default(),
453                log: Vec::new(),
454                pending_show: Vec::new(),
455                on_shown: Vec::new(),
456                activate_on_show: false,
457                focus_orders: HashMap::new(),
458                app_name: None,
459                app_id: None,
460                tab_insets: std::cell::Cell::new(None),
461                group_probes: RefCell::default(),
462                children: HashMap::new(),
463                touched_lists: HashSet::new(),
464                touched_windows: HashSet::new(),
465                touched_all_lists: false,
466            })),
467        }
468    }
469
470    pub fn handle(&self) -> AppKitHandle {
471        AppKitHandle { state: self.state.clone() }
472    }
473}
474
475impl Backend for AppKitBackend {
476    fn init(&mut self, events: EventSink) {
477        self.state.borrow_mut().events = events;
478    }
479
480    /// The box's own, which a tweak may have changed (a title at the
481    /// bottom, other margins).
482    fn group_insets(&self, id: NodeId) -> Option<mitsuami_core::Insets> {
483        let state = self.state.borrow();
484        let Widget::Group { frame, .. } = &state.nodes.get(&id)?.widget else { return None };
485        Some(group_probe_like(&state.group_probes, frame).0)
486    }
487
488    fn metrics(&self) -> PlatformMetrics {
489        let state = self.state.borrow();
490        let metrics = metrics(state.mtm, state.options.appearance);
491        state.tab_insets.set(Some(metrics.tab_insets));
492        // Fonts, and so titles, may have changed.
493        state.group_probes.borrow_mut().clear();
494        metrics
495    }
496
497    fn apply(&mut self, batch: &[Command]) {
498        let mut state = self.state.borrow_mut();
499        for command in batch {
500            if state.options.record_commands {
501                state.log.push(command.clone());
502            }
503            state.apply(command);
504            state.note_touched(command);
505        }
506        state.layout_touched();
507        state.place_document_tabs();
508    }
509
510    fn measure(&mut self, id: NodeId, request: MeasureRequest) -> Size {
511        measure::measure(&self.state.borrow(), id, request)
512    }
513
514    fn perform(&mut self, id: NodeId, action: &A11yAction) -> Result<(), ActionError> {
515        self.perform_action(id, action)
516    }
517
518    fn synthesize(&mut self, id: NodeId, input: &SyntheticInput) -> Result<(), ActionError> {
519        self.synthesize_input(id, input)
520    }
521
522    fn native_state(&self, id: NodeId) -> Option<NativeState> {
523        native_state::native_state(&self.state.borrow(), id)
524    }
525
526    /// The id is the bundle's, and so is the icon if the bundle has one: a
527    /// bundle's icon has the sizes and variants (dark, tinted) that one
528    /// image doesn't. The name goes in the app menu; the menu bar's title
529    /// is the bundle's or the process's, which AppKit alone sets.
530    fn set_app_info(&mut self, info: &AppInfo) {
531        let mut state = self.state.borrow_mut();
532        state.app_name = info.name.clone();
533        state.app_id = info.id.clone();
534        let bundle = NSBundle::mainBundle();
535        let has_icon = ["CFBundleIconFile", "CFBundleIconName"]
536            .iter()
537            .any(|key| bundle.objectForInfoDictionaryKey(&ns(key)).is_some());
538        let image = info.icon.as_ref().filter(|_| !has_icon).and_then(app_icon_image);
539        if let Some(image) = image {
540            unsafe { NSApplication::sharedApplication(state.mtm).setApplicationIconImage(Some(&image)) };
541        }
542    }
543
544    fn locale(&self) -> std::rc::Rc<dyn mitsuami_core::l10n::PlatformLocale> {
545        std::rc::Rc::new(crate::locale::AppKitLocale::new(self.state.borrow().options.locale.as_deref()))
546    }
547
548    fn set_locale(&mut self, language: &mitsuami_core::l10n::LanguageIdentifier, right_to_left: bool) {
549        crate::locale::set_app_locale(language, right_to_left);
550    }
551
552    fn services(&self) -> Box<dyn mitsuami_core::services::Services> {
553        let state = self.state.borrow();
554        Box::new(crate::services::AppKitServices::new(state.mtm, self.handle(), state.options.private_clipboard))
555    }
556
557    fn capture(&mut self, id: NodeId, reply: mitsuami_core::services::Reply<Result<Image, CaptureError>>) {
558        // Drawing into a bitmap is synchronous on AppKit: answer right away.
559        reply(self.capture_now(id));
560    }
561}
562
563/// A colour well's colour, as the core keeps it: sRGB, opaque.
564pub(crate) fn opaque(color: &objc2_app_kit::NSColor) -> mitsuami_core::Color {
565    match native_state::rgba(color) {
566        mitsuami_core::Color::Rgba(r, g, b, _) => mitsuami_core::Color::rgb(r, g, b),
567        other => other,
568    }
569}
570
571/// An app icon as an image: a named one shows its image, as macOS has no
572/// icon theme, and one with a dark variant its light one, since macOS
573/// tints the tray's template image for the menu bar itself.
574pub(crate) fn app_icon_image(icon: &AppIcon) -> Option<Retained<NSImage>> {
575    match icon {
576        AppIcon::File(path) => NSImage::initWithContentsOfFile(NSImage::alloc(), &ns(&path.to_string_lossy())),
577        AppIcon::Bytes(bytes) => NSImage::initWithData(NSImage::alloc(), &NSData::with_bytes(bytes)),
578        AppIcon::Named { image, .. } => app_icon_image(image.as_ref()?),
579        AppIcon::Themed { light, .. } => app_icon_image(light),
580    }
581}