Sources/OrgstarMobile/SettingsScreen.swift

c4d5cb219ab6fe95c4d840f835a207f3da933181
orgstar/Sources/OrgstarMobile/SettingsScreen.swift

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