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