SPB Git

Repository Public

MainMenu.swift 12.4 KB 196 lines swift

1import AppKit2import SheetUI34@MainActor5enum MainMenu {6    private static func L(_ s: String) -> String { NSLocalizedString(s, comment: "") }78    private static func item(_ title: String, _ action: Selector?, _ key: String = "", _ mods: NSEvent.ModifierFlags = .command, target: AnyObject? = nil, represented: Any? = nil) -> NSMenuItem {9        let it = NSMenuItem(title: L(title), action: action, keyEquivalent: key)10        it.keyEquivalentModifierMask = mods11        it.target = target12        it.representedObject = represented13        return it14    }1516    private static func menu(_ title: String, _ items: [NSMenuItem]) -> NSMenuItem {17        let m = NSMenu(title: L(title))18        for i in items { m.addItem(i) }19        let top = NSMenuItem(title: L(title), action: nil, keyEquivalent: "")20        top.submenu = m21        return top22    }2324    private static func sub(_ title: String, _ items: [NSMenuItem]) -> NSMenuItem { menu(title, items) }25    private static var sep: NSMenuItem { .separator() }2627    static func build(delegate d: AppDelegate) -> NSMenu {28        let main = NSMenu()29        let appName = "ORIX Sheet"3031        // Application32        let services = NSMenu(title: L("Services"))33        NSApp.servicesMenu = services34        let servicesItem = NSMenuItem(title: L("Services"), action: nil, keyEquivalent: ""); servicesItem.submenu = services35        main.addItem(menu(appName, [36            item("About ORIX Sheet", #selector(NSApplication.orderFrontStandardAboutPanel(_:))),37            sep, item("Settings…", #selector(AppDelegate.showSettings(_:)), ",", target: d),38            sep, servicesItem,39            sep, item("Hide ORIX Sheet", #selector(NSApplication.hide(_:)), "h"),40            item("Hide Others", #selector(NSApplication.hideOtherApplications(_:)), "h", [.command, .option]),41            item("Show All", #selector(NSApplication.unhideAllApplications(_:))),42            sep, item("Quit ORIX Sheet", #selector(NSApplication.terminate(_:)), "q"),43        ]))4445        // File46        let recent = NSMenu(title: L("Open Recent"))47        recent.perform(NSSelectorFromString("_setMenuName:"), with: "NSRecentDocumentsMenu")48        recent.addItem(item("Clear Menu", #selector(NSDocumentController.clearRecentDocuments(_:))))49        let recentItem = NSMenuItem(title: L("Open Recent"), action: nil, keyEquivalent: ""); recentItem.submenu = recent50        main.addItem(menu("File", [51            item("New", #selector(NSDocumentController.newDocument(_:)), "n"),52            item("New from Template…", #selector(AppDelegate.newFromTemplate(_:)), "n", [.command, .shift], target: d),53            item("Open…", #selector(NSDocumentController.openDocument(_:)), "o"),54            recentItem,55            sep, item("Close", #selector(NSWindow.performClose(_:)), "w"),56            item("Save…", #selector(NSDocument.save(_:)), "s"),57            item("Duplicate", #selector(NSDocument.duplicate(_:)), "s", [.command, .shift]),58            item("Rename…", #selector(NSDocument.rename(_:))),59            item("Move To…", #selector(NSDocument.move(_:))),60            item("Revert To Saved", #selector(NSDocument.revertToSaved(_:))),61            sep, sub("Export To", [62                item("Excel Workbook (.xlsx)…", #selector(AppDelegate.exportXLSX(_:)), target: d),63                item("Excel Macro-Enabled Workbook (.xlsm)…", #selector(AppDelegate.exportXLSM(_:)), target: d),64                item("OpenDocument Spreadsheet (.ods)…", #selector(AppDelegate.exportODS(_:)), target: d),65                item("CSV — Active Sheet…", #selector(AppDelegate.exportCSV(_:)), target: d),66                item("TSV — Active Sheet…", #selector(AppDelegate.exportTSV(_:)), target: d),67                item("JSON — Active Sheet…", #selector(AppDelegate.exportJSON(_:)), target: d),68                sep, item("PDF — Active Sheet…", #selector(AppDelegate.exportPDF(_:)), "e", [.command, .shift], target: d),69                item("PDF — All Sheets…", #selector(AppDelegate.exportPDFAll(_:)), target: d),70            ]),71            item("Import Report…", #selector(AppDelegate.showImportReport(_:)), target: d),72            sep, item("Page Setup…", #selector(AppDelegate.pageSetup(_:)), "p", [.command, .shift], target: d),73            item("Print…", #selector(NSDocument.printDocument(_:)), "p"),74        ]))7576        // Edit77        main.addItem(menu("Edit", [78            item("Undo", Selector(("undo:")), "z"), item("Redo", Selector(("redo:")), "z", [.command, .shift]),79            sep, item("Cut", #selector(NSText.cut(_:)), "x"), item("Copy", #selector(NSText.copy(_:)), "c"), item("Paste", #selector(NSText.paste(_:)), "v"),80            sub("Paste Special", [81                item("Values", #selector(AppDelegate.pasteValues(_:)), "v", [.command, .shift], target: d),82                item("Formulas", #selector(AppDelegate.pasteFormulas(_:)), target: d),83                item("Formatting", #selector(AppDelegate.pasteFormats(_:)), "v", [.command, .option], target: d),84                item("Transposed", #selector(AppDelegate.pasteTransposed(_:)), target: d),85            ]),86            item("Delete", #selector(NSText.delete(_:))),87            sub("Clear", [item("All", #selector(AppDelegate.clearAll(_:)), target: d), item("Formatting", #selector(AppDelegate.clearFormats(_:)), target: d)]),88            item("Select All", #selector(NSText.selectAll(_:)), "a"),89            sep, item("Fill Down", #selector(AppDelegate.fillDown(_:)), "d", target: d), item("Fill Right", #selector(AppDelegate.fillRight(_:)), "r", target: d),90            sep, item("Find and Replace…", #selector(AppDelegate.find(_:)), "f", target: d),91            item("Go To…", #selector(AppDelegate.goToCell(_:)), "g", [.control], target: d),92        ]))9394        // Insert95        var insertItems = [96            item("Rows", #selector(AppDelegate.insertRows(_:)), target: d), item("Columns", #selector(AppDelegate.insertColumns(_:)), target: d),97            item("Sheet", #selector(AppDelegate.insertSheet(_:)), target: d), sep,98        ]99        insertItems += workspaceItems(.insert, d)100        main.addItem(menu("Insert", insertItems))101102        // Format103        let formats: [(String, String)] = [(LK("General"), "General"), (LK("Number"), "#,##0.00"), (LK("Currency"), "$#,##0.00"), (LK("Percent"), "0.00%"), (LK("Scientific"), "0.00E+00"),104                                           (LK("Date"), "yyyy-mm-dd"), (LK("Time"), "hh:mm:ss"), (LK("Text"), "@")]105        main.addItem(menu("Format", [106            item("Bold", #selector(AppDelegate.bold(_:)), "b", target: d), item("Italic", #selector(AppDelegate.italic(_:)), "i", target: d),107            item("Underline", #selector(AppDelegate.underline(_:)), "u", target: d),108            sep, sub("Number Format", formats.map { item($0.0, #selector(AppDelegate.numberFormat(_:)), target: d, represented: $0.1) }),109            item("Merge or Unmerge Cells", #selector(AppDelegate.mergeCells(_:)), "m", [.command, .option], target: d),110            sep, item("Freeze Panes at Selection", #selector(AppDelegate.freezeAtSelection(_:)), target: d), item("Unfreeze Panes", #selector(AppDelegate.unfreeze(_:)), target: d),111            sep, sub("Rows", [item("Delete", #selector(AppDelegate.deleteRows(_:)), target: d), item("Hide", #selector(AppDelegate.hideRows(_:)), target: d), item("Unhide", #selector(AppDelegate.unhideRows(_:)), target: d)]),112            sub("Columns", [item("Delete", #selector(AppDelegate.deleteColumns(_:)), target: d), item("Hide", #selector(AppDelegate.hideColumns(_:)), target: d), item("Unhide", #selector(AppDelegate.unhideColumns(_:)), target: d)]),113            sub("Sheet", [item("Rename…", #selector(AppDelegate.renameSheet(_:)), "r", [.command, .option], target: d),114                          item("Duplicate", #selector(AppDelegate.duplicateSheet(_:)), target: d), item("Delete", #selector(AppDelegate.deleteSheet(_:)), target: d),115                          item("Next Sheet", #selector(AppDelegate.nextSheet(_:)), String(UnicodeScalar(NSRightArrowFunctionKey)!), [.command, .option], target: d),116                          item("Previous Sheet", #selector(AppDelegate.previousSheet(_:)), String(UnicodeScalar(NSLeftArrowFunctionKey)!), [.command, .option], target: d)]),117        ]))118119        // Data / Analyze / Tools120        main.addItem(menu("Data", [item("Sort Ascending", #selector(AppDelegate.sortAscending(_:)), target: d), item("Sort Descending", #selector(AppDelegate.sortDescending(_:)), target: d), sep]121                          + workspaceItems(.data, d)))122        let analyze = workspaceItems(.analyze, d)123        if !analyze.isEmpty { main.addItem(menu("Analyze", analyze)) }124        main.addItem(menu("Tools", [item("Recalculate Everything", #selector(AppDelegate.recalculate(_:)), "=", target: d), sep] + workspaceItems(.tools, d)))125126        // View127        var viewItems = [128            item("Show Navigator", #selector(AppDelegate.toggleSidebar(_:)), "s", [.command, .control], target: d),129            item("Show Inspector", #selector(AppDelegate.toggleInspector(_:)), "i", [.command, .option], target: d),130            item("Show Formulas", #selector(AppDelegate.toggleFormulas(_:)), "`", target: d),131            sep, item("Zoom In", #selector(AppDelegate.zoomIn(_:)), "+"), item("Zoom Out", #selector(AppDelegate.zoomOut(_:)), "-"), item("Actual Size", #selector(AppDelegate.zoomActual(_:)), "0"),132            sep, item("Back to Sheet", #selector(AppDelegate.backToSheet(_:)), target: d),133        ]134        for it in viewItems where it.action == #selector(AppDelegate.zoomIn(_:)) || it.action == #selector(AppDelegate.zoomOut(_:)) || it.action == #selector(AppDelegate.zoomActual(_:)) { it.target = d }135        let studios = Workspace.shared.panes(.studio)136        if !studios.isEmpty {137            viewItems.append(sep)138            for p in studios { viewItems.append(paneItem(p, #selector(AppDelegate.openStudio(_:)), d)) }139        }140        let inspectors = Workspace.shared.panes(.inspector)141        if !inspectors.isEmpty {142            viewItems.append(sub("Inspector", inspectors.map { paneItem($0, #selector(AppDelegate.openInspectorPane(_:)), d) }))143        }144        viewItems += [sep, item("Enter Full Screen", #selector(NSWindow.toggleFullScreen(_:)), "f", [.command, .control])]145        main.addItem(menu("View", viewItems))146147        // Window148        let windowMenu = menu("Window", [149            item("Minimize", #selector(NSWindow.performMiniaturize(_:)), "m"), item("Zoom", #selector(NSWindow.performZoom(_:))),150            sep, item("Bring All to Front", #selector(NSApplication.arrangeInFront(_:))),151        ])152        NSApp.windowsMenu = windowMenu.submenu153        main.addItem(windowMenu)154155        let help = menu("Help", [item("ORIX Sheet Help", #selector(AppDelegate.showHelp(_:)), "?", target: d)])156        NSApp.helpMenu = help.submenu157        main.addItem(help)158        return main159    }160161    private static func paneItem(_ p: WorkspacePane, _ action: Selector, _ d: AppDelegate) -> NSMenuItem {162        let it = NSMenuItem(title: p.id, action: action, keyEquivalent: "")163        it.title = p.plainTitle164        it.image = NSImage(systemSymbolName: p.systemImage, accessibilityDescription: nil)165        it.target = d166        it.representedObject = p.id167        return it168    }169170    /// Shortcuts already given to a feature action: when two features ask for the same one, the first keeps it.171    private static var claimedShortcuts = Set<String>()172173    private static func workspaceItems(_ group: WorkspaceAction.Group, _ d: AppDelegate) -> [NSMenuItem] {174        Workspace.shared.actions(group).map { a in175            var shortcut = a.shortcut176            if let s = shortcut, !claimedShortcuts.insert("\(s.modifiers.union(.command).rawValue)|\(s.key)").inserted { shortcut = nil }177            let it = NSMenuItem(title: a.title, action: #selector(AppDelegate.performWorkspaceAction(_:)), keyEquivalent: shortcut.map { String($0.key) } ?? "")178            if let s = shortcut { it.keyEquivalentModifierMask = s.modifiers.union(.command) }179            it.image = NSImage(systemSymbolName: a.systemImage, accessibilityDescription: nil)180            it.target = d181            it.representedObject = a.id182            return it183        }184    }185}186187/// `WorkspacePane.title` is a LocalizedStringKey (for SwiftUI); menus need a plain string.188@MainActor189enum PaneTitles {190    static func title(for pane: WorkspacePane) -> String {191        let mirror = Mirror(reflecting: pane.title)192        if let key = mirror.children.first(where: { $0.label == "key" })?.value as? String { return key }193        return pane.id.capitalized194    }195}196
Files main
Menu

Theme