aboutsummaryrefslogtreecommitdiff
path: root/Map/Presentation/Preferences/GeneralPreferencesView.swift
blob: 31e54c21e17f9bd8e286d24c1ea86af0f7985394 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
// Copyright (C) 2024 Rubén Beltrán del Río

// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.

// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.

// You should have received a copy of the GNU General Public License
// along with this program. If not, see https://map.tranquil.systems.

import SwiftUI
import UniformTypeIdentifiers

struct GeneralPreferencesView: View {
  @State private var showingResetAlert = false
  @State private var showingExportDialog = false
  @State private var showingImportDialog = false
  @State private var showingImportError = false
  @State private var importErrorMessage = ""
  @State private var showingExportFailedAlert = false
  @State private var exportShouldReset = false

  @AppStorage("appearanceStyle") private var appearanceStyle: String = UserPreferences.Defaults
    .appearanceStyle
  @AppStorage("quickLookPreviewStyle", store: UserDefaults(suiteName: "group.systems.tranquil.Map"))
  private var quickLookPreviewStyle: String = UserPreferences.Defaults.quickLookPreviewStyle

  var body: some View {
    VStack(alignment: .center, spacing: Dimensions.Spacing.loose) {
      // Appearance section
      HStack(alignment: .firstTextBaseline, spacing: Dimensions.Spacing.regular) {
        Text("preferences.appearance.title")
          .font(.Theme.Body.emphasized)
          .frame(maxWidth: 250, alignment: .trailing)

        Picker("", selection: $appearanceStyle) {
          ForEach(AppearanceStyle.allCases, id: \.rawValue) { style in
            Text(style.localizedName)
              .tag(style.rawValue)
          }
        }
        .pickerStyle(.radioGroup)
        .frame(maxWidth: 250, alignment: .leading)
        .frame(maxWidth: .infinity, alignment: .leading)
      }

      Divider()

      // QuickLook section
      HStack(alignment: .firstTextBaseline, spacing: Dimensions.Spacing.regular) {
        Text("preferences.quick_look.title")
          .font(.Theme.Body.emphasized)
          .frame(maxWidth: 250, alignment: .trailing)

        VStack(alignment: .leading, spacing: Dimensions.Spacing.regular) {

          Text("preferences.quick_look.preview_style.title")
            .font(.Theme.Body.regular)

          Picker("", selection: $quickLookPreviewStyle) {
            ForEach(QuickLookPreviewStyle.allCases, id: \.rawValue) { style in
              Text(style.localizedName)
                .tag(style.rawValue)
            }
          }
          .pickerStyle(.menu)
          .frame(maxWidth: 250)
          .padding(.leading, -Dimensions.Spacing.regular)

        }
        .frame(maxWidth: .infinity, alignment: .leading)
      }

      Divider()

      HStack(alignment: .firstTextBaseline, spacing: Dimensions.Spacing.regular) {
        Text("preferences.general.preferences.title")
          .font(.Theme.Body.emphasized)
          .frame(maxWidth: 250, alignment: .trailing)

        VStack(alignment: .leading, spacing: Dimensions.Spacing.regular) {
          HStack(spacing: Dimensions.Spacing.cozy) {
            Button(
              action: {
                exportShouldReset = false
                showingExportDialog = true
              },
              label: {
                Text("preferences.general.preferences.export")
                  .font(.Theme.Body.regular)
              }
            )
            .buttonStyle(.bordered)

            Button(
              action: {
                showingImportDialog = true
              },
              label: {
                Text("preferences.general.preferences.import")
                  .font(.Theme.Body.regular)
              }
            )
            .buttonStyle(.bordered)
          }

          Button(
            action: {
              showingResetAlert = true
            },
            label: {
              Text("preferences.general.preferences.reset")
                .font(.Theme.Body.regular)
                .foregroundColor(Color.Theme.UI.secondary)
            }
          )
          .buttonStyle(.borderless)
        }
        .frame(maxWidth: .infinity, alignment: .leading)
      }

      Spacer()
    }
    .padding(.vertical, Dimensions.Spacing.loose)
    .padding(.horizontal, Dimensions.Spacing.indulgent)
    .alert("preferences.general.reset.title", isPresented: $showingResetAlert) {
      Button("preferences.general.reset.cancel", role: .cancel) {}
      Button("preferences.general.reset.without_export", role: .destructive) {
        resetPreferences()
      }
      Button("preferences.general.reset.export_and_reset") {
        exportShouldReset = true
        showingExportDialog = true
      }
    } message: {
      Text("preferences.general.reset.message")
    }
    .alert("preferences.general.import.error.title", isPresented: $showingImportError) {
      Button("preferences.general.import.error.ok") {}
    } message: {
      Text(importErrorMessage)
    }
    .alert("preferences.general.export.failed.title", isPresented: $showingExportFailedAlert) {
      Button("preferences.general.export.failed.ok") {}
    } message: {
      Text("preferences.general.export.failed.message")
    }
    .fileExporter(
      isPresented: $showingExportDialog,
      document: PreferencesDocument(),
      contentType: .json,
      defaultFilename: String(localized: "preferences.general.export.filename")
    ) { result in
      handleExportResult(result)
    }
    .fileImporter(
      isPresented: $showingImportDialog,
      allowedContentTypes: [.json],
      allowsMultipleSelection: false
    ) { result in
      handleImport(result)
    }
  }

  private func resetPreferences() {
    var preferences = UserPreferences()
    preferences.resetToDefaults()
  }

  private func handleExportResult(_ result: Result<URL, Error>) {
    switch result {
    case .success(_):
      // Export successful
      if exportShouldReset {
        // Reset preferences if this was an export-and-reset operation
        resetPreferences()
      }
      // Reset the flag
      exportShouldReset = false
    case .failure(let error):
      if exportShouldReset {
        // Export failed during export-and-reset - show alert and don't reset
        showingExportFailedAlert = true
        exportShouldReset = false
      } else {
        // Regular export failed - just log it
        print("Export error: \(error)")
      }
    }
  }

  private func handleImport(_ result: Result<[URL], Error>) {
    switch result {
    case .success(let urls):
      guard let url = urls.first else { return }

      // Start accessing the security-scoped resource
      guard url.startAccessingSecurityScopedResource() else {
        importErrorMessage = String(localized: "preferences.general.import.error.file_read")
        showingImportError = true
        return
      }

      // Ensure we stop accessing the resource when done
      defer {
        url.stopAccessingSecurityScopedResource()
      }

      do {
        let jsonData = try Data(contentsOf: url)
        let jsonString = String(data: jsonData, encoding: .utf8) ?? ""

        var preferences = UserPreferences.loadFromUserDefaults()
        if preferences.updateFromJSON(jsonString) {
          // Import successful
        } else {
          importErrorMessage = String(localized: "preferences.general.import.error.invalid_format")
          showingImportError = true
        }
      } catch {
        importErrorMessage = String(localized: "preferences.general.import.error.file_read")
        showingImportError = true
      }

    case .failure(let error):
      importErrorMessage = error.localizedDescription
      showingImportError = true
    }
  }
}

// Document wrapper for file export
struct PreferencesDocument: FileDocument {
  static var readableContentTypes: [UTType] { [.json] }

  var preferences: UserPreferences

  init() {
    self.preferences = UserPreferences.loadFromUserDefaults()
  }

  init(configuration: ReadConfiguration) throws {
    self.preferences = UserPreferences()
  }

  func fileWrapper(configuration: WriteConfiguration) throws -> FileWrapper {
    let jsonString = preferences.toJSON() ?? "{}"
    let data = jsonString.data(using: .utf8) ?? Data()
    return FileWrapper(regularFileWithContents: data)
  }
}

#Preview {
  GeneralPreferencesView()
}