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