Repository Public
1import DesignSystem2import SettingsModel3import SwiftUI4import TerminalCore5import WorkspaceKit67/// Content of a window: title bar with tabs, banners, sidebar, pane canvas, inspector, search bar, status bar.8///9/// Motion rule of the whole file: `.animation` is attached to chrome only. The pane canvas snaps10/// (`snapGeometry`), because animating the size of a terminal would resize its PTY every frame.11struct WindowRootView: View {12 @Bindable var state: WindowState13 let model: AppModel14 /// Bumped by focus, tab and completion events; moves the ambient gradient.15 @State private var ambientPhase = 01617 var body: some View {18 let palette = model.palette(in: state)19 let chrome = model.chromeContext20 let motion = chrome.motion21 let zen = state.focusMode22 let showBar = state.showsTitleBar23 let showSidebar = state.sidebarVisible && !zen24 let showStatus = model.settings.showStatusBar && !zen25 let completion = state.focusedPane.flatMap { model.completions[$0] }26 VStack(spacing: 0) {27 if showBar {28 TabBarView(state: state, model: model, palette: palette)29 .onHover { inside in30 if !inside, state.chromePeek { state.chromePeek = false }31 state.controller?.syncTrafficLights()32 }33 .transition(motion.slide(.top))34 .zIndex(3)35 } else if !state.isQuickTerminal {36 // Focus mode: a thin strip still drags the window and brings the title bar back on hover.37 Color.clear.frame(height: 12)38 .contentShape(Rectangle())39 .background(WindowDragArea())40 .onHover { inside in41 if inside { state.chromePeek = true }42 state.controller?.syncTrafficLights()43 }44 .accessibilityHidden(true)45 }46 VStack(spacing: 4) {47 if state.isBroadcasting { BroadcastBanner(state: state, model: model).transition(motion.slide(.top)) }48 if let banner = state.banner {49 BannerView(banner: banner, palette: palette) { state.banner = nil }.transition(motion.slide(.top))50 }51 ForEach(Array(model.storageWarnings.enumerated()), id: \.offset) { _, warning in52 BannerView(banner: Banner(style: .warning, text: warning), palette: palette, dismiss: nil)53 }54 }55 .padding(.horizontal, zen ? 0 : Metrics.cardGap)56 .padding(.bottom, state.isBroadcasting || state.banner != nil || !model.storageWarnings.isEmpty ? 4 : 0)57 .zIndex(2)58 HStack(spacing: 0) {59 if showSidebar {60 SidebarView(state: state, model: model, palette: palette)61 .frame(width: Metrics.sidebarWidth)62 .transition(motion.slide(.leading))63 }64 PaneCanvasView(state: state, model: model, bottomInset: !showStatus && !state.searchVisible)65 .frame(maxWidth: .infinity, maxHeight: .infinity)66 .snapGeometry()67 if let inspector = state.inspector, !zen {68 InspectorCard(palette: palette) { InspectorView(kind: inspector, state: state, model: model) }69 .frame(width: Metrics.inspectorWidth)70 .padding(.trailing, Metrics.cardGap)71 .padding(.bottom, showStatus || state.searchVisible ? 0 : Metrics.cardGap)72 .transition(motion.slide(.trailing))73 }74 }75 if state.searchVisible { SearchBarView(state: state, model: model, palette: palette).transition(motion.slide(.bottom)) }76 if showStatus { StatusBarView(state: state, model: model, palette: palette).transition(motion.slide(.bottom)) }77 }78 .animation(motion.gentle, value: ChromeLayout(bar: showBar, sidebar: showSidebar, inspector: zen ? nil : state.inspector, status: showStatus,79 search: state.searchVisible, banner: state.banner?.id, broadcast: state.isBroadcasting))80 .background { ChromeBackground(palette: palette, settings: model.settings, phase: ambientPhase) }81 .foregroundStyle(palette.text)82 .tint(palette.accent)83 .overlay(alignment: .top) {84 ZStack(alignment: .top) {85 if state.paletteVisible {86 Color.black.opacity(palette.theme.isDark ? 0.28 : 0.14)87 .onTapGesture {88 state.paletteVisible = false89 model.focusCurrentPane(in: state)90 }91 .transition(.opacity)92 .accessibilityHidden(true)93 CommandPaletteView(state: state, model: model, palette: palette)94 .padding(.top, 72)95 .transition(motion.transition(.scale(scale: 0.96, anchor: .top).combined(with: .opacity).combined(with: .offset(y: -8))))96 }97 }98 .animation(motion.smooth, value: state.paletteVisible)99 }100 .environment(\.chrome, chrome)101 .sheet(item: $state.sheet) { sheet in102 SheetHost(sheet: sheet, state: state, model: model)103 }104 .ignoresSafeArea(.all, edges: .top)105 .onChange(of: state.selectedTabID) { _, _ in106 state.controller?.updateTitle()107 ambientPhase &+= 1108 }109 .onChange(of: state.focusedPane) { _, _ in ambientPhase &+= 1 }110 .onChange(of: completion?.id) { _, id in if id != nil { ambientPhase &+= 1 } }111 .onChange(of: model.tick) { _, _ in state.controller?.updateTitle() }112 .preferredColorScheme(model.theme.isDark ? .dark : .light)113 }114}115116/// Everything that changes the arrangement of the chrome; one animation follows all of it.117private struct ChromeLayout: Equatable {118 var bar: Bool119 var sidebar: Bool120 var inspector: InspectorKind?121 var status: Bool122 var search: Bool123 var banner: UUID?124 var broadcast: Bool125}126127/// The layer everything floats on: system material (or the solid theme colour), a tint that keeps128/// the identity of the theme, and the ambient accent light. Never drawn under terminal text.129struct ChromeBackground: View {130 let palette: Palette131 let settings: AppSettings132 let phase: Int133134 var body: some View {135 let opacity = settings.backgroundOpacity136 let plain = palette.theme.isHighContrast137 // A see-through window keeps its 1.0 meaning: blur only if the user asked for it.138 let material = opacity < 1 ? settings.backgroundBlur : (settings.chromeMaterial == .translucent && !plain)139 ZStack {140 if material { VisualEffectBackground() }141 palette.tintedChrome.opacity((material && opacity >= 1 ? 0.74 : 1) * opacity)142 if settings.ambientGradient && !plain { AmbientGradient(palette: palette, phase: phase) }143 }144 .ignoresSafeArea()145 }146}147148/// Side panels float as a card, like panes.149struct InspectorCard<Content: View>: View {150 let palette: Palette151 @ViewBuilder var content: Content152153 var body: some View {154 let shape = RoundedRectangle(cornerRadius: Radius.l, style: .continuous)155 content156 .background(palette.chrome)157 .clipShape(shape)158 .overlay(shape.strokeBorder(palette.hairline).allowsHitTesting(false))159 .background(shape.fill(palette.chrome).shadow(color: palette.cardShadow, radius: 4, y: 1))160 }161}162163struct BannerView: View {164 let banner: Banner165 let palette: Palette166 let dismiss: (() -> Void)?167168 var body: some View {169 let color: Color = banner.style == .error ? palette.danger : (banner.style == .warning ? palette.warning : palette.accent)170 let shape = RoundedRectangle(cornerRadius: Radius.m, style: .continuous)171 HStack(spacing: 8) {172 Image(systemName: banner.style == .info ? "info.circle.fill" : "exclamationmark.triangle.fill")173 .foregroundStyle(color)174 Text(banner.text).font(.system(size: TypeScale.body)).lineLimit(3).textSelection(.enabled)175 Spacer(minLength: 8)176 if let dismiss { IconButton(systemName: "xmark", help: "Dismiss", size: 10, action: dismiss) }177 }178 .padding(.horizontal, 12).padding(.vertical, 6)179 .background(shape.fill(palette.chrome))180 .background(shape.fill(color.opacity(0.16)))181 .overlay(shape.strokeBorder(color.opacity(0.35)))182 .accessibilityElement(children: .combine)183 }184}185186/// Permanent, unmistakable warning shown while keystrokes are mirrored to several sessions.187struct BroadcastBanner: View {188 let state: WindowState189 let model: AppModel190191 var body: some View {192 let palette = model.palette193 let count = state.selectedTab?.panes.count ?? 0194 HStack(spacing: 8) {195 Image(systemName: "dot.radiowaves.left.and.right")196 Text("BROADCAST INPUT — everything you type goes to all \(count) panes of this tab")197 .font(.system(size: TypeScale.body, weight: .semibold))198 Spacer()199 Button("Stop Broadcasting") { model.requestBroadcastToggle(in: state) }200 .controlSize(.small)201 }202 .padding(.horizontal, 12).padding(.vertical, 5)203 .foregroundStyle(Color.black)204 .background(RoundedRectangle(cornerRadius: Radius.m, style: .continuous).fill(palette.warning))205 .accessibilityLabel("Broadcast input is on for \(count) panes")206 }207}208209// MARK: Title bar210211/// Integrated title bar: native traffic lights, sidebar toggle, tabs, user-chosen toolbar buttons.212struct TabBarView: View {213 @Bindable var state: WindowState214 let model: AppModel215 let palette: Palette216 @Namespace private var selection217 @Environment(\.chrome) private var chrome218219 var body: some View {220 let metrics = ChromeMetrics.metrics(for: model.settings.density)221 let native = !state.isFullScreen && !state.isQuickTerminal222 let height = native && state.titleBarHeight > 0 ? state.titleBarHeight : CGFloat(metrics.titleBarHeight)223 HStack(spacing: 4) {224 // Room for the traffic lights (absent in full screen and in the quick terminal).225 Color.clear.frame(width: native ? state.trafficLightInset : 10)226 if !state.isQuickTerminal {227 IconButton(systemName: "sidebar.left", help: "Toggle Sidebar", shortcut: shortcut(.toggleSidebar), richTip: true,228 active: state.sidebarVisible) { model.perform(.toggleSidebar, in: state) }229 }230 ScrollViewReader { proxy in231 ScrollView(.horizontal, showsIndicators: false) {232 HStack(spacing: 3) {233 ForEach(state.tabs) { tab in234 TabItemView(tab: tab, state: state, model: model, metrics: metrics, selection: selection)235 .id(tab.id)236 .transition(chrome.motion.pop)237 }238 // The "new tab" button follows the last tab, as in a browser.239 IconButton(systemName: "plus", help: "New Tab", shortcut: shortcut(.newTab)) { model.perform(.newTab, in: state) }240 }241 .padding(.horizontal, 2)242 .animation(chrome.motion.smooth, value: state.tabs.map(\.id))243 .animation(chrome.motion.smooth, value: state.selectedTabID)244 }245 .onChange(of: state.selectedTabID) { _, id in246 if let id { withAnimation(chrome.motion.smooth) { proxy.scrollTo(id) } }247 }248 }249 if model.settings.privateMode {250 Label("Private", systemImage: "eye.slash").font(.system(size: TypeScale.footnote, weight: .medium))251 .padding(.horizontal, 8).padding(.vertical, 3)252 .background(Capsule().fill(palette.warning.opacity(0.16)))253 .foregroundStyle(palette.warning).help("Private mode: nothing about sessions is written to disk")254 .transition(chrome.motion.pop)255 }256 HStack(spacing: 2) {257 ForEach(model.toolbarActions) { action in258 let active = action.isActive(in: state)259 IconButton(systemName: action.symbol, help: action.title.replacingOccurrences(of: "…", with: ""), shortcut: shortcut(action),260 tint: active ? palette.accent : nil, richTip: true, tipAlignment: .bottomTrailing, active: active) {261 model.perform(action, in: state)262 }263 .transition(chrome.motion.pop)264 }265 }266 .animation(chrome.motion.smooth, value: model.settings.toolbarItems)267 Color.clear.frame(width: 6)268 }269 .frame(height: height)270 .background(WindowDragArea())271 .animation(chrome.motion.smooth, value: model.settings.privateMode)272 .contextMenu { ToolbarCustomizationMenu(model: model) }273 }274275 private func shortcut(_ action: AppAction) -> String { action.chord(in: model.settings)?.symbolic ?? "" }276}277278/// Check-list of the buttons of the title bar (right-click on the bar, also in Settings).279struct ToolbarCustomizationMenu: View {280 let model: AppModel281282 var body: some View {283 Section("Toolbar Buttons") {284 ForEach(AppAction.toolbarCandidates) { action in285 Toggle(isOn: Binding(get: { model.settings.toolbarItems.contains(action.rawValue) },286 set: { model.setToolbar(action, shown: $0) })) {287 Label(action.title.replacingOccurrences(of: "…", with: ""), systemImage: action.symbol)288 }289 }290 }291 Divider()292 Toggle("Expanded Title Bar", isOn: Binding(get: { model.settings.density == .expanded },293 set: { model.settings.density = $0 ? .expanded : .compact }))294 Button("Reset Toolbar") { model.settings.toolbarItems = AppSettings.defaultToolbarItems }295 }296}297298struct TabItemView: View {299 let tab: TabModel300 @Bindable var state: WindowState301 let model: AppModel302 let metrics: ChromeMetrics303 let selection: Namespace.ID304 @State private var hovering = false305 @Environment(\.chrome) private var chrome306307 var body: some View {308 let focus = tab.focusedPane ?? tab.layout.panes.first309 let palette = model.palette(for: focus)310 let selected = tab.id == state.selectedTabID311 let _ = model.tick312 let sessions = tab.layout.panes.map { model.session(for: $0) }313 let activity: SessionActivity = sessions.allSatisfy({ SessionActivity($0) == .ended }) ? .ended314 : (sessions.contains { $0?.hasForegroundJob == true } ? .busy : .idle)315 let completion = tab.layout.panes.compactMap { model.completions[$0] }.first316 let expanded = model.settings.density == .expanded317 let shape = RoundedRectangle(cornerRadius: expanded ? Radius.l : Radius.m, style: .continuous)318 HStack(spacing: 7) {319 StatusDot(activity: activity, palette: palette, pulse: completion?.id)320 VStack(alignment: .leading, spacing: 1) {321 Text(model.tabTitle(tab))322 .font(.system(size: TypeScale.body, weight: selected ? .semibold : .regular))323 .lineLimit(1)324 .foregroundStyle(selected ? palette.text : palette.secondary)325 if expanded {326 Text(subtitle(focus: focus, completion: completion))327 .font(.system(size: TypeScale.caption)).lineLimit(1)328 .foregroundStyle(palette.secondary)329 }330 }331 if tab.panes.count > 1 {332 Text("\(tab.panes.count)")333 .font(.system(size: TypeScale.caption, weight: .medium, design: .rounded))334 .padding(.horizontal, 4).padding(.vertical, 1)335 .background(Capsule().fill(palette.hover))336 .foregroundStyle(palette.secondary)337 .accessibilityLabel("\(tab.panes.count) panes")338 }339 if state.broadcastTabs.contains(tab.id) {340 Image(systemName: "dot.radiowaves.left.and.right").font(.system(size: TypeScale.caption)).foregroundStyle(palette.warning)341 }342 IconButton(systemName: "xmark", help: "Close Tab", size: 9) { model.closeTab(tab.id, in: state) }343 .opacity(hovering || selected ? 1 : 0)344 .frame(width: hovering || selected ? nil : 0)345 .clipped()346 }347 .padding(.leading, 10).padding(.trailing, hovering || selected ? 3 : 10)348 .frame(height: metrics.tabHeight)349 .frame(minWidth: 96, maxWidth: 240)350 .background {351 if selected {352 shape.fill(palette.background.opacity(palette.theme.isDark ? 0.9 : 1))353 .overlay(shape.strokeBorder(palette.hairline))354 .shadow(color: palette.cardShadow.opacity(0.6), radius: 2, y: 1)355 .matchedGeometryEffect(id: "selected-tab", in: selection)356 } else if hovering {357 shape.fill(palette.hover)358 }359 }360 .overlay(alignment: .bottom) {361 // Two-line tabs have no room under the text: the raised pill alone marks the selection.362 if selected && !expanded {363 Capsule().fill(palette.accent).frame(width: 18, height: 2).padding(.bottom, 2)364 .matchedGeometryEffect(id: "selected-tab-mark", in: selection)365 }366 }367 .contentShape(Rectangle())368 .onHover { hovering = $0 }369 .animation(chrome.motion.snappy, value: hovering)370 .onTapGesture { model.selectTab(tab.id, in: state) }371 .draggable("spterm-tab:" + tab.id.raw.uuidString)372 .dropDestination(for: String.self) { items, _ in373 guard let text = items.first else { return false }374 if text.hasPrefix("spterm-tab:"), let uuid = UUID(uuidString: String(text.dropFirst(11))),375 let target = state.tabs.firstIndex(where: { $0.id == tab.id }) {376 model.moveTab(TabID(uuid), in: state, to: target)377 return true378 }379 return false380 }381 .contextMenu {382 Button("Rename Tab…") { state.sheet = .renameTab(tab.id, current: tab.customTitle ?? model.tabTitle(tab)) }383 Button("Move Tab to New Window") { model.detachTab(tab.id, from: state) }.disabled(state.tabs.count < 2 || state.isQuickTerminal)384 Divider()385 Button("Close Tab") { model.closeTab(tab.id, in: state) }386 }387 .accessibilityElement(children: .combine)388 .accessibilityLabel("Tab \(model.tabTitle(tab)), \(activity.label)")389 .accessibilityAddTraits(selected ? [.isSelected, .isButton] : .isButton)390 }391392 private func subtitle(focus: PaneID?, completion: CommandCompletion?) -> String {393 if let completion { return "\(completion.name) ended · \(Formatters.duration(completion.duration))" }394 guard let focus, let session = model.session(for: focus) else { return " " }395 if !session.status.isRunning && session.status != .notStarted { return session.status.label }396 let program = session.foregroundProcessName ?? "shell"397 if let host = model.remoteHost(of: focus) { return "\(program) · \(host)" }398 return program399 }400}401402/// Lets the empty part of the tab bar drag the window and zoom it on double click, like a title bar.403struct WindowDragArea: NSViewRepresentable {404 final class DragView: NSView {405 override func mouseDown(with event: NSEvent) {406 if event.clickCount == 2 { window?.performZoom(nil) } else { window?.performDrag(with: event) }407 }408 }409 func makeNSView(context: Context) -> DragView { DragView() }410 func updateNSView(_ nsView: DragView, context: Context) {}411}412413// MARK: Status bar414415struct StatusBarView: View {416 let state: WindowState417 let model: AppModel418 let palette: Palette419 @Environment(\.chrome) private var chrome420421 var body: some View {422 let metrics = ChromeMetrics.metrics(for: model.settings.density)423 let _ = model.tick424 let pane = state.focusedPane425 let session = pane.flatMap { model.session(for: $0) }426 let completion = pane.flatMap { model.completions[$0] }427 HStack(spacing: 12) {428 if let session {429 if let host = pane.flatMap({ model.remoteHost(of: $0) }) {430 item("network", host, help: "Remote host", tint: palette.accent)431 } else {432 item("desktopcomputer", "local", help: "Local session")433 }434 // For a remote session the local directory of the ssh process means nothing: show a435 // directory only when it is local or was reported by the remote shell itself.436 let isRemote = pane.flatMap({ model.remoteHost(of: $0) }) != nil437 if let directory = session.workingDirectory, !isRemote || session.reportedRemoteHost != nil {438 item("folder", Formatters.abbreviate(path: directory), help: "Working directory")439 }440 if let pane, let branch = model.gitSummary(for: pane) {441 item("arrow.triangle.branch", branch, help: "Git branch")442 }443 Spacer(minLength: 8)444 if let completion {445 // Name and duration only: the exit status is unknown without shell integration.446 item("flag.checkered", "\(completion.name) ended · \(Formatters.duration(completion.duration))", help: "Last command", tint: palette.accent)447 .padding(.horizontal, 7).padding(.vertical, 2)448 .background(Capsule().fill(palette.accent.opacity(0.14)))449 .transition(chrome.motion.pop)450 }451 if session.hasForegroundJob, let name = session.foregroundProcessName {452 item("gearshape.2", name + (session.foregroundSince.map { " · " + Formatters.duration(Date().timeIntervalSince($0)) } ?? ""),453 help: "Running task", tint: palette.accent)454 if let resources = session.resources {455 item("cpu", String(format: "%.0f%% · %@", session.cpuLoad * 100, Formatters.bytes(resources.residentBytes)),456 help: "CPU and memory of the running task")457 }458 } else if session.status.isRunning {459 item("terminal", session.foregroundProcessName ?? "shell", help: "Foreground program")460 }461 if !session.status.isRunning { item("stop.circle", session.status.label, help: "Process state", tint: palette.warning) }462 item("textformat", "UTF-8", help: "Encoding")463 item("rectangle.dashed", "\(session.columns)×\(session.rows)", help: "Terminal size (columns × rows)")464 } else {465 Spacer()466 }467 }468 .font(.system(size: TypeScale.footnote))469 .monospacedDigit()470 .padding(.horizontal, 12)471 .frame(height: metrics.statusBarHeight)472 .animation(chrome.motion.smooth, value: completion?.id)473 }474475 private func item(_ icon: String, _ text: String, help: String, tint: Color? = nil) -> some View {476 HStack(spacing: 4) {477 Image(systemName: icon).font(.system(size: TypeScale.caption))478 Text(text).lineLimit(1).truncationMode(.middle)479 }480 .foregroundStyle(tint ?? palette.secondary)481 .help(help)482 .accessibilityElement(children: .combine)483 .accessibilityLabel("\(help): \(text)")484 }485}486487// MARK: Search488489struct SearchBarView: View {490 @Bindable var state: WindowState491 let model: AppModel492 let palette: Palette493 @FocusState private var focused: Bool494495 var body: some View {496 let shape = RoundedRectangle(cornerRadius: Radius.l, style: .continuous)497 HStack(spacing: 8) {498 Image(systemName: "magnifyingglass").foregroundStyle(palette.secondary)499 TextField("Search scrollback", text: $state.searchQuery)500 .textFieldStyle(.plain)501 .focused($focused)502 .onSubmit { model.search(in: state, forward: true) }503 .onChange(of: state.searchQuery) { _, _ in model.search(in: state, forward: true) }504 .accessibilityLabel("Search scrollback")505 Text(state.searchSummary).font(.system(size: TypeScale.footnote)).foregroundStyle(palette.secondary).monospacedDigit()506 Toggle("Aa", isOn: $state.searchCaseSensitive).toggleStyle(.button).controlSize(.small).help("Case sensitive")507 Toggle(".*", isOn: $state.searchRegex).toggleStyle(.button).controlSize(.small).help("Regular expression")508 IconButton(systemName: "chevron.up", help: "Previous match") { model.search(in: state, forward: false) }509 IconButton(systemName: "chevron.down", help: "Next match") { model.search(in: state, forward: true) }510 Menu {511 let counts = model.searchCounts(in: state)512 if counts.isEmpty { Text("No matches in open sessions") }513 ForEach(counts, id: \.pane) { entry in514 Button("\(entry.title) — \(entry.count)") {515 if let window = model.window(containing: entry.pane) {516 window.searchQuery = state.searchQuery517 window.searchVisible = true518 model.focus(entry.pane, in: window)519 window.controller?.window?.makeKeyAndOrderFront(nil)520 model.search(in: window, forward: true)521 }522 }523 }524 } label: { Text("All sessions") }525 .menuStyle(.borderlessButton).fixedSize().help("Matches in every open session")526 IconButton(systemName: "xmark", help: "Close search") { close() }527 }528 .padding(.horizontal, 12).frame(height: 34)529 .background(shape.fill(palette.chrome))530 .overlay(shape.strokeBorder(focused ? palette.accent.opacity(0.7) : palette.hairline))531 .padding(.horizontal, Metrics.cardGap).padding(.top, Metrics.cardGap)532 .padding(.bottom, model.settings.showStatusBar ? 0 : Metrics.cardGap)533 .onAppear { focused = true }534 .onChange(of: state.searchCaseSensitive) { _, _ in model.search(in: state, forward: true) }535 .onChange(of: state.searchRegex) { _, _ in model.search(in: state, forward: true) }536 .onExitCommand { close() }537 }538539 private func close() {540 state.searchVisible = false541 if let pane = state.focusedPane { model.session(for: pane)?.view.clearSearch() }542 model.focusCurrentPane(in: state)543 }544}545