Sources/Orgstar/ModeLine.swift
cmc Mac: route echo-area, alert, inspector and modeline strings through the catalog
8835742e44 12 hours ago153 lines · 6854 bytes
6 symbols in this file
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 timer, 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 @Environment(\.orgTheme) private var theme
13 @Environment(\.colorScheme) private var colorScheme
14 @Environment(\.appearsActive) private var appearsActive
15 @State private var words: Int?
16 @State private var characters = 0
17 @State private var crlf = false
18 @State private var branch: String?
19
20 var body: some View {
21 let text = commands.editor?.document.text ?? ""
22 let selection = commands.selection
23 HStack(spacing: 10) {
24 if let state = commands.editorState { StateTag(state: state) }
25 if session.isDirty {
26 Image(systemName: "circle.fill")
27 .font(.system(size: 6))
28 .foregroundStyle(.secondary)
29 .help("Unsaved changes")
30 .accessibilityLabel("Unsaved changes")
31 }
32 breadcrumb(at: selection.location)
33 Spacer(minLength: 12)
34 if let timer = TimerModel.shared.timer {
35 Menu {
36 Button(timer.paused == nil ? "Pause Timer" : "Continue Timer") { commands.editor?.run("org.timer.pause") }
37 Button("Stop Timer") { commands.editor?.run("org.timer.stop") }
38 } label: {
39 TimelineView(.periodic(from: .now, by: 1)) { context in
40 Text(timer.modeLine(now: context.date)).font(.system(.caption, design: .monospaced))
41 }
42 }
43 .menuStyle(.borderlessButton)
44 .menuIndicator(.hidden)
45 .fixedSize()
46 .help(timer.isCountdown ? "Countdown timer" : "Relative timer")
47 }
48 if selection.length > 0, let region = region(text, selection) {
49 Text("\(region.lines) lines, \(region.words) words, \(region.characters) chars")
50 .help("Selection (count-words-region)")
51 }
52 let position = TextStats.position(in: text, at: selection.location + selection.length)
53 Text("\(position.line):\(position.column)")
54 .help("Line \(position.line), column \(position.column)")
55 if let words {
56 Menu {
57 Text(TextStats.summary(words: words, characters: characters))
58 if selection.length > 0, let region = region(text, selection) {
59 Text(String(localized: "Selection: \(TextStats.summary(words: region.words, characters: region.characters))"))
60 }
61 } label: {
62 Text("\(words) words")
63 }
64 .menuStyle(.borderlessButton)
65 .menuIndicator(.hidden)
66 .fixedSize()
67 .help("Words in the file (count-words); click for characters and reading time")
68 }
69 ForEach(encodingNotes, id: \.self) { note in
70 Text(note).foregroundStyle(.orange)
71 }
72 if let branch {
73 Label(branch, systemImage: "arrow.triangle.branch")
74 .labelStyle(.titleAndIcon)
75 .help("Git branch")
76 }
77 }
78 .font(.system(.caption, design: .monospaced))
79 .monospacedDigit()
80 .lineLimit(1)
81 .foregroundStyle(theme.color("modeline-foreground") ?? .secondary)
82 .padding(.horizontal, 10)
83 .frame(height: 22)
84 .background { if let bg = theme.color("modeline-background", in: colorScheme) { bg } else { Rectangle().fill(.bar) } }
85 .overlay(alignment: .top) { Divider() }
86 .task(id: BranchKey(path: session.path, active: appearsActive)) {
87 // HEAD changes outside the app, so look again every few seconds while the window is
88 // active, and once when it becomes active again.
89 while appearsActive, !Task.isCancelled {
90 let path = session.path
91 branch = await Task.detached(priority: .utility) { path.flatMap(GitBranch.current) }.value
92 try? await Task.sleep(for: .seconds(5))
93 }
94 }
95 .task(id: WordsKey(path: session.path, version: session.editVersion)) {
96 guard let text = commands.editor?.document.text ?? session.document?.text else {
97 words = nil
98 return
99 }
100 let counts = await Task.detached(priority: .utility) { (TextStats.region(text), text.contains("\r\n")) }.value
101 (words, characters, crlf) = (counts.0.words, counts.0.characters, counts.1)
102 }
103 }
104
105 private struct BranchKey: Hashable {
106 var path: String?
107 var active: Bool
108 }
109
110 private struct WordsKey: Hashable {
111 var path: String?
112 var version: Int
113 }
114
115 /// The outline path of the heading containing `offset`, outermost first.
116 @ViewBuilder
117 private func breadcrumb(at offset: Int) -> some View {
118 let path = outlinePath(at: offset)
119 if !path.isEmpty {
120 Text(path.joined(separator: " › "))
121 .truncationMode(.head)
122 .foregroundStyle(theme.color("modeline-highlight") ?? .primary)
123 .help(path.joined(separator: " › "))
124 }
125 }
126
127 private func outlinePath(at offset: Int) -> [String] {
128 let outline = session.outline
129 var path: [String] = []
130 var current = outline.lastIndex { $0.start <= offset }
131 while let i = current {
132 path.insert(outline[i].title.isEmpty ? String(localized: "(untitled)") : outline[i].title, at: 0)
133 current = outline[i].parent
134 }
135 return path
136 }
137
138 private func region(_ text: String, _ range: NSRange) -> (lines: Int, words: Int, characters: Int)? {
139 let ns = text as NSString
140 guard NSMaxRange(range) <= ns.length else { return nil }
141 return TextStats.region(ns.substring(with: range))
142 }
143
144 /// Only what differs from UTF-8 with LF endings.
145 private var encodingNotes: [String] {
146 guard let document = session.document else { return [] }
147 var notes: [String] = []
148 if session.isReadOnly { notes.append(String(localized: "Read-only")) }
149 if document.source.hasBOM { notes.append(String(localized: "BOM", comment: "Modeline: the file starts with a byte order mark")) }
150 if crlf { notes.append(String(localized: "CRLF", comment: "Modeline: the file has Windows line endings")) }
151 return notes
152 }
153}