forked from ghostty-org/ghostty
-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathTerminalCommandPalette.swift
More file actions
401 lines (344 loc) · 13.9 KB
/
TerminalCommandPalette.swift
File metadata and controls
401 lines (344 loc) · 13.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
import SwiftUI
import Combine
import GhosttyKit
struct TerminalCommandPaletteView: View {
/// The surface that this command palette represents.
let surfaceView: Ghostty.SurfaceView
/// Set this to true to show the view, this will be set to false if any actions
/// result in the view disappearing.
@Binding var isPresented: Bool
/// The configuration so we can lookup keyboard shortcuts.
@ObservedObject var ghosttyConfig: Ghostty.Config
/// The update view model for showing update commands.
var updateViewModel: UpdateViewModel?
/// The callback when an action is submitted.
var onAction: ((String) -> Void)
@State private var query: String = ""
private enum WorktrunkPaletteMode: Hashable {
case root
case pickRepo
case createWorktree(repoID: UUID)
}
@State private var worktrunkMode: WorktrunkPaletteMode = .root
@State private var repoPromptResolution: TerminalRepoPromptResolution = .disabled(.noFocusedTerminal)
var body: some View {
ZStack {
if isPresented {
GeometryReader { geometry in
VStack {
Spacer().frame(height: geometry.size.height * 0.05)
ResponderChainInjector(responder: surfaceView)
.frame(width: 0, height: 0)
CommandPaletteView(
isPresented: $isPresented,
query: $query,
backgroundColor: ghosttyConfig.backgroundColor,
options: commandOptions
)
.id(worktrunkMode)
.zIndex(1) // Ensure it's on top
Spacer()
}
.frame(width: geometry.size.width, height: geometry.size.height, alignment: .top)
}
}
}
.onChange(of: isPresented) { newValue in
// When the command palette disappears we need to send focus back to the
// surface view we were overlaid on top of. There's probably a better way
// to handle the first responder state here but I don't know it.
if !newValue {
worktrunkMode = .root
query = ""
// Has to be on queue because onChange happens on a user-interactive
// thread and Xcode is mad about this call on that.
DispatchQueue.main.async {
surfaceView.window?.makeFirstResponder(surfaceView)
}
} else {
refreshRepoPromptResolution()
}
}
.onReceive(worktrunkStoreChangePublisher) { _ in
guard isPresented else { return }
refreshRepoPromptResolution()
}
}
/// All commands available in the command palette, combining update and terminal options.
private var commandOptions: [CommandOption] {
switch worktrunkMode {
case .root:
var options: [CommandOption] = []
// Updates always appear first
options.append(contentsOf: updateOptions)
options.append(contentsOf: githubOptions)
let rest = (worktrunkRootOptions + jumpOptions + terminalOptions).sorted { a, b in
let aNormalized = a.title.replacingOccurrences(of: ":", with: "\t")
let bNormalized = b.title.replacingOccurrences(of: ":", with: "\t")
let comparison = aNormalized.localizedCaseInsensitiveCompare(bNormalized)
if comparison != .orderedSame {
return comparison == .orderedAscending
}
if let aSortKey = a.sortKey, let bSortKey = b.sortKey {
return aSortKey < bSortKey
}
return false
}
options.append(contentsOf: rest)
return options
case .pickRepo:
return worktrunkPickRepoOptions
case .createWorktree:
return worktrunkCreateWorktreeOptions
}
}
/// Commands for installing or canceling available updates.
private var updateOptions: [CommandOption] {
var options: [CommandOption] = []
guard let updateViewModel, updateViewModel.state.isInstallable else {
return options
}
// We override the update available one only because we want to properly
// convey it'll go all the way through.
let title: String
if case .updateAvailable = updateViewModel.state {
title = "Update Ghostree and Restart"
} else {
title = updateViewModel.text
}
options.append(CommandOption(
title: title,
description: updateViewModel.description,
leadingIcon: updateViewModel.iconName ?? "shippingbox.fill",
badge: updateViewModel.badge,
emphasis: true
) {
(NSApp.delegate as? AppDelegate)?.updateController.installUpdate()
})
options.append(CommandOption(
title: "Cancel or Skip Update",
description: "Dismiss the current update process"
) {
updateViewModel.state.cancel()
})
return options
}
/// Custom commands from the command-palette-entry configuration.
private var terminalOptions: [CommandOption] {
guard let appDelegate = NSApp.delegate as? AppDelegate else { return [] }
return appDelegate.ghostty.config.commandPaletteEntries
.filter(\.isSupported)
.map { c in
let symbols = appDelegate.ghostty.config.keyboardShortcut(for: c.action)?.keyList
return CommandOption(
title: c.title,
description: c.description,
symbols: symbols
) {
onAction(c.action)
}
}
}
/// Commands for jumping to other terminal surfaces.
private var jumpOptions: [CommandOption] {
TerminalController.all.flatMap { controller -> [CommandOption] in
guard let window = controller.window else { return [] }
let color = (window as? TerminalWindow)?.tabColor
let displayColor = color != TerminalTabColor.none ? color : nil
return controller.surfaceTree.map { surface in
let terminalTitle = surface.title.isEmpty ? window.title : surface.title
let displayTitle: String
if let override = controller.titleOverride, !override.isEmpty {
displayTitle = override
} else if !terminalTitle.isEmpty {
displayTitle = terminalTitle
} else {
displayTitle = "Untitled"
}
let pwd = surface.pwd?.abbreviatedPath
let subtitle: String? = if let pwd, !displayTitle.contains(pwd) {
pwd
} else {
nil
}
return CommandOption(
title: "Focus: \(displayTitle)",
subtitle: subtitle,
leadingIcon: "rectangle.on.rectangle",
leadingColor: displayColor?.displayColor.map { Color($0) },
sortKey: AnySortKey(ObjectIdentifier(surface))
) {
NotificationCenter.default.post(
name: Ghostty.Notification.ghosttyPresentTerminal,
object: surface
)
}
}
}
}
private var terminalController: TerminalController? {
surfaceView.window?.windowController as? TerminalController
}
private var worktrunkStore: WorktrunkStore? {
(NSApp.delegate as? AppDelegate)?.worktrunkStore
}
private var worktrunkStoreChangePublisher: AnyPublisher<Void, Never> {
guard let worktrunkStore else {
return Empty<Void, Never>().eraseToAnyPublisher()
}
return worktrunkStore.objectWillChange
.debounce(for: .milliseconds(100), scheduler: RunLoop.main)
.map { _ in () }
.eraseToAnyPublisher()
}
private var githubOptions: [CommandOption] {
switch repoPromptResolution {
case .disabled(let reason):
return TerminalRepoPromptAction.menuActions.map { action in
CommandOption(
title: action.paletteTitle,
description: reason.description,
leadingIcon: "arrow.trianglehead.branch",
dismissOnSelect: false,
isEnabled: false
) {}
}
case .ready(let readyState):
var options: [CommandOption] = []
if let shortcut = readyState.shortcutAction {
options.append(CommandOption(
title: shortcut.action.paletteTitle,
description: shortcut.description,
leadingIcon: "arrow.trianglehead.branch"
) {
terminalController?.insertRepoPrompt(shortcut.action)
})
}
options.append(contentsOf: readyState.actionStates.map { state in
CommandOption(
title: state.action.paletteTitle,
description: state.description,
leadingIcon: "arrow.trianglehead.branch",
emphasis: state.action == readyState.primaryAction,
dismissOnSelect: state.isAvailable,
isEnabled: state.isAvailable
) {
terminalController?.insertRepoPrompt(state.action)
}
})
return options
}
}
private var worktrunkRootOptions: [CommandOption] {
guard terminalController != nil, worktrunkStore != nil else { return [] }
let newWorktree = CommandOption(
title: "Worktrunk: New worktree…",
description: "Pick a repo, then type a branch/worktree name and press Enter.",
dismissOnSelect: false
) {
worktrunkMode = .pickRepo
query = ""
}
return [newWorktree]
}
private func refreshRepoPromptResolution() {
guard let terminalController else {
repoPromptResolution = .disabled(.noFocusedTerminal)
return
}
Task { @MainActor in
let resolution = await TerminalRepoPrompt.resolve(
pwd: terminalController.focusedSurface?.pwd,
worktrunkStore: worktrunkStore
)
repoPromptResolution = resolution
}
}
private var worktrunkPickRepoOptions: [CommandOption] {
guard terminalController != nil, let store = worktrunkStore else { return [] }
var options: [CommandOption] = []
for repo in store.repositories {
options.append(CommandOption(
title: "Worktrunk: Use repo “\(repo.name)”",
subtitle: repo.path,
dismissOnSelect: false
) {
worktrunkMode = .createWorktree(repoID: repo.id)
query = ""
})
}
options.append(CommandOption(
title: "Worktrunk: Back",
dismissOnSelect: false,
pinned: true
) {
worktrunkMode = .root
query = ""
})
return options
}
private var worktrunkCreateWorktreeOptions: [CommandOption] {
guard let controller = terminalController, let store = worktrunkStore else { return [] }
guard case .createWorktree(let repoID) = worktrunkMode else { return [] }
let trimmed = query.trimmingCharacters(in: .whitespacesAndNewlines)
var options: [CommandOption] = []
if trimmed.isEmpty {
options.append(CommandOption(
title: "Worktrunk: Type branch/worktree name to create",
description: "Type the branch/worktree name in the palette query, then press Enter.",
dismissOnSelect: false
) {})
} else {
options.append(CommandOption(
title: "Worktrunk: Create worktree “\(trimmed)”",
emphasis: true,
dismissOnSelect: false
) { [trimmed] in
Task {
let created = await store.createWorktree(
repoID: repoID,
branch: trimmed,
base: nil,
createBranch: true
)
guard let created else { return }
await MainActor.run {
controller.openWorktreeFromPalette(atPath: created.path)
worktrunkMode = .root
query = ""
isPresented = false
}
}
})
}
options.append(CommandOption(
title: "Worktrunk: Back",
dismissOnSelect: false,
pinned: true
) {
worktrunkMode = .pickRepo
query = ""
})
options.append(CommandOption(
title: "Worktrunk: Cancel",
dismissOnSelect: false,
pinned: true
) {
worktrunkMode = .root
query = ""
})
return options
}
}
/// This is done to ensure that the given view is in the responder chain.
private struct ResponderChainInjector: NSViewRepresentable {
let responder: NSResponder
func makeNSView(context: Context) -> NSView {
let dummy = NSView()
DispatchQueue.main.async {
dummy.nextResponder = responder
}
return dummy
}
func updateNSView(_ nsView: NSView, context: Context) {}
}