Sources/OrgstarMobile/SettingsScreen.swift

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