restores Helder in all its glory

This commit is contained in:
2026-09-28 11:34:49 +02:00
parent c2b38b853c
commit 1d29d0952d
280 changed files with 29205 additions and 7 deletions
+64
View File
@@ -0,0 +1,64 @@
import AppKit
import HelderServices
/// App-level setup that SwiftUI has no hook for.
@MainActor
public final class AppDelegate: NSObject, NSApplicationDelegate {
public override init() {
super.init()
}
public func applicationWillFinishLaunching(_ notification: Notification) {
Log.setSink(FileLogger(directory: FileLogger.defaultDirectory))
FontRegistry.registerBundledFonts()
// `swift run` starts a bare executable, which macOS treats as a background tool without these two.
NSApp.setActivationPolicy(.regular)
NSApp.appearance = NSAppearance(named: .darkAqua)
// Every window is one project; tabs would put two projects in one window.
NSWindow.allowsAutomaticWindowTabbing = false
// One window per process: a quit must not leave windows for the next launch to reopen.
// Set in the app's domain, which wins over the system-wide "Close windows when quitting" choice.
UserDefaults.standard.set(false, forKey: "NSQuitAlwaysKeepsWindows")
// The View menu carries its own full-screen item; AppKit's automatic one would be a duplicate.
UserDefaults.standard.set(false, forKey: "NSFullScreenMenuItemEverywhere")
}
public func applicationDidFinishLaunching(_ notification: Notification) {
NSApp.activate(ignoringOtherApps: true)
}
public func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool {
false
}
/// ⌘Q asks about unsaved files in every window first, and writes each note and session before quitting.
public func applicationShouldTerminate(_ sender: NSApplication) -> NSApplication.TerminateReply {
let models = WorkspaceRegistry.models
guard !models.isEmpty else { return .terminateNow }
Task { @MainActor in
for model in models where !(await model.prepareToClose()) {
sender.reply(toApplicationShouldTerminate: false)
return
}
for model in models { await model.closeProject() }
sender.reply(toApplicationShouldTerminate: true)
}
return .terminateLater
}
/// The Dock's right-click menu: the project's name, then New Window (a new process).
public func applicationDockMenu(_ sender: NSApplication) -> NSMenu? {
let menu = NSMenu()
menu.autoenablesItems = false
if let model = WorkspaceRegistry.current, model.root != nil {
menu.addItem(withTitle: model.title, action: nil, keyEquivalent: "").isEnabled = false
menu.addItem(.separator())
}
menu.addItem(withTitle: "New Window", action: #selector(newWindow), keyEquivalent: "").target = self
return menu
}
@objc private func newWindow() {
LiveSystemActions().openNewInstance(nil)
}
}
+44
View File
@@ -0,0 +1,44 @@
import Darwin
import Foundation
import HelderServices
/// Renames the running app, which is what Mission Control, the Dock tooltip and ⌘Tab show.
/// Uses private LaunchServices calls looked up at runtime; when one is missing the name stays as it is.
@MainActor
enum AppName {
static let standard = "Helder"
private static var current: String?
static func set(_ name: String) {
guard name != current else { return }
current = name
guard let calls = LaunchServicesCalls.shared, let asn = calls.currentASN()?.takeUnretainedValue() else { return }
let status = calls.setItem(LaunchServicesCalls.defaultSession, asn, calls.displayNameKey, name as CFString, nil)
if status != noErr { Log.warn("app", "could not rename the app to \(name): \(status)") }
}
}
private struct LaunchServicesCalls {
typealias CurrentASN = @convention(c) () -> Unmanaged<CFTypeRef>?
typealias SetItem = @convention(c) (Int32, CFTypeRef, CFString, CFTypeRef, UnsafeMutableRawPointer?) -> OSStatus
/// `kLSDefaultSessionID`
static let defaultSession: Int32 = -2
let currentASN: CurrentASN
let setItem: SetItem
let displayNameKey: CFString
static let shared: LaunchServicesCalls? = {
guard let handle = dlopen("/System/Library/Frameworks/CoreServices.framework/CoreServices", RTLD_LAZY),
let asn = dlsym(handle, "_LSGetCurrentApplicationASN"),
let set = dlsym(handle, "_LSSetApplicationInformationItem"),
let key = dlsym(handle, "_kLSDisplayNameKey") else {
Log.warn("app", "LaunchServices rename calls not found; the app keeps its name")
return nil
}
return LaunchServicesCalls(currentASN: unsafeBitCast(asn, to: CurrentASN.self),
setItem: unsafeBitCast(set, to: SetItem.self),
displayNameKey: key.load(as: CFString.self))
}()
}
+139
View File
@@ -0,0 +1,139 @@
import CoreGraphics
import Foundation
import HelderCore
/// Where a focus request sends the keyboard. Views observe `WorkspaceModel.focusRequest` and take
/// first responder when it names them.
public enum FocusTarget: Equatable, Sendable {
case panel(Panel)
/// ⌘C without a selection: the commit message field.
case commitMessage
}
/// A focus request; `id` makes a repeated request for the same target observable.
public struct FocusRequest: Equatable {
public var target: FocusTarget
public var id = UUID()
public init(_ target: FocusTarget) {
self.target = target
}
}
/// A text selection read from the focused text view, for ⌘→ and ⌘F.
public struct TextSelectionInfo: Equatable, Sendable {
public var text: String
/// 1-based, inclusive.
public var startLine: Int
public var endLine: Int
public init(text: String, startLine: Int, endLine: Int) {
self.text = text
self.startLine = startLine
self.endLine = endLine
}
}
public enum ZoomStep: Equatable, Sendable {
case reset
case bigger
case smaller
}
/// Everything the user can ask a workspace window to do. Views, menus and the key router all call
/// `WorkspaceModel.perform(_:)` with one of these, so one shortcut and its button can never drift apart.
public enum Command: Equatable, Sendable {
// MARK: Overlays
/// ⌘F; the seed is the first line of the current selection.
case showSearch(seed: String)
/// ⌘N
case showNote
/// `?`
case showShortcuts
/// ⇧⌘O: the other recent projects.
case showRecentProjects
/// ⌘↑/⌘↓ from the editor.
case showRecentFiles(initialSelection: Int)
/// Right-click or ⌘→ on a row; `anchor` is in window coordinates.
case showContextMenu(ContextTarget, anchor: CGPoint)
/// Esc: closes the one open overlay, with its own close behaviour (the note saves, Diff restores the mode).
case dismissOverlay
/// The confirm overlay's yes.
case confirmPending
/// The name prompt's ↵ with the typed name.
case submitName(String)
/// The pass-on prompt's ↵: inserts `text` into the agent and toasts `reference`.
case passToAgent(text: String, reference: String?)
// MARK: Launcher
case launcherMove(Int)
case launcherSelect(Int)
case launcherActivate
// MARK: Layout and focus
/// ⌘G
case toggleGit
/// ⌘L
case toggleAutoFit
/// ⌘.
case toggleHidden
/// Moves keyboard focus to a column (and takes first responder).
case focus(Panel)
/// ⌘←/⌘→ outside a text field.
case focusNeighbour(step: Int)
// MARK: Row cursor in Source Control and Explorer
/// ↑/↓
case moveRowCursor(Int)
/// ↵: git row opens its half, a file opens, a folder toggles.
case openSelectedRow
/// ⌘→ on a row: its context menu, anchored to the column's right edge.
case openRowMenu
// MARK: Editor
case open(String, OpenOptions)
/// ⌘S
case save
/// ⌘W: closes the active file, or the window when none is open.
case closeFileOrWindow
/// ⌘M
case cycleMode
/// ⌘→ with a selection: the pass-on prompt for it. nil falls back to the editor's line selection.
case passSelection(TextSelectionInfo?)
/// ⌘A outside a text field: the whole open file in its pane.
case selectAllInFile
// MARK: Git
/// ⌘↵
case commit
/// ⌘P
case push
/// ⌘C without a selection
case focusCommitMessage
// MARK: Note
/// ⌘P while the note is open.
case passNote
// MARK: Project and window
/// ⌘O
case openFolder
case openRecentProject(String)
/// ⌘R: git, tree and the open file, re-read from disk.
case refresh
/// ⇧⌘N
case newWindow
/// View → Actual Size, Zoom In, Zoom Out: the code and terminal text size.
case zoom(ZoomStep)
/// A context-menu item.
case context(ContextAction)
}
+23
View File
@@ -0,0 +1,23 @@
import SwiftUI
/// `⑂ branch │ project`, centred for half a second when the window becomes key again. No fade.
struct FocusFlash: View {
let model: WorkspaceModel
var body: some View {
HStack(spacing: 11) {
Image(systemName: "arrow.triangle.branch").font(.system(size: 18, weight: .light)).foregroundStyle(Palette.amber)
Text(model.sourceControl?.state.branch ?? "—").typeRole(Typography.focusFlash).foregroundStyle(Palette.amber)
Rectangle().fill(Palette.raised).frame(width: 1, height: 17).padding(.horizontal, 1)
Text(model.name).typeRole(Typography.focusFlashName).foregroundStyle(Palette.text1).lineLimit(1)
}
.padding(.horizontal, 22)
.padding(.vertical, 15)
.background(Palette.panel, in: RoundedRectangle(cornerRadius: Metrics.radiusMedium))
.overlay(RoundedRectangle(cornerRadius: Metrics.radiusMedium).strokeBorder(Palette.raised, lineWidth: Metrics.hairline))
.overlay(alignment: .leading) { Rectangle().fill(Palette.amber).frame(width: Metrics.accentRule) }
.shadow(color: Palette.overlayShadow, radius: Metrics.overlayShadowRadius / 2, y: Metrics.overlayShadowY)
.frame(maxWidth: .infinity, maxHeight: .infinity)
.allowsHitTesting(false)
}
}
+143
View File
@@ -0,0 +1,143 @@
import AppKit
import HelderCore
import HelderServices
import SwiftUI
/// The app's window scene: one project per window.
public struct HelderScene: Scene {
public static let windowID = "workspace"
public init() {}
public var body: some Scene {
WindowGroup(id: Self.windowID) {
WorkspaceWindow(root: LaunchState.claimRoot())
}
.windowStyle(.hiddenTitleBar)
.defaultSize(width: Metrics.defaultWindow.width, height: Metrics.defaultWindow.height)
.commands { HelderCommands() }
}
}
/// The menu bar. Shortcuts the key router owns (⌘F, ⌘G, ⌘L, ⌘.) are shown here too; the router
/// consumes them first, so the menu item fires only when a field or an overlay let the key through.
struct HelderCommands: Commands {
@FocusedValue(\.workspace) private var workspace
var body: some Commands {
CommandGroup(replacing: .newItem) {
Button("New Window") { openNewInstance(nil) }
.keyboardShortcut("n", modifiers: [.command, .shift])
Button("Open Folder…") { openFolder() }
.keyboardShortcut("o", modifiers: .command)
Menu("Open Recent") {
let recents = workspace?.recentProjects.filter { $0.path != workspace?.root?.path } ?? []
if recents.isEmpty {
Text("No Recent Projects")
} else {
ForEach(recents) { project in
Button(project.name) { openRecent(project.path) }
}
}
}
Button("Open Recent Project…") { workspace?.perform(.showRecentProjects) }
.keyboardShortcut("o", modifiers: [.command, .shift])
.disabled(workspace?.root == nil)
}
CommandGroup(replacing: .saveItem) {
Button(workspace?.editor?.activePath == nil ? "Close" : "Close File") {
if let workspace { workspace.perform(.closeFileOrWindow) } else { NSApp.keyWindow?.performClose(nil) }
}
.keyboardShortcut("w", modifiers: .command)
Button("Close Window") { NSApp.keyWindow?.performClose(nil) }
.keyboardShortcut("w", modifiers: [.command, .shift])
Divider()
Button("Save") { workspace?.perform(.save) }
.keyboardShortcut("s", modifiers: .command)
.disabled(workspace?.editor?.activePath == nil)
}
// ⌘M cycles the editor's view, so Minimize gives up its shortcut.
CommandGroup(replacing: .windowSize) {
Button("Minimize") { NSApp.keyWindow?.miniaturize(nil) }
Button("Zoom") { NSApp.keyWindow?.zoom(nil) }
}
CommandGroup(before: .toolbar) {
Button("Refresh") { workspace?.perform(.refresh) }
.keyboardShortcut("r", modifiers: .command)
.disabled(workspace?.root == nil)
Divider()
Button(workspace?.layout.gitVisible == false ? "Show Source Control" : "Hide Source Control") {
workspace?.perform(.toggleGit)
}
.keyboardShortcut("g", modifiers: .command)
Button(workspace?.layout.fluid == false ? "Fluid Column Widths" : "Lock Column Widths") {
workspace?.perform(.toggleAutoFit)
}
.keyboardShortcut("l", modifiers: .command)
Button(workspace?.layout.showHidden == true ? "Hide Hidden Files" : "Show Hidden Files") {
workspace?.perform(.toggleHidden)
}
.keyboardShortcut(".", modifiers: .command)
Divider()
Button("Search") { workspace?.perform(.showSearch(seed: "")) }
.keyboardShortcut("f", modifiers: .command)
Button("Project Note") { workspace?.perform(.showNote) }
.keyboardShortcut("n", modifiers: .command)
Button("Keyboard Shortcuts") { workspace?.perform(.showShortcuts) }
Divider()
Button("Actual Size") { workspace?.perform(.zoom(.reset)) }
.keyboardShortcut("0", modifiers: .command)
Button("Zoom In") { workspace?.perform(.zoom(.bigger)) }
.keyboardShortcut("+", modifiers: .command)
Button("Zoom Out") { workspace?.perform(.zoom(.smaller)) }
.keyboardShortcut("-", modifiers: .command)
Divider()
Button(workspace?.layout.isFullScreen == true ? "Exit Full Screen" : "Enter Full Screen") {
NSApp.keyWindow?.toggleFullScreen(nil)
}
.keyboardShortcut("f", modifiers: [.command, .control])
}
CommandGroup(replacing: .help) {
Button("Keyboard Shortcuts") { workspace?.perform(.showShortcuts) }
Divider()
Button("Open Log") { LiveSystemActions().openLog() }
Button("Reveal Log in Finder") { LiveSystemActions().revealLog() }
}
}
private func openNewInstance(_ root: URL?) {
LiveSystemActions().openNewInstance(root)
}
/// Without a key window there is no project to switch, so the choice opens in a new process.
private func openFolder() {
if let workspace {
workspace.perform(.openFolder)
return
}
Task { @MainActor in
if let url = await LiveSystemActions().chooseFolder() { openNewInstance(url) }
}
}
private func openRecent(_ path: String) {
if let workspace {
workspace.perform(.openRecentProject(path))
} else {
openNewInstance(URL(fileURLWithPath: path))
}
}
}
/// Hands the launch folder (`$HELDER_PROJECT` or an argument) to the first window; a later window
/// in this process (the Dock reopening one after the last closed) starts on the launcher.
@MainActor
enum LaunchState {
private static var claimedInitial = false
static func claimRoot() -> URL? {
guard !claimedInitial else { return nil }
claimedInitial = true
return ProjectLocator.initialRoot()
}
}
+194
View File
@@ -0,0 +1,194 @@
import Foundation
import HelderCore
/// A key press, reduced to what the router matches on.
public struct KeyPress: Equatable, Sendable {
public enum Key: Equatable, Sendable {
/// Lowercased, as typed without modifiers; `?` arrives as itself.
case character(String)
case up, down, left, right
case enter
case escape
case other
}
public var key: Key
public var command: Bool
public var shift: Bool
public var option: Bool
public var control: Bool
public init(_ key: Key, command: Bool = false, shift: Bool = false, option: Bool = false, control: Bool = false) {
self.key = key
self.command = command
self.shift = shift
self.option = option
self.control = control
}
static func cmd(_ key: Key, shift: Bool = false) -> KeyPress { KeyPress(key, command: true, shift: shift) }
}
/// Who holds the keyboard when the key arrives.
public enum KeyboardOwner: Equatable, Sendable {
/// No text input: the workspace itself.
case workspace
/// A text field or text view, and the column it sits in.
case text(in: Panel?)
/// A terminal pane.
case terminal
}
/// The state a routing decision depends on; built from the window and the model at key time.
public struct KeyContext: Equatable, Sendable {
public var hasProject: Bool
public var overlay: OverlayKind
public var owner: KeyboardOwner
/// The focused text view or terminal has a non-empty selection.
public var hasTextSelection: Bool
/// The focused text view's selection, when it sits in the editor column.
public var editorTextSelection: TextSelectionInfo?
/// The editor's read-only panes hold a multi-line selection.
public var hasEditorLineSelection: Bool
public var activePanel: Panel?
public var focusZone: FocusZone
public var recentFileCount: Int
/// The seed ⌘F uses: the first line of the current selection.
public var searchSeed: String
public init(hasProject: Bool = true, overlay: OverlayKind = .none, owner: KeyboardOwner = .workspace,
hasTextSelection: Bool = false, editorTextSelection: TextSelectionInfo? = nil,
hasEditorLineSelection: Bool = false, activePanel: Panel? = nil, focusZone: FocusZone = .neutral,
recentFileCount: Int = 0, searchSeed: String = "") {
self.hasProject = hasProject
self.overlay = overlay
self.owner = owner
self.hasTextSelection = hasTextSelection
self.editorTextSelection = editorTextSelection
self.hasEditorLineSelection = hasEditorLineSelection
self.activePanel = activePanel
self.focusZone = focusZone
self.recentFileCount = recentFileCount
self.searchSeed = searchSeed
}
}
/// The overlay kinds the router tells apart.
public enum OverlayKind: Equatable, Sendable {
case none
case note
/// The full-screen Diff: the workspace shortcuts keep working over it. `busy` while its own
/// menu or pass-on prompt is open; those then own every key.
case diff(busy: Bool)
/// Any other overlay: it owns every key but Esc.
case other
public init(_ overlay: Overlay, diffBusy: Bool = false) {
switch overlay {
case .none: self = .none
case .note: self = .note
case .diff: self = .diff(busy: diffBusy)
default: self = .other
}
}
}
public enum KeyRoute: Equatable {
/// The key belongs to someone else: a text field, a terminal, an overlay's own handler, or a menu.
case pass
case perform(Command)
}
/// Maps a key press to a command. A key that a focused field or terminal needs is never taken:
/// arrows, ↵, `?`, ⌘A and ⌘C/⌘←/⌘→ go to the field; ⌘O, ⌘R and ⇧⌘N are left to the menu bar.
public enum KeyRouter {
public static func route(_ press: KeyPress, _ context: KeyContext) -> KeyRoute {
if press.control || press.option { return .pass }
if !context.hasProject { return launcherKey(press) }
switch context.overlay {
case .diff(busy: true): return .pass
case .none: if press.key == .escape { return .pass }
default: if press.key == .escape && !press.command { return .perform(.dismissOverlay) }
}
switch context.overlay {
case .none: break
case .diff:
if press == .cmd(.character("a")) { return .pass }
case .note:
return press == .cmd(.character("p")) ? .perform(.passNote) : .pass
case .other: return .pass
}
return press.command ? commandKey(press, context) : plainKey(press, context)
}
private static func launcherKey(_ press: KeyPress) -> KeyRoute {
guard !press.shift else { return .pass }
switch press.key {
case .up: return .perform(.launcherMove(-1))
case .down: return .perform(.launcherMove(1))
case .enter where !press.command: return .perform(.launcherActivate)
default: return .pass
}
}
private static func plainKey(_ press: KeyPress, _ context: KeyContext) -> KeyRoute {
let inList = context.owner == .workspace && (context.activePanel == .sourceControl || context.activePanel == .explorer)
switch press.key {
case .up where inList && !press.shift: return .perform(.moveRowCursor(-1))
case .down where inList && !press.shift: return .perform(.moveRowCursor(1))
case .enter where inList && !press.shift: return .perform(.openSelectedRow)
case .character("?") where context.owner == .workspace: return .perform(.showShortcuts)
default: return .pass
}
}
private static func commandKey(_ press: KeyPress, _ context: KeyContext) -> KeyRoute {
let owner = context.owner
if press.shift {
return press.key == .character("o") ? .perform(.showRecentProjects) : .pass
}
switch press.key {
case .up, .down:
guard context.focusZone == .editor, context.recentFileCount > 0 else { return .pass }
return .perform(.showRecentFiles(initialSelection: ListCursor.recentFilesStart(movingDown: press.key == .down,
count: context.recentFileCount)))
case .right:
if owner == .workspace, context.activePanel == .sourceControl || context.activePanel == .explorer {
return .perform(.openRowMenu)
}
if let selection = context.editorTextSelection { return .perform(.passSelection(selection)) }
if context.hasEditorLineSelection && owner != .terminal { return .perform(.passSelection(nil)) }
return owner == .workspace ? .perform(.focusNeighbour(step: 1)) : .pass
case .left:
return owner == .workspace ? .perform(.focusNeighbour(step: -1)) : .pass
case .enter:
return owner == .text(in: .sourceControl) ? .pass : .perform(.commit)
case let .character(c):
return commandCharacter(c, context)
default:
return .pass
}
}
private static func commandCharacter(_ c: String, _ context: KeyContext) -> KeyRoute {
switch c {
case "f": return .perform(.showSearch(seed: context.searchSeed))
case "p": return .perform(.push)
case "n": return .perform(.showNote)
case "s": return .perform(.save)
case "m": return .perform(.cycleMode)
case "w": return .perform(.closeFileOrWindow)
case "g": return .perform(.toggleGit)
case "l": return .perform(.toggleAutoFit)
case ".": return .perform(.toggleHidden)
case "a": return context.owner == .workspace ? .perform(.selectAllInFile) : .pass
case "c":
if context.hasTextSelection || context.hasEditorLineSelection { return .pass }
return .perform(.focusCommitMessage)
default: return .pass
}
}
}
+39
View File
@@ -0,0 +1,39 @@
import Foundation
import HelderCore
/// What choosing a launcher row does.
public enum LauncherChoice: Equatable {
/// "Open new project…": the folder picker.
case chooseFolder
case open(path: String)
}
/// The launcher's rows and keyboard cursor: row 0 is "Open new project…", then the recent projects.
public struct LauncherList: Equatable {
public private(set) var recents: [RecentProject]
public private(set) var selection = 0
/// `excluding` drops the window's own project, so ⇧⌘O never offers the folder that is already open.
public init(recents: [RecentProject] = [], excluding root: String? = nil) {
self.recents = recents.filter { $0.path != root }
}
public var count: Int { recents.count + 1 }
/// Moves the cursor, clamped to the first and last row.
public mutating func move(by step: Int) {
selection = min(max(selection + step, 0), count - 1)
}
public mutating func select(_ index: Int) {
selection = min(max(index, 0), count - 1)
}
public func choice(at index: Int) -> LauncherChoice? {
if index == 0 { return .chooseFolder }
guard recents.indices.contains(index - 1) else { return nil }
return .open(path: recents[index - 1].path)
}
public var selectedChoice: LauncherChoice? { choice(at: selection) }
}
+152
View File
@@ -0,0 +1,152 @@
import HelderCore
import SwiftUI
/// The bare window: no title bar, the launcher card top-centred on the editor ground.
struct LauncherScreen: View {
let model: WorkspaceModel
var body: some View {
ZStack(alignment: .top) {
Palette.editor
LauncherCard(model: model)
.padding(.top, Metrics.launcherTopPadding)
.padding(.horizontal, 20)
.padding(.bottom, 20)
}
}
}
/// Head, "Open new project…", the RECENT list and the key hints. Hover and the arrows move the same cursor.
/// The card hugs a short list and scrolls a long one inside the window.
struct LauncherCard: View {
let model: WorkspaceModel
var body: some View {
OverlayCard {
ViewThatFits(in: .vertical) {
VStack(spacing: 0) {
head
rows
footer
}
VStack(spacing: 0) {
head
ScrollViewReader { proxy in
ScrollView { rows }
.onChange(of: model.launcher.selection) { _, selection in proxy.scrollTo(selection) }
}
footer
}
}
}
.frame(width: Metrics.launcherWidth)
.frame(maxHeight: .infinity, alignment: .top)
}
private var rows: some View {
let launcher = model.launcher
return LazyVStack(alignment: .leading, spacing: 0) {
LauncherRow(index: 0, model: model) {
Image(systemName: "plus")
} text: {
Text("Open new project…").typeRole(Typography.rowSelected).foregroundStyle(Palette.text1)
} trailing: {
EscChip("↵")
}
.frame(height: Metrics.launcherNewRow)
.hairline(.bottom)
if !launcher.recents.isEmpty {
Text("Recent")
.typeRole(Typography.panelLabel)
.foregroundStyle(Palette.text4)
.padding(EdgeInsets(top: 14, leading: 20, bottom: 6, trailing: 20))
}
ForEach(Array(launcher.recents.enumerated()), id: \.element.id) { offset, project in
recentRow(project, index: offset + 1)
}
}
}
private var head: some View {
HStack(spacing: 14) {
Image(systemName: "sparkle").font(.system(size: 16, weight: .light)).foregroundStyle(Palette.amber)
VStack(alignment: .leading, spacing: 5) {
Wordmark(role: Typography.launcherWordmark)
Text("Open a project to begin").typeRole(Typography.tooltip).foregroundStyle(Palette.text4)
}
Spacer(minLength: 0)
}
.padding(20)
.hairline(.bottom)
}
private func recentRow(_ project: RecentProject, index: Int) -> some View {
let selected = model.launcher.selection == index
return LauncherRow(index: index, model: model) {
Image(systemName: "folder")
} text: {
HStack(alignment: .firstTextBaseline, spacing: 10) {
Text(project.name).typeRole(Typography.rowSelected).foregroundStyle(selected ? Palette.text1 : Palette.text3)
.lineLimit(1)
Text(project.path).typeRole(Typography.meta).foregroundStyle(selected ? Palette.text3 : Palette.text4)
.lineLimit(1).truncationMode(.head)
}
} trailing: {
EmptyView()
}
.frame(height: Metrics.launcherRow)
.help(project.path)
}
private var footer: some View {
OverlayFooter.hint([("⌘↑↓", "navigate"), ("↵", "open")])
.typeRole(Typography.chip)
.padding(.horizontal, 20)
.frame(maxWidth: .infinity, minHeight: Metrics.launcherFooter, alignment: .leading)
.hairline(.top)
}
}
private struct LauncherRow<Icon: View, Label: View, Trailing: View>: View {
let index: Int
let model: WorkspaceModel
let icon: Icon
let text: Label
let trailing: Trailing
@State private var isHovered = false
init(index: Int, model: WorkspaceModel, @ViewBuilder icon: () -> Icon, @ViewBuilder text: () -> Label,
@ViewBuilder trailing: () -> Trailing) {
self.index = index
self.model = model
self.icon = icon()
self.text = text()
self.trailing = trailing()
}
var body: some View {
let selected = model.launcher.selection == index
HStack(spacing: 12) {
icon
.font(.system(size: 13, weight: .light))
.foregroundStyle(selected || index == 0 ? Palette.amber : Palette.text4)
.frame(width: 16, height: 16)
text
Spacer(minLength: 8)
trailing
}
.padding(.horizontal, 20)
.frame(maxHeight: .infinity)
.selectableRow(isSelected: selected, isHovered: isHovered)
.contentShape(Rectangle())
.id(index)
.onHover { inside in
isHovered = inside
if inside { model.perform(.launcherSelect(index)) }
}
.onTapGesture {
model.perform(.launcherSelect(index))
model.perform(.launcherActivate)
}
}
}
@@ -0,0 +1,117 @@
import AppKit
import HelderCore
import SwiftUI
/// ⇧⌘O: the other recent projects; ↵ or a click switches this window to one.
struct RecentProjectsOverlay: View {
let model: WorkspaceModel
@State private var selection = 0
@State private var parkedPointer: CGPoint?
private var projects: [RecentProject] { model.otherRecentProjects }
var body: some View {
OverlayShell(.sized(width: 560), onDismiss: close) {
VStack(spacing: 0) {
OverlayHeader(systemImage: "folder", title: "Open recent project", iconColor: Palette.text4, showsEscChip: false) {
HStack(spacing: 4) {
Text("\(projects.count) project\(projects.count == 1 ? "" : "s") ·")
Keycap("⌘↓")
Keycap("⌘↑")
Keycap("↵")
}
.typeRole(Typography.path)
.foregroundStyle(Palette.text4)
.padding(.horizontal, 6)
.padding(.vertical, 4)
.overlay(RoundedRectangle(cornerRadius: Metrics.radiusSmall).strokeBorder(Palette.raised, lineWidth: Metrics.hairline))
}
list
}
.background(OverlayKeyCatcher(onKey: handle))
}
}
private var list: some View {
ScrollViewReader { proxy in
ScrollView {
LazyVStack(spacing: 0) {
if projects.isEmpty {
Text("No other recent projects")
.typeRole(Typography.tooltip)
.foregroundStyle(Palette.text4)
.padding(EdgeInsets(top: 12, leading: 14, bottom: 12, trailing: 14))
.frame(maxWidth: .infinity, alignment: .leading)
}
ForEach(Array(projects.enumerated()), id: \.element.id) { index, project in
row(project, selected: index == selection)
.id(index)
.onHover { inside in if inside { hover(index) } }
.onTapGesture { open(project) }
}
}
.padding(.vertical, 6)
}
.frame(height: min(460, CGFloat(max(projects.count, 1)) * Metrics.launcherRow + 12 + (projects.isEmpty ? 12 : 0)))
.onChange(of: selection) { _, row in proxy.scrollTo(row) }
}
}
private func row(_ project: RecentProject, selected: Bool) -> some View {
HStack(spacing: 10) {
Image(systemName: "folder")
.font(.system(size: 13, weight: .light))
.foregroundStyle(selected ? Palette.amber : Palette.text4)
.frame(width: 16)
VStack(alignment: .leading, spacing: 1) {
Text(project.name)
.typeRole(Typography.rowSelected)
.foregroundStyle(selected ? Palette.text1 : Palette.text2)
.lineLimit(1)
Text(project.path)
.typeRole(Typography.meta)
.foregroundStyle(Palette.text4)
.lineLimit(1)
.truncationMode(.head)
}
Spacer(minLength: 0)
}
.padding(.horizontal, 14)
.frame(height: Metrics.launcherRow)
.contentShape(Rectangle())
.selectableRow(isSelected: selected)
.help(project.path)
}
private func handle(_ key: OverlayKey) -> Bool {
switch key {
case .up, .commandUp: park(); selection = ListCursor.step(selection, by: -1, count: projects.count)
case .down, .commandDown: park(); selection = ListCursor.step(selection, by: 1, count: projects.count)
case .enter: if projects.indices.contains(selection) { open(projects[selection]) }
case .escape: close()
default: return false
}
return true
}
/// Arrow keys park the pointer, so a list scrolling under a still mouse does not steal the selection.
private func park() {
parkedPointer = NSEvent.mouseLocation
}
private func hover(_ index: Int) {
if let parked = parkedPointer, parked == NSEvent.mouseLocation { return }
parkedPointer = nil
selection = index
}
private func close() {
model.perform(.dismissOverlay)
}
private func open(_ project: RecentProject) {
close()
model.perform(.openRecentProject(project.path))
}
}
@@ -0,0 +1,47 @@
import HelderCore
import SwiftUI
/// 28pt display-only bar: branch, line totals and staged/unstaged counts left; path, position, encoding, line ending and language right.
struct StatusBarView: View {
let model: WorkspaceModel
var body: some View {
let git = model.sourceControl?.state ?? .empty
let totals = git.totals
let editor = model.editor
let path = editor?.activePath
HStack(spacing: Metrics.statusBarGap) {
Text("⑂ \(git.branch)").foregroundStyle(Palette.amber).lineLimit(1)
Text("+\(totals.added)").foregroundStyle(Palette.addedText)
Text("\u{2212}\(totals.removed)").foregroundStyle(Palette.removedText)
Text("\(git.stagedCount) staged · \(git.unstagedCount) unstaged").lineLimit(1)
Spacer(minLength: 0)
if let path {
Text(path).lineLimit(1).truncationMode(.head)
.frame(maxWidth: 0.52 * model.layout.windowWidth, alignment: .trailing)
.fixedSize(horizontal: false, vertical: true)
Text("·")
Text(position(editor?.cursor, path: path))
Text("·")
}
Text("UTF-8")
Text("·")
Text("LF")
if let path {
Text("·")
Text(FileType.languageLabel(for: path)).foregroundStyle(Palette.text3)
}
}
.typeRole(Typography.meta)
.foregroundStyle(Palette.text4)
.padding(.horizontal, 14)
.frame(height: Metrics.statusBar)
.background(Palette.panel)
.hairline(.top)
}
private func position(_ cursor: Cursor?, path: String) -> String {
guard let cursor, cursor.path == path else { return "Ln 1, Col 1" }
return "Ln \(cursor.line), Col \(cursor.column)"
}
}
@@ -0,0 +1,92 @@
import AppKit
import HelderCore
import HelderServices
/// The AppKit side effects a workspace triggers: dialogs, the pasteboard, Finder and the log file.
@MainActor
public protocol SystemActing: AnyObject {
/// The folder picker; nil when cancelled.
func chooseFolder() async -> URL?
func copy(_ text: String)
func pasteboardText() -> String?
func revealInFinder(_ url: URL)
/// Asked before a file with unsaved edits closes.
func confirmUnsavedClose(_ path: String) -> UnsavedCloseChoice
func openLog()
func revealLog()
/// Starts another Helder process on `root`, or on the launcher when nil; each project runs in its own process.
func openNewInstance(_ root: URL?)
}
public final class LiveSystemActions: SystemActing {
public nonisolated init() {}
public func chooseFolder() async -> URL? {
let panel = NSOpenPanel()
panel.canChooseDirectories = true
panel.canChooseFiles = false
panel.allowsMultipleSelection = false
panel.prompt = "Open"
panel.message = "Choose a project folder"
let response = await panel.begin()
return response == .OK ? panel.url : nil
}
public func copy(_ text: String) {
NSPasteboard.general.clearContents()
NSPasteboard.general.setString(text, forType: .string)
}
public func pasteboardText() -> String? {
NSPasteboard.general.string(forType: .string)
}
public func revealInFinder(_ url: URL) {
NSWorkspace.shared.activateFileViewerSelecting([url])
}
public func confirmUnsavedClose(_ path: String) -> UnsavedCloseChoice {
let alert = NSAlert()
alert.messageText = "Save changes to \(PathUtils.basename(path))?"
alert.informativeText = "\(path) has unsaved edits. They are lost if you close without saving."
alert.alertStyle = .warning
alert.addButton(withTitle: "Save")
alert.addButton(withTitle: "Don’t Save")
alert.addButton(withTitle: "Cancel")
switch alert.runModal() {
case .alertFirstButtonReturn: return .save
case .alertSecondButtonReturn: return .discard
default: return .cancel
}
}
public func openLog() {
NSWorkspace.shared.open(Self.logURL)
}
public func revealLog() {
revealInFinder(Self.logURL)
}
public func openNewInstance(_ root: URL?) {
let bundle = Bundle.main.bundleURL
guard bundle.pathExtension == "app" else {
guard let executable = Bundle.main.executableURL else { return }
do {
try InstanceLauncher.spawn(executable, root: root)
} catch {
Log.error("window", "could not start a new instance: \(error.localizedDescription)")
}
return
}
let configuration = NSWorkspace.OpenConfiguration()
configuration.createsNewApplicationInstance = true
configuration.activates = true
configuration.arguments = InstanceLauncher.arguments(for: root)
NSWorkspace.shared.openApplication(at: bundle, configuration: configuration) { _, error in
if let error { Log.error("window", "could not start a new instance: \(error.localizedDescription)") }
}
}
private static var logURL: URL { FileLogger.defaultDirectory.appendingPathComponent("helder.log") }
}
+117
View File
@@ -0,0 +1,117 @@
import HelderCore
import SwiftUI
/// 44pt bar: traffic-light inset, wordmark, project · branch, the open file's breadcrumb, and the toolbar.
struct TitleBarView: View {
let model: WorkspaceModel
var body: some View {
HStack(spacing: Metrics.titleBarGap) {
HStack(alignment: .firstTextBaseline, spacing: Metrics.titleClusterGap) {
Wordmark()
ProjectName(name: model.name) { model.perform(.openFolder) }
Text("·").typeRole(Typography.path).foregroundStyle(Palette.text4)
Text(model.sourceControl?.state.branch ?? "—")
.typeRole(Typography.branch)
.foregroundStyle(Palette.amber)
.lineLimit(1)
}
.fixedSize()
Breadcrumb(path: model.editor?.activePath, isDirty: model.editor.map { e in e.activePath.map(e.isDirty) ?? false } ?? false)
.frame(maxWidth: .infinity, alignment: .leading)
TitleToolbar(model: model)
}
.padding(.leading, model.layout.isFullScreen ? 14 : Metrics.trafficLightInset)
.padding(.trailing, 14)
.frame(height: Metrics.titleBar)
.background(Palette.panel)
.hairline(.bottom)
}
}
private struct ProjectName: View {
let name: String
let action: () -> Void
@State private var isHovered = false
var body: some View {
Text(name)
.typeRole(Typography.path)
.foregroundStyle(isHovered ? Palette.text2 : Palette.text4)
.lineLimit(1)
.onHover { isHovered = $0 }
.onTapGesture(perform: action)
.help("Open folder…")
.animation(Metrics.colorTransition, value: isHovered)
}
}
/// `resources › views › form.blade.php`: segments in text-4, the file name in text-1 600, a dot when unsaved.
private struct Breadcrumb: View {
let path: String?
let isDirty: Bool
var body: some View {
if let path {
let segments = path.split(separator: "/").map(String.init)
HStack(spacing: Metrics.crumbGap) {
ForEach(Array(segments.enumerated()), id: \.offset) { index, segment in
if index > 0 { Text("›").foregroundStyle(Palette.text4) }
if index == segments.count - 1 {
Text(segment).typeRole(Typography.crumbLeaf).foregroundStyle(Palette.text1)
} else {
Text(segment).foregroundStyle(Palette.text4)
}
}
if isDirty {
Text("●").font(.system(size: 10)).foregroundStyle(Palette.amber).padding(.leading, 4).help("Unsaved changes")
}
}
.typeRole(Typography.path)
.lineLimit(1)
.truncationMode(.head)
} else {
Spacer(minLength: 0)
}
}
}
/// Search ⌘F · Fluid ⌘L · Hidden ⌘. · Note ⌘N · Git ⌘G · `?`, each with a tooltip that names its state.
private struct TitleToolbar: View {
let model: WorkspaceModel
var body: some View {
let layout = model.layout
let overlay = model.overlay.current
HStack(spacing: Metrics.toolbarGap) {
ToolbarToggle("Search", keys: "⌘F", isOn: isSearch(overlay)) { model.perform(.showSearch(seed: "")) }
.tip("Search the open file, the project and the file names.", edge: .trailing)
ToolbarToggle("Fluid", keys: "⌘L", isOn: layout.fluid) { model.perform(.toggleAutoFit) }
.tip(layout.fluid
? Tooltip.stated("Column widths: ", "fluid", " — the columns re-fit on resize and focus. Click to lock them.")
: Tooltip.stated("Column widths: ", "locked", " — the columns keep their size. Click to make them fluid."),
edge: .trailing)
ToolbarToggle("Hidden", keys: "⌘.", isOn: layout.showHidden, muted: !layout.showHidden) { model.perform(.toggleHidden) }
.tip(layout.showHidden
? Tooltip.stated("Hidden files: ", "shown", " — dotfiles appear in the tree and the search. Click to hide them.")
: Tooltip.stated("Hidden files: ", "hidden", " — dotfiles are excluded from the tree and the search. Click to show them."),
edge: .trailing)
ToolbarToggle("Note", keys: "⌘N", isOn: overlay == .note) { model.perform(.showNote) }
.tip("Project note (.notes.txt) — kept next to this project.", edge: .trailing)
ToolbarToggle("Git", keys: "⌘G", isOn: layout.gitVisible) { model.perform(.toggleGit) }
.tip(layout.gitVisible
? Tooltip.stated("Source Control column: ", "shown", ". Click to hide it.")
: Tooltip.stated("Source Control column: ", "hidden", ". Click to show it."),
edge: .trailing)
ToolbarIconButton("?") { model.perform(.showShortcuts) }
.padding(.leading, 6)
.tip("Keyboard shortcuts.", edge: .trailing)
}
.fixedSize()
}
private func isSearch(_ overlay: Overlay) -> Bool {
if case .search = overlay { return true }
return false
}
}
+50
View File
@@ -0,0 +1,50 @@
import SwiftUI
/// Short confirmations, bottom-centred 44pt above the window edge. They may sit over an overlay.
struct ToastStack: View {
let toasts: ToastStore
var body: some View {
VStack(spacing: 8) {
ForEach(toasts.toasts) { toast in
ToastView(toast: toast)
}
}
.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .bottom)
.padding(.bottom, Metrics.toastBottom)
.allowsHitTesting(false)
}
}
private struct ToastView: View {
let toast: Toast
var body: some View {
HStack(spacing: 12) {
Image(systemName: "doc.on.doc").font(.system(size: 12, weight: .light)).foregroundStyle(Palette.amber)
Text(toast.title).typeRole(Typography.toastTitle).foregroundStyle(Palette.text1)
if let detail = toast.detail, !detail.isEmpty {
Text(detail)
.typeRole(Typography.toastReference)
.foregroundStyle(Palette.ink)
.lineLimit(1)
.truncationMode(.middle)
.padding(.horizontal, 7)
.padding(.vertical, 3)
.background(Palette.amber, in: RoundedRectangle(cornerRadius: Metrics.radiusSmall))
}
}
.padding(.horizontal, 14)
.padding(.vertical, 10)
.frame(maxWidth: 560)
.fixedSize()
.background(Palette.panel, in: RoundedRectangle(cornerRadius: Metrics.radiusMedium))
.overlay(RoundedRectangle(cornerRadius: Metrics.radiusMedium).strokeBorder(Palette.raised, lineWidth: Metrics.hairline))
.overlay(alignment: .leading) {
UnevenRoundedRectangle(topLeadingRadius: Metrics.radiusMedium, bottomLeadingRadius: Metrics.radiusMedium)
.fill(Palette.amber)
.frame(width: Metrics.accentRule)
}
.shadow(color: Palette.menuShadow, radius: Metrics.menuShadowRadius / 2, y: Metrics.menuShadowY)
}
}
+364
View File
@@ -0,0 +1,364 @@
import AppKit
import SwiftTerm
import SwiftUI
/// Reaches the hosting NSWindow for what SwiftUI cannot do: title bar geometry, the key router and window events.
struct WindowBridge: NSViewRepresentable {
let model: WorkspaceModel
/// Passed as values so a project switch re-runs `updateNSView`, which renames the window and the app.
let title: String
let hasProject: Bool
func makeCoordinator() -> WindowCoordinator {
WindowCoordinator(model: model)
}
func makeNSView(context: Context) -> BridgeView {
let view = BridgeView()
view.coordinator = context.coordinator
return view
}
func updateNSView(_ view: BridgeView, context: Context) {
context.coordinator.updateTitle(title, hasProject: hasProject)
context.coordinator.guardClose()
}
static func dismantleNSView(_ view: BridgeView, coordinator: WindowCoordinator) {
coordinator.detach()
}
final class BridgeView: NSView {
weak var coordinator: WindowCoordinator?
override func viewDidMoveToWindow() {
super.viewDidMoveToWindow()
if let window { coordinator?.attach(to: window) }
}
}
}
@MainActor
final class WindowCoordinator: NSObject {
let model: WorkspaceModel
private weak var window: NSWindow?
private var monitors: [Any] = []
private var observers: [NSObjectProtocol] = []
private let closeGuard = WindowCloseGuard()
/// Set once the unsaved prompt said yes, so the second close goes through.
private var closeApproved = false
private var isAskingToClose = false
init(model: WorkspaceModel) {
self.model = model
}
func attach(to window: NSWindow) {
guard self.window !== window else { return }
detach()
self.window = window
configure(window)
installMonitors()
observe(window)
closeGuard.shouldClose = { [weak self] window in self?.shouldClose(window) ?? true }
guardClose()
WorkspaceRegistry.register(model, window: window)
model.hooks.closeWindow = { [weak window] in window?.performClose(nil) }
layoutTrafficLights()
}
/// Puts the close guard in front of SwiftUI's window delegate; SwiftUI may set its own again later.
func guardClose() {
guard let window, window.delegate !== closeGuard else { return }
closeGuard.original = window.delegate
window.delegate = closeGuard
}
/// The first close only asks: unsaved files prompt, the note and session are written, then the window closes.
private func shouldClose(_ window: NSWindow) -> Bool {
if closeApproved { return true }
guard !isAskingToClose else { return false }
isAskingToClose = true
Task { @MainActor [weak self, weak window] in
guard let self else { return }
let approved = await self.model.prepareToClose()
self.isAskingToClose = false
guard approved, let window else { return }
self.closeApproved = true
window.close()
}
return false
}
func detach() {
monitors.forEach(NSEvent.removeMonitor)
monitors = []
observers.forEach(NotificationCenter.default.removeObserver)
observers = []
}
/// The launcher keeps the app's own name.
func updateTitle(_ title: String, hasProject: Bool) {
window?.title = title
AppName.set(hasProject ? title : AppName.standard)
}
private func configure(_ window: NSWindow) {
window.title = model.title
window.titleVisibility = .hidden
window.titlebarAppearsTransparent = true
window.styleMask.insert(.fullSizeContentView)
window.isMovableByWindowBackground = false
window.backgroundColor = NSColor(hex: 0x101720)
window.appearance = NSAppearance(named: .darkAqua)
window.minSize = Metrics.minimumWindow
window.tabbingMode = .disallowed
// A restored window would be a second project in this process.
window.isRestorable = false
}
// MARK: Traffic lights
/// Places the traffic lights at (14, 12) and grows the title-bar container to match, so the whole strip drags the window.
/// AppKit resets both on resize and full-screen changes, hence the repeat calls.
func layoutTrafficLights() {
guard let window,
let close = window.standardWindowButton(.closeButton),
let zoom = window.standardWindowButton(.zoomButton),
let container = close.superview?.superview else { return }
let buttons = [close, window.standardWindowButton(.miniaturizeButton), zoom].compactMap { $0 }
let spacing = zoom.frame.minX - (window.standardWindowButton(.miniaturizeButton)?.frame.maxX ?? close.frame.maxX)
let origin = Metrics.trafficLightOrigin
var frame = container.frame
frame.size.height = close.frame.height + origin.y * 2
frame.origin.y = window.frame.height - frame.height
container.frame = frame
for (index, button) in buttons.enumerated() {
button.setFrameOrigin(NSPoint(x: origin.x + CGFloat(index) * (button.frame.width + spacing),
y: (frame.height - button.frame.height) / 2))
}
}
private func observe(_ window: NSWindow) {
let center = NotificationCenter.default
let relayout: [Notification.Name] = [NSWindow.didResizeNotification, NSWindow.didEndLiveResizeNotification,
NSWindow.didExitFullScreenNotification, NSWindow.didBecomeKeyNotification]
for name in relayout {
observers.append(center.addObserver(forName: name, object: window, queue: .main) { [weak self] _ in
MainActor.assumeIsolated { self?.layoutTrafficLights() }
})
}
observers.append(center.addObserver(forName: NSWindow.willEnterFullScreenNotification, object: window, queue: .main) { [weak self] _ in
MainActor.assumeIsolated { self?.model.layout.isFullScreen = true }
})
observers.append(center.addObserver(forName: NSWindow.didExitFullScreenNotification, object: window, queue: .main) { [weak self] _ in
MainActor.assumeIsolated { self?.model.layout.isFullScreen = false }
})
observers.append(center.addObserver(forName: NSWindow.didResignKeyNotification, object: window, queue: .main) { [weak self] _ in
MainActor.assumeIsolated { self?.model.windowDidResignKey() }
})
observers.append(center.addObserver(forName: NSWindow.didBecomeKeyNotification, object: window, queue: .main) { [weak self] _ in
MainActor.assumeIsolated {
guard let self else { return }
WorkspaceRegistry.becameKey(self.model)
self.model.windowDidBecomeKey()
}
})
observers.append(center.addObserver(forName: NSWindow.willCloseNotification, object: window, queue: .main) { [weak self] _ in
MainActor.assumeIsolated {
guard let self else { return }
WorkspaceRegistry.unregister(self.model)
if WorkspaceRegistry.models.isEmpty { AppName.set(AppName.standard) }
self.model.windowWillClose()
self.detach()
}
})
}
// MARK: Keyboard and pointer
private func installMonitors() {
if let keys = NSEvent.addLocalMonitorForEvents(matching: .keyDown, handler: { [weak self] event in
let consumed = MainActor.assumeIsolated { self?.handleKey(event) ?? false }
return consumed ? nil : event
}) { monitors.append(keys) }
if let mouse = NSEvent.addLocalMonitorForEvents(matching: [.leftMouseDown, .rightMouseDown], handler: { [weak self] event in
MainActor.assumeIsolated { self?.handleMouseDown(event) }
return event
}) { monitors.append(mouse) }
}
/// Returns true when the key ran a command and must not reach the responder chain.
private func handleKey(_ event: NSEvent) -> Bool {
guard let window, event.window === window, window.attachedSheet == nil else { return false }
switch KeyRouter.route(KeyPress(event), context(in: window)) {
case .pass:
return false
case let .perform(command):
model.perform(command)
if case let .focus(panel) = command { takeFocus(for: panel, in: window) }
if case .focusNeighbour = command, let panel = model.layout.activePanel { takeFocus(for: panel, in: window) }
return true
}
}
/// Source Control and Explorer have no text view to focus, so they hold the keyboard by clearing first responder.
private func takeFocus(for panel: Panel, in window: NSWindow) {
if panel == .sourceControl || panel == .explorer { window.makeFirstResponder(nil) }
}
private func handleMouseDown(_ event: NSEvent) {
guard let window, event.window === window, model.root != nil, !model.overlay.isPresented else { return }
let point = event.locationInWindow
let height = window.contentView?.bounds.height ?? window.frame.height
guard height - point.y > Metrics.titleBar, point.y > Metrics.statusBar else { return }
guard let panel = model.layout.panel(atX: point.x, splitterMargin: 4) else { return }
model.pointerFocused(panel)
guard panel == .sourceControl || panel == .explorer else { return }
// A row click pulls the keyboard out of a text view in another column; otherwise typing lands there.
DispatchQueue.main.async { [weak self, weak window] in
guard let self, let window, let view = window.firstResponder as? NSView,
view is NSText || view is TerminalView else { return }
if self.column(of: view) != panel { window.makeFirstResponder(nil) }
}
}
private func column(of view: NSView) -> Panel? {
let frame = view.convert(view.visibleRect, to: nil)
return model.layout.panel(atX: frame.midX)
}
private func context(in window: NSWindow) -> KeyContext {
let responder = window.firstResponder
var owner = KeyboardOwner.workspace
var hasSelection = false
var editorSelection: TextSelectionInfo?
var seed = ""
if let text = responder as? NSTextView {
let column = column(of: text)
owner = .text(in: column)
let range = text.selectedRange()
hasSelection = range.length > 0
if hasSelection {
let string = text.string as NSString
let selected = string.substring(with: range)
seed = selected.split(separator: "\n", omittingEmptySubsequences: false).first.map(String.init)?
.trimmingCharacters(in: .whitespaces) ?? ""
if column == .editor {
editorSelection = TextSelectionInfo(text: selected, startLine: Self.line(at: range.location, in: string),
endLine: Self.line(at: range.location + range.length - 1, in: string))
}
}
} else if let terminal = responder as? TerminalView {
owner = .terminal
hasSelection = terminal.selectionActive
} else if let canvas = responder as? DiffCanvasView {
hasSelection = canvas.hasSelection
}
let editor = model.editor
let lineSelection = editor.flatMap { editor in
editor.selection.flatMap { $0.path == editor.activePath && $0.start != $0.end ? $0 : nil }
}
return KeyContext(
hasProject: model.root != nil,
overlay: OverlayKind(model.overlay.current, diffBusy: editor?.diffOverlayBusy ?? false),
owner: owner,
hasTextSelection: hasSelection,
editorTextSelection: editorSelection,
hasEditorLineSelection: lineSelection != nil,
activePanel: model.layout.activePanel,
focusZone: model.layout.focusZone,
recentFileCount: editor?.history.count ?? 0,
searchSeed: seed
)
}
private static func line(at location: Int, in string: NSString) -> Int {
let end = min(max(location, 0), string.length)
var line = 1
var index = 0
while index < end {
let range = string.range(of: "\n", options: [], range: NSRange(location: index, length: end - index))
guard range.location != NSNotFound else { break }
line += 1
index = range.location + 1
}
return line
}
}
extension KeyPress {
/// Reads `.` by key code, so ⌘. works on every keyboard layout.
init(_ event: NSEvent) {
let flags = event.modifierFlags.intersection(.deviceIndependentFlagsMask)
let key: Key
switch event.keyCode {
case 126: key = .up
case 125: key = .down
case 123: key = .left
case 124: key = .right
case 36, 76: key = .enter
case 53: key = .escape
case 47: key = .character(".")
default:
let typed = flags.contains(.command) ? event.charactersIgnoringModifiers : event.characters
key = typed.flatMap { $0.isEmpty ? nil : Key.character($0.lowercased()) } ?? .other
}
self.init(key, command: flags.contains(.command), shift: flags.contains(.shift),
option: flags.contains(.option), control: flags.contains(.control))
}
}
/// Stands in as the window's delegate to ask before a close, and hands every other message to SwiftUI's delegate.
final class WindowCloseGuard: NSObject, NSWindowDelegate {
weak var original: NSWindowDelegate?
var shouldClose: @MainActor (NSWindow) -> Bool = { _ in true }
override func responds(to selector: Selector!) -> Bool {
super.responds(to: selector) || original?.responds(to: selector) == true
}
override func forwardingTarget(for selector: Selector!) -> Any? {
original?.responds(to: selector) == true ? original : nil
}
func windowShouldClose(_ sender: NSWindow) -> Bool {
let allowed = MainActor.assumeIsolated { shouldClose(sender) }
guard allowed else { return false }
return original?.windowShouldClose?(sender) ?? true
}
}
/// Every open workspace window, for ⌘Q and the Dock menu.
@MainActor
enum WorkspaceRegistry {
private struct Entry {
weak var model: WorkspaceModel?
weak var window: NSWindow?
}
private static var entries: [Entry] = []
private static weak var lastKey: WorkspaceModel?
static var models: [WorkspaceModel] { entries.compactMap(\.model) }
static func register(_ model: WorkspaceModel, window: NSWindow) {
entries.removeAll { $0.model == nil || $0.model === model }
entries.append(Entry(model: model, window: window))
}
static func unregister(_ model: WorkspaceModel) {
entries.removeAll { $0.model == nil || $0.model === model }
if lastKey === model { lastKey = nil }
}
static func becameKey(_ model: WorkspaceModel) {
lastKey = model
}
/// The key window's workspace, else the one that was key last.
static var current: WorkspaceModel? {
if let key = NSApp.keyWindow, let entry = entries.first(where: { $0.window === key }) { return entry.model }
return lastKey
}
}
@@ -0,0 +1,93 @@
import SwiftUI
/// The launcher without a project; with one, the title bar, four columns and status bar, overlays above.
struct WorkspaceView: View {
let model: WorkspaceModel
var body: some View {
ZStack {
if model.root == nil {
if model.isReady { LauncherScreen(model: model) } else { Palette.editor }
} else {
workspace
}
ToastStack(toasts: model.toasts)
if model.isFocusFlashVisible { FocusFlash(model: model) }
}
.ignoresSafeArea()
}
private var workspace: some View {
GeometryReader { proxy in
VStack(spacing: 0) {
TitleBarView(model: model)
.zIndex(2)
Columns(model: model)
.frame(maxHeight: .infinity)
.zIndex(1)
StatusBarView(model: model)
}
.overlay { OverlayHost(model: model) }
.overlay {
if model.overlay.current == .launcher { RecentProjectsOverlay(model: model) }
}
.onAppear { model.layout.windowResized(width: proxy.size.width) }
.onChange(of: proxy.size.width) { _, width in model.layout.windowResized(width: width) }
}
}
}
/// The four columns and their splitters. The agent column is keyed by the project so its terminals respawn on a switch.
private struct Columns: View {
let model: WorkspaceModel
var body: some View {
let layout = model.layout
HStack(spacing: 0) {
if layout.gitVisible {
SourceControlColumn(model: model)
.frame(width: layout.widths.sourceControl)
.refreshFlash(model.refreshTick)
Splitter(onDrag: { layout.dragSourceControl(by: $0) }, onEnd: layout.endDrag)
}
ExplorerColumn(model: model)
.frame(width: layout.widths.explorer)
.refreshFlash(model.refreshTick)
Splitter(onDrag: { layout.dragExplorer(by: $0) }, onEnd: layout.endDrag)
EditorColumn(model: model)
.frame(minWidth: Metrics.minEditorWidth, maxWidth: .infinity)
.refreshFlash(model.refreshTick)
Splitter(onDrag: { layout.dragAgent(by: $0) }, onEnd: layout.endDrag)
AgentColumn(model: model)
.frame(width: layout.widths.agent)
.id(model.root)
}
.clipped()
}
}
/// ⌘R lightens a column for a moment and lets it settle back; each new tick replays it.
private struct RefreshFlash: ViewModifier {
let tick: Int
@State private var strength = 0.0
func body(content: Content) -> some View {
content
.overlay {
Palette.refreshFlash
.blendMode(.plusLighter)
.opacity(strength)
.allowsHitTesting(false)
}
.onChange(of: tick) {
strength = 1
withAnimation(.easeOut(duration: Metrics.refreshFlashDuration)) { strength = 0 }
}
}
}
extension View {
fileprivate func refreshFlash(_ tick: Int) -> some View {
modifier(RefreshFlash(tick: tick))
}
}
@@ -0,0 +1,33 @@
import AppKit
import SwiftUI
/// The root view of one window: owns the WorkspaceModel and wires it to the NSWindow and the menus.
public struct WorkspaceWindow: View {
@State private var model: WorkspaceModel
public init(root: URL?) {
_model = State(initialValue: WorkspaceModel(root: root, app: .live))
}
public var body: some View {
WorkspaceView(model: model)
.frame(minWidth: Metrics.minimumWindow.width, minHeight: Metrics.minimumWindow.height)
.background(Palette.editor)
.background(WindowBridge(model: model, title: model.title, hasProject: model.root != nil))
.preferredColorScheme(.dark)
.focusedSceneValue(\.workspace, model)
.task { await model.start() }
}
}
struct WorkspaceFocusKey: FocusedValueKey {
typealias Value = WorkspaceModel
}
extension FocusedValues {
/// The key window's workspace, for menu commands.
var workspace: WorkspaceModel? {
get { self[WorkspaceFocusKey.self] }
set { self[WorkspaceFocusKey.self] = newValue }
}
}