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 on_shown: Vec<(NodeId, Box<dyn FnOnce()>)>,
334 focus_orders: HashMap<NodeId, Vec<NodeId>>,
336 app_name: Option<String>,
338 tab_insets: std::cell::Cell<Option<mitsuami_core::Insets>>,
341 group_probes: RefCell<HashMap<group::ProbeKey, (mitsuami_core::Insets, f32)>>,
344 children: HashMap<NodeId, Vec<NodeId>>,
347 touched_lists: HashSet<NodeId>,
352 touched_windows: HashSet<NodeId>,
353 touched_all_lists: bool,
354}
355
356pub struct AppKitBackend {
357 state: Rc<RefCell<State>>,
358}
359
360#[derive(Clone)]
362pub struct AppKitHandle {
363 state: Rc<RefCell<State>>,
364}
365
366pub(crate) fn toggle_image_position(
369 direction: objc2_app_kit::NSUserInterfaceLayoutDirection,
370) -> objc2_app_kit::NSCellImagePosition {
371 match direction {
372 objc2_app_kit::NSUserInterfaceLayoutDirection::RightToLeft => objc2_app_kit::NSCellImagePosition::ImageRight,
373 _ => objc2_app_kit::NSCellImagePosition::ImageLeft,
374 }
375}
376
377pub(crate) fn field_alignment(
380 direction: objc2_app_kit::NSUserInterfaceLayoutDirection,
381) -> objc2_app_kit::NSTextAlignment {
382 match direction {
383 objc2_app_kit::NSUserInterfaceLayoutDirection::RightToLeft => objc2_app_kit::NSTextAlignment::Right,
384 _ => objc2_app_kit::NSTextAlignment::Left,
385 }
386}
387
388pub(crate) fn ns(s: &str) -> Retained<NSString> {
389 NSString::from_str(s)
390}
391
392fn key(view: &NSView) -> usize {
393 view as *const NSView as usize
394}
395
396fn violation(command: &Command, problem: &str) -> ! {
397 panic!("appkit backend: protocol violation in {command:?}: {problem}")
398}
399
400impl AppKitBackend {
401 pub fn new(mtm: MainThreadMarker, options: BackendOptions) -> AppKitBackend {
402 AppKitBackend {
403 state: Rc::new(RefCell::new(State {
404 mtm,
405 options,
406 nodes: HashMap::new(),
407 by_view: ViewMap::default(),
408 events: EventSink::default(),
409 log: Vec::new(),
410 pending_show: Vec::new(),
411 on_shown: Vec::new(),
412 focus_orders: HashMap::new(),
413 app_name: None,
414 tab_insets: std::cell::Cell::new(None),
415 group_probes: RefCell::default(),
416 children: HashMap::new(),
417 touched_lists: HashSet::new(),
418 touched_windows: HashSet::new(),
419 touched_all_lists: false,
420 })),
421 }
422 }
423
424 pub fn handle(&self) -> AppKitHandle {
425 AppKitHandle { state: self.state.clone() }
426 }
427}
428
429impl Backend for AppKitBackend {
430 fn init(&mut self, events: EventSink) {
431 self.state.borrow_mut().events = events;
432 }
433
434 fn group_insets(&self, id: NodeId) -> Option<mitsuami_core::Insets> {
437 let state = self.state.borrow();
438 let Widget::Group { frame, .. } = &state.nodes.get(&id)?.widget else { return None };
439 Some(group_probe_like(&state.group_probes, frame).0)
440 }
441
442 fn metrics(&self) -> PlatformMetrics {
443 let state = self.state.borrow();
444 let metrics = metrics(state.mtm, state.options.appearance);
445 state.tab_insets.set(Some(metrics.tab_insets));
446 state.group_probes.borrow_mut().clear();
448 metrics
449 }
450
451 fn apply(&mut self, batch: &[Command]) {
452 let mut state = self.state.borrow_mut();
453 for command in batch {
454 if state.options.record_commands {
455 state.log.push(command.clone());
456 }
457 state.apply(command);
458 state.note_touched(command);
459 }
460 state.layout_touched();
461 state.place_document_tabs();
462 }
463
464 fn measure(&mut self, id: NodeId, request: MeasureRequest) -> Size {
465 measure::measure(&self.state.borrow(), id, request)
466 }
467
468 fn perform(&mut self, id: NodeId, action: &A11yAction) -> Result<(), ActionError> {
469 self.perform_action(id, action)
470 }
471
472 fn synthesize(&mut self, id: NodeId, input: &SyntheticInput) -> Result<(), ActionError> {
473 self.synthesize_input(id, input)
474 }
475
476 fn native_state(&self, id: NodeId) -> Option<NativeState> {
477 native_state::native_state(&self.state.borrow(), id)
478 }
479
480 fn set_app_info(&mut self, info: &AppInfo) {
485 let mut state = self.state.borrow_mut();
486 state.app_name = info.name.clone();
487 let bundle = NSBundle::mainBundle();
488 let has_icon = ["CFBundleIconFile", "CFBundleIconName"]
489 .iter()
490 .any(|key| bundle.objectForInfoDictionaryKey(&ns(key)).is_some());
491 let image = info.icon.as_ref().filter(|_| !has_icon).and_then(|icon| match icon {
492 AppIcon::File(path) => NSImage::initWithContentsOfFile(NSImage::alloc(), &ns(&path.to_string_lossy())),
493 AppIcon::Bytes(bytes) => NSImage::initWithData(NSImage::alloc(), &NSData::with_bytes(bytes)),
494 });
495 if let Some(image) = image {
496 unsafe { NSApplication::sharedApplication(state.mtm).setApplicationIconImage(Some(&image)) };
497 }
498 }
499
500 fn locale(&self) -> std::rc::Rc<dyn mitsuami_core::l10n::PlatformLocale> {
501 std::rc::Rc::new(crate::locale::AppKitLocale::new(self.state.borrow().options.locale.as_deref()))
502 }
503
504 fn set_locale(&mut self, language: &mitsuami_core::l10n::LanguageIdentifier, right_to_left: bool) {
505 crate::locale::set_app_locale(language, right_to_left);
506 }
507
508 fn services(&self) -> Box<dyn mitsuami_core::services::Services> {
509 let state = self.state.borrow();
510 Box::new(crate::services::AppKitServices::new(state.mtm, self.handle(), state.options.private_clipboard))
511 }
512
513 fn capture(&mut self, id: NodeId, reply: mitsuami_core::services::Reply<Result<Image, CaptureError>>) {
514 reply(self.capture_now(id));
516 }
517}