Sources/OrgstarMobile/SettingsScreen.swift

65a97fc9c9a3370a0d84c11f1152fd3ced3089b2
orgstar/Sources/OrgstarMobile/SettingsScreen.swift

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

Global

⌘K
Command palette & jump
/
Focus search
?
Show this help
g d
Dashboard
g e
Explore repositories
g n
Notifications

Repository & editor

t
Find file in repository
y
Copy immutable SHA permalink
g c
Code tab
g i
Issues tab
g m
Merge requests tab
g b
Builds tab
⌘↵
Submit active form