Repository Public
1import AppKit2import SwiftUI3import SheetCore4import SheetIO5import SheetUI67@MainActor8final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuItemValidation {9 static var shared: AppDelegate!10 private var settingsWindow: NSWindow?11 var welcomeWindow: NSWindow?1213 var currentDocument: WorkbookDocument? {14 (NSDocumentController.shared.currentDocument ?? NSApp.orderedDocuments.first) as? WorkbookDocument15 }16 var session: WorkbookSession? { currentDocument?.session }1718 func applicationWillFinishLaunching(_ notification: Notification) {19 Features.registerAll()20 Workspace.shared.displayProvider = FormatDisplayProvider()21 NSApp.mainMenu = MainMenu.build(delegate: self)22 AppSettings.shared.applyAppearance()23 NSWindow.allowsAutomaticWindowTabbing = true24 }2526 func applicationDidFinishLaunching(_ notification: Notification) {27 LaunchArguments.apply(delegate: self)28 }2930 func applicationShouldOpenUntitledFile(_ sender: NSApplication) -> Bool {31 if LaunchArguments.suppressUntitled || UserDefaults.standard.bool(forKey: "ORIXTesting") { return false }32 if AppSettings.shared.showWelcomeAtLaunch, Welcome.isAvailable {33 Welcome.show(delegate: self)34 return false35 }36 return true37 }3839 func applicationSupportsSecureRestorableState(_ app: NSApplication) -> Bool { true }4041 // MARK: Menu actions4243 @objc func showSettings(_ sender: Any?) {44 if settingsWindow == nil {45 let w = NSWindow(contentRect: .zero, styleMask: [.titled, .closable], backing: .buffered, defer: false)46 w.title = NSLocalizedString("Settings", comment: "")47 w.contentView = NSHostingView(rootView: SettingsView())48 w.isReleasedWhenClosed = false49 w.center()50 settingsWindow = w51 }52 settingsWindow?.makeKeyAndOrderFront(nil)53 }5455 @objc func newFromTemplate(_ sender: Any?) { Welcome.show(delegate: self) }5657 func openWorkbook(_ workbook: Workbook, name: String?) {58 let doc = WorkbookDocument(workbook: workbook, displayName: name)59 NSDocumentController.shared.addDocument(doc)60 doc.makeWindowControllers()61 doc.showWindows()62 }6364 @objc func exportXLSX(_ sender: Any?) { currentDocument?.export(as: .xlsx) }65 @objc func exportXLSM(_ sender: Any?) { currentDocument?.export(as: .xlsm) }66 @objc func exportCSV(_ sender: Any?) { currentDocument?.export(as: .csv) }67 @objc func exportTSV(_ sender: Any?) { currentDocument?.export(as: .tsv) }68 @objc func exportODS(_ sender: Any?) { currentDocument?.export(as: .ods) }69 @objc func exportJSON(_ sender: Any?) { currentDocument?.export(as: .json) }70 @objc func exportPDF(_ sender: Any?) { currentDocument?.exportPDF(allSheets: false) }71 @objc func exportPDFAll(_ sender: Any?) { currentDocument?.exportPDF(allSheets: true) }72 @objc func showImportReport(_ sender: Any?) { currentDocument?.showImportReport() }7374 @objc func pageSetup(_ sender: Any?) {75 guard let doc = currentDocument, let window = doc.window else { return }76 let panel = NSPanel(contentRect: .zero, styleMask: [.titled], backing: .buffered, defer: false)77 panel.contentView = NSHostingView(rootView: PageSetupView(session: doc.session) { window.endSheet(panel) })78 window.beginSheet(panel)79 }8081 @objc func find(_ sender: Any?) { if let s = session { NotificationCenter.default.post(name: .orixShowFind, object: s) } }82 @objc func goToCell(_ sender: Any?) {83 guard let s = session, let window = currentDocument?.window else { return }84 let alert = NSAlert()85 alert.messageText = NSLocalizedString("Go To", comment: "")86 alert.informativeText = NSLocalizedString("Cell, range or name (for example B12, A1:C5, Sheet2!D4)", comment: "")87 let field = NSTextField(frame: NSRect(x: 0, y: 0, width: 260, height: 24))88 field.setAccessibilityLabel(NSLocalizedString("Cell, range or name", comment: ""))89 alert.accessoryView = field90 alert.addButton(withTitle: NSLocalizedString("Go", comment: ""))91 alert.addButton(withTitle: NSLocalizedString("Cancel", comment: ""))92 alert.window.initialFirstResponder = field93 alert.beginSheetModal(for: window) { r in94 if r == .alertFirstButtonReturn, !s.goTo(field.stringValue) { NSSound.beep() }95 }96 }9798 @objc func fillDown(_ sender: Any?) { session?.fillDown() }99 @objc func fillRight(_ sender: Any?) { session?.fillRight() }100 @objc func pasteValues(_ sender: Any?) { session?.paste(mode: .values) }101 @objc func pasteFormats(_ sender: Any?) { session?.paste(mode: .formats) }102 @objc func pasteFormulas(_ sender: Any?) { session?.paste(mode: .formulas) }103 @objc func pasteTransposed(_ sender: Any?) { session?.paste(transpose: true) }104 @objc func clearAll(_ sender: Any?) { session?.clearSelection(.all) }105 @objc func clearFormats(_ sender: Any?) { session?.clearSelection(.formats) }106107 @objc func insertRows(_ sender: Any?) { session?.insertRows() }108 @objc func insertColumns(_ sender: Any?) { session?.insertCols() }109 @objc func deleteRows(_ sender: Any?) { session?.deleteRows() }110 @objc func deleteColumns(_ sender: Any?) { session?.deleteCols() }111 @objc func insertSheet(_ sender: Any?) { session?.addSheet() }112 @objc func deleteSheet(_ sender: Any?) { if let s = session { s.removeSheet(at: s.sheetIndex) } }113 @objc func duplicateSheet(_ sender: Any?) { if let s = session { s.duplicateSheet(at: s.sheetIndex) } }114 /// Keyboard path to renaming a sheet tab (otherwise a double-click or the tab's context menu).115 @objc func renameSheet(_ sender: Any?) { if let s = session { s.studioPane = nil; NotificationCenter.default.post(name: .orixRenameSheet, object: s) } }116 @objc func nextSheet(_ sender: Any?) { if let s = session { s.activateSheet(min(s.sheetIndex + 1, s.workbook.sheets.count - 1)) } }117 @objc func previousSheet(_ sender: Any?) { if let s = session { s.activateSheet(max(s.sheetIndex - 1, 0)) } }118119 @objc func bold(_ sender: Any?) { session?.toggleBold() }120 @objc func italic(_ sender: Any?) { session?.toggleItalic() }121 @objc func underline(_ sender: Any?) { session?.toggleUnderline() }122 @objc func mergeCells(_ sender: Any?) { session?.toggleMerge() }123 @objc func freezeAtSelection(_ sender: Any?) { if let s = session { s.setFrozen(rows: s.selection.active.row, cols: s.selection.active.col) } }124 @objc func unfreeze(_ sender: Any?) { session?.setFrozen(rows: 0, cols: 0) }125 @objc func hideRows(_ sender: Any?) { session?.setHidden(rows: true, hidden: true) }126 @objc func unhideRows(_ sender: Any?) { session?.setHidden(rows: true, hidden: false) }127 @objc func hideColumns(_ sender: Any?) { session?.setHidden(rows: false, hidden: true) }128 @objc func unhideColumns(_ sender: Any?) { session?.setHidden(rows: false, hidden: false) }129 @objc func numberFormat(_ sender: NSMenuItem) { if let code = sender.representedObject as? String { session?.applyStyle("Number Format") { $0.numberFormat = code } } }130131 @objc func sortAscending(_ sender: Any?) { session?.sortSelection(ascending: true) }132 @objc func sortDescending(_ sender: Any?) { session?.sortSelection(ascending: false) }133 @objc func recalculate(_ sender: Any?) { session?.recalculateAll() }134135 @objc func toggleSidebar(_ sender: Any?) { session?.showSidebar.toggle() }136 @objc func toggleInspector(_ sender: Any?) { if let s = session { s.inspectorPane = s.inspectorPane == nil ? "format" : nil } }137 @objc func toggleFormulas(_ sender: Any?) { if let s = session { s.showFormulas.toggle(); s.invalidate() } }138 @objc func zoomIn(_ sender: Any?) { if let s = session { s.gridView?.setZoom(s.zoom * 1.1) } }139 @objc func zoomOut(_ sender: Any?) { if let s = session { s.gridView?.setZoom(s.zoom / 1.1) } }140 @objc func zoomActual(_ sender: Any?) { session?.gridView?.setZoom(1) }141 @objc func backToSheet(_ sender: Any?) { session?.studioPane = nil }142143 @objc func performWorkspaceAction(_ sender: NSMenuItem) {144 guard let id = sender.representedObject as? String, let s = session, let action = Workspace.shared.actions.first(where: { $0.id == id }) else { return }145 action.perform(s)146 }147 @objc func openStudio(_ sender: NSMenuItem) { if let id = sender.representedObject as? String { session?.studioPane = id } }148 @objc func openInspectorPane(_ sender: NSMenuItem) { if let id = sender.representedObject as? String { session?.inspectorPane = id } }149150 @objc func showHelp(_ sender: Any?) { HelpWindow.show() }151152 func validateMenuItem(_ item: NSMenuItem) -> Bool {153 let needsDocument: Set<Selector> = [#selector(showSettings(_:)), #selector(newFromTemplate(_:)), #selector(showHelp(_:))]154 if let a = item.action, needsDocument.contains(a) { return true }155 guard let s = session else { return false }156 switch item.action {157 case #selector(toggleFormulas(_:)): item.state = s.showFormulas ? .on : .off158 case #selector(toggleSidebar(_:)): item.state = s.showSidebar ? .on : .off159 case #selector(toggleInspector(_:)): item.state = s.inspectorPane != nil ? .on : .off160 case #selector(backToSheet(_:)): return s.studioPane != nil161 case #selector(showImportReport(_:)): return !(currentDocument?.importIssues.isEmpty ?? true)162 case #selector(deleteSheet(_:)): return s.workbook.sheets.count > 1163 default: break164 }165 return true166 }167}168169/// Launch arguments used by tests, screenshots and automation:170/// -ORIXOpen <path> open a file171/// -ORIXTemplate <id> open a template172/// -ORIXPane <id> show an inspector pane; -ORIXStudio <id> a studio173/// -ORIXSelect <A1 ref> select a range; -ORIXSheet <name> activate a sheet174/// -ORIXSidebar YES|NO, -ORIXBottom <pane id>, -ORIXAction <action id>, -ORIXWindowSize WxH175/// -ORIXAppearance light|dark176/// -ORIXShot <png> [-ORIXShotDelay s] render the front window's content to a PNG, then quit177/// -ORIXShotWindow settings|help|pagesetup with -ORIXShot: capture that window instead of the document178/// -ORIXFind 1 open the find-and-replace bar179/// -ORIXDumpMenus <json> write the main-menu tree (titles, key equivalents), then quit (localization checks)180@MainActor181enum LaunchArguments {182 static var suppressUntitled: Bool {183 let d = UserDefaults.standard184 return d.string(forKey: "ORIXOpen") != nil || d.string(forKey: "ORIXTemplate") != nil185 }186187 static func apply(delegate: AppDelegate) {188 let d = UserDefaults.standard189 if let out = d.string(forKey: "ORIXDumpMenus") {190 // let features finish registering their menu commands, then dump and quit191 DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) { dumpMenus(to: out) }192 }193 if let a = d.string(forKey: "ORIXAppearance") { NSApp.appearance = NSAppearance(named: a == "dark" ? .darkAqua : .aqua) }194 if let path = d.string(forKey: "ORIXOpen") {195 NSDocumentController.shared.openDocument(withContentsOf: URL(fileURLWithPath: path), display: true) { _, _, error in196 if let error { NSLog("ORIXOpen failed: %@", error.localizedDescription) }197 MainActor.assumeIsolated { configure(delegate: delegate) }198 }199 } else if let id = d.string(forKey: "ORIXTemplate"), let wb = Welcome.buildTemplate(id: id) {200 delegate.openWorkbook(wb.0, name: wb.1)201 configure(delegate: delegate)202 } else {203 DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) { configure(delegate: delegate) }204 }205 }206207 private static func configure(delegate: AppDelegate) {208 let d = UserDefaults.standard209 guard let session = delegate.session else { scheduleShot(delegate); return }210 if let sheet = d.string(forKey: "ORIXSheet"), let i = session.workbook.sheetIndex(named: sheet) { session.activateSheet(i) }211 if let sel = d.string(forKey: "ORIXSelect") { session.goTo(sel) }212 if let pane = d.string(forKey: "ORIXPane") { session.inspectorPane = pane == "none" ? nil : pane }213 if d.object(forKey: "ORIXSidebar") != nil { session.showSidebar = d.bool(forKey: "ORIXSidebar") }214 if let studio = d.string(forKey: "ORIXStudio") { session.studioPane = studio }215 if let bottom = d.string(forKey: "ORIXBottom") { session.bottomPane = bottom }216 if let action = d.string(forKey: "ORIXAction"), let a = Workspace.shared.actions.first(where: { $0.id == action }) { a.perform(session) }217 if d.bool(forKey: "ORIXFind") { NotificationCenter.default.post(name: .orixShowFind, object: session) }218 switch d.string(forKey: "ORIXShotWindow") {219 case "settings": delegate.showSettings(nil)220 case "help": delegate.showHelp(nil)221 case "pagesetup": delegate.pageSetup(nil)222 default: break223 }224 if let size = d.string(forKey: "ORIXWindowSize")?.split(separator: "x").compactMap({ Double($0) }), size.count == 2, let w = delegate.currentDocument?.window {225 w.setContentSize(NSSize(width: size[0], height: size[1]))226 }227 scheduleShot(delegate)228 }229230 private static func scheduleShot(_ delegate: AppDelegate) {231 let d = UserDefaults.standard232 guard let out = d.string(forKey: "ORIXShot") else { return }233 let delay = d.object(forKey: "ORIXShotDelay") != nil ? d.double(forKey: "ORIXShotDelay") : 1.5234 DispatchQueue.main.asyncAfter(deadline: .now() + delay) {235 var window = delegate.currentDocument?.window ?? delegate.welcomeWindow ?? NSApp.windows.first { $0.isVisible }236 switch d.string(forKey: "ORIXShotWindow") {237 case "settings", "help": window = NSApp.keyWindow ?? NSApp.windows.last { $0.isVisible && $0 !== delegate.currentDocument?.window } ?? window238 case "pagesetup": window = delegate.currentDocument?.window?.attachedSheet ?? window239 default: break240 }241 guard let view = window?.contentView, let rep = view.bitmapImageRepForCachingDisplay(in: view.bounds) else { exit(2) }242 view.cacheDisplay(in: view.bounds, to: rep)243 try? rep.representation(using: .png, properties: [:])?.write(to: URL(fileURLWithPath: out))244 if let g = delegate.session?.gridView { print(String(format: "grid draw %.2f ms", g.lastDrawDuration * 1000)) }245 exit(0)246 }247 }248249 // MARK: Menu dump (localization and shortcut checks)250251 private static func describe(_ item: NSMenuItem) -> [String: Any] {252 var out: [String: Any] = ["title": item.title]253 if item.isSeparatorItem { return ["separator": true] }254 if !item.keyEquivalent.isEmpty {255 let m = item.keyEquivalentModifierMask256 var mods = ""257 if m.contains(.function) { mods += "fn " }258 if m.contains(.control) { mods += "⌃" }259 if m.contains(.option) { mods += "⌥" }260 if m.contains(.shift) || (item.keyEquivalent != item.keyEquivalent.lowercased()) { mods += "⇧" }261 if m.contains(.command) { mods += "⌘" }262 let key: String263 switch item.keyEquivalent.unicodeScalars.first?.value {264 case UInt32(NSLeftArrowFunctionKey): key = "←"265 case UInt32(NSRightArrowFunctionKey): key = "→"266 case UInt32(NSUpArrowFunctionKey): key = "↑"267 case UInt32(NSDownArrowFunctionKey): key = "↓"268 default: key = item.keyEquivalent.uppercased()269 }270 out["shortcut"] = mods + key271 }272 if item.isAlternate { out["alternate"] = true }273 if item.isHidden { out["hidden"] = true }274 if let a = item.action { out["action"] = NSStringFromSelector(a) }275 if let id = item.representedObject as? String { out["id"] = id }276 if let sub = item.submenu { out["items"] = sub.items.map(describe) }277 return out278 }279280 private static func dumpMenus(to path: String) {281 let tree = (NSApp.mainMenu?.items ?? []).map(describe)282 let payload: [String: Any] = ["language": Bundle.main.preferredLocalizations.first ?? "", "menus": tree]283 do {284 let data = try JSONSerialization.data(withJSONObject: payload, options: [.prettyPrinted, .sortedKeys, .withoutEscapingSlashes])285 try data.write(to: URL(fileURLWithPath: path), options: .atomic)286 exit(0)287 } catch {288 NSLog("ORIXDumpMenus failed: %@", error.localizedDescription)289 exit(2)290 }291 }292}293