Sources/OrgstarMobile/SettingsScreen.swift

974c897ecb48b138c67b0c0e8115887978db2b89
orgstar/Sources/OrgstarMobile/SettingsScreen.swift

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