Sources/OrgstarMobile/SettingsScreen.swift

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