Sources/OrgstarMobile/SettingsScreen.swift

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