1mod 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#[derive(Clone, Debug)]
56pub struct BackendOptions {
57 pub show_windows: bool,
60 pub record_commands: bool,
62 pub appearance: Option<Appearance>,
65 pub private_clipboard: bool,
67 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 toolbar: Option<Toolbar>,
91 split: Option<Split>,
93 },
94 Host(Retained<HostView>),
95 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 MenuButton {
114 popup: Retained<NSPopUpButton>,
115 target: Retained<ClosureTarget>,
116 sent: Vec<MenuEntry>,
117 },
118 Slider {
121 slider: Retained<NSSlider>,
122 step: Option<f64>,
123 },
124 NumberInput(Retained<NumberField>),
125 Progress(Retained<NSProgressIndicator>),
126 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 Custom {
140 view: Retained<NSView>,
141 render: Rc<dyn ErasedRender>,
142 props: CustomProps,
143 },
144 Drawn {
146 view: Retained<DrawnView>,
147 props: CustomProps,
148 },
149 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 Widget::NumberInput(n) => Some(n.field()),
196 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 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 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 _target: Option<Retained<ActionTarget>>,
249 _targets: Vec<Retained<ClosureTarget>>,
251 parent: Option<NodeId>,
252 row: Option<RowKey>,
254 column: Option<usize>,
256 text_style: Option<TextStyle>,
258 weight: Option<FontWeight>,
261 italic: Option<bool>,
262 text_color: Option<Color>,
263 align: bool,
264 truncation: Option<Truncation>,
267 role: Option<ButtonRole>,
268 button_style: Option<ButtonStyle>,
269 tabs_style: Option<TabsStyle>,
272 tab_icons: Option<Vec<String>>,
273 orientation: Option<Orientation>,
276 mixed: Option<bool>,
279 checked: bool,
280 scroll_axes: ScrollAxes,
283 scroll_bars: bool,
284 image: Option<ImageSource>,
287 fit: Option<ImageFit>,
288 icon: Option<String>,
292 icon_size: Option<f32>,
293 icon_only: Option<bool>,
294 file: Option<std::path::PathBuf>,
297 thumbnail: Option<bool>,
298 modal: Option<(Option<NodeId>, Modality)>,
300 tweak: Option<Opaque>,
302 file_drop: bool,
304 context_menu: Option<(Vec<MenuEntry>, Retained<ClosureTarget>)>,
308 hover: Option<(Retained<crate::classes::HoverTracker>, Retained<objc2_app_kit::NSTrackingArea>)>,
311 double_click: Option<(Retained<crate::classes::DoubleClicker>, Retained<objc2_app_kit::NSClickGestureRecognizer>)>,
314 header: Option<crate::header::Header>,
317 header_edge: Option<mitsuami_core::HeaderEdge>,
319}
320
321struct State {
322 mtm: MainThreadMarker,
323 options: BackendOptions,
324 nodes: HashMap<NodeId, Node>,
325 by_view: ViewMap,
328 events: EventSink,
329 log: Vec<Command>,
330 pending_show: Vec<NodeId>,
331 focus_orders: HashMap<NodeId, Vec<NodeId>>,
333 app_name: Option<String>,
335 tab_insets: std::cell::Cell<Option<mitsuami_core::Insets>>,
338 group_probes: RefCell<HashMap<group::ProbeKey, (mitsuami_core::Insets, f32)>>,
341 children: HashMap<NodeId, Vec<NodeId>>,
344 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#[derive(Clone)]
359pub struct AppKitHandle {
360 state: Rc<RefCell<State>>,
361}
362
363pub(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
374pub(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 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 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 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 reply(self.capture_now(id));
512 }
513}