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    /// The key view chain last built for each window.
373    focus_orders: HashMap<NodeId, Vec<NodeId>>,
374    /// The app's name, for the app menu.
375    app_name: Option<String>,
376    /// Where tab views put their pages, from the last metrics: measuring
377    /// one would otherwise make a tab view to probe each time.
378    tab_insets: std::cell::Cell<Option<mitsuami_core::Insets>>,
379    /// Where group boxes put their content, by how they're set up, from
380    /// probes made since the last metrics (see `group_probe_like`).
381    group_probes: RefCell<HashMap<group::ProbeKey, (mitsuami_core::Insets, f32)>>,
382    /// Each node's children, in no particular order (`Node::parent` the
383    /// other way).
384    children: HashMap<NodeId, Vec<NodeId>>,
385    /// The lists and windows the batch being applied touched, which are
386    /// laid out at its end (see `layout_touched`), and whether it touched
387    /// something that can bring any list into view (a tab view's page, a
388    /// scroll view's offset).
389    touched_lists: HashSet<NodeId>,
390    touched_windows: HashSet<NodeId>,
391    touched_all_lists: bool,
392}
393
394pub struct AppKitBackend {
395    state: Rc<RefCell<State>>,
396}
397
398/// Shared access to an [`AppKitBackend`] after it was moved into a `Ui`.
399#[derive(Clone)]
400pub struct AppKitHandle {
401    state: Rc<RefCell<State>>,
402}
403
404/// Where a checkbox or radio button puts its box: on the reading side,
405/// which AppKit takes from the app's direction, not the button's.
406pub(crate) fn toggle_image_position(
407    direction: objc2_app_kit::NSUserInterfaceLayoutDirection,
408) -> objc2_app_kit::NSCellImagePosition {
409    match direction {
410        objc2_app_kit::NSUserInterfaceLayoutDirection::RightToLeft => objc2_app_kit::NSCellImagePosition::ImageRight,
411        _ => objc2_app_kit::NSCellImagePosition::ImageLeft,
412    }
413}
414
415/// A field's text starts on its reading side; natural alignment would
416/// take the app's direction, not the field's.
417pub(crate) fn field_alignment(
418    direction: objc2_app_kit::NSUserInterfaceLayoutDirection,
419) -> objc2_app_kit::NSTextAlignment {
420    match direction {
421        objc2_app_kit::NSUserInterfaceLayoutDirection::RightToLeft => objc2_app_kit::NSTextAlignment::Right,
422        _ => objc2_app_kit::NSTextAlignment::Left,
423    }
424}
425
426pub(crate) fn ns(s: &str) -> Retained<NSString> {
427    NSString::from_str(s)
428}
429
430fn key(view: &NSView) -> usize {
431    view as *const NSView as usize
432}
433
434fn violation(command: &Command, problem: &str) -> ! {
435    panic!("appkit backend: protocol violation in {command:?}: {problem}")
436}
437
438impl AppKitBackend {
439    pub fn new(mtm: MainThreadMarker, options: BackendOptions) -> AppKitBackend {
440        AppKitBackend {
441            state: Rc::new(RefCell::new(State {
442                mtm,
443                options,
444                nodes: HashMap::new(),
445                by_view: ViewMap::default(),
446                events: EventSink::default(),
447                log: Vec::new(),
448                pending_show: Vec::new(),
449                on_shown: Vec::new(),
450                focus_orders: HashMap::new(),
451                app_name: None,
452                tab_insets: std::cell::Cell::new(None),
453                group_probes: RefCell::default(),
454                children: HashMap::new(),
455                touched_lists: HashSet::new(),
456                touched_windows: HashSet::new(),
457                touched_all_lists: false,
458            })),
459        }
460    }
461
462    pub fn handle(&self) -> AppKitHandle {
463        AppKitHandle { state: self.state.clone() }
464    }
465}
466
467impl Backend for AppKitBackend {
468    fn init(&mut self, events: EventSink) {
469        self.state.borrow_mut().events = events;
470    }
471
472    /// The box's own, which a tweak may have changed (a title at the
473    /// bottom, other margins).
474    fn group_insets(&self, id: NodeId) -> Option<mitsuami_core::Insets> {
475        let state = self.state.borrow();
476        let Widget::Group { frame, .. } = &state.nodes.get(&id)?.widget else { return None };
477        Some(group_probe_like(&state.group_probes, frame).0)
478    }
479
480    fn metrics(&self) -> PlatformMetrics {
481        let state = self.state.borrow();
482        let metrics = metrics(state.mtm, state.options.appearance);
483        state.tab_insets.set(Some(metrics.tab_insets));
484        // Fonts, and so titles, may have changed.
485        state.group_probes.borrow_mut().clear();
486        metrics
487    }
488
489    fn apply(&mut self, batch: &[Command]) {
490        let mut state = self.state.borrow_mut();
491        for command in batch {
492            if state.options.record_commands {
493                state.log.push(command.clone());
494            }
495            state.apply(command);
496            state.note_touched(command);
497        }
498        state.layout_touched();
499        state.place_document_tabs();
500    }
501
502    fn measure(&mut self, id: NodeId, request: MeasureRequest) -> Size {
503        measure::measure(&self.state.borrow(), id, request)
504    }
505
506    fn perform(&mut self, id: NodeId, action: &A11yAction) -> Result<(), ActionError> {
507        self.perform_action(id, action)
508    }
509
510    fn synthesize(&mut self, id: NodeId, input: &SyntheticInput) -> Result<(), ActionError> {
511        self.synthesize_input(id, input)
512    }
513
514    fn native_state(&self, id: NodeId) -> Option<NativeState> {
515        native_state::native_state(&self.state.borrow(), id)
516    }
517
518    /// The id is the bundle's, and so is the icon if the bundle has one: a
519    /// bundle's icon has the sizes and variants (dark, tinted) that one
520    /// image doesn't. The name goes in the app menu; the menu bar's title
521    /// is the bundle's or the process's, which AppKit alone sets.
522    fn set_app_info(&mut self, info: &AppInfo) {
523        let mut state = self.state.borrow_mut();
524        state.app_name = info.name.clone();
525        let bundle = NSBundle::mainBundle();
526        let has_icon = ["CFBundleIconFile", "CFBundleIconName"]
527            .iter()
528            .any(|key| bundle.objectForInfoDictionaryKey(&ns(key)).is_some());
529        let image = info.icon.as_ref().filter(|_| !has_icon).and_then(|icon| match icon {
530            AppIcon::File(path) => NSImage::initWithContentsOfFile(NSImage::alloc(), &ns(&path.to_string_lossy())),
531            AppIcon::Bytes(bytes) => NSImage::initWithData(NSImage::alloc(), &NSData::with_bytes(bytes)),
532        });
533        if let Some(image) = image {
534            unsafe { NSApplication::sharedApplication(state.mtm).setApplicationIconImage(Some(&image)) };
535        }
536    }
537
538    fn locale(&self) -> std::rc::Rc<dyn mitsuami_core::l10n::PlatformLocale> {
539        std::rc::Rc::new(crate::locale::AppKitLocale::new(self.state.borrow().options.locale.as_deref()))
540    }
541
542    fn set_locale(&mut self, language: &mitsuami_core::l10n::LanguageIdentifier, right_to_left: bool) {
543        crate::locale::set_app_locale(language, right_to_left);
544    }
545
546    fn services(&self) -> Box<dyn mitsuami_core::services::Services> {
547        let state = self.state.borrow();
548        Box::new(crate::services::AppKitServices::new(state.mtm, self.handle(), state.options.private_clipboard))
549    }
550
551    fn capture(&mut self, id: NodeId, reply: mitsuami_core::services::Reply<Result<Image, CaptureError>>) {
552        // Drawing into a bitmap is synchronous on AppKit: answer right away.
553        reply(self.capture_now(id));
554    }
555}
556
557/// A colour well's colour, as the core keeps it: sRGB, opaque.
558pub(crate) fn opaque(color: &objc2_app_kit::NSColor) -> mitsuami_core::Color {
559    match native_state::rgba(color) {
560        mitsuami_core::Color::Rgba(r, g, b, _) => mitsuami_core::Color::rgb(r, g, b),
561        other => other,
562    }
563}