Sources/OrgstarMobile/SettingsScreen.swift

a6efdda15d73f36320bc8a9004ecfbe07a6211f9
orgstar/Sources/OrgstarMobile/SettingsScreen.swift

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