Sources/OrgstarMobile/SettingsScreen.swift

cf1c2de361bd33dc4f739537ae53e36a30076444
orgstar/Sources/OrgstarMobile/SettingsScreen.swift

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