Sources/OrgstarMobile/SettingsScreen.swift

fae1458f0e97c353b1b784f27c1a5bc1511b8078
orgstar/Sources/OrgstarMobile/SettingsScreen.swift

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