Sources/OrgstarMobile/SettingsScreen.swift

317 lines · 14276 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    @Environment(\.openURL) private var openURL
 17    @Environment(\.scenePhase) private var scenePhase
 18
 19    private struct CalendarChoice {
 20        let id: String
 21        let title: String
 22        let color: RGBA?
 23    }
 24
 25    var body: some View {
 26        Form {
 27            Section {
 28                LabeledContent("Folder", value: model.configFolder?.lastPathComponent ?? "None")
 29                Button(model.configFolder == nil ? "Choose Folder…" : "Choose Another Folder…") { choosing = true }
 30                if model.configFolder != nil {
 31                    NavigationLink("Edit config.toml") { ConfigFileEditor(model: model) }
 32                }
 33                NavigationLink("Import from Emacs") { EmacsImportScreen(model: model) }
 34                if model.configFolder != nil {
 35                    Button("Stop Using This Folder", role: .destructive) { model.setConfigFolder(nil) }
 36                }
 37                ForEach(model.configProblems, id: \.self) { Text($0).foregroundStyle(.red) }
 38            } header: {
 39                Text("Configuration")
 40            } footer: {
 41                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.")
 42            }
 43            Section("Agenda") {
 44                let _ = model.settingsVersion
 45                Toggle("Show days without entries", isOn: Binding {
 46                    OrgPreferences.agendaShowAllDates()
 47                } set: { model.set("agendaShowAllDates", to: .bool($0)) })
 48                Picker("Blocked entries", selection: Binding {
 49                    UserDefaults.standard.string(forKey: "agendaDimBlockedTasks") ?? "t"
 50                } set: { model.set("agendaDimBlockedTasks", to: .string($0)) }) {
 51                    Text("Dimmed").tag("t")
 52                    Text("Hidden").tag("invisible")
 53                    Text("Shown as usual").tag("nil")
 54                }
 55            }
 56            Section {
 57                let _ = model.settingsVersion
 58                Toggle("Not done before TODO children", isOn: Binding {
 59                    UserDefaults.standard.bool(forKey: "enforceTodoDependencies")
 60                } set: { model.set("enforceTodoDependencies", to: .bool($0)) })
 61                Toggle("Not done with unchecked boxes", isOn: Binding {
 62                    UserDefaults.standard.bool(forKey: "enforceTodoCheckboxDependencies")
 63                } set: { model.set("enforceTodoCheckboxDependencies", to: .bool($0)) })
 64            } header: {
 65                Text("TODO Dependencies")
 66            } footer: {
 67                Text("org-enforce-todo-dependencies and org-enforce-todo-checkbox-dependencies.")
 68            }
 69            Section {
 70                if badges == true {
 71                    LabeledContent("Overdue Count on Icon", value: "On")
 72                } else if badges == false {
 73                    Button("Show Overdue Count on Icon…") {
 74                        Task {
 75                            if await model.badgesEnabled(asking: true) {
 76                                badges = true
 77                                await model.updateWidgets()
 78                            } else if let url = URL(string: UIApplication.openNotificationSettingsURLString) {
 79                                openURL(url)
 80                            }
 81                        }
 82                    }
 83                }
 84            } header: {
 85                Text("Badge")
 86            } footer: {
 87                if badges == false { Text("Turn on Badges in orgstar's notification settings.") }
 88            }
 89            calendarSection
 90            reminderSection
 91            Section("In use") {
 92                let _ = model.settingsVersion
 93                LabeledContent("TODO keywords", value: todoKeywords)
 94                LabeledContent("Agenda", value: agenda)
 95                LabeledContent("Reminders", value: OrgPreferences.reminders() ? "\(OrgPreferences.reminderLead()) min before" : "Off")
 96                LabeledContent("Capture templates", value: CaptureTemplates.load().templates.map(\.key).joined(separator: " "))
 97                LabeledContent("Theme", value: UserDefaults.standard.string(forKey: "themeFile").flatMap { $0.isEmpty ? nil : $0 } ?? "Default")
 98                LabeledContent("Font", value: font)
 99            }
100        }
101        .navigationTitle("Settings")
102        // Read again on return from the Settings app.
103        .task(id: scenePhase) { badges = await model.badgesEnabled(asking: false) }
104        .fileImporter(isPresented: $choosing, allowedContentTypes: [.folder]) { result in
105            if case .success(let url) = result { model.setConfigFolder(url) }
106        }
107    }
108
109    /// `calendar-events` and `calendar-event-calendars`, written to config.toml.
110    private var calendarSection: some View {
111        let _ = model.settingsVersion
112        let on = OrgPreferences.calendarEvents()
113        let chosen = OrgPreferences.calendarEventCalendars()
114        return Section {
115            Toggle("Show Calendar Events", isOn: Binding {
116                on
117            } set: { value in
118                model.set("calendarEvents", to: .bool(value))
119                if value { Task { await requestCalendars() } }
120            })
121            if on {
122                if !CalendarEvents.isAuthorized {
123                    Button("Allow Access to Calendars…") { Task { await requestCalendars() } }
124                }
125                ForEach(calendars, id: \.id) { calendar in
126                    let shown = CalendarEvents.chooses(id: calendar.id, title: calendar.title, chosen: chosen)
127                    Button {
128                        toggle(calendar.title, shown: shown, chosen: chosen)
129                    } label: {
130                        HStack {
131                            Circle().fill(calendar.color?.swiftUI ?? .secondary).frame(width: 10, height: 10)
132                            Text(calendar.title).foregroundStyle(.primary)
133                            Spacer()
134                            if shown { Image(systemName: "checkmark").foregroundStyle(Color.accentColor) }
135                        }
136                    }
137                    .tint(.primary)
138                }
139            }
140        } header: {
141            Text("Calendar")
142        } footer: {
143            Text(on ? "Events from the checked calendars show in the agenda. Tap one to edit it." : "Show events from Calendar in the agenda.")
144        }
145        .task(id: on) { loadCalendars() }
146    }
147
148    /// `agenda-reminders` and `agenda-reminder-lists`, written to config.toml.
149    private var reminderSection: some View {
150        let _ = model.settingsVersion
151        let on = OrgPreferences.agendaReminders()
152        let chosen = OrgPreferences.agendaReminderLists()
153        return Section {
154            Toggle("Show Reminders", isOn: Binding {
155                on
156            } set: { value in
157                model.set("agendaReminders", to: .bool(value))
158                if value { Task { await requestReminders() } }
159            })
160            if on {
161                if !ReminderLists.isAuthorized {
162                    Button("Allow Access to Reminders…") { Task { await requestReminders() } }
163                }
164                ForEach(reminderLists, id: \.id) { list in
165                    let shown = CalendarEvents.chooses(id: list.id, title: list.title, chosen: chosen)
166                    Button {
167                        toggle(list.title, shown: shown, chosen: chosen, among: reminderLists, key: "agendaReminderLists")
168                    } label: {
169                        HStack {
170                            Circle().fill(list.color?.swiftUI ?? .secondary).frame(width: 10, height: 10)
171                            Text(list.title).foregroundStyle(.primary)
172                            Spacer()
173                            if shown { Image(systemName: "checkmark").foregroundStyle(Color.accentColor) }
174                        }
175                    }
176                    .tint(.primary)
177                }
178            }
179        } header: {
180            Text("Reminders")
181        } footer: {
182            Text(on ? "Incomplete reminders with a due date from the checked lists show in the agenda, read-only; overdue ones under today."
183                 : "Show reminders from Reminders in the agenda, read-only.")
184        }
185        .task(id: on) { loadReminderLists() }
186    }
187
188    private func requestReminders() async {
189        _ = await model.reminderLists.requestAccess()
190        loadReminderLists()
191        model.reloadConfig()
192    }
193
194    private func loadReminderLists() {
195        reminderLists = model.reminderLists.lists()
196            .sorted { $0.title.localizedStandardCompare($1.title) == .orderedAscending }
197            .map { CalendarChoice(id: $0.id, title: $0.title, color: $0.color) }
198    }
199
200    private func requestCalendars() async {
201        _ = await model.calendarEvents.requestAccess()
202        loadCalendars()
203        model.reloadConfig()
204    }
205
206    private func loadCalendars() {
207        calendars = model.calendarEvents.calendars()
208            .sorted { $0.title.localizedStandardCompare($1.title) == .orderedAscending }
209            .map { CalendarChoice(id: $0.id, title: $0.title, color: $0.color) }
210    }
211
212    /// Shows or hides a calendar's events or a list's reminders; with every one checked the
213    /// setting is empty. The last checked one stays checked, as an empty list means every one.
214    private func toggle(_ title: String, shown: Bool, chosen: [String], among choices: [CalendarChoice]? = nil, key: String = "calendarEventCalendars") {
215        let choices = choices ?? calendars
216        var titles = choices.filter { CalendarEvents.chooses(id: $0.id, title: $0.title, chosen: chosen) }.map(\.title)
217        titles.removeAll { $0 == title }
218        if !shown { titles.append(title) }
219        guard !titles.isEmpty else { return }
220        let value = Set(titles) == Set(choices.map(\.title)) ? "" : titles.joined(separator: ", ")
221        model.set(key, to: .string(value))
222    }
223
224    /// The span and start day, worded as the Mac's Settings word the start.
225    private var agenda: String {
226        func days(_ count: Int) -> String { count == 1 ? "1 day" : "\(count) days" }
227        let offset = OrgPreferences.agendaStartOffset()
228        let start = offset == 0 ? "today" : offset < 0 ? "\(days(-offset)) before today" : "\(days(offset)) after today"
229        return "\(days(OrgPreferences.agendaSpan())), starting \(start)"
230    }
231
232    /// The theme's family, or the system's monospaced font when it's unset or not on the device.
233    private var font: String {
234        let spec = model.theme
235        let family = spec.font.isEmpty || UIFont.fontNames(forFamilyName: spec.font).isEmpty ? "System monospaced" : spec.font
236        let missing = !spec.font.isEmpty && family != spec.font ? " (\(spec.font) isn't installed)" : ""
237        return "\(family), \(spec.fontSize) pt\(missing)"
238    }
239
240    private var todoKeywords: String {
241        OrgPreferences.orgSettings().todoSequences.map { ($0.active.map(\.name) + ["|"] + $0.done.map(\.name)).joined(separator: " ") }
242            .joined(separator: "; ")
243    }
244}
245/// The configuration folder's `config.toml` as plain text, saved when you tap Save or leave.
246struct ConfigFileEditor: View {
247    let model: MobileModel
248    @State private var text = ""
249    @State private var saved: String?
250
251    var body: some View {
252        PlainTextView(text: $text)
253            .navigationTitle("config.toml")
254            .navigationBarTitleDisplayMode(.inline)
255            .toolbar {
256                Button("Save") { save() }.disabled(text == saved)
257            }
258            .safeAreaInset(edge: .bottom) {
259                let _ = model.settingsVersion
260                if !model.configProblems.isEmpty {
261                    VStack(alignment: .leading, spacing: 4) {
262                        ForEach(model.configProblems, id: \.self) { Text($0) }
263                    }
264                    .font(.footnote)
265                    .foregroundStyle(.red)
266                    .padding()
267                    .frame(maxWidth: .infinity, alignment: .leading)
268                    .background(.bar)
269                }
270            }
271            .onAppear {
272                guard saved == nil else { return }
273                text = model.configText() ?? UserConfig.defaultTemplate
274                saved = text
275            }
276            .onDisappear { save() }
277    }
278
279    private func save() {
280        guard text != saved else { return }
281        model.saveConfig(text)
282        saved = text
283    }
284}
285
286/// A monospaced text view without smart quotes, dashes or autocorrection, which would break TOML.
287private struct PlainTextView: UIViewRepresentable {
288    @Binding var text: String
289
290    func makeUIView(context: Context) -> UITextView {
291        let view = UITextView()
292        view.font = .monospacedSystemFont(ofSize: UIFont.preferredFont(forTextStyle: .footnote).pointSize, weight: .regular)
293        view.adjustsFontForContentSizeCategory = true
294        view.autocorrectionType = .no
295        view.autocapitalizationType = .none
296        view.smartQuotesType = .no
297        view.smartDashesType = .no
298        view.smartInsertDeleteType = .no
299        view.spellCheckingType = .no
300        view.keyboardDismissMode = .interactive
301        view.delegate = context.coordinator
302        return view
303    }
304
305    func updateUIView(_ view: UITextView, context: Context) {
306        if view.text != text { view.text = text }
307    }
308
309    func makeCoordinator() -> Coordinator { Coordinator(text: $text) }
310
311    final class Coordinator: NSObject, UITextViewDelegate {
312        var text: Binding<String>
313        init(text: Binding<String>) { self.text = text }
314        func textViewDidChange(_ view: UITextView) { text.wrappedValue = view.text }
315    }
316}
317#endif