mod apply;
mod capture;
mod create;
mod fonts;
mod group;
mod handle;
mod images;
mod input;
mod measure;
mod menus;
mod native_state;
mod perform;
mod props;
mod scrolling;
mod selection;
mod windows;
use std::cell::RefCell;
use std::collections::{HashMap, HashSet};
use std::rc::Rc;
use mitsuami_core::a11y::{A11yAction, ActionError};
use mitsuami_core::backend::{
Appearance, Backend, CaptureError, EventSink, Image, MeasureRequest, NativeState, PlatformMetrics, SyntheticInput,
};
use mitsuami_core::services::MenuEntry;
use mitsuami_core::{
AppIcon, AppInfo, ButtonRole, ButtonStyle, Color, Command, CustomProps, FontWeight, ImageFit, ImageSource,
Modality, NodeId, Opaque, Orientation, RowKey, ScrollAxes, Size, TabsStyle, TextStyle, Truncation, WidgetKind,
};
use objc2::rc::Retained;
use objc2::{AnyThread, MainThreadMarker, Message};
use objc2_app_kit::{
NSApplication, NSBox, NSButton, NSControl, NSImage, NSImageView, NSPopUpButton, NSProgressIndicator, NSSlider,
NSSwitch, NSTextField, NSView, NSWindow,
};
use objc2_foundation::{NSBundle, NSData, NSString};
use crate::classes::{ActionTarget, ClosureTarget, DrawnView, EdgeScrollView, HostView, ViewMap, WindowDelegate};
use crate::custom::ErasedRender;
use crate::number_field::NumberField;
use crate::radio::RadioGroup;
use crate::sidebar::{Sidebar, Split};
use crate::surface::SurfaceView;
use crate::tabs::Tabs;
use crate::toolbar::Toolbar;
use fonts::metrics;
use group::group_probe_like;
pub(crate) use images::ns_image;
#[derive(Clone, Debug)]
pub struct BackendOptions {
pub show_windows: bool,
pub record_commands: bool,
pub appearance: Option<Appearance>,
pub private_clipboard: bool,
pub locale: Option<String>,
}
impl Default for BackendOptions {
fn default() -> Self {
BackendOptions {
show_windows: true,
record_commands: false,
appearance: None,
private_clipboard: false,
locale: None,
}
}
}
enum Widget {
Window {
window: Retained<NSWindow>,
host: Retained<HostView>,
_delegate: Retained<WindowDelegate>,
toolbar: Option<Toolbar>,
split: Option<Split>,
},
Host(Retained<HostView>),
Group {
host: Retained<HostView>,
frame: Retained<NSBox>,
},
Sidebar(Sidebar),
Tabs(Tabs),
DocumentTabs(crate::document_tabs::DocumentTabs),
Label(Retained<NSTextField>),
Field(Retained<NSTextField>),
TextArea(crate::text_area::TextArea),
Button(Retained<NSButton>),
Checkbox(Retained<NSButton>),
Switch(Retained<NSSwitch>),
Select(Retained<NSPopUpButton>),
RadioGroup(RadioGroup),
MenuButton {
popup: Retained<NSPopUpButton>,
target: Retained<ClosureTarget>,
sent: Vec<MenuEntry>,
},
Slider {
slider: Retained<NSSlider>,
step: Option<f64>,
},
NumberInput(Retained<NumberField>),
Progress(Retained<NSProgressIndicator>),
Spinner {
indicator: Retained<NSProgressIndicator>,
running: bool,
},
Separator(Retained<NSBox>),
Image(Retained<NSImageView>),
Icon(Retained<NSImageView>),
FileIcon(Retained<NSImageView>),
GpuSurface(Retained<SurfaceView>),
Scroll(Retained<EdgeScrollView>),
List(crate::list::List),
Custom {
view: Retained<NSView>,
render: Rc<dyn ErasedRender>,
props: CustomProps,
},
Drawn {
view: Retained<DrawnView>,
props: CustomProps,
},
Native {
view: Retained<NSView>,
measure: Option<NativeMeasure>,
last: Opaque,
},
}
type NativeMeasure = Rc<dyn Fn(&NSView, &MeasureRequest) -> Size>;
impl Widget {
fn view(&self) -> &NSView {
match self {
Widget::Window { host, .. } => host,
Widget::Host(v) | Widget::Group { host: v, .. } => v,
Widget::Label(v) | Widget::Field(v) => v,
Widget::TextArea(area) => &area.scroll,
Widget::Button(v) | Widget::Checkbox(v) => v,
Widget::Switch(v) => v,
Widget::Select(v) | Widget::MenuButton { popup: v, .. } => v,
Widget::RadioGroup(group) => &group.stack,
Widget::Slider { slider, .. } => slider,
Widget::NumberInput(v) => v,
Widget::Progress(v) => v,
Widget::Spinner { indicator, .. } => indicator,
Widget::Separator(v) => v,
Widget::Image(v) | Widget::Icon(v) | Widget::FileIcon(v) => v,
Widget::GpuSurface(v) => v,
Widget::Scroll(v) => v,
Widget::List(list) => &list.scroll,
Widget::Sidebar(sidebar) => &sidebar.scroll,
Widget::Tabs(tabs) => &tabs.view,
Widget::DocumentTabs(tabs) => &tabs.view,
Widget::Custom { view, .. } | Widget::Native { view, .. } => view,
Widget::Drawn { view, .. } => view,
}
}
fn control(&self) -> Option<&NSControl> {
match self {
Widget::Label(v) | Widget::Field(v) => Some(v),
Widget::Button(v) | Widget::Checkbox(v) => Some(v),
Widget::Switch(v) => Some(v),
Widget::Select(v) | Widget::MenuButton { popup: v, .. } => Some(v),
Widget::Slider { slider, .. } => Some(slider),
Widget::NumberInput(n) => Some(n.field()),
Widget::Window { .. }
| Widget::RadioGroup(_)
| Widget::TextArea(_)
| Widget::Progress(_)
| Widget::Spinner { .. }
| Widget::Separator(_)
| Widget::Image(_)
| Widget::Icon(_)
| Widget::FileIcon(_)
| Widget::GpuSurface(_)
| Widget::Host(_)
| Widget::Group { .. }
| Widget::Scroll(_)
| Widget::List(_)
| Widget::Sidebar(_)
| Widget::Tabs(_)
| Widget::DocumentTabs(_)
| Widget::Custom { .. }
| Widget::Drawn { .. }
| Widget::Native { .. } => None,
}
}
fn key_view(&self) -> Retained<NSView> {
match self {
Widget::List(list) => Retained::into_super(Retained::into_super(Retained::into_super(list.table.clone()))),
Widget::Sidebar(sidebar) => Retained::into_super(Retained::into_super(sidebar.table.clone())),
Widget::NumberInput(n) => Retained::into_super(Retained::into_super(n.field().retain())),
Widget::RadioGroup(group) => group.key_view(),
Widget::TextArea(area) => Retained::into_super(Retained::into_super(area.text.clone())),
widget => widget.view().retain(),
}
}
fn enabled(&self) -> Option<bool> {
match self {
Widget::TextArea(area) => Some(area.enabled()),
Widget::DocumentTabs(tabs) => Some(tabs.enabled()),
widget => widget.control().map(|c| c.isEnabled()),
}
}
}
struct Node {
kind: WidgetKind,
widget: Widget,
_target: Option<Retained<ActionTarget>>,
_targets: Vec<Retained<ClosureTarget>>,
parent: Option<NodeId>,
row: Option<RowKey>,
column: Option<usize>,
text_style: Option<TextStyle>,
weight: Option<FontWeight>,
italic: Option<bool>,
text_color: Option<Color>,
align: bool,
truncation: Option<Truncation>,
role: Option<ButtonRole>,
button_style: Option<ButtonStyle>,
tabs_style: Option<TabsStyle>,
tab_icons: Option<Vec<String>>,
orientation: Option<Orientation>,
mixed: Option<bool>,
checked: bool,
scroll_axes: ScrollAxes,
scroll_bars: bool,
image: Option<ImageSource>,
fit: Option<ImageFit>,
icon: Option<String>,
icon_size: Option<f32>,
icon_only: Option<bool>,
file: Option<std::path::PathBuf>,
thumbnail: Option<bool>,
modal: Option<(Option<NodeId>, Modality)>,
tweak: Option<Opaque>,
file_drop: bool,
context_menu: Option<(Vec<MenuEntry>, Retained<ClosureTarget>)>,
hover: Option<(Retained<crate::classes::HoverTracker>, Retained<objc2_app_kit::NSTrackingArea>)>,
double_click: Option<(Retained<crate::classes::DoubleClicker>, Retained<objc2_app_kit::NSClickGestureRecognizer>)>,
header: Option<crate::header::Header>,
header_edge: Option<mitsuami_core::HeaderEdge>,
}
struct State {
mtm: MainThreadMarker,
options: BackendOptions,
nodes: HashMap<NodeId, Node>,
by_view: ViewMap,
events: EventSink,
log: Vec<Command>,
pending_show: Vec<NodeId>,
focus_orders: HashMap<NodeId, Vec<NodeId>>,
app_name: Option<String>,
tab_insets: std::cell::Cell<Option<mitsuami_core::Insets>>,
group_probes: RefCell<HashMap<group::ProbeKey, (mitsuami_core::Insets, f32)>>,
children: HashMap<NodeId, Vec<NodeId>>,
touched_lists: HashSet<NodeId>,
touched_windows: HashSet<NodeId>,
touched_all_lists: bool,
}
pub struct AppKitBackend {
state: Rc<RefCell<State>>,
}
#[derive(Clone)]
pub struct AppKitHandle {
state: Rc<RefCell<State>>,
}
pub(crate) fn toggle_image_position(
direction: objc2_app_kit::NSUserInterfaceLayoutDirection,
) -> objc2_app_kit::NSCellImagePosition {
match direction {
objc2_app_kit::NSUserInterfaceLayoutDirection::RightToLeft => objc2_app_kit::NSCellImagePosition::ImageRight,
_ => objc2_app_kit::NSCellImagePosition::ImageLeft,
}
}
pub(crate) fn field_alignment(
direction: objc2_app_kit::NSUserInterfaceLayoutDirection,
) -> objc2_app_kit::NSTextAlignment {
match direction {
objc2_app_kit::NSUserInterfaceLayoutDirection::RightToLeft => objc2_app_kit::NSTextAlignment::Right,
_ => objc2_app_kit::NSTextAlignment::Left,
}
}
pub(crate) fn ns(s: &str) -> Retained<NSString> {
NSString::from_str(s)
}
fn key(view: &NSView) -> usize {
view as *const NSView as usize
}
fn violation(command: &Command, problem: &str) -> ! {
panic!("appkit backend: protocol violation in {command:?}: {problem}")
}
impl AppKitBackend {
pub fn new(mtm: MainThreadMarker, options: BackendOptions) -> AppKitBackend {
AppKitBackend {
state: Rc::new(RefCell::new(State {
mtm,
options,
nodes: HashMap::new(),
by_view: ViewMap::default(),
events: EventSink::default(),
log: Vec::new(),
pending_show: Vec::new(),
focus_orders: HashMap::new(),
app_name: None,
tab_insets: std::cell::Cell::new(None),
group_probes: RefCell::default(),
children: HashMap::new(),
touched_lists: HashSet::new(),
touched_windows: HashSet::new(),
touched_all_lists: false,
})),
}
}
pub fn handle(&self) -> AppKitHandle {
AppKitHandle { state: self.state.clone() }
}
}
impl Backend for AppKitBackend {
fn init(&mut self, events: EventSink) {
self.state.borrow_mut().events = events;
}
fn group_insets(&self, id: NodeId) -> Option<mitsuami_core::Insets> {
let state = self.state.borrow();
let Widget::Group { frame, .. } = &state.nodes.get(&id)?.widget else { return None };
Some(group_probe_like(&state.group_probes, frame).0)
}
fn metrics(&self) -> PlatformMetrics {
let state = self.state.borrow();
let metrics = metrics(state.mtm, state.options.appearance);
state.tab_insets.set(Some(metrics.tab_insets));
state.group_probes.borrow_mut().clear();
metrics
}
fn apply(&mut self, batch: &[Command]) {
let mut state = self.state.borrow_mut();
for command in batch {
if state.options.record_commands {
state.log.push(command.clone());
}
state.apply(command);
state.note_touched(command);
}
state.layout_touched();
state.place_document_tabs();
}
fn measure(&mut self, id: NodeId, request: MeasureRequest) -> Size {
measure::measure(&self.state.borrow(), id, request)
}
fn perform(&mut self, id: NodeId, action: &A11yAction) -> Result<(), ActionError> {
self.perform_action(id, action)
}
fn synthesize(&mut self, id: NodeId, input: &SyntheticInput) -> Result<(), ActionError> {
self.synthesize_input(id, input)
}
fn native_state(&self, id: NodeId) -> Option<NativeState> {
native_state::native_state(&self.state.borrow(), id)
}
fn set_app_info(&mut self, info: &AppInfo) {
let mut state = self.state.borrow_mut();
state.app_name = info.name.clone();
let bundle = NSBundle::mainBundle();
let has_icon = ["CFBundleIconFile", "CFBundleIconName"]
.iter()
.any(|key| bundle.objectForInfoDictionaryKey(&ns(key)).is_some());
let image = info.icon.as_ref().filter(|_| !has_icon).and_then(|icon| match icon {
AppIcon::File(path) => NSImage::initWithContentsOfFile(NSImage::alloc(), &ns(&path.to_string_lossy())),
AppIcon::Bytes(bytes) => NSImage::initWithData(NSImage::alloc(), &NSData::with_bytes(bytes)),
});
if let Some(image) = image {
unsafe { NSApplication::sharedApplication(state.mtm).setApplicationIconImage(Some(&image)) };
}
}
fn locale(&self) -> std::rc::Rc<dyn mitsuami_core::l10n::PlatformLocale> {
std::rc::Rc::new(crate::locale::AppKitLocale::new(self.state.borrow().options.locale.as_deref()))
}
fn set_locale(&mut self, language: &mitsuami_core::l10n::LanguageIdentifier, right_to_left: bool) {
crate::locale::set_app_locale(language, right_to_left);
}
fn services(&self) -> Box<dyn mitsuami_core::services::Services> {
let state = self.state.borrow();
Box::new(crate::services::AppKitServices::new(state.mtm, self.handle(), state.options.private_clipboard))
}
fn capture(&mut self, id: NodeId, reply: mitsuami_core::services::Reply<Result<Image, CaptureError>>) {
reply(self.capture_now(id));
}
}