1#![warn(missing_docs)]
63#![doc(html_logo_url = "https://raw.githubusercontent.com/lhassa8/ferrokit/main/assets/icon.png", html_favicon_url = "https://raw.githubusercontent.com/lhassa8/ferrokit/main/assets/icon-128.png")]
64
65mod appkit_views;
66mod canvas;
67mod charts;
68mod chrome;
69mod collection;
70mod commands;
71mod controls;
72mod dialogs;
73mod documents;
74mod frame;
75mod l10n;
76mod layout;
77mod material;
78mod browser;
79mod crash;
80mod failure;
81mod filter;
82mod form;
83mod media;
84mod quicklook;
85mod services;
86mod status;
87mod motion;
88mod native;
89mod related;
90mod widgets;
91mod interact;
92mod menu;
93mod models;
94mod outline;
95mod platform;
96mod popover;
97mod resource;
98mod signal;
99mod store;
100mod style;
101mod surface;
102mod syntax;
103mod task;
104mod transfer;
105mod undo;
106pub mod updates;
107mod value;
108pub mod testing;
109mod view;
110mod window_ref;
111
112use ferrokit_core::kept::{UiCell, UiLocal};
113use std::any::Any;
114use std::cell::{Cell, RefCell};
115use std::collections::HashMap;
116use std::rc::Rc;
117
118use objc2::runtime::ProtocolObject;
119use objc2::{MainThreadMarker, MainThreadOnly, define_class, msg_send};
120use objc2_app_kit::{
121 NSApplication, NSApplicationActivationPolicy, NSBackingStoreType, NSResponder, NSView, NSWindowStyleMask,
122};
123use objc2_foundation::NSObject;
124
125use platform::{Native, Platform};
126use objc2_foundation::{NSPoint, NSRect, NSSize, NSString};
127
128pub use ferrokit_core::{is_dark, system_colors};
129pub use frame::{FrameLoop, on_frame};
130pub use store::{Stored, read_stored, remove_stored, stored, write_stored};
131pub use undo::{set_undoable, undoable, undoable_in};
132pub use commands::{Command, can_perform, can_perform_in, focused_value, focused_value_in, focused_window, menu_command, perform, perform_in, toolbar_command};
133pub use resource::{Cancel, Load, Resource};
134pub use task::{Answer, Background, Sleep, Task, background, sleep, spawn_local};
135#[cfg(feature = "tokio")]
136pub use task::{OnRuntime, on_runtime};
137pub use signal::{Effect, Memo, Signal, after_batch, batch, untrack};
138pub use controls::{
139 ColorWell, ComboBox, DatePicker, SearchField, Segmented, TimePicker, color_well, combo_box, combo_box_with, date_picker, search_field, segmented, segmented_with, time_picker,
140 Checkbox, Image, Picker, Progress, Slider, Stepper, SymbolEffect, TextField, checkbox, image, image_data, image_file, picker, progress, secure_field, slider,
141 stepper, text_field, toggle,
142};
143pub use chrome::{MenuItem, Modifier, Split, customize_toolbar_item, dynamic_submenu, format_menu, submenu, ToolbarItem, menu_item, menu_separator, split, toolbar_button, toolbar_fixed_space, toolbar_group, toolbar_picker, toolbar_search, toolbar_space};
144pub use dialogs::{Alert, OpenOptions, Reply, SheetHandle, alert, alert_async, open_panel, open_panel_async, save_panel, save_panel_async, sheet, sheet_async, sheet_with};
145pub use documents::{
146 Document, DocumentType, choose_documents, document_edited, new_document, open_document, recent_documents, regain_access, set_recent_documents, remember_access, revert_document, save_document, save_document_as, show_welcome, welcome_window,
147};
148pub use models::{Table, TextEditor, table, text_editor};
149pub use outline::{Outline, TreeNode, outline, sidebar};
150pub use collection::{Collection, CollectionItem, ItemImage, collection};
151pub use ferrokit_core::table::{CellImage, CellStyle, Column, ColumnState, Sort, TableKey, TableModel};
152pub use ferrokit_core::text::{Color, Completion, TextModel, TextStyle};
153pub use syntax::Syntax;
154pub use style::{Font, Weight};
155pub use surface::Shadow;
156pub use material::{Glass, Material, has_liquid_glass};
157pub use widgets::{Gauge, Link, PathControl, RadioGroup, TabStyle, Tabs, TokenField, gauge, link, path_control, radio_group, rating, tabs, token_field};
158pub use media::{PdfView, VideoControls, VideoPlayer, WebPage, WebView, pdf_view, pdf_view_data, video_player, video_stream, web_view};
159pub use browser::{ColumnBrowser, column_browser};
160pub use crash::CrashReport;
161pub use updates::UpdateEvent;
162pub use failure::Failure;
163pub use filter::{FieldKind, FieldValue, Filter, FilterEditor, FilterField, FilterRule, FilterTest, Match, filter_editor};
164pub use form::{Form, FormRow, FormStyle, Section, disclosure, form, form_content, form_row, group_box, section};
165pub use quicklook::{Thumbnail, close_quick_look, is_quick_look_open, quick_look, thumbnail};
166pub use services::{FULL_DISK_ACCESS_SETTINGS, FileDates, Notification, SentNotification, ShareButton, ShareItem, asks_before_reading, cancel_notification, file_dates, has_full_disk_access, move_to_trash, notifications_supported, notify, open_url, pdf_data, print, reveal_in_finder, save_pdf, share_button};
167pub use status::MenuBarExtra;
168pub use motion::{Animation, Keyframes, Transition, animate, animated, animated_with, keyframes, reduce_motion, stop_animation};
169pub use popover::{Edge, toolbar_popover};
170pub use canvas::{Canvas, CanvasDrag, Painter, canvas};
171pub use native::{NativeView, native};
172pub use related::{RelatedFiles, related_files};
173pub use value::{IntoValue, Value};
174pub use transfer::{Clipboard, DragItem, WriteFile};
175pub use l10n::{format_date, format_number, format_number_for, local_day, local_day_start, today, weekday, language, parse_strings, plural_category, set_language, t, t_plural, t_with};
176pub use charts::{Chart, Format, Rule, Series, area_chart, bar_chart, heatmap, histogram, line_chart, pie_chart, scatter_chart, sparkline, stacked_bar_chart};
177pub use window_ref::WindowRef;
178pub use objc2::rc::Retained;
181use objc2_app_kit::NSWindow;
182pub use view::{
183 Align, AnyView, Axis, Cx, Dynamic, ForEach, Grid, Identifiable, Modified, Node, Size, Spacer, Stack, View, ViewExt, Views,
184 dynamic, for_each, grid, hstack, zstack, Layers, spacer, vstack, watch, Watch,
185};
186#[allow(deprecated)]
187pub use appkit_views::{Button, ButtonStyle, ControlSize, Divider, HelpButton, MenuButton, Scroll, Text, button, divider, help_button, menu_button, scroll, text};
188
189fn mtm() -> MainThreadMarker {
190 MainThreadMarker::new().expect("ferrokit must be used on the main thread")
191}
192
193pub struct Window {
195 title: String,
196 size: (f64, f64),
197 content: Option<Box<dyn FnOnce() -> Retained<NSView>>>,
198 view: Option<AnyView>,
199 toolbar: Vec<ToolbarItem>,
200 customizable_toolbar: Option<String>,
201 autosave: Option<String>,
202 fixed: bool,
203 responds: commands::Responds,
204 drops: Option<FileDrop>,
205 chrome: WindowChrome,
206 panel: Option<PanelStyle>,
207 tabbing: Option<(Tabbing, Option<String>)>,
208 full_screen: bool,
209 sidebar: Option<(AnyView, Option<Signal<bool>>)>,
211 inspector: Option<(AnyView, Option<Signal<bool>>)>,
212}
213
214#[derive(Debug, Clone, Copy, PartialEq, Eq)]
217#[non_exhaustive]
218pub enum Tabbing {
219 Automatic,
221 Preferred,
223 Disallowed,
225}
226
227#[derive(Debug, Clone, Copy, PartialEq, Eq)]
230#[non_exhaustive]
231pub enum PanelStyle {
232 Floating,
236 Utility,
238 Hud,
240}
241
242#[derive(Default)]
244struct WindowChrome {
245 toolbar_style: Option<ToolbarStyle>,
246 hide_title: bool,
247 transparent_title_bar: bool,
248 full_size_content: bool,
249 background: Option<Color>,
250}
251
252#[derive(Debug, Clone, Copy, PartialEq, Eq)]
254#[non_exhaustive]
255pub enum ToolbarStyle {
256 Unified,
258 UnifiedCompact,
260 Expanded,
263 Preference,
265}
266
267impl ToolbarStyle {
268 fn ns(self) -> objc2_app_kit::NSWindowToolbarStyle {
269 use objc2_app_kit::NSWindowToolbarStyle as S;
270 match self {
271 ToolbarStyle::Unified => S::Unified,
272 ToolbarStyle::UnifiedCompact => S::UnifiedCompact,
273 ToolbarStyle::Expanded => S::Expanded,
274 ToolbarStyle::Preference => S::Preference,
275 }
276 }
277}
278
279struct FileDrop {
281 extensions: Vec<String>,
283 action: Rc<dyn Fn(Vec<std::path::PathBuf>)>,
284}
285
286impl FileDrop {
287 fn accepted(&self, pasteboard: &objc2_app_kit::NSPasteboard) -> Vec<std::path::PathBuf> {
288 transfer::files_on(pasteboard)
289 .into_iter()
290 .filter(|p| {
291 self.extensions.is_empty()
292 || p.extension().is_some_and(|e| self.extensions.contains(&e.to_string_lossy().to_lowercase()))
293 })
294 .collect()
295 }
296}
297
298thread_local! {
299 static DROPS: UiCell<Vec<(usize, Rc<FileDrop>)>> = const { UiCell::new(Vec::new()) };
301}
302
303fn drop_operation(root: &RootView, info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>) -> objc2_app_kit::NSDragOperation {
304 use objc2_app_kit::NSDraggingInfo;
305 let takes = file_drop(root).is_some_and(|d| !d.accepted(&info.draggingPasteboard()).is_empty());
306 if takes { objc2_app_kit::NSDragOperation::Copy } else { objc2_app_kit::NSDragOperation::None }
307}
308
309fn perform_drop(root: &RootView, info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>) -> bool {
310 use objc2_app_kit::NSDraggingInfo;
311 let Some(drop) = file_drop(root) else { return false };
312 let paths = drop.accepted(&info.draggingPasteboard());
313 if paths.is_empty() {
314 return false;
315 }
316 let action = drop.action.clone();
318 let paths = RefCell::new(Some(paths));
319 later(move || {
320 if let Some(paths) = paths.borrow_mut().take() {
321 batch(|| action(paths));
322 }
323 });
324 true
325}
326
327fn file_drop(root: &RootView) -> Option<Rc<FileDrop>> {
328 DROPS.with_borrow(|d| d.iter().find(|(k, _)| *k == root as *const RootView as usize).map(|(_, f)| f.clone()))
329}
330
331impl Window {
332 pub fn on_drop_files(mut self, extensions: &[&str], action: impl Fn(Vec<std::path::PathBuf>) + 'static) -> Self {
337 self.drops = Some(FileDrop { extensions: extensions.iter().map(|e| e.to_lowercase()).collect(), action: Rc::new(action) });
338 self
339 }
340
341 pub fn new(title: &str) -> Self {
343 Window {
344 title: title.into(),
345 size: (800.0, 600.0),
346 content: None,
347 view: None,
348 toolbar: Vec::new(),
349 customizable_toolbar: None,
350 autosave: None,
351 fixed: false,
352 responds: commands::Responds::default(),
353 drops: None,
354 chrome: WindowChrome::default(),
355 panel: None,
356 tabbing: None,
357 full_screen: true,
358 sidebar: None,
359 inspector: None,
360 }
361 }
362
363 pub fn sidebar(mut self, view: impl View) -> Self {
370 self.sidebar = Some((AnyView::new(view), self.sidebar.and_then(|s| s.1)));
371 self
372 }
373
374 pub fn sidebar_hidden(mut self, hidden: &Signal<bool>) -> Self {
377 if let Some(s) = &mut self.sidebar {
378 s.1 = Some(*hidden);
379 }
380 self
381 }
382
383 pub fn inspector(mut self, view: impl View) -> Self {
388 self.inspector = Some((AnyView::new(view), self.inspector.and_then(|s| s.1)));
389 self
390 }
391
392 pub fn inspector_hidden(mut self, hidden: &Signal<bool>) -> Self {
394 if let Some(s) = &mut self.inspector {
395 s.1 = Some(*hidden);
396 }
397 self
398 }
399
400 pub fn tabbing(mut self, tabbing: Tabbing, group: Option<&str>) -> Self {
405 self.tabbing = Some((tabbing, group.map(Into::into)));
406 self
407 }
408
409 pub fn no_full_screen(mut self) -> Self {
412 self.full_screen = false;
413 self
414 }
415
416 pub fn panel(mut self, style: PanelStyle) -> Self {
420 self.panel = Some(style);
421 self
422 }
423
424 pub fn toolbar_style(mut self, style: ToolbarStyle) -> Self {
427 self.chrome.toolbar_style = Some(style);
428 self
429 }
430
431 pub fn hide_title(mut self) -> Self {
435 self.chrome.hide_title = true;
436 self
437 }
438
439 pub fn transparent_title_bar(mut self) -> Self {
442 self.chrome.transparent_title_bar = true;
443 self
444 }
445
446 pub fn full_size_content(mut self) -> Self {
452 self.chrome.full_size_content = true;
453 self.chrome.transparent_title_bar = true;
454 self
455 }
456
457 pub fn background(mut self, color: Color) -> Self {
460 self.chrome.background = Some(color);
461 self
462 }
463
464 pub fn size(mut self, width: f64, height: f64) -> Self {
466 self.size = (width, height);
467 self
468 }
469
470 pub fn view(mut self, view: impl View) -> Self {
472 self.view = Some(AnyView::new(view));
473 self
474 }
475
476 pub fn toolbar(mut self, items: Vec<ToolbarItem>) -> Self {
478 self.toolbar = items;
479 self
480 }
481
482 pub fn customizable_toolbar(mut self, name: &str) -> Self {
490 self.customizable_toolbar = Some(name.into());
491 self
492 }
493
494 pub fn on_command(mut self, command: Command, action: impl Fn() + 'static) -> Self {
498 self.responds.commands.push((command, commands::Handler::new(action, None)));
499 self
500 }
501
502 pub fn on_command_when(mut self, command: Command, enabled: impl Fn() -> bool + 'static, action: impl Fn() + 'static) -> Self {
505 self.responds.commands.push((command, commands::Handler::new(action, Some(Box::new(enabled)))));
506 self
507 }
508
509 pub fn remember_frame(mut self, name: &str) -> Self {
513 self.autosave = Some(name.into());
514 self
515 }
516
517 pub fn content(mut self, build: impl FnOnce() -> Retained<NSView> + 'static) -> Self {
519 self.content = Some(Box::new(build));
520 self
521 }
522
523 pub(crate) fn open(mut self, mtm: MainThreadMarker) -> Retained<NSWindow> {
524 let (sidebar, inspector) = (self.sidebar.take(), self.inspector.take());
525 let shell = (sidebar.is_some(), inspector.is_some());
526 if shell.0 {
528 self.chrome.full_size_content = true;
529 }
530 let rect = NSRect::new(NSPoint::new(0.0, 0.0), NSSize::new(self.size.0, self.size.1));
531 let mut style = if self.fixed {
532 NSWindowStyleMask::Titled | NSWindowStyleMask::Closable
533 } else {
534 NSWindowStyleMask::Titled | NSWindowStyleMask::Closable | NSWindowStyleMask::Miniaturizable | NSWindowStyleMask::Resizable
535 };
536 if self.chrome.full_size_content {
537 style |= NSWindowStyleMask::FullSizeContentView;
538 }
539 let window: Retained<NSWindow> = match self.panel {
540 None => {
541 unsafe { NSWindow::initWithContentRect_styleMask_backing_defer(NSWindow::alloc(mtm), rect, style, NSBackingStoreType::Buffered, false) }
543 }
544 Some(kind) => {
545 style.remove(NSWindowStyleMask::Miniaturizable);
546 match kind {
547 PanelStyle::Floating => {}
548 PanelStyle::Utility => style |= NSWindowStyleMask::UtilityWindow,
549 PanelStyle::Hud => style |= NSWindowStyleMask::UtilityWindow | NSWindowStyleMask::HUDWindow,
550 }
551 let panel =
552 objc2_app_kit::NSPanel::initWithContentRect_styleMask_backing_defer(objc2_app_kit::NSPanel::alloc(mtm), rect, style, NSBackingStoreType::Buffered, false);
553 panel.setFloatingPanel(true);
554 panel.setBecomesKeyOnlyIfNeeded(true);
555 panel.setHidesOnDeactivate(true);
556 panel.setExcludedFromWindowsMenu(true);
557 Retained::into_super(panel)
558 }
559 };
560 unsafe { window.setReleasedWhenClosed(false) };
563 window.setTitle(&NSString::from_str(&self.title));
564 if let Some((tabbing, group)) = &self.tabbing {
565 use objc2_app_kit::NSWindowTabbingMode;
566 window.setTabbingMode(match tabbing {
567 Tabbing::Automatic => NSWindowTabbingMode::Automatic,
568 Tabbing::Preferred => NSWindowTabbingMode::Preferred,
569 Tabbing::Disallowed => NSWindowTabbingMode::Disallowed,
570 });
571 if let Some(g) = group {
572 window.setTabbingIdentifier(&NSString::from_str(g));
573 }
574 }
575 if !self.full_screen {
576 use objc2_app_kit::NSWindowCollectionBehavior;
577 window.setCollectionBehavior((window.collectionBehavior() - NSWindowCollectionBehavior::FullScreenPrimary) | NSWindowCollectionBehavior::FullScreenNone);
578 }
579 let mut toolbar_delegate = None;
580 if !self.toolbar.is_empty() {
581 let delegate = chrome::install_toolbar(&window, self.toolbar, self.customizable_toolbar, shell);
582 toolbar_delegate = Some(delegate.clone());
583 WINDOW_EXTRAS.with_borrow_mut(|e| e.push((window.clone(), delegate)));
584 }
585 if let Some(style) = self.chrome.toolbar_style {
586 window.setToolbarStyle(style.ns());
587 if matches!(style, ToolbarStyle::Expanded | ToolbarStyle::Preference)
589 && let Some(t) = window.toolbar()
590 {
591 t.setDisplayMode(objc2_app_kit::NSToolbarDisplayMode::IconAndLabel);
592 }
593 }
594 if self.chrome.hide_title {
595 window.setTitleVisibility(objc2_app_kit::NSWindowTitleVisibility::Hidden);
596 }
597 window.setTitlebarAppearsTransparent(self.chrome.transparent_title_bar);
598 if let Some(color) = self.chrome.background {
599 window.setBackgroundColor(Some(&color.ns()));
600 }
601 let (delegate, undo) = undo::install(mtm, &window);
602 WINDOW_EXTRAS.with_borrow_mut(|e| e.push((window.clone(), delegate)));
603 window.setAutorecalculatesKeyViewLoop(true);
605 if let Some(build) = self.content {
606 window.setContentView(Some(&build()));
607 }
608 if let Some(view) = if shell.0 || shell.1 { self.view.take() } else { None } {
610 let make = |v: AnyView| {
611 let root: Retained<RootView> = unsafe { msg_send![RootView::alloc(mtm), initWithFrame: rect] };
613 let node = undo::building(&undo, || batch(|| Node::build_owned(v, &mut Cx::new(Retained::into_super(root.clone())))));
614 (root, node)
615 };
616 let (croot, mut cnode) = make(view);
617 {
618 let mut r = cnode.meta.responds.borrow_mut();
619 r.commands.splice(0..0, std::mem::take(&mut self.responds.commands));
620 r.values.splice(0..0, std::mem::take(&mut self.responds.values));
621 }
622 let controller = objc2_app_kit::NSSplitViewController::new(mtm);
623 let item = |root: &RootView, kind: u8| {
624 let vc = objc2_app_kit::NSViewController::new(mtm);
625 vc.setView(root);
626 match kind {
627 0 => objc2_app_kit::NSSplitViewItem::sidebarWithViewController(&vc),
628 2 => objc2_app_kit::NSSplitViewItem::inspectorWithViewController(&vc),
629 _ => objc2_app_kit::NSSplitViewItem::splitViewItemWithViewController(&vc),
630 }
631 };
632 let mut panes: Vec<(Retained<objc2_app_kit::NSSplitViewItem>, Option<Signal<bool>>)> = Vec::new();
633 let mut roots = Vec::new();
634 if let Some((v, hidden)) = sidebar {
637 let (root, node) = make(v);
638 root.setFrameSize(NSSize::new(220.0, rect.size.height));
639 let it = item(&root, 0);
640 it.setMinimumThickness(180.0);
641 it.setMaximumThickness(400.0);
642 controller.addSplitViewItem(&it);
643 panes.push((it, hidden));
644 roots.push((root, node));
645 }
646 let content_item = item(&croot, 1);
647 content_item.setMinimumThickness(300.0);
648 content_item.setHoldingPriority(objc2_app_kit::NSLayoutPriorityDefaultLow - 10.0);
649 croot.setFrameSize(NSSize::new((rect.size.width - 220.0 * f64::from(u8::from(shell.0)) - 260.0 * f64::from(u8::from(shell.1))).max(300.0), rect.size.height));
650 controller.addSplitViewItem(&content_item);
651 if let Some((v, hidden)) = inspector {
652 let (root, node) = make(v);
653 root.setFrameSize(NSSize::new(260.0, rect.size.height));
654 let it = item(&root, 2);
655 it.setMinimumThickness(220.0);
656 it.setMaximumThickness(420.0);
657 controller.addSplitViewItem(&it);
658 panes.push((it, hidden));
659 roots.push((root, node));
660 }
661 for (it, hidden) in &panes {
664 let Some(hidden) = *hidden else { continue };
665 it.setCollapsed(hidden.get_untracked());
666 let it = it.clone();
667 cnode.own(signal::Effect::new(move || {
668 let h = hidden.get();
669 if it.isCollapsed() != h {
670 unsafe {
672 let a: Retained<objc2::runtime::AnyObject> = msg_send![&*it, animator];
673 let () = msg_send![&*a, setCollapsed: h];
674 }
675 }
676 }));
677 }
678 let followed: Vec<(Retained<objc2_app_kit::NSSplitViewItem>, Signal<bool>)> = panes.iter().filter_map(|(i, h)| h.map(|h| (i.clone(), h))).collect();
679 if !followed.is_empty() {
680 let name = unsafe { objc2_app_kit::NSSplitViewDidResizeSubviewsNotification };
682 let observer = media::Observer::new(name, Some(&controller.splitView()), move || {
683 for (it, h) in &followed {
684 h.set_if_changed(it.isCollapsed());
685 }
686 });
687 cnode.hold(Rc::new(observer));
688 }
689 if let Some(drop) = self.drops.take() {
692 let drop = Rc::new(drop);
693 for root in std::iter::once(&croot).chain(roots.iter().map(|(r, _)| r)) {
694 root.registerForDraggedTypes(&objc2_foundation::NSArray::from_slice(&[unsafe { objc2_app_kit::NSPasteboardTypeFileURL }]));
696 DROPS.with_borrow_mut(|d| d.push((Retained::as_ptr(root) as usize, drop.clone())));
697 }
698 }
699 SHELL_ROOTS.with_borrow_mut(|s| s.push((Retained::as_ptr(&window) as usize, Retained::into_super(croot.clone()))));
700 SHELL_PANES.with_borrow_mut(|p| p.extend(std::iter::once(&croot).chain(roots.iter().map(|(r, _)| r)).map(|r| Retained::as_ptr(r) as usize)));
701 ROOTS.with_borrow_mut(|r| {
702 r.push((croot.clone(), cnode));
703 r.extend(roots);
704 });
705 window.setContentViewController(Some(&controller));
706 window.setContentSize(rect.size);
707 relayout_all();
708 }
709 if let Some(view) = self.view {
710 let root: Retained<RootView> = unsafe { msg_send![RootView::alloc(mtm), initWithFrame: rect] };
712 let node = undo::building(&undo, || batch(|| Node::build_owned(view, &mut Cx::new(Retained::into_super(root.clone())))));
714 {
715 let mut r = node.meta.responds.borrow_mut();
717 r.commands.splice(0..0, self.responds.commands);
718 r.values.splice(0..0, self.responds.values);
719 }
720 let sidebar = match &node.kind {
724 view::Kind::Split { split, panes, stacked: false, .. } if panes.len() >= 2 => Some(split.clone()),
725 _ => None,
726 };
727 ROOTS.with_borrow_mut(|r| r.push((root.clone(), node)));
728 if let Some(drop) = self.drops {
729 root.registerForDraggedTypes(&objc2_foundation::NSArray::from_slice(&[unsafe { objc2_app_kit::NSPasteboardTypeFileURL }]));
731 DROPS.with_borrow_mut(|d| d.push((Retained::as_ptr(&root) as usize, Rc::new(drop))));
732 }
733 window.setContentView(Some(&root));
734 relayout_all();
735 if let (Some(split), Some(delegate)) = (sidebar, toolbar_delegate.as_ref()) {
736 chrome::track_sidebar(&window, delegate, &split);
737 }
738 }
739 window.center();
740 let preview_name = (self.autosave.is_none() && preview_mode()).then(|| format!("ferrokit preview {}", self.title));
743 if let Some(name) = self.autosave.as_ref().or(preview_name.as_ref()) {
744 let name = NSString::from_str(name);
745 window.setFrameUsingName(&name);
747 window.setFrameAutosaveName(&name);
748 }
749 window
750 }
751}
752
753#[derive(Debug, Clone, PartialEq)]
755#[non_exhaustive]
756pub enum AppEvent {
757 AppearanceChanged,
760}
761
762type Handler = Rc<dyn Fn(AppEvent)>;
763
764define_class!(
765 #[unsafe(super(NSView, NSResponder, NSObject))]
768 #[thread_kind = MainThreadOnly]
769 #[name = "FerrokitRootView"]
770 struct RootView;
771
772 impl RootView {
773 #[unsafe(method(isFlipped))]
774 fn is_flipped(&self) -> bool {
775 true
776 }
777
778 #[unsafe(method(setFrameSize:))]
779 fn set_frame_size(&self, size: NSSize) {
780 crate::failure::guard("a window's content view (set_frame_size)", (), || {
781 let _: () = unsafe { msg_send![super(self), setFrameSize: size] };
782 relayout(self);
783 })
784 }
785
786 #[unsafe(method(draggingEntered:))]
787 fn dragging_entered(&self, info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>) -> objc2_app_kit::NSDragOperation {
788 crate::failure::guard("a window's content view (dragging_entered)", objc2_app_kit::NSDragOperation::None, || {
789 drop_operation(self, info)
790 })
791 }
792
793 #[unsafe(method(draggingUpdated:))]
794 fn dragging_updated(&self, info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>) -> objc2_app_kit::NSDragOperation {
795 crate::failure::guard("a window's content view (dragging_updated)", objc2_app_kit::NSDragOperation::None, || {
796 drop_operation(self, info)
797 })
798 }
799
800 #[unsafe(method(performDragOperation:))]
801 fn perform_drag(&self, info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>) -> objc2::runtime::Bool {
802 crate::failure::guard("a window's content view (perform_drag)", objc2::runtime::Bool::NO, || {
803 objc2::runtime::Bool::new(perform_drop(self, info))
804 })
805 }
806
807 #[unsafe(method(keyDown:))]
811 fn key_down(&self, event: &objc2_app_kit::NSEvent) {
812 crate::failure::guard("a window's content view (key_down)", (), || {
813 let window = self.window();
814 let escape = event.keyCode() == 53;
815 match window.filter(|w| escape && popover::is_popover_window(w)) {
816 Some(w) => {
817 let _: () = unsafe { msg_send![&*w, cancelOperation: Option::<&objc2::runtime::AnyObject>::None] };
818 }
819 None => {
820 let _: () = unsafe { msg_send![super(self), keyDown: event] };
821 }
822 }
823 })
824 }
825 }
826);
827
828thread_local! {
829 static ROOTS: UiCell<Vec<(Retained<RootView>, Node)>> = const { UiCell::new(Vec::new()) };
830 static IN_LAYOUT: Cell<bool> = const { Cell::new(false) };
831 static EXTRAS: UiCell<Vec<Retained<NSObject>>> = const { UiCell::new(Vec::new()) };
833 static WINDOW_EXTRAS: UiCell<Vec<(Retained<NSWindow>, Retained<NSObject>)>> = const { UiCell::new(Vec::new()) };
836 static LAYOUT_US: UiCell<Vec<f64>> = const { UiCell::new(Vec::new()) };
837 static LAYOUT_PASSES: Cell<u64> = const { Cell::new(0) };
838}
839
840fn relayout(root: &RootView) {
841 if ROOTS.try_with(|_| ()).is_err() || IN_LAYOUT.try_with(|_| ()).is_err() || LAYOUT_US.try_with(|_| ()).is_err() || LAYOUT_PASSES.try_with(|_| ()).is_err() {
844 return;
845 }
846 if IN_LAYOUT.with(Cell::get) {
847 return;
848 }
849 let t = std::time::Instant::now();
850 batch(|| {
854 struct Done;
856 impl Drop for Done {
857 fn drop(&mut self) {
858 let _ = IN_LAYOUT.try_with(|l| l.set(false));
859 }
860 }
861 IN_LAYOUT.with(|l| l.set(true));
862 let _done = Done;
863 ROOTS.with_borrow(|roots| {
864 for (view, node) in roots {
865 if std::ptr::eq(&**view, root) {
866 let b = view.bounds().size;
867 let window = view.window();
868 let scale = window.as_ref().map_or(2.0, |w| w.backingScaleFactor());
869 let top = window.as_deref().map_or(0.0, |w| title_bar_inset(w, view));
870 layout::mirrored(right_to_left(), b.width, || layout::place_under_bar(node, b.width, b.height, top, &layout::Snap(scale)));
871 }
872 }
873 });
874 });
875 LAYOUT_US.with_borrow_mut(|v| {
876 if v.len() >= 2 * LAYOUT_KEPT {
878 v.drain(..LAYOUT_KEPT);
879 }
880 v.push(t.elapsed().as_secs_f64() * 1e6);
881 });
882 LAYOUT_PASSES.with(|n| n.set(n.get() + 1));
883}
884
885fn title_bar_inset(window: &NSWindow, root: &RootView) -> f64 {
888 if !window.styleMask().contains(NSWindowStyleMask::FullSizeContentView) {
889 return 0.0;
890 }
891 let Some(content) = window.contentView() else { return 0.0 };
895 let key = root as *const RootView as usize;
896 let pane = SHELL_PANES.with_borrow(|p| p.contains(&key));
897 if !std::ptr::eq(&*content, &**root) && !pane {
898 return 0.0;
899 }
900 (content.bounds().size.height - window.contentLayoutRect().size.height).max(0.0)
901}
902
903thread_local! {
904 static FORCE_RTL: Cell<Option<bool>> = const { Cell::new(None) };
905}
906
907pub fn right_to_left() -> bool {
912 FORCE_RTL.with(Cell::get).unwrap_or_else(|| {
913 MainThreadMarker::new().is_some_and(|mtm| NSApplication::sharedApplication(mtm).userInterfaceLayoutDirection() == objc2_app_kit::NSUserInterfaceLayoutDirection::RightToLeft)
914 })
915}
916
917pub(crate) fn force_right_to_left(on: Option<bool>) {
919 FORCE_RTL.with(|f| f.set(on));
920}
921
922fn main_root(window: &NSWindow) -> Option<Retained<NSView>> {
925 let key = window as *const NSWindow as usize;
926 SHELL_ROOTS.with_borrow(|s| s.iter().find(|(w, _)| *w == key).map(|(_, r)| r.clone())).or_else(|| window.contentView())
927}
928
929pub(crate) fn root_meta(window: &NSWindow) -> Option<Rc<view::Meta>> {
931 let content = main_root(window)?;
932 ROOTS.with_borrow(|r| r.iter().find(|(v, _)| std::ptr::eq(&***v as *const NSView, &*content as *const NSView)).map(|(_, n)| n.meta.clone()))
933}
934
935pub(crate) fn drop_root(window: &NSWindow) {
938 let Some(content) = main_root(window) else { return };
939 let key = Retained::as_ptr(&content) as usize;
940 DROPS.with_borrow_mut(|d| d.retain(|(k, _)| *k != key));
941 let wkey = window as *const NSWindow as usize;
943 SHELL_ROOTS.with_borrow_mut(|s| s.retain(|(w, _)| *w != wkey));
944 let nodes: Vec<(Retained<RootView>, Node)> = ROOTS.with_borrow_mut(|r| {
945 let mut gone = Vec::new();
946 let mut i = 0;
947 while i < r.len() {
948 let mine = std::ptr::eq(&**r[i].0 as *const NSView, &*content as *const NSView) || r[i].0.window().is_some_and(|w| std::ptr::eq(&*w, window));
949 if mine {
950 gone.push(r.remove(i));
951 } else {
952 i += 1;
953 }
954 }
955 gone
956 });
957 SHELL_PANES.with_borrow_mut(|p| p.retain(|k| !nodes.iter().any(|(r, _)| Retained::as_ptr(r) as usize == *k)));
958 drop(nodes);
959 window.setContentViewController(None);
961}
962
963pub(crate) fn host_view(view: view::AnyView) -> (Retained<NSView>, NSSize) {
968 let mtm = mtm();
969 let root: Retained<RootView> = unsafe { msg_send![RootView::alloc(mtm), initWithFrame: NSRect::new(NSPoint::ZERO, NSSize::new(100.0, 100.0))] };
971 let node = batch(|| Node::build_owned(view, &mut Cx::new(Retained::into_super(root.clone()))));
972 let size = layout::ideal(&node);
973 ROOTS.with_borrow_mut(|r| r.push((root.clone(), node)));
974 root.setFrameSize(NSSize::new(size.w.ceil(), size.h.ceil()));
975 (Retained::into_super(root), NSSize::new(size.w.ceil(), size.h.ceil()))
976}
977
978pub(crate) fn hosted_ideal(root: &NSView) -> Option<NSSize> {
980 ROOTS.with_borrow(|r| {
981 let (_, node) = r.iter().find(|(v, _)| std::ptr::eq(&***v as *const NSView, root as *const NSView))?;
982 let s = layout::ideal(node);
983 Some(NSSize::new(s.w.ceil(), s.h.ceil()))
984 })
985}
986
987pub(crate) fn drop_hosted(root: &NSView) {
989 let node = ROOTS
992 .try_with(|r| {
993 let mut r = r.try_borrow_mut().ok()?;
994 let i = r.iter().position(|(v, _)| std::ptr::eq(&***v as *const NSView, root as *const NSView))?;
995 Some(r.remove(i))
996 })
997 .ok()
998 .flatten();
999 drop(node);
1000}
1001
1002pub(crate) fn in_layout() -> bool {
1004 IN_LAYOUT.with(Cell::get)
1005}
1006
1007pub(crate) fn relayout_now() {
1009 relayout_all();
1010}
1011
1012fn relayout_all() {
1013 view::LAYOUT_DIRTY.with(|d| d.set(false));
1014 let roots: Vec<Retained<RootView>> = ROOTS.with_borrow(|r| r.iter().map(|(v, _)| v.clone()).collect());
1015 for r in roots {
1016 relayout(&r);
1017 }
1018}
1019
1020const LAYOUT_KEPT: usize = 10_000;
1022
1023pub(crate) fn layout_times_us() -> Vec<f64> {
1026 LAYOUT_US.with_borrow(Clone::clone)
1027}
1028
1029pub(crate) fn layout_passes() -> u64 {
1032 LAYOUT_PASSES.with(Cell::get)
1033}
1034
1035thread_local! {
1036 static SHELL_ROOTS: UiCell<Vec<(usize, Retained<NSView>)>> = const { UiCell::new(Vec::new()) };
1039 static SHELL_PANES: UiCell<Vec<usize>> = const { UiCell::new(Vec::new()) };
1041 static HANDLERS: UiCell<Vec<Handler>> = const { UiCell::new(Vec::new()) };
1042 static WINDOWS: UiCell<Vec<Retained<NSWindow>>> = const { UiCell::new(Vec::new()) };
1043}
1044
1045pub struct App {
1047 name: String,
1048 windows: Vec<Window>,
1049 on_launch: Option<Box<dyn FnOnce()>>,
1050 menus: Vec<(String, Vec<MenuItem>)>,
1051 settings: Option<Window>,
1052 documents: Option<Box<dyn FnOnce()>>,
1053 extras: Vec<MenuBarExtra>,
1054 menu_bar_only: bool,
1055 welcome: Option<Rc<dyn Fn() -> Window>>,
1056 dock_menu: Option<Rc<dyn Fn() -> Vec<MenuItem>>>,
1057 open_url: Option<documents::OpenUrl>,
1058 crash_reports: Option<Box<dyn Fn(CrashReport)>>,
1059 about: Option<(String, Option<(String, String)>)>,
1060}
1061
1062impl App {
1063 pub fn new(name: &str) -> Self {
1065 failure::install();
1066 App { name: name.into(), windows: Vec::new(), on_launch: None, menus: Vec::new(), settings: None, documents: None, extras: Vec::new(), menu_bar_only: false, welcome: None, dock_menu: None, open_url: None, crash_reports: None, about: None }
1067 }
1068
1069 pub fn window(mut self, window: Window) -> Self {
1071 self.windows.push(window);
1072 self
1073 }
1074
1075 pub fn translations(self, tables: &[(&str, &str)]) -> Self {
1080 l10n::add_translations(tables);
1081 self
1082 }
1083
1084 pub fn menu(mut self, title: &str, items: Vec<MenuItem>) -> Self {
1091 self.menus.push((title.into(), items));
1092 self
1093 }
1094
1095 pub fn about(mut self, credits: &str, link: Option<(&str, &str)>) -> Self {
1099 self.about = Some((credits.into(), link.map(|(t, u)| (t.into(), u.into()))));
1100 self
1101 }
1102
1103 pub fn settings(mut self, window: Window) -> Self {
1107 self.settings = Some(window);
1108 self
1109 }
1110
1111 pub fn documents<T: Clone + PartialEq + 'static>(mut self, kind: DocumentType<T>) -> Self {
1117 self.documents = Some(Box::new(move || documents::install(kind)));
1118 self
1119 }
1120
1121 pub fn welcome(mut self, make: impl Fn() -> Window + 'static) -> Self {
1127 self.welcome = Some(Rc::new(make));
1128 self
1129 }
1130
1131 pub fn menu_bar_extra(mut self, extra: MenuBarExtra) -> Self {
1134 self.extras.push(extra);
1135 self
1136 }
1137
1138 pub fn menu_bar_only(mut self) -> Self {
1142 self.menu_bar_only = true;
1143 self
1144 }
1145
1146 pub fn dock_menu(mut self, items: impl Fn() -> Vec<MenuItem> + 'static) -> Self {
1150 self.dock_menu = Some(Rc::new(items));
1151 self
1152 }
1153
1154 pub fn on_open_url(mut self, f: impl Fn(&str) + 'static) -> Self {
1184 self.open_url = Some(Rc::new(f));
1185 self
1186 }
1187
1188 pub fn crash_reports(mut self, f: impl Fn(CrashReport) + 'static) -> Self {
1212 crash::install(&self.name);
1213 self.crash_reports = Some(Box::new(f));
1214 self
1215 }
1216
1217 pub fn on_launch(mut self, f: impl FnOnce() + 'static) -> Self {
1224 self.on_launch = Some(Box::new(f));
1225 self
1226 }
1227
1228 pub fn on_command(self, command: Command, action: impl Fn() + 'static) -> Self {
1231 commands::app_command(command, commands::Handler::new(action, None));
1232 self
1233 }
1234
1235 pub fn on_error(self, f: impl Fn(&Failure) + 'static) -> Self {
1247 failure::set_hook(f);
1248 self
1249 }
1250
1251 pub fn on_event(self, f: impl Fn(AppEvent) + 'static) -> Self {
1253 HANDLERS.with_borrow_mut(|h| h.push(Rc::new(f)));
1254 self
1255 }
1256
1257 pub fn run(self) {
1260 let mtm = mtm();
1261 let app = NSApplication::sharedApplication(mtm);
1262 app.setActivationPolicy(if self.menu_bar_only { NSApplicationActivationPolicy::Accessory } else { NSApplicationActivationPolicy::Regular });
1263 let settings = self.settings.map(|w| {
1264 SETTINGS.with_borrow_mut(|s| *s = Some(Err(w)));
1265 Retained::into_super(appkit_views::ActionTarget::new(mtm, || {
1266 open_settings_ns();
1267 }))
1268 });
1269 let about = self.about.map(|(credits, link)| Retained::into_super(appkit_views::ActionTarget::new(mtm, move || show_about(&credits, link.as_ref()))));
1270 let is_documents = self.documents.is_some();
1271 let mut menus = self.menus;
1272 let mut file_after = Vec::new();
1273 if let Some(install) = self.documents {
1274 install();
1275 let (above, after) = documents::file_items();
1276 file_after = after;
1277 match menus.iter_mut().find(|(t, _)| t == "File") {
1278 Some((_, items)) => {
1279 let own = std::mem::take(items);
1280 *items = above.into_iter().chain(own).collect();
1281 }
1282 None => menus.insert(0, ("File".into(), above)),
1283 }
1284 }
1285 let welcome = self.welcome.filter(|_| is_documents);
1286 let start_welcome = welcome.is_some() && self.windows.is_empty();
1287 let start_untitled = is_documents && self.windows.is_empty() && !start_welcome;
1288 let mut window_items = Vec::new();
1289 if let Some(make) = welcome {
1290 documents::set_welcome(make);
1291 window_items.push(menu_item(t_with("Welcome to {app}", &[("app", &self.name)]), || {
1292 show_welcome();
1293 }).key_with("1", &[Modifier::Shift]));
1294 }
1295 let updater = objc2::rc::autoreleasepool(|_| updates::start());
1297 let targets = menu::install(mtm, &self.name, menus, menu::AppTargets { about, settings, updater }, file_after, window_items);
1298 EXTRAS.with_borrow_mut(|e| e.extend(targets));
1299 for extra in self.extras {
1300 status::install(extra, &self.name);
1301 }
1302 if let Some(items) = self.dock_menu {
1303 documents::DOCK_MENU.with_borrow_mut(|d| *d = Some(items));
1304 documents::install_delegate();
1305 }
1306 if let Some(f) = self.open_url {
1307 documents::OPEN_URL.with_borrow_mut(|o| *o = Some(f));
1308 documents::install_delegate();
1309 }
1310 after_batch(|| {
1311 motion::run_layout(|| {
1312 if view::LAYOUT_DIRTY.with(Cell::get) {
1313 relayout_all();
1314 }
1315 });
1316 });
1317
1318 services::listen_for_notifications();
1319 ferrokit_core::observe_appearance();
1320 ferrokit_core::set_event_sink(|event| match event {
1321 ferrokit_core::Event::AppearanceChanged => emit(AppEvent::AppearanceChanged),
1322 ferrokit_core::Event::Redraw => later(models::drain_all),
1325 _ => {}
1326 });
1327
1328 objc2::rc::autoreleasepool(|_| {
1331 for window in self.windows {
1332 let w = window.open(mtm);
1333 w.makeKeyAndOrderFront(None);
1334 WINDOWS.with_borrow_mut(|ws| ws.push(w));
1335 }
1336 });
1337 let restored = if start_untitled || start_welcome { objc2::rc::autoreleasepool(|_| documents::restore_open()) } else { 0 };
1340 if start_untitled && restored == 0 {
1341 objc2::rc::autoreleasepool(|_| documents::new_launch_document());
1342 }
1343 if start_welcome && restored == 0 {
1344 objc2::rc::autoreleasepool(|_| show_welcome());
1345 }
1346 if preview_mode() {
1347 WINDOWS.with_borrow(|ws| ws.iter().for_each(|w| w.orderFrontRegardless()));
1350 } else {
1351 #[allow(deprecated)]
1352 app.activateIgnoringOtherApps(true);
1353 }
1354 if let Some(f) = self.on_launch {
1355 let f = RefCell::new(Some(f));
1356 later(move || {
1357 if let Some(f) = f.borrow_mut().take() {
1358 f();
1359 }
1360 });
1361 }
1362 if let Some(f) = self.crash_reports {
1363 let dir = crash::folder(&self.name);
1365 later(move || {
1366 for report in crash::pending(&dir) {
1367 failure::entry("a crash report's handler", (), || f(report));
1368 }
1369 });
1370 }
1371 app.run();
1372 }
1373}
1374
1375fn emit(event: AppEvent) {
1376 let handlers: Vec<Handler> = HANDLERS.with_borrow(|h| h.clone());
1377 for h in handlers {
1378 h(event.clone());
1379 }
1380}
1381
1382fn show_about(credits: &str, link: Option<&(String, String)>) {
1384 use objc2_app_kit::{NSFont, NSForegroundColorAttributeName, NSFontAttributeName, NSLinkAttributeName, NSParagraphStyleAttributeName};
1385 use objc2_foundation::{NSAttributedString, NSMutableAttributedString, NSRange, NSURL};
1386 let text = match link {
1387 Some((title, _)) => format!("{credits}\n{title}"),
1388 None => credits.to_string(),
1389 };
1390 let s = NSMutableAttributedString::from_nsstring(&NSString::from_str(&text));
1391 let all = NSRange::new(0, text.encode_utf16().count());
1392 let centred = objc2_app_kit::NSMutableParagraphStyle::new();
1393 centred.setAlignment(objc2_app_kit::NSTextAlignment::Center);
1394 unsafe {
1396 s.addAttribute_value_range(NSFontAttributeName, &NSFont::systemFontOfSize(11.0), all);
1397 s.addAttribute_value_range(NSForegroundColorAttributeName, &objc2_app_kit::NSColor::labelColor(), all);
1398 s.addAttribute_value_range(NSParagraphStyleAttributeName, ¢red, all);
1399 if let Some((title, url)) = link
1400 && let Some(u) = NSURL::URLWithString(&NSString::from_str(url))
1401 {
1402 let start = text.encode_utf16().count() - title.encode_utf16().count();
1403 s.addAttribute_value_range(NSLinkAttributeName, &u, NSRange::new(start, title.encode_utf16().count()));
1404 }
1405 }
1406 let credits: Retained<NSAttributedString> = Retained::into_super(s);
1407 let options = objc2_foundation::NSDictionary::from_retained_objects(&[unsafe { objc2_app_kit::NSAboutPanelOptionCredits }], &[Retained::into_super(Retained::into_super(credits))]);
1408 unsafe { NSApplication::sharedApplication(mtm()).orderFrontStandardAboutPanelWithOptions(&options) };
1410 ABOUT_SHOWN.with(|a| a.set(a.get() + 1));
1411}
1412
1413thread_local! {
1414 pub(crate) static ABOUT_SHOWN: std::cell::Cell<u32> = const { std::cell::Cell::new(0) };
1416}
1417
1418pub fn open_tab(beside: &WindowRef, window: Window) -> WindowRef {
1421 let beside = beside.ns();
1422 let w = open_ns(window);
1423 beside.addTabbedWindow_ordered(&w, objc2_app_kit::NSWindowOrderingMode::Above);
1424 w.makeKeyAndOrderFront(None);
1425 WindowRef::new(w)
1426}
1427
1428pub fn toggle_full_screen(window: &crate::WindowRef) {
1431 let window = window.ns();
1432 window.toggleFullScreen(None);
1433}
1434
1435pub fn is_full_screen(window: &crate::WindowRef) -> bool {
1437 let window = window.ns();
1438 window.styleMask().contains(NSWindowStyleMask::FullScreen)
1439}
1440
1441pub fn set_dock_badge(badge: Option<&str>) {
1443 let tile = NSApplication::sharedApplication(mtm()).dockTile();
1444 tile.setBadgeLabel(badge.map(NSString::from_str).as_deref());
1445}
1446
1447pub fn dock_badge() -> Option<String> {
1449 NSApplication::sharedApplication(mtm()).dockTile().badgeLabel().map(|b| b.to_string())
1450}
1451
1452pub fn open_with(make: impl FnOnce() -> Window) -> WindowRef {
1469 let owner = signal::Owner::new();
1470 let window = owner.with(make);
1471 let w = open_ns(window);
1472 keep_until_closed(&w, owner);
1473 WindowRef::new(w)
1474}
1475
1476thread_local! {
1477 static KEPT: UiCell<Vec<(usize, Box<dyn std::any::Any>)>> = const { UiCell::new(Vec::new()) };
1479}
1480
1481pub(crate) fn keep_until_closed(window: &NSWindow, value: impl std::any::Any) {
1484 KEPT.with_borrow_mut(|k| k.push((window as *const NSWindow as usize, Box::new(value))));
1485}
1486
1487pub fn open(window: Window) -> WindowRef {
1489 WindowRef::new(open_ns(window))
1490}
1491
1492pub(crate) fn open_ns(window: Window) -> Retained<NSWindow> {
1493 let mtm = mtm();
1494 objc2::rc::autoreleasepool(|_| {
1495 let w = window.open(mtm);
1496 w.makeKeyAndOrderFront(None);
1497 WINDOWS.with_borrow_mut(|ws| ws.push(w.clone()));
1498 w
1499 })
1500}
1501
1502thread_local! {
1503 static SETTINGS: UiCell<Option<Result<Retained<NSWindow>, Window>>> = const { UiCell::new(None) };
1505}
1506
1507pub fn open_settings() -> Option<WindowRef> {
1510 open_settings_ns().map(WindowRef::new)
1511}
1512
1513pub(crate) fn open_settings_ns() -> Option<Retained<NSWindow>> {
1514 let mtm = mtm();
1515 let pending = SETTINGS.with_borrow_mut(|s| match s.take() {
1516 Some(Err(w)) => Some(w),
1517 other => {
1518 *s = other;
1519 None
1520 }
1521 });
1522 if let Some(mut w) = pending {
1523 w.fixed = true;
1524 if w.autosave.is_none() {
1525 w.autosave = Some("ferrokit settings".into());
1526 }
1527 let window = objc2::rc::autoreleasepool(|_| w.open(mtm));
1528 window.setExcludedFromWindowsMenu(true);
1529 SETTINGS.with_borrow_mut(|s| *s = Some(Ok(window)));
1530 }
1531 let window = SETTINGS.with_borrow(|s| s.as_ref().and_then(|w| w.as_ref().ok().cloned()))?;
1532 window.makeKeyAndOrderFront(None);
1533 Some(window)
1534}
1535
1536pub fn close_window(window: &crate::WindowRef) {
1542 let window = window.ns();
1543 window.close();
1544 teardown(window);
1545}
1546
1547pub(crate) fn window_will_close(window: &NSWindow) {
1551 if is_settings(window) {
1552 return;
1553 }
1554 let window = objc2::Message::retain(window);
1555 later(move || {
1556 if !window.isVisible() {
1558 teardown(&window);
1559 }
1560 });
1561}
1562
1563fn is_settings(window: &NSWindow) -> bool {
1564 SETTINGS.with_borrow(|s| matches!(s, Some(Ok(w)) if std::ptr::eq(&**w, window)))
1565}
1566
1567pub(crate) fn teardown(window: &NSWindow) {
1570 if let Some(undo) = window.undoManager() {
1571 undo.removeAllActions();
1572 }
1573 drop_root(window);
1574 let key = window as *const NSWindow as usize;
1576 let kept: Vec<_> = KEPT.with_borrow_mut(|k| {
1577 let (mine, rest): (Vec<_>, Vec<_>) = std::mem::take(k).into_iter().partition(|(w, _)| *w == key);
1578 *k = rest;
1579 mine
1580 });
1581 drop(kept);
1582 documents::forget(window);
1583 WINDOWS.with_borrow_mut(|ws| ws.retain(|w| !std::ptr::eq(&**w, window)));
1584 let extras: Vec<Retained<NSObject>> = WINDOW_EXTRAS.with_borrow_mut(|e| {
1585 let (mine, rest): (Vec<_>, Vec<_>) = std::mem::take(e).into_iter().partition(|(w, _)| std::ptr::eq(&**w, window));
1586 *e = rest;
1587 mine.into_iter().map(|(_, x)| x).collect()
1588 });
1589 if !extras.is_empty() {
1590 window.setDelegate(None);
1592 if let Some(toolbar) = window.toolbar() {
1593 toolbar.setDelegate(None);
1594 }
1595 }
1596 drop(extras);
1597}
1598
1599pub fn windows() -> Vec<WindowRef> {
1601 windows_ns().into_iter().map(WindowRef::new).collect()
1602}
1603
1604pub(crate) fn windows_ns() -> Vec<Retained<NSWindow>> {
1605 WINDOWS.with_borrow(|w| w.clone())
1606}
1607
1608pub fn later(f: impl Fn() + 'static) {
1610 Native::later(Box::new(f));
1611}
1612
1613#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1615pub enum Appearance {
1616 System,
1618 Light,
1620 Dark,
1622}
1623
1624pub fn set_appearance(appearance: Appearance) {
1627 let name = match appearance {
1628 Appearance::System => None,
1629 Appearance::Light => Some(unsafe { objc2_app_kit::NSAppearanceNameAqua }),
1631 Appearance::Dark => Some(unsafe { objc2_app_kit::NSAppearanceNameDarkAqua }),
1632 };
1633 let appearance = name.and_then(objc2_app_kit::NSAppearance::appearanceNamed);
1634 NSApplication::sharedApplication(mtm()).setAppearance(appearance.as_deref());
1635}
1636
1637pub fn quit() {
1642 later(|| NSApplication::sharedApplication(mtm()).terminate(None));
1643}
1644
1645type Continuation = Box<dyn FnOnce(Result<Box<dyn Any + Send>, String>)>;
1646
1647thread_local! {
1648 static CONTINUATIONS: UiCell<HashMap<u64, Continuation>> = UiCell::new(HashMap::new());
1649 static NEXT_TASK: Cell<u64> = const { Cell::new(0) };
1650}
1651
1652pub fn spawn<T: Send + 'static>(work: impl FnOnce() -> T + Send + 'static, then: impl FnOnce(T) + 'static) {
1659 spawn_outcome(work, move |outcome| {
1660 if let Ok(result) = outcome {
1661 then(result);
1662 }
1663 });
1664}
1665
1666pub(crate) fn spawn_outcome<T: Send + 'static>(work: impl FnOnce() -> T + Send + 'static, then: impl FnOnce(Result<T, String>) + 'static) {
1669 let _ = mtm();
1670 let id = NEXT_TASK.with(|n| n.replace(n.get() + 1));
1671 CONTINUATIONS.with_borrow_mut(|c| {
1672 c.insert(
1673 id,
1674 Box::new(move |outcome: Result<Box<dyn Any + Send>, String>| {
1675 then(outcome.map(|result| *result.downcast::<T>().expect("spawned task result type")));
1676 }),
1677 )
1678 });
1679 std::thread::spawn(move || {
1680 let outcome: Result<Box<dyn Any + Send>, String> = crash::catching(|| std::panic::catch_unwind(std::panic::AssertUnwindSafe(work)))
1682 .map(|result| Box::new(result) as Box<dyn Any + Send>)
1683 .map_err(|payload| payload.downcast_ref::<&str>().map(|s| s.to_string()).or_else(|| payload.downcast_ref::<String>().cloned()).unwrap_or_else(|| "(no message)".into()));
1684 Native::on_main(Box::new(move || {
1687 if let Err(message) = &outcome {
1688 failure::report(Failure { place: "a background task", message: message.clone(), exception: false });
1689 }
1690 if let Some(then) = CONTINUATIONS.with_borrow_mut(|c| c.remove(&id)) {
1691 batch(|| then(outcome));
1692 }
1693 }));
1694 });
1695}
1696
1697thread_local! {
1698 static PROGRESS: UiCell<HashMap<u64, Signal<Option<f64>>>> = UiCell::new(HashMap::new());
1700}
1701
1702pub struct Reporter {
1705 id: u64,
1706 latest: std::sync::Arc<(std::sync::atomic::AtomicU64, std::sync::atomic::AtomicBool)>,
1709}
1710
1711impl Reporter {
1712 pub fn report(&self, fraction: f64) {
1715 use std::sync::atomic::Ordering;
1716 let (latest, pending) = &*self.latest;
1717 latest.store(fraction.clamp(0.0, 1.0).to_bits(), Ordering::Relaxed);
1718 if pending.swap(true, Ordering::AcqRel) {
1719 return;
1720 }
1721 let (id, shared) = (self.id, self.latest.clone());
1722 Native::on_main(Box::new(move || {
1723 let (latest, pending) = &*shared;
1724 pending.store(false, Ordering::Release);
1725 let value = f64::from_bits(latest.load(Ordering::Relaxed));
1726 if let Some(signal) = PROGRESS.with_borrow(|p| p.get(&id).copied()) {
1727 batch(|| signal.set_if_changed(Some(value)));
1728 }
1729 }));
1730 }
1731}
1732
1733pub fn spawn_with_progress<T: Send + 'static>(progress: &Signal<Option<f64>>, work: impl FnOnce(&Reporter) -> T + Send + 'static, then: impl FnOnce(T) + 'static) {
1752 let id = NEXT_TASK.with(|n| n.replace(n.get() + 1));
1753 PROGRESS.with_borrow_mut(|p| p.insert(id, *progress));
1754 progress.set(Some(0.0));
1755 let reporter = Reporter { id, latest: std::sync::Arc::new((std::sync::atomic::AtomicU64::new(0), std::sync::atomic::AtomicBool::new(false))) };
1756 let signal = *progress;
1757 spawn_outcome(
1758 move || work(&reporter),
1759 move |outcome| {
1760 PROGRESS.with_borrow_mut(|p| p.remove(&id));
1762 signal.set(None);
1763 if let Ok(result) = outcome {
1764 then(result);
1765 }
1766 },
1767 );
1768}
1769
1770#[cfg(any(doc, doctest))]
1791pub mod guide {
1792 #[allow(unused_imports)]
1794 use crate::*;
1795 #[cfg(doctest)]
1796 #[doc = include_str!("../README.md")]
1797 mod readme {}
1798 #[doc = include_str!("../guide/01-getting-started.md")]
1799 pub mod ch01_getting_started {}
1800 #[doc = include_str!("../guide/02-state.md")]
1801 pub mod ch02_state {}
1802 #[doc = include_str!("../guide/03-views-and-layout.md")]
1803 pub mod ch03_views_and_layout {}
1804 #[doc = include_str!("../guide/04-controls-and-forms.md")]
1805 pub mod ch04_controls_and_forms {}
1806 #[doc = include_str!("../guide/05-tables-outlines-editors.md")]
1807 pub mod ch05_tables_outlines_editors {}
1808 #[doc = include_str!("../guide/06-app-shell.md")]
1809 pub mod ch06_app_shell {}
1810 #[doc = include_str!("../guide/07-live-data.md")]
1811 pub mod ch07_live_data {}
1812 #[doc = include_str!("../guide/08-testing-and-shipping.md")]
1813 pub mod ch08_testing_and_shipping {}
1814 #[doc = include_str!("../guide/09-styling.md")]
1815 pub mod ch09_styling {}
1816 #[doc = include_str!("../guide/10-materials-and-windows.md")]
1817 pub mod ch10_materials_and_windows {}
1818 #[doc = include_str!("../guide/11-motion.md")]
1819 pub mod ch11_motion {}
1820 #[doc = include_str!("../guide/12-more-controls-and-charts.md")]
1821 pub mod ch12_more_controls_and_charts {}
1822 #[doc = include_str!("../guide/13-web-pdf-video-and-services.md")]
1823 pub mod ch13_web_pdf_video_and_services {}
1824 #[doc = include_str!("../guide/14-custom-native-views.md")]
1825 pub mod ch14_custom_native_views {}
1826 #[doc = include_str!("../guide/15-coming-from-egui-iced-slint.md")]
1827 pub mod ch15_coming_from_egui_iced_slint {}
1828}
1829
1830thread_local! {
1831 static PREVIEW: std::cell::Cell<Option<bool>> = const { std::cell::Cell::new(None) };
1833}
1834
1835pub(crate) fn preview_mode() -> bool {
1839 PREVIEW.with(|p| match p.get() {
1840 Some(on) => on,
1841 None => {
1842 let on = std::env::var("FERROKIT_PREVIEW").is_ok_and(|v| v == "1");
1843 p.set(Some(on));
1844 on
1845 }
1846 })
1847}
1848
1849pub(crate) fn set_preview_mode(on: bool) {
1850 PREVIEW.with(|p| p.set(Some(on)));
1851}