Sources/OrgstarMobile/SettingsScreen.swift

design-themes-widgets
orgstar/Sources/OrgstarMobile/SettingsScreen.swift history · blame · raw

400 lines · 17765 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("Appearance") {
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            }
126            calendarSection
127            reminderSection
128            Section("In use") {
129                let _ = model.settingsVersion
130                LabeledContent("TODO keywords", value: todoKeywords)
131                LabeledContent("Agenda", value: agenda)
132                LabeledContent("Reminders", value: OrgPreferences.reminders() ? "\(OrgPreferences.reminderLead()) min before" : "Off")
133                LabeledContent("Capture templates", value: CaptureTemplates.load().templates.map(\.key).joined(separator: " "))
134                LabeledContent("Theme", value: themeInUse)
135                LabeledContent("Font", value: font)
136            }
137            Section {
138                NavigationLink {
139                    AboutScreen(appIcon: appIcon)
140                } label: {
141                    Label("About orgstar", systemImage: "info.circle")
142                }
143            }
144        }
145        .navigationTitle("Settings")
146        // Read again on return from the Settings app.
147        .task(id: scenePhase) { badges = await model.badgesEnabled(asking: false) }
148        .fileImporter(isPresented: $choosing, allowedContentTypes: [.folder]) { result in
149            if case .success(let url) = result { model.setConfigFolder(url) }
150        }
151    }
152
153    /// The two palettes' names, and the theme file's when there is one.
154    private var themeInUse: String {
155        let names = "\(ThemePickerScreen.current(.light).displayName) / \(ThemePickerScreen.current(.dark).displayName)"
156        guard let file = UserDefaults.standard.string(forKey: "themeFile"), !file.isEmpty else { return names }
157        return "\(names), \(file)"
158    }
159
160    /// `calendar-events` and `calendar-event-calendars`, written to config.toml.
161    private var calendarSection: some View {
162        let _ = model.settingsVersion
163        let on = OrgPreferences.calendarEvents()
164        let chosen = OrgPreferences.calendarEventCalendars()
165        return Section {
166            Toggle("Show Calendar Events", isOn: Binding {
167                on
168            } set: { value in
169                guard !value || ProAccess.shared.allows(.calendar) else { return }
170                model.set("calendarEvents", to: .bool(value))
171                if value { Task { await requestCalendars() } }
172            })
173            if on {
174                if !CalendarEvents.isAuthorized {
175                    Button("Allow Access to Calendars…") { Task { await requestCalendars() } }
176                }
177                ForEach(calendars, id: \.id) { calendar in
178                    let shown = CalendarEvents.chooses(id: calendar.id, title: calendar.title, chosen: chosen)
179                    Button {
180                        toggle(calendar.title, shown: shown, chosen: chosen)
181                    } label: {
182                        HStack {
183                            Circle().fill(calendar.color?.swiftUI ?? .secondary).frame(width: 10, height: 10)
184                            Text(calendar.title).foregroundStyle(.primary)
185                            Spacer()
186                            if shown { Image(systemName: "checkmark").foregroundStyle(Color.accentColor) }
187                        }
188                    }
189                    .tint(.primary)
190                }
191            }
192        } header: {
193            Text("Calendar")
194        } footer: {
195            Text(on ? "Events from the checked calendars show in the agenda. Tap one to edit it." : "Show events from Calendar in the agenda.")
196        }
197        .task(id: on) { loadCalendars() }
198    }
199
200    /// `agenda-reminders` and `agenda-reminder-lists`, written to config.toml.
201    private var reminderSection: some View {
202        let _ = model.settingsVersion
203        let on = OrgPreferences.agendaReminders()
204        let chosen = OrgPreferences.agendaReminderLists()
205        return Section {
206            Toggle("Show Reminders", isOn: Binding {
207                on
208            } set: { value in
209                guard !value || ProAccess.shared.allows(.calendar) else { return }
210                model.set("agendaReminders", to: .bool(value))
211                if value { Task { await requestReminders() } }
212            })
213            if on {
214                if !ReminderLists.isAuthorized {
215                    Button("Allow Access to Reminders…") { Task { await requestReminders() } }
216                }
217                ForEach(reminderLists, id: \.id) { list in
218                    let shown = CalendarEvents.chooses(id: list.id, title: list.title, chosen: chosen)
219                    Button {
220                        toggle(list.title, shown: shown, chosen: chosen, among: reminderLists, key: "agendaReminderLists")
221                    } label: {
222                        HStack {
223                            Circle().fill(list.color?.swiftUI ?? .secondary).frame(width: 10, height: 10)
224                            Text(list.title).foregroundStyle(.primary)
225                            Spacer()
226                            if shown { Image(systemName: "checkmark").foregroundStyle(Color.accentColor) }
227                        }
228                    }
229                    .tint(.primary)
230                }
231            }
232        } header: {
233            Text("Reminders")
234        } footer: {
235            Text(on ? "Incomplete reminders with a due date from the checked lists show in the agenda, read-only; overdue ones under today."
236                 : "Show reminders from Reminders in the agenda, read-only.")
237        }
238        .task(id: on) { loadReminderLists() }
239    }
240
241    private func requestReminders() async {
242        _ = await model.reminderLists.requestAccess()
243        loadReminderLists()
244        model.reloadConfig()
245    }
246
247    private func loadReminderLists() {
248        reminderLists = model.reminderLists.lists()
249            .sorted { $0.title.localizedStandardCompare($1.title) == .orderedAscending }
250            .map { CalendarChoice(id: $0.id, title: $0.title, color: $0.color) }
251    }
252
253    private func requestCalendars() async {
254        _ = await model.calendarEvents.requestAccess()
255        loadCalendars()
256        model.reloadConfig()
257    }
258
259    private func loadCalendars() {
260        calendars = model.calendarEvents.calendars()
261            .sorted { $0.title.localizedStandardCompare($1.title) == .orderedAscending }
262            .map { CalendarChoice(id: $0.id, title: $0.title, color: $0.color) }
263    }
264
265    /// Shows or hides a calendar's events or a list's reminders; with every one checked the
266    /// setting is empty. The last checked one stays checked, as an empty list means every one.
267    private func toggle(_ title: String, shown: Bool, chosen: [String], among choices: [CalendarChoice]? = nil, key: String = "calendarEventCalendars") {
268        let choices = choices ?? calendars
269        var titles = choices.filter { CalendarEvents.chooses(id: $0.id, title: $0.title, chosen: chosen) }.map(\.title)
270        titles.removeAll { $0 == title }
271        if !shown { titles.append(title) }
272        guard !titles.isEmpty else { return }
273        let value = Set(titles) == Set(choices.map(\.title)) ? "" : titles.joined(separator: ", ")
274        model.set(key, to: .string(value))
275    }
276
277    /// The span and start day, worded as the Mac's Settings word the start.
278    private var agenda: String {
279        func days(_ count: Int) -> String { count == 1 ? "1 day" : "\(count) days" }
280        let offset = OrgPreferences.agendaStartOffset()
281        let start = offset == 0 ? "today" : offset < 0 ? "\(days(-offset)) before today" : "\(days(offset)) after today"
282        return "\(days(OrgPreferences.agendaSpan())), starting \(start)"
283    }
284
285    /// The theme's family, or the system's monospaced font when it's unset or not on the device.
286    private var font: String {
287        let spec = model.theme
288        let family = spec.font.isEmpty || UIFont.fontNames(forFamilyName: spec.font).isEmpty ? "System monospaced" : spec.font
289        let missing = !spec.font.isEmpty && family != spec.font ? " (\(spec.font) isn't installed)" : ""
290        return "\(family), \(spec.fontSize) pt\(missing)"
291    }
292
293    private var todoKeywords: String {
294        OrgPreferences.orgSettings().todoSequences.map { ($0.active.map(\.name) + ["|"] + $0.done.map(\.name)).joined(separator: " ") }
295            .joined(separator: "; ")
296    }
297}
298/// The orgstar+ row at the top of Settings.
299private struct ProBanner: View {
300    private var access: ProAccess { .shared }
301
302    static var rowBackground: some View {
303        ZStack {
304            Color(uiColor: .secondarySystemGroupedBackground)
305            LinearGradient.plusGold.opacity(0.22)
306        }
307    }
308
309    var body: some View {
310        HStack(spacing: 14) {
311            PlusBadge()
312            VStack(alignment: .leading, spacing: 3) {
313                Text(verbatim: "orgstar+").font(.headline)
314                Group {
315                    if access.isUnlocked {
316                        Text("Unlocked. Thanks for supporting orgstar.")
317                    } else {
318                        Text("Export, encryption, widgets, the Watch app and more")
319                    }
320                }
321                .font(.subheadline)
322                .foregroundStyle(.secondary)
323            }
324        }
325        .padding(.vertical, 6)
326    }
327}
328
329/// The configuration folder's `config.toml` as plain text, saved when you tap Save or leave.
330struct ConfigFileEditor: View {
331    let model: MobileModel
332    @State private var text = ""
333    @State private var saved: String?
334
335    var body: some View {
336        PlainTextView(text: $text)
337            .navigationTitle("config.toml")
338            .navigationBarTitleDisplayMode(.inline)
339            .toolbar {
340                Button("Save") { save() }.disabled(text == saved)
341            }
342            .safeAreaInset(edge: .bottom) {
343                let _ = model.settingsVersion
344                if !model.configProblems.isEmpty {
345                    VStack(alignment: .leading, spacing: 4) {
346                        ForEach(model.configProblems, id: \.self) { Text($0) }
347                    }
348                    .font(.footnote)
349                    .foregroundStyle(.red)
350                    .padding()
351                    .frame(maxWidth: .infinity, alignment: .leading)
352                    .background(.bar)
353                }
354            }
355            .onAppear {
356                guard saved == nil else { return }
357                text = model.configText() ?? UserConfig.defaultTemplate
358                saved = text
359            }
360            .onDisappear { save() }
361    }
362
363    private func save() {
364        guard text != saved else { return }
365        if model.saveConfig(text) { saved = text }
366    }
367}
368
369/// A monospaced text view without smart quotes, dashes or autocorrection, which would break TOML.
370private struct PlainTextView: UIViewRepresentable {
371    @Binding var text: String
372
373    func makeUIView(context: Context) -> UITextView {
374        let view = UITextView()
375        view.font = .monospacedSystemFont(ofSize: UIFont.preferredFont(forTextStyle: .footnote).pointSize, weight: .regular)
376        view.adjustsFontForContentSizeCategory = true
377        view.autocorrectionType = .no
378        view.autocapitalizationType = .none
379        view.smartQuotesType = .no
380        view.smartDashesType = .no
381        view.smartInsertDeleteType = .no
382        view.spellCheckingType = .no
383        view.keyboardDismissMode = .interactive
384        view.delegate = context.coordinator
385        return view
386    }
387
388    func updateUIView(_ view: UITextView, context: Context) {
389        if view.text != text { view.text = text }
390    }
391
392    func makeCoordinator() -> Coordinator { Coordinator(text: $text) }
393
394    final class Coordinator: NSObject, UITextViewDelegate {
395        var text: Binding<String>
396        init(text: Binding<String>) { self.text = text }
397        func textViewDidChange(_ view: UITextView) { text.wrappedValue = view.text }
398    }
399}
400#endif