diff --git a/CHANGELOG.md b/CHANGELOG.md index f4044a1..3a46252 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,5 +15,10 @@ All notable changes to this project are documented here. The format follows [Kee - Keyboard control: arrows, ⌃P/⌃N, Tab, Return, ⌘Return to show in Finder, and ⌘1–⌘9 with hints while ⌘ is held. - Settings: shortcut, theme, size, translucency, visible results, sources, search engine, menu bar item, and open at login. - Liquid Glass on macOS 26 and the popover material on earlier versions, or a solid background. +- System Settings topics and keywords from System Settings' own search terms, so "dark mode", "low power", or "firewall" find the right pane, shown with the pane's icon. + +### Fixed + +- A file Spotlight listed twice showed as two rows. [Unreleased]: https://github.com/oddurs/common-command/commits/main diff --git a/Package.swift b/Package.swift index b8cb43c..8c4082b 100644 --- a/Package.swift +++ b/Package.swift @@ -9,7 +9,9 @@ let package = Package( .executableTarget( name: "CommonCommand", dependencies: ["CommandKit"], - linkerSettings: [.linkedFramework("Carbon"), .linkedFramework("ServiceManagement")] + linkerSettings: [ + .linkedFramework("Carbon"), .linkedFramework("IOKit"), .linkedFramework("ServiceManagement"), + ] ), .testTarget(name: "CommandKitTests", dependencies: ["CommandKit"]), ] diff --git a/README.md b/README.md index fe8bb66..fa0754c 100644 --- a/README.md +++ b/README.md @@ -46,7 +46,7 @@ What a query finds, in order: 1. **Links.** `github.com/apple`, `https://…`, and `localhost:3000` open in your browser. Only well-known endings count, so `notes.md` and `Info.plist` stay file searches. 2. **Calculations.** `2^10`, `15% * 80`, `sqrt(2)`, `(1+2)(3+4)`, `5!`, with `pi`, `e`, and functions such as `sin`, `log`, and `round`. Return copies the result. Numbers follow your region, so `1,5 + 1` works where the comma is the decimal separator. A bare number isn't treated as a sum, so `1Password` and `2024` stay searches. -3. **Apps, System Settings panes, and Common Command's own commands** (Settings, Quit). +3. **Apps, System Settings, and Common Command's own commands** (Settings, Quit). Settings covers each pane and the topics inside it, found by the same keywords System Settings' own search uses: "dark mode" finds Appearance, "low power" finds Low Power Mode, "firewall" finds the firewall switch. Panes show their own icons. Laptop-only settings appear only on laptops. 4. **Files and folders** in your home folder whose name has a word starting with each word you typed. Build output, caches, and dot-folders are left out, and files you've opened recently rank higher. 5. **A web search** with your chosen engine: Google, DuckDuckGo, Bing, Kagi, Ecosia, or Startpage. diff --git a/Sources/CommandKit/Catalogs.swift b/Sources/CommandKit/Catalogs.swift index 9423695..1733b83 100644 --- a/Sources/CommandKit/Catalogs.swift +++ b/Sources/CommandKit/Catalogs.swift @@ -18,6 +18,9 @@ public enum AppCatalog { /// /Applications/Adobe Photoshop/. static let depth = 2 + /// Apps win a tie with a System Settings pane or topic: "gc" means Google Chrome before Game Center. + static let weight = 3 + public static func scan( roots: [URL] = standardRoots, extras: [URL] = extras, displayName: (URL) -> String = defaultDisplayName ) -> [Candidate] { @@ -31,7 +34,7 @@ public enum AppCatalog { let item = Item( id: "app:" + resolved, title: name, subtitle: "Application", kind: .application, action: .open(url)) - candidates.append(Candidate(item, alternatives: [fileName], weight: 2)) + candidates.append(Candidate(item, alternatives: [fileName], weight: weight)) } for root in roots { walk(root, depth: depth, found: add) } for url in extras where FileManager.default.fileExists(atPath: url.path) { add(url) } @@ -59,33 +62,92 @@ public enum AppCatalog { } } -/// The panes of System Settings, read from the extensions that provide them, so the list follows the -/// macOS version instead of a hard-coded table. +/// The panes of System Settings and the topics inside them, read from the extensions that provide them, so +/// the list follows the macOS version instead of a hard-coded table. Topics and their keywords come from the +/// same search-terms files System Settings' own search uses: "dark" finds Appearance, "low power" Battery. public enum SettingsPanes { public static let standardDirectory = URL(filePath: "/System/Library/ExtensionKit/Extensions") - public static func scan(directory: URL = standardDirectory) -> [Candidate] { + /// Topics rank below apps and panes with an equally good name; there are hundreds of them. + static let topicWeight = -12 + + struct Topic: Equatable { + var title: String + var keywords: [String] + } + + /// `isPortable` hides topics that only apply to laptops, such as Low Power Mode, or only to desktops. + public static func scan(directory: URL = standardDirectory, isPortable: Bool) -> [Candidate] { let entries = (try? FileManager.default.contentsOfDirectory(at: directory, includingPropertiesForKeys: nil)) ?? [] - var seen: Set = [] - return entries.compactMap { url in + var seenNames: Set = [] + return entries.sorted { $0.path < $1.path }.flatMap { url -> [Candidate] in guard url.pathExtension == "appex", let bundle = Bundle(url: url), let info = bundle.infoDictionary, let identifier = info["CFBundleIdentifier"] as? String, let attributes = info["EXAppExtensionAttributes"] as? [String: Any], attributes["EXExtensionPointIdentifier"] as? String == "com.apple.Settings.extension.ui", let settings = attributes["SettingsExtensionAttributes"] as? [String: Any], settings["allowsXAppleSystemPreferencesURLScheme"] as? Bool == true, - let name = readableName( - localized: bundle.localizedInfoDictionary?["CFBundleDisplayName"] as? String, - raw: info["CFBundleDisplayName"] as? String), - seen.insert(name).inserted, let target = URL(string: "x-apple.systempreferences:" + identifier) - else { return nil } + else { return [] } + var name = readableName( + localized: bundle.localizedInfoDictionary?["CFBundleDisplayName"] as? String, + raw: info["CFBundleDisplayName"] as? String) + if let shown = name, !seenNames.insert(shown).inserted { name = nil } + let terms = (settings["searchTermsFileName"] as? String) + .flatMap { bundle.url(forResource: $0, withExtension: "searchTerms") } + .flatMap { NSDictionary(contentsOf: $0) as? [String: Any] } + // Panes drawn from an SF Symbol have a proper icon; the rest show as a generic extension. + let hasIcon = (info["CFBundleIcons"] as? [String: Any])?["ISGraphicIconConfiguration"] != nil + return candidates( + identifier: identifier, name: name, topics: terms.map { topics(in: $0, isPortable: isPortable) } ?? [], + target: target, icon: hasIcon ? url : nil) + } + } + + static func topics(in terms: [String: Any], isPortable: Bool) -> [Topic] { + terms.keys.sorted().flatMap { section -> [Topic] in + let strings = (terms[section] as? [String: Any])?["localizableStrings"] as? [[String: Any]] ?? [] + return strings.compactMap { entry in + guard let title = entry["title"] as? String, !title.isEmpty, + !(entry["portableOnly"] as? Bool == true && !isPortable), + !(entry["desktopOnly"] as? Bool == true && isPortable) + else { return nil } + let keywords = (entry["index"] as? String ?? "").split(separator: ",") + .map { $0.trimmingCharacters(in: .whitespaces) }.filter { !$0.isEmpty } + return Topic(title: title, keywords: keywords) + } + } + } + + static func candidates(identifier: String, name: String?, topics: [Topic], target: URL, icon: URL?) + -> [Candidate] + { + let paneKey = name.map(Usage.key) + var paneKeywords: [String] = [] + var seenTitles: Set = [] + var result: [Candidate] = [] + for topic in topics { + let key = Usage.key(topic.title) + // A topic named like its pane is the pane itself; its keywords find the pane. + if key == paneKey { + paneKeywords += topic.keywords + continue + } + guard seenTitles.insert(key).inserted else { continue } + let item = Item( + id: "pane:\(identifier)#\(topic.title)", title: topic.title, + subtitle: name.map { "System Settings › \($0)" } ?? "System Settings", kind: .settings, + action: .open(target), iconFile: icon) + result.append(Candidate(item, keywords: topic.keywords, weight: topicWeight)) + } + if let name { let item = Item( id: "pane:" + identifier, title: name, subtitle: "System Settings", kind: .settings, - action: .open(target)) - return Candidate(item) + action: .open(target), iconFile: icon) + result.insert(Candidate(item, keywords: paneKeywords), at: 0) } + return result } /// The localised name when there is one. Otherwise the raw name, unless it is an internal one like diff --git a/Sources/CommandKit/Fuzzy.swift b/Sources/CommandKit/Fuzzy.swift index fb10236..a44b466 100644 --- a/Sources/CommandKit/Fuzzy.swift +++ b/Sources/CommandKit/Fuzzy.swift @@ -137,6 +137,16 @@ public enum Fuzzy { return Match(score: score, positions: positions) } + /// A keyword the query starts: below a name that starts the same way, above a scattered name match. + static func keywordScore(_ q: [UInt32], _ keywords: [[UInt32]]) -> Int? { + var best: Int? + for keyword in keywords where keyword.count >= q.count && keyword.starts(with: q) { + let score = 12 * q.count + 8 + (keyword.count == q.count ? 10 : 0) + best = max(best ?? score, score) + } + return best + } + static func isSubsequence(_ q: [UInt32], of t: [UInt32]) -> Bool { var i = 0 for c in t where c == q[i] { diff --git a/Sources/CommandKit/Item.swift b/Sources/CommandKit/Item.swift index 9a5d07c..e1734fa 100644 --- a/Sources/CommandKit/Item.swift +++ b/Sources/CommandKit/Item.swift @@ -21,16 +21,20 @@ public struct Item: Identifiable, Sendable, Hashable { public let subtitle: String public let kind: Kind public let action: Action + /// A file whose icon stands for the item when it isn't a file itself, such as a System Settings pane's + /// extension. + public let iconFile: URL? - public init(id: String, title: String, subtitle: String, kind: Kind, action: Action) { + public init(id: String, title: String, subtitle: String, kind: Kind, action: Action, iconFile: URL? = nil) { self.id = id self.title = title self.subtitle = subtitle self.kind = kind self.action = action + self.iconFile = iconFile } - /// The file behind the item, for its icon and for Reveal in Finder. + /// The file behind the item, for Reveal in Finder. public var fileURL: URL? { if case .open(let url) = action, url.isFileURL { return url } return nil @@ -38,18 +42,29 @@ public struct Item: Identifiable, Sendable, Hashable { } /// An item with the names it can be found by. The title comes first; the others are alternatives, such -/// as an app's file name when its display name is localised. +/// as an app's file name when its display name is localised. Keywords match only from their start, the +/// way a word you'd think of matches: "dark" finds the Appearance pane through "Dark Mode". public struct Candidate: Sendable { public let item: Item public let names: [SearchText] + let keywords: [[UInt32]] /// Added to every match, so an app outranks a settings pane with an equally good name. Small, so a /// clearly closer name still wins: "Bluetooth" the pane over "Bluetooth File Exchange" the app. public let weight: Int - public init(_ item: Item, alternatives: [String] = [], weight: Int = 0) { + public init(_ item: Item, alternatives: [String] = [], keywords: [String] = [], weight: Int = 0) { self.item = item var seen: Set = [item.title] names = [SearchText(item.title)] + alternatives.filter { seen.insert($0).inserted }.map(SearchText.init) + // Each keyword whole, spaces dropped, and each of its words, so "darkm" and "mode" both find "Dark Mode". + var prepared: Set<[UInt32]> = [] + for keyword in keywords { + prepared.insert(Fuzzy.prepare(keyword)) + for word in keyword.split(whereSeparator: { $0.isWhitespace || $0 == "-" }) { + prepared.insert(Fuzzy.prepare(String(word))) + } + } + self.keywords = prepared.filter { $0.count >= 2 }.sorted { $0.lexicographicallyPrecedes($1) } self.weight = weight } } diff --git a/Sources/CommandKit/Ranker.swift b/Sources/CommandKit/Ranker.swift index 86f3237..89a0071 100644 --- a/Sources/CommandKit/Ranker.swift +++ b/Sources/CommandKit/Ranker.swift @@ -34,14 +34,23 @@ public enum Ranker { best = match bestIsTitle = index == 0 } - guard let best else { continue } - let score = best.score + candidate.weight + usage.boost(for: candidate.item.id, key: key, at: now) + var matchScore = best?.score + var highlightsTitle = bestIsTitle + if !candidate.keywords.isEmpty, let keywordScore = Fuzzy.keywordScore(q, candidate.keywords), + keywordScore > (matchScore ?? .min) + { + matchScore = keywordScore + highlightsTitle = false + } + guard let matchScore else { continue } + let score = matchScore + candidate.weight + usage.boost(for: candidate.item.id, key: key, at: now) let length = candidate.names[0].keys.count if top.count == limit, let last = top.last, !isOrderedBefore(score, length, candidate.item, last) { continue } let entry = ( - Ranked(item: candidate.item, score: score, highlights: bestIsTitle ? best.positions : []), length + Ranked(item: candidate.item, score: score, highlights: highlightsTitle ? best?.positions ?? [] : []), + length ) let index = top.firstIndex { !isOrderedBefore($0.ranked.score, $0.length, $0.ranked.item, entry) } ?? top.count diff --git a/Sources/CommonCommand/Library.swift b/Sources/CommonCommand/Library.swift index 4b412bd..5823e6b 100644 --- a/Sources/CommonCommand/Library.swift +++ b/Sources/CommonCommand/Library.swift @@ -1,6 +1,7 @@ import CommandKit import CoreServices import Foundation +import IOKit.ps import os /// Everything that can be searched, and what has been chosen before. @@ -41,7 +42,7 @@ final class Library { let needsPanes = panes.isEmpty Task { let (apps, panes) = await Task.detached(priority: .userInitiated) { - (AppCatalog.scan(), needsPanes ? SettingsPanes.scan() : []) + (AppCatalog.scan(), needsPanes ? SettingsPanes.scan(isPortable: Self.hasBattery) : []) }.value self.apps = apps // System Settings changes only with macOS, so its panes are read once per launch. @@ -52,6 +53,18 @@ final class Library { } } + /// Whether this Mac runs on a battery, so laptop-only settings such as Low Power Mode are offered only + /// where they exist. + nonisolated static var hasBattery: Bool { + guard let info = IOPSCopyPowerSourcesInfo()?.takeRetainedValue(), + let sources = IOPSCopyPowerSourcesList(info)?.takeRetainedValue() as? [CFTypeRef] + else { return false } + return sources.contains { source in + let description = IOPSGetPowerSourceDescription(info, source)?.takeUnretainedValue() as? [String: Any] + return description?[kIOPSTypeKey] as? String == kIOPSInternalBatteryType + } + } + func record(_ item: Item, query: String) { usage.record(item.id, query: query, at: Date()) let usage = usage diff --git a/Sources/CommonCommand/PanelView.swift b/Sources/CommonCommand/PanelView.swift index 8c59580..e1127da 100644 --- a/Sources/CommonCommand/PanelView.swift +++ b/Sources/CommonCommand/PanelView.swift @@ -154,16 +154,22 @@ final class Icons { switch item.kind { case .application, .file, .folder: guard let path = item.fileURL?.path else { return nil } - if let image = cache[path] { return image } - let image = NSWorkspace.shared.icon(forFile: path) - cache[path] = image - return image - case .settings: return settingsIcon + return cached(path) + case .settings: + guard let path = item.iconFile?.path else { return settingsIcon } + return cached(path) case .command: return NSApp.applicationIconImage case .calculation, .link, .webSearch: return nil } } + private func cached(_ path: String) -> NSImage { + if let image = cache[path] { return image } + let image = NSWorkspace.shared.icon(forFile: path) + cache[path] = image + return image + } + static func symbol(for kind: Kind) -> String { switch kind { case .calculation: "equal" diff --git a/Tests/CommandKitTests/CatalogTests.swift b/Tests/CommandKitTests/CatalogTests.swift index 25d3a56..51d78da 100644 --- a/Tests/CommandKitTests/CatalogTests.swift +++ b/Tests/CommandKitTests/CatalogTests.swift @@ -64,11 +64,57 @@ import Testing #expect(SettingsPanes.readableName(localized: nil, raw: "Touch ID & Password") == "Touch ID & Password") } - @Test func findsPanesOnThisMac() { - let panes = SettingsPanes.scan() + @Test func findsPanesAndTopicsOnThisMac() { + let found = SettingsPanes.scan(isPortable: true) + let panes = found.filter { $0.item.subtitle == "System Settings" && !$0.item.id.contains("#") } #expect(panes.count > 10) - #expect(panes.allSatisfy { $0.item.kind == .settings }) - #expect(Set(panes.map(\.item.title)).count == panes.count) + #expect(found.count > panes.count) + #expect(found.allSatisfy { $0.item.kind == .settings }) + #expect(Set(found.map(\.item.id)).count == found.count) + } + + let terms: [String: Any] = [ + "Main": [ + "localizableStrings": [ + ["title": "Appearance", "index": "light, dark, theme, Dark Mode"], + ["title": "Accent color", "index": "button, selection"], + ["title": "Accent Color", "index": "duplicate"], + ["title": "Low Power Mode", "index": "save battery", "portableOnly": true], + ["title": "UPS", "index": "uninterruptible power", "desktopOnly": true], + ["index": "no title"], + ] + ] + ] + let target = URL(string: "x-apple.systempreferences:com.apple.Appearance-Settings.extension")! + + @Test func topicsFollowWhetherTheMacHasABattery() { + #expect(SettingsPanes.topics(in: terms, isPortable: true).map(\.title).contains("Low Power Mode")) + #expect(!SettingsPanes.topics(in: terms, isPortable: true).map(\.title).contains("UPS")) + #expect(SettingsPanes.topics(in: terms, isPortable: false).map(\.title).contains("UPS")) + #expect( + SettingsPanes.topics(in: terms, isPortable: true).first?.keywords == [ + "light", "dark", "theme", "Dark Mode", + ]) + } + + @Test func aTopicNamedLikeItsPaneLendsThePaneItsKeywords() { + let candidates = SettingsPanes.candidates( + identifier: "appearance", name: "Appearance", topics: SettingsPanes.topics(in: terms, isPortable: true), + target: target, icon: nil) + #expect(candidates.map(\.item.title) == ["Appearance", "Accent color", "Low Power Mode"]) + #expect(candidates[0].item.subtitle == "System Settings") + #expect(candidates[1].item.subtitle == "System Settings › Appearance") + #expect(candidates[1].weight < candidates[0].weight) + #expect(Fuzzy.keywordScore(Fuzzy.prepare("dark"), candidates[0].keywords) != nil) + } + + @Test func aPaneWithoutAReadableNameStillOffersItsTopics() { + let candidates = SettingsPanes.candidates( + identifier: "battery", name: nil, + topics: [.init(title: "Battery", keywords: ["charge"]), .init(title: "Low Power Mode", keywords: [])], + target: target, icon: nil) + #expect(candidates.map(\.item.title) == ["Battery", "Low Power Mode"]) + #expect(candidates.allSatisfy { $0.item.subtitle == "System Settings" }) } } diff --git a/Tests/CommandKitTests/SearchTests.swift b/Tests/CommandKitTests/SearchTests.swift index a5145d9..3aba588 100644 --- a/Tests/CommandKitTests/SearchTests.swift +++ b/Tests/CommandKitTests/SearchTests.swift @@ -3,7 +3,7 @@ import Testing @testable import CommandKit -func app(_ title: String, alternatives: [String] = [], weight: Int = 2) -> Candidate { +func app(_ title: String, alternatives: [String] = [], weight: Int = AppCatalog.weight) -> Candidate { Candidate( Item( id: "app:" + title, title: title, subtitle: "Application", kind: .application, @@ -120,6 +120,57 @@ func titles(_ ranked: [Ranked]) -> [String] { ranked.map(\.item.title) } } } +@Suite struct KeywordTests { + let now = Date(timeIntervalSince1970: 1_000_000) + + func pane(_ title: String, keywords: [String] = [], weight: Int = 0) -> Candidate { + Candidate( + Item( + id: "pane:" + title, title: title, subtitle: "System Settings", kind: .settings, + action: .open(URL(string: "x-apple.systempreferences:x")!)), + keywords: keywords, weight: weight) + } + + @Test func aKeywordFindsWhatTheNameDoesNot() { + let ranked = Ranker.rank( + [pane("Appearance", keywords: ["theme", "Dark Mode"]), app("Darkroom")], query: "dark mode", usage: Usage(), + now: now, limit: 2) + #expect(ranked.map(\.item.title) == ["Appearance"]) + #expect(ranked.first?.highlights == []) + } + + @Test func everyWordOfAKeywordCounts() { + let ranked = Ranker.rank( + [pane("Appearance", keywords: ["Dark Mode"])], query: "mode", usage: Usage(), now: now, limit: 1) + #expect(ranked.count == 1) + } + + @Test func keywordsMatchFromTheirStartOnly() { + #expect( + Ranker.rank([pane("Appearance", keywords: ["theme"])], query: "eme", usage: Usage(), now: now, limit: 1) + .isEmpty) + } + + @Test func aNameStartingWithTheQueryBeatsAKeyword() { + let ranked = Ranker.rank( + [pane("Appearance", keywords: ["display"]), pane("Displays")], query: "disp", usage: Usage(), now: now, + limit: 2) + #expect(ranked.map(\.item.title) == ["Displays", "Appearance"]) + } + + @Test func topicsStayBelowAppsTheyMerelyResemble() { + let topic = pane("Set time zone", weight: SettingsPanes.topicWeight) + let ranked = Ranker.rank([topic, app("System Settings")], query: "set", usage: Usage(), now: now, limit: 2) + #expect(ranked.first?.item.title == "System Settings") + } + + @Test func anAppBeatsASettingOnATie() { + let ranked = Ranker.rank( + [pane("Game Center"), app("Google Chrome")], query: "gc", usage: Usage(), now: now, limit: 2) + #expect(ranked.first?.item.title == "Google Chrome") + } +} + @Suite struct UsageTests { let now = Date(timeIntervalSince1970: 1_000_000)