Sources/OrgstarMobile/SettingsScreen.swift
486 lines · 23540 bytes
16 symbols in this file
1#if os(iOS)
2import OrgApp
3import OrgCore
4import OrgPresentation
5import SwiftUI
6import UIKit
7
8/// Where settings come from: a folder with the Mac's `config.toml` and `capture.toml`, kept in
9/// sync by iCloud Drive or another app.
10struct SettingsScreen: View {
11 let model: MobileModel
12 @State private var choosing = false
13 @State private var calendars: [CalendarChoice] = []
14 @State private var reminderLists: [CalendarChoice] = []
15 @State private var badges: Bool?
16 @State private var appIcon = AppIcons.id(alternateName: UIApplication.shared.alternateIconName)
17 @Environment(\.openURL) private var openURL
18 @Environment(\.scenePhase) private var scenePhase
19
20 private struct CalendarChoice {
21 let id: String
22 let title: String
23 let color: RGBA?
24 }
25
26 var body: some View {
27 Form {
28 Section {
29 NavigationLink {
30 ProScreen()
31 } label: {
32 ProBanner()
33 }
34 }
35 .listRowBackground(ProBanner.rowBackground)
36 Section {
37 let _ = model.settingsVersion
38 NavigationLink {
39 ThemePickerScreen(model: model, appearance: .light)
40 } label: {
41 LabeledContent("Light theme", value: ThemePickerScreen.current(.light).displayName)
42 }
43 NavigationLink {
44 ThemePickerScreen(model: model, appearance: .dark)
45 } label: {
46 LabeledContent("Dark theme", value: ThemePickerScreen.current(.dark).displayName)
47 }
48 NavigationLink {
49 AppIconScreen(current: $appIcon)
50 } label: {
51 LabeledContent("App icon", value: AppIcons.name(appIcon))
52 }
53 Picker("Body font", selection: Binding {
54 UserDefaults.standard.string(forKey: "themeBodyFont") ?? ""
55 } set: { model.set("themeBodyFont", to: .string($0)) }) {
56 let body = UserDefaults.standard.string(forKey: "themeBodyFont") ?? ""
57 Text("Same as Font").tag("")
58 Text("System").tag("system")
59 ForEach(Self.proportionalFamilies, id: \.self) { Text($0).tag($0) }
60 if !["", "system"].contains(body), !Self.proportionalFamilies.contains(body) { Text(body).tag(body) }
61 }
62 .pickerStyle(.navigationLink)
63 Picker("Text width", selection: Binding {
64 UserDefaults.standard.integer(forKey: "themeTextWidth")
65 } set: { model.set("themeTextWidth", to: .integer($0)) }) {
66 let width = UserDefaults.standard.integer(forKey: "themeTextWidth")
67 Text("Whole screen").tag(0)
68 ForEach([60, 70, 80, 90, 100, 120], id: \.self) { Text("\($0) columns").tag($0) }
69 if ![0, 60, 70, 80, 90, 100, 120].contains(width) { Text("\(width) columns").tag(width) }
70 }
71 } header: {
72 Text("Appearance")
73 } footer: {
74 Text("With a body font, prose uses it while tables, code, dates, tags and drawers keep the monospaced font. Text width keeps lines to that many columns, centred, on a screen wider than that.")
75 }
76 Section {
77 NavigationLink("Key Bar") { KeyBarSettings(model: model) }
78 } footer: {
79 Text("The buttons above the on-screen keyboard.")
80 }
81 if let workspace = model.workspace {
82 Section {
83 NavigationLink("Working Copy") { WorkingCopyScreen(workspace: workspace) }
84 } footer: {
85 Text("Sync folders that are git repositories in Working Copy.")
86 }
87 }
88 DecryptSettings()
89 Section {
90 let _ = model.settingsVersion
91 Toggle("Show days without entries", isOn: Binding {
92 OrgPreferences.agendaShowAllDates()
93 } set: { model.set("agendaShowAllDates", to: .bool($0)) })
94 .help(Text(verbatim: "org-agenda-show-all-dates"))
95 Toggle("Habits only today", isOn: Binding {
96 OrgPreferences.habitsOnlyForToday()
97 } set: { model.set("habitsOnlyForToday", to: .bool($0)) })
98 .help(Text(verbatim: "org-habit-show-habits-only-for-today"))
99 Toggle("Exclude archived tasks", isOn: Binding {
100 OrgPreferences.agendaExcludeArchives()
101 } set: { model.set("agendaExcludeArchives", to: .bool($0)) })
102 .help(Text(verbatim: "agenda-exclude-archives"))
103 Picker("Blocked entries", selection: Binding {
104 UserDefaults.standard.string(forKey: "agendaDimBlockedTasks") ?? "t"
105 } set: { model.set("agendaDimBlockedTasks", to: .string($0)) }) {
106 Text("Dimmed").tag("t")
107 Text("Hidden").tag("invisible")
108 Text("Shown as usual").tag("nil")
109 }
110 .help(Text(verbatim: "org-agenda-dim-blocked-tasks"))
111 } header: {
112 Text("Agenda")
113 } footer: {
114 Text("Archive files are the ones your agenda files archive to, named by #+ARCHIVE:, an :ARCHIVE: property or org-archive-location.")
115 }
116 Section {
117 let _ = model.settingsVersion
118 Toggle("Entries can't be done before their TODO children", isOn: Binding {
119 UserDefaults.standard.bool(forKey: "enforceTodoDependencies")
120 } set: { model.set("enforceTodoDependencies", to: .bool($0)) })
121 .help(Text(verbatim: "org-enforce-todo-dependencies"))
122 Toggle("Entries can't be done with unchecked boxes", isOn: Binding {
123 UserDefaults.standard.bool(forKey: "enforceTodoCheckboxDependencies")
124 } set: { model.set("enforceTodoCheckboxDependencies", to: .bool($0)) })
125 .help(Text(verbatim: "org-enforce-todo-checkbox-dependencies"))
126 } header: {
127 Text("TODO Dependencies")
128 } footer: {
129 Text("org-enforce-todo-dependencies and org-enforce-todo-checkbox-dependencies.")
130 }
131 Section {
132 let _ = model.settingsVersion
133 Picker("Completion list opens", selection: Binding {
134 UserDefaults.standard.string(forKey: "completionAuto") ?? "preset"
135 } set: { model.set("completionAuto", to: .string($0)) }) {
136 Text("As the keys do (by itself with Doom)").tag("preset")
137 Text("By itself as you type").tag("on")
138 Text("Only with a key").tag("off")
139 }
140 .help(Text(verbatim: "completion-auto"))
141 let delay = OrgPreferences.completion().delay
142 Stepper("After a pause of \(Int(delay * 1000)) ms", value: Binding {
143 Int(delay * 1000)
144 } set: { model.set("completionAutoDelay", to: .integer($0)) }, in: 0...2000, step: 50)
145 .help(Text(verbatim: "completion-auto-delay"))
146 let prefix = OrgPreferences.completion().prefix
147 Stepper("Once \(prefix) characters are typed", value: Binding {
148 prefix
149 } set: { model.set("completionAutoPrefix", to: .integer($0)) }, in: 1...10)
150 .help(Text(verbatim: "completion-auto-prefix"))
151 Picker("Candidates", selection: Binding {
152 UserDefaults.standard.string(forKey: "completionStyle") ?? "preset"
153 } set: { model.set("completionStyle", to: .string($0)) }) {
154 Text("As the keys do (letters in order with Doom)").tag("preset")
155 Text("Start with what's typed").tag("prefix")
156 Text("Have its letters in order, best first").tag("fuzzy")
157 }
158 .help(Text(verbatim: "completion-style"))
159 Toggle("The list offers words from open files and folders", isOn: Binding {
160 OrgPreferences.completion().words
161 } set: { model.set("completionWords", to: .bool($0)) })
162 .help(Text(verbatim: "completion-words"))
163 } header: {
164 Text("Completion")
165 } footer: {
166 Text("Doom's keys open the list by itself and match letters in order, as Doom's corfu does; the Emacs and Mac keys do neither unless set here. Expand Word completes the word before the caret from your files whatever is set.")
167 }
168 calendarSection
169 reminderSection
170 Section {
171 if badges == true {
172 LabeledContent("Overdue count on icon", value: String(localized: "On"))
173 } else if badges == false {
174 Button("Show Overdue Count on Icon…") {
175 Task {
176 if await model.badgesEnabled(asking: true) {
177 badges = true
178 await model.updateWidgets()
179 } else if let url = URL(string: UIApplication.openNotificationSettingsURLString) {
180 openURL(url)
181 }
182 }
183 }
184 }
185 } header: {
186 Text("Badge")
187 } footer: {
188 if badges == false { Text("Turn on Badges in orgstar's notification settings.") }
189 }
190 Section {
191 LabeledContent("Folder", value: model.configFolder?.lastPathComponent ?? String(localized: "none.folder", defaultValue: "None", comment: "No configuration folder chosen"))
192 Button(model.configFolder == nil ? "Choose Folder…" : "Choose Another Folder…") { choosing = true }
193 if model.configFolder != nil {
194 NavigationLink("Edit config.toml") { ConfigFileEditor(model: model) }
195 }
196 NavigationLink("Import from Emacs") { EmacsImportScreen(model: model) }
197 if model.configFolder != nil {
198 Button("Stop Using This Folder", role: .destructive) { model.setConfigFolder(nil) }
199 }
200 ForEach(model.configProblems, id: \.self) { Text($0).foregroundStyle(.red) }
201 } header: {
202 Text("Configuration")
203 } footer: {
204 Text("A folder with config.toml and capture.toml, such as a synced copy of ~/.config/orgstar from your Mac. Changes to them apply as they sync.")
205 }
206 Section("In Use") {
207 let _ = model.settingsVersion
208 LabeledContent("TODO keywords", value: todoKeywords)
209 LabeledContent("Agenda", value: agenda)
210 LabeledContent("Notifications", value: OrgPreferences.reminders() ? String(localized: "\(OrgPreferences.reminderLead()) min before") : String(localized: "Off"))
211 LabeledContent("Capture templates", value: CaptureTemplates.load().templates.map(\.key).joined(separator: " "))
212 LabeledContent("Theme", value: themeInUse)
213 LabeledContent("Font", value: font)
214 }
215 Section {
216 NavigationLink {
217 AboutScreen(appIcon: appIcon)
218 } label: {
219 Label("About orgstar", systemImage: "info.circle")
220 }
221 }
222 }
223 .navigationTitle("Settings")
224 // Read again on return from the Settings app.
225 .task(id: scenePhase) { badges = await model.badgesEnabled(asking: false) }
226 .fileImporter(isPresented: $choosing, allowedContentTypes: [.folder]) { result in
227 if case .success(let url) = result { model.setConfigFolder(url) }
228 }
229 }
230
231 /// The two palettes' names, and the theme file's when there is one.
232 private var themeInUse: String {
233 let names = "\(ThemePickerScreen.current(.light).displayName) / \(ThemePickerScreen.current(.dark).displayName)"
234 guard let file = UserDefaults.standard.string(forKey: "themeFile"), !file.isEmpty else { return names }
235 return "\(names), \(file)"
236 }
237
238 /// `calendar-events` and `calendar-event-calendars`, written to config.toml.
239 private var calendarSection: some View {
240 let _ = model.settingsVersion
241 let on = OrgPreferences.calendarEvents()
242 let chosen = OrgPreferences.calendarEventCalendars()
243 return Section {
244 Toggle("Show events from Calendar", isOn: Binding {
245 on
246 } set: { value in
247 guard !value || ProAccess.shared.allows(.calendar) else { return }
248 model.set("calendarEvents", to: .bool(value))
249 if value { Task { await requestCalendars() } }
250 })
251 if on {
252 if !CalendarEvents.isAuthorized {
253 Button("Allow Access to Calendars…") { Task { await requestCalendars() } }
254 }
255 ForEach(calendars, id: \.id) { calendar in
256 let shown = CalendarEvents.chooses(id: calendar.id, title: calendar.title, chosen: chosen)
257 Button {
258 toggle(calendar.title, shown: shown, chosen: chosen)
259 } label: {
260 HStack {
261 Circle().fill(calendar.color?.swiftUI ?? .secondary).frame(width: 10, height: 10)
262 Text(calendar.title).foregroundStyle(.primary)
263 Spacer()
264 if shown { Image(systemName: "checkmark").foregroundStyle(Color.accentColor) }
265 }
266 }
267 .tint(.primary)
268 }
269 }
270 } header: {
271 Text("Calendar")
272 } footer: {
273 Text(on ? "Events from the checked calendars show in the agenda. Tap one to edit it." : "Show events from Calendar in the agenda.")
274 }
275 .task(id: on) { loadCalendars() }
276 }
277
278 /// `agenda-reminders` and `agenda-reminder-lists`, written to config.toml.
279 private var reminderSection: some View {
280 let _ = model.settingsVersion
281 let on = OrgPreferences.agendaReminders()
282 let chosen = OrgPreferences.agendaReminderLists()
283 return Section {
284 Toggle("Show reminders from Reminders", isOn: Binding {
285 on
286 } set: { value in
287 guard !value || ProAccess.shared.allows(.calendar) else { return }
288 model.set("agendaReminders", to: .bool(value))
289 if value { Task { await requestReminders() } }
290 })
291 if on {
292 if !ReminderLists.isAuthorized {
293 Button("Allow Access to Reminders…") { Task { await requestReminders() } }
294 }
295 ForEach(reminderLists, id: \.id) { list in
296 let shown = CalendarEvents.chooses(id: list.id, title: list.title, chosen: chosen)
297 Button {
298 toggle(list.title, shown: shown, chosen: chosen, among: reminderLists, key: "agendaReminderLists")
299 } label: {
300 HStack {
301 Circle().fill(list.color?.swiftUI ?? .secondary).frame(width: 10, height: 10)
302 Text(list.title).foregroundStyle(.primary)
303 Spacer()
304 if shown { Image(systemName: "checkmark").foregroundStyle(Color.accentColor) }
305 }
306 }
307 .tint(.primary)
308 }
309 }
310 } header: {
311 Text("Reminders")
312 } footer: {
313 Text(on ? "Incomplete reminders with a due date from the checked lists show in the agenda, read-only; overdue ones under today."
314 : "Show reminders from Reminders in the agenda, read-only.")
315 }
316 .task(id: on) { loadReminderLists() }
317 }
318
319 private func requestReminders() async {
320 _ = await model.reminderLists.requestAccess()
321 loadReminderLists()
322 model.reloadConfig()
323 }
324
325 private func loadReminderLists() {
326 reminderLists = model.reminderLists.lists()
327 .sorted { $0.title.localizedStandardCompare($1.title) == .orderedAscending }
328 .map { CalendarChoice(id: $0.id, title: $0.title, color: $0.color) }
329 }
330
331 private func requestCalendars() async {
332 _ = await model.calendarEvents.requestAccess()
333 loadCalendars()
334 model.reloadConfig()
335 }
336
337 private func loadCalendars() {
338 calendars = model.calendarEvents.calendars()
339 .sorted { $0.title.localizedStandardCompare($1.title) == .orderedAscending }
340 .map { CalendarChoice(id: $0.id, title: $0.title, color: $0.color) }
341 }
342
343 /// Shows or hides a calendar's events or a list's reminders; with every one checked the
344 /// setting is empty. The last checked one stays checked, as an empty list means every one.
345 private func toggle(_ title: String, shown: Bool, chosen: [String], among choices: [CalendarChoice]? = nil, key: String = "calendarEventCalendars") {
346 let choices = choices ?? calendars
347 var titles = choices.filter { CalendarEvents.chooses(id: $0.id, title: $0.title, chosen: chosen) }.map(\.title)
348 titles.removeAll { $0 == title }
349 if !shown { titles.append(title) }
350 guard !titles.isEmpty else { return }
351 let value = Set(titles) == Set(choices.map(\.title)) ? "" : titles.joined(separator: ", ")
352 model.set(key, to: .string(value))
353 }
354
355 /// Installed proportional font families, for prose.
356 private static let proportionalFamilies: [String] = UIFont.familyNames.sorted().filter { family in
357 guard let name = UIFont.fontNames(forFamilyName: family).first, let font = UIFont(name: name, size: 13) else { return false }
358 return !font.fontDescriptor.symbolicTraits.contains(.traitMonoSpace)
359 }
360
361 /// The span and start day, worded as the Mac's Settings word the start.
362 private var agenda: String {
363 let offset = OrgPreferences.agendaStartOffset()
364 let span = String(localized: "\(OrgPreferences.agendaSpan()) days", comment: "Agenda span in Settings ▸ In Use")
365 let start = offset == 0 ? String(localized: "starting today", comment: "Agenda start in Settings ▸ In Use")
366 : offset < 0 ? String(localized: "starting \(-offset) days before today", comment: "Agenda start in Settings ▸ In Use")
367 : String(localized: "starting \(offset) days after today", comment: "Agenda start in Settings ▸ In Use")
368 return String(localized: "\(span), \(start)", comment: "Agenda span and start in Settings ▸ In Use")
369 }
370
371 /// The theme's family, or the system's monospaced font when it's unset or not on the device.
372 private var font: String {
373 let spec = model.theme
374 let family = spec.font.isEmpty || UIFont.fontNames(forFamilyName: spec.font).isEmpty ? String(localized: "System monospaced") : spec.font
375 return !spec.font.isEmpty && family != spec.font ? String(localized: "\(family), \(spec.fontSize) pt (\(spec.font) isn't installed)")
376 : String(localized: "\(family), \(spec.fontSize) pt")
377 }
378
379 private var todoKeywords: String {
380 OrgPreferences.orgSettings().todoSequences.map { ($0.active.map(\.name) + ["|"] + $0.done.map(\.name)).joined(separator: " ") }
381 .joined(separator: "; ")
382 }
383}
384/// The orgstar+ row at the top of Settings.
385private struct ProBanner: View {
386 private var access: ProAccess { .shared }
387
388 static var rowBackground: some View {
389 ZStack {
390 Color(uiColor: .secondarySystemGroupedBackground)
391 LinearGradient.plusGold.opacity(0.22)
392 }
393 }
394
395 var body: some View {
396 HStack(spacing: 14) {
397 PlusBadge()
398 VStack(alignment: .leading, spacing: 3) {
399 Text(verbatim: "orgstar+").font(.headline)
400 Group {
401 if access.isUnlocked {
402 Text("Unlocked. Thanks for supporting orgstar.")
403 } else {
404 Text("Export, encryption, widgets, the Watch app and more")
405 }
406 }
407 .font(.subheadline)
408 .foregroundStyle(.secondary)
409 }
410 }
411 .padding(.vertical, 6)
412 }
413}
414
415/// The configuration folder's `config.toml` as plain text, saved when you tap Save or leave.
416struct ConfigFileEditor: View {
417 let model: MobileModel
418 @State private var text = ""
419 @State private var saved: String?
420
421 var body: some View {
422 PlainTextView(text: $text)
423 .navigationTitle("config.toml")
424 .navigationBarTitleDisplayMode(.inline)
425 .toolbar {
426 Button("Save") { save() }.disabled(text == saved)
427 }
428 .safeAreaInset(edge: .bottom) {
429 let _ = model.settingsVersion
430 if !model.configProblems.isEmpty {
431 VStack(alignment: .leading, spacing: 4) {
432 ForEach(model.configProblems, id: \.self) { Text($0) }
433 }
434 .font(.footnote)
435 .foregroundStyle(.red)
436 .padding()
437 .frame(maxWidth: .infinity, alignment: .leading)
438 .background(.bar)
439 }
440 }
441 .onAppear {
442 guard saved == nil else { return }
443 text = model.configText() ?? UserConfig.defaultTemplate
444 saved = text
445 }
446 .onDisappear { save() }
447 }
448
449 private func save() {
450 guard text != saved else { return }
451 if model.saveConfig(text) { saved = text }
452 }
453}
454
455/// A monospaced text view without smart quotes, dashes or autocorrection, which would break TOML.
456private struct PlainTextView: UIViewRepresentable {
457 @Binding var text: String
458
459 func makeUIView(context: Context) -> UITextView {
460 let view = UITextView()
461 view.font = .monospacedSystemFont(ofSize: UIFont.preferredFont(forTextStyle: .footnote).pointSize, weight: .regular)
462 view.adjustsFontForContentSizeCategory = true
463 view.autocorrectionType = .no
464 view.autocapitalizationType = .none
465 view.smartQuotesType = .no
466 view.smartDashesType = .no
467 view.smartInsertDeleteType = .no
468 view.spellCheckingType = .no
469 view.keyboardDismissMode = .interactive
470 view.delegate = context.coordinator
471 return view
472 }
473
474 func updateUIView(_ view: UITextView, context: Context) {
475 if view.text != text { view.text = text }
476 }
477
478 func makeCoordinator() -> Coordinator { Coordinator(text: $text) }
479
480 final class Coordinator: NSObject, UITextViewDelegate {
481 var text: Binding<String>
482 init(text: Binding<String>) { self.text = text }
483 func textViewDidChange(_ view: UITextView) { text.wrappedValue = view.text }
484 }
485}
486#endif