From d0dc4ad69d9a7b9939dc75be4326a4a7471130dc Mon Sep 17 00:00:00 2001 From: progresshans Date: Sun, 29 Nov 2026 17:48:02 +0900 Subject: [PATCH 01/13] feat: open the repository and Review's file in an editor, Claude Code, Finder or a terminal MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit An Open button in the toolbar, beside Review and Focus, opens the repository in the default editor and shows that editor's icon (Finder's when none is installed). Its ▾ lists the installed editors (VS Code, Cursor, Zed, Xcode, the JetBrains IDEs…), Claude Code in the Claude app (claude://code/new) and in a terminal (claude-cli://open), Finder, the terminal, Copy Path, and which editor the button uses. File › Open in…, the right-click menus of a tab and of the repository list, and Quick Open have the same, with ⌥E, ⌥O and ⌥T as in GitKraken. The keys are off while text is typed, so ⌥ still types é, ø and † there. Review's header and each All Files header have the same kind of button for a file: it opens the file in the editor at its first change (VS Code and its forks by their file links, Xcode with xed), or a picture or a PDF in the app macOS picks, and ⌘↓ (File › Open “…”) does the same. Its ▾ adds Claude Code with the file named (@path) and, for a commit's file, Open Version at : a read-only copy named after the commit. The files' right-click menus have Open in and Open With. Settings › General picks the editor and the terminal (Terminal, iTerm, Ghostty); Open in Terminal always opened Terminal before. A repository's Show in Finder is now Open in Finder, which opens the folder itself. From macOS 27 a menu hides its items' images unless they ask to be shown (preferredImageVisibility), so the app icons ask. With names under the icons and the window under 1,000 pt, Open goes into » with New Branch, Stash and Pop. A test instance opens nothing: it notes what it would have opened (OpenIn.debugLog). Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 10 + Kaern/App/AppDelegate.swift | 1 + Kaern/App/AppModel.swift | 2 + Kaern/App/MainMenu.swift | 46 ++- Kaern/App/OpenIn.swift | 361 ++++++++++++++++++ .../Repository/RepositoryModel+Actions.swift | 17 +- Kaern/Settings/AppSettings.swift | 4 + Kaern/Settings/SettingsWindow.swift | 42 ++ Kaern/Views/CommandLog/CommandLogWindow.swift | 6 +- Kaern/Views/Common/DebugFrame.swift | 39 ++ Kaern/Views/Menus/ContextMenus.swift | 20 +- Kaern/Views/Menus/OpenMenus.swift | 141 +++++++ Kaern/Views/QuickOpen/QuickOpen.swift | 19 +- .../RepositoryList/RepositoryListView.swift | 7 +- Kaern/Views/Review/FileOpenButton.swift | 69 ++++ Kaern/Views/Review/ReviewView.swift | 33 +- Kaern/Views/TabBar/TabBar.swift | 33 +- Kaern/Views/Toolbar/MainToolbar.swift | 73 +++- 18 files changed, 861 insertions(+), 62 deletions(-) create mode 100644 Kaern/App/OpenIn.swift create mode 100644 Kaern/Views/Common/DebugFrame.swift create mode 100644 Kaern/Views/Menus/OpenMenus.swift create mode 100644 Kaern/Views/Review/FileOpenButton.swift diff --git a/CHANGELOG.md b/CHANGELOG.md index 25f5349..e98da68 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,16 @@ What changed in each version of Kaern. A version's section is what its update wi ## [Unreleased] +### New + +- An Open button in the toolbar opens the repository in your editor, VS Code for example, and shows that editor's + icon. Its ▾ opens it in another editor, in Claude Code (the Claude app or claude in a terminal), in Finder or in + the terminal. ⌥E, ⌥O and ⌥T do the same from the keyboard, as in GitKraken. +- Review has an Open button too: it opens the file you're looking at in your editor at its first change, and so does + ⌘↓. For a commit's file, its ▾ also opens that commit's version as a read-only copy. The files' right-click menus + have Open in and Open With. +- Choose the editor and the terminal in Settings › General. Open in Terminal used to always open Terminal. + ### Improved - A branch or tag name that doesn't fit can be read whole: rest the pointer on it. In the history, a label that diff --git a/Kaern/App/AppDelegate.swift b/Kaern/App/AppDelegate.swift index 7c92dac..2fe73ce 100644 --- a/Kaern/App/AppDelegate.swift +++ b/Kaern/App/AppDelegate.swift @@ -28,6 +28,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate { #endif AppModel.shared.launch() QuickLookCopies.removeOld() + VersionCopies.removeOld() // Release builds only (UpdateController.isAvailable). UpdateController.shared.start() } diff --git a/Kaern/App/AppModel.swift b/Kaern/App/AppModel.swift index c82ba96..09b0c7d 100644 --- a/Kaern/App/AppModel.swift +++ b/Kaern/App/AppModel.swift @@ -113,6 +113,8 @@ final class AppModel { // Without the file watcher (Settings › Advanced), coming back to Kaern refreshes. center.addObserver(forName: NSApplication.didBecomeActiveNotification, object: nil, queue: .main) { [weak self] _ in MainActor.assumeIsolated { + // An editor or a terminal may have been installed or removed meanwhile (OpenIn). + OpenIn.refresh() guard let self, !AppSettings.watchesFiles else { return } for model in self.repositories.values where model.isVisible { model.refreshAfterActivation() } } diff --git a/Kaern/App/MainMenu.swift b/Kaern/App/MainMenu.swift index 3834d9f..13fde42 100644 --- a/Kaern/App/MainMenu.swift +++ b/Kaern/App/MainMenu.swift @@ -133,15 +133,42 @@ enum MainMenu { title: { repository?.quickLookFile.map { "Quick Look “\($0.name)”" } ?? "Quick Look" }) { if let file = repository?.quickLookFile { repository?.quickLook(file) } }) - menu.addItem(MenuAction.item("Show in Finder", enabled: { window?.activeTab != nil }) { - if let path = window?.activeTab?.path { NSWorkspace.shared.activateFileViewerSelecting([URL(filePath: path)]) } + // The same file in the app it opens in, at its first change (Finder's Open is ⌘↓). Off while text is typed: + // ⌘↓ goes to the end of the text there. + menu.addItem(MenuAction.item("Open File", key: arrow(NSDownArrowFunctionKey), enabled: { textView == nil && openableFile != nil }, title: { + guard let file = openableFile, let url = repository?.existingFile(file.path) else { return "Open File" } + return "Open “\(file.name)” in \(OpenIn.app(forFile: url)?.name ?? "Default App")" + }) { + if let file = openableFile { repository?.open(file.opening) } + }) + menu.addItem(.separator()) + // The repository (ScreenOpenIn). ⌥E, ⌥O and ⌥T as in GitKraken; off while text is typed, so ⌥ still types é, ø, †. + let hasTab = { window?.activeTab != nil && textView == nil } + menu.addItem(MenuAction.item("Open in Editor", key: "e", modifiers: [.option], enabled: { hasTab() && OpenIn.editor() != nil }, + title: { "Open in \(OpenIn.editor()?.name ?? "Editor")" }) { + if let path = window?.activeTab?.path, let editor = OpenIn.editor() { OpenIn.open(folder: path, in: editor) } + }) + menu.addItem(MenuAction.item("Open in Finder", key: "o", modifiers: [.option], enabled: hasTab) { + if let path = window?.activeTab?.path { OpenIn.open(folder: path, in: .finder) } }) - menu.addItem(MenuAction.item("Open in Terminal", enabled: { window?.activeTab != nil }) { - if let path = window?.activeTab?.path { TabBar.openInTerminal(path) } + menu.addItem(MenuAction.item("Open in Terminal", key: "t", modifiers: [.option], enabled: hasTab, title: { "Open in \(OpenIn.terminal().name)" }) { + if let path = window?.activeTab?.path { OpenIn.openInTerminal(path) } + }) + menu.addItem(MenuAction.item("Open in Claude Code", enabled: { window?.activeTab != nil }, visible: { OpenIn.claudeApp != nil }) { + if let path = window?.activeTab?.path { OpenIn.claudeCode(folder: path, inTerminal: false) } + }) + menu.addItem(MenuAction.item("Open Claude Code in Terminal", enabled: { window?.activeTab != nil }, visible: { OpenIn.claudeTerminal != nil }) { + if let path = window?.activeTab?.path { OpenIn.claudeCode(folder: path, inTerminal: true) } }) return menu } + /// The file Review shows on its own, if it can open: on disk, or a commit's version of it. + private static var openableFile: ReviewFile? { + guard let repository, let file = repository.quickLookFile, !file.isSubmodule else { return nil } + return repository.existingFile(file.path) != nil || file.opening.version != nil ? file : nil + } + /// The text view being typed in (a field's editor, the description), if any. private static var textView: NSTextView? { NSApp.keyWindow?.firstResponder as? NSTextView } @@ -559,20 +586,24 @@ final class MenuAction: NSObject, NSMenuItemValidation { private let isAvailable: () -> Bool private let isChecked: (() -> Bool)? private let currentTitle: (() -> String)? + private let isVisible: (() -> Bool)? - private init(run: @escaping () -> Void, isAvailable: @escaping () -> Bool, isChecked: (() -> Bool)?, title: (() -> String)?) { + private init(run: @escaping () -> Void, isAvailable: @escaping () -> Bool, isChecked: (() -> Bool)?, title: (() -> String)?, + visible: (() -> Bool)?) { self.run = run self.isAvailable = isAvailable self.isChecked = isChecked self.currentTitle = title + self.isVisible = visible super.init() } /// `title`: when set, the item's title is updated each time it's validated ("Undo Checkout develop"). + /// `visible`: when set, the item is hidden while it's false (Open in Claude Code without the Claude app). static func item(_ title: String, key: String = "", modifiers: NSEvent.ModifierFlags = [.command], enabled: @escaping () -> Bool = { true }, checked: (() -> Bool)? = nil, title currentTitle: (() -> String)? = nil, - run: @escaping () -> Void) -> NSMenuItem { - let action = MenuAction(run: run, isAvailable: enabled, isChecked: checked, title: currentTitle) + visible: (() -> Bool)? = nil, run: @escaping () -> Void) -> NSMenuItem { + let action = MenuAction(run: run, isAvailable: enabled, isChecked: checked, title: currentTitle, visible: visible) // AppKit spells Shift with a letter as the uppercase letter (⇧⌘T is "T" with ⌘). var key = key var modifiers = modifiers @@ -594,6 +625,7 @@ final class MenuAction: NSObject, NSMenuItemValidation { func validateMenuItem(_ menuItem: NSMenuItem) -> Bool { if let isChecked { menuItem.state = isChecked() ? .on : .off } if let currentTitle { menuItem.title = currentTitle() } + if let isVisible { menuItem.isHidden = !isVisible() } return isAvailable() } } diff --git a/Kaern/App/OpenIn.swift b/Kaern/App/OpenIn.swift new file mode 100644 index 0000000..98b6607 --- /dev/null +++ b/Kaern/App/OpenIn.swift @@ -0,0 +1,361 @@ +import AppKit +import KaernKit +import UniformTypeIdentifiers + +/// An app Kaern opens a repository or a file in: an editor, a terminal, Finder. +struct ExternalApp: Hashable, Identifiable { + /// Its bundle identifier. + let id: String + /// Its name while it isn't installed; an installed app goes by the name it has on this Mac. + let fallbackName: String + /// `://file/::`: VS Code and the editors built on it open a file at a line this way. + var fileScheme: String? + + static let finder = ExternalApp(id: "com.apple.finder", fallbackName: "Finder") + + var url: URL? { NSWorkspace.shared.urlForApplication(withBundleIdentifier: id) } + + var name: String { + guard let url else { return fallbackName } + return FileManager.default.displayName(atPath: url.path(percentEncoded: false)).replacingOccurrences(of: ".app", with: "") + } + + /// Its icon, `size` points square (16 in menus, 18 in the toolbar). + func icon(_ size: CGFloat) -> NSImage { + let key = "\(id) \(size)" + if let icon = ExternalApp.icons[key] { return icon } + let path = url?.path(percentEncoded: false) ?? "/System/Applications/Utilities/Terminal.app" + let icon = (NSWorkspace.shared.icon(forFile: path).copy() as? NSImage) ?? NSImage() + icon.size = NSSize(width: size, height: size) + ExternalApp.icons[key] = icon + return icon + } + + private static var icons: [String: NSImage] = [:] + + /// The app macOS opens `url` with (a file's default app). + static func opening(_ url: URL) -> ExternalApp? { + guard let app = NSWorkspace.shared.urlForApplication(toOpen: url), let id = Bundle(url: app)?.bundleIdentifier else { return nil } + return ExternalApp(id: id, fallbackName: app.deletingPathExtension().lastPathComponent) + } +} + +/// Opening a repository or a file somewhere else (the toolbar's Open button, File › Open in…, the file menus): in +/// an editor, a terminal, Finder or Claude Code. The editor and the terminal are Settings › General's; until one +/// is chosen, the first one of these lists that is installed. +/// +/// A test instance (`-KaernSessionFile`) opens nothing: it notes what it would have opened (`debugLog`). +@MainActor +enum OpenIn { + static let editors: [ExternalApp] = [ + ExternalApp(id: "com.microsoft.VSCode", fallbackName: "Visual Studio Code", fileScheme: "vscode"), + ExternalApp(id: "com.todesktop.230313mzl4w4u92", fallbackName: "Cursor", fileScheme: "cursor"), + ExternalApp(id: "com.exafunction.windsurf", fallbackName: "Windsurf", fileScheme: "windsurf"), + ExternalApp(id: "dev.zed.Zed", fallbackName: "Zed"), + ExternalApp(id: "dev.kiro.desktop", fallbackName: "Kiro"), + ExternalApp(id: "com.microsoft.VSCodeInsiders", fallbackName: "Visual Studio Code - Insiders", fileScheme: "vscode-insiders"), + ExternalApp(id: "com.sublimetext.4", fallbackName: "Sublime Text"), + ExternalApp(id: "com.panic.Nova", fallbackName: "Nova"), + ExternalApp(id: "com.barebones.bbedit", fallbackName: "BBEdit"), + ExternalApp(id: "com.jetbrains.intellij", fallbackName: "IntelliJ IDEA"), + ExternalApp(id: "com.jetbrains.intellij.ce", fallbackName: "IntelliJ IDEA CE"), + ExternalApp(id: "com.jetbrains.WebStorm", fallbackName: "WebStorm"), + ExternalApp(id: "com.jetbrains.pycharm", fallbackName: "PyCharm"), + ExternalApp(id: "com.jetbrains.pycharm.ce", fallbackName: "PyCharm CE"), + ExternalApp(id: "com.google.android.studio", fallbackName: "Android Studio"), + ExternalApp(id: "com.apple.dt.Xcode", fallbackName: "Xcode"), + ] + + /// Terminals that open a window in a folder handed to them. + static let terminals: [ExternalApp] = [ + ExternalApp(id: "com.apple.Terminal", fallbackName: "Terminal"), + ExternalApp(id: "com.googlecode.iterm2", fallbackName: "iTerm"), + ExternalApp(id: "com.mitchellh.ghostty", fallbackName: "Ghostty"), + ] + + // MARK: What is installed + + private struct Found { + var editors: [ExternalApp] + var terminals: [ExternalApp] + /// The app that takes `claude://code/new` links: the Claude app. + var claudeApp: ExternalApp? + /// The app that takes `claude-cli://open` links: Claude Code's handler, which claude registers once it has been + /// used, and which opens a terminal window running it. + var claudeTerminal: ExternalApp? + } + + private static var found: Found? + + private static var installed: Found { + if let found { return found } + func handler(_ link: String) -> ExternalApp? { + guard let url = URL(string: link), let app = NSWorkspace.shared.urlForApplication(toOpen: url) else { return nil } + return ExternalApp(id: Bundle(url: app)?.bundleIdentifier ?? app.lastPathComponent, fallbackName: "Claude") + } + let result = Found(editors: editors.filter { $0.url != nil }, terminals: terminals.filter { $0.url != nil }, + claudeApp: handler("claude://code/new"), claudeTerminal: handler("claude-cli://open")) + found = result + return result + } + + /// Looks for the apps again (Kaern became active: one may have been installed or removed meanwhile). + static func refresh() { found = nil } + + static var installedEditors: [ExternalApp] { installed.editors } + static var installedTerminals: [ExternalApp] { installed.terminals } + static var claudeApp: ExternalApp? { installed.claudeApp } + static var claudeTerminal: ExternalApp? { installed.claudeTerminal } + + /// The editor chosen in Settings (its bundle identifier), else the first one installed; nil when none is. + static func editor(chosen: String? = UserDefaults.kaern.string(forKey: SettingsKey.openEditor)) -> ExternalApp? { + installedEditors.first { $0.id == chosen } ?? installedEditors.first + } + + /// The terminal chosen in Settings, else the first one installed (Terminal comes with macOS). + static func terminal(chosen: String? = UserDefaults.kaern.string(forKey: SettingsKey.openTerminal)) -> ExternalApp { + installedTerminals.first { $0.id == chosen } ?? installedTerminals.first ?? terminals[0] + } + + /// What the toolbar's Open button opens a repository in: the editor, else Finder. + static func repositoryApp(chosen: String? = UserDefaults.kaern.string(forKey: SettingsKey.openEditor)) -> ExternalApp { + editor(chosen: chosen) ?? .finder + } + + /// Text and code open in the editor; a picture, a PDF and the like in the app macOS opens them with. + static func isText(_ path: String) -> Bool { + let ext = (path as NSString).pathExtension + guard !ext.isEmpty, let type = UTType(filenameExtension: ext), !type.isDynamic else { return true } + return [UTType.text, .sourceCode, .script, .json, .xml, .propertyList, .yaml].contains { type.conforms(to: $0) } + } + + /// The app a file opens in: the editor for text, else the app macOS opens it with. + static func app(forFile url: URL, chosen: String? = UserDefaults.kaern.string(forKey: SettingsKey.openEditor)) -> ExternalApp? { + if isText(url.lastPathComponent), let editor = editor(chosen: chosen) { return editor } + return ExternalApp.opening(url) ?? editor(chosen: chosen) + } + + // MARK: Opening + + /// The folder `path` in `app`: Finder shows what's in it, an editor opens it as a project, a terminal opens a + /// window there. + static func open(folder path: String, in app: ExternalApp) { + let folder = URL(filePath: path, directoryHint: .isDirectory) + if app.id == ExternalApp.finder.id { + perform("finder \(path)") { NSWorkspace.shared.open(folder) } + return + } + guard let location = app.url else { return } + perform("\(app.id) \(path)") { + NSWorkspace.shared.open([folder], withApplicationAt: location, configuration: NSWorkspace.OpenConfiguration()) + } + } + + static func openInTerminal(_ path: String) { + open(folder: path, in: terminal()) + } + + /// A file selected in a Finder window of its folder. + static func reveal(_ url: URL) { + perform("reveal \(url.path(percentEncoded: false))") { NSWorkspace.shared.activateFileViewerSelecting([url]) } + } + + /// The file `url` in `app` (nil: the app macOS opens it with), at `line` where the app can: VS Code and its forks + /// by their file links, Xcode with `xed`. + static func open(file url: URL, line: Int? = nil, in app: ExternalApp?) { + let path = url.path(percentEncoded: false) + guard let app else { + perform("default \(path)") { NSWorkspace.shared.open(url) } + return + } + let place = line.map { "\(path):\($0)" } ?? path + if let line, let scheme = app.fileScheme, let encoded = path.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed), + let link = URL(string: "\(scheme)://file\(encoded):\(line):1") { + perform("\(app.id) \(place)") { + // Its link handler not set up: the file opens without the line. + if !NSWorkspace.shared.open(link), let location = app.url { + NSWorkspace.shared.open([url], withApplicationAt: location, configuration: NSWorkspace.OpenConfiguration()) + } + } + return + } + if let line, app.id == "com.apple.dt.Xcode", FileManager.default.isExecutableFile(atPath: "/usr/bin/xed") { + perform("\(app.id) \(place)") { + let process = Process() + process.executableURL = URL(filePath: "/usr/bin/xed") + process.arguments = ["--line", String(line), path] + try? process.run() + } + return + } + guard let location = app.url else { return } + perform("\(app.id) \(path)") { + NSWorkspace.shared.open([url], withApplicationAt: location, configuration: NSWorkspace.OpenConfiguration()) + } + } + + /// Claude Code in `folder`: the Claude app's Code tab (it asks before it takes a folder from a link), or a new + /// terminal window running claude. `prompt` waits in its input field; nothing is sent. + static func claudeCode(folder: String, prompt: String? = nil, inTerminal: Bool) { + var query = [inTerminal ? "cwd" : "folder": folder] + if let prompt { query["q"] = prompt } + let pairs = query.sorted { $0.key < $1.key }.map { "\($0.key)=\($0.value.addingPercentEncoding(withAllowedCharacters: .linkValue) ?? "")" } + guard let link = URL(string: (inTerminal ? "claude-cli://open?" : "claude://code/new?") + pairs.joined(separator: "&")) else { return } + perform("link \(link.absoluteString)") { NSWorkspace.shared.open(link) } + } + + /// What Claude Code is asked to look at for a file: `@path`, quoted when it has a space. + static func mention(_ path: String) -> String { + (path.contains(" ") ? "@\"\(path)\"" : "@" + path) + " " + } + + #if DEBUG + /// What a test instance would have opened: " [:line]", "finder ", "reveal ", + /// "default ", "link ". + static var debugLog: [String] = [] + #endif + + private static func perform(_ entry: String, _ open: () -> Void) { + #if DEBUG + if SessionStore.testSessionPath != nil { + debugLog.append(entry) + return + } + #endif + open() + } +} + +private extension CharacterSet { + /// What a link's query value keeps as it is; the rest is percent-encoded (`&`, `=`, `+`, spaces, `@`…). + static let linkValue = CharacterSet(charactersIn: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~/") +} + +/// A file as the Open buttons and menus open it: its place in the repository, where its first change is, and the +/// version Review shows when that isn't the file on disk (a commit's). +struct FileOpening: Equatable { + /// The path in the repository. + let path: String + /// The first changed line, on the new side. + var line: Int? + /// The version Review shows when it's a commit's, for Open Version at…: the commit, and the path there. + var version: (commit: String, path: String)? + + static func == (lhs: FileOpening, rhs: FileOpening) -> Bool { + lhs.path == rhs.path && lhs.line == rhs.line && lhs.version?.commit == rhs.version?.commit && lhs.version?.path == rhs.version?.path + } + + var name: String { (path as NSString).lastPathComponent } +} + +extension ReviewFile { + /// A submodule is a folder of its own: no Open button. + var isSubmodule: Bool { + if case .submodule? = special { return true } + return false + } + + /// How the Open buttons and menus open this file. + var opening: FileOpening { + var opening = FileOpening(path: path, line: firstChangedLine) + if case .revision(let commit)? = sides.new { + opening.version = (commit, path) + } else if sides.new == nil, case .revision(let commit)? = sides.old { + // Deleted there: the last version it had. + opening.version = (commit, sides.oldPath ?? path) + } + return opening + } + + /// The first line its change touches in the new version: an added line, or where removed lines were. + var firstChangedLine: Int? { + for hunk in hunks.map(\.hunk).sorted(by: { $0.newStart < $1.newStart }) { + var last = max(hunk.newStart - 1, 0) + for line in hunk.lines { + if line.kind == .addition, let number = line.newNumber { return number } + if line.kind == .deletion { return last + 1 } + if let number = line.newNumber { last = number } + } + } + return nil + } +} + +extension RepositoryModel { + func fileOpening(_ path: String) -> FileOpening { + reviewFiles?.first { $0.path == path }?.opening ?? FileOpening(path: path) + } + + /// What a file's Open menu says Review shows of it: "uncommitted", "staged", "in e7b7dd2". + func openSubtitle(_ file: ReviewFile?) -> String { + if let compare = review?.compare { + return compare.target.map { "in \($0.prefix(7))" } ?? "working copy" + } + switch selection { + case .workingCopy: return file.map { $0.hasStaged && !$0.hasUnstaged } == true ? "staged" : "uncommitted" + case .commit(let id): return "in \(id.prefix(7))" + } + } + + /// The file on disk, if it's there. + func existingFile(_ path: String) -> URL? { + guard let url = fileURL(path), FileManager.default.fileExists(atPath: url.path(percentEncoded: false)) else { return nil } + return url + } + + /// Opens a file in `app` (nil: the app it opens in), at its first change. + func open(_ opening: FileOpening, in app: ExternalApp? = nil) { + guard let url = existingFile(opening.path) else { + if opening.version != nil { openVersion(opening, in: app) } + return + } + OpenIn.open(file: url, line: opening.line, in: app ?? OpenIn.app(forFile: url)) + } + + /// The version a commit has of a file, as a read-only copy named after the commit ("Feed (e7b7dd2).swift"), + /// opened in `app` (nil: the app it opens in). + func openVersion(_ opening: FileOpening, in app: ExternalApp? = nil) { + guard let version = opening.version else { return } + Task { + let short = String(version.commit.prefix(7)) + guard let contents = await fileContents(version.path, at: .revision(version.commit)), let data = contents.data else { + showToast("Couldn’t read \(opening.name) at \(short)") + return + } + do { + let url = try VersionCopies.make(data, name: opening.name, commit: short) + OpenIn.open(file: url, line: opening.line, in: app ?? OpenIn.app(forFile: url)) + } catch { + showToast("Couldn’t open \(opening.name) at \(short): \(error.localizedDescription)") + } + } + } +} + +/// The read-only copies Open Version at… opens, in the temporary folder. A copy stays while its editor may show it; +/// copies over a day old go at launch. +enum VersionCopies { + static let folder = FileManager.default.temporaryDirectory.appending(path: "Kaern Versions", directoryHint: .isDirectory) + + static func make(_ data: Data, name: String, commit: String) throws -> URL { + let place = folder.appending(path: String(UUID().uuidString.prefix(8)), directoryHint: .isDirectory) + try FileManager.default.createDirectory(at: place, withIntermediateDirectories: true) + let ext = (name as NSString).pathExtension + let base = (name as NSString).deletingPathExtension + let url = place.appending(path: "\(base) (\(commit))" + (ext.isEmpty ? "" : ".\(ext)")) + try data.write(to: url) + try FileManager.default.setAttributes([.posixPermissions: 0o444], ofItemAtPath: url.path(percentEncoded: false)) + return url + } + + static func removeOld() { + let fileManager = FileManager.default + guard let items = try? fileManager.contentsOfDirectory(at: folder, includingPropertiesForKeys: [.contentModificationDateKey]) else { + return + } + let dayAgo = Date().addingTimeInterval(-86_400) + for item in items where ((try? item.resourceValues(forKeys: [.contentModificationDateKey]))?.contentModificationDate ?? .distantPast) < dayAgo { + try? fileManager.removeItem(at: item) + } + } +} diff --git a/Kaern/Repository/RepositoryModel+Actions.swift b/Kaern/Repository/RepositoryModel+Actions.swift index f9a7ccb..2d2eec7 100644 --- a/Kaern/Repository/RepositoryModel+Actions.swift +++ b/Kaern/Repository/RepositoryModel+Actions.swift @@ -557,23 +557,10 @@ extension RepositoryModel { repository?.root.appending(path: path) } - /// "Open in Xcode": the app macOS opens the file with. - func defaultAppName(for path: String) -> String? { - guard let url = fileURL(path), let app = NSWorkspace.shared.urlForApplication(toOpen: url) else { return nil } - return FileManager.default.displayName(atPath: app.path(percentEncoded: false)).replacingOccurrences(of: ".app", with: "") - } - + /// A file at a line (one a failure names), in the app it opens in (`OpenIn`). func open(path: String, line: Int? = nil) { guard let url = fileURL(path) else { return } - if let line, FileManager.default.isExecutableFile(atPath: "/usr/bin/xed"), - NSWorkspace.shared.urlForApplication(toOpen: url)?.lastPathComponent.hasPrefix("Xcode") == true { - let process = Process() - process.executableURL = URL(filePath: "/usr/bin/xed") - process.arguments = ["--line", String(line), url.path(percentEncoded: false)] - try? process.run() - } else { - NSWorkspace.shared.open(url) - } + OpenIn.open(file: url, line: line, in: OpenIn.app(forFile: url)) } } diff --git a/Kaern/Settings/AppSettings.swift b/Kaern/Settings/AppSettings.swift index 4ec6c16..b2f8299 100644 --- a/Kaern/Settings/AppSettings.swift +++ b/Kaern/Settings/AppSettings.swift @@ -42,6 +42,10 @@ nonisolated enum SettingsKey { /// Settings › General › Updates › Get beta versions: Sparkle also offers the appcast's beta channel. A beta /// starts with it on (UpdateController). static let betaUpdates = "KaernBetaUpdates" + /// Settings › General › Open in: the editor (its bundle identifier) the toolbar's Open button, ⌥E and ⌘↓ use. + static let openEditor = "KaernOpenEditor" + /// Settings › General › Open in: the terminal (its bundle identifier) ⌥T and Open in Terminal use. + static let openTerminal = "KaernOpenTerminal" // Accounts static let accounts = "KaernAccounts" // Diff diff --git a/Kaern/Settings/SettingsWindow.swift b/Kaern/Settings/SettingsWindow.swift index 9ef63fc..9980f08 100644 --- a/Kaern/Settings/SettingsWindow.swift +++ b/Kaern/Settings/SettingsWindow.swift @@ -259,6 +259,10 @@ private struct GeneralPane: View { .labelsHidden() .fixedSize() } + SettingsRow(label: "Open in:") { + OpenInSettings() + Hint("The toolbar’s Open button opens a repository in the editor (⌥E), and Review’s opens a file there at its first change (⌘↓). ⌥O opens the repository in Finder and ⌥T in the terminal. Claude Code is in the Open button’s ▾ menu.") + } SettingsRow(label: "Appearance:") { SegmentedChoice(options: [(AppTheme.system, "System"), (.light, "Light"), (.dark, "Dark")], selection: $theme, label: "Appearance") .padding(.top, 1) @@ -282,6 +286,44 @@ private struct GeneralPane: View { } } +/// General › Open in: the editor and the terminal Kaern opens repositories and files in (`OpenIn`), from the ones +/// installed on this Mac. +private struct OpenInSettings: View { + @AppStorage(SettingsKey.openEditor, store: .kaern) private var editorID = "" + @AppStorage(SettingsKey.openTerminal, store: .kaern) private var terminalID = "" + + var body: some View { + let editors = OpenIn.installedEditors + Grid(alignment: .leading, horizontalSpacing: z(8), verticalSpacing: z(8)) { + GridRow { + Text("Editor") + if editors.isEmpty { + Text("None found · repositories open in Finder").foregroundStyle(K.label2) + } else { + Picker("Editor", selection: Binding(get: { OpenIn.editor(chosen: editorID)?.id ?? "" }, set: { editorID = $0 })) { + ForEach(editors) { app in + Label { Text(app.name) } icon: { Image(nsImage: app.icon(16)) }.tag(app.id) + } + } + .labelsHidden() + .fixedSize() + } + } + GridRow { + Text("Terminal") + Picker("Terminal", selection: Binding(get: { OpenIn.terminal(chosen: terminalID).id }, set: { terminalID = $0 })) { + ForEach(OpenIn.installedTerminals) { app in + Label { Text(app.name) } icon: { Image(nsImage: app.icon(16)) }.tag(app.id) + } + } + .labelsHidden() + .fixedSize() + } + } + .font(.system(size: z(13))) + } +} + extension GeneralPane { /// The line under the three layouts. var switchingDescription: String { diff --git a/Kaern/Views/CommandLog/CommandLogWindow.swift b/Kaern/Views/CommandLog/CommandLogWindow.swift index 4cbbd58..63675fd 100644 --- a/Kaern/Views/CommandLog/CommandLogWindow.swift +++ b/Kaern/Views/CommandLog/CommandLogWindow.swift @@ -370,11 +370,11 @@ private struct CommandDetail: View { .padding(.top, z(10)) HStack(spacing: z(6)) { GhostButton(title: "Copy Command") { copy(record.commandLine, "Copied the command") } - GhostButton(title: "Open in Terminal") { + GhostButton(title: "Open in \(OpenIn.terminal().name)") { NSPasteboard.general.clearContents() NSPasteboard.general.setString(record.commandLine, forType: .string) - TabBar.openInTerminal(record.directory) - flash("Opened Terminal in \(Formatters.abbreviatedPath(record.directory)) · the command is on the clipboard") + OpenIn.openInTerminal(record.directory) + flash("Opened \(OpenIn.terminal().name) in \(Formatters.abbreviatedPath(record.directory)) · the command is on the clipboard") } .disabled(record.directory.isEmpty) } diff --git a/Kaern/Views/Common/DebugFrame.swift b/Kaern/Views/Common/DebugFrame.swift new file mode 100644 index 0000000..5ba72e5 --- /dev/null +++ b/Kaern/Views/Common/DebugFrame.swift @@ -0,0 +1,39 @@ +import SwiftUI + +extension View { + /// Where the debug driver finds this view (`driver.frames` in its dump, window points from the top left), by `name`. + /// Nothing in a Release build. + func debugFrame(_ name: String) -> some View { + #if DEBUG + modifier(DebugFrameModifier(name: name)) + #else + self + #endif + } +} + +#if DEBUG +/// The frames views report with `debugFrame(_:)`, for a check to click them. +@MainActor +final class DebugFrames { + static let shared = DebugFrames() + var frames: [String: CGRect] = [:] +} + +private struct DebugFrameModifier: ViewModifier { + let name: String + @State private var place = FramePlace() + + func body(content: Content) -> some View { + content + // `.global` is the window's content view, which fills the window (top-left origin). + .onGeometryChange(for: CGRect.self) { $0.frame(in: .global) } action: { frame in + place.frame = frame + DebugFrames.shared.frames[name] = frame + } + // Back where it was (its tab shows again): nothing moved, so nothing above ran. + .onAppear { if let frame = place.frame { DebugFrames.shared.frames[name] = frame } } + .onDisappear { DebugFrames.shared.frames[name] = nil } + } +} +#endif diff --git a/Kaern/Views/Menus/ContextMenus.swift b/Kaern/Views/Menus/ContextMenus.swift index e5af822..ef80adb 100644 --- a/Kaern/Views/Menus/ContextMenus.swift +++ b/Kaern/Views/Menus/ContextMenus.swift @@ -452,13 +452,9 @@ enum ContextMenus { } menu.addItem(submenu("Ignore", enabled: idle, items: ignoreItems)) menu.addItem(.separator()) - let app = r.defaultAppName(for: path) - let exists = r.fileURL(path).map { FileManager.default.fileExists(atPath: $0.path(percentEncoded: false)) } ?? false - menu.addItem(item("Open in \(app ?? "Default App")", key: String(Character(UnicodeScalar(UInt16(NSDownArrowFunctionKey))!)), - enabled: exists && app != nil) { r.open(path: path) }) - menu.addItem(item("Show in Finder", enabled: exists) { - if let url = r.fileURL(path) { NSWorkspace.shared.activateFileViewerSelecting([url]) } - }) + openItems(r.fileOpening(path), r).forEach(menu.addItem) + let file = r.existingFile(path) + menu.addItem(item("Show in Finder", enabled: file != nil) { if let file { OpenIn.reveal(file) } }) menu.addItem(item("Copy Path") { r.copy(path, toast: "Copied \(path)") }) menu.addItem(.separator()) menu.addItem(item("Show File History", hint: entry.isUntracked ? "Not committed yet" : nil, enabled: !entry.isUntracked) { @@ -501,10 +497,12 @@ enum ContextMenus { menu.addItem(item("Show File History") { r.showFileHistory(path, at: commit) }) menu.addItem(item("Blame at \(String(commit.prefix(7)))") { r.showBlame(path, at: commit) }) menu.addItem(.separator()) - let exists = r.fileURL(path).map { FileManager.default.fileExists(atPath: $0.path(percentEncoded: false)) } ?? false - menu.addItem(item("Show in Finder", enabled: exists) { - if let url = r.fileURL(path) { NSWorkspace.shared.activateFileViewerSelecting([url]) } - }) + // Review's version of it when this commit is what Review shows; this commit's otherwise. + var opening = r.fileOpening(path) + if opening.version?.commit != commit { opening = FileOpening(path: path, version: (commit, path)) } + openItems(opening, r).forEach(menu.addItem) + let file = r.existingFile(path) + menu.addItem(item("Show in Finder", enabled: file != nil) { if let file { OpenIn.reveal(file) } }) menu.addItem(item("Copy Path") { r.copy(path, toast: "Copied \(path)") }) return menu } diff --git a/Kaern/Views/Menus/OpenMenus.swift b/Kaern/Views/Menus/OpenMenus.swift new file mode 100644 index 0000000..6f62284 --- /dev/null +++ b/Kaern/Views/Menus/OpenMenus.swift @@ -0,0 +1,141 @@ +import AppKit +import KaernKit + +/// The Open menus: the toolbar Open button's ▾ (a repository), a file's Open ▾ (Review), and the Open items of the +/// files' right-click menus. What they open in is `OpenIn`'s. +extension ContextMenus { + /// ⌘↓ as a menu shows it (Finder's Open). + static let openKey = String(Character(UnicodeScalar(UInt16(NSDownArrowFunctionKey))!)) + + /// An app's icon beside an item. From macOS 27, menus hide an item's image unless it asks to show it. + static func showIcon(_ item: NSMenuItem, _ icon: NSImage) { + item.image = icon + if #available(macOS 27, *) { item.preferredImageVisibility = .visible } + } + + /// The toolbar Open button's ▾: the editors (✓ the button's, ⌥E), Claude Code, Finder (⌥O), the terminal (⌥T), + /// Copy Path, and which editor the button uses. + static func openInMenu(_ r: RepositoryModel) -> NSMenu { + let path = r.path + let menu = NSMenu(title: "Open In") + menu.autoenablesItems = false + menu.addItem(header(r.name, Formatters.abbreviatedPath(path))) + let editors = OpenIn.installedEditors + let current = OpenIn.editor() + for editor in editors { + let isCurrent = editor == current + let menuItem = item(editor.name, key: isCurrent ? "e" : "", modifiers: [.option]) { OpenIn.open(folder: path, in: editor) } + showIcon(menuItem, editor.icon(16)) + menuItem.state = isCurrent ? .on : .off + menu.addItem(menuItem) + } + if !editors.isEmpty { menu.addItem(.separator()) } + let claude = claudeItems(folder: path, prompt: nil) + claude.forEach(menu.addItem) + if !claude.isEmpty { menu.addItem(.separator()) } + let finder = item("Finder", key: "o", modifiers: [.option]) { OpenIn.open(folder: path, in: .finder) } + showIcon(finder, ExternalApp.finder.icon(16)) + menu.addItem(finder) + let terminal = OpenIn.terminal() + let terminalItem = item(terminal.name, key: "t", modifiers: [.option]) { OpenIn.openInTerminal(path) } + showIcon(terminalItem, terminal.icon(16)) + menu.addItem(terminalItem) + menu.addItem(.separator()) + menu.addItem(item("Copy Path") { r.copy(path, toast: "Copied \(Formatters.abbreviatedPath(path))") }) + if editors.count > 1 { + menu.addItem(submenu("Default Editor", enabled: true, items: editors.map { editor in + let menuItem = item(editor.name) { UserDefaults.kaern.set(editor.id, forKey: SettingsKey.openEditor) } + showIcon(menuItem, editor.icon(16)) + menuItem.state = editor == current ? .on : .off + return menuItem + })) + } + return fitHeader(menu) + } + + /// A file's Open ▾ (Review's header, All Files' file headers): the apps it opens in at its first change (✓ the + /// button's), Claude Code with the file named, the version Review shows when that's a commit's, Finder. + static func openFileMenu(_ opening: FileOpening, subtitle: String, _ r: RepositoryModel) -> NSMenu { + let menu = NSMenu(title: opening.path) + menu.autoenablesItems = false + let directory = (opening.path as NSString).deletingLastPathComponent + menu.addItem(header(opening.name, (directory.isEmpty ? "" : directory + "/ · ") + subtitle)) + let choices = openChoices(opening, r) + for app in choices.apps { + let isFirst = app == choices.first + let menuItem = item(app.name, hint: app == choices.macDefault && !isFirst ? "macOS default" : choices.reason, + key: isFirst ? openKey : "", modifiers: [.command], enabled: choices.enabled) { r.open(opening, in: app) } + showIcon(menuItem, app.icon(16)) + menuItem.state = isFirst ? .on : .off + menu.addItem(menuItem) + } + menu.addItem(.separator()) + let claude = claudeItems(folder: r.path, prompt: OpenIn.mention(opening.path)) + claude.forEach(menu.addItem) + if !claude.isEmpty { menu.addItem(.separator()) } + if let version = opening.version { + menu.addItem(item("Open Version at \(version.commit.prefix(7))", hint: "Read-only copy") { r.openVersion(opening) }) + menu.addItem(.separator()) + } + let file = r.existingFile(opening.path) + menu.addItem(item("Show in Finder", enabled: file != nil) { if let file { OpenIn.reveal(file) } }) + menu.addItem(item("Copy Path") { r.copy(opening.path, toast: "Copied \(opening.path)") }) + return fitHeader(menu) + } + + /// A file's right-click Open items: Open in (⌘↓), then Open With ▸ the others and + /// Claude Code; for a commit's file, Open Version at…. + static func openItems(_ opening: FileOpening, _ r: RepositoryModel) -> [NSMenuItem] { + let choices = openChoices(opening, r) + var items: [NSMenuItem] = [] + if let first = choices.first { + items.append(item("Open in \(first.name)", hint: choices.reason, key: openKey, modifiers: [.command], + enabled: choices.enabled) { r.open(opening, in: first) }) + } + var others: [NSMenuItem] = choices.apps.filter { $0 != choices.first }.map { app in + let menuItem = item(app.name, hint: app == choices.macDefault ? "macOS default" : nil, enabled: choices.enabled) { + r.open(opening, in: app) + } + showIcon(menuItem, app.icon(16)) + return menuItem + } + let claude = claudeItems(folder: r.path, prompt: OpenIn.mention(opening.path)) + if !others.isEmpty, !claude.isEmpty { others.append(.separator()) } + others += claude + if !others.isEmpty { items.append(submenu("Open With", enabled: true, items: others)) } + if let version = opening.version { + items.append(item("Open Version at \(version.commit.prefix(7))", hint: "Read-only copy") { r.openVersion(opening) }) + } + return items + } + + /// Where a file can open: the app its button uses first, then the editors, then the app macOS opens it with. + /// A file that isn't on disk opens its commit's version, or nothing (`reason`). + private static func openChoices(_ opening: FileOpening, _ r: RepositoryModel) + -> (apps: [ExternalApp], first: ExternalApp?, macDefault: ExternalApp?, enabled: Bool, reason: String?) { + let file = r.existingFile(opening.path) + let first = OpenIn.app(forFile: file ?? URL(filePath: opening.path)) + let macDefault = file.flatMap(ExternalApp.opening) + var seen = Set() + let apps = ([first].compactMap { $0 } + OpenIn.installedEditors + [macDefault].compactMap { $0 }).filter { seen.insert($0.id).inserted } + let enabled = file != nil || opening.version != nil + return (apps, first, macDefault, enabled, enabled ? nil : "Not on disk") + } + + /// Claude Code's two ways in, as far as they're set up on this Mac: the Claude app's Code tab, and claude in a + /// terminal window. `prompt` waits in its input field. + static func claudeItems(folder: String, prompt: String?) -> [NSMenuItem] { + var items: [NSMenuItem] = [] + if let app = OpenIn.claudeApp { + let menuItem = item("Claude Code", hint: "Claude app") { OpenIn.claudeCode(folder: folder, prompt: prompt, inTerminal: false) } + showIcon(menuItem, app.icon(16)) + items.append(menuItem) + } + if let handler = OpenIn.claudeTerminal { + let menuItem = item("Claude Code", hint: "Terminal") { OpenIn.claudeCode(folder: folder, prompt: prompt, inTerminal: true) } + showIcon(menuItem, (OpenIn.claudeApp ?? handler).icon(16)) + items.append(menuItem) + } + return items + } +} diff --git a/Kaern/Views/QuickOpen/QuickOpen.swift b/Kaern/Views/QuickOpen/QuickOpen.swift index 0894c45..1eab240 100644 --- a/Kaern/Views/QuickOpen/QuickOpen.swift +++ b/Kaern/Views/QuickOpen/QuickOpen.swift @@ -159,7 +159,24 @@ enum QuickOpenSource { Command(title: "Command Log", shortcut: "⇧⌘L") { CommandLogWindowController.shared.show(repository: r.path) }, Command(title: "Activity", shortcut: "⌥⌘A") { NotificationCenter.default.post(name: .kaernShowActivity, object: r.id) }, Command(title: "Settings…", shortcut: "⌘,") { SettingsWindowController.shared.show() }, - ] + ] + openCommands(r) + } + + /// The repository somewhere else (ScreenOpenIn): the editor, Finder, the terminal, Claude Code. + private static func openCommands(_ r: RepositoryModel) -> [Command] { + var commands: [Command] = [] + if let editor = OpenIn.editor() { + commands.append(Command(title: "Open in \(editor.name)", shortcut: "⌥E") { OpenIn.open(folder: r.path, in: editor) }) + } + commands.append(Command(title: "Open in Finder", shortcut: "⌥O") { OpenIn.open(folder: r.path, in: .finder) }) + commands.append(Command(title: "Open in \(OpenIn.terminal().name)", shortcut: "⌥T") { OpenIn.openInTerminal(r.path) }) + if OpenIn.claudeApp != nil { + commands.append(Command(title: "Open in Claude Code", shortcut: "") { OpenIn.claudeCode(folder: r.path, inTerminal: false) }) + } + if OpenIn.claudeTerminal != nil { + commands.append(Command(title: "Open Claude Code in Terminal", shortcut: "") { OpenIn.claudeCode(folder: r.path, inTerminal: true) }) + } + return commands } } diff --git a/Kaern/Views/RepositoryList/RepositoryListView.swift b/Kaern/Views/RepositoryList/RepositoryListView.swift index dd42e47..a4b3f4e 100644 --- a/Kaern/Views/RepositoryList/RepositoryListView.swift +++ b/Kaern/Views/RepositoryList/RepositoryListView.swift @@ -659,12 +659,7 @@ enum RepoListMenus { Button("Remove from Group") { window.removeFromGroup(tab.id) } .disabled(tab.group == nil) Divider() - Button("Show in Finder") { NSWorkspace.shared.activateFileViewerSelecting([URL(filePath: tab.path)]) } - Button("Open in Terminal") { TabBar.openInTerminal(tab.path) } - Button("Copy Path") { - NSPasteboard.general.clearContents() - NSPasteboard.general.setString(tab.path, forType: .string) - } + OpenInButtons(path: tab.path) Divider() Button("Move to New Window") { app.moveToNewWindow(tab.id, from: window) } .disabled(window.tabs.count < 2) diff --git a/Kaern/Views/Review/FileOpenButton.swift b/Kaern/Views/Review/FileOpenButton.swift new file mode 100644 index 0000000..ab126b0 --- /dev/null +++ b/Kaern/Views/Review/FileOpenButton.swift @@ -0,0 +1,69 @@ +import AppKit +import SwiftUI + +/// A file's Open button (ScreenOpenIn: Review's header, All Files' file headers): the app the file opens in, shown by +/// its icon, opens it at its first change; ▾ lists the other apps, Claude Code, Open Version at… and Finder. A file +/// that isn't on disk opens the commit's version Review shows, or nothing. +struct FileOpenButton: View { + let repository: RepositoryModel + let opening: FileOpening + /// The menu header's second line ("uncommitted", "in e7b7dd2"). + let subtitle: String + /// The key that opens it too, for its tooltip (⌘↓ for the file Review shows on its own). + var shortcut: String? + /// Settings › General's editor: the button follows it. + @AppStorage(SettingsKey.openEditor, store: .kaern) private var editorID = "" + @State private var hovering = false + @State private var menuHovering = false + @State private var anchor = MenuAnchor() + + var body: some View { + let file = repository.existingFile(opening.path) + let enabled = file != nil || opening.version != nil + let app = enabled ? OpenIn.app(forFile: file ?? URL(filePath: opening.path), chosen: editorID) : nil + HStack(spacing: 0) { + Button { repository.open(opening, in: app) } label: { + Group { + if let app { + Image(nsImage: app.icon(16)).resizable().interpolation(.high) + } else { + Icon(Icons.file, size: 13).foregroundStyle(K.label3) + } + } + .frame(width: z(15), height: z(15)) + .frame(width: z(26), height: z(24)) + .background(RoundedRectangle(cornerRadius: z(6), style: .continuous).fill(hovering && enabled ? K.hover : .clear)) + .contentShape(Rectangle()) + } + .buttonStyle(.plain) + .disabled(!enabled) + .onHover { hovering = $0 } + .help(app.map { "Open in \($0.name)" + (shortcut.map { " (\($0))" } ?? "") } ?? "\(opening.name) isn’t on disk") + .accessibilityLabel(app.map { "Open \(opening.name) in \($0.name)" } ?? "\(opening.name) isn’t on disk") + .debugFrame("openFile \(repository.path) \(opening.path)") + Button { showMenu() } label: { + Icon(Icons.chevronDown, size: 8) + .foregroundStyle(K.label2) + .frame(width: z(14), height: z(24)) + .background(RoundedRectangle(cornerRadius: z(6), style: .continuous).fill(menuHovering ? K.hover : .clear)) + .contentShape(Rectangle()) + } + .buttonStyle(.plain) + .onHover { menuHovering = $0 } + .help("Open In") + .accessibilityLabel("Open \(opening.name) in another app") + .debugFrame("openFileMenu \(repository.path) \(opening.path)") + } + .padding(.horizontal, z(1)) + .controlSurface(radius: z(7)) + .background(MenuAnchorView(anchor: anchor)) + .fixedSize() + } + + /// Under the button, its right edge at the button's: the button ends its header. + private func showMenu() { + guard let view = anchor.view else { return } + let menu = ContextMenus.openFileMenu(opening, subtitle: subtitle, repository) + menu.popUp(positioning: nil, at: NSPoint(x: view.bounds.width - menu.size.width, y: -4), in: view) + } +} diff --git a/Kaern/Views/Review/ReviewView.swift b/Kaern/Views/Review/ReviewView.swift index 696222b..67d13e8 100644 --- a/Kaern/Views/Review/ReviewView.swift +++ b/Kaern/Views/Review/ReviewView.swift @@ -24,7 +24,8 @@ struct ReviewView: View { let state = repository.review ?? ReviewState() let files = repository.reviewFiles VStack(spacing: 0) { - ReviewHeader(repository: repository, files: files ?? [], state: state, layout: $layout) + ReviewHeader(repository: repository, files: files ?? [], state: state, layout: $layout, + target: contextTarget, openSubtitle: openSubtitle) if let files, files.contains(where: { !$0.pickable.isEmpty }), state.compare == nil { LinePickHint() } @@ -71,6 +72,11 @@ struct ReviewView: View { } } + /// What a file's Open menu says it is ("uncommitted", "in e7b7dd2"). + private func openSubtitle(_ file: ReviewFile) -> String { + repository.openSubtitle(file) + } + /// Line picking for a working-copy file whose diffs allow it. private func picking(for file: ReviewFile) -> LinePicking? { guard file.isWorking, !file.pickable.isEmpty, repository.review?.compare == nil else { return nil } @@ -130,7 +136,7 @@ struct ReviewView: View { } header: { // The chips scroll to the header, so the file starts below it. if state.showsAllFiles { - FileSectionHeader(file: file) + FileSectionHeader(file: file, repository: repository, openSubtitle: openSubtitle(file)) .contextTarget(contextTarget(file), ring: ContextRing(radius: 0, inset: 1)) .id("file:" + file.path) } @@ -163,12 +169,15 @@ struct ReviewView: View { } /// `.rvhead`: ‹ History, what's reviewed and its line counts, ‹ n of m ›, Split / Unified, -/// One File / All Files, and Stage File for a working-copy file. +/// One File / All Files, Stage File for a working-copy file, and the file's Open button. private struct ReviewHeader: View { let repository: RepositoryModel let files: [ReviewFile] let state: ReviewState @Binding var layout: DiffLayout + /// A file's right-click menu (its path in One File). + let target: (ReviewFile) -> ContextTarget + let openSubtitle: (ReviewFile) -> String var body: some View { let current = currentIndex @@ -189,8 +198,12 @@ private struct ReviewHeader: View { .keyboardShortcut(.cancelAction) HStack(spacing: z(7)) { if !state.showsAllFiles, let file { - StatusTile(letter: file.letter) - Text(file.path).truncationMode(.middle) + // Right-click: the same menu as the file's row in the panel. + HStack(spacing: z(7)) { + StatusTile(letter: file.letter) + Text(file.path).truncationMode(.middle) + } + .contextTarget(target(file), ring: ContextRing(radius: z(6), inset: -z(3))) if file.isLFS { LFSBadge() } if case .submodule? = file.special { KindPill(text: "Submodule") } } else { @@ -236,6 +249,9 @@ private struct ReviewHeader: View { } .disabled(!repository.canChangeIndex) } + if !state.showsAllFiles, let file, !file.isSubmodule { + FileOpenButton(repository: repository, opening: file.opening, subtitle: openSubtitle(file), shortcut: "⌘↓") + } } .padding(.leading, z(8)) .padding(.trailing, z(12)) @@ -346,9 +362,11 @@ private struct FileIndex: View { } } -/// `.fh`: the sticky header of a file in All Files. +/// `.fh`: the sticky header of a file in All Files, with the file's Open button. private struct FileSectionHeader: View { let file: ReviewFile + let repository: RepositoryModel + let openSubtitle: String var body: some View { HStack(spacing: z(8)) { @@ -359,6 +377,9 @@ private struct FileSectionHeader: View { } Spacer(minLength: 0) LineCounts(additions: file.additions, deletions: file.deletions) + if !file.isSubmodule { + FileOpenButton(repository: repository, opening: file.opening, subtitle: openSubtitle) + } } .padding(.leading, z(16)) .padding(.trailing, z(14)) diff --git a/Kaern/Views/TabBar/TabBar.swift b/Kaern/Views/TabBar/TabBar.swift index 6264303..22bf44a 100644 --- a/Kaern/Views/TabBar/TabBar.swift +++ b/Kaern/Views/TabBar/TabBar.swift @@ -298,12 +298,7 @@ struct TabBar: View { Button("Remove from Group") { withAnimation { window.removeFromGroup(tab.id) } } .disabled(tab.group == nil) Divider() - Button("Show in Finder") { NSWorkspace.shared.activateFileViewerSelecting([URL(filePath: tab.path)]) } - Button("Open in Terminal") { Self.openInTerminal(tab.path) } - Button("Copy Path") { - NSPasteboard.general.clearContents() - NSPasteboard.general.setString(tab.path, forType: .string) - } + OpenInButtons(path: tab.path) Divider() Button("Move Tab to New Window") { app.moveToNewWindow(tab.id, from: window) } .disabled(window.tabs.count < 2) @@ -376,11 +371,29 @@ struct TabBar: View { } return tab.parentName } +} + +/// A repository's Open items in a right-click menu (a tab, the repository list): the editor, Finder, the terminal, +/// Claude Code as far as it's set up, Copy Path. +struct OpenInButtons: View { + let path: String - static func openInTerminal(_ path: String) { - let url = URL(filePath: path, directoryHint: .isDirectory) - guard let terminal = NSWorkspace.shared.urlForApplication(withBundleIdentifier: "com.apple.Terminal") else { return } - NSWorkspace.shared.open([url], withApplicationAt: terminal, configuration: NSWorkspace.OpenConfiguration()) + var body: some View { + if let editor = OpenIn.editor() { + Button("Open in \(editor.name)") { OpenIn.open(folder: path, in: editor) } + } + Button("Open in Finder") { OpenIn.open(folder: path, in: .finder) } + Button("Open in \(OpenIn.terminal().name)") { OpenIn.openInTerminal(path) } + if OpenIn.claudeApp != nil { + Button("Open in Claude Code") { OpenIn.claudeCode(folder: path, inTerminal: false) } + } + if OpenIn.claudeTerminal != nil { + Button("Open Claude Code in Terminal") { OpenIn.claudeCode(folder: path, inTerminal: true) } + } + Button("Copy Path") { + NSPasteboard.general.clearContents() + NSPasteboard.general.setString(path, forType: .string) + } } } diff --git a/Kaern/Views/Toolbar/MainToolbar.swift b/Kaern/Views/Toolbar/MainToolbar.swift index 8fecfa7..7bc9ebc 100644 --- a/Kaern/Views/Toolbar/MainToolbar.swift +++ b/Kaern/Views/Toolbar/MainToolbar.swift @@ -5,7 +5,7 @@ import SwiftUI /// The compact toolbar (WindowBase, icon-only mode): 44 pt, icon buttons grouped in pills, /// text only where it's information (the branch name, push/pull counts). /// -/// Sidebar · Branch · Undo Redo · Fetch Pull ▾ Push · New Branch Stash Pop — Review Focus · +/// Sidebar · Branch · Undo Redo · Fetch Pull ▾ Push · New Branch Stash Pop — Open ▾ · Review Focus · /// Search Details. struct MainToolbar: View { let window: WindowModel @@ -97,6 +97,13 @@ struct MainToolbar: View { } } Spacer(minLength: z(6)) + // With names under 1,000 pt, Open goes into » with New Branch, Stash and Pop. + if !foldsMake { + ToolbarCap { + OpenInButton(repository: repository) + } + ToolbarGroupSeparator() + } ToolbarCap { ToolbarButton(icon: Icons.review, name: "Review", shortcut: "⌥⌘R", isOn: repository.review != nil) { repository.toggleReview() @@ -220,7 +227,65 @@ private struct PullMenu: View { } } -/// » (ScreenNarrow, Icon and Text under 1,000 pt): New Branch, Stash and Pop in a menu. +/// Open (ScreenOpenIn): the repository in the default editor, which the button shows by its icon (Finder's when no +/// editor is installed); ▾ for the other editors, Claude Code, Finder and the terminal. +private struct OpenInButton: View { + let repository: RepositoryModel + /// Settings › General's editor: the button follows it. + @AppStorage(SettingsKey.openEditor, store: .kaern) private var editorID = "" + @Environment(\.toolbarShowsText) private var showsText + @State private var hovering = false + @State private var menuHovering = false + @State private var anchor = MenuAnchor() + + var body: some View { + let app = OpenIn.repositoryApp(chosen: editorID) + HStack(spacing: 0) { + Button { OpenIn.open(folder: repository.path, in: app) } label: { + VStack(spacing: z(4)) { + Image(nsImage: app.icon(18)) + .resizable() + .interpolation(.high) + .frame(width: z(18), height: z(18)) + if showsText { + Text("Open").font(.system(size: z(10))).foregroundStyle(K.label).lineLimit(1).fixedSize() + } + } + .padding(.horizontal, showsText ? z(6) : z(8)) + .frame(minWidth: showsText ? z(46) : z(34)) + .frame(maxHeight: .infinity) + .background(RoundedRectangle(cornerRadius: z(7), style: .continuous).fill(hovering ? K.hover : .clear)) + .contentShape(Rectangle()) + } + .buttonStyle(.plain) + .toolbarTooltip(name: "Open in \(app.name)", shortcut: app == .finder ? "⌥O" : "⌥E", hovering: $hovering) + .accessibilityLabel("Open \(repository.name) in \(app.name)") + .debugFrame("openButton \(repository.path)") + Button { showMenu() } label: { + Icon(Icons.chevronDown, size: 9) + .foregroundStyle(K.label2) + .frame(width: z(14)) + .frame(maxHeight: .infinity) + .background(RoundedRectangle(cornerRadius: z(6), style: .continuous).fill(menuHovering ? K.hover : .clear)) + .contentShape(Rectangle()) + } + .buttonStyle(.plain) + .toolbarTooltip(name: "Open In", shortcut: nil, placement: .trailing, hovering: $menuHovering) + .accessibilityLabel("Open \(repository.name) in another app") + .debugFrame("openMenu \(repository.path)") + } + .background(MenuAnchorView(anchor: anchor)) + } + + /// Under the button, its right edge at the button's: the button is near the window's right edge. + private func showMenu() { + guard let view = anchor.view else { return } + let menu = ContextMenus.openInMenu(repository) + menu.popUp(positioning: nil, at: NSPoint(x: view.bounds.width - menu.size.width, y: -4), in: view) + } +} + +/// » (ScreenNarrow, Icon and Text under 1,000 pt): New Branch, Stash and Pop in a menu, then Open's. private struct MoreMenu: View { let repository: RepositoryModel let busy: Bool @@ -236,6 +301,8 @@ private struct MoreMenu: View { .disabled(!ready || busy || repository.status.isClean) Button("Pop Stash") { repository.from("Toolbar » menu") { repository.popStash() } } .disabled(!ready || busy || repository.stashes.isEmpty) + Divider() + OpenInButtons(path: repository.path) } label: { VStack(spacing: z(4)) { Image(systemName: "chevron.right.2").font(.system(size: z(14), weight: .medium)) @@ -255,7 +322,7 @@ private struct MoreMenu: View { .frame(height: z(46)) .onHover { hovering = $0 } .toolbarTooltip(name: "More", shortcut: nil, placement: .trailing, hovering: $hovering) - .accessibilityLabel("More: New Branch, Stash, Pop") + .accessibilityLabel("More: New Branch, Stash, Pop, Open") } } From 324a04fb6567ef10d8ed7d281982e3a73f2e91b4 Mon Sep 17 00:00:00 2001 From: progresshans Date: Sun, 29 Nov 2026 17:48:02 +0900 Subject: [PATCH 02/13] test: t_openin checks the Open buttons, their menus, the keys and the setting MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The dump's driver section has what a test instance would have opened (opened), which editors, terminal and Claude Code handlers the Mac has (openIn), and where the views that report themselves are (frames, from debugFrame). menu, menuItems and menuRun know openIn and openFile , a menu placed by its right edge, an item named with its reason ("Claude Code — Terminal") or in a submenu ("Open With > Cursor"); right-click menus know commitFile ; key … through and press … through go the whole way a real key goes; openClear forgets what was opened. t_openin clicks the toolbar's Open button and Review's, reads both ▾ menus and runs their items, presses ⌥O ⌥T ⌥E (and ⌥O in the search field, which types ø there and opens nothing) and ⌘↓, opens a commit's version and reads the copy, and moves the button to another editor in Settings. It goes by what the Mac has installed, so it passes on any Mac. The checks' README says how a test instance opens nothing. t_openin, t_narrow760, t_zoom, t_modes, t_settings and t_small passed, with their light and dark pictures. Co-Authored-By: Claude Opus 5.5 --- Kaern/App/DebugDriver.swift | 117 +++++++++++++++++++------ checks/README.md | 4 + checks/suite.py | 2 + checks/t_openin.py | 166 ++++++++++++++++++++++++++++++++++++ 4 files changed, 265 insertions(+), 24 deletions(-) create mode 100644 checks/t_openin.py diff --git a/Kaern/App/DebugDriver.swift b/Kaern/App/DebugDriver.swift index 993c56c..4675736 100644 --- a/Kaern/App/DebugDriver.swift +++ b/Kaern/App/DebugDriver.swift @@ -237,6 +237,9 @@ final class DebugDriver { try? Data("ok".utf8).write(to: URL(filePath: args.first ?? "/tmp/kaern-ping"), options: .atomic) case "tooltip": DebugTooltip.shared.pinned = args.isEmpty ? nil : args.joined(separator: " ") + case "openClear": + // Forgets what was opened so far (the dump's `opened`). + OpenIn.debugLog.removeAll() case "snapshotPopover": // The + popover lives in a window of its own. if let popover = NSApp.windows.first(where: { $0.isVisible && String(describing: type(of: $0)).contains("Popover") }), @@ -248,7 +251,8 @@ final class DebugDriver { case "menus": dumpMenus(to: args.first ?? "/tmp/kaern-menus.txt") case "key": - // key [cmd] [shift] [option] [control] — goes through the main menu's key equivalents. + // key [cmd] [shift] [option] [control] [through ] — goes through the main menu's key + // equivalents; with `through`, the whole way a real key goes (the focused view types ). if let chars = args.first { key(chars == "tab" ? "\t" : chars, modifiers: Array(args.dropFirst())) } case "stripFrames": stripFrames(to: args.first ?? "/tmp/kaern-strip.json") @@ -279,9 +283,10 @@ final class DebugDriver { // zoom — View › Zoom In / Zoom Out: text, rows and spacing that much larger or smaller. if let factor = args.first.flatMap(Double.init) { UIScale.keep(factor) } case "press": - // press up|down|return|escape|space [shift] [option] [command] [hold [every ]] — a key - // down through the window, to the focused view. hold: the key stays down for n repeats (33 ms - // apart unless `every` says otherwise) before it comes up, as a held key does. + // press up|down|return|escape|space [shift] [option] [command] [through] [hold [every ]] — a key + // down through the window, to the focused view (`through`: by way of NSApp, the menus' key equivalents + // first). hold: the key stays down for n repeats (33 ms apart unless `every` says otherwise) before it + // comes up, as a held key does. press(args.first ?? "", modifiers: Array(args.dropFirst())) case "front": // Makes the window key, so snapshots show the active-window look (traffic lights, checkboxes). @@ -427,7 +432,7 @@ final class DebugDriver { return repository.commits.first { $0.id.hasPrefix(text) }?.id } /// What a right-click menu is for: commit | branch | remote | - /// tag | file [staged] | stash | worktree . + /// tag | file [staged] | stash | worktree | commitFile . func menuTarget(_ spec: [String]) -> ContextTarget? { guard let kind = spec.first else { return nil } let name = spec.dropFirst().joined(separator: " ") @@ -440,44 +445,75 @@ final class DebugDriver { let staged = spec.last == "staged" return .file(path: spec.dropFirst().dropLast(staged ? 1 : 0).joined(separator: " "), staged: staged) case "stash": return Int(name).flatMap { repository.stashes.indices.contains($0) ? .stash(repository.stashes[$0].id) : nil } + case "commitFile": + // commitFile : a file in a commit's details. + return commitID(spec.dropFirst().first).map { .commitFile(path: spec.dropFirst(2).joined(separator: " "), commit: $0) } case "worktree": return repository.worktrees.first { $0.name == name }.map { .worktree($0.path) } default: return nil } } + /// The menu for `spec`: a right-click menu (see `menuTarget`), `openIn` (the toolbar Open button's ▾) or + /// `openFile ` (a file's Open ▾ in Review). + func builtMenu(_ spec: [String]) -> NSMenu? { + switch spec.first { + case "openIn": return ContextMenus.openInMenu(repository) + case "openFile": + let path = spec.dropFirst().joined(separator: " ") + return ContextMenus.openFileMenu(repository.fileOpening(path), subtitle: repository.openSubtitle(repository.reviewFiles?.first { $0.path == path }), + repository) + default: return menuTarget(spec).flatMap { ContextMenus.menu(for: $0, repository: repository, window: window) } + } + } switch command { case "menuItems": - // menuItems — that target's right-click menu (see `menuTarget`) as JSON in - // : the header's title, then each item's title, the reason it doesn't apply and whether it's on. - guard args.count >= 3, let target = menuTarget(Array(args.dropFirst())), - let menu = ContextMenus.menu(for: target, repository: repository, window: window) else { return } - let items = menu.items.map { item -> [String: Any] in + // menuItems — that menu (see `builtMenu`) as JSON in : the header's title, then each + // item's title, the reason it doesn't apply, whether it's on (✓), its shortcut, whether it has an icon, and a + // submenu's titles. + guard args.count >= 2, let menu = builtMenu(Array(args.dropFirst())) else { return } + func describe(_ item: NSMenuItem) -> [String: Any] { if item.isSeparatorItem { return ["separator": true] } if item.view != nil { return ["header": item.title] } // An item with a reason has it in its title after a tab (`ContextMenus.titled`). let parts = item.title.components(separatedBy: "\t") - return ["title": parts[0], "hint": parts.dropFirst().first ?? "", "enabled": item.isEnabled] + var entry: [String: Any] = ["title": parts[0], "hint": parts.dropFirst().first ?? "", "enabled": item.isEnabled, + "on": item.state == .on, "icon": item.image != nil, + "key": item.keyEquivalent.isEmpty ? "" : Self.shortcut(of: item)] + if let submenu = item.submenu { entry["submenu"] = submenu.items.map(describe) } + return entry } - if let data = try? JSONSerialization.data(withJSONObject: items, options: [.prettyPrinted]) { + if let data = try? JSONSerialization.data(withJSONObject: menu.items.map(describe), options: [.prettyPrinted]) { try? data.write(to: URL(filePath: args[0])) } case "menuRun": - // menuRun | — chooses that item of the target's right-click menu. + // menuRun | — chooses that item of the menu (see `builtMenu`). An item with a + // reason can be named with it ("Claude Code — Terminal"), and one in a submenu after it ("Open With > Cursor"). let halves = rest.components(separatedBy: " | ") - guard halves.count == 2, let target = menuTarget(halves[0].split(separator: " ").map(String.init)), - let menu = ContextMenus.menu(for: target, repository: repository, window: window), - let index = menu.items.firstIndex(where: { $0.title.components(separatedBy: "\t").first == halves[1] }), + guard halves.count == 2, var menu = builtMenu(halves[0].split(separator: " ").map(String.init)) else { return } + var wanted = halves[1] + if let range = wanted.range(of: " > ") { + let parent = String(wanted[.. | branch | remote | tag | file [staged] | stash , - // then (window points, top-left): where the menu's top-left goes, or with `sub ` - // where that item goes. `snap ` saves the window with the menu (and the item's submenu) open. + // menu commit | branch | remote | tag | file [staged] | stash | + // openIn | openFile , then (window points, top-left): where the menu's top-left goes (with + // `right`, its top-right), or with `sub ` where that item goes. `snap ` saves the window + // with the menu (and the item's submenu) open. // Distributed notifications don't arrive while a menu tracks the mouse, so the menu takes // its own snapshot after a moment and closes again; a submenu is captured in a second // pass, opened next to its item. var parts = args var sub: String? var snap: String? + // `right`: x is where the menu's right edge goes (the Open menus open that way, under their button's end). + let rightAligned = parts.contains("right") + parts.removeAll { $0 == "right" } if let index = parts.firstIndex(of: "sub") { sub = parts[(index + 1)...].joined(separator: " ") parts = Array(parts[..= 4, let x = Double(parts[parts.count - 2]), let y = Double(parts[parts.count - 1]) else { return } + // At least a kind (`openIn` needs no name) and the place. + guard parts.count >= 3, let x = Double(parts[parts.count - 2]), let y = Double(parts[parts.count - 1]) else { return } let spec = Array(parts.dropLast(2)) let target = menuTarget(spec) // `toolbarBranch`: the toolbar branch button's menu (phase 4); `graphScope`: the bar's Graph: menu (phase 6). let built = spec[0] == "toolbarBranch" ? ContextMenus.toolbarBranchMenu(repository, onNewBranch: {}) : spec[0] == "graphScope" ? ContextMenus.graphScopeMenu(repository) - : target.flatMap { ContextMenus.menu(for: $0, repository: repository, window: window) } + : builtMenu(spec) guard let menu = built, let nsWindow = controller.window, let view = nsWindow.contentView else { return } - let point = NSPoint(x: x, y: view.isFlipped ? y : view.bounds.height - y) + let point = NSPoint(x: rightAligned ? x - menu.size.width : x, y: view.isFlipped ? y : view.bounds.height - y) let parent = sub.flatMap { title in menu.items.first { $0.title == title } } openMenu = menu let tracker = controller.contextTracker @@ -821,6 +858,8 @@ final class DebugDriver { try? lines.joined(separator: "\n").write(to: URL(filePath: path), atomically: true, encoding: .utf8) } + /// `through `: the key goes the whole way a real one does (NSApp.sendEvent: the menus' key equivalents, + /// then the focused view, which types ``), as ⌥O does (it types ø), instead of only to the menus. private func key(_ characters: String, modifiers: [String]) { guard let nsWindow = controller?.window else { return } var flags: NSEvent.ModifierFlags = [] @@ -828,15 +867,35 @@ final class DebugDriver { if modifiers.contains("shift") { flags.insert(.shift) } if modifiers.contains("option") { flags.insert(.option) } if modifiers.contains("control") { flags.insert(.control) } + let typed = modifiers.firstIndex(of: "through").flatMap { modifiers.indices.contains($0 + 1) ? modifiers[$0 + 1] : nil } guard let event = NSEvent.keyEvent( with: .keyDown, location: .zero, modifierFlags: flags, timestamp: ProcessInfo.processInfo.systemUptime, - windowNumber: nsWindow.windowNumber, context: nil, characters: characters, + windowNumber: nsWindow.windowNumber, context: nil, characters: typed ?? characters, charactersIgnoringModifiers: characters, isARepeat: false, keyCode: characters == "\t" ? 48 : 0 ) else { return } + if typed != nil { + NSApp.sendEvent(event) + return + } let handled = NSApp.mainMenu?.performKeyEquivalent(with: event) ?? false Self.log.info("key \(characters, privacy: .public) \(modifiers, privacy: .public) handled: \(handled)") } + /// "⌥E", "⌘↓": a menu item's shortcut the way its menu shows it. + static func shortcut(of item: NSMenuItem) -> String { + let flags = item.keyEquivalentModifierMask + var text = "" + if flags.contains(.control) { text += "⌃" } + if flags.contains(.option) { text += "⌥" } + if flags.contains(.shift) { text += "⇧" } + if flags.contains(.command) { text += "⌘" } + switch item.keyEquivalent { + case "\t": return text + "⇥" + case ContextMenus.openKey: return text + "↓" + default: return text + item.keyEquivalent.uppercased() + } + } + // MARK: Synthesized input (in-process, through NSWindow.sendEvent) private func press(_ name: String, modifiers names: [String] = []) { @@ -858,13 +917,15 @@ final class DebugDriver { } let repeats = max(number(after: "hold") ?? 0, 0) let interval = number(after: "every") ?? 33 + // `through`: by way of NSApp, so the menus' key equivalents get it first, as a real key's (⌘↓ opens the file). + let through = names.contains("through") func send(_ type: NSEvent.EventType, isRepeat: Bool = false) { guard let event = NSEvent.keyEvent( with: type, location: .zero, modifierFlags: flags, timestamp: ProcessInfo.processInfo.systemUptime, windowNumber: nsWindow.windowNumber, context: nil, characters: characters, charactersIgnoringModifiers: characters, isARepeat: isRepeat, keyCode: code ) else { return } - nsWindow.sendEvent(event) + if through { NSApp.sendEvent(event) } else { nsWindow.sendEvent(event) } } // A plain press stays in this turn; a held key's repeats come one after the other, as a keyboard sends them. guard repeats > 0 else { send(.keyDown); send(.keyUp); return } @@ -1161,6 +1222,14 @@ final class DebugDriver { "appearance": NSApp.effectiveAppearance.isDark ? "dark" : "light", // The tag on the Dock icon (DockTag): TEST on a test instance. "dockTag": DockTag.shown?.rawValue ?? "", + // What this instance would have opened elsewhere (OpenIn: a test instance opens nothing), and where. + "opened": OpenIn.debugLog, + "openIn": [ + "editor": OpenIn.editor()?.id ?? "", "editors": OpenIn.installedEditors.map(\.id), "terminal": OpenIn.terminal().id, + "repositoryApp": OpenIn.repositoryApp().id, "claudeApp": OpenIn.claudeApp != nil, "claudeTerminal": OpenIn.claudeTerminal != nil, + ] as [String: Any], + // Views that report where they are (`debugFrame`): [x, y, width, height] in window points from the top left. + "frames": DebugFrames.shared.frames.mapValues { [$0.minX, $0.minY, $0.width, $0.height] }, "pointerBusy": pointerTasks > 0, "drag": ["sequence": lastDragSequence, "handle": lastResizeHandle, "value": lastResizeValue, "storedAfterChange": sizesAfterDragChange, "storedAfterMouseUp": sizesAfterMouseUp] as [String: Any], diff --git a/checks/README.md b/checks/README.md index 5f69b27..cb6ff62 100644 --- a/checks/README.md +++ b/checks/README.md @@ -49,6 +49,10 @@ A test instance's Dock icon has a purple TEST tag, and a Debug build you run you (`Kaern/App/DockTag.swift`), so neither is taken for the Kaern you use. `t_isolation` checks it and keeps a picture of each tag in `shots/`. +A test instance opens nothing in another app (an editor, Finder, a terminal, Claude Code): it notes what it would +have opened in the dump's `driver.opened` (`OpenIn`), and `driver.openIn` says which of those apps this Mac has. +`t_openin` goes by both, so it passes whatever is installed. + ## Where things are `python3 checks/paths.py` prints the work folder and the app. The work folder is in the temporary folder, one per diff --git a/checks/suite.py b/checks/suite.py index 5aa18c7..25163e8 100644 --- a/checks/suite.py +++ b/checks/suite.py @@ -93,6 +93,7 @@ def __init__(self, name, areas, dark=False, alone=False, samples=('base',), seco Check('t_deepselect', 'history', samples=('base', 'big-60000'), seconds=20), Check('t_firstload', 'launch history changes', seconds=8), Check('t_remotemore', 'sidebar', samples=('base', 'remotes-3000'), seconds=12), + Check('t_openin', 'openin menus layout review changes settings', dark=True, seconds=14), ] BY_NAME = {c.name: c for c in CHECKS} @@ -135,6 +136,7 @@ def __init__(self, name, areas, dark=False, alone=False, samples=('base',), seco (r'RepositoryModel\+Worktrees', 'worktrees'), (r'RepositoryModel\+Undo|GitRepository\+Undo', 'undo'), (r'Views/Menus/|App/MainMenu', 'menus'), + (r'App/OpenIn|Menus/OpenMenus|Review/FileOpenButton|Common/DebugFrame', 'openin'), (r'Views/StatusBar/', 'statusbar'), (r'Views/CommandLog/|App/CommandLog|Git/GitCommandLog', 'commandlog'), ] diff --git a/checks/t_openin.py b/checks/t_openin.py new file mode 100644 index 0000000..56719fb --- /dev/null +++ b/checks/t_openin.py @@ -0,0 +1,166 @@ +"""t_openin.py [light|dark] — Open (ScreenOpenIn). The toolbar's Open button opens the repository in the default editor +(Finder when none is installed), and its ▾ lists the editors, Claude Code, Finder and the terminal; ⌥E ⌥O ⌥T do the +same, but not while text is typed. Review's Open button opens a file at its first change (so does ⌘↓), and for a +commit's file its ▾ has Open Version at…, a read-only copy of that version. Settings › General picks the editor. + +A test instance opens nothing: it notes what it would have opened (the dump's `opened`). What is installed differs from +Mac to Mac (the dump's `openIn`), so the check goes by that.""" +import json, os, stat, sys, urllib.parse +sys.path.insert(0, os.path.dirname(__file__)) +from k5 import * +mode = sys.argv[1] if len(sys.argv) > 1 else 'light' +# Editors that open a file at a line: VS Code and its forks by their file links, Xcode with xed (OpenIn). +AT_LINE = {'com.microsoft.VSCode', 'com.microsoft.VSCodeInsiders', 'com.todesktop.230313mzl4w4u92', 'com.exafunction.windsurf', + 'com.apple.dt.Xcode'} +ITEMS = os.path.join(RUN_DIR, 'openin-items.json') + + +def opened(d): return d['driver']['opened'] + + +def frame(name): + """Where the view that reports itself as `name …` is (the driver's frames).""" + for key, value in full_dump()['driver']['frames'].items(): + if key.startswith(name + ' '): return value + raise SystemExit('no %s on screen' % name) + + +def center(f): return str(f[0] + f[2] / 2), str(f[1] + f[3] / 2) + + +def menu_items(*spec): + if os.path.exists(ITEMS): os.remove(ITEMS) + k('menuItems', ITEMS, *spec); sync() + with open(ITEMS) as f: return json.load(f) + + +def opens(label, *command): + """Runs the command and returns what it opened (one thing).""" + k('openClear') + k(*command) + d = until(lambda d: len(opened(d)) > 0, label=label) + return opened(d) + + +launch_prepared(mode) +show_tab('powerlens') +repo = os.path.realpath(PL) +info = full_dump()['driver']['openIn']; print('installed:', info) +editors, terminal = info['editors'], info['terminal'] +assert info['repositoryApp'] == (info['editor'] or 'com.apple.finder'), 'the button opens in the editor, else Finder: %s' % info +snap('openin-toolbar', mode) + +# The toolbar's button: the repository in the default editor (Finder without one). +done = opens('the Open button', 'click', *center(frame('openButton'))) +print('Open button:', done) +assert done == [('finder ' if not editors else info['editor'] + ' ') + repo], done + +# Its ▾: a header, the editors (✓ the button's, ⌥E), Claude Code as far as it's set up, Finder ⌥O, the terminal ⌥T. +items = menu_items('openIn') +print('▾:', [(i.get('title') or i.get('header') or '—', i.get('hint', ''), i.get('key', ''), i.get('on', False)) for i in items]) +assert items[0].get('header') == 'powerlens', items[0] +choices = [i for i in items if 'title' in i] +on = [i for i in choices if i['on']] +assert len(on) == (1 if editors else 0) and all(i['key'] == '⌥E' and i['icon'] for i in on), on +assert sum(1 for i in choices if i['icon'] and i['title'] not in ('Finder', 'Claude Code') and i['key'] != '⌥T') == len(editors), choices +finder = next(i for i in choices if i['title'] == 'Finder'); assert finder['key'] == '⌥O' and finder['icon'], finder +shell = next(i for i in choices if i['key'] == '⌥T'); assert shell['icon'], shell +claude = sorted(i['hint'] for i in choices if i['title'] == 'Claude Code') +assert claude == sorted((['Claude app'] if info['claudeApp'] else []) + (['Terminal'] if info['claudeTerminal'] else [])), claude +assert any(i['title'] == 'Copy Path' for i in choices) +assert any(i['title'] == 'Default Editor' and len(i.get('submenu', [])) == len(editors) for i in choices) == (len(editors) > 1) +menu_snap('openin-menu', 'menu', 'openIn', str(sum(frame('openMenu')[0:3:2])), str(sum(frame('openMenu')[1:4:2]) + 4), 'right') + +assert opens('▾ › Finder', 'menuRun', 'openIn | Finder') == ['finder ' + repo] +assert opens('▾ › the terminal', 'menuRun', 'openIn | ' + shell['title']) == [terminal + ' ' + repo] +quoted = urllib.parse.quote(repo, safe='/') +if info['claudeApp']: + link = opens('▾ › Claude Code in the Claude app', 'menuRun', 'openIn | Claude Code — Claude app'); print('Claude app:', link) + assert link == ['link claude://code/new?folder=' + quoted], link +if info['claudeTerminal']: + link = opens('▾ › Claude Code in a terminal', 'menuRun', 'openIn | Claude Code — Terminal'); print('Claude in a terminal:', link) + assert link == ['link claude-cli://open?cwd=' + quoted], link + +# ⌥O ⌥T ⌥E as in GitKraken, through the menus the way a real key goes. +k('openClear') +k('key', 'o', 'option', 'through', 'ø'); k('key', 't', 'option', 'through', '†'); k('key', 'e', 'option', 'through', '´') +d = until(lambda d: len(opened(d)) == (3 if editors else 2), label='⌥O ⌥T ⌥E') +print('⌥O ⌥T ⌥E:', opened(d)) +assert opened(d) == ['finder ' + repo, terminal + ' ' + repo] + ([info['editor'] + ' ' + repo] if editors else []), opened(d) +# While a field has the keyboard, ⌥O types ø there and opens nothing. +k('key', 'f', 'cmd') +until(lambda d: d['driver']['typing'], label='the search field has the keyboard') +k('openClear') +k('key', 'o', 'option', 'through', 'ø') +d = until(lambda d: 'ø' in d['driver']['fieldText'], label='⌥O typed ø in the search field') +assert opened(d) == [], 'a key typed in a field opened %s' % opened(d) +k('search', 'off') +until(lambda d: not d['driver']['typing'], label='the search field closed') + +# Review's Open button: the file in the editor at its first change (line 16 of the sample's ci.yml); ⌘↓ too. +CI = '.github/workflows/ci.yml' +k('select', 'wip'); k('review', 'one', CI) +settle(lambda d: (d['active']['review'] or {}).get('path') == CI, label='Review shows ' + CI) +snap('openin-review', mode) +done = opens('Review’s Open button', 'click', *center(frame('openFile'))) +print('file button:', done) +app, place = done[0].split(' ', 1) +assert place == os.path.join(repo, CI) + (':16' if app in AT_LINE else ''), done +assert app == (info['editor'] or app), 'a text file opens in the editor: %s' % done +assert opens('⌘↓', 'press', 'down', 'command', 'through') == done +items = menu_items('openFile', CI) +print('file ▾:', [(i.get('title') or i.get('header') or '—', i.get('hint', ''), i.get('key', ''), i.get('on', False)) for i in items]) +assert items[0].get('header') == 'ci.yml' +first = next(i for i in items if 'title' in i); assert first['on'] and first['key'] == '⌘↓' and first['enabled'], first +assert not any(i.get('title', '').startswith('Open Version at') for i in items), 'a working-copy file has no commit version' +button = frame('openFileMenu') +menu_snap('openin-filemenu', 'menu', 'openFile', CI, str(button[0] + button[2]), str(button[1] + button[3] + 4), 'right') +assert opens('▾ › Show in Finder', 'menuRun', 'openFile ' + CI + ' | Show in Finder') == ['reveal ' + os.path.join(repo, CI)] +# Its row's right-click menu: Open in (⌘↓) and Open With ▸ the others. +row = menu_items('file', CI) +open_in = next(i for i in row if i.get('title', '').startswith('Open in ')); assert open_in['key'] == '⌘↓', open_in +assert any(i.get('title') == 'Open With' and i.get('submenu') for i in row) == (len(editors) > 1 or info['claudeApp'] or info['claudeTerminal']) + +# All Files: each file's header has the button. +k('review', 'all') +settle(lambda d: (d['active']['review'] or {}).get('all'), label='All Files') +frame('openFile') +snap('openin-allfiles', mode) + +# A commit's file: Open Version at… opens a read-only copy of that version, named after the commit. +k('review', 'off'); k('select', '1'); k('review', 'all') +d = settle(lambda d: d['active']['selection'].startswith('commit 1 ') and d['active']['reviewFiles'], label='commit 1 in Review') +path = d['active']['reviewFiles'][0]['path'] +commit = d['active']['selection'].split()[2] # "commit 1 e7b7dd2" +k('review', 'one', path) +settle(lambda d: (d['active']['review'] or {}).get('path') == path, label='commit 1 › ' + path) +items = menu_items('openFile', path) +version = next(i for i in items if i.get('title', '').startswith('Open Version at ')); print('version item:', version) +short = version['title'].rsplit(' ', 1)[1] +assert version['hint'] == 'Read-only copy' and commit.startswith(short), (version, commit) +done = opens('Open Version at ' + short, 'menuRun', 'openFile ' + path + ' | ' + version['title']) +print('version:', done) +copy = done[0].split(' ', 1)[1] +if copy.rsplit(':', 1)[-1].isdigit(): copy = copy.rsplit(':', 1)[0] +name, ext = os.path.splitext(os.path.basename(path)) +assert os.path.basename(copy) == '%s (%s)%s' % (name, short, ext), copy +assert os.stat(copy).st_mode & (stat.S_IWUSR | stat.S_IWGRP | stat.S_IWOTH) == 0, 'the copy can be written to' +with open(copy) as f: assert f.read().strip() == git('show', '%s:%s' % (commit, path)), 'the copy is not that version' +right = menu_items('commitFile', '1', path) +assert any(i.get('title', '') == version['title'] for i in right), 'the commit file’s right-click menu has Open Version at…' + +# Settings › General › Open in: another editor moves the button to it. +k('settings', 'General') +until(lambda d: window_open(d, ' General'), label='the Settings window on General') +snap('openin-settings', window='General') +k('settings', 'close') +until(lambda d: not window_open(d, ' General'), label='the Settings window closed') +if len(editors) > 1: + other = editors[1] + set_setting('KaernOpenEditor', other) + d = until(lambda d: d['driver']['openIn']['repositoryApp'] == other, label='the button follows the setting') + k('review', 'off') + assert opens('the Open button, another editor', 'click', *center(frame('openButton'))) == [other + ' ' + repo] + assert next(i for i in menu_items('openIn') if i.get('on'))['key'] == '⌥E' +quit_app() +print('OPEN IN OK') From c3c4adb7ed99f849b650c4a8f5ceebecd831009e Mon Sep 17 00:00:00 2001 From: progresshans Date: Sun, 29 Nov 2026 22:36:59 +0900 Subject: [PATCH 03/13] fix: the Open menus' text lines up in one column MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit macOS 27 starts the title of a menu row without an image where the icons are, and Kaern's menu header starts at the ✓ column, so the Open menus had three left edges: the header at 16 pt, Copy Path and Default Editor at 30 pt, the apps' names at 52 pt. Rows without an app now have a blank 16 pt icon, so their titles start with the apps' names; the header's text starts there too, and its hairline runs where the separators do (measured in the menu pictures: 52 pt, and 29.5 to 15.5 pt from the edges). The repository menu's ✓ is on Finder when no editor is installed (the button then opens Finder), so the menu always has its ✓ column and the header stays in line. t_openin now checks that every row has an icon and that one row has the ✓; it passed. Co-Authored-By: Claude Opus 5.5 --- Kaern/Views/Menus/ContextMenus.swift | 17 ++++++++---- Kaern/Views/Menus/OpenMenus.swift | 40 ++++++++++++++++++++-------- checks/t_openin.py | 10 ++++--- 3 files changed, 48 insertions(+), 19 deletions(-) diff --git a/Kaern/Views/Menus/ContextMenus.swift b/Kaern/Views/Menus/ContextMenus.swift index ef80adb..7cfa5ef 100644 --- a/Kaern/Views/Menus/ContextMenus.swift +++ b/Kaern/Views/Menus/ContextMenus.swift @@ -661,11 +661,15 @@ enum ContextMenus { return menuItem } - /// `.cmh`: what the menu is about — the commit's summary, branch or file — and a second line. - static func header(_ title: String, _ subtitle: String) -> NSMenuItem { + /// `.cmh`: what the menu is about — the commit's summary, branch or file — and a second line. `textInset` and `rule`: + /// where its text starts and its hairline runs, for a menu whose titles don't start at the usual place (one with + /// icons, `openHeader`). + static func header(_ title: String, _ subtitle: String, textInset: CGFloat = 16, + rule: (leading: CGFloat, trailing: CGFloat) = (10, 10)) -> NSMenuItem { let item = NSMenuItem(title: title, action: nil, keyEquivalent: "") item.isEnabled = false - let view = NSHostingView(rootView: MenuHeader(title: title, subtitle: subtitle)) + let view = NSHostingView(rootView: MenuHeader(title: title, subtitle: subtitle, textInset: textInset, + ruleLeading: rule.leading, ruleTrailing: rule.trailing)) let size = view.fittingSize // A fixed width: a wider menu leaves the header at the left, a long summary is cut. view.frame = NSRect(x: 0, y: 0, width: min(max(size.width, 220), 320), height: size.height) @@ -679,6 +683,9 @@ enum ContextMenus { private struct MenuHeader: View { let title: String let subtitle: String + var textInset: CGFloat = 16 + var ruleLeading: CGFloat = 10 + var ruleTrailing: CGFloat = 10 var body: some View { VStack(alignment: .leading, spacing: 1) { @@ -692,9 +699,9 @@ private struct MenuHeader: View { .lineLimit(1) .truncationMode(.tail) .frame(maxWidth: .infinity, alignment: .leading) - .padding(EdgeInsets(top: 4, leading: 16, bottom: 7, trailing: 14)) + .padding(EdgeInsets(top: 4, leading: textInset, bottom: 7, trailing: 14)) .overlay(alignment: .bottom) { - Rectangle().fill(.separator).frame(height: 1).padding(.horizontal, 10) + Rectangle().fill(.separator).frame(height: 1).padding(.leading, ruleLeading).padding(.trailing, ruleTrailing) } .padding(.bottom, 4) .fixedSize(horizontal: false, vertical: true) diff --git a/Kaern/Views/Menus/OpenMenus.swift b/Kaern/Views/Menus/OpenMenus.swift index 6f62284..9980742 100644 --- a/Kaern/Views/Menus/OpenMenus.swift +++ b/Kaern/Views/Menus/OpenMenus.swift @@ -8,18 +8,35 @@ extension ContextMenus { static let openKey = String(Character(UnicodeScalar(UInt16(NSDownArrowFunctionKey))!)) /// An app's icon beside an item. From macOS 27, menus hide an item's image unless it asks to show it. - static func showIcon(_ item: NSMenuItem, _ icon: NSImage) { + @discardableResult + static func showIcon(_ item: NSMenuItem, _ icon: NSImage) -> NSMenuItem { item.image = icon if #available(macOS 27, *) { item.preferredImageVisibility = .visible } + return item } - /// The toolbar Open button's ▾: the editors (✓ the button's, ⌥E), Claude Code, Finder (⌥O), the terminal (⌥T), - /// Copy Path, and which editor the button uses. + /// A row without an app (Copy Path, Show in Finder…): a blank icon keeps its title in line with the apps' names. + /// Without one, macOS 27 starts the title where the icons are. + @discardableResult + static func plainRow(_ item: NSMenuItem) -> NSMenuItem { + showIcon(item, blankIcon) + } + + private static let blankIcon = NSImage(size: NSSize(width: 16, height: 16), flipped: false) { _ in true } + + /// An Open menu's header, in line with the rest: its text where the apps' names start (after the ✓ column and a + /// 16 pt icon), its hairline where the separators run. Measured in macOS 27's menus; the menus always have a ✓. + static func openHeader(_ title: String, _ subtitle: String) -> NSMenuItem { + header(title, subtitle, textInset: 52, rule: (29.5, 15.5)) + } + + /// The toolbar Open button's ▾: the editors (✓ the button's, ⌥E), Claude Code, Finder (⌥O; ✓ when there's no + /// editor, as the button then opens Finder), the terminal (⌥T), Copy Path, and which editor the button uses. static func openInMenu(_ r: RepositoryModel) -> NSMenu { let path = r.path let menu = NSMenu(title: "Open In") menu.autoenablesItems = false - menu.addItem(header(r.name, Formatters.abbreviatedPath(path))) + menu.addItem(openHeader(r.name, Formatters.abbreviatedPath(path))) let editors = OpenIn.installedEditors let current = OpenIn.editor() for editor in editors { @@ -35,20 +52,21 @@ extension ContextMenus { if !claude.isEmpty { menu.addItem(.separator()) } let finder = item("Finder", key: "o", modifiers: [.option]) { OpenIn.open(folder: path, in: .finder) } showIcon(finder, ExternalApp.finder.icon(16)) + finder.state = current == nil ? .on : .off menu.addItem(finder) let terminal = OpenIn.terminal() let terminalItem = item(terminal.name, key: "t", modifiers: [.option]) { OpenIn.openInTerminal(path) } showIcon(terminalItem, terminal.icon(16)) menu.addItem(terminalItem) menu.addItem(.separator()) - menu.addItem(item("Copy Path") { r.copy(path, toast: "Copied \(Formatters.abbreviatedPath(path))") }) + menu.addItem(plainRow(item("Copy Path") { r.copy(path, toast: "Copied \(Formatters.abbreviatedPath(path))") })) if editors.count > 1 { - menu.addItem(submenu("Default Editor", enabled: true, items: editors.map { editor in + menu.addItem(plainRow(submenu("Default Editor", enabled: true, items: editors.map { editor in let menuItem = item(editor.name) { UserDefaults.kaern.set(editor.id, forKey: SettingsKey.openEditor) } showIcon(menuItem, editor.icon(16)) menuItem.state = editor == current ? .on : .off return menuItem - })) + }))) } return fitHeader(menu) } @@ -59,7 +77,7 @@ extension ContextMenus { let menu = NSMenu(title: opening.path) menu.autoenablesItems = false let directory = (opening.path as NSString).deletingLastPathComponent - menu.addItem(header(opening.name, (directory.isEmpty ? "" : directory + "/ · ") + subtitle)) + menu.addItem(openHeader(opening.name, (directory.isEmpty ? "" : directory + "/ · ") + subtitle)) let choices = openChoices(opening, r) for app in choices.apps { let isFirst = app == choices.first @@ -74,12 +92,12 @@ extension ContextMenus { claude.forEach(menu.addItem) if !claude.isEmpty { menu.addItem(.separator()) } if let version = opening.version { - menu.addItem(item("Open Version at \(version.commit.prefix(7))", hint: "Read-only copy") { r.openVersion(opening) }) + menu.addItem(plainRow(item("Open Version at \(version.commit.prefix(7))", hint: "Read-only copy") { r.openVersion(opening) })) menu.addItem(.separator()) } let file = r.existingFile(opening.path) - menu.addItem(item("Show in Finder", enabled: file != nil) { if let file { OpenIn.reveal(file) } }) - menu.addItem(item("Copy Path") { r.copy(opening.path, toast: "Copied \(opening.path)") }) + menu.addItem(plainRow(item("Show in Finder", enabled: file != nil) { if let file { OpenIn.reveal(file) } })) + menu.addItem(plainRow(item("Copy Path") { r.copy(opening.path, toast: "Copied \(opening.path)") })) return fitHeader(menu) } diff --git a/checks/t_openin.py b/checks/t_openin.py index 56719fb..221d942 100644 --- a/checks/t_openin.py +++ b/checks/t_openin.py @@ -56,14 +56,17 @@ def opens(label, *command): assert done == [('finder ' if not editors else info['editor'] + ' ') + repo], done # Its ▾: a header, the editors (✓ the button's, ⌥E), Claude Code as far as it's set up, Finder ⌥O, the terminal ⌥T. +# Every row has an icon (a blank one without an app), so the titles line up. items = menu_items('openIn') print('▾:', [(i.get('title') or i.get('header') or '—', i.get('hint', ''), i.get('key', ''), i.get('on', False)) for i in items]) assert items[0].get('header') == 'powerlens', items[0] choices = [i for i in items if 'title' in i] +assert all(i['icon'] for i in choices), [i['title'] for i in choices if not i['icon']] on = [i for i in choices if i['on']] -assert len(on) == (1 if editors else 0) and all(i['key'] == '⌥E' and i['icon'] for i in on), on -assert sum(1 for i in choices if i['icon'] and i['title'] not in ('Finder', 'Claude Code') and i['key'] != '⌥T') == len(editors), choices -finder = next(i for i in choices if i['title'] == 'Finder'); assert finder['key'] == '⌥O' and finder['icon'], finder +assert len(on) == 1 and on[0]['key'] == ('⌥E' if editors else '⌥O'), 'one ✓, on what the button opens: %s' % on +rows = [i for i in choices if i['title'] not in ('Finder', 'Claude Code', 'Copy Path', 'Default Editor') and i['key'] != '⌥T'] +assert len(rows) == len(editors), rows +finder = next(i for i in choices if i['title'] == 'Finder'); assert finder['key'] == '⌥O' and finder['on'] == (not editors), finder shell = next(i for i in choices if i['key'] == '⌥T'); assert shell['icon'], shell claude = sorted(i['hint'] for i in choices if i['title'] == 'Claude Code') assert claude == sorted((['Claude app'] if info['claudeApp'] else []) + (['Terminal'] if info['claudeTerminal'] else [])), claude @@ -111,6 +114,7 @@ def opens(label, *command): items = menu_items('openFile', CI) print('file ▾:', [(i.get('title') or i.get('header') or '—', i.get('hint', ''), i.get('key', ''), i.get('on', False)) for i in items]) assert items[0].get('header') == 'ci.yml' +assert all(i['icon'] for i in items if 'title' in i), 'every row has an icon, so the titles line up' first = next(i for i in items if 'title' in i); assert first['on'] and first['key'] == '⌘↓' and first['enabled'], first assert not any(i.get('title', '').startswith('Open Version at') for i in items), 'a working-copy file has no commit version' button = frame('openFileMenu') From c8045c53824190debabab6efead7cf2338283340 Mon Sep 17 00:00:00 2001 From: progresshans Date: Mon, 30 Nov 2026 01:25:09 +0900 Subject: [PATCH 04/13] =?UTF-8?q?fix:=20the=20Open=20menus=20have=20no=20?= =?UTF-8?q?=E2=9C=93=20column=20and=20start=20every=20row=20at=20one=20edg?= =?UTF-8?q?e?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit c3c4adb lined the Open menus' text up after the ✓ column and a 16 pt icon, 52 pt in, so the header, Copy Path and Default Editor sat indented under the apps' names. The Open menus now hide their ✓ column (showsStateColumn), and nothing is indented: the header's text, the apps' icons and the rows without an app start 16 pt in, and the header's hairline runs where the separators do, 16 pt in from each side (measured in the menu pictures). The one ✓ left is the default editor's, in Default Editor ▸; ⌥E marks the button's editor, and ⌘↓ the app a file's button opens. A row without an icon that has a reason at its right (Open Version at… · Read-only copy) has its tab 22 pt further, an icon and its gap, so the reason ends where the apps' reasons end. The debug frames lost a view's frame when another view with the same name disappeared after it appeared (a file's Open button in Review's header and the same file's in All Files): a name is now forgotten only by the view that reported it last. The driver's menuItems tells whether a menu has a ✓ column. t_openin checks that the Open menus have no ✓ column and no ✓ outside Default Editor, that Default Editor's ✓ is on the ⌥E editor and follows the setting, and takes a picture of a commit file's menu; it passed in light and dark. Co-Authored-By: Claude Opus 5.5 --- Kaern/App/DebugDriver.swift | 8 ++-- Kaern/Views/Common/DebugFrame.swift | 18 +++++++-- Kaern/Views/Menus/ContextMenus.swift | 7 ++-- Kaern/Views/Menus/OpenMenus.swift | 58 ++++++++++++++-------------- checks/t_openin.py | 52 ++++++++++++++++--------- 5 files changed, 85 insertions(+), 58 deletions(-) diff --git a/Kaern/App/DebugDriver.swift b/Kaern/App/DebugDriver.swift index 4675736..12dc141 100644 --- a/Kaern/App/DebugDriver.swift +++ b/Kaern/App/DebugDriver.swift @@ -466,13 +466,13 @@ final class DebugDriver { } switch command { case "menuItems": - // menuItems — that menu (see `builtMenu`) as JSON in : the header's title, then each - // item's title, the reason it doesn't apply, whether it's on (✓), its shortcut, whether it has an icon, and a - // submenu's titles. + // menuItems — that menu (see `builtMenu`) as JSON in : the header's title and + // whether its menu has a ✓ column, then each item's title, the reason it doesn't apply, whether it's on (✓), + // its shortcut, whether it has an icon, and a submenu's titles. guard args.count >= 2, let menu = builtMenu(Array(args.dropFirst())) else { return } func describe(_ item: NSMenuItem) -> [String: Any] { if item.isSeparatorItem { return ["separator": true] } - if item.view != nil { return ["header": item.title] } + if item.view != nil { return ["header": item.title, "stateColumn": item.menu?.showsStateColumn ?? true] } // An item with a reason has it in its title after a tab (`ContextMenus.titled`). let parts = item.title.components(separatedBy: "\t") var entry: [String: Any] = ["title": parts[0], "hint": parts.dropFirst().first ?? "", "enabled": item.isEnabled, diff --git a/Kaern/Views/Common/DebugFrame.swift b/Kaern/Views/Common/DebugFrame.swift index 5ba72e5..c89e1fd 100644 --- a/Kaern/Views/Common/DebugFrame.swift +++ b/Kaern/Views/Common/DebugFrame.swift @@ -17,7 +17,17 @@ extension View { @MainActor final class DebugFrames { static let shared = DebugFrames() - var frames: [String: CGRect] = [:] + /// Each name's frame and the view that reported it. Two views can have one name for a moment: a file's Open button + /// in Review's header appears before the same file's in All Files disappears. + private var entries: [String: (owner: ObjectIdentifier, frame: CGRect)] = [:] + var frames: [String: CGRect] { entries.mapValues(\.frame) } + + func set(_ name: String, _ frame: CGRect, by owner: AnyObject) { entries[name] = (ObjectIdentifier(owner), frame) } + + /// Forgets the name, unless another view has reported it since. + func remove(_ name: String, by owner: AnyObject) { + if entries[name]?.owner == ObjectIdentifier(owner) { entries[name] = nil } + } } private struct DebugFrameModifier: ViewModifier { @@ -29,11 +39,11 @@ private struct DebugFrameModifier: ViewModifier { // `.global` is the window's content view, which fills the window (top-left origin). .onGeometryChange(for: CGRect.self) { $0.frame(in: .global) } action: { frame in place.frame = frame - DebugFrames.shared.frames[name] = frame + DebugFrames.shared.set(name, frame, by: place) } // Back where it was (its tab shows again): nothing moved, so nothing above ran. - .onAppear { if let frame = place.frame { DebugFrames.shared.frames[name] = frame } } - .onDisappear { DebugFrames.shared.frames[name] = nil } + .onAppear { if let frame = place.frame { DebugFrames.shared.set(name, frame, by: place) } } + .onDisappear { DebugFrames.shared.remove(name, by: place) } } } #endif diff --git a/Kaern/Views/Menus/ContextMenus.swift b/Kaern/Views/Menus/ContextMenus.swift index 7cfa5ef..893282c 100644 --- a/Kaern/Views/Menus/ContextMenus.swift +++ b/Kaern/Views/Menus/ContextMenus.swift @@ -626,15 +626,16 @@ enum ContextMenus { } /// The reason an item doesn't apply, in small secondary text at the right of its title - /// (`.mh`), like the board. - static func titled(_ title: String, hint: String) -> NSAttributedString { + /// (`.mh`), like the board. `lead`: how far left of the other titles this one starts (a row without an icon among + /// rows with one), so its reason still ends where theirs do. + static func titled(_ title: String, hint: String, lead: CGFloat = 0) -> NSAttributedString { let font = NSFont.menuFont(ofSize: 0) let result = NSMutableAttributedString(string: title, attributes: [.font: font]) let width = (title as NSString).size(withAttributes: [.font: font]).width let hintFont = NSFont.systemFont(ofSize: z(11)) let hintWidth = (hint as NSString).size(withAttributes: [.font: hintFont]).width let style = NSMutableParagraphStyle() - style.tabStops = [NSTextTab(textAlignment: .right, location: max(280, width + 28 + hintWidth))] + style.tabStops = [NSTextTab(textAlignment: .right, location: max(280 + lead, width + 28 + hintWidth))] result.append(NSAttributedString(string: "\t" + hint, attributes: [ .font: hintFont, .foregroundColor: NSColor.tertiaryLabelColor, .baselineOffset: 1, ])) diff --git a/Kaern/Views/Menus/OpenMenus.swift b/Kaern/Views/Menus/OpenMenus.swift index 9980742..7a10afc 100644 --- a/Kaern/Views/Menus/OpenMenus.swift +++ b/Kaern/Views/Menus/OpenMenus.swift @@ -15,35 +15,40 @@ extension ContextMenus { return item } - /// A row without an app (Copy Path, Show in Finder…): a blank icon keeps its title in line with the apps' names. - /// Without one, macOS 27 starts the title where the icons are. - @discardableResult - static func plainRow(_ item: NSMenuItem) -> NSMenuItem { - showIcon(item, blankIcon) + /// An Open ▾ menu. It has no ✓ column (its one ✓ is in Default Editor ▸), so nothing is indented: the header's text, + /// the apps' icons and the rows without an app (Copy Path, Show in Finder…) all start 16 pt in from its left side. + private static func openMenu(_ title: String) -> NSMenu { + let menu = NSMenu(title: title) + menu.autoenablesItems = false + menu.showsStateColumn = false + return menu } - private static let blankIcon = NSImage(size: NSSize(width: 16, height: 16), flipped: false) { _ in true } - - /// An Open menu's header, in line with the rest: its text where the apps' names start (after the ✓ column and a - /// 16 pt icon), its hairline where the separators run. Measured in macOS 27's menus; the menus always have a ✓. + /// An Open menu's header, in line with the rest: its text where the icons start, its hairline where the separators + /// run (16 pt in from each side). Measured in macOS 27's menus without a ✓ column. static func openHeader(_ title: String, _ subtitle: String) -> NSMenuItem { - header(title, subtitle, textInset: 52, rule: (29.5, 15.5)) + header(title, subtitle, textInset: 16, rule: (16, 16)) } - /// The toolbar Open button's ▾: the editors (✓ the button's, ⌥E), Claude Code, Finder (⌥O; ✓ when there's no - /// editor, as the button then opens Finder), the terminal (⌥T), Copy Path, and which editor the button uses. + /// A row without an app, with a reason at its right: its title starts where the icons do, an icon and its gap (22 pt) + /// before the apps' names, so its reason's tab is that much further, to end where the apps' reasons end. + private static func plainItem(_ title: String, hint: String, run: @escaping () -> Void) -> NSMenuItem { + let menuItem = item(title, run: run) + menuItem.attributedTitle = titled(title, hint: hint, lead: 22) + return menuItem + } + + /// The toolbar Open button's ▾: the editors (⌥E on the button's), Claude Code, Finder (⌥O), the terminal (⌥T), + /// Copy Path, and which editor the button uses (Default Editor ▸, with the ✓). static func openInMenu(_ r: RepositoryModel) -> NSMenu { let path = r.path - let menu = NSMenu(title: "Open In") - menu.autoenablesItems = false + let menu = openMenu("Open In") menu.addItem(openHeader(r.name, Formatters.abbreviatedPath(path))) let editors = OpenIn.installedEditors let current = OpenIn.editor() for editor in editors { - let isCurrent = editor == current - let menuItem = item(editor.name, key: isCurrent ? "e" : "", modifiers: [.option]) { OpenIn.open(folder: path, in: editor) } + let menuItem = item(editor.name, key: editor == current ? "e" : "", modifiers: [.option]) { OpenIn.open(folder: path, in: editor) } showIcon(menuItem, editor.icon(16)) - menuItem.state = isCurrent ? .on : .off menu.addItem(menuItem) } if !editors.isEmpty { menu.addItem(.separator()) } @@ -52,30 +57,28 @@ extension ContextMenus { if !claude.isEmpty { menu.addItem(.separator()) } let finder = item("Finder", key: "o", modifiers: [.option]) { OpenIn.open(folder: path, in: .finder) } showIcon(finder, ExternalApp.finder.icon(16)) - finder.state = current == nil ? .on : .off menu.addItem(finder) let terminal = OpenIn.terminal() let terminalItem = item(terminal.name, key: "t", modifiers: [.option]) { OpenIn.openInTerminal(path) } showIcon(terminalItem, terminal.icon(16)) menu.addItem(terminalItem) menu.addItem(.separator()) - menu.addItem(plainRow(item("Copy Path") { r.copy(path, toast: "Copied \(Formatters.abbreviatedPath(path))") })) + menu.addItem(item("Copy Path") { r.copy(path, toast: "Copied \(Formatters.abbreviatedPath(path))") }) if editors.count > 1 { - menu.addItem(plainRow(submenu("Default Editor", enabled: true, items: editors.map { editor in + menu.addItem(submenu("Default Editor", enabled: true, items: editors.map { editor in let menuItem = item(editor.name) { UserDefaults.kaern.set(editor.id, forKey: SettingsKey.openEditor) } showIcon(menuItem, editor.icon(16)) menuItem.state = editor == current ? .on : .off return menuItem - }))) + })) } return fitHeader(menu) } - /// A file's Open ▾ (Review's header, All Files' file headers): the apps it opens in at its first change (✓ the + /// A file's Open ▾ (Review's header, All Files' file headers): the apps it opens in at its first change (⌘↓ on the /// button's), Claude Code with the file named, the version Review shows when that's a commit's, Finder. static func openFileMenu(_ opening: FileOpening, subtitle: String, _ r: RepositoryModel) -> NSMenu { - let menu = NSMenu(title: opening.path) - menu.autoenablesItems = false + let menu = openMenu(opening.path) let directory = (opening.path as NSString).deletingLastPathComponent menu.addItem(openHeader(opening.name, (directory.isEmpty ? "" : directory + "/ · ") + subtitle)) let choices = openChoices(opening, r) @@ -84,7 +87,6 @@ extension ContextMenus { let menuItem = item(app.name, hint: app == choices.macDefault && !isFirst ? "macOS default" : choices.reason, key: isFirst ? openKey : "", modifiers: [.command], enabled: choices.enabled) { r.open(opening, in: app) } showIcon(menuItem, app.icon(16)) - menuItem.state = isFirst ? .on : .off menu.addItem(menuItem) } menu.addItem(.separator()) @@ -92,12 +94,12 @@ extension ContextMenus { claude.forEach(menu.addItem) if !claude.isEmpty { menu.addItem(.separator()) } if let version = opening.version { - menu.addItem(plainRow(item("Open Version at \(version.commit.prefix(7))", hint: "Read-only copy") { r.openVersion(opening) })) + menu.addItem(plainItem("Open Version at \(version.commit.prefix(7))", hint: "Read-only copy") { r.openVersion(opening) }) menu.addItem(.separator()) } let file = r.existingFile(opening.path) - menu.addItem(plainRow(item("Show in Finder", enabled: file != nil) { if let file { OpenIn.reveal(file) } })) - menu.addItem(plainRow(item("Copy Path") { r.copy(opening.path, toast: "Copied \(opening.path)") })) + menu.addItem(item("Show in Finder", enabled: file != nil) { if let file { OpenIn.reveal(file) } }) + menu.addItem(item("Copy Path") { r.copy(opening.path, toast: "Copied \(opening.path)") }) return fitHeader(menu) } diff --git a/checks/t_openin.py b/checks/t_openin.py index 221d942..c19070f 100644 --- a/checks/t_openin.py +++ b/checks/t_openin.py @@ -19,10 +19,9 @@ def opened(d): return d['driver']['opened'] def frame(name): - """Where the view that reports itself as `name …` is (the driver's frames).""" - for key, value in full_dump()['driver']['frames'].items(): - if key.startswith(name + ' '): return value - raise SystemExit('no %s on screen' % name) + """Where the view that reports itself as `name …` is (the driver's frames), once it's on screen.""" + def find(d): return next((value for key, value in d['driver']['frames'].items() if key.startswith(name + ' ')), None) + return find(until(find, label=name + ' on screen')) def center(f): return str(f[0] + f[2] / 2), str(f[1] + f[3] / 2) @@ -55,23 +54,31 @@ def opens(label, *command): print('Open button:', done) assert done == [('finder ' if not editors else info['editor'] + ' ') + repo], done -# Its ▾: a header, the editors (✓ the button's, ⌥E), Claude Code as far as it's set up, Finder ⌥O, the terminal ⌥T. -# Every row has an icon (a blank one without an app), so the titles line up. +# Its ▾: a header, the editors (⌥E on the button's), Claude Code as far as it's set up, Finder ⌥O, the terminal ⌥T, +# Copy Path, Default Editor ▸. Nothing is indented: no ✓ column, and the rows without an app have no icon, so their +# titles start where the icons do. The one ✓ is the default editor's, in Default Editor ▸. items = menu_items('openIn') print('▾:', [(i.get('title') or i.get('header') or '—', i.get('hint', ''), i.get('key', ''), i.get('on', False)) for i in items]) -assert items[0].get('header') == 'powerlens', items[0] +assert items[0].get('header') == 'powerlens' and not items[0]['stateColumn'], items[0] choices = [i for i in items if 'title' in i] -assert all(i['icon'] for i in choices), [i['title'] for i in choices if not i['icon']] -on = [i for i in choices if i['on']] -assert len(on) == 1 and on[0]['key'] == ('⌥E' if editors else '⌥O'), 'one ✓, on what the button opens: %s' % on -rows = [i for i in choices if i['title'] not in ('Finder', 'Claude Code', 'Copy Path', 'Default Editor') and i['key'] != '⌥T'] +PLAIN = ('Copy Path', 'Default Editor') +assert all(i['icon'] for i in choices if i['title'] not in PLAIN), [i['title'] for i in choices if not i['icon']] +assert not any(i['icon'] for i in choices if i['title'] in PLAIN), 'a row without an app has an icon' +assert not any(i['on'] for i in choices), 'a ✓ outside Default Editor: %s' % [i['title'] for i in choices if i['on']] +keyed = [i['title'] for i in choices if i['key'] == '⌥E'] +assert len(keyed) == (1 if editors else 0), keyed +rows = [i for i in choices if i['title'] not in ('Finder', 'Claude Code') + PLAIN and i['key'] != '⌥T'] assert len(rows) == len(editors), rows -finder = next(i for i in choices if i['title'] == 'Finder'); assert finder['key'] == '⌥O' and finder['on'] == (not editors), finder -shell = next(i for i in choices if i['key'] == '⌥T'); assert shell['icon'], shell +finder = next(i for i in choices if i['title'] == 'Finder'); assert finder['key'] == '⌥O', finder +shell = next(i for i in choices if i['key'] == '⌥T') claude = sorted(i['hint'] for i in choices if i['title'] == 'Claude Code') assert claude == sorted((['Claude app'] if info['claudeApp'] else []) + (['Terminal'] if info['claudeTerminal'] else [])), claude assert any(i['title'] == 'Copy Path' for i in choices) -assert any(i['title'] == 'Default Editor' and len(i.get('submenu', [])) == len(editors) for i in choices) == (len(editors) > 1) +default = next((i for i in choices if i['title'] == 'Default Editor'), None) +assert (default is not None) == (len(editors) > 1), default +if default: + assert len(default['submenu']) == len(editors), default + assert [s['title'] for s in default['submenu'] if s['on']] == keyed, 'the ✓ in Default Editor is on the ⌥E editor' menu_snap('openin-menu', 'menu', 'openIn', str(sum(frame('openMenu')[0:3:2])), str(sum(frame('openMenu')[1:4:2]) + 4), 'right') assert opens('▾ › Finder', 'menuRun', 'openIn | Finder') == ['finder ' + repo] @@ -113,9 +120,11 @@ def opens(label, *command): assert opens('⌘↓', 'press', 'down', 'command', 'through') == done items = menu_items('openFile', CI) print('file ▾:', [(i.get('title') or i.get('header') or '—', i.get('hint', ''), i.get('key', ''), i.get('on', False)) for i in items]) -assert items[0].get('header') == 'ci.yml' -assert all(i['icon'] for i in items if 'title' in i), 'every row has an icon, so the titles line up' -first = next(i for i in items if 'title' in i); assert first['on'] and first['key'] == '⌘↓' and first['enabled'], first +assert items[0].get('header') == 'ci.yml' and not items[0]['stateColumn'], items[0] +rows = [i for i in items if 'title' in i] +assert all(i['icon'] != (i['title'] in ('Show in Finder', 'Copy Path')) for i in rows), 'icons on the apps only' +assert not any(i['on'] for i in rows), 'a ✓ in a file’s ▾' +first = rows[0]; assert first['key'] == '⌘↓' and first['enabled'], first assert not any(i.get('title', '').startswith('Open Version at') for i in items), 'a working-copy file has no commit version' button = frame('openFileMenu') menu_snap('openin-filemenu', 'menu', 'openFile', CI, str(button[0] + button[2]), str(button[1] + button[3] + 4), 'right') @@ -141,7 +150,9 @@ def opens(label, *command): items = menu_items('openFile', path) version = next(i for i in items if i.get('title', '').startswith('Open Version at ')); print('version item:', version) short = version['title'].rsplit(' ', 1)[1] -assert version['hint'] == 'Read-only copy' and commit.startswith(short), (version, commit) +assert version['hint'] == 'Read-only copy' and not version['icon'] and commit.startswith(short), (version, commit) +menu_snap('openin-versionmenu', 'menu', 'openFile', path, str(sum(frame('openFileMenu')[0:3:2])), + str(sum(frame('openFileMenu')[1:4:2]) + 4), 'right') done = opens('Open Version at ' + short, 'menuRun', 'openFile ' + path + ' | ' + version['title']) print('version:', done) copy = done[0].split(' ', 1)[1] @@ -165,6 +176,9 @@ def opens(label, *command): d = until(lambda d: d['driver']['openIn']['repositoryApp'] == other, label='the button follows the setting') k('review', 'off') assert opens('the Open button, another editor', 'click', *center(frame('openButton'))) == [other + ' ' + repo] - assert next(i for i in menu_items('openIn') if i.get('on'))['key'] == '⌥E' + choices = [i for i in menu_items('openIn') if 'title' in i] + moved = [i['title'] for i in choices if i['key'] == '⌥E'] + ticked = [s['title'] for s in next(i for i in choices if i['title'] == 'Default Editor')['submenu'] if s['on']] + assert moved != keyed and ticked == moved, ('⌥E and the ✓ follow the setting', keyed, moved, ticked) quit_app() print('OPEN IN OK') From ee59d7afd1f6520d51e6b51a7a3cc157c8c68ad6 Mon Sep 17 00:00:00 2001 From: progresshans Date: Mon, 30 Nov 2026 01:38:28 +0900 Subject: [PATCH 05/13] fix: the Open menus' notes follow their titles instead of stopping short of the shortcuts MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A note at a row's right end (`titled`: a right tab in the title) ends where the menu's titles end, which is where its shortcuts' column begins. The Open menus have shortcuts (⌥E ⌥O ⌥T, ⌘↓), so their notes (Claude app, Terminal, macOS default, Read-only copy) stopped well short of the right edge. The notes now follow their titles, in the same small secondary text (`noted`), the way Finder writes "(default)", and the 22 pt lead c8045c5 gave a row without an icon is gone. Tried first: the item's badge, which macOS 27 puts at the right edge but draws as a grey pill. The driver reads both kinds of note from the title (`menuLabel`). t_openin passed in light and dark. Co-Authored-By: Claude Opus 5.5 --- Kaern/App/DebugDriver.swift | 22 ++++++++++---- Kaern/Views/Menus/ContextMenus.swift | 7 ++--- Kaern/Views/Menus/OpenMenus.swift | 45 +++++++++++++++++----------- 3 files changed, 47 insertions(+), 27 deletions(-) diff --git a/Kaern/App/DebugDriver.swift b/Kaern/App/DebugDriver.swift index 12dc141..3702946 100644 --- a/Kaern/App/DebugDriver.swift +++ b/Kaern/App/DebugDriver.swift @@ -473,9 +473,8 @@ final class DebugDriver { func describe(_ item: NSMenuItem) -> [String: Any] { if item.isSeparatorItem { return ["separator": true] } if item.view != nil { return ["header": item.title, "stateColumn": item.menu?.showsStateColumn ?? true] } - // An item with a reason has it in its title after a tab (`ContextMenus.titled`). - let parts = item.title.components(separatedBy: "\t") - var entry: [String: Any] = ["title": parts[0], "hint": parts.dropFirst().first ?? "", "enabled": item.isEnabled, + let label = Self.menuLabel(item) + var entry: [String: Any] = ["title": label.title, "hint": label.hint, "enabled": item.isEnabled, "on": item.state == .on, "icon": item.image != nil, "key": item.keyEquivalent.isEmpty ? "" : Self.shortcut(of: item)] if let submenu = item.submenu { entry["submenu"] = submenu.items.map(describe) } @@ -492,12 +491,16 @@ final class DebugDriver { var wanted = halves[1] if let range = wanted.range(of: " > ") { let parent = String(wanted[.. String { + let label = Self.menuLabel(item) + return label.hint.isEmpty ? label.title : label.title + " — " + label.hint + } + guard let index = menu.items.firstIndex(where: { named($0) == wanted }) + ?? menu.items.firstIndex(where: { Self.menuLabel($0).title == wanted }), menu.items[index].isEnabled else { return } menu.performActionForItem(at: index) case "menu": @@ -881,6 +884,13 @@ final class DebugDriver { Self.log.info("key \(characters, privacy: .public) \(modifiers, privacy: .public) handled: \(handled)") } + /// A menu item's title and its note, which follows a tab in its title: a reason at its right end + /// (`ContextMenus.titled`) or a note right after it (the Open menus', `ContextMenus.noted`). + static func menuLabel(_ item: NSMenuItem) -> (title: String, hint: String) { + let parts = item.title.components(separatedBy: "\t") + return (parts[0], parts.dropFirst().first ?? "") + } + /// "⌥E", "⌘↓": a menu item's shortcut the way its menu shows it. static func shortcut(of item: NSMenuItem) -> String { let flags = item.keyEquivalentModifierMask diff --git a/Kaern/Views/Menus/ContextMenus.swift b/Kaern/Views/Menus/ContextMenus.swift index 893282c..7cfa5ef 100644 --- a/Kaern/Views/Menus/ContextMenus.swift +++ b/Kaern/Views/Menus/ContextMenus.swift @@ -626,16 +626,15 @@ enum ContextMenus { } /// The reason an item doesn't apply, in small secondary text at the right of its title - /// (`.mh`), like the board. `lead`: how far left of the other titles this one starts (a row without an icon among - /// rows with one), so its reason still ends where theirs do. - static func titled(_ title: String, hint: String, lead: CGFloat = 0) -> NSAttributedString { + /// (`.mh`), like the board. + static func titled(_ title: String, hint: String) -> NSAttributedString { let font = NSFont.menuFont(ofSize: 0) let result = NSMutableAttributedString(string: title, attributes: [.font: font]) let width = (title as NSString).size(withAttributes: [.font: font]).width let hintFont = NSFont.systemFont(ofSize: z(11)) let hintWidth = (hint as NSString).size(withAttributes: [.font: hintFont]).width let style = NSMutableParagraphStyle() - style.tabStops = [NSTextTab(textAlignment: .right, location: max(280 + lead, width + 28 + hintWidth))] + style.tabStops = [NSTextTab(textAlignment: .right, location: max(280, width + 28 + hintWidth))] result.append(NSAttributedString(string: "\t" + hint, attributes: [ .font: hintFont, .foregroundColor: NSColor.tertiaryLabelColor, .baselineOffset: 1, ])) diff --git a/Kaern/Views/Menus/OpenMenus.swift b/Kaern/Views/Menus/OpenMenus.swift index 7a10afc..2775a2d 100644 --- a/Kaern/Views/Menus/OpenMenus.swift +++ b/Kaern/Views/Menus/OpenMenus.swift @@ -30,12 +30,21 @@ extension ContextMenus { header(title, subtitle, textInset: 16, rule: (16, 16)) } - /// A row without an app, with a reason at its right: its title starts where the icons do, an icon and its gap (22 pt) - /// before the apps' names, so its reason's tab is that much further, to end where the apps' reasons end. - private static func plainItem(_ title: String, hint: String, run: @escaping () -> Void) -> NSMenuItem { - let menuItem = item(title, run: run) - menuItem.attributedTitle = titled(title, hint: hint, lead: 22) - return menuItem + /// A row's note (Claude app, Terminal, macOS default, Read-only copy, Not on disk), in small secondary text right + /// after its title. At the row's right end (`titled`) it would stop short of the shortcuts, before their column. + @discardableResult + static func noted(_ item: NSMenuItem, _ note: String?) -> NSMenuItem { + guard let note else { return item } + let font = NSFont.menuFont(ofSize: 0) + let title = NSMutableAttributedString(string: item.title, attributes: [.font: font]) + let style = NSMutableParagraphStyle() + style.tabStops = [NSTextTab(textAlignment: .left, location: (item.title as NSString).size(withAttributes: [.font: font]).width + 6)] + title.append(NSAttributedString(string: "\t" + note, attributes: [ + .font: NSFont.systemFont(ofSize: z(11)), .foregroundColor: NSColor.tertiaryLabelColor, .baselineOffset: 1, + ])) + title.addAttribute(.paragraphStyle, value: style, range: NSRange(location: 0, length: title.length)) + item.attributedTitle = title + return item } /// The toolbar Open button's ▾: the editors (⌥E on the button's), Claude Code, Finder (⌥O), the terminal (⌥T), @@ -84,8 +93,10 @@ extension ContextMenus { let choices = openChoices(opening, r) for app in choices.apps { let isFirst = app == choices.first - let menuItem = item(app.name, hint: app == choices.macDefault && !isFirst ? "macOS default" : choices.reason, - key: isFirst ? openKey : "", modifiers: [.command], enabled: choices.enabled) { r.open(opening, in: app) } + let menuItem = item(app.name, key: isFirst ? openKey : "", modifiers: [.command], enabled: choices.enabled) { + r.open(opening, in: app) + } + noted(menuItem, app == choices.macDefault && !isFirst ? "macOS default" : choices.reason) showIcon(menuItem, app.icon(16)) menu.addItem(menuItem) } @@ -94,7 +105,7 @@ extension ContextMenus { claude.forEach(menu.addItem) if !claude.isEmpty { menu.addItem(.separator()) } if let version = opening.version { - menu.addItem(plainItem("Open Version at \(version.commit.prefix(7))", hint: "Read-only copy") { r.openVersion(opening) }) + menu.addItem(noted(item("Open Version at \(version.commit.prefix(7))") { r.openVersion(opening) }, "Read-only copy")) menu.addItem(.separator()) } let file = r.existingFile(opening.path) @@ -109,13 +120,13 @@ extension ContextMenus { let choices = openChoices(opening, r) var items: [NSMenuItem] = [] if let first = choices.first { - items.append(item("Open in \(first.name)", hint: choices.reason, key: openKey, modifiers: [.command], - enabled: choices.enabled) { r.open(opening, in: first) }) + items.append(noted(item("Open in \(first.name)", key: openKey, modifiers: [.command], enabled: choices.enabled) { + r.open(opening, in: first) + }, choices.reason)) } var others: [NSMenuItem] = choices.apps.filter { $0 != choices.first }.map { app in - let menuItem = item(app.name, hint: app == choices.macDefault ? "macOS default" : nil, enabled: choices.enabled) { - r.open(opening, in: app) - } + let menuItem = item(app.name, enabled: choices.enabled) { r.open(opening, in: app) } + noted(menuItem, app == choices.macDefault ? "macOS default" : nil) showIcon(menuItem, app.icon(16)) return menuItem } @@ -124,7 +135,7 @@ extension ContextMenus { others += claude if !others.isEmpty { items.append(submenu("Open With", enabled: true, items: others)) } if let version = opening.version { - items.append(item("Open Version at \(version.commit.prefix(7))", hint: "Read-only copy") { r.openVersion(opening) }) + items.append(noted(item("Open Version at \(version.commit.prefix(7))") { r.openVersion(opening) }, "Read-only copy")) } return items } @@ -147,12 +158,12 @@ extension ContextMenus { static func claudeItems(folder: String, prompt: String?) -> [NSMenuItem] { var items: [NSMenuItem] = [] if let app = OpenIn.claudeApp { - let menuItem = item("Claude Code", hint: "Claude app") { OpenIn.claudeCode(folder: folder, prompt: prompt, inTerminal: false) } + let menuItem = noted(item("Claude Code") { OpenIn.claudeCode(folder: folder, prompt: prompt, inTerminal: false) }, "Claude app") showIcon(menuItem, app.icon(16)) items.append(menuItem) } if let handler = OpenIn.claudeTerminal { - let menuItem = item("Claude Code", hint: "Terminal") { OpenIn.claudeCode(folder: folder, prompt: prompt, inTerminal: true) } + let menuItem = noted(item("Claude Code") { OpenIn.claudeCode(folder: folder, prompt: prompt, inTerminal: true) }, "Terminal") showIcon(menuItem, (OpenIn.claudeApp ?? handler).icon(16)) items.append(menuItem) } From 694680be2c75fdf872ef0529d157b4269253c3da Mon Sep 17 00:00:00 2001 From: progresshans Date: Mon, 30 Nov 2026 02:29:16 +0900 Subject: [PATCH 06/13] =?UTF-8?q?feat:=20agents=20in=20the=20Open=20menus,?= =?UTF-8?q?=20and=20Settings=20=E2=80=BA=20Open=20In=20to=20leave=20out=20?= =?UTF-8?q?and=20add?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The toolbar's ▾, a file's ▾, the files' Open With ▸, File › Open in Agent ▸, Quick Open and a tab's menu list the agents found on this Mac (OpenAgents): Claude Code and Codex in their apps by their links (claude://code/new; codex://threads/new, whose `path` the ChatGPT app reads as the new thread's folder since it took Codex in) or in the terminal, and Kiro CLI, Gemini CLI, Cursor Agent and Copilot CLI in the terminal. One shows when its app takes its link or its command is on the login shell's PATH, which Kaern asks the shell for once a launch, in the background (LoginPath). From a file's menu, Claude Code and Codex get "@path" in their prompt, not sent. A command runs in the chosen terminal through a .command script handed to it (Terminal, iTerm and Ghostty all run one): the script removes itself, goes to the folder and runs the command in an interactive login shell, then leaves you in that shell (TerminalCommands). Run outside a terminal, it found codex from a bare PATH, in a folder whose name has a quote and a space. Settings › Open In, a new tab, takes the editor and terminal pickers from General and lists what the Open menus show: untick one to leave it out (never the default editor), and + adds an app, a command for the terminal or a link, with {folder}, {file}, {line} and {prompt} (KaernOpenHidden, KaernOpenCustom). The toolbar's ▾ ends with Customize Menu…, which opens it. The debug driver reports the agents, opens the + sheet (openInSheet) and takes a picture of a sheet (snapshotWindow sheet ). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- CHANGELOG.md | 11 +- Kaern/App/AppDelegate.swift | 3 + Kaern/App/DebugDriver+Phase4.swift | 10 +- Kaern/App/DebugDriver.swift | 16 +- Kaern/App/MainMenu.swift | 30 ++- Kaern/App/OpenAgents.swift | 359 +++++++++++++++++++++++++ Kaern/App/OpenIn.swift | 56 ++-- Kaern/Settings/AppSettings.swift | 8 +- Kaern/Settings/OpenInPane.swift | 366 ++++++++++++++++++++++++++ Kaern/Settings/SettingsWindow.swift | 67 ++--- Kaern/Views/Menus/OpenMenus.swift | 55 ++-- Kaern/Views/QuickOpen/QuickOpen.swift | 10 +- Kaern/Views/TabBar/TabBar.swift | 9 +- 13 files changed, 863 insertions(+), 137 deletions(-) create mode 100644 Kaern/App/OpenAgents.swift create mode 100644 Kaern/Settings/OpenInPane.swift diff --git a/CHANGELOG.md b/CHANGELOG.md index e98da68..b83a51b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,12 +7,17 @@ What changed in each version of Kaern. A version's section is what its update wi ### New - An Open button in the toolbar opens the repository in your editor, VS Code for example, and shows that editor's - icon. Its ▾ opens it in another editor, in Claude Code (the Claude app or claude in a terminal), in Finder or in - the terminal. ⌥E, ⌥O and ⌥T do the same from the keyboard, as in GitKraken. + icon. Its ▾ opens it in another editor, in an agent, in Finder or in the terminal. ⌥E, ⌥O and ⌥T do the same from + the keyboard, as in GitKraken. +- The agents you have show up in the Open menus by themselves: Claude Code and Codex (in their apps, the Claude app + and ChatGPT, or in a terminal), Kiro CLI, Gemini CLI, Cursor Agent and Copilot CLI. From a file's menu, Claude Code + and Codex start with the file named in their prompt. - Review has an Open button too: it opens the file you're looking at in your editor at its first change, and so does ⌘↓. For a commit's file, its ▾ also opens that commit's version as a read-only copy. The files' right-click menus have Open in and Open With. -- Choose the editor and the terminal in Settings › General. Open in Terminal used to always open Terminal. +- Settings › Open In: choose the editor and the terminal, leave out of the Open menus what you don't use, and add + any other app, a command to run in your terminal, or a link (Customize Menu… in the ▾ goes there). Open in + Terminal used to always open Terminal. ### Improved diff --git a/Kaern/App/AppDelegate.swift b/Kaern/App/AppDelegate.swift index 2fe73ce..f6cb78f 100644 --- a/Kaern/App/AppDelegate.swift +++ b/Kaern/App/AppDelegate.swift @@ -29,6 +29,9 @@ final class AppDelegate: NSObject, NSApplicationDelegate { AppModel.shared.launch() QuickLookCopies.removeOld() VersionCopies.removeOld() + TerminalCommands.removeOld() + // The agents in the terminal are found on your login shell's PATH (OpenAgents). + LoginPath.load() // Release builds only (UpdateController.isAvailable). UpdateController.shared.start() } diff --git a/Kaern/App/DebugDriver+Phase4.swift b/Kaern/App/DebugDriver+Phase4.swift index e978539..36a77c5 100644 --- a/Kaern/App/DebugDriver+Phase4.swift +++ b/Kaern/App/DebugDriver+Phase4.swift @@ -11,17 +11,17 @@ extension DebugDriver { "undoPop", "openStash", "closeScreen", "stashBranch", "renameStash", "sheet", "sheetName", "sheetSubmit", "sheetClose", "finishFeature", "irAction", "irMove", "irStart", "irBase", "squash", "type", "history", "blame", "historySelect", "blameFocus", "blameBefore", "exploreMode", "blameOption", "showInHistory", - "autoFetchNow", "fetchAll", "activity", "fakeFailure", "signInSheet", "quickOpen", + "autoFetchNow", "fetchAll", "activity", "fakeFailure", "signInSheet", "openInSheet", "quickOpen", ] func phase4(_ command: String, _ args: [String]) { switch command { case "settings": - // settings <General|Accounts|Git|Diff|Advanced> | settings close + // settings <General|Accounts|Git|Diff|Open In|Advanced> | settings close if args.first == "close" { SettingsWindowController.shared.window?.close() } else { - let pane = SettingsWindowController.Pane(rawValue: args.first ?? "General") ?? .general + let pane = SettingsWindowController.Pane(rawValue: args.isEmpty ? "General" : args.joined(separator: " ")) ?? .general SettingsWindowController.shared.show(pane) } return @@ -54,6 +54,10 @@ extension DebugDriver { case "signInSheet": SettingsWindowController.shared.showSignIn(host: args.first ?? "github.com") return + case "openInSheet": + // openInSheet — Settings › Open In with its + sheet open (Add to the Open Menus). + SettingsWindowController.shared.showAddOpenItem() + return case "fakeAccount": // fakeAccount <login> <host> [Full Name] — shows an account without a token (Accounts pane). guard args.count >= 2 else { return } diff --git a/Kaern/App/DebugDriver.swift b/Kaern/App/DebugDriver.swift index 3702946..1854aed 100644 --- a/Kaern/App/DebugDriver.swift +++ b/Kaern/App/DebugDriver.swift @@ -415,9 +415,12 @@ final class DebugDriver { snapshotComposite(to: args.first ?? "/tmp/kaern-all.png") return case "snapshotWindow": - // snapshotWindow <png> <title…> - let title = args.dropFirst().joined(separator: " ") - if args.count >= 2, let target = NSApp.windows.first(where: { $0.title == title && $0.isVisible }) { + // snapshotWindow <png> <title…> — or "sheet <title…>": the sheet open on that window. + var title = args.dropFirst().joined(separator: " ") + let ofSheet = title.hasPrefix("sheet ") + if ofSheet { title = String(title.dropFirst("sheet ".count)) } + if args.count >= 2, let found = NSApp.windows.first(where: { $0.title == title && $0.isVisible }), + let target = ofSheet ? found.attachedSheet : found { render(target, to: args[0]) } return @@ -1235,8 +1238,11 @@ final class DebugDriver { // What this instance would have opened elsewhere (OpenIn: a test instance opens nothing), and where. "opened": OpenIn.debugLog, "openIn": [ - "editor": OpenIn.editor()?.id ?? "", "editors": OpenIn.installedEditors.map(\.id), "terminal": OpenIn.terminal().id, - "repositoryApp": OpenIn.repositoryApp().id, "claudeApp": OpenIn.claudeApp != nil, "claudeTerminal": OpenIn.claudeTerminal != nil, + "editor": OpenIn.editor()?.id ?? "", "editors": OpenIn.installedEditors.map(\.id), "shownEditors": OpenIn.shownEditors.map(\.id), + "terminal": OpenIn.terminal().id, "repositoryApp": OpenIn.repositoryApp().id, + // The agents a repository's Open menu lists, and a file's (their ids). + "agents": OpenAgents.shown(forFiles: false).map { ["id": $0.id, "name": $0.name, "note": OpenAgents.note($0) ?? ""] }, + "fileAgents": OpenAgents.shown(forFiles: true).map(\.id), ] as [String: Any], // Views that report where they are (`debugFrame`): [x, y, width, height] in window points from the top left. "frames": DebugFrames.shared.frames.mapValues { [$0.minX, $0.minY, $0.width, $0.height] }, diff --git a/Kaern/App/MainMenu.swift b/Kaern/App/MainMenu.swift index 13fde42..95f0af2 100644 --- a/Kaern/App/MainMenu.swift +++ b/Kaern/App/MainMenu.swift @@ -20,6 +20,7 @@ enum MainMenu { return key } private static let recentDelegate = RecentMenuDelegate() + private static let agentsDelegate = AgentsMenuDelegate() static func build(showSettings: @escaping () -> Void) -> NSMenu { let main = NSMenu() @@ -154,12 +155,11 @@ enum MainMenu { menu.addItem(MenuAction.item("Open in Terminal", key: "t", modifiers: [.option], enabled: hasTab, title: { "Open in \(OpenIn.terminal().name)" }) { if let path = window?.activeTab?.path { OpenIn.openInTerminal(path) } }) - menu.addItem(MenuAction.item("Open in Claude Code", enabled: { window?.activeTab != nil }, visible: { OpenIn.claudeApp != nil }) { - if let path = window?.activeTab?.path { OpenIn.claudeCode(folder: path, inTerminal: false) } - }) - menu.addItem(MenuAction.item("Open Claude Code in Terminal", enabled: { window?.activeTab != nil }, visible: { OpenIn.claudeTerminal != nil }) { - if let path = window?.activeTab?.path { OpenIn.claudeCode(folder: path, inTerminal: true) } - }) + // The agents the Open menus list (Settings › Open In), filled as it opens. + let agents = NSMenuItem(title: "Open in Agent", action: nil, keyEquivalent: "") + agents.submenu = NSMenu(title: "Open in Agent") + agents.submenu?.delegate = agentsDelegate + menu.addItem(agents) return menu } @@ -630,6 +630,24 @@ final class MenuAction: NSObject, NSMenuItemValidation { } } +/// Fills File › Open in Agent when it opens: the agents the Open menus list, for the repository in front, and +/// Customize Menu… (Settings › Open In). +final class AgentsMenuDelegate: NSObject, NSMenuDelegate { + func menuNeedsUpdate(_ menu: NSMenu) { + menu.removeAllItems() + let path = AppModel.shared.activeWindow?.model.activeTab?.path + for agent in OpenAgents.shown(forFiles: false) { + let item = MenuAction.item(agent.name, enabled: { path != nil }) { + if let path { OpenAgents.open(agent, at: OpenAgents.Place(folder: path)) } + } + ContextMenus.noted(item, OpenAgents.note(agent)) + menu.addItem(ContextMenus.showIcon(item, OpenAgents.icon(agent, 16))) + } + if !menu.items.isEmpty { menu.addItem(.separator()) } + menu.addItem(MenuAction.item("Customize Menu…") { SettingsWindowController.shared.show(.openIn) }) + } +} + /// Fills File › Open Recent when it opens. final class RecentMenuDelegate: NSObject, NSMenuDelegate { func menuNeedsUpdate(_ menu: NSMenu) { diff --git a/Kaern/App/OpenAgents.swift b/Kaern/App/OpenAgents.swift new file mode 100644 index 0000000..82174f2 --- /dev/null +++ b/Kaern/App/OpenAgents.swift @@ -0,0 +1,359 @@ +import AppKit +import Darwin +import KaernKit + +/// Something besides the editors that the Open menus open a repository or a file in: an agent such as Claude Code or +/// Codex — in its app, or in the terminal — or what was added in Settings › Open In: an app, a command for the +/// terminal, or a link. +struct OpenAgent: Codable, Hashable, Identifiable { + enum Way: String, Codable, CaseIterable { + case app, terminal, link + } + + var id: String + var name: String + var way: Way + /// `.app`: the app, by its bundle identifier. For the other ways, the app whose icon its row shows. + var app: String? + /// `.terminal`: what runs in the repository's folder, in the terminal. `{folder}`, `{file}` and `{line}` become the + /// repository's folder, a file's path and its first changed line, quoted for the shell. + var command: String? + /// `.link`: what's opened. `{folder}`, `{file}`, `{line}` and `{prompt}` (“@path” for a file) are percent-encoded + /// into it, and a query item left empty goes. One of Kaern's agents in the terminal can have one too: its own + /// handler's link, used while that's installed (Claude Code's opens the terminal itself and fills in the prompt). + var link: String? + var forRepositories = true + var forFiles = true + + init(id: String, name: String, way: Way, app: String? = nil, command: String? = nil, link: String? = nil, + forRepositories: Bool = true, forFiles: Bool = true) { + self.id = id + self.name = name + self.way = way + self.app = app + self.command = command + self.link = link + self.forRepositories = forRepositories + self.forFiles = forFiles + } + + /// An added one as Settings › Open In saved it; what it leaves out is as Kaern's are. + init(from decoder: Decoder) throws { + let values = try decoder.container(keyedBy: CodingKeys.self) + id = try values.decode(String.self, forKey: .id) + name = try values.decode(String.self, forKey: .name) + way = try values.decode(Way.self, forKey: .way) + app = try values.decodeIfPresent(String.self, forKey: .app) + command = try values.decodeIfPresent(String.self, forKey: .command) + link = try values.decodeIfPresent(String.self, forKey: .link) + forRepositories = try values.decodeIfPresent(Bool.self, forKey: .forRepositories) ?? true + forFiles = try values.decodeIfPresent(Bool.self, forKey: .forFiles) ?? true + } + + /// One Kaern knows, not one added in Settings. + var isBuiltIn: Bool { OpenAgents.builtIn.contains { $0.id == id } } +} + +/// The agents the Open menus list (`OpenAgent`): Kaern's own once they're installed, then the ones added in Settings › +/// Open In, without what's hidden there. A test instance opens none of them (`OpenIn.debugLog`). +@MainActor +enum OpenAgents { + /// The ones Kaern knows. One shows when its app takes its link, or its command is on your PATH. + static let builtIn: [OpenAgent] = [ + OpenAgent(id: "claude.app", name: "Claude Code", way: .link, app: "com.anthropic.claudefordesktop", + link: "claude://code/new?folder={folder}&q={prompt}"), + OpenAgent(id: "claude.terminal", name: "Claude Code", way: .terminal, app: "com.anthropic.claudefordesktop", command: "claude", + link: "claude-cli://open?cwd={folder}&q={prompt}"), + // The ChatGPT app has Codex since July 2026 (bundle com.openai.codex); `path` is the new thread's folder. + OpenAgent(id: "codex.app", name: "Codex", way: .link, app: "com.openai.codex", + link: "codex://threads/new?path={folder}&prompt={prompt}"), + OpenAgent(id: "codex.terminal", name: "Codex", way: .terminal, app: "com.openai.codex", command: "codex"), + OpenAgent(id: "kiro.terminal", name: "Kiro CLI", way: .terminal, app: "com.amazon.codewhisperer", command: "kiro-cli chat"), + OpenAgent(id: "gemini.terminal", name: "Gemini CLI", way: .terminal, command: "gemini"), + OpenAgent(id: "cursor.terminal", name: "Cursor Agent", way: .terminal, app: "com.todesktop.230313mzl4w4u92", command: "cursor-agent"), + OpenAgent(id: "copilot.terminal", name: "Copilot CLI", way: .terminal, command: "copilot"), + ] + + // MARK: Settings › Open In + + /// The ones added in Settings. + static var custom: [OpenAgent] { + get { + guard let text = UserDefaults.kaern.string(forKey: SettingsKey.openCustom), let data = text.data(using: .utf8), + let list = try? JSONDecoder().decode([OpenAgent].self, from: data) else { return [] } + return list + } + set { + let data = (try? JSONEncoder().encode(newValue)) ?? Data("[]".utf8) + UserDefaults.kaern.set(String(decoding: data, as: UTF8.self), forKey: SettingsKey.openCustom) + } + } + + /// What the Open menus leave out: editors by bundle identifier, agents by id. + static var hidden: Set<String> { + get { + guard let text = UserDefaults.kaern.string(forKey: SettingsKey.openHidden), let data = text.data(using: .utf8), + let list = try? JSONDecoder().decode([String].self, from: data) else { return [] } + return Set(list) + } + set { + let data = (try? JSONEncoder().encode(newValue.sorted())) ?? Data("[]".utf8) + UserDefaults.kaern.set(String(decoding: data, as: UTF8.self), forKey: SettingsKey.openHidden) + } + } + + // MARK: What is installed + + private static var installed: [OpenAgent]? + private static var handlers: [String: URL?] = [:] + + /// Looks again (Kaern became active, or the login shell's PATH came). + static func refresh() { + installed = nil + handlers = [:] + } + + /// Kaern's that are installed, then the added ones (Settings lists these). + static var all: [OpenAgent] { + if installed == nil { installed = builtIn.filter { handler($0) != nil || $0.command.flatMap(commandPath) != nil } } + return (installed ?? []) + custom + } + + /// Kaern's that aren't installed (Settings names them). + static var missing: [String] { + let shown = Set(all.map(\.name)) + var names: [String] = [] + for agent in builtIn where !shown.contains(agent.name) && !names.contains(agent.name) { names.append(agent.name) } + return names + } + + /// What an Open menu lists: for a repository, or for a file; without the hidden ones. + static func shown(forFiles: Bool) -> [OpenAgent] { + let hidden = hidden + return all.filter { !hidden.contains($0.id) && (forFiles ? $0.forFiles : $0.forRepositories) } + } + + /// The app that takes an agent's link, if one is installed. + static func handler(_ agent: OpenAgent) -> URL? { + guard let link = agent.link, let scheme = link.range(of: "://").map({ String(link[..<$0.lowerBound]) }), !scheme.isEmpty else { return nil } + if let known = handlers[scheme] { return known } + let app = URL(string: scheme + "://").flatMap { NSWorkspace.shared.urlForApplication(toOpen: $0) } + handlers[scheme] = app + return app + } + + /// Where a command's program is, from its first word. + private static func commandPath(_ command: String) -> String? { + command.split(separator: " ").first.flatMap { LoginPath.find(String($0)) } + } + + /// What a row says after its name: the app a link opens ("Claude app", "ChatGPT app"), "Terminal"; nothing for an + /// app, whose name is the row's. + static func note(_ agent: OpenAgent) -> String? { + switch agent.way { + case .app: return nil + case .terminal: return "Terminal" + case .link: + guard let app = handler(agent) else { return "Link" } + return FileManager.default.displayName(atPath: app.path(percentEncoded: false)).replacingOccurrences(of: ".app", with: "") + " app" + } + } + + /// Its row's icon: its own app's when that's installed, else the link's handler's or the terminal's. + static func icon(_ agent: OpenAgent, _ size: CGFloat) -> NSImage { + if let id = agent.app, NSWorkspace.shared.urlForApplication(withBundleIdentifier: id) != nil { + return ExternalApp(id: id, fallbackName: agent.name).icon(size) + } + if agent.way == .link, let app = handler(agent), let id = Bundle(url: app)?.bundleIdentifier { + return ExternalApp(id: id, fallbackName: agent.name).icon(size) + } + return OpenIn.terminal().icon(size) + } + + // MARK: Opening + + /// Where an agent opens: the repository's folder, and a file there for a file's menu. + struct Place { + var folder: String + /// The file's full path. + var file: String? + /// Its path in the repository, which a prompt names (“@path”). + var path: String? + var line: Int? + } + + static func open(_ agent: OpenAgent, at place: Place) { + switch agent.way { + case .app: + guard let id = agent.app else { return } + let app = ExternalApp(id: id, fallbackName: agent.name) + if let file = place.file { OpenIn.open(file: URL(filePath: file), line: place.line, in: app) } else { OpenIn.open(folder: place.folder, in: app) } + case .link: + if let template = agent.link, let url = link(template, place) { OpenIn.openLink(url) } + case .terminal: + if let template = agent.link, handler(agent) != nil, let url = link(template, place) { + OpenIn.openLink(url) + } else if let command = agent.command { + OpenIn.runInTerminal(filled(command, place), folder: place.folder) + } + } + } + + /// A link with the place in it: each value percent-encoded, and a query item left empty dropped ("q=" without a + /// prompt). + static func link(_ template: String, _ place: Place) -> URL? { + let values = ["folder": place.folder, "file": place.file ?? "", "line": place.line.map(String.init) ?? "", + "prompt": place.path.map(OpenIn.mention) ?? ""] + var text = template + for (key, value) in values { + text = text.replacingOccurrences(of: "{\(key)}", with: value.addingPercentEncoding(withAllowedCharacters: .linkValue) ?? "") + } + if let mark = text.firstIndex(of: "?") { + let items = text[text.index(after: mark)...].split(separator: "&").filter { !$0.isEmpty && !$0.hasSuffix("=") } + text = String(text[..<mark]) + (items.isEmpty ? "" : "?" + items.joined(separator: "&")) + } + return URL(string: text) + } + + /// A command with the place in it, each value quoted for the shell (nothing for a file in a repository's menu). + static func filled(_ command: String, _ place: Place) -> String { + command.replacingOccurrences(of: "{folder}", with: TerminalCommands.quoted(place.folder)) + .replacingOccurrences(of: "{file}", with: place.file.map(TerminalCommands.quoted) ?? "") + .replacingOccurrences(of: "{line}", with: place.line.map(String.init) ?? "") + } +} + +extension RepositoryModel { + /// The repository, or a file of it, in an agent. An app opens a file that isn't on disk at its commit's version, + /// as the editors do. + func open(_ opening: FileOpening?, inAgent agent: OpenAgent) { + if agent.way == .app, let id = agent.app { + let app = ExternalApp(id: id, fallbackName: agent.name) + if let opening { open(opening, in: app) } else { OpenIn.open(folder: path, in: app) } + return + } + OpenAgents.open(agent, at: OpenAgents.Place(folder: path, file: opening.flatMap { fileURL($0.path)?.path(percentEncoded: false) }, + path: opening?.path, line: opening?.line)) + } +} + +/// The folders on the PATH your login shell sets up. Kaern opened from the Dock has only macOS's own PATH, so it asks +/// your shell once a launch, in the background, as editors do; it also looks in the usual places, for the time before +/// the shell answers, or if it doesn't. +@MainActor +enum LoginPath { + private static var folders: [String] = [] + private static var asked = false + + /// Your login shell (the one Terminal starts). + static let shell: String = { + if let entry = getpwuid(getuid()), let raw = entry.pointee.pw_shell { + let shell = String(cString: raw) + if !shell.isEmpty { return shell } + } + return ProcessInfo.processInfo.environment["SHELL"] ?? "/bin/zsh" + }() + + static let usual = ["~/.local/bin", "/opt/homebrew/bin", "/usr/local/bin", "~/.npm-global/bin", "~/.bun/bin", "~/.cargo/bin", + "~/.volta/bin", "~/bin"] + + /// Where `name` is on that PATH, or in the usual places. + static func find(_ name: String) -> String? { + let home = NSHomeDirectory() + for folder in folders + usual.map({ $0.hasPrefix("~") ? home + $0.dropFirst() : $0 }) { + let path = (folder as NSString).appendingPathComponent(name) + if FileManager.default.isExecutableFile(atPath: path) { return path } + } + return nil + } + + /// Asks the login shell for its PATH, once a launch; the agents are looked for again when it answers. A test + /// instance goes by the usual places. + static func load() { + guard !asked else { return } + asked = true + #if DEBUG + if SessionStore.testSessionPath != nil { return } + #endif + let shell = shell + Task.detached(priority: .utility) { + guard let path = readPath(shell) else { return } + await MainActor.run { + folders = path.split(separator: ":").map(String.init).filter { !$0.isEmpty } + OpenAgents.refresh() + } + } + } + + /// The shell's PATH, written to a file so what its setup prints doesn't matter; nothing after 6 s. + nonisolated private static func readPath(_ shell: String) -> String? { + let file = FileManager.default.temporaryDirectory.appending(path: "kaern-path-\(UUID().uuidString)") + defer { try? FileManager.default.removeItem(at: file) } + let target = TerminalCommands.quoted(file.path(percentEncoded: false)) + let fish = (shell as NSString).lastPathComponent == "fish" + let process = Process() + process.executableURL = URL(filePath: shell) + process.arguments = ["-l", "-i", "-c", fish ? "string join : $PATH > \(target)" : "printf '%s' \"$PATH\" > \(target)"] + process.standardInput = FileHandle.nullDevice + process.standardOutput = FileHandle.nullDevice + process.standardError = FileHandle.nullDevice + let done = DispatchSemaphore(value: 0) + process.terminationHandler = { _ in done.signal() } + do { try process.run() } catch { return nil } + if done.wait(timeout: .now() + 6) == .timedOut { + process.terminate() + return nil + } + return (try? String(contentsOf: file, encoding: .utf8))?.trimmingCharacters(in: .whitespacesAndNewlines) + } +} + +/// A command in a new window of the terminal (Settings › Open In). Kaern writes a small script and hands it to the +/// terminal: Terminal, iTerm and Ghostty all run a `.command` file they're given. The script removes itself, goes to +/// the folder, and starts your login shell (your PATH and setup) to run the command; when that ends, you're in the +/// shell there. +enum TerminalCommands { + static let folder = FileManager.default.temporaryDirectory.appending(path: "Kaern Commands", directoryHint: .isDirectory) + + /// `text` in single quotes, for the shell. + nonisolated static func quoted(_ text: String) -> String { + "'" + text.replacingOccurrences(of: "'", with: "'\\''") + "'" + } + + static func script(_ command: String, in directory: String, shell: String) -> String { + let then = (shell as NSString).lastPathComponent == "fish" + ? "eval $KAERN_COMMAND; set -e KAERN_COMMAND; exec \(quoted(shell)) -l -i" + : "eval \"$KAERN_COMMAND\"; unset KAERN_COMMAND; exec \(quoted(shell)) -l -i" + return """ + #!/bin/sh + rm -f -- "$0" + cd -- \(quoted(directory)) || exit 1 + KAERN_COMMAND=\(quoted(command)) + export KAERN_COMMAND + exec \(quoted(shell)) -l -i -c \(quoted(then)) + + """ + } + + @MainActor + static func run(_ command: String, in directory: String, terminal: ExternalApp) throws { + guard let app = terminal.url else { return } + try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true) + let url = folder.appending(path: String(UUID().uuidString.prefix(8)) + ".command") + try script(command, in: directory, shell: LoginPath.shell).write(to: url, atomically: true, encoding: .utf8) + try FileManager.default.setAttributes([.posixPermissions: 0o700], ofItemAtPath: url.path(percentEncoded: false)) + NSWorkspace.shared.open([url], withApplicationAt: app, configuration: NSWorkspace.OpenConfiguration()) + } + + /// Scripts no terminal ran (each removes itself when it runs). + static func removeOld() { + let fileManager = FileManager.default + guard let items = try? fileManager.contentsOfDirectory(at: folder, includingPropertiesForKeys: [.contentModificationDateKey]) else { + return + } + let hourAgo = Date().addingTimeInterval(-3_600) + for item in items where ((try? item.resourceValues(forKeys: [.contentModificationDateKey]))?.contentModificationDate ?? .distantPast) < hourAgo { + try? fileManager.removeItem(at: item) + } + } +} diff --git a/Kaern/App/OpenIn.swift b/Kaern/App/OpenIn.swift index 98b6607..919fb93 100644 --- a/Kaern/App/OpenIn.swift +++ b/Kaern/App/OpenIn.swift @@ -41,8 +41,8 @@ struct ExternalApp: Hashable, Identifiable { } /// Opening a repository or a file somewhere else (the toolbar's Open button, File › Open in…, the file menus): in -/// an editor, a terminal, Finder or Claude Code. The editor and the terminal are Settings › General's; until one -/// is chosen, the first one of these lists that is installed. +/// an editor, a terminal, Finder or an agent (`OpenAgents`). The editor and the terminal are Settings › Open In's; +/// until one is chosen, the first one of these lists that is installed. /// /// A test instance (`-KaernSessionFile`) opens nothing: it notes what it would have opened (`debugLog`). @MainActor @@ -78,34 +78,33 @@ enum OpenIn { private struct Found { var editors: [ExternalApp] var terminals: [ExternalApp] - /// The app that takes `claude://code/new` links: the Claude app. - var claudeApp: ExternalApp? - /// The app that takes `claude-cli://open` links: Claude Code's handler, which claude registers once it has been - /// used, and which opens a terminal window running it. - var claudeTerminal: ExternalApp? } private static var found: Found? private static var installed: Found { if let found { return found } - func handler(_ link: String) -> ExternalApp? { - guard let url = URL(string: link), let app = NSWorkspace.shared.urlForApplication(toOpen: url) else { return nil } - return ExternalApp(id: Bundle(url: app)?.bundleIdentifier ?? app.lastPathComponent, fallbackName: "Claude") - } - let result = Found(editors: editors.filter { $0.url != nil }, terminals: terminals.filter { $0.url != nil }, - claudeApp: handler("claude://code/new"), claudeTerminal: handler("claude-cli://open")) + let result = Found(editors: editors.filter { $0.url != nil }, terminals: terminals.filter { $0.url != nil }) found = result return result } - /// Looks for the apps again (Kaern became active: one may have been installed or removed meanwhile). - static func refresh() { found = nil } + /// Looks for the apps and agents again (Kaern became active: one may have been installed or removed meanwhile). + static func refresh() { + found = nil + OpenAgents.refresh() + } static var installedEditors: [ExternalApp] { installed.editors } static var installedTerminals: [ExternalApp] { installed.terminals } - static var claudeApp: ExternalApp? { installed.claudeApp } - static var claudeTerminal: ExternalApp? { installed.claudeTerminal } + + /// The editors the Open menus list: the installed ones Settings › Open In doesn't leave out, and always the + /// default one. + static var shownEditors: [ExternalApp] { + let hidden = OpenAgents.hidden + let current = editor() + return installedEditors.filter { !hidden.contains($0.id) || $0 == current } + } /// The editor chosen in Settings (its bundle identifier), else the first one installed; nil when none is. static func editor(chosen: String? = UserDefaults.kaern.string(forKey: SettingsKey.openEditor)) -> ExternalApp? { @@ -194,24 +193,27 @@ enum OpenIn { } } - /// Claude Code in `folder`: the Claude app's Code tab (it asks before it takes a folder from a link), or a new - /// terminal window running claude. `prompt` waits in its input field; nothing is sent. - static func claudeCode(folder: String, prompt: String? = nil, inTerminal: Bool) { - var query = [inTerminal ? "cwd" : "folder": folder] - if let prompt { query["q"] = prompt } - let pairs = query.sorted { $0.key < $1.key }.map { "\($0.key)=\($0.value.addingPercentEncoding(withAllowedCharacters: .linkValue) ?? "")" } - guard let link = URL(string: (inTerminal ? "claude-cli://open?" : "claude://code/new?") + pairs.joined(separator: "&")) else { return } + /// A link, in the app that takes it (an agent's: `claude://`, `codex://`…). + static func openLink(_ link: URL) { perform("link \(link.absoluteString)") { NSWorkspace.shared.open(link) } } - /// What Claude Code is asked to look at for a file: `@path`, quoted when it has a space. + /// A command in a new window of the terminal, in `folder` (an agent in the terminal, `TerminalCommands`). + static func runInTerminal(_ command: String, folder: String) { + let terminal = terminal() + perform("terminal \(terminal.id) \(folder) \(command)") { + try? TerminalCommands.run(command, in: folder, terminal: terminal) + } + } + + /// What an agent's prompt names for a file: `@path`, quoted when it has a space. static func mention(_ path: String) -> String { (path.contains(" ") ? "@\"\(path)\"" : "@" + path) + " " } #if DEBUG /// What a test instance would have opened: "<bundle id> <path>[:line]", "finder <path>", "reveal <path>", - /// "default <path>", "link <url>". + /// "default <path>", "link <url>", "terminal <terminal's bundle id> <folder> <command>". static var debugLog: [String] = [] #endif @@ -226,7 +228,7 @@ enum OpenIn { } } -private extension CharacterSet { +extension CharacterSet { /// What a link's query value keeps as it is; the rest is percent-encoded (`&`, `=`, `+`, spaces, `@`…). static let linkValue = CharacterSet(charactersIn: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~/") } diff --git a/Kaern/Settings/AppSettings.swift b/Kaern/Settings/AppSettings.swift index b2f8299..b62e841 100644 --- a/Kaern/Settings/AppSettings.swift +++ b/Kaern/Settings/AppSettings.swift @@ -42,10 +42,14 @@ nonisolated enum SettingsKey { /// Settings › General › Updates › Get beta versions: Sparkle also offers the appcast's beta channel. A beta /// starts with it on (UpdateController). static let betaUpdates = "KaernBetaUpdates" - /// Settings › General › Open in: the editor (its bundle identifier) the toolbar's Open button, ⌥E and ⌘↓ use. + /// Settings › Open In: the editor (its bundle identifier) the toolbar's Open button, ⌥E and ⌘↓ use. static let openEditor = "KaernOpenEditor" - /// Settings › General › Open in: the terminal (its bundle identifier) ⌥T and Open in Terminal use. + /// Settings › Open In: the terminal (its bundle identifier) ⌥T, Open in Terminal and the agents' commands use. static let openTerminal = "KaernOpenTerminal" + /// Settings › Open In: what the Open menus leave out (editors' bundle identifiers, agents' ids), a JSON array. + static let openHidden = "KaernOpenHidden" + /// Settings › Open In: the agents, apps and links added there (`OpenAgent`s), a JSON array. + static let openCustom = "KaernOpenCustom" // Accounts static let accounts = "KaernAccounts" // Diff diff --git a/Kaern/Settings/OpenInPane.swift b/Kaern/Settings/OpenInPane.swift new file mode 100644 index 0000000..b2aea94 --- /dev/null +++ b/Kaern/Settings/OpenInPane.swift @@ -0,0 +1,366 @@ +import AppKit +import SwiftUI +import UniformTypeIdentifiers + +/// Settings › Open In: the editor and the terminal Kaern opens repositories and files in, and what the Open menus list +/// — the editors and agents found on this Mac, each of which can be left out, and the apps, commands and links added +/// here with +. +struct OpenInPane: View { + @AppStorage(SettingsKey.openEditor, store: .kaern) private var editorID = "" + @AppStorage(SettingsKey.openTerminal, store: .kaern) private var terminalID = "" + @AppStorage(SettingsKey.openHidden, store: .kaern) private var hiddenText = "" + @AppStorage(SettingsKey.openCustom, store: .kaern) private var customText = "" + /// The added one selected in the list, which − removes. + @State private var selection: String? + /// The sheet: a new one (+), or an added one to change (a double-click on it). + @State private var editing: Editing? + + struct Editing: Identifiable { + var agent: OpenAgent + var isNew: Bool + var id: String { agent.id } + } + + var body: some View { + let editors = OpenIn.installedEditors + SettingsGrid { + SettingsRow(label: "Editor:") { + if editors.isEmpty { + Text("None found · repositories open in Finder") + .font(.system(size: z(13))) + .foregroundStyle(K.label2) + .padding(.top, z(5)) + } else { + Picker("Editor", selection: Binding(get: { OpenIn.editor(chosen: editorID)?.id ?? "" }, set: { editorID = $0 })) { + ForEach(editors) { app in + Label { Text(app.name) } icon: { Image(nsImage: app.icon(16)) }.tag(app.id) + } + } + .labelsHidden() + .fixedSize() + } + } + SettingsRow(label: "Terminal:") { + Picker("Terminal", selection: Binding(get: { OpenIn.terminal(chosen: terminalID).id }, set: { terminalID = $0 })) { + ForEach(OpenIn.installedTerminals) { app in + Label { Text(app.name) } icon: { Image(nsImage: app.icon(16)) }.tag(app.id) + } + } + .labelsHidden() + .fixedSize() + Hint("The toolbar’s Open button opens a repository in the editor (⌥E), and Review’s opens a file there at its first change (⌘↓). ⌥O opens the repository in Finder and ⌥T in the terminal, where the agents’ commands run too.") + } + SettingsRow(label: "Open menus:") { + list + HStack(spacing: 0) { + SmallSquareButton(title: "+", label: "Add an app, a command or a link") { add() } + SmallSquareButton(title: "−", label: "Remove the selected one") { remove() } + .disabled(selection == nil) + } + Hint(hint) + } + } + .sheet(item: $editing) { edit in + OpenItemSheet(agent: edit.agent, isNew: edit.isNew) { save($0) } + } + .onAppear { takeAddRequest() } + .onChange(of: SettingsRouter.shared.addsOpenItem) { takeAddRequest() } + } + + // MARK: The list + + private struct Row: Identifiable { + var id: String + var icon: NSImage + var name: String + var note: String? + /// At the right: "Default", an agent's command, "Added". + var detail: String? + var isAdded = false + /// The default editor stays in the menus. + var isLocked = false + } + + private var editorRows: [Row] { + let current = OpenIn.editor(chosen: editorID) + return OpenIn.installedEditors.map { app in + Row(id: app.id, icon: app.icon(16), name: app.name, detail: app == current ? "Default" : nil, isLocked: app == current) + } + } + + private var agentRows: [Row] { + _ = customText + return OpenAgents.all.map { agent in + let added = !agent.isBuiltIn + return Row(id: agent.id, icon: OpenAgents.icon(agent, 16), name: agent.name, note: OpenAgents.note(agent), + detail: added ? "Added" : (agent.way == .terminal ? agent.command : nil), isAdded: added) + } + } + + private var list: some View { + let editors = editorRows + let agents = agentRows + let groups = (editors.isEmpty ? 0 : 1) + (agents.isEmpty ? 0 : 1) + let height = CGFloat(editors.count + agents.count) * z(26) + CGFloat(groups) * z(24) + z(6) + return ScrollView { + VStack(alignment: .leading, spacing: 0) { + if !editors.isEmpty { + group("EDITORS") + ForEach(Array(editors.enumerated()), id: \.element.id) { index, row in line(row, index) } + } + if !agents.isEmpty { + group("AGENTS") + ForEach(Array(agents.enumerated()), id: \.element.id) { index, row in line(row, index) } + } + } + .padding(.bottom, z(6)) + } + .frame(width: z(470), height: min(height, z(400))) + .background(RoundedRectangle(cornerRadius: z(8), style: .continuous).fill(K.field)) + .clipShape(RoundedRectangle(cornerRadius: z(8), style: .continuous)) + .overlay(RoundedRectangle(cornerRadius: z(8), style: .continuous).strokeBorder(K.sepStrong, lineWidth: 0.5)) + } + + private func group(_ title: String) -> some View { + Text(title) + .font(.system(size: z(10.5), weight: .semibold)) + .tracking(0.4) + .foregroundStyle(K.label2) + .frame(height: z(24), alignment: .bottomLeading) + .padding(.leading, z(10)) + .padding(.bottom, z(2)) + } + + private func line(_ row: Row, _ index: Int) -> some View { + let hidden = hiddenSet + let shown = row.isLocked || !hidden.contains(row.id) + let isSelected = row.isAdded && selection == row.id + return HStack(spacing: z(8)) { + Toggle("Show \(row.name) in the Open menus", isOn: Binding(get: { shown }, set: { setHidden(row.id, !$0) })) + .toggleStyle(.checkbox) + .labelsHidden() + .disabled(row.isLocked) + Image(nsImage: row.icon) + .resizable() + .frame(width: z(16), height: z(16)) + Text(row.name) + .font(.system(size: z(13))) + .foregroundStyle(isSelected ? Color.white : (shown ? K.label : K.label2)) + if let note = row.note { + Text(note) + .font(.system(size: z(11))) + .foregroundStyle(isSelected ? Color.white.opacity(0.8) : K.label2) + } + Spacer(minLength: z(8)) + if let detail = row.detail { + Text(detail) + .font(.system(size: z(11), weight: row.isAdded ? .semibold : .regular)) + .foregroundStyle(isSelected ? Color.white.opacity(0.85) : (row.isAdded ? K.accentText : K.label2)) + } + } + .lineLimit(1) + .padding(.horizontal, z(10)) + .frame(height: z(26)) + .background(isSelected ? K.sel : (index % 2 == 1 ? K.alt : Color.clear)) + .contentShape(Rectangle()) + .onTapGesture(count: 2) { + if row.isAdded, let agent = OpenAgents.custom.first(where: { $0.id == row.id }) { + selection = row.id + editing = Editing(agent: agent, isNew: false) + } + } + .simultaneousGesture(TapGesture().onEnded { selection = row.isAdded ? row.id : nil }) + } + + private var hint: String { + var text = "Untick one to leave it out of the Open menus; the default editor stays. + adds an app, a command for your terminal or a link — for an agent or an app Kaern doesn’t know. Double-click one you added to change it." + let missing = OpenAgents.missing + if !missing.isEmpty { + let names = missing.count == 1 ? missing[0] : missing.dropLast().joined(separator: ", ") + " and " + missing[missing.count - 1] + text += " \(names) \(missing.count == 1 ? "shows" : "show") up here once installed." + } + return text + } + + // MARK: Changes + + private var hiddenSet: Set<String> { + _ = hiddenText + return OpenAgents.hidden + } + + private func setHidden(_ id: String, _ isHidden: Bool) { + var hidden = OpenAgents.hidden + if isHidden { hidden.insert(id) } else { hidden.remove(id) } + OpenAgents.hidden = hidden + } + + private func add() { + editing = Editing(agent: OpenAgent(id: UUID().uuidString, name: "", way: .terminal), isNew: true) + } + + private func save(_ agent: OpenAgent) { + var custom = OpenAgents.custom + if let index = custom.firstIndex(where: { $0.id == agent.id }) { custom[index] = agent } else { custom.append(agent) } + OpenAgents.custom = custom + selection = agent.id + } + + private func remove() { + guard let selection else { return } + OpenAgents.custom = OpenAgents.custom.filter { $0.id != selection } + setHidden(selection, false) + self.selection = nil + } + + private func takeAddRequest() { + guard SettingsRouter.shared.addsOpenItem else { return } + SettingsRouter.shared.addsOpenItem = false + add() + } +} + +/// Add to the Open Menus, or change one added before: its name; how it opens — an app, a command in the terminal, a +/// link —; and whether a repository's Open menus list it, a file's, or both. +struct OpenItemSheet: View { + @State var agent: OpenAgent + let isNew: Bool + let save: (OpenAgent) -> Void + @Environment(\.dismiss) private var dismiss + + var body: some View { + VStack(alignment: .leading, spacing: z(16)) { + Text(isNew ? "Add to the Open Menus" : "Edit “\(agent.name)”") + .font(.system(size: z(13), weight: .bold)) + Grid(alignment: .topLeading, horizontalSpacing: z(10), verticalSpacing: z(12)) { + GridRow { + label("Name:") + TextField("Name", text: $agent.name, prompt: Text(namePrompt)) + .textFieldStyle(.roundedBorder) + .labelsHidden() + } + GridRow { + label("Opens:") + SegmentedChoice(options: [(OpenAgent.Way.app, "App"), (.terminal, "Terminal"), (.link, "Link")], + selection: $agent.way, label: "Opens") + } + switch agent.way { + case .app: + GridRow { + label("App:") + VStack(alignment: .leading, spacing: z(5)) { + appChoice + Hint("Opens the repository’s folder, or the file, with that app.") + } + } + case .terminal: + GridRow { + label("Command:") + VStack(alignment: .leading, spacing: z(5)) { + TextField("Command", text: text(\.command), prompt: Text("opencode")) + .font(.system(size: z(12), design: .monospaced)) + .textFieldStyle(.roundedBorder) + .labelsHidden() + Hint("Runs in the repository’s folder, in \(OpenIn.terminal().name). For a file, {file} and {line} are its path and its first change.") + } + } + case .link: + GridRow { + label("Link:") + VStack(alignment: .leading, spacing: z(5)) { + TextField("Link", text: text(\.link), prompt: Text("myagent://new?folder={folder}&prompt={prompt}")) + .font(.system(size: z(12), design: .monospaced)) + .textFieldStyle(.roundedBorder) + .labelsHidden() + Hint("{folder} the repository · {file} and {line} a file and its first change · {prompt} “@file” for a file") + } + } + } + GridRow { + label("Show for:") + HStack(spacing: z(18)) { + Toggle("Repositories", isOn: $agent.forRepositories).toggleStyle(.checkbox) + Toggle("Files", isOn: $agent.forFiles).toggleStyle(.checkbox) + } + .font(.system(size: z(13))) + .padding(.top, z(3)) + } + } + HStack(spacing: z(10)) { + Spacer() + Button("Cancel") { dismiss() } + .keyboardShortcut(.cancelAction) + Button(isNew ? "Add" : "Save") { + save(cleaned) + dismiss() + } + .keyboardShortcut(.defaultAction) + .disabled(!isValid) + } + } + .padding(z(20)) + .frame(width: z(540)) + } + + private var namePrompt: String { + switch agent.way { + case .app: "Zed" + case .terminal: "opencode" + case .link: "My Agent" + } + } + + private func label(_ text: String) -> some View { + Text(text) + .font(.system(size: z(13))) + .frame(width: z(80), alignment: .trailing) + .padding(.top, z(4)) + } + + private func text(_ key: WritableKeyPath<OpenAgent, String?>) -> Binding<String> { + Binding(get: { agent[keyPath: key] ?? "" }, set: { agent[keyPath: key] = $0 }) + } + + private var appChoice: some View { + HStack(spacing: z(8)) { + if let id = agent.app, NSWorkspace.shared.urlForApplication(withBundleIdentifier: id) != nil { + let app = ExternalApp(id: id, fallbackName: id) + Image(nsImage: app.icon(16)) + Text(app.name).font(.system(size: z(13))) + } + Button(agent.app == nil ? "Choose App…" : "Change…") { chooseApp() } + } + } + + private func chooseApp() { + let panel = NSOpenPanel() + panel.allowedContentTypes = [.application] + panel.directoryURL = URL(filePath: "/Applications", directoryHint: .isDirectory) + panel.canChooseDirectories = false + panel.allowsMultipleSelection = false + guard panel.runModal() == .OK, let url = panel.url, let id = Bundle(url: url)?.bundleIdentifier else { return } + agent.app = id + if agent.name.trimmingCharacters(in: .whitespaces).isEmpty { + agent.name = FileManager.default.displayName(atPath: url.path(percentEncoded: false)).replacingOccurrences(of: ".app", with: "") + } + } + + private var isValid: Bool { + guard !agent.name.trimmingCharacters(in: .whitespaces).isEmpty, agent.forRepositories || agent.forFiles else { return false } + switch agent.way { + case .app: return agent.app != nil + case .terminal: return !(agent.command ?? "").trimmingCharacters(in: .whitespaces).isEmpty + case .link: return (agent.link ?? "").contains("://") + } + } + + /// What's saved: the name, command and link trimmed, and only what its way uses. + private var cleaned: OpenAgent { + var result = agent + result.name = agent.name.trimmingCharacters(in: .whitespacesAndNewlines) + result.app = agent.way == .app ? agent.app : nil + result.command = agent.way == .terminal ? agent.command?.trimmingCharacters(in: .whitespacesAndNewlines) : nil + result.link = agent.way == .link ? agent.link?.trimmingCharacters(in: .whitespacesAndNewlines) : nil + return result + } +} diff --git a/Kaern/Settings/SettingsWindow.swift b/Kaern/Settings/SettingsWindow.swift index 9980f08..a0d8be3 100644 --- a/Kaern/Settings/SettingsWindow.swift +++ b/Kaern/Settings/SettingsWindow.swift @@ -2,14 +2,14 @@ import AppKit import KaernKit import SwiftUI -/// Kaern › Settings… (⌘,): General, Accounts, Git, Diff and Advanced as toolbar tabs, like +/// Kaern › Settings… (⌘,): General, Accounts, Git, Diff, Open In and Advanced as toolbar tabs, like /// every Mac app's settings. The window title follows the pane. @MainActor final class SettingsWindowController: NSWindowController, NSWindowDelegate { static let shared = SettingsWindowController() enum Pane: String, CaseIterable { - case general = "General", accounts = "Accounts", git = "Git", diff = "Diff", advanced = "Advanced" + case general = "General", accounts = "Accounts", git = "Git", diff = "Diff", openIn = "Open In", advanced = "Advanced" var symbol: String { switch self { @@ -17,6 +17,7 @@ final class SettingsWindowController: NSWindowController, NSWindowDelegate { case .accounts: "person.crop.circle" case .git: "arrow.triangle.branch" case .diff: "rectangle.split.2x1" + case .openIn: "arrow.up.forward.app" case .advanced: "slider.horizontal.3" } } @@ -63,13 +64,20 @@ final class SettingsWindowController: NSWindowController, NSWindowDelegate { show(.accounts) SettingsRouter.shared.signInHost = host } + + /// Open In with its + sheet open (the debug driver's pictures). + func showAddOpenItem() { + show(.openIn) + SettingsRouter.shared.addsOpenItem = true + } } -/// Asks a pane to do something when the window opens on it (the sign-in sheet). +/// Asks a pane to do something when the window opens on it (the sign-in sheet, the Open In + sheet). @MainActor @Observable final class SettingsRouter { static let shared = SettingsRouter() var signInHost: String? + var addsOpenItem = false } // MARK: - Layout @@ -86,6 +94,7 @@ private struct SettingsPaneView: View { case .accounts: AccountsPane() case .git: GitPane() case .diff: DiffPane() + case .openIn: OpenInPane() case .advanced: AdvancedPane() } } @@ -106,7 +115,7 @@ private struct SettingsPaneView: View { } /// `.grid2`: right-aligned labels in a 170 pt column, controls on the right. -private struct SettingsGrid<Content: View>: View { +struct SettingsGrid<Content: View>: View { @ViewBuilder let content: Content var body: some View { @@ -116,7 +125,7 @@ private struct SettingsGrid<Content: View>: View { } } -private struct SettingsRow<Content: View>: View { +struct SettingsRow<Content: View>: View { let label: String @ViewBuilder let content: Content @@ -135,7 +144,7 @@ private struct SettingsRow<Content: View>: View { } /// `.chk`: a checkbox row, 26 pt tall so its text lines up with the row's label. -private struct Checkbox: View { +struct Checkbox: View { let title: String @Binding var isOn: Bool @@ -153,7 +162,7 @@ private struct Checkbox: View { } /// `.hint`: gray help text under a control. -private struct Hint: View { +struct Hint: View { let text: String var strong = false @@ -259,10 +268,6 @@ private struct GeneralPane: View { .labelsHidden() .fixedSize() } - SettingsRow(label: "Open in:") { - OpenInSettings() - Hint("The toolbar’s Open button opens a repository in the editor (⌥E), and Review’s opens a file there at its first change (⌘↓). ⌥O opens the repository in Finder and ⌥T in the terminal. Claude Code is in the Open button’s ▾ menu.") - } SettingsRow(label: "Appearance:") { SegmentedChoice(options: [(AppTheme.system, "System"), (.light, "Light"), (.dark, "Dark")], selection: $theme, label: "Appearance") .padding(.top, 1) @@ -286,44 +291,6 @@ private struct GeneralPane: View { } } -/// General › Open in: the editor and the terminal Kaern opens repositories and files in (`OpenIn`), from the ones -/// installed on this Mac. -private struct OpenInSettings: View { - @AppStorage(SettingsKey.openEditor, store: .kaern) private var editorID = "" - @AppStorage(SettingsKey.openTerminal, store: .kaern) private var terminalID = "" - - var body: some View { - let editors = OpenIn.installedEditors - Grid(alignment: .leading, horizontalSpacing: z(8), verticalSpacing: z(8)) { - GridRow { - Text("Editor") - if editors.isEmpty { - Text("None found · repositories open in Finder").foregroundStyle(K.label2) - } else { - Picker("Editor", selection: Binding(get: { OpenIn.editor(chosen: editorID)?.id ?? "" }, set: { editorID = $0 })) { - ForEach(editors) { app in - Label { Text(app.name) } icon: { Image(nsImage: app.icon(16)) }.tag(app.id) - } - } - .labelsHidden() - .fixedSize() - } - } - GridRow { - Text("Terminal") - Picker("Terminal", selection: Binding(get: { OpenIn.terminal(chosen: terminalID).id }, set: { terminalID = $0 })) { - ForEach(OpenIn.installedTerminals) { app in - Label { Text(app.name) } icon: { Image(nsImage: app.icon(16)) }.tag(app.id) - } - } - .labelsHidden() - .fixedSize() - } - } - .font(.system(size: z(13))) - } -} - extension GeneralPane { /// The line under the three layouts. var switchingDescription: String { @@ -687,7 +654,7 @@ private struct AccountsPane: View { } /// `.apm button`: + and − under a list. -private struct SmallSquareButton: View { +struct SmallSquareButton: View { let title: String let label: String let action: () -> Void diff --git a/Kaern/Views/Menus/OpenMenus.swift b/Kaern/Views/Menus/OpenMenus.swift index 2775a2d..99ed3b0 100644 --- a/Kaern/Views/Menus/OpenMenus.swift +++ b/Kaern/Views/Menus/OpenMenus.swift @@ -47,13 +47,14 @@ extension ContextMenus { return item } - /// The toolbar Open button's ▾: the editors (⌥E on the button's), Claude Code, Finder (⌥O), the terminal (⌥T), - /// Copy Path, and which editor the button uses (Default Editor ▸, with the ✓). + /// The toolbar Open button's ▾: the editors (⌥E on the button's), the agents, Finder (⌥O), the terminal (⌥T), + /// Copy Path, which editor the button uses (Default Editor ▸, with the ✓), and Customize Menu… (Settings › Open In, + /// which leaves some out and adds others). static func openInMenu(_ r: RepositoryModel) -> NSMenu { let path = r.path let menu = openMenu("Open In") menu.addItem(openHeader(r.name, Formatters.abbreviatedPath(path))) - let editors = OpenIn.installedEditors + let editors = OpenIn.shownEditors let current = OpenIn.editor() for editor in editors { let menuItem = item(editor.name, key: editor == current ? "e" : "", modifiers: [.option]) { OpenIn.open(folder: path, in: editor) } @@ -61,9 +62,9 @@ extension ContextMenus { menu.addItem(menuItem) } if !editors.isEmpty { menu.addItem(.separator()) } - let claude = claudeItems(folder: path, prompt: nil) - claude.forEach(menu.addItem) - if !claude.isEmpty { menu.addItem(.separator()) } + let agents = agentItems(r) + agents.forEach(menu.addItem) + if !agents.isEmpty { menu.addItem(.separator()) } let finder = item("Finder", key: "o", modifiers: [.option]) { OpenIn.open(folder: path, in: .finder) } showIcon(finder, ExternalApp.finder.icon(16)) menu.addItem(finder) @@ -81,11 +82,13 @@ extension ContextMenus { return menuItem })) } + menu.addItem(item("Customize Menu…") { SettingsWindowController.shared.show(.openIn) }) return fitHeader(menu) } /// A file's Open ▾ (Review's header, All Files' file headers): the apps it opens in at its first change (⌘↓ on the - /// button's), Claude Code with the file named, the version Review shows when that's a commit's, Finder. + /// button's), the agents (Claude Code and Codex with the file named), the version Review shows when that's a + /// commit's, Finder. static func openFileMenu(_ opening: FileOpening, subtitle: String, _ r: RepositoryModel) -> NSMenu { let menu = openMenu(opening.path) let directory = (opening.path as NSString).deletingLastPathComponent @@ -101,9 +104,9 @@ extension ContextMenus { menu.addItem(menuItem) } menu.addItem(.separator()) - let claude = claudeItems(folder: r.path, prompt: OpenIn.mention(opening.path)) - claude.forEach(menu.addItem) - if !claude.isEmpty { menu.addItem(.separator()) } + let agents = agentItems(r, file: opening) + agents.forEach(menu.addItem) + if !agents.isEmpty { menu.addItem(.separator()) } if let version = opening.version { menu.addItem(noted(item("Open Version at \(version.commit.prefix(7))") { r.openVersion(opening) }, "Read-only copy")) menu.addItem(.separator()) @@ -114,8 +117,8 @@ extension ContextMenus { return fitHeader(menu) } - /// A file's right-click Open items: Open in <the app its button uses> (⌘↓), then Open With ▸ the others and - /// Claude Code; for a commit's file, Open Version at…. + /// A file's right-click Open items: Open in <the app its button uses> (⌘↓), then Open With ▸ the others and the + /// agents; for a commit's file, Open Version at…. static func openItems(_ opening: FileOpening, _ r: RepositoryModel) -> [NSMenuItem] { let choices = openChoices(opening, r) var items: [NSMenuItem] = [] @@ -130,9 +133,9 @@ extension ContextMenus { showIcon(menuItem, app.icon(16)) return menuItem } - let claude = claudeItems(folder: r.path, prompt: OpenIn.mention(opening.path)) - if !others.isEmpty, !claude.isEmpty { others.append(.separator()) } - others += claude + let agents = agentItems(r, file: opening) + if !others.isEmpty, !agents.isEmpty { others.append(.separator()) } + others += agents if !others.isEmpty { items.append(submenu("Open With", enabled: true, items: others)) } if let version = opening.version { items.append(noted(item("Open Version at \(version.commit.prefix(7))") { r.openVersion(opening) }, "Read-only copy")) @@ -148,25 +151,17 @@ extension ContextMenus { let first = OpenIn.app(forFile: file ?? URL(filePath: opening.path)) let macDefault = file.flatMap(ExternalApp.opening) var seen = Set<String>() - let apps = ([first].compactMap { $0 } + OpenIn.installedEditors + [macDefault].compactMap { $0 }).filter { seen.insert($0.id).inserted } + let apps = ([first].compactMap { $0 } + OpenIn.shownEditors + [macDefault].compactMap { $0 }).filter { seen.insert($0.id).inserted } let enabled = file != nil || opening.version != nil return (apps, first, macDefault, enabled, enabled ? nil : "Not on disk") } - /// Claude Code's two ways in, as far as they're set up on this Mac: the Claude app's Code tab, and claude in a - /// terminal window. `prompt` waits in its input field. - static func claudeItems(folder: String, prompt: String?) -> [NSMenuItem] { - var items: [NSMenuItem] = [] - if let app = OpenIn.claudeApp { - let menuItem = noted(item("Claude Code") { OpenIn.claudeCode(folder: folder, prompt: prompt, inTerminal: false) }, "Claude app") - showIcon(menuItem, app.icon(16)) - items.append(menuItem) + /// The agents' rows (`OpenAgents`), each with how it opens after its name ("Claude app", "Terminal"): the + /// repository, or `file` — which Claude Code and Codex find named in their prompt, waiting to be sent. + static func agentItems(_ r: RepositoryModel, file: FileOpening? = nil) -> [NSMenuItem] { + OpenAgents.shown(forFiles: file != nil).map { agent in + let menuItem = noted(item(agent.name) { r.open(file, inAgent: agent) }, OpenAgents.note(agent)) + return showIcon(menuItem, OpenAgents.icon(agent, 16)) } - if let handler = OpenIn.claudeTerminal { - let menuItem = noted(item("Claude Code") { OpenIn.claudeCode(folder: folder, prompt: prompt, inTerminal: true) }, "Terminal") - showIcon(menuItem, (OpenIn.claudeApp ?? handler).icon(16)) - items.append(menuItem) - } - return items } } diff --git a/Kaern/Views/QuickOpen/QuickOpen.swift b/Kaern/Views/QuickOpen/QuickOpen.swift index 1eab240..b8a9a28 100644 --- a/Kaern/Views/QuickOpen/QuickOpen.swift +++ b/Kaern/Views/QuickOpen/QuickOpen.swift @@ -162,7 +162,7 @@ enum QuickOpenSource { ] + openCommands(r) } - /// The repository somewhere else (ScreenOpenIn): the editor, Finder, the terminal, Claude Code. + /// The repository somewhere else (ScreenOpenIn): the editor, Finder, the terminal, the agents. private static func openCommands(_ r: RepositoryModel) -> [Command] { var commands: [Command] = [] if let editor = OpenIn.editor() { @@ -170,11 +170,9 @@ enum QuickOpenSource { } commands.append(Command(title: "Open in Finder", shortcut: "⌥O") { OpenIn.open(folder: r.path, in: .finder) }) commands.append(Command(title: "Open in \(OpenIn.terminal().name)", shortcut: "⌥T") { OpenIn.openInTerminal(r.path) }) - if OpenIn.claudeApp != nil { - commands.append(Command(title: "Open in Claude Code", shortcut: "") { OpenIn.claudeCode(folder: r.path, inTerminal: false) }) - } - if OpenIn.claudeTerminal != nil { - commands.append(Command(title: "Open Claude Code in Terminal", shortcut: "") { OpenIn.claudeCode(folder: r.path, inTerminal: true) }) + for agent in OpenAgents.shown(forFiles: false) { + let note = OpenAgents.note(agent).map { " (\($0))" } ?? "" + commands.append(Command(title: "Open in \(agent.name)\(note)", shortcut: "") { r.open(nil, inAgent: agent) }) } return commands } diff --git a/Kaern/Views/TabBar/TabBar.swift b/Kaern/Views/TabBar/TabBar.swift index 22bf44a..92487e3 100644 --- a/Kaern/Views/TabBar/TabBar.swift +++ b/Kaern/Views/TabBar/TabBar.swift @@ -384,11 +384,10 @@ struct OpenInButtons: View { } Button("Open in Finder") { OpenIn.open(folder: path, in: .finder) } Button("Open in \(OpenIn.terminal().name)") { OpenIn.openInTerminal(path) } - if OpenIn.claudeApp != nil { - Button("Open in Claude Code") { OpenIn.claudeCode(folder: path, inTerminal: false) } - } - if OpenIn.claudeTerminal != nil { - Button("Open Claude Code in Terminal") { OpenIn.claudeCode(folder: path, inTerminal: true) } + ForEach(OpenAgents.shown(forFiles: false)) { agent in + Button("Open in \(agent.name)" + (OpenAgents.note(agent).map { " (\($0))" } ?? "")) { + OpenAgents.open(agent, at: OpenAgents.Place(folder: path)) + } } Button("Copy Path") { NSPasteboard.general.clearContents() From f3417ff96ef42ab1349ef189c1e92cbc486216b7 Mon Sep 17 00:00:00 2001 From: progresshans <progresshans@gmail.com> Date: Mon, 30 Nov 2026 02:29:16 +0900 Subject: [PATCH 07/13] =?UTF-8?q?test:=20t=5Fopenin=20checks=20the=20agent?= =?UTF-8?q?s,=20the=20added=20ones,=20leaving=20out=20and=20Settings=20?= =?UTF-8?q?=E2=80=BA=20Open=20In?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit t_openin goes by the agents this Mac has (each one's link or command) and adds three of its own through KaernOpenCustom: a command, a link no app takes, and an app only for files. It checks each in a repository's and a file's menus, with the folder, the file, its line and the prompt filled in; that a left-out agent and editor go while the default editor stays; that Customize Menu… opens Settings › Open In; and it takes pictures of that tab and its + sheet. It passed in light and dark, and so did t_quickopen. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- checks/README.md | 8 ++-- checks/suite.py | 2 +- checks/t_openin.py | 111 ++++++++++++++++++++++++++++++++++----------- 3 files changed, 91 insertions(+), 30 deletions(-) diff --git a/checks/README.md b/checks/README.md index cb6ff62..c47fb42 100644 --- a/checks/README.md +++ b/checks/README.md @@ -49,9 +49,11 @@ A test instance's Dock icon has a purple TEST tag, and a Debug build you run you (`Kaern/App/DockTag.swift`), so neither is taken for the Kaern you use. `t_isolation` checks it and keeps a picture of each tag in `shots/`. -A test instance opens nothing in another app (an editor, Finder, a terminal, Claude Code): it notes what it would -have opened in the dump's `driver.opened` (`OpenIn`), and `driver.openIn` says which of those apps this Mac has. -`t_openin` goes by both, so it passes whatever is installed. +A test instance opens nothing in another app (an editor, Finder, a terminal, an agent): it notes what it would have +opened in the dump's `driver.opened` (`OpenIn`; a command for the terminal as `terminal <terminal> <folder> +<command>`), and `driver.openIn` says which of those apps and agents this Mac has. `t_openin` goes by both, so it +passes whatever is installed, and adds agents of its own through `KaernOpenCustom`. A test instance looks for the +agents' commands only in the usual places (`LoginPath`), without asking a login shell. ## Where things are diff --git a/checks/suite.py b/checks/suite.py index 25163e8..e9de906 100644 --- a/checks/suite.py +++ b/checks/suite.py @@ -136,7 +136,7 @@ def __init__(self, name, areas, dark=False, alone=False, samples=('base',), seco (r'RepositoryModel\+Worktrees', 'worktrees'), (r'RepositoryModel\+Undo|GitRepository\+Undo', 'undo'), (r'Views/Menus/|App/MainMenu', 'menus'), - (r'App/OpenIn|Menus/OpenMenus|Review/FileOpenButton|Common/DebugFrame', 'openin'), + (r'App/OpenIn|App/OpenAgents|Settings/OpenInPane|Menus/OpenMenus|Review/FileOpenButton|Common/DebugFrame', 'openin'), (r'Views/StatusBar/', 'statusbar'), (r'Views/CommandLog/|App/CommandLog|Git/GitCommandLog', 'commandlog'), ] diff --git a/checks/t_openin.py b/checks/t_openin.py index c19070f..dd54b87 100644 --- a/checks/t_openin.py +++ b/checks/t_openin.py @@ -1,11 +1,12 @@ """t_openin.py [light|dark] — Open (ScreenOpenIn). The toolbar's Open button opens the repository in the default editor -(Finder when none is installed), and its ▾ lists the editors, Claude Code, Finder and the terminal; ⌥E ⌥O ⌥T do the -same, but not while text is typed. Review's Open button opens a file at its first change (so does ⌘↓), and for a -commit's file its ▾ has Open Version at…, a read-only copy of that version. Settings › General picks the editor. +(Finder when none is installed), and its ▾ lists the editors, the agents (Claude Code, Codex… as installed), Finder and +the terminal; ⌥E ⌥O ⌥T do the same, but not while text is typed. Review's Open button opens a file at its first change +(so does ⌘↓), and for a commit's file its ▾ has Open Version at…, a read-only copy of that version. Settings › Open In +picks the editor, leaves editors and agents out of the menus, and adds apps, commands and links (Customize Menu…). A test instance opens nothing: it notes what it would have opened (the dump's `opened`). What is installed differs from -Mac to Mac (the dump's `openIn`), so the check goes by that.""" -import json, os, stat, sys, urllib.parse +Mac to Mac (the dump's `openIn`), so the check goes by that, and adds three of its own (an app, a command, a link).""" +import json, os, shlex, stat, sys, urllib.parse sys.path.insert(0, os.path.dirname(__file__)) from k5 import * mode = sys.argv[1] if len(sys.argv) > 1 else 'light' @@ -13,11 +14,27 @@ AT_LINE = {'com.microsoft.VSCode', 'com.microsoft.VSCodeInsiders', 'com.todesktop.230313mzl4w4u92', 'com.exafunction.windsurf', 'com.apple.dt.Xcode'} ITEMS = os.path.join(RUN_DIR, 'openin-items.json') +# Added in Settings › Open In: a command for the terminal, a link no app takes, and an app only for files. +CUSTOM = [ + {'id': 'check-command', 'name': 'Check Agent', 'way': 'terminal', 'command': 'check-agent --in {folder} {file}'}, + {'id': 'check-link', 'name': 'Check Link', 'way': 'link', 'link': 'kaerncheck://open?folder={folder}&file={file}&line={line}&q={prompt}'}, + {'id': 'check-app', 'name': 'Check App', 'way': 'app', 'app': 'com.apple.TextEdit', 'forRepositories': False}, +] def opened(d): return d['driver']['opened'] +def sh(text): + """Quoted for the shell as Kaern quotes a command's {folder} and {file}.""" + return "'" + text.replace("'", "'\\''") + "'" + + +def agent_rows(items): + """An Open menu's agents: the rows between the editors and Finder (or the file's apps and what follows).""" + return [(i['title'], i['hint']) for i in items if 'title' in i and i['title'] in AGENT_NAMES] + + def frame(name): """Where the view that reports itself as `name …` is (the driver's frames), once it's on screen.""" def find(d): return next((value for key, value in d['driver']['frames'].items() if key.startswith(name + ' ')), None) @@ -46,6 +63,8 @@ def opens(label, *command): repo = os.path.realpath(PL) info = full_dump()['driver']['openIn']; print('installed:', info) editors, terminal = info['editors'], info['terminal'] +agents = info['agents'] +AGENT_NAMES = {a['name'] for a in agents} | {c['name'] for c in CUSTOM} assert info['repositoryApp'] == (info['editor'] or 'com.apple.finder'), 'the button opens in the editor, else Finder: %s' % info snap('openin-toolbar', mode) @@ -54,26 +73,25 @@ def opens(label, *command): print('Open button:', done) assert done == [('finder ' if not editors else info['editor'] + ' ') + repo], done -# Its ▾: a header, the editors (⌥E on the button's), Claude Code as far as it's set up, Finder ⌥O, the terminal ⌥T, -# Copy Path, Default Editor ▸. Nothing is indented: no ✓ column, and the rows without an app have no icon, so their -# titles start where the icons do. The one ✓ is the default editor's, in Default Editor ▸. +# Its ▾: a header, the editors (⌥E on the button's), the agents found here, Finder ⌥O, the terminal ⌥T, Copy Path, +# Default Editor ▸, Customize Menu…. Nothing is indented: no ✓ column, and the rows without an app have no icon, so +# their titles start where the icons do. The one ✓ is the default editor's, in Default Editor ▸. items = menu_items('openIn') print('▾:', [(i.get('title') or i.get('header') or '—', i.get('hint', ''), i.get('key', ''), i.get('on', False)) for i in items]) assert items[0].get('header') == 'powerlens' and not items[0]['stateColumn'], items[0] choices = [i for i in items if 'title' in i] -PLAIN = ('Copy Path', 'Default Editor') +PLAIN = ('Copy Path', 'Default Editor', 'Customize Menu…') assert all(i['icon'] for i in choices if i['title'] not in PLAIN), [i['title'] for i in choices if not i['icon']] assert not any(i['icon'] for i in choices if i['title'] in PLAIN), 'a row without an app has an icon' assert not any(i['on'] for i in choices), 'a ✓ outside Default Editor: %s' % [i['title'] for i in choices if i['on']] keyed = [i['title'] for i in choices if i['key'] == '⌥E'] assert len(keyed) == (1 if editors else 0), keyed -rows = [i for i in choices if i['title'] not in ('Finder', 'Claude Code') + PLAIN and i['key'] != '⌥T'] +rows = [i for i in choices if i['title'] not in ('Finder',) + PLAIN and i['title'] not in AGENT_NAMES and i['key'] != '⌥T'] assert len(rows) == len(editors), rows +assert agent_rows(items) == [(a['name'], a['note']) for a in agents], ('the agents found', agent_rows(items), agents) finder = next(i for i in choices if i['title'] == 'Finder'); assert finder['key'] == '⌥O', finder shell = next(i for i in choices if i['key'] == '⌥T') -claude = sorted(i['hint'] for i in choices if i['title'] == 'Claude Code') -assert claude == sorted((['Claude app'] if info['claudeApp'] else []) + (['Terminal'] if info['claudeTerminal'] else [])), claude -assert any(i['title'] == 'Copy Path' for i in choices) +assert any(i['title'] == 'Copy Path' for i in choices) and choices[-1]['title'] == 'Customize Menu…', choices[-1] default = next((i for i in choices if i['title'] == 'Default Editor'), None) assert (default is not None) == (len(editors) > 1), default if default: @@ -84,12 +102,37 @@ def opens(label, *command): assert opens('▾ › Finder', 'menuRun', 'openIn | Finder') == ['finder ' + repo] assert opens('▾ › the terminal', 'menuRun', 'openIn | ' + shell['title']) == [terminal + ' ' + repo] quoted = urllib.parse.quote(repo, safe='/') -if info['claudeApp']: - link = opens('▾ › Claude Code in the Claude app', 'menuRun', 'openIn | Claude Code — Claude app'); print('Claude app:', link) - assert link == ['link claude://code/new?folder=' + quoted], link -if info['claudeTerminal']: - link = opens('▾ › Claude Code in a terminal', 'menuRun', 'openIn | Claude Code — Terminal'); print('Claude in a terminal:', link) - assert link == ['link claude-cli://open?cwd=' + quoted], link +# The agents Kaern knows, as far as they're installed here: by their links, or their command in the terminal. +ids = [a['id'] for a in agents] +for agent in agents: + done = opens('▾ › ' + agent['id'], 'menuRun', 'openIn | %s — %s' % (agent['name'], agent['note'])); print(agent['id'] + ':', done) + if agent['id'] == 'claude.app': assert done == ['link claude://code/new?folder=' + quoted], done + elif agent['id'] == 'claude.terminal': # Claude Code's own handler while it's set up, else claude in the terminal + assert done in (['link claude-cli://open?cwd=' + quoted], ['terminal %s %s claude' % (terminal, repo)]), done + elif agent['id'] == 'codex.app': assert done == ['link codex://threads/new?path=' + quoted], done + elif agent['id'] == 'codex.terminal': assert done == ['terminal %s %s codex' % (terminal, repo)], done + +# Settings › Open In adds three: the command and the link show for a repository, the app only for files. +set_setting('KaernOpenCustom', json.dumps(CUSTOM, separators=(',', ':'))) +until(lambda d: [a['id'] for a in d['driver']['openIn']['agents']][-2:] == ['check-command', 'check-link'], label='the added ones') +items = menu_items('openIn') +assert agent_rows(items)[-2:] == [('Check Agent', 'Terminal'), ('Check Link', 'Link')], agent_rows(items) +assert opens('▾ › Check Agent', 'menuRun', 'openIn | Check Agent — Terminal') == \ + ['terminal %s %s check-agent --in %s ' % (terminal, repo, sh(repo))] +assert opens('▾ › Check Link', 'menuRun', 'openIn | Check Link — Link') == ['link kaerncheck://open?folder=' + quoted] +# What Settings leaves out goes from the menu, but never the default editor. +hide = ['check-link'] + editors[1:2] + editors[:1] +set_setting('KaernOpenHidden', json.dumps(hide, separators=(',', ':'))) +until(lambda d: 'check-link' not in [a['id'] for a in d['driver']['openIn']['agents']], label='Check Link left out') +titles = [i['title'] for i in menu_items('openIn') if 'title' in i] +assert 'Check Link' not in titles and 'Check Agent' in titles, titles +assert full_dump()['driver']['openIn']['shownEditors'] == editors[:1] + editors[2:], 'the second editor left out, the default kept' +set_setting('KaernOpenHidden', None) +# Customize Menu… opens Settings › Open In. +k('menuRun', 'openIn | Customize Menu…') +until(lambda d: window_open(d, 'Open In'), label='Settings › Open In') +k('settings', 'close') +until(lambda d: not window_open(d, 'Open In'), label='the Settings window closed') # ⌥O ⌥T ⌥E as in GitKraken, through the menus the way a real key goes. k('openClear') @@ -126,13 +169,25 @@ def opens(label, *command): assert not any(i['on'] for i in rows), 'a ✓ in a file’s ▾' first = rows[0]; assert first['key'] == '⌘↓' and first['enabled'], first assert not any(i.get('title', '').startswith('Open Version at') for i in items), 'a working-copy file has no commit version' +# The agents for files: Kaern's, then the three added (the app only here). +assert agent_rows(items) == [(a['name'], a['note']) for a in agents] + [('Check Agent', 'Terminal'), ('Check Link', 'Link'), ('Check App', '')], \ + agent_rows(items) button = frame('openFileMenu') menu_snap('openin-filemenu', 'menu', 'openFile', CI, str(button[0] + button[2]), str(button[1] + button[3] + 4), 'right') assert opens('▾ › Show in Finder', 'menuRun', 'openFile ' + CI + ' | Show in Finder') == ['reveal ' + os.path.join(repo, CI)] -# Its row's right-click menu: Open in <that app> (⌘↓) and Open With ▸ the others. +# A file's path, line and “@path” prompt go into the added command and link; the app opens the file. +full = os.path.join(repo, CI) +assert opens('file ▾ › Check Agent', 'menuRun', 'openFile ' + CI + ' | Check Agent — Terminal') == \ + ['terminal %s %s check-agent --in %s %s' % (terminal, repo, sh(repo), sh(full))] +link = opens('file ▾ › Check Link', 'menuRun', 'openFile ' + CI + ' | Check Link — Link') +assert link == ['link kaerncheck://open?folder=%s&file=%s&line=16&q=%s' % (quoted, urllib.parse.quote(full, safe='/'), + urllib.parse.quote('@' + CI + ' ', safe='/'))], link +assert opens('file ▾ › Check App', 'menuRun', 'openFile ' + CI + ' | Check App') == ['com.apple.TextEdit ' + full] +# Its row's right-click menu: Open in <that app> (⌘↓) and Open With ▸ the others and the agents. row = menu_items('file', CI) open_in = next(i for i in row if i.get('title', '').startswith('Open in ')); assert open_in['key'] == '⌘↓', open_in -assert any(i.get('title') == 'Open With' and i.get('submenu') for i in row) == (len(editors) > 1 or info['claudeApp'] or info['claudeTerminal']) +with_menu = next(i for i in row if i.get('title') == 'Open With') +assert [s['title'] for s in with_menu['submenu'] if 'title' in s][-3:] == ['Check Agent', 'Check Link', 'Check App'], with_menu # All Files: each file's header has the button. k('review', 'all') @@ -164,12 +219,16 @@ def opens(label, *command): right = menu_items('commitFile', '1', path) assert any(i.get('title', '') == version['title'] for i in right), 'the commit file’s right-click menu has Open Version at…' -# Settings › General › Open in: another editor moves the button to it. -k('settings', 'General') -until(lambda d: window_open(d, ' General'), label='the Settings window on General') -snap('openin-settings', window='General') +# Settings › Open In: the editor, the terminal, and the list — Kaern's, then the added ones; + opens the sheet. +k('settings', 'Open In') +until(lambda d: window_open(d, 'Open In'), label='the Settings window on Open In') +snap('openin-settings', window='Open In') +k('openInSheet') +until(lambda d: window_open(d, 'SheetPresentationWindow'), label='the + sheet') +snap('openin-sheet', window='sheet Open In') k('settings', 'close') -until(lambda d: not window_open(d, ' General'), label='the Settings window closed') +until(lambda d: not window_open(d, 'Open In'), label='the Settings window closed') +# Another editor moves the button to it. if len(editors) > 1: other = editors[1] set_setting('KaernOpenEditor', other) From 8e1b8511f9c85d096c030379e84d7a50088552cd Mon Sep 17 00:00:00 2001 From: progresshans <progresshans@gmail.com> Date: Mon, 30 Nov 2026 02:56:19 +0900 Subject: [PATCH 08/13] =?UTF-8?q?fix:=20Settings=20=E2=80=BA=20Open=20In's?= =?UTF-8?q?=20checkboxes=20respond=20at=20once?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Each row of the list had a double-click gesture (to change an added one), and SwiftUI holds every click such a gesture covers until it knows no second click is coming: a checkbox in such a row changed 355 ms after the click, against 2 ms in a row without it (measured with the same rows put in a test instance's main window, whose clicks the debug driver can send). The double-click is now on an added one's name only, and a single click on the row selects it: the checkboxes change in 2 ms, a click beside the name selects in 1 ms, and a double-click on the name opens the sheet. Only a single click on an added one's name still waits for a possible second one before it selects. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- Kaern/Settings/OpenInPane.swift | 39 ++++++++++++++++++++------------- 1 file changed, 24 insertions(+), 15 deletions(-) diff --git a/Kaern/Settings/OpenInPane.swift b/Kaern/Settings/OpenInPane.swift index b2aea94..38a00ac 100644 --- a/Kaern/Settings/OpenInPane.swift +++ b/Kaern/Settings/OpenInPane.swift @@ -135,6 +135,16 @@ struct OpenInPane: View { let hidden = hiddenSet let shown = row.isLocked || !hidden.contains(row.id) let isSelected = row.isAdded && selection == row.id + let names = HStack(spacing: z(8)) { + Text(row.name) + .font(.system(size: z(13))) + .foregroundStyle(isSelected ? Color.white : (shown ? K.label : K.label2)) + if let note = row.note { + Text(note) + .font(.system(size: z(11))) + .foregroundStyle(isSelected ? Color.white.opacity(0.8) : K.label2) + } + } return HStack(spacing: z(8)) { Toggle("Show \(row.name) in the Open menus", isOn: Binding(get: { shown }, set: { setHidden(row.id, !$0) })) .toggleStyle(.checkbox) @@ -143,13 +153,12 @@ struct OpenInPane: View { Image(nsImage: row.icon) .resizable() .frame(width: z(16), height: z(16)) - Text(row.name) - .font(.system(size: z(13))) - .foregroundStyle(isSelected ? Color.white : (shown ? K.label : K.label2)) - if let note = row.note { - Text(note) - .font(.system(size: z(11))) - .foregroundStyle(isSelected ? Color.white.opacity(0.8) : K.label2) + // A double-click on an added one's name changes it. Only there: a double-click gesture holds each click + // it covers until it knows no second one comes (~350 ms), and over the whole row it held the checkbox's. + if row.isAdded { + names.onTapGesture(count: 2) { edit(row.id) } + } else { + names } Spacer(minLength: z(8)) if let detail = row.detail { @@ -163,17 +172,17 @@ struct OpenInPane: View { .frame(height: z(26)) .background(isSelected ? K.sel : (index % 2 == 1 ? K.alt : Color.clear)) .contentShape(Rectangle()) - .onTapGesture(count: 2) { - if row.isAdded, let agent = OpenAgents.custom.first(where: { $0.id == row.id }) { - selection = row.id - editing = Editing(agent: agent, isNew: false) - } - } - .simultaneousGesture(TapGesture().onEnded { selection = row.isAdded ? row.id : nil }) + .onTapGesture { selection = row.isAdded ? row.id : nil } + } + + private func edit(_ id: String) { + guard let agent = OpenAgents.custom.first(where: { $0.id == id }) else { return } + selection = id + editing = Editing(agent: agent, isNew: false) } private var hint: String { - var text = "Untick one to leave it out of the Open menus; the default editor stays. + adds an app, a command for your terminal or a link — for an agent or an app Kaern doesn’t know. Double-click one you added to change it." + var text = "Untick one to leave it out of the Open menus; the default editor stays. + adds an app, a command for your terminal or a link — for an agent or an app Kaern doesn’t know. Double-click the name of one you added to change it." let missing = OpenAgents.missing if !missing.isEmpty { let names = missing.count == 1 ? missing[0] : missing.dropLast().joined(separator: ", ") + " and " + missing[missing.count - 1] From ee3d8dfc27348e2e01c8c386b69d94b9ff38aebb Mon Sep 17 00:00:00 2001 From: progresshans <progresshans@gmail.com> Date: Mon, 30 Nov 2026 03:08:25 +0900 Subject: [PATCH 09/13] =?UTF-8?q?fix:=20Settings=20=E2=80=BA=20Open=20In's?= =?UTF-8?q?=20list=20selects=20and=20edits=20at=20a=20click,=20with=20+=20?= =?UTF-8?q?and=20=E2=88=92=20in=20its=20strip?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit After 8e1b851 an added one waited ~350 ms after a click on its name before it was selected (the name's double-click gesture held the click), and a double-click changed it only when it landed on the name itself. The list is now the system's (a List with selection, a table underneath): a click selects an added one at once, a double-click anywhere on its row or its right-click menu's Edit… changes it, and Remove takes it away; the table tells a double-click from a click without holding either, and no gesture lies over the checkboxes. + and − sit in a strip along the box's bottom, as in the mock-up and System Settings' lists, instead of two buttons stuck together under it, and the list is tall enough for about 15 rows before it scrolls. A test instance can't time the table's clicks: the debug driver's clicks don't reach a table in a window that isn't in front. t_openin passed in light and dark. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- Kaern/Settings/OpenInPane.swift | 186 ++++++++++++++++++---------- Kaern/Settings/SettingsWindow.swift | 2 +- 2 files changed, 121 insertions(+), 67 deletions(-) diff --git a/Kaern/Settings/OpenInPane.swift b/Kaern/Settings/OpenInPane.swift index 38a00ac..d11d55c 100644 --- a/Kaern/Settings/OpenInPane.swift +++ b/Kaern/Settings/OpenInPane.swift @@ -52,11 +52,6 @@ struct OpenInPane: View { } SettingsRow(label: "Open menus:") { list - HStack(spacing: 0) { - SmallSquareButton(title: "+", label: "Add an app, a command or a link") { add() } - SmallSquareButton(title: "−", label: "Remove the selected one") { remove() } - .disabled(selection == nil) - } Hint(hint) } } @@ -97,82 +92,84 @@ struct OpenInPane: View { } } + /// The list in a box with its + and − strip at the bottom. It's a list of the system's (a table underneath): a click + /// selects one added here at once, a double-click changes it, and the checkboxes answer at once — SwiftUI's own + /// double-click gesture held every click it covered for ~350 ms, in case a second one came. private var list: some View { let editors = editorRows let agents = agentRows + let hidden = hiddenSet let groups = (editors.isEmpty ? 0 : 1) + (agents.isEmpty ? 0 : 1) - let height = CGFloat(editors.count + agents.count) * z(26) + CGFloat(groups) * z(24) + z(6) - return ScrollView { - VStack(alignment: .leading, spacing: 0) { + // Tall enough for all of it up to about 15 rows (no scroller to make room for), then it scrolls. + let height = CGFloat(editors.count + agents.count) * z(26) + CGFloat(groups) * z(28) + z(14) + return VStack(spacing: 0) { + List(selection: $selection) { if !editors.isEmpty { - group("EDITORS") - ForEach(Array(editors.enumerated()), id: \.element.id) { index, row in line(row, index) } + Section { + ForEach(editors) { row in line(row, hidden) } + } header: { + groupTitle("Editors") + } } if !agents.isEmpty { - group("AGENTS") - ForEach(Array(agents.enumerated()), id: \.element.id) { index, row in line(row, index) } + Section { + ForEach(agents) { row in line(row, hidden) } + } header: { + groupTitle("Agents") + } } } - .padding(.bottom, z(6)) + .listStyle(.plain) + .alternatingRowBackgrounds() + .environment(\.defaultMinListRowHeight, z(26)) + .contextMenu(forSelectionType: String.self) { ids in + if let id = ids.first, isAdded(id) { + Button("Edit…") { edit(id) } + Button("Remove") { remove(id) } + } + } primaryAction: { ids in + if let id = ids.first { edit(id) } + } + .frame(height: min(height, z(470))) + footer } - .frame(width: z(470), height: min(height, z(400))) - .background(RoundedRectangle(cornerRadius: z(8), style: .continuous).fill(K.field)) + .frame(width: z(470)) + .background(K.field) .clipShape(RoundedRectangle(cornerRadius: z(8), style: .continuous)) .overlay(RoundedRectangle(cornerRadius: z(8), style: .continuous).strokeBorder(K.sepStrong, lineWidth: 0.5)) } - private func group(_ title: String) -> some View { - Text(title) + private func line(_ row: Row, _ hidden: Set<String>) -> some View { + OpenInRow(row: row, isShown: row.isLocked || !hidden.contains(row.id)) { setHidden(row.id, !$0) } + .tag(row.id) + .selectionDisabled(!row.isAdded) + } + + private func groupTitle(_ title: String) -> some View { + Text(title.uppercased()) .font(.system(size: z(10.5), weight: .semibold)) .tracking(0.4) .foregroundStyle(K.label2) - .frame(height: z(24), alignment: .bottomLeading) - .padding(.leading, z(10)) - .padding(.bottom, z(2)) } - private func line(_ row: Row, _ index: Int) -> some View { - let hidden = hiddenSet - let shown = row.isLocked || !hidden.contains(row.id) - let isSelected = row.isAdded && selection == row.id - let names = HStack(spacing: z(8)) { - Text(row.name) - .font(.system(size: z(13))) - .foregroundStyle(isSelected ? Color.white : (shown ? K.label : K.label2)) - if let note = row.note { - Text(note) - .font(.system(size: z(11))) - .foregroundStyle(isSelected ? Color.white.opacity(0.8) : K.label2) - } - } - return HStack(spacing: z(8)) { - Toggle("Show \(row.name) in the Open menus", isOn: Binding(get: { shown }, set: { setHidden(row.id, !$0) })) - .toggleStyle(.checkbox) - .labelsHidden() - .disabled(row.isLocked) - Image(nsImage: row.icon) - .resizable() - .frame(width: z(16), height: z(16)) - // A double-click on an added one's name changes it. Only there: a double-click gesture holds each click - // it covers until it knows no second one comes (~350 ms), and over the whole row it held the checkbox's. - if row.isAdded { - names.onTapGesture(count: 2) { edit(row.id) } - } else { - names - } - Spacer(minLength: z(8)) - if let detail = row.detail { - Text(detail) - .font(.system(size: z(11), weight: row.isAdded ? .semibold : .regular)) - .foregroundStyle(isSelected ? Color.white.opacity(0.85) : (row.isAdded ? K.accentText : K.label2)) - } + /// `+` and `−` in a strip along the box's bottom, as System Settings' lists have them. + private var footer: some View { + HStack(spacing: 0) { + FooterButton(symbol: "plus", label: "Add an app, a command or a link") { add() } + Divider().frame(height: z(14)) + FooterButton(symbol: "minus", label: "Remove the selected one") { if let selection { remove(selection) } } + .disabled(!(selection.map(isAdded) ?? false)) + Divider().frame(height: z(14)) + Spacer(minLength: 0) } - .lineLimit(1) - .padding(.horizontal, z(10)) .frame(height: z(26)) - .background(isSelected ? K.sel : (index % 2 == 1 ? K.alt : Color.clear)) - .contentShape(Rectangle()) - .onTapGesture { selection = row.isAdded ? row.id : nil } + .background(K.alt) + .overlay(alignment: .top) { K.sep.frame(height: 1) } + } + + private func isAdded(_ id: String) -> Bool { + _ = customText + return OpenAgents.custom.contains { $0.id == id } } private func edit(_ id: String) { @@ -182,7 +179,7 @@ struct OpenInPane: View { } private var hint: String { - var text = "Untick one to leave it out of the Open menus; the default editor stays. + adds an app, a command for your terminal or a link — for an agent or an app Kaern doesn’t know. Double-click the name of one you added to change it." + var text = "Untick one to leave it out of the Open menus; the default editor stays. + adds an app, a command for your terminal or a link — for an agent or an app Kaern doesn’t know. Double-click one you added to change it." let missing = OpenAgents.missing if !missing.isEmpty { let names = missing.count == 1 ? missing[0] : missing.dropLast().joined(separator: ", ") + " and " + missing[missing.count - 1] @@ -215,11 +212,10 @@ struct OpenInPane: View { selection = agent.id } - private func remove() { - guard let selection else { return } - OpenAgents.custom = OpenAgents.custom.filter { $0.id != selection } - setHidden(selection, false) - self.selection = nil + private func remove(_ id: String) { + OpenAgents.custom = OpenAgents.custom.filter { $0.id != id } + setHidden(id, false) + if selection == id { selection = nil } } private func takeAddRequest() { @@ -227,6 +223,63 @@ struct OpenInPane: View { SettingsRouter.shared.addsOpenItem = false add() } + + /// One row: shown in the menus or not, the icon, the name and how it opens, and at the right "Default", a command or + /// "Added". Selected (an added one), its text turns white with the row. + private struct OpenInRow: View { + let row: Row + let isShown: Bool + let setShown: (Bool) -> Void + @Environment(\.backgroundProminence) private var prominence + + var body: some View { + let selected = prominence == .increased + HStack(spacing: z(8)) { + Toggle("Show \(row.name) in the Open menus", isOn: Binding(get: { isShown }, set: setShown)) + .toggleStyle(.checkbox) + .labelsHidden() + .disabled(row.isLocked) + Image(nsImage: row.icon) + .resizable() + .frame(width: z(16), height: z(16)) + Text(row.name) + .font(.system(size: z(13))) + .foregroundStyle(isShown || selected ? AnyShapeStyle(.primary) : AnyShapeStyle(.secondary)) + if let note = row.note { + Text(note) + .font(.system(size: z(11))) + .foregroundStyle(.secondary) + } + Spacer(minLength: z(8)) + if let detail = row.detail { + Text(detail) + .font(.system(size: z(11), weight: row.isAdded ? .semibold : .regular)) + .foregroundStyle(row.isAdded && !selected ? AnyShapeStyle(K.accentText) : AnyShapeStyle(.secondary)) + } + } + .lineLimit(1) + } + } +} + +/// `+` or `−` in the strip under a list. +private struct FooterButton: View { + let symbol: String + let label: String + let action: () -> Void + @Environment(\.isEnabled) private var isEnabled + + var body: some View { + Button(action: action) { + Image(systemName: symbol) + .font(.system(size: z(11), weight: .semibold)) + .frame(width: z(28), height: z(26)) + .contentShape(Rectangle()) + } + .buttonStyle(.plain) + .foregroundStyle(isEnabled ? K.label : K.label3) + .accessibilityLabel(label) + } } /// Add to the Open Menus, or change one added before: its name; how it opens — an app, a command in the terminal, a @@ -373,3 +426,4 @@ struct OpenItemSheet: View { return result } } + diff --git a/Kaern/Settings/SettingsWindow.swift b/Kaern/Settings/SettingsWindow.swift index a0d8be3..6ceb8b0 100644 --- a/Kaern/Settings/SettingsWindow.swift +++ b/Kaern/Settings/SettingsWindow.swift @@ -654,7 +654,7 @@ private struct AccountsPane: View { } /// `.apm button`: + and − under a list. -struct SmallSquareButton: View { +private struct SmallSquareButton: View { let title: String let label: String let action: () -> Void From 32275f8e6c82ee16f82ac561214d28ab6c243cc3 Mon Sep 17 00:00:00 2001 From: progresshans <progresshans@gmail.com> Date: Mon, 30 Nov 2026 03:22:42 +0900 Subject: [PATCH 10/13] fix: what a read-through of the Open work turned up MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Settings › Open In fits a small screen: the list is as tall as the screen leaves room for (some 450 pt go to the rest of the window), so the window doesn't run past the bottom of a 1280×800 display; the list scrolls there. - Delete removes the added one selected, as in other lists, and a built-in one's right-click menu has Leave Out of / Show in the Open Menus (not an empty menu). - The + sheet takes a link only when it makes a URL with a place in it (a space in it, for one, didn't, and the item did nothing). - {folder}, {file}, {line} and {prompt} are replaced in one pass: a folder named "{file}" no longer has its name replaced too. - An added app is off in a file's menus when the file is neither on disk nor a commit's (it had nothing to open). - The hint under Terminal says Claude Code's own link picks its terminal itself (it does: its handler is claude). - The link handler cache keeps "no app" too (assigning nil to it forgot the scheme), comments no longer say Settings › General or Claude Code where they mean Open In and the agents, and MenuAction's `visible`, unused since the agents' submenu replaced the two Claude Code items, goes. The checks for every area the branch touches (53) passed, then t_openin (light and dark) and t_quickopen again on this; the Release build compiles. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- Kaern/App/MainMenu.swift | 11 +++------ Kaern/App/OpenAgents.swift | 31 ++++++++++++++++++------- Kaern/Settings/OpenInPane.swift | 29 +++++++++++++++++------ Kaern/Views/Menus/OpenMenus.swift | 7 ++++-- Kaern/Views/Review/FileOpenButton.swift | 4 ++-- Kaern/Views/TabBar/TabBar.swift | 2 +- Kaern/Views/Toolbar/MainToolbar.swift | 4 ++-- checks/t_openin.py | 3 ++- 8 files changed, 60 insertions(+), 31 deletions(-) diff --git a/Kaern/App/MainMenu.swift b/Kaern/App/MainMenu.swift index 95f0af2..f834d5f 100644 --- a/Kaern/App/MainMenu.swift +++ b/Kaern/App/MainMenu.swift @@ -586,24 +586,20 @@ final class MenuAction: NSObject, NSMenuItemValidation { private let isAvailable: () -> Bool private let isChecked: (() -> Bool)? private let currentTitle: (() -> String)? - private let isVisible: (() -> Bool)? - private init(run: @escaping () -> Void, isAvailable: @escaping () -> Bool, isChecked: (() -> Bool)?, title: (() -> String)?, - visible: (() -> Bool)?) { + private init(run: @escaping () -> Void, isAvailable: @escaping () -> Bool, isChecked: (() -> Bool)?, title: (() -> String)?) { self.run = run self.isAvailable = isAvailable self.isChecked = isChecked self.currentTitle = title - self.isVisible = visible super.init() } /// `title`: when set, the item's title is updated each time it's validated ("Undo Checkout develop"). - /// `visible`: when set, the item is hidden while it's false (Open in Claude Code without the Claude app). static func item(_ title: String, key: String = "", modifiers: NSEvent.ModifierFlags = [.command], enabled: @escaping () -> Bool = { true }, checked: (() -> Bool)? = nil, title currentTitle: (() -> String)? = nil, - visible: (() -> Bool)? = nil, run: @escaping () -> Void) -> NSMenuItem { - let action = MenuAction(run: run, isAvailable: enabled, isChecked: checked, title: currentTitle, visible: visible) + run: @escaping () -> Void) -> NSMenuItem { + let action = MenuAction(run: run, isAvailable: enabled, isChecked: checked, title: currentTitle) // AppKit spells Shift with a letter as the uppercase letter (⇧⌘T is "T" with ⌘). var key = key var modifiers = modifiers @@ -625,7 +621,6 @@ final class MenuAction: NSObject, NSMenuItemValidation { func validateMenuItem(_ menuItem: NSMenuItem) -> Bool { if let isChecked { menuItem.state = isChecked() ? .on : .off } if let currentTitle { menuItem.title = currentTitle() } - if let isVisible { menuItem.isHidden = !isVisible() } return isAvailable() } } diff --git a/Kaern/App/OpenAgents.swift b/Kaern/App/OpenAgents.swift index 82174f2..7f90ffe 100644 --- a/Kaern/App/OpenAgents.swift +++ b/Kaern/App/OpenAgents.swift @@ -138,7 +138,7 @@ enum OpenAgents { guard let link = agent.link, let scheme = link.range(of: "://").map({ String(link[..<$0.lowerBound]) }), !scheme.isEmpty else { return nil } if let known = handlers[scheme] { return known } let app = URL(string: scheme + "://").flatMap { NSWorkspace.shared.urlForApplication(toOpen: $0) } - handlers[scheme] = app + handlers.updateValue(app, forKey: scheme) // nil too: no app takes it (`handlers[scheme] = nil` would forget it) return app } @@ -204,10 +204,7 @@ enum OpenAgents { static func link(_ template: String, _ place: Place) -> URL? { let values = ["folder": place.folder, "file": place.file ?? "", "line": place.line.map(String.init) ?? "", "prompt": place.path.map(OpenIn.mention) ?? ""] - var text = template - for (key, value) in values { - text = text.replacingOccurrences(of: "{\(key)}", with: value.addingPercentEncoding(withAllowedCharacters: .linkValue) ?? "") - } + var text = substitute(template, values.mapValues { $0.addingPercentEncoding(withAllowedCharacters: .linkValue) ?? "" }) if let mark = text.firstIndex(of: "?") { let items = text[text.index(after: mark)...].split(separator: "&").filter { !$0.isEmpty && !$0.hasSuffix("=") } text = String(text[..<mark]) + (items.isEmpty ? "" : "?" + items.joined(separator: "&")) @@ -217,9 +214,27 @@ enum OpenAgents { /// A command with the place in it, each value quoted for the shell (nothing for a file in a repository's menu). static func filled(_ command: String, _ place: Place) -> String { - command.replacingOccurrences(of: "{folder}", with: TerminalCommands.quoted(place.folder)) - .replacingOccurrences(of: "{file}", with: place.file.map(TerminalCommands.quoted) ?? "") - .replacingOccurrences(of: "{line}", with: place.line.map(String.init) ?? "") + substitute(command, ["folder": TerminalCommands.quoted(place.folder), "file": place.file.map(TerminalCommands.quoted) ?? "", + "line": place.line.map(String.init) ?? ""]) + } + + /// `template` with each `{name}` of `values` replaced, in one pass: a value with such a name in it (a folder named + /// "{file}") stays as it is. Other braces stay too. + private static func substitute(_ template: String, _ values: [String: String]) -> String { + var result = "" + var rest = template[...] + while let open = rest.firstIndex(of: "{") { + result += rest[..<open] + let after = rest.index(after: open) + if let close = rest[after...].firstIndex(of: "}"), let value = values[String(rest[after..<close])] { + result += value + rest = rest[rest.index(after: close)...] + } else { + result += "{" + rest = rest[after...] + } + } + return result + rest } } diff --git a/Kaern/Settings/OpenInPane.swift b/Kaern/Settings/OpenInPane.swift index d11d55c..915a669 100644 --- a/Kaern/Settings/OpenInPane.swift +++ b/Kaern/Settings/OpenInPane.swift @@ -48,7 +48,7 @@ struct OpenInPane: View { } .labelsHidden() .fixedSize() - Hint("The toolbar’s Open button opens a repository in the editor (⌥E), and Review’s opens a file there at its first change (⌘↓). ⌥O opens the repository in Finder and ⌥T in the terminal, where the agents’ commands run too.") + Hint("The toolbar’s Open button opens a repository in the editor (⌥E), and Review’s opens a file there at its first change (⌘↓). ⌥O opens the repository in Finder and ⌥T in the terminal, where agents’ commands run too — Claude Code’s own link picks its terminal itself.") } SettingsRow(label: "Open menus:") { list @@ -100,8 +100,11 @@ struct OpenInPane: View { let agents = agentRows let hidden = hiddenSet let groups = (editors.isEmpty ? 0 : 1) + (agents.isEmpty ? 0 : 1) - // Tall enough for all of it up to about 15 rows (no scroller to make room for), then it scrolls. + // Tall enough for all of it up to about 15 rows (no scroller to make room for), then it scrolls; shorter on a + // small screen, where the window around it (some 450 pt more) would run past the screen's bottom. let height = CGFloat(editors.count + agents.count) * z(26) + CGFloat(groups) * z(28) + z(14) + let room = (NSScreen.main?.visibleFrame.height ?? 900) - z(450) + let tallest = max(z(180), min(z(470), room)) return VStack(spacing: 0) { List(selection: $selection) { if !editors.isEmpty { @@ -123,14 +126,22 @@ struct OpenInPane: View { .alternatingRowBackgrounds() .environment(\.defaultMinListRowHeight, z(26)) .contextMenu(forSelectionType: String.self) { ids in - if let id = ids.first, isAdded(id) { - Button("Edit…") { edit(id) } - Button("Remove") { remove(id) } + if let id = ids.first { + if isAdded(id) { + Button("Edit…") { edit(id) } + Button("Remove") { remove(id) } + } else { + let isHidden = hidden.contains(id) + Button(isHidden ? "Show in the Open Menus" : "Leave Out of the Open Menus") { setHidden(id, !isHidden) } + .disabled(id == OpenIn.editor(chosen: editorID)?.id) + } } } primaryAction: { ids in if let id = ids.first { edit(id) } } - .frame(height: min(height, z(470))) + // Delete takes away the added one selected, as in other lists. + .onDeleteCommand { if let selection, isAdded(selection) { remove(selection) } } + .frame(height: min(height, tallest)) footer } .frame(width: z(470)) @@ -412,7 +423,11 @@ struct OpenItemSheet: View { switch agent.way { case .app: return agent.app != nil case .terminal: return !(agent.command ?? "").trimmingCharacters(in: .whitespaces).isEmpty - case .link: return (agent.link ?? "").contains("://") + case .link: + // A link that makes a URL once a place is in it (a space in it, for one, doesn't). + let template = agent.link?.trimmingCharacters(in: .whitespaces) ?? "" + return template.contains("://") + && OpenAgents.link(template, OpenAgents.Place(folder: "/folder", file: "/folder/file", path: "file", line: 1)) != nil } } diff --git a/Kaern/Views/Menus/OpenMenus.swift b/Kaern/Views/Menus/OpenMenus.swift index 99ed3b0..3d46920 100644 --- a/Kaern/Views/Menus/OpenMenus.swift +++ b/Kaern/Views/Menus/OpenMenus.swift @@ -159,8 +159,11 @@ extension ContextMenus { /// The agents' rows (`OpenAgents`), each with how it opens after its name ("Claude app", "Terminal"): the /// repository, or `file` — which Claude Code and Codex find named in their prompt, waiting to be sent. static func agentItems(_ r: RepositoryModel, file: FileOpening? = nil) -> [NSMenuItem] { - OpenAgents.shown(forFiles: file != nil).map { agent in - let menuItem = noted(item(agent.name) { r.open(file, inAgent: agent) }, OpenAgents.note(agent)) + // An app opens the file on disk or its commit's version: without either, it has nothing to open. + let reachable = file.map { r.existingFile($0.path) != nil || $0.version != nil } ?? true + return OpenAgents.shown(forFiles: file != nil).map { agent in + let menuItem = noted(item(agent.name, enabled: agent.way != .app || reachable) { r.open(file, inAgent: agent) }, + OpenAgents.note(agent)) return showIcon(menuItem, OpenAgents.icon(agent, 16)) } } diff --git a/Kaern/Views/Review/FileOpenButton.swift b/Kaern/Views/Review/FileOpenButton.swift index ab126b0..b1e55f0 100644 --- a/Kaern/Views/Review/FileOpenButton.swift +++ b/Kaern/Views/Review/FileOpenButton.swift @@ -2,7 +2,7 @@ import AppKit import SwiftUI /// A file's Open button (ScreenOpenIn: Review's header, All Files' file headers): the app the file opens in, shown by -/// its icon, opens it at its first change; ▾ lists the other apps, Claude Code, Open Version at… and Finder. A file +/// its icon, opens it at its first change; ▾ lists the other apps, the agents, Open Version at… and Finder. A file /// that isn't on disk opens the commit's version Review shows, or nothing. struct FileOpenButton: View { let repository: RepositoryModel @@ -11,7 +11,7 @@ struct FileOpenButton: View { let subtitle: String /// The key that opens it too, for its tooltip (⌘↓ for the file Review shows on its own). var shortcut: String? - /// Settings › General's editor: the button follows it. + /// Settings › Open In's editor: the button follows it. @AppStorage(SettingsKey.openEditor, store: .kaern) private var editorID = "" @State private var hovering = false @State private var menuHovering = false diff --git a/Kaern/Views/TabBar/TabBar.swift b/Kaern/Views/TabBar/TabBar.swift index 92487e3..d75ec0e 100644 --- a/Kaern/Views/TabBar/TabBar.swift +++ b/Kaern/Views/TabBar/TabBar.swift @@ -374,7 +374,7 @@ struct TabBar: View { } /// A repository's Open items in a right-click menu (a tab, the repository list): the editor, Finder, the terminal, -/// Claude Code as far as it's set up, Copy Path. +/// the agents the Open menus list, Copy Path. struct OpenInButtons: View { let path: String diff --git a/Kaern/Views/Toolbar/MainToolbar.swift b/Kaern/Views/Toolbar/MainToolbar.swift index 7bc9ebc..60050b3 100644 --- a/Kaern/Views/Toolbar/MainToolbar.swift +++ b/Kaern/Views/Toolbar/MainToolbar.swift @@ -228,10 +228,10 @@ private struct PullMenu: View { } /// Open (ScreenOpenIn): the repository in the default editor, which the button shows by its icon (Finder's when no -/// editor is installed); ▾ for the other editors, Claude Code, Finder and the terminal. +/// editor is installed); ▾ for the other editors, the agents, Finder and the terminal. private struct OpenInButton: View { let repository: RepositoryModel - /// Settings › General's editor: the button follows it. + /// Settings › Open In's editor: the button follows it. @AppStorage(SettingsKey.openEditor, store: .kaern) private var editorID = "" @Environment(\.toolbarShowsText) private var showsText @State private var hovering = false diff --git a/checks/t_openin.py b/checks/t_openin.py index dd54b87..d61685b 100644 --- a/checks/t_openin.py +++ b/checks/t_openin.py @@ -223,8 +223,9 @@ def opens(label, *command): k('settings', 'Open In') until(lambda d: window_open(d, 'Open In'), label='the Settings window on Open In') snap('openin-settings', window='Open In') +before = len(full_dump()['driver']['visibleWindows']) k('openInSheet') -until(lambda d: window_open(d, 'SheetPresentationWindow'), label='the + sheet') +until(lambda d: len(d['driver']['visibleWindows']) > before, label='the + sheet') snap('openin-sheet', window='sheet Open In') k('settings', 'close') until(lambda d: not window_open(d, 'Open In'), label='the Settings window closed') From 790e68ab371c3c1f5366ae95f888408ef5d547dd Mon Sep 17 00:00:00 2001 From: progresshans <progresshans@gmail.com> Date: Mon, 30 Nov 2026 03:43:25 +0900 Subject: [PATCH 11/13] =?UTF-8?q?fix:=20Settings=20=E2=80=BA=20Open=20In's?= =?UTF-8?q?=20rows=20build=20their=20checkbox=20binding=20from=20Sendable?= =?UTF-8?q?=20values?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A row's checkbox passed the row's stored setter (a non-Sendable function value) to Binding, which now takes @Sendable closures: "converting non-Sendable function value … may introduce data races". The pane builds the binding itself from the row's id and a Bool, and the row takes it as a @Binding. Every Swift file the branch changed, compiled again in Debug and Release, gives no warning now; t_openin passed in light and dark. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- Kaern/Settings/OpenInPane.swift | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/Kaern/Settings/OpenInPane.swift b/Kaern/Settings/OpenInPane.swift index 915a669..a0fac8e 100644 --- a/Kaern/Settings/OpenInPane.swift +++ b/Kaern/Settings/OpenInPane.swift @@ -151,8 +151,11 @@ struct OpenInPane: View { } private func line(_ row: Row, _ hidden: Set<String>) -> some View { - OpenInRow(row: row, isShown: row.isLocked || !hidden.contains(row.id)) { setHidden(row.id, !$0) } - .tag(row.id) + // The binding's closures hold only Sendable values (the id, a Bool), not the row with its icon. + let id = row.id + let shown = row.isLocked || !hidden.contains(id) + return OpenInRow(row: row, isShown: Binding(get: { shown }, set: { setHidden(id, !$0) })) + .tag(id) .selectionDisabled(!row.isAdded) } @@ -239,14 +242,13 @@ struct OpenInPane: View { /// "Added". Selected (an added one), its text turns white with the row. private struct OpenInRow: View { let row: Row - let isShown: Bool - let setShown: (Bool) -> Void + @Binding var isShown: Bool @Environment(\.backgroundProminence) private var prominence var body: some View { let selected = prominence == .increased HStack(spacing: z(8)) { - Toggle("Show \(row.name) in the Open menus", isOn: Binding(get: { isShown }, set: setShown)) + Toggle("Show \(row.name) in the Open menus", isOn: $isShown) .toggleStyle(.checkbox) .labelsHidden() .disabled(row.isLocked) From 8b757cfba49739600e721115f31642e8604b8af2 Mon Sep 17 00:00:00 2001 From: progresshans <progresshans@gmail.com> Date: Mon, 30 Nov 2026 13:31:29 +0900 Subject: [PATCH 12/13] fix: a file a commit deleted opens and blames as it was before, from its right-click menu MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The right-click menu of a commit's file (the commit's details, Review's chips and headers) used Review's way of opening it only when Review's version was the commit's own. A file the commit deleted has none there: Review opens it at the parent. So the menu fell back to the commit's version, which has no such file, and Open Version at… and Open in… (with the file gone from disk too) ended in "Couldn't read … at <commit>", while Review's ▾ opened it. Now which commit Review shows decides (the selection, or a compare's target); while Review shows something else, a file the selected commit deleted (its details say so) opens at the parent. Blame at… in the same menu blamed the file at the commit, where it isn't, and showed an empty blame (also before this branch). It now blames the version the menu opens: Blame at <parent>. Codex's review of PR 9 found the first. t_openin now deletes a file in a commit and checks the menu's Open Version at…, Open in… and Blame at…, with Review on that commit and on a compare with the working copy; it passed. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- CHANGELOG.md | 2 ++ Kaern/App/OpenIn.swift | 14 ++++++++ Kaern/Views/Menus/ContextMenus.swift | 10 +++--- checks/t_openin.py | 52 ++++++++++++++++++++++++---- 4 files changed, 66 insertions(+), 12 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b83a51b..f6c5889 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -39,6 +39,8 @@ What changed in each version of Kaern. A version's section is what its update wi the submodule out, as it does with `ignore = all`. It read "?" before. - Quick Look opened again right after closing it (Space twice in a row) stays open. Before, it closed again at once. +- Blame on a file that a commit deleted, from that commit's right-click menu, shows the file as it was before the + commit. It showed an empty blame. ## [1.0.1] - 2026-11-19 diff --git a/Kaern/App/OpenIn.swift b/Kaern/App/OpenIn.swift index 919fb93..2f0ed1b 100644 --- a/Kaern/App/OpenIn.swift +++ b/Kaern/App/OpenIn.swift @@ -288,6 +288,20 @@ extension RepositoryModel { reviewFiles?.first { $0.path == path }?.opening ?? FileOpening(path: path) } + /// A commit's file as its right-click menu opens and blames it (the commit's details, Review's chips and headers): + /// the way Review does while Review shows that commit — at the first change, and a file the commit deleted as it was + /// before — and otherwise at the commit's version, or for a file it deleted, at its parent's. Which commit Review + /// shows decides it, not the version: a deleted file's version is the parent's. + func commitFileOpening(_ path: String, commit: String) -> FileOpening { + let reviewShows = review?.compare.map { $0.target == commit } ?? (selectedCommitID == commit) + if reviewShows, let file = reviewFiles?.first(where: { $0.path == path }) { return file.opening } + if selectedCommitID == commit, selectedFiles.first(where: { $0.path == path })?.kind == .deleted, + let parent = self.commit(commit)?.parents.first { + return FileOpening(path: path, version: (parent, path)) + } + return FileOpening(path: path, version: (commit, path)) + } + /// What a file's Open menu says Review shows of it: "uncommitted", "staged", "in e7b7dd2". func openSubtitle(_ file: ReviewFile?) -> String { if let compare = review?.compare { diff --git a/Kaern/Views/Menus/ContextMenus.swift b/Kaern/Views/Menus/ContextMenus.swift index 7cfa5ef..332d863 100644 --- a/Kaern/Views/Menus/ContextMenus.swift +++ b/Kaern/Views/Menus/ContextMenus.swift @@ -487,19 +487,19 @@ enum ContextMenus { return menu } - /// A file in a commit's details: its history from there, blame as of that commit. + /// A file in a commit's details: its history from there, blame as of that commit, and the ways to open it. A file + /// the commit deleted is blamed and opened as it was before, in the parent (`commitFileOpening`). static func commitFileMenu(_ path: String, commit: String, _ r: RepositoryModel) -> NSMenu? { let menu = NSMenu(title: path) menu.autoenablesItems = false let name = (path as NSString).lastPathComponent let directory = (path as NSString).deletingLastPathComponent + let opening = r.commitFileOpening(path, commit: commit) + let version = opening.version ?? (commit, path) menu.addItem(header(name, (directory.isEmpty ? "" : directory + "/ · ") + "in \(String(commit.prefix(7)))")) menu.addItem(item("Show File History") { r.showFileHistory(path, at: commit) }) - menu.addItem(item("Blame at \(String(commit.prefix(7)))") { r.showBlame(path, at: commit) }) + menu.addItem(item("Blame at \(String(version.commit.prefix(7)))") { r.showBlame(version.path, at: version.commit) }) menu.addItem(.separator()) - // Review's version of it when this commit is what Review shows; this commit's otherwise. - var opening = r.fileOpening(path) - if opening.version?.commit != commit { opening = FileOpening(path: path, version: (commit, path)) } openItems(opening, r).forEach(menu.addItem) let file = r.existingFile(path) menu.addItem(item("Show in Finder", enabled: file != nil) { if let file { OpenIn.reveal(file) } }) diff --git a/checks/t_openin.py b/checks/t_openin.py index d61685b..6aac851 100644 --- a/checks/t_openin.py +++ b/checks/t_openin.py @@ -1,7 +1,8 @@ """t_openin.py [light|dark] — Open (ScreenOpenIn). The toolbar's Open button opens the repository in the default editor (Finder when none is installed), and its ▾ lists the editors, the agents (Claude Code, Codex… as installed), Finder and the terminal; ⌥E ⌥O ⌥T do the same, but not while text is typed. Review's Open button opens a file at its first change -(so does ⌘↓), and for a commit's file its ▾ has Open Version at…, a read-only copy of that version. Settings › Open In +(so does ⌘↓), and for a commit's file its ▾ has Open Version at…, a read-only copy of that version (for a file the +commit deleted, the version before, which its right-click menu also blames). Settings › Open In picks the editor, leaves editors and agents out of the menus, and adds apps, commands and links (Customize Menu…). A test instance opens nothing: it notes what it would have opened (the dump's `opened`). What is installed differs from @@ -58,6 +59,16 @@ def opens(label, *command): return opened(d) +def copied(done, commit, path): + """The read-only copy that Open Version at… opened: named after `commit`, with `path` as it is there.""" + copy = done[0].split(' ', 1)[1] + if copy.rsplit(':', 1)[-1].isdigit(): copy = copy.rsplit(':', 1)[0] + name, ext = os.path.splitext(os.path.basename(path)) + assert os.path.basename(copy) == '%s (%s)%s' % (name, commit[:7], ext), copy + assert os.stat(copy).st_mode & (stat.S_IWUSR | stat.S_IWGRP | stat.S_IWOTH) == 0, 'the copy can be written to' + with open(copy) as f: assert f.read().strip() == git('show', '%s:%s' % (commit, path)), 'the copy is not that version' + + launch_prepared(mode) show_tab('powerlens') repo = os.path.realpath(PL) @@ -210,15 +221,42 @@ def opens(label, *command): str(sum(frame('openFileMenu')[1:4:2]) + 4), 'right') done = opens('Open Version at ' + short, 'menuRun', 'openFile ' + path + ' | ' + version['title']) print('version:', done) -copy = done[0].split(' ', 1)[1] -if copy.rsplit(':', 1)[-1].isdigit(): copy = copy.rsplit(':', 1)[0] -name, ext = os.path.splitext(os.path.basename(path)) -assert os.path.basename(copy) == '%s (%s)%s' % (name, short, ext), copy -assert os.stat(copy).st_mode & (stat.S_IWUSR | stat.S_IWGRP | stat.S_IWOTH) == 0, 'the copy can be written to' -with open(copy) as f: assert f.read().strip() == git('show', '%s:%s' % (commit, path)), 'the copy is not that version' +copied(done, commit, path) right = menu_items('commitFile', '1', path) assert any(i.get('title', '') == version['title'] for i in right), 'the commit file’s right-click menu has Open Version at…' +# A file a commit deleted isn't in that commit: Review's ▾ and the file's right-click menu open it, and the menu blames +# it, as it was before (the parent), also while Review shows something else (a compare with the working copy). +GONE = 'CHANGELOG.md' +assert git('ls-files', '--', GONE) == GONE and git('status', '--porcelain', '--', GONE) == '', 'CHANGELOG.md unchanged' +git('rm', '-q', '--', GONE) +git('-c', 'user.name=HH', '-c', 'user.email=hh@kaern.invalid', 'commit', '-q', '-m', 'Remove the changelog', '--', GONE) +gone_at, before = git('rev-parse', '--short=7', 'HEAD'), git('rev-parse', '--short=7', 'HEAD^') +settle(lambda d: d['active']['head'] == gone_at, label='the deletion committed') +k('review', 'off'); k('pick', gone_at); k('review', 'all') +settle(lambda d: d['active']['selection'].split()[2:] == [gone_at] and d['active']['reviewFiles'], label='the deletion in Review') +k('review', 'one', GONE) +settle(lambda d: (d['active']['review'] or {}).get('path') == GONE, label='Review › ' + GONE) +assert next(i for i in menu_items('openFile', GONE) if i.get('title', '').startswith('Open Version at '))['title'] == \ + 'Open Version at ' + before, 'Review’s ▾ opens the version before' +right = [i['title'] for i in menu_items('commitFile', gone_at, GONE) if 'title' in i] +print('deleted file, right-click:', right) +assert 'Blame at ' + before in right and 'Open Version at ' + before in right, right +copied(opens('right-click › Open Version at ' + before, 'menuRun', 'commitFile %s %s | Open Version at %s' % (gone_at, GONE, before)), + before, GONE) +first = next(t for t in right if t.startswith('Open in ')) # not on disk: the version before +copied(opens('right-click › ' + first, 'menuRun', 'commitFile %s %s | %s' % (gone_at, GONE, first)), before, GONE) +k('compareWorking', gone_at) +settle(lambda d: d['active']['reviewFiles'] and GONE not in [f['path'] for f in d['active']['reviewFiles']], + label='Review on a compare with the working copy') +right = [i['title'] for i in menu_items('commitFile', gone_at, GONE) if 'title' in i] +assert 'Blame at ' + before in right and 'Open Version at ' + before in right, ('Review showing a compare', right) +k('menuRun', 'commitFile %s %s | Blame at %s' % (gone_at, GONE, before)) +d = settle(lambda d: (d['active']['phase4'].get('explore') or {}).get('blameAt') == before + and d['active']['phase4']['explore']['chunks'], label='the blame before the deletion') +print('deleted file, blame:', d['active']['phase4']['explore']['chunks'][:3]) +k('closeScreen'); k('review', 'off') + # Settings › Open In: the editor, the terminal, and the list — Kaern's, then the added ones; + opens the sheet. k('settings', 'Open In') until(lambda d: window_open(d, 'Open In'), label='the Settings window on Open In') From c66a2b935d7381801221572c1b4b97c9197a9b21 Mon Sep 17 00:00:00 2001 From: progresshans <progresshans@gmail.com> Date: Mon, 30 Nov 2026 13:34:21 +0900 Subject: [PATCH 13/13] fix: an added link keeps the query values it writes itself, a value ending in "=" too MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit An added link dropped query items by looking at the filled-in text: every item ending in "=" went. So myagent://new?token=YWJjZA==&folder={folder} opened as myagent://new?folder=… (the token's Base64 padding ends in "="), and an item the link leaves empty itself (mode=) went too. Now each item is decided on the link as written: it goes only when its value was nothing but {folder}, {file}, {line} or {prompt} and they came out empty (q={prompt} without a prompt). Splitting the link as written also means a filled-in value can't split an item, though Kaern percent-encodes & and = in those anyway. Kaern's own links (Claude Code, Codex) come out as before. Codex's review of PR 9 found it. t_openin's added link now writes token=YWJjZA== and mode=, and both stay in a repository's and a file's menus. It passed in light and dark; so did the checks of the areas the two fixes touch (menus, Open, explore: 9) and the function alone on 12 links, a file name with & and = among them. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- Kaern/App/OpenAgents.swift | 21 +++++++++++++-------- checks/t_openin.py | 14 +++++++++----- 2 files changed, 22 insertions(+), 13 deletions(-) diff --git a/Kaern/App/OpenAgents.swift b/Kaern/App/OpenAgents.swift index 7f90ffe..5b3df6e 100644 --- a/Kaern/App/OpenAgents.swift +++ b/Kaern/App/OpenAgents.swift @@ -19,7 +19,7 @@ struct OpenAgent: Codable, Hashable, Identifiable { /// repository's folder, a file's path and its first changed line, quoted for the shell. var command: String? /// `.link`: what's opened. `{folder}`, `{file}`, `{line}` and `{prompt}` (“@path” for a file) are percent-encoded - /// into it, and a query item left empty goes. One of Kaern's agents in the terminal can have one too: its own + /// into it, and a query item they leave empty goes. One of Kaern's agents in the terminal can have one too: its own /// handler's link, used while that's installed (Claude Code's opens the terminal itself and fills in the prompt). var link: String? var forRepositories = true @@ -199,17 +199,22 @@ enum OpenAgents { } } - /// A link with the place in it: each value percent-encoded, and a query item left empty dropped ("q=" without a - /// prompt). + /// A link with the place in it, each value percent-encoded. A query item goes when its value was only names that + /// came out empty ("q={prompt}" without a prompt); what the link writes itself stays, a value ending in "=" (Base64 + /// padding) and an empty item too. So it's decided item by item on the link as written, not on the filled-in text. static func link(_ template: String, _ place: Place) -> URL? { let values = ["folder": place.folder, "file": place.file ?? "", "line": place.line.map(String.init) ?? "", "prompt": place.path.map(OpenIn.mention) ?? ""] - var text = substitute(template, values.mapValues { $0.addingPercentEncoding(withAllowedCharacters: .linkValue) ?? "" }) - if let mark = text.firstIndex(of: "?") { - let items = text[text.index(after: mark)...].split(separator: "&").filter { !$0.isEmpty && !$0.hasSuffix("=") } - text = String(text[..<mark]) + (items.isEmpty ? "" : "?" + items.joined(separator: "&")) + .mapValues { $0.addingPercentEncoding(withAllowedCharacters: .linkValue) ?? "" } + guard let mark = template.firstIndex(of: "?") else { return URL(string: substitute(template, values)) } + let items = template[template.index(after: mark)...].split(separator: "&").compactMap { item -> String? in + guard let equals = item.firstIndex(of: "=") else { return substitute(String(item), values) } + let value = item[item.index(after: equals)...] + let filled = substitute(String(value), values) + if filled.isEmpty, !value.isEmpty { return nil } + return substitute(String(item[..<equals]), values) + "=" + filled } - return URL(string: text) + return URL(string: substitute(String(template[..<mark]), values) + (items.isEmpty ? "" : "?" + items.joined(separator: "&"))) } /// A command with the place in it, each value quoted for the shell (nothing for a file in a repository's menu). diff --git a/checks/t_openin.py b/checks/t_openin.py index 6aac851..3244c64 100644 --- a/checks/t_openin.py +++ b/checks/t_openin.py @@ -15,10 +15,14 @@ AT_LINE = {'com.microsoft.VSCode', 'com.microsoft.VSCodeInsiders', 'com.todesktop.230313mzl4w4u92', 'com.exafunction.windsurf', 'com.apple.dt.Xcode'} ITEMS = os.path.join(RUN_DIR, 'openin-items.json') -# Added in Settings › Open In: a command for the terminal, a link no app takes, and an app only for files. +OWN = '&token=YWJjZA==&mode=' # what Check Link's query writes itself +# Added in Settings › Open In: a command for the terminal, a link no app takes, and an app only for files. The link +# writes a value ending in "=" (Base64 padding) and an empty item itself: those stay, while the items its names leave +# empty go. CUSTOM = [ {'id': 'check-command', 'name': 'Check Agent', 'way': 'terminal', 'command': 'check-agent --in {folder} {file}'}, - {'id': 'check-link', 'name': 'Check Link', 'way': 'link', 'link': 'kaerncheck://open?folder={folder}&file={file}&line={line}&q={prompt}'}, + {'id': 'check-link', 'name': 'Check Link', 'way': 'link', + 'link': 'kaerncheck://open?folder={folder}&file={file}&line={line}&q={prompt}&token=YWJjZA==&mode='}, {'id': 'check-app', 'name': 'Check App', 'way': 'app', 'app': 'com.apple.TextEdit', 'forRepositories': False}, ] @@ -130,7 +134,7 @@ def copied(done, commit, path): assert agent_rows(items)[-2:] == [('Check Agent', 'Terminal'), ('Check Link', 'Link')], agent_rows(items) assert opens('▾ › Check Agent', 'menuRun', 'openIn | Check Agent — Terminal') == \ ['terminal %s %s check-agent --in %s ' % (terminal, repo, sh(repo))] -assert opens('▾ › Check Link', 'menuRun', 'openIn | Check Link — Link') == ['link kaerncheck://open?folder=' + quoted] +assert opens('▾ › Check Link', 'menuRun', 'openIn | Check Link — Link') == ['link kaerncheck://open?folder=' + quoted + OWN] # What Settings leaves out goes from the menu, but never the default editor. hide = ['check-link'] + editors[1:2] + editors[:1] set_setting('KaernOpenHidden', json.dumps(hide, separators=(',', ':'))) @@ -191,8 +195,8 @@ def copied(done, commit, path): assert opens('file ▾ › Check Agent', 'menuRun', 'openFile ' + CI + ' | Check Agent — Terminal') == \ ['terminal %s %s check-agent --in %s %s' % (terminal, repo, sh(repo), sh(full))] link = opens('file ▾ › Check Link', 'menuRun', 'openFile ' + CI + ' | Check Link — Link') -assert link == ['link kaerncheck://open?folder=%s&file=%s&line=16&q=%s' % (quoted, urllib.parse.quote(full, safe='/'), - urllib.parse.quote('@' + CI + ' ', safe='/'))], link +assert link == ['link kaerncheck://open?folder=%s&file=%s&line=16&q=%s%s' % (quoted, urllib.parse.quote(full, safe='/'), + urllib.parse.quote('@' + CI + ' ', safe='/'), OWN)], link assert opens('file ▾ › Check App', 'menuRun', 'openFile ' + CI + ' | Check App') == ['com.apple.TextEdit ' + full] # Its row's right-click menu: Open in <that app> (⌘↓) and Open With ▸ the others and the agents. row = menu_items('file', CI)