| | |
| | | Settings { |
| | | PreferencesView() |
| | | } |
| | | .defaultSize(width: 880, height: 420) |
| | | .defaultSize(width: 880, height: 460) |
| | | .commands { |
| | | CommandGroup(replacing: .systemServices) { } |
| | | CommandGroup(replacing: .appVisibility) { } |
| | | } |
| | | } |
| | | } |
| | | |
| | |
| | | } |
| | | |
| | | final class AppDelegate: NSObject, NSApplicationDelegate { |
| | | private var statusItem: NSStatusItem! |
| | | private static let showDockIconKey = "showDockIcon" |
| | | private static let showAppListMenuItemIdentifier = NSUserInterfaceItemIdentifier("TagLauncherShowAppListMenuItem") |
| | | private static let showAppListShortcutGlyphs = "⌥⇧␣" |
| | | private static let overlayDefaultLevel = NSWindow.Level(rawValue: Int(CGWindowLevelForKey(.maximumWindow))) |
| | | private static let overlayTextInputLevel = NSWindow.Level.modalPanel |
| | | |
| | | private var statusItem: NSStatusItem? |
| | | private var overlayWindow: NSWindow? |
| | | private var overlayKeyMonitor: Any? |
| | | private var settingsWindow: NSWindow? // Track Settings window to keep it above overlay |
| | | private var hotkeyRef: EventHotKeyRef? |
| | | private var isInEditMode = false // Suppress auto-dismiss during editing |
| | | private var isEditingAppNote = false |
| | | private var isConfiguringApplicationMenu = false |
| | | private var lastShowDockIcon: Bool? |
| | | |
| | | static func refreshChromeSettings() { |
| | | (NSApp.delegate as? AppDelegate)?.syncChromeSettings(force: true) |
| | | } |
| | | |
| | | static func openPreferencesWindow() { |
| | | (NSApp.delegate as? AppDelegate)?.openPreferences() |
| | | } |
| | | |
| | | func applicationDidFinishLaunching(_ notification: Notification) { |
| | | AppDefaults.register() |
| | | L10n.setup() |
| | | migrateDefaultGroupName() |
| | | TagDatabase.seedDefaultTags() |
| | | let showDock = UserDefaults.standard.bool(forKey: "showDockIcon") |
| | | NSApp.setActivationPolicy(showDock ? .regular : .accessory) |
| | | setupMenuBar() |
| | | syncChromeSettings(force: true) |
| | | registerHotkey() |
| | | observeOtherWindows() |
| | | observeSettingsClose() |
| | | observeEditMode() |
| | | observeDockSetting() |
| | | observeAppNoteEditing() |
| | | observePreferencesRequests() |
| | | observeApplicationMenuChanges() |
| | | observeChromeSettings() |
| | | observeLanguageChanges() |
| | | setupLaunchAtLogin() |
| | | configureApplicationMenuWhenAvailable() |
| | | } |
| | | |
| | | /// Dock icon click → show overlay (same as menubar "Show TagLauncher") |
| | | func applicationShouldHandleReopen(_ sender: NSApplication, hasVisibleWindows flag: Bool) -> Bool { |
| | | showOverlay() |
| | | return false // Suppress default "unhide all windows" behavior |
| | | } |
| | | |
| | | func applicationWillTerminate(_ notification: Notification) { |
| | | TagDatabase.flushPendingCategorySchemeBackupBatch() |
| | | } |
| | | |
| | | /// Ensure defaultGroupName is always the language-neutral key "Other". |
| | |
| | | // User has set a custom name — keep it |
| | | } |
| | | |
| | | /// Observe Show in Dock changes so it takes effect immediately. |
| | | private func observeDockSetting() { |
| | | /// Observe Dock visibility changes so they take effect immediately. |
| | | private func observeChromeSettings() { |
| | | NotificationCenter.default.addObserver( |
| | | forName: UserDefaults.didChangeNotification, |
| | | object: nil, queue: .main |
| | | ) { _ in |
| | | let show = UserDefaults.standard.bool(forKey: "showDockIcon") |
| | | NSApp.setActivationPolicy(show ? .regular : .accessory) |
| | | ) { [weak self] _ in |
| | | self?.syncChromeSettings() |
| | | } |
| | | } |
| | | |
| | | private func syncChromeSettings(force: Bool = false) { |
| | | let showDock = UserDefaults.standard.bool(forKey: Self.showDockIconKey) |
| | | let dockChanged = lastShowDockIcon != showDock |
| | | |
| | | if force || dockChanged { |
| | | NSApp.setActivationPolicy(showDock ? .regular : .accessory) |
| | | lastShowDockIcon = showDock |
| | | } |
| | | |
| | | if force { |
| | | setupMenuBar() |
| | | } |
| | | } |
| | | |
| | |
| | | object: nil, queue: .main |
| | | ) { [weak self] _ in |
| | | self?.setupMenuBar() |
| | | self?.configureApplicationMenuWhenAvailable() |
| | | } |
| | | } |
| | | |
| | |
| | | return |
| | | } |
| | | let key = "launchAtLogin" |
| | | if UserDefaults.standard.object(forKey: key) == nil { |
| | | UserDefaults.standard.set(true, forKey: key) |
| | | if !AppDefaults.hasStoredValue(for: key) && UserDefaults.standard.bool(forKey: key) { |
| | | Self.enableLaunchAtLogin() |
| | | } |
| | | } |
| | |
| | | // MARK: - Menu Bar |
| | | |
| | | private func setupMenuBar() { |
| | | // Remove old status item if re-creating (language switch, etc.) |
| | | if let existing = statusItem { |
| | | NSStatusBar.system.removeStatusItem(existing) |
| | | } |
| | | statusItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength) |
| | | removeMenuBarItem() |
| | | statusItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.squareLength) |
| | | guard let statusItem else { return } |
| | | statusItem.isVisible = true |
| | | |
| | | if let button = statusItem.button { |
| | | button.image = NSImage( |
| | | systemSymbolName: "tag.fill", |
| | | accessibilityDescription: "TagLauncher" |
| | | ) |
| | | button.image = makeMenuBarIcon() |
| | | button.imageScaling = .scaleProportionallyDown |
| | | button.imagePosition = .imageOnly |
| | | button.toolTip = "TagLauncher — Tag-based app launcher" |
| | | button.action = #selector(toggleOverlay) |
| | | button.target = self |
| | | } |
| | | |
| | | let menu = NSMenu() |
| | | menu.addItem( |
| | | NSMenuItem( |
| | | title: "\(tr("menu.show")) ⇧⌥Space", |
| | | action: #selector(toggleOverlay), |
| | | keyEquivalent: "" |
| | | ) |
| | | let showItem = NSMenuItem( |
| | | title: showAppListMenuTitle, |
| | | action: #selector(toggleOverlay), |
| | | keyEquivalent: "" |
| | | ) |
| | | showItem.target = self |
| | | menu.addItem(showItem) |
| | | menu.addItem(.separator()) |
| | | |
| | | // Version display |
| | |
| | | action: #selector(openPreferences), |
| | | keyEquivalent: "," |
| | | ) |
| | | prefsItem.target = self |
| | | prefsItem.keyEquivalentModifierMask = .command |
| | | menu.addItem(prefsItem) |
| | | menu.addItem(.separator()) |
| | |
| | | statusItem.menu = menu |
| | | } |
| | | |
| | | private func makeMenuBarIcon() -> NSImage { |
| | | let menuBarIconSize = NSSize(width: 19, height: 19) |
| | | if let url = Bundle.main.url(forResource: "TagLauncherMenuBarIcon", withExtension: "svg"), |
| | | let image = NSImage(contentsOf: url) { |
| | | image.size = menuBarIconSize |
| | | image.isTemplate = true |
| | | image.accessibilityDescription = "TagLauncher" |
| | | return image |
| | | } |
| | | |
| | | let image = NSImage(size: menuBarIconSize) |
| | | image.lockFocus() |
| | | defer { image.unlockFocus() } |
| | | |
| | | NSGraphicsContext.current?.shouldAntialias = true |
| | | NSColor.black.withAlphaComponent(0.88).setStroke() |
| | | NSColor.black.withAlphaComponent(0.88).setFill() |
| | | |
| | | let scale = image.size.width / 220.0 |
| | | func rectFromSVG(x: CGFloat, y: CGFloat, width: CGFloat, height: CGFloat) -> NSRect { |
| | | NSRect( |
| | | x: x * scale, |
| | | y: (220.0 - y - height) * scale, |
| | | width: width * scale, |
| | | height: height * scale |
| | | ) |
| | | } |
| | | |
| | | let outline = NSBezierPath( |
| | | roundedRect: rectFromSVG(x: 15, y: 15, width: 190, height: 190), |
| | | xRadius: 44 * scale, |
| | | yRadius: 44 * scale |
| | | ) |
| | | outline.lineWidth = 11 * scale |
| | | outline.stroke() |
| | | |
| | | for rect in [ |
| | | rectFromSVG(x: 49, y: 134, width: 27, height: 27), |
| | | rectFromSVG(x: 92, y: 134, width: 27, height: 27), |
| | | rectFromSVG(x: 49, y: 91, width: 27, height: 27), |
| | | rectFromSVG(x: 92, y: 91, width: 27, height: 27), |
| | | rectFromSVG(x: 49, y: 48, width: 27, height: 27), |
| | | rectFromSVG(x: 92, y: 48, width: 27, height: 27) |
| | | ] { |
| | | NSBezierPath(roundedRect: rect, xRadius: 8 * scale, yRadius: 8 * scale).fill() |
| | | } |
| | | |
| | | for rect in [ |
| | | rectFromSVG(x: 132, y: 133, width: 47, height: 28), |
| | | rectFromSVG(x: 132, y: 90.5, width: 47, height: 28), |
| | | rectFromSVG(x: 132, y: 48, width: 47, height: 28) |
| | | ] { |
| | | NSBezierPath(roundedRect: rect, xRadius: 12 * scale, yRadius: 12 * scale).fill() |
| | | } |
| | | |
| | | image.isTemplate = true |
| | | image.accessibilityDescription = "TagLauncher" |
| | | return image |
| | | } |
| | | |
| | | private var showAppListMenuTitle: String { |
| | | "\(tr("menu.showAppList")) \(Self.showAppListShortcutGlyphs)" |
| | | } |
| | | |
| | | private func observeApplicationMenuChanges() { |
| | | NotificationCenter.default.addObserver( |
| | | forName: NSApplication.didBecomeActiveNotification, |
| | | object: NSApp, queue: .main |
| | | ) { [weak self] _ in |
| | | self?.configureApplicationMenuWhenAvailable(retries: 4) |
| | | } |
| | | |
| | | NotificationCenter.default.addObserver( |
| | | forName: NSMenu.didAddItemNotification, |
| | | object: nil, queue: .main |
| | | ) { [weak self] notification in |
| | | guard let self, |
| | | !self.isConfiguringApplicationMenu, |
| | | let menu = notification.object as? NSMenu, |
| | | menu === NSApp.mainMenu?.items.first?.submenu |
| | | else { return } |
| | | self.configureApplicationMenuWhenAvailable(retries: 2) |
| | | } |
| | | } |
| | | |
| | | private func configureApplicationMenuWhenAvailable(retries: Int = 20) { |
| | | DispatchQueue.main.asyncAfter(deadline: .now() + 0.05) { [weak self] in |
| | | guard let self else { return } |
| | | guard NSApp.mainMenu?.items.first?.submenu != nil else { |
| | | if retries > 0 { |
| | | self.configureApplicationMenuWhenAvailable(retries: retries - 1) |
| | | } |
| | | return |
| | | } |
| | | |
| | | self.configureApplicationMenu() |
| | | if retries > 0 && self.applicationMenuNeedsCleanup() { |
| | | self.configureApplicationMenuWhenAvailable(retries: retries - 1) |
| | | } |
| | | } |
| | | } |
| | | |
| | | private func configureApplicationMenu() { |
| | | guard !isConfiguringApplicationMenu else { return } |
| | | guard let appMenu = NSApp.mainMenu?.items.first?.submenu else { return } |
| | | |
| | | isConfiguringApplicationMenu = true |
| | | defer { isConfiguringApplicationMenu = false } |
| | | |
| | | removeUnusedDefaultItems(from: appMenu) |
| | | configurePreferencesMenuItem(in: appMenu) |
| | | upsertShowAppListItem(in: appMenu) |
| | | normalizeSeparators(in: appMenu) |
| | | } |
| | | |
| | | private func applicationMenuNeedsCleanup() -> Bool { |
| | | guard let appMenu = NSApp.mainMenu?.items.first?.submenu else { return true } |
| | | let hasUnusedDefaultItems = appMenu.items.contains(where: isUnusedDefaultApplicationMenuItem) |
| | | let hasShowAppListItem = appMenu.items.contains { |
| | | $0.identifier == Self.showAppListMenuItemIdentifier |
| | | } |
| | | return hasUnusedDefaultItems || !hasShowAppListItem |
| | | } |
| | | |
| | | private func removeUnusedDefaultItems(from menu: NSMenu) { |
| | | for item in menu.items.reversed() where isUnusedDefaultApplicationMenuItem(item) { |
| | | menu.removeItem(item) |
| | | } |
| | | } |
| | | |
| | | private func isUnusedDefaultApplicationMenuItem(_ item: NSMenuItem) -> Bool { |
| | | if let servicesMenu = NSApp.servicesMenu, item.submenu === servicesMenu { |
| | | return true |
| | | } |
| | | return item.action == #selector(NSApplication.hide(_:)) |
| | | || item.action == #selector(NSApplication.hideOtherApplications(_:)) |
| | | || item.action == #selector(NSApplication.unhideAllApplications(_:)) |
| | | } |
| | | |
| | | private func upsertShowAppListItem(in menu: NSMenu) { |
| | | if let existingItem = menu.items.first(where: { $0.identifier == Self.showAppListMenuItemIdentifier }) { |
| | | configureShowAppListItem(existingItem) |
| | | return |
| | | } |
| | | |
| | | let item = NSMenuItem() |
| | | item.identifier = Self.showAppListMenuItemIdentifier |
| | | configureShowAppListItem(item) |
| | | |
| | | if let settingsIndex = menu.items.firstIndex(where: { isSettingsMenuItem($0) }) { |
| | | menu.insertItem(item, at: settingsIndex + 1) |
| | | } else if let firstSeparatorIndex = menu.items.firstIndex(where: { $0.isSeparatorItem }) { |
| | | menu.insertItem(item, at: firstSeparatorIndex) |
| | | } else { |
| | | menu.addItem(item) |
| | | } |
| | | } |
| | | |
| | | private func configureShowAppListItem(_ item: NSMenuItem) { |
| | | item.title = showAppListMenuTitle |
| | | item.action = #selector(toggleOverlay) |
| | | item.target = self |
| | | item.keyEquivalent = "" |
| | | item.keyEquivalentModifierMask = [] |
| | | item.isEnabled = true |
| | | } |
| | | |
| | | private func configurePreferencesMenuItem(in menu: NSMenu) { |
| | | let item: NSMenuItem |
| | | if let existingItem = menu.items.first(where: { isSettingsMenuItem($0) }) { |
| | | item = existingItem |
| | | } else { |
| | | item = NSMenuItem() |
| | | if let firstSeparatorIndex = menu.items.firstIndex(where: { $0.isSeparatorItem }) { |
| | | menu.insertItem(item, at: firstSeparatorIndex) |
| | | } else { |
| | | menu.addItem(item) |
| | | } |
| | | } |
| | | |
| | | item.title = tr("menu.preferences") |
| | | item.action = #selector(openPreferences) |
| | | item.target = self |
| | | item.keyEquivalent = "," |
| | | item.keyEquivalentModifierMask = .command |
| | | item.isEnabled = true |
| | | } |
| | | |
| | | private func isSettingsMenuItem(_ item: NSMenuItem) -> Bool { |
| | | item.action == Selector(("showSettingsWindow:")) |
| | | || item.action == #selector(openPreferences) |
| | | || item.title == tr("menu.preferences") |
| | | } |
| | | |
| | | private func normalizeSeparators(in menu: NSMenu) { |
| | | var indexesToRemove: [Int] = [] |
| | | var previousWasSeparator = false |
| | | |
| | | for (index, item) in menu.items.enumerated() { |
| | | guard item.isSeparatorItem else { |
| | | previousWasSeparator = false |
| | | continue |
| | | } |
| | | if index == 0 || index == menu.items.count - 1 || previousWasSeparator { |
| | | indexesToRemove.append(index) |
| | | } |
| | | previousWasSeparator = true |
| | | } |
| | | |
| | | for index in indexesToRemove.reversed() { |
| | | menu.removeItem(at: index) |
| | | } |
| | | } |
| | | |
| | | private func removeMenuBarItem() { |
| | | guard let statusItem else { return } |
| | | NSStatusBar.system.removeStatusItem(statusItem) |
| | | self.statusItem = nil |
| | | } |
| | | |
| | | // MARK: - Overlay Window |
| | | |
| | | @objc private func toggleOverlay() { |
| | |
| | | overlayWindow?.orderOut(nil) |
| | | overlayWindow = makeOverlayWindow(on: screen) |
| | | overlayWindow?.setFrame(screen.frame, display: true) |
| | | overlayWindow?.level = NSWindow.Level(rawValue: Int(CGWindowLevelForKey(.maximumWindow))) |
| | | overlayWindow?.level = isEditingAppNote ? Self.overlayTextInputLevel : Self.overlayDefaultLevel |
| | | |
| | | // Local key monitor: catch Escape while overlay is up |
| | | NSEvent.addLocalMonitorForEvents(matching: .keyDown) { [weak self] event in |
| | | installOverlayKeyMonitor() |
| | | |
| | | overlayWindow?.makeKeyAndOrderFront(nil) |
| | | overlayWindow?.orderFrontRegardless() |
| | | } |
| | | |
| | | private func installOverlayKeyMonitor() { |
| | | guard overlayKeyMonitor == nil else { return } |
| | | overlayKeyMonitor = NSEvent.addLocalMonitorForEvents(matching: .keyDown) { [weak self] event in |
| | | if event.keyCode == 53 { // Escape |
| | | self?.hideOverlay() |
| | | return nil |
| | | } |
| | | return event |
| | | } |
| | | } |
| | | |
| | | overlayWindow?.makeKeyAndOrderFront(nil) |
| | | overlayWindow?.orderFrontRegardless() |
| | | private func removeOverlayKeyMonitor() { |
| | | if let monitor = overlayKeyMonitor { |
| | | NSEvent.removeMonitor(monitor) |
| | | overlayKeyMonitor = nil |
| | | } |
| | | } |
| | | |
| | | private func makeOverlayWindow(on screen: NSScreen) -> NSWindow { |
| | |
| | | |
| | | private func hideOverlay(force: Bool = false) { |
| | | guard force || !isInEditMode else { return } |
| | | TagDatabase.flushPendingCategorySchemeBackupBatch() |
| | | if let settingsWindow, settingsWindow.parent == overlayWindow { |
| | | detachSettingsWindow(settingsWindow) |
| | | } |
| | | overlayWindow?.orderOut(nil) |
| | | removeOverlayKeyMonitor() |
| | | if force { |
| | | overlayWindow = nil |
| | | } |
| | |
| | | !self.isInEditMode |
| | | else { return } |
| | | |
| | | // Settings/Preferences window → float it above overlay for real-time preview |
| | | if NSApp.windows.contains(keyWindow) { |
| | | // Settings/Preferences window -> float it above overlay for real-time preview. |
| | | if self.isSettingsWindowCandidate(keyWindow) { |
| | | self.prepareSettingsWindow(keyWindow) |
| | | return |
| | | } |
| | |
| | | |
| | | /// Settings must always appear centered over the current overlay view and float above it. |
| | | private func prepareSettingsWindow(_ window: NSWindow) { |
| | | let settingsSize = NSSize(width: 880, height: max(window.frame.height, 420)) |
| | | window.minSize = NSSize(width: 880, height: 420) |
| | | window.maxSize = NSSize(width: 880, height: CGFloat.greatestFiniteMagnitude) |
| | | if abs(window.frame.width - settingsSize.width) > 0.5 || window.frame.height < settingsSize.height { |
| | | let settingsSize = NSSize(width: 880, height: 460) |
| | | window.identifier = NSUserInterfaceItemIdentifier("TagLauncherPreferencesWindow") |
| | | window.minSize = settingsSize |
| | | window.maxSize = settingsSize |
| | | if abs(window.frame.width - settingsSize.width) > 0.5 || abs(window.frame.height - settingsSize.height) > 0.5 { |
| | | window.setFrame( |
| | | NSRect(origin: window.frame.origin, size: settingsSize), |
| | | display: false |
| | |
| | | |
| | | if let overlayWindow, overlayWindow.isVisible { |
| | | center(window, over: overlayWindow.frame) |
| | | window.level = NSWindow.Level(rawValue: overlayWindow.level.rawValue + 1) |
| | | attachSettingsWindow(window, to: overlayWindow) |
| | | window.level = overlayWindow.level |
| | | } else if let screen = screenUnderMouse() { |
| | | center(window, over: screen.visibleFrame) |
| | | window.level = .floating |
| | | detachSettingsWindow(window) |
| | | } |
| | | |
| | | window.collectionBehavior.formUnion([.moveToActiveSpace, .fullScreenAuxiliary]) |
| | | var behavior = window.collectionBehavior |
| | | behavior.remove(.canJoinAllSpaces) |
| | | behavior.formUnion([.fullScreenAuxiliary, .moveToActiveSpace]) |
| | | window.collectionBehavior = behavior |
| | | window.makeKeyAndOrderFront(nil) |
| | | window.orderFrontRegardless() |
| | | settingsWindow = window |
| | | } |
| | | |
| | | private func attachSettingsWindow(_ window: NSWindow, to overlayWindow: NSWindow) { |
| | | if window.parent != overlayWindow { |
| | | window.parent?.removeChildWindow(window) |
| | | overlayWindow.addChildWindow(window, ordered: .above) |
| | | } |
| | | } |
| | | |
| | | private func detachSettingsWindow(_ window: NSWindow) { |
| | | window.parent?.removeChildWindow(window) |
| | | } |
| | | |
| | | private func isSettingsWindowCandidate(_ window: NSWindow) -> Bool { |
| | | if window == settingsWindow { return true } |
| | | if window.identifier?.rawValue == "TagLauncherPreferencesWindow" { return true } |
| | | guard NSApp.windows.contains(window), |
| | | window != overlayWindow, |
| | | window.isVisible, |
| | | !(window is NSPanel) |
| | | else { return false } |
| | | return true |
| | | } |
| | | |
| | | private func center(_ window: NSWindow, over rect: NSRect) { |
| | |
| | | let closingWindow = notification.object as? NSWindow, |
| | | closingWindow == self.settingsWindow |
| | | else { return } |
| | | self.detachSettingsWindow(closingWindow) |
| | | self.settingsWindow = nil |
| | | } |
| | | } |
| | |
| | | } |
| | | } |
| | | |
| | | @objc private func openPreferences() { |
| | | // Don't hide overlay — keep it visible for real-time setting preview. |
| | | NSApp.sendAction(Selector(("showSettingsWindow:")), to: nil, from: nil) |
| | | prepareSettingsWindowWhenAvailable(retries: 5) |
| | | /// Lower the overlay while editing app notes so IME candidate windows are not hidden behind it. |
| | | private func observeAppNoteEditing() { |
| | | NotificationCenter.default.addObserver( |
| | | forName: .tagLauncherAppNoteEditingChanged, |
| | | object: nil, |
| | | queue: .main |
| | | ) { [weak self] notification in |
| | | guard let self else { return } |
| | | self.isEditingAppNote = (notification.userInfo?["active"] as? Bool) ?? false |
| | | self.updateOverlayLevelForTextInput() |
| | | } |
| | | } |
| | | |
| | | private func prepareSettingsWindowWhenAvailable(retries: Int) { |
| | | DispatchQueue.main.asyncAfter(deadline: .now() + 0.03) { [weak self] in |
| | | guard let self else { return } |
| | | let candidates = NSApp.windows.filter { window in |
| | | window != self.overlayWindow && window.isVisible |
| | | } |
| | | candidates.forEach { self.prepareSettingsWindow($0) } |
| | | if candidates.isEmpty && retries > 0 { |
| | | self.prepareSettingsWindowWhenAvailable(retries: retries - 1) |
| | | } |
| | | private func updateOverlayLevelForTextInput() { |
| | | guard let overlayWindow else { return } |
| | | overlayWindow.level = isEditingAppNote ? Self.overlayTextInputLevel : Self.overlayDefaultLevel |
| | | if let settingsWindow, settingsWindow.parent == overlayWindow { |
| | | settingsWindow.level = overlayWindow.level |
| | | } |
| | | } |
| | | |
| | | /// The overlay buttons live inside SwiftUI; use an app-level notification like edit mode does. |
| | | private func observePreferencesRequests() { |
| | | NotificationCenter.default.addObserver( |
| | | forName: .tagLauncherOpenPreferencesRequested, |
| | | object: nil, |
| | | queue: .main |
| | | ) { [weak self] _ in |
| | | self?.openPreferences() |
| | | } |
| | | } |
| | | |
| | | @objc private func openPreferences() { |
| | | TagDatabase.flushPendingCategorySchemeBackupBatch() |
| | | // Don't hide overlay — keep it visible for real-time setting preview. |
| | | if let overlayWindow, overlayWindow.isVisible { |
| | | overlayWindow.makeKeyAndOrderFront(nil) |
| | | overlayWindow.orderFrontRegardless() |
| | | } |
| | | NSApp.activate(ignoringOtherApps: true) |
| | | |
| | | if let settingsWindow { |
| | | prepareSettingsWindow(settingsWindow) |
| | | return |
| | | } |
| | | |
| | | let settingsSize = NSSize(width: 880, height: 460) |
| | | let window = NSWindow( |
| | | contentRect: NSRect(origin: .zero, size: settingsSize), |
| | | styleMask: [.titled, .closable], |
| | | backing: .buffered, |
| | | defer: false |
| | | ) |
| | | window.title = tr("menu.preferences").replacingOccurrences(of: "…", with: "") |
| | | window.contentView = NSHostingView(rootView: PreferencesView()) |
| | | window.isReleasedWhenClosed = false |
| | | settingsWindow = window |
| | | prepareSettingsWindow(window) |
| | | } |
| | | |
| | | @objc private func switchLanguage(_ sender: NSMenuItem) { |
| | |
| | | onBackdropTap() |
| | | return |
| | | } |
| | | if let floatingButton = findFloatingIconButton(at: event.locationInWindow, in: self) { |
| | | floatingButton.mouseDown(with: event) |
| | | return |
| | | } |
| | | // Recursively search hit subtree for TextFieldContainer or NSTextField. |
| | | // NSHostingView.hitTest may return a SwiftUI-internal wrapper — the |
| | | // actual AppKit subview may be nested deeper. |
| | |
| | | if let tf = findNSTextField(in: hit) { |
| | | tf.window?.makeFirstResponder(tf) |
| | | tf.mouseDown(with: event) |
| | | return |
| | | } |
| | | // Forward to any other NSControl we find |
| | | if let control = findNSControl(in: hit) { |
| | | control.mouseDown(with: event) |
| | | return |
| | | } |
| | | super.mouseDown(with: event) |
| | |
| | | return nil |
| | | } |
| | | |
| | | private func findNSControl(in view: NSView) -> NSControl? { |
| | | if let control = view as? NSControl { return control } |
| | | for sub in view.subviews { |
| | | if let found = findNSControl(in: sub) { return found } |
| | | private func findFloatingIconButton(at windowPoint: NSPoint, in view: NSView) -> FloatingIconButtonView? { |
| | | for subview in view.subviews.reversed() where !subview.isHidden { |
| | | if let found = findFloatingIconButton(at: windowPoint, in: subview) { |
| | | return found |
| | | } |
| | | } |
| | | guard let floatingButton = view as? FloatingIconButtonView else { return nil } |
| | | let localPoint = floatingButton.convert(windowPoint, from: nil) |
| | | if floatingButton.bounds.contains(localPoint) { |
| | | return floatingButton |
| | | } |
| | | return nil |
| | | } |
| | | } |
| | | |
| | | // MARK: - Preferences View |
| | | |
| | | struct PreferencesView: View { |
| | | private let settingsWindowWidth: CGFloat = 880 |
| | | private let settingsContentWidth: CGFloat = 820 |
| | | private let settingsLabelWidth: CGFloat = 160 |
| | | private let widePickerWidth: CGFloat = 650 |
| | | private let compactPickerWidth: CGFloat = 320 |
| | | |
| | | @AppStorage("tagFontSize") private var tagFontSize: Double = 18 |
| | | @AppStorage("iconSize") private var iconSize: Double = 56 |
| | | @AppStorage("tagPosition") private var tagPosition = "left" |
| | | @AppStorage("defaultGroupName") private var defaultGroupName = "Other" |
| | | @AppStorage("displayMode") private var displayMode = "flat" |
| | | @AppStorage("hideAppNames") private var hideAppNames = false |
| | | @AppStorage("showDockIcon") private var showDockIcon = false |
| | | @AppStorage("launchAtLogin") private var launchAtLogin = true |
| | | @State private var selectedLanguage = L10n.currentCode |
| | | @State private var languageRefreshID = UUID() |
| | | @State private var isRefreshingLanguage = false |
| | | @State private var allApps: [AppInfo] = [] |
| | | @State private var tagColors: [String: Int] = [:] |
| | | |
| | | private func scanApps() { |
| | | DispatchQueue.global(qos: .userInitiated).async { |
| | | var apps = AppIndexer.scan() |
| | | let store = TagDatabase.load() |
| | | apps = TagEditor.annotate(apps: apps) |
| | | let colors = store.tags.mapValues { $0.color } |
| | | DispatchQueue.main.async { |
| | | allApps = apps |
| | | tagColors = colors |
| | | } |
| | | } |
| | | } |
| | | |
| | | private func exportTags() { |
| | | let panel = NSSavePanel() |
| | | panel.title = tr("settings.export") |
| | | panel.nameFieldStringValue = "TagLauncher-tags.json" |
| | | panel.allowedContentTypes = [.json] |
| | | panel.begin { response in |
| | | guard response == .OK, let url = panel.url else { return } |
| | | do { |
| | | try TagDatabase.exportTo(url) |
| | | } catch { |
| | | fputs("[TagLauncher] Export failed: \(error)\n", stderr) |
| | | } |
| | | } |
| | | } |
| | | |
| | | private func importTags() { |
| | | let panel = NSOpenPanel() |
| | | panel.title = tr("settings.import") |
| | | panel.allowedContentTypes = [.json] |
| | | panel.allowsMultipleSelection = false |
| | | panel.begin { response in |
| | | guard response == .OK, let url = panel.url else { return } |
| | | do { |
| | | _ = try TagDatabase.importFrom(url) |
| | | scanApps() |
| | | } catch { |
| | | fputs("[TagLauncher] Import failed: \(error)\n", stderr) |
| | | // Show alert on failure |
| | | let alert = NSAlert() |
| | | alert.messageText = tr("settings.importFailed") |
| | | alert.informativeText = error.localizedDescription |
| | | alert.alertStyle = .warning |
| | | alert.runModal() |
| | | } |
| | | } |
| | | } |
| | | |
| | | private var appVersion: String { |
| | | Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? "?" |
| | | } |
| | | private var buildVersion: String { |
| | | Bundle.main.infoDictionary?["CFBundleVersion"] as? String ?? "?" |
| | | } |
| | | |
| | | var body: some View { |
| | | ZStack { |
| | | TabView { |
| | | // Tab 1: Language |
| | | Form { |
| | | Section { |
| | | Picker(tr("settings.languagePicker"), selection: $selectedLanguage) { |
| | | ForEach(L10n.supported, id: \.code) { language in |
| | | Text(language.name).tag(language.code) |
| | | } |
| | | } |
| | | .pickerStyle(.radioGroup) |
| | | } header: { |
| | | Text(tr("settings.language")) |
| | | } footer: { |
| | | Text(tr("settings.languageDesc")) |
| | | } |
| | | } |
| | | .tabItem { Label(tr("settings.language"), systemImage: "globe") } |
| | | .padding() |
| | | |
| | | // Tab 2: General |
| | | VStack(alignment: .leading, spacing: 0) { |
| | | // Toggle row — centered as a rectangular block |
| | | HStack(spacing: 20) { |
| | | if AppDelegate.supportsLaunchAtLogin { |
| | | Toggle(tr("settings.launchAtLogin"), isOn: $launchAtLogin) |
| | | .onChange(of: launchAtLogin) { _, enabled in |
| | | if enabled { |
| | | AppDelegate.enableLaunchAtLogin() |
| | | } else { |
| | | AppDelegate.disableLaunchAtLogin() |
| | | } |
| | | } |
| | | } |
| | | Toggle(tr("settings.showInDock"), isOn: $showDockIcon) |
| | | Toggle(tr("settings.hideAppNames"), isOn: $hideAppNames) |
| | | } |
| | | .frame(maxWidth: .infinity, alignment: .center) |
| | | .padding(.bottom, 16) |
| | | |
| | | Divider() |
| | | .padding(.bottom, 16) |
| | | |
| | | // Two-column layout: each row label (right-aligned) + controls (left-aligned) |
| | | // All pickers and descriptions share the same left edge |
| | | VStack(spacing: 16) { |
| | | HStack(alignment: .top, spacing: 16) { |
| | | Text(tr("settings.appListStyle")) |
| | | .frame(width: settingsLabelWidth, alignment: .trailing) |
| | | VStack(alignment: .leading, spacing: 4) { |
| | | Picker("", selection: $displayMode) { |
| | | Text(tr("settings.flat")).tag("flat") |
| | | Text(tr("settings.container")).tag("container") |
| | | Text(tr("settings.coloredContainer")).tag("coloredContainer") |
| | | Text(tr("settings.gridContainer")).tag("gridContainer") |
| | | Text(tr("settings.coloredGridContainer")).tag("coloredGridContainer") |
| | | } |
| | | .pickerStyle(.segmented) |
| | | .frame(width: widePickerWidth, alignment: .leading) |
| | | Text(tr("settings.flatDesc")) |
| | | .font(.caption).foregroundStyle(.secondary) |
| | | .fixedSize(horizontal: false, vertical: true) |
| | | } |
| | | } |
| | | HStack(alignment: .top, spacing: 16) { |
| | | Text(tr("settings.tagPosition")) |
| | | .frame(width: settingsLabelWidth, alignment: .trailing) |
| | | VStack(alignment: .leading, spacing: 4) { |
| | | Picker("", selection: $tagPosition) { |
| | | Text(tr("settings.left")).tag("left") |
| | | Text(tr("settings.right")).tag("right") |
| | | Text(tr("settings.top")).tag("top") |
| | | } |
| | | .pickerStyle(.segmented) |
| | | .frame(width: compactPickerWidth, alignment: .leading) |
| | | Text(tr("settings.tagPosDesc")) |
| | | .font(.caption).foregroundStyle(.secondary) |
| | | .fixedSize(horizontal: false, vertical: true) |
| | | } |
| | | } |
| | | HStack(alignment: .top, spacing: 16) { |
| | | Text(tr("settings.tagFontSize")) |
| | | .frame(width: settingsLabelWidth, alignment: .trailing) |
| | | VStack(alignment: .leading, spacing: 4) { |
| | | Picker("", selection: $tagFontSize) { |
| | | ForEach([16.0, 18.0, 20.0, 22.0, 24.0, 26.0], id: \.self) { size in |
| | | Text("\(Int(size))").tag(size) |
| | | } |
| | | } |
| | | .pickerStyle(.segmented) |
| | | .frame(width: compactPickerWidth, alignment: .leading) |
| | | Text(tr("settings.tagFontDesc")) |
| | | .font(.caption).foregroundStyle(.secondary) |
| | | .fixedSize(horizontal: false, vertical: true) |
| | | } |
| | | } |
| | | HStack(alignment: .top, spacing: 16) { |
| | | Text(tr("settings.iconSize")) |
| | | .frame(width: settingsLabelWidth, alignment: .trailing) |
| | | VStack(alignment: .leading, spacing: 4) { |
| | | Picker("", selection: $iconSize) { |
| | | ForEach([40.0, 48.0, 56.0, 64.0, 72.0, 80.0], id: \.self) { size in |
| | | Text("\(Int(size))").tag(size) |
| | | } |
| | | } |
| | | .pickerStyle(.segmented) |
| | | .frame(width: compactPickerWidth, alignment: .leading) |
| | | Text(tr("settings.iconSizeDesc")) |
| | | .font(.caption).foregroundStyle(.secondary) |
| | | .fixedSize(horizontal: false, vertical: true) |
| | | } |
| | | } |
| | | } |
| | | } |
| | | .frame(maxWidth: settingsContentWidth, alignment: .center) |
| | | .padding() |
| | | .tabItem { Label(tr("settings.general"), systemImage: "gearshape") } |
| | | |
| | | // Tab 3: Tags |
| | | VStack(spacing: 0) { |
| | | TagEditorView( |
| | | tagColors: $tagColors, |
| | | excludedTagNames: ["Mac自带", defaultGroupName], |
| | | onRefresh: { scanApps() } |
| | | ) |
| | | } |
| | | .padding(.leading, 16) |
| | | .tabItem { Label(tr("settings.tags"), systemImage: "tag.fill") } |
| | | .onAppear { scanApps() } |
| | | |
| | | // Tab 4: Data |
| | | Form { |
| | | Section { |
| | | HStack(spacing: 12) { |
| | | Button(tr("settings.export")) { exportTags() } |
| | | .buttonStyle(.bordered) |
| | | Button(tr("settings.import")) { importTags() } |
| | | .buttonStyle(.bordered) |
| | | } |
| | | Text(tr("settings.backupDesc")) |
| | | .font(.caption) |
| | | .foregroundStyle(.secondary) |
| | | } header: { |
| | | Text(tr("settings.backup")) |
| | | } |
| | | } |
| | | .tabItem { Label(tr("settings.data"), systemImage: "externaldrive.fill") } |
| | | .padding() |
| | | |
| | | // Tab 5: About |
| | | Form { |
| | | Section { |
| | | HStack { |
| | | if let icon = NSImage(named: NSImage.applicationIconName) { |
| | | Image(nsImage: icon) |
| | | .resizable() |
| | | .frame(width: 128, height: 128) |
| | | } |
| | | VStack(alignment: .leading, spacing: 4) { |
| | | Text("TagLauncher") |
| | | .font(.title2) |
| | | .fontWeight(.semibold) |
| | | Text(tr("app.description")) |
| | | .font(.body) |
| | | .foregroundStyle(.secondary) |
| | | Text("\(tr("app.version")) \(appVersion) (\(tr("app.build")) \(buildVersion))") |
| | | .font(.callout) |
| | | .foregroundStyle(.tertiary) |
| | | |
| | | Divider() |
| | | .padding(.vertical, 4) |
| | | |
| | | Text("万物之中,希望最美") |
| | | .font(.caption) |
| | | .foregroundStyle(.secondary) |
| | | Text("永桔@2026-18602102518") |
| | | .font(.caption) |
| | | .foregroundStyle(.secondary) |
| | | } |
| | | } |
| | | .padding(.leading, 100) |
| | | } |
| | | } |
| | | .tabItem { Label(tr("settings.about"), systemImage: "info.circle") } |
| | | .padding() |
| | | } |
| | | .id(languageRefreshID) |
| | | .onChange(of: selectedLanguage) { _, code in |
| | | L10n.switchTo(code) |
| | | } |
| | | .onReceive(NotificationCenter.default.publisher(for: .appLanguageDidChange)) { notification in |
| | | if let code = notification.userInfo?["code"] as? String { |
| | | selectedLanguage = code |
| | | } |
| | | showLanguageRefresh() |
| | | } |
| | | |
| | | if isRefreshingLanguage { |
| | | ZStack { |
| | | Color(nsColor: .windowBackgroundColor) |
| | | .opacity(0.84) |
| | | Image(systemName: "arrow.clockwise") |
| | | .font(.system(size: 30, weight: .regular)) |
| | | .symbolRenderingMode(.hierarchical) |
| | | .foregroundStyle(.secondary) |
| | | } |
| | | .transition(.opacity) |
| | | } |
| | | } |
| | | .frame(minWidth: settingsWindowWidth, maxWidth: settingsWindowWidth, minHeight: 420) |
| | | } |
| | | |
| | | private func showLanguageRefresh() { |
| | | isRefreshingLanguage = true |
| | | languageRefreshID = UUID() |
| | | DispatchQueue.main.asyncAfter(deadline: .now() + 0.35) { |
| | | withAnimation(.easeOut(duration: 0.18)) { |
| | | isRefreshingLanguage = false |
| | | } |
| | | } |
| | | } |
| | | } |