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