mitsuami-appkit 2.5.1

AppKit (macOS) backend for mitsuami
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
//! Creating nodes: the native view for each kind of widget.

use std::rc::Rc;

use mitsuami_core::backend::Appearance;
use mitsuami_core::{Command, NodeId, ScrollAxes, TextStyle, UiEvent, WidgetKind, find_prop};
use objc2::rc::Retained;
use objc2::runtime::{AnyObject, ProtocolObject};
use objc2::{MainThreadOnly, msg_send, sel};
use objc2_app_kit::{
    NSAppearance, NSAppearanceCustomization, NSAppearanceNameAqua, NSAppearanceNameDarkAqua, NSAutoresizingMaskOptions,
    NSBackingStoreType, NSBox, NSBoxType, NSButton, NSButtonType, NSImageScaling, NSImageView, NSMenuItem,
    NSPopUpButton, NSProgressIndicator, NSProgressIndicatorStyle, NSScrollView, NSSearchField, NSSecureTextField,
    NSSlider, NSSwitch, NSTextField, NSViewBoundsDidChangeNotification, NSViewFrameDidChangeNotification,
    NSWindowStyleMask,
};
use objc2_foundation::{NSNotificationCenter, NSPoint, NSRect, NSSize};

use crate::classes::{ActionTarget, ClosureTarget, DrawnView, HostView, WindowDelegate};
use crate::custom::{AppKitCx, ErasedRender, NativePayload};
use crate::number_field::NumberField;
use crate::radio::RadioGroup;
use crate::sidebar::Sidebar;
use crate::surface::SurfaceView;
use crate::tabs::Tabs;

use super::fonts::font;
use super::group::group_box;
use super::menus::show_pull_down;
use super::{Node, State, Widget, key, ns, violation};

impl State {
    pub(super) fn create(&mut self, id: NodeId, kind: WidgetKind, command: &Command) {
        let mtm = self.mtm;
        let target = matches!(
            kind,
            WidgetKind::Button
                | WidgetKind::SplitButton
                | WidgetKind::ToggleButton
                | WidgetKind::Checkbox
                | WidgetKind::Switch
                | WidgetKind::Select
                | WidgetKind::Slider
                | WidgetKind::ColorWell
                | WidgetKind::TextInput
                | WidgetKind::PasswordInput
                | WidgetKind::SearchInput
                | WidgetKind::TextArea
                | WidgetKind::ScrollView
                | WidgetKind::List
                | WidgetKind::Table
                | WidgetKind::Tree
        )
        .then(|| ActionTarget::new(mtm, id, kind, self.events.clone()));
        let action = Some(sel!(fire:));
        let mut targets = Vec::new();
        let target_obj: Option<&AnyObject> = target.as_deref().map(|t| t.as_ref());
        let widget = match kind {
            WidgetKind::Window => {
                let style = NSWindowStyleMask::Titled
                    | NSWindowStyleMask::Closable
                    | NSWindowStyleMask::Miniaturizable
                    | NSWindowStyleMask::Resizable;
                // Our subclass, for Escape in a dialog (`NodeWindow`).
                let window: Retained<crate::classes::NodeWindow> = unsafe {
                    msg_send![
                        crate::classes::NodeWindow::alloc(mtm),
                        initWithContentRect: NSRect::new(NSPoint::new(0.0, 0.0), NSSize::new(400.0, 300.0)),
                        styleMask: style,
                        backing: NSBackingStoreType::Buffered,
                        defer: false,
                    ]
                };
                let window = window.into_super();
                unsafe { window.setReleasedWhenClosed(false) };
                // The core owns the Tab order (reading order, not geometry)
                // and sends it with SetFocusOrder.
                window.setAutorecalculatesKeyViewLoop(false);
                let host = HostView::new(mtm);
                window.setContentView(Some(&host));
                let delegate =
                    WindowDelegate::new(mtm, id, self.events.clone(), self.by_view.clone(), self.options.show_windows);
                window.setDelegate(Some(ProtocolObject::from_ref(&*delegate)));
                delegate.observe_focus(&window);
                if let Some(appearance) = self.options.appearance {
                    let name = match appearance {
                        Appearance::Light => unsafe { NSAppearanceNameAqua },
                        Appearance::Dark => unsafe { NSAppearanceNameDarkAqua },
                    };
                    window.setAppearance(NSAppearance::appearanceNamed(name).as_deref());
                }
                if self.options.show_windows {
                    self.pending_show.push(id);
                }
                Widget::Window { window, host, _delegate: delegate, toolbar: None, split: None }
            }
            WidgetKind::Sidebar => Widget::Sidebar(Sidebar::new(mtm, id, self.events.clone())),
            WidgetKind::RadioGroup => Widget::RadioGroup(RadioGroup::new(mtm, id, self.events.clone())),
            WidgetKind::Container | WidgetKind::ToolbarItem => Widget::Host(HostView::new(mtm)),
            WidgetKind::Popover => {
                Widget::Popover(crate::popover::Popover::new(mtm, id, self.events.clone(), self.options.show_windows))
            }
            WidgetKind::Group => {
                let host = HostView::new(mtm);
                let frame = group_box(mtm, NSSize::new(0.0, 0.0));
                frame.setAutoresizingMask(
                    NSAutoresizingMaskOptions::ViewWidthSizable | NSAutoresizingMaskOptions::ViewHeightSizable,
                );
                host.addSubview(&frame);
                Widget::Group { host, frame }
            }
            WidgetKind::Tabs => Widget::Tabs(Tabs::new(mtm, id, self.events.clone())),
            WidgetKind::Split => Widget::SplitView(crate::split_view::SplitView::new(mtm, id, self.events.clone())),
            WidgetKind::DocumentTabs => {
                Widget::DocumentTabs(crate::document_tabs::DocumentTabs::new(mtm, id, self.events.clone()))
            }
            WidgetKind::Custom(_) => {
                let Command::Create { props, .. } = command else { unreachable!() };
                let Some(custom) = find_prop!(props, Custom) else {
                    violation(command, "a custom widget needs its Prop::Custom")
                };
                match custom.native() {
                    Some(native) => {
                        let Some(render) = native.downcast_ref::<Rc<dyn ErasedRender>>().cloned() else {
                            violation(command, "the native render is not an AppKit one")
                        };
                        let mut cx = AppKitCx::new(mtm, id, self.events.clone(), &mut targets);
                        let view = render.create(custom.props(), &mut cx);
                        Widget::Custom { view, render, props: custom }
                    }
                    None => Widget::Drawn { view: DrawnView::new(mtm, id, self.events.clone()), props: custom },
                }
            }
            WidgetKind::Native => {
                let Command::Create { props, .. } = command else { unreachable!() };
                let Some(opaque) = find_prop!(props, Native) else {
                    violation(command, "a native view needs its Prop::Native")
                };
                let Some(payload) = opaque.downcast_ref::<NativePayload>() else {
                    violation(command, "the native view is not an AppKit one")
                };
                let Some(create) = payload.spec.create.borrow_mut().take() else {
                    violation(command, "this native view was already created")
                };
                let measure = payload.spec.measure.clone();
                let mut cx = AppKitCx::new(mtm, id, self.events.clone(), &mut targets);
                let view = create(&mut cx);
                payload.apply(&view);
                Widget::Native { view, measure, last: opaque }
            }
            WidgetKind::Text => {
                let label = NSTextField::wrappingLabelWithString(&ns(""), mtm);
                label.setSelectable(false);
                Widget::Label(label)
            }
            WidgetKind::Button => {
                Widget::Button(unsafe { NSButton::buttonWithTitle_target_action(&ns(""), target_obj, action, mtm) })
            }
            // A push button that stays in once clicked, with a darker bezel
            // while it's in (macOS 26).
            WidgetKind::ToggleButton => {
                let button = unsafe { NSButton::buttonWithTitle_target_action(&ns(""), target_obj, action, mtm) };
                button.setButtonType(NSButtonType::PushOnPushOff);
                Widget::Button(button)
            }
            WidgetKind::Checkbox => {
                Widget::Checkbox(unsafe { NSButton::checkboxWithTitle_target_action(&ns(""), target_obj, action, mtm) })
            }
            WidgetKind::Switch => {
                let switch = NSSwitch::new(mtm);
                unsafe {
                    switch.setTarget(target_obj);
                    switch.setAction(action);
                }
                Widget::Switch(switch)
            }
            WidgetKind::Select => {
                let popup = NSPopUpButton::initWithFrame_pullsDown(
                    NSPopUpButton::alloc(mtm),
                    crate::classes::zero_rect(),
                    false,
                );
                unsafe {
                    popup.setTarget(target_obj);
                    popup.setAction(action);
                }
                Widget::Select(popup)
            }
            WidgetKind::MenuButton => {
                let popup = crate::classes::PullDown::create(mtm);
                let events = self.events.clone();
                let target = ClosureTarget::new(mtm, move |sender| {
                    if let Some(item) = sender.downcast_ref::<NSMenuItem>() {
                        events.emit(id, UiEvent::MenuItem(item.tag() as u32));
                    }
                });
                let widget = Widget::MenuButton { popup, target, sent: Vec::new(), opener: None };
                show_pull_down(&widget, "", None, None);
                widget
            }
            WidgetKind::SplitButton => Widget::SplitButton(super::split_button::SplitButton::new(
                mtm,
                id,
                self.events.clone(),
                target_obj,
                sel!(fire:),
            )),
            WidgetKind::Slider => {
                let slider = NSSlider::new(mtm);
                unsafe {
                    slider.setTarget(target_obj);
                    slider.setAction(action);
                }
                Widget::Slider { slider, step: None }
            }
            WidgetKind::NumberInput => Widget::NumberInput(NumberField::new(mtm, id, self.events.clone())),
            // AppKit's default style: a swatch, which opens the colour
            // panel; continuous, so a pick reports as it's dragged.
            WidgetKind::ColorWell => {
                let well = objc2_app_kit::NSColorWell::new(mtm);
                // Opaque colours only; `supportsAlpha` is macOS 14's.
                if objc2::runtime::NSObjectProtocol::respondsToSelector(&*well, sel!(setSupportsAlpha:)) {
                    well.setSupportsAlpha(false);
                }
                unsafe {
                    well.setTarget(target_obj);
                    well.setAction(action);
                }
                Widget::ColorWell(well)
            }
            // Not editable, framed or animated: what `NSImageView` is
            // made as.
            WidgetKind::Image => Widget::Image(NSImageView::new(mtm)),
            // At the symbol's own size, which its configuration sets.
            WidgetKind::Icon => {
                let view = NSImageView::new(mtm);
                view.setImageScaling(NSImageScaling::ScaleNone);
                Widget::Icon(view)
            }
            // Scaled to its square, which its thumbnail may not fill.
            WidgetKind::FileIcon => {
                let view = NSImageView::new(mtm);
                view.setImageScaling(NSImageScaling::ScaleProportionallyUpOrDown);
                Widget::FileIcon(view)
            }
            WidgetKind::GpuSurface => {
                let (view, handle) = SurfaceView::new(mtm, id, self.events.clone());
                self.events.emit(id, UiEvent::SurfaceReady(handle));
                Widget::GpuSurface(view)
            }
            WidgetKind::Progress => {
                let progress = NSProgressIndicator::new(mtm);
                progress.setMinValue(0.0);
                progress.setMaxValue(1.0);
                Widget::Progress(progress)
            }
            WidgetKind::Spinner => {
                let indicator = NSProgressIndicator::new(mtm);
                indicator.setStyle(NSProgressIndicatorStyle::Spinning);
                indicator.setIndeterminate(true);
                // Stopped, it shows nothing, as the other platforms' do.
                indicator.setDisplayedWhenStopped(false);
                Widget::Spinner { indicator, running: false }
            }
            // It runs the long way of its frame, which the layout gives.
            WidgetKind::Separator => {
                let line = NSBox::new(mtm);
                line.setBoxType(NSBoxType::Separator);
                Widget::Separator(line)
            }
            WidgetKind::TextInput => {
                // No target-action: submit comes from the delegate (Return
                // only), edits from `controlTextDidChange:`.
                let field = NSTextField::textFieldWithString(&ns(""), mtm);
                if let Some(target) = &target {
                    // SAFETY: the node keeps the target alive as long as the field.
                    unsafe { field.setDelegate(Some(ProtocolObject::from_ref(&**target))) };
                }
                Widget::Field(field)
            }
            WidgetKind::PasswordInput => {
                // A text field whose cell and field editor hide the text;
                // the rest is a text field's, delegate included.
                // `textFieldWithString:` is inherited: called on the secure
                // class, it makes a secure field set up as a text field.
                // SAFETY: the class method returns an autoreleased instance
                // of the class it's called on.
                let field: Retained<NSSecureTextField> = unsafe {
                    msg_send![<NSSecureTextField as objc2::ClassType>::class(), textFieldWithString: &*ns("")]
                };
                let field = field.into_super();
                if let Some(target) = &target {
                    // SAFETY: the node keeps the target alive as long as the field.
                    unsafe { field.setDelegate(Some(ProtocolObject::from_ref(&**target))) };
                }
                Widget::Field(field)
            }
            WidgetKind::SearchInput => {
                // Edits come from the delegate, as a text field's; searches
                // from the field's action, which AppKit sends when typing
                // pauses, on Return, and when the field is cleared, but not
                // for text set in code. Made as the password field is: a
                // search field's `init` leaves its cell unscrollable, so
                // the text didn't follow the caret past the field's end.
                // SAFETY: the class method returns an autoreleased instance
                // of the class it's called on.
                let field: Retained<NSSearchField> =
                    unsafe { msg_send![<NSSearchField as objc2::ClassType>::class(), textFieldWithString: &*ns("")] };
                if let Some(target) = &target {
                    // SAFETY: the node keeps the target alive as long as the field.
                    unsafe {
                        field.setTarget(Some(target.as_ref()));
                        field.setAction(action);
                        field.setDelegate(Some(ProtocolObject::from_ref(&**target)));
                    }
                }
                Widget::Field(field.into_super())
            }
            // Edits come from the delegate's `textDidChange:`.
            WidgetKind::TextArea => Widget::TextArea(crate::text_area::TextArea::new(
                mtm,
                target.as_deref().map(ProtocolObject::from_ref),
                &font(TextStyle::Body),
            )),
            WidgetKind::ScrollView => {
                let scroll = crate::classes::EdgeScrollView::new(mtm);
                scroll.setDrawsBackground(false);
                scroll.setAutohidesScrollers(true);
                // The core places the content; AppKit mustn't inset it for
                // the title bar on top of that.
                scroll.setAutomaticallyAdjustsContentInsets(false);
                observe_scrolling(&scroll, target.as_deref());
                Widget::Scroll(scroll)
            }
            WidgetKind::List | WidgetKind::Table => {
                let list = crate::list::List::new(mtm, id, self.events.clone(), kind == WidgetKind::Table);
                observe_scrolling(&list.scroll, target.as_deref());
                Widget::List(list)
            }
            WidgetKind::Tree => {
                let list = crate::list::List::new_tree(mtm, id, self.events.clone());
                observe_scrolling(&list.scroll, target.as_deref());
                Widget::List(list)
            }
            WidgetKind::Fragment => violation(command, "fragments are core-only"),
        };
        // The core assumes new nodes start with a zero frame and only sends
        // frames that differ; AppKit controls come with their own.
        if !matches!(widget, Widget::Window { .. }) {
            widget.view().setFrame(crate::classes::zero_rect());
        }
        self.by_view.borrow_mut().insert(key(widget.view()), id);
        self.nodes.insert(
            id,
            Node {
                kind,
                widget,
                _target: target,
                suggestions: None,
                search_on_return: false,
                _targets: targets,
                parent: None,
                row: None,
                column: None,
                text_style: None,
                weight: None,
                italic: None,
                text_color: None,
                align: false,
                truncation: None,
                role: None,
                button_style: None,
                error: None,
                help: None,
                tabs_style: None,
                tab_icons: None,
                orientation: None,
                scroll_axes: ScrollAxes::default(),
                scroll_bars: true,
                image: None,
                fit: None,
                icon: None,
                vector_icon: None,
                icon_size: None,
                icon_only: None,
                file: None,
                thumbnail: None,
                file_lookup: None,
                modal: None,
                mixed: None,
                checked: false,
                tweak: None,
                file_drop: false,
                context_menu: None,
                menu_on_open: None,
                hover: None,
                double_click: None,
                click: None,
                header: None,
                header_edge: None,
                sidebar_pane: None,
                click_through: false,
            },
        );
    }
}

/// Reports a scroll view's clip view moving, and its frame changing (the
/// core lays out the content in it), through the node's target.
fn observe_scrolling(scroll: &NSScrollView, target: Option<&ActionTarget>) {
    let clip = scroll.contentView();
    clip.setPostsBoundsChangedNotifications(true);
    clip.setPostsFrameChangedNotifications(true);
    if let Some(target) = target {
        let center = NSNotificationCenter::defaultCenter();
        // SAFETY: the target is removed as an observer when the node is destroyed.
        unsafe {
            center.addObserver_selector_name_object(
                target,
                sel!(scrolled:),
                Some(NSViewBoundsDidChangeNotification),
                Some(&clip),
            );
            center.addObserver_selector_name_object(
                target,
                sel!(viewportChanged:),
                Some(NSViewFrameDidChangeNotification),
                Some(&clip),
            );
        }
    }
}