Sources/Orgstar/ModeLine.swift
166 lines · 7445 bytes
1import OrgApp
2import OrgCore
3import OrgPresentation
4import SwiftUI
5
6/// The line under the editor: evil state, unsaved mark and the headings around the caret on
7/// the left; the running clock, the selection's counts, line and column, the file's words,
8/// anything unusual about its encoding and the git branch on the right.
9struct ModeLine: View {
10 let session: DocumentSession
11 let commands: AppCommands
12 let clock: ClockModel
13 /// Runs an app command (clock out, go to the clocked entry).
14 let perform: (String) -> Void
15 @Environment(\.orgTheme) private var theme
16 @Environment(\.colorScheme) private var colorScheme
17 @State private var words: Int?
18 @State private var characters = 0
19 @State private var crlf = false
20 @State private var branch: String?
21
22 var body: some View {
23 let text = commands.editor?.document.text ?? ""
24 let selection = commands.selection
25 HStack(spacing: 10) {
26 if let state = commands.editorState { StateTag(state: state) }
27 if session.isDirty {
28 Image(systemName: "circle.fill")
29 .font(.system(size: 6))
30 .foregroundStyle(.secondary)
31 .help("Unsaved changes")
32 .accessibilityLabel("Unsaved changes")
33 }
34 breadcrumb(at: selection.location)
35 Spacer(minLength: 12)
36 if let running = clock.running {
37 Menu {
38 Button("Clock Out") { perform("app.clock.out") }
39 Button("Cancel Clock") { perform("app.clock.cancel") }
40 Button("Go to Clocked Entry") { perform("app.clock.goto") }
41 } label: {
42 TimelineView(.periodic(from: .now, by: 30)) { context in
43 Text("⏱ \(clockElapsed(running, now: context.date)) \(running.heading)")
44 .font(.system(.caption, design: .monospaced))
45 }
46 }
47 .menuStyle(.borderlessButton)
48 .menuIndicator(.hidden)
49 .fixedSize()
50 .foregroundStyle(theme.color("modeline-highlight") ?? .primary)
51 .help("Clocked in since \(running.startedAt.formatted(date: .omitted, time: .shortened))")
52 }
53 if let timer = TimerModel.shared.timer {
54 Menu {
55 Button(timer.paused == nil ? "Pause Timer" : "Continue Timer") { commands.editor?.run("org.timer.pause") }
56 Button("Stop Timer") { commands.editor?.run("org.timer.stop") }
57 } label: {
58 TimelineView(.periodic(from: .now, by: 1)) { context in
59 Text(timer.modeLine(now: context.date)).font(.system(.caption, design: .monospaced))
60 }
61 }
62 .menuStyle(.borderlessButton)
63 .menuIndicator(.hidden)
64 .fixedSize()
65 .help(timer.isCountdown ? "Countdown timer" : "Relative timer")
66 }
67 if selection.length > 0, let region = region(text, selection) {
68 Text("\(region.lines) lines, \(region.words) words, \(region.characters) chars")
69 .help("Selection (count-words-region)")
70 }
71 let position = TextStats.position(in: text, at: selection.location + selection.length)
72 Text("\(position.line):\(position.column)")
73 .help("Line \(position.line), column \(position.column)")
74 if let words {
75 Menu {
76 Text(TextStats.summary(words: words, characters: characters))
77 if selection.length > 0, let region = region(text, selection) {
78 Text("Selection: " + TextStats.summary(words: region.words, characters: region.characters))
79 }
80 } label: {
81 Text("\(words.formatted()) \(words == 1 ? "word" : "words")")
82 }
83 .menuStyle(.borderlessButton)
84 .menuIndicator(.hidden)
85 .fixedSize()
86 .help("Words in the file (count-words); click for characters and reading time")
87 }
88 ForEach(encodingNotes, id: \.self) { note in
89 Text(note).foregroundStyle(.orange)
90 }
91 if let branch {
92 Label(branch, systemImage: "arrow.triangle.branch")
93 .labelStyle(.titleAndIcon)
94 .help("Git branch")
95 }
96 }
97 .font(.system(.caption, design: .monospaced))
98 .monospacedDigit()
99 .lineLimit(1)
100 .foregroundStyle(theme.color("modeline-foreground") ?? .secondary)
101 .padding(.horizontal, 10)
102 .frame(height: 22)
103 .background { if let bg = theme.color("modeline-background", in: colorScheme) { bg } else { Rectangle().fill(.bar) } }
104 .overlay(alignment: .top) { Divider() }
105 .task(id: session.path) {
106 // HEAD changes outside the app, so look again every few seconds.
107 while !Task.isCancelled {
108 let path = session.path
109 branch = await Task.detached(priority: .utility) { path.flatMap(GitBranch.current) }.value
110 try? await Task.sleep(for: .seconds(5))
111 }
112 }
113 .task(id: WordsKey(path: session.path, version: session.editVersion)) {
114 guard let text = commands.editor?.document.text ?? session.document?.text else {
115 words = nil
116 return
117 }
118 let counts = await Task.detached(priority: .utility) { (TextStats.region(text), text.contains("\r\n")) }.value
119 (words, characters, crlf) = (counts.0.words, counts.0.characters, counts.1)
120 }
121 }
122
123 private struct WordsKey: Hashable {
124 var path: String?
125 var version: Int
126 }
127
128 /// The outline path of the heading containing `offset`, outermost first.
129 @ViewBuilder
130 private func breadcrumb(at offset: Int) -> some View {
131 let path = outlinePath(at: offset)
132 if !path.isEmpty {
133 Text(path.joined(separator: " › "))
134 .truncationMode(.head)
135 .foregroundStyle(theme.color("modeline-highlight") ?? .primary)
136 .help(path.joined(separator: " › "))
137 }
138 }
139
140 private func outlinePath(at offset: Int) -> [String] {
141 let outline = session.outline
142 var path: [String] = []
143 var current = outline.lastIndex { $0.start <= offset }
144 while let i = current {
145 path.insert(outline[i].title.isEmpty ? "(untitled)" : outline[i].title, at: 0)
146 current = outline[i].parent
147 }
148 return path
149 }
150
151 private func region(_ text: String, _ range: NSRange) -> (lines: Int, words: Int, characters: Int)? {
152 let ns = text as NSString
153 guard NSMaxRange(range) <= ns.length else { return nil }
154 return TextStats.region(ns.substring(with: range))
155 }
156
157 /// Only what differs from UTF-8 with LF endings.
158 private var encodingNotes: [String] {
159 guard let document = session.document else { return [] }
160 var notes: [String] = []
161 if session.isReadOnly { notes.append("Read-only") }
162 if document.source.hasBOM { notes.append("BOM") }
163 if crlf { notes.append("CRLF") }
164 return notes
165 }
166}