Sources/OrgstarMobile/SettingsScreen.swift

29b770d6b2f9edcc6607ab4a46db6c659dd12c1d
orgstar/Sources/OrgstarMobile/SettingsScreen.swift

485 lines · 23510 bytes

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

Global

⌘K
Command palette & jump
/
Focus search
?
Show this help
g d
Dashboard
g e
Explore repositories
g n
Notifications

Repository & editor

t
Find file in repository
y
Copy immutable SHA permalink
g c
Code tab
g i
Issues tab
g m
Merge requests tab
g b
Builds tab
⌘↵
Submit active form