Skip to content
This repository was archived by the owner on Oct 17, 2026. It is now read-only.
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
4 changes: 3 additions & 1 deletion Package.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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"]),
]
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
88 changes: 75 additions & 13 deletions Sources/CommandKit/Catalogs.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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] {
Expand All @@ -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) }
Expand Down Expand Up @@ -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<String> = []
return entries.compactMap { url in
var seenNames: Set<String> = []
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<String> = []
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
Expand Down
10 changes: 10 additions & 0 deletions Sources/CommandKit/Fuzzy.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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] {
Expand Down
23 changes: 19 additions & 4 deletions Sources/CommandKit/Item.swift
Original file line number Diff line number Diff line change
Expand Up @@ -21,35 +21,50 @@ 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
}
}

/// 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<String> = [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
}
}
15 changes: 12 additions & 3 deletions Sources/CommandKit/Ranker.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
15 changes: 14 additions & 1 deletion Sources/CommonCommand/Library.swift
Original file line number Diff line number Diff line change
@@ -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.
Expand Down Expand Up @@ -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.
Expand All @@ -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
Expand Down
16 changes: 11 additions & 5 deletions Sources/CommonCommand/PanelView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
54 changes: 50 additions & 4 deletions Tests/CommandKitTests/CatalogTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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" })
}
}

Expand Down
Loading
Loading