aboutsummaryrefslogtreecommitdiff
path: root/Hotline/MacApp.swift
blob: 9052c0ba25aa90351af049b77ec44ad043e8b5d6 (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
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
import SwiftUI
import SwiftData
import CloudKit
import UniformTypeIdentifiers
import Darwin

@Observable
final class AppLaunchState {
  static let shared = AppLaunchState()
  
  enum LaunchState {
    case loading
    case launched
    case terminated
  }
  
  var launchState = LaunchState.loading
}

class AppDelegate: NSObject, NSApplicationDelegate {
  private var cloudKitObserverToken: Any? = nil
  
  func applicationDidFinishLaunching(_ notification: Notification) {
    AppLaunchState.shared.launchState = .launched
    
    CKContainer.default().accountStatus { status, error in
      switch status {
      case .noAccount:
        print("iCloud Unavailable")
        
        // We mark CloudKit has available now since we're not waiting on
        // a server sync or anything.
        AppState.shared.cloudKitReady = true
      default:
        print("iCloud Available")
        
        self.cloudKitObserverToken = NotificationCenter.default.addObserver(forName: NSPersistentCloudKitContainer.eventChangedNotification, object: nil, queue: OperationQueue.main) { [weak self] note in
          print("iCloud Changed!")
          AppState.shared.cloudKitReady = true
            
          guard let token = self?.cloudKitObserverToken else { return }
          NotificationCenter.default.removeObserver(token)
        }
      }
    }

    Task {
      await AppUpdate.shared.checkForUpdatesOnLaunch()
    }
  }
  
  func applicationWillTerminate(_ notification: Notification) {
    AppLaunchState.shared.launchState = .terminated
  }
}

@main
struct Application: App {
  @Environment(\.scenePhase) private var scenePhase
  @Environment(\.openWindow) private var openWindow
  @Environment(\.openURL) private var openURL
  
  @NSApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
  
  @State private var hotlinePanel: HotlinePanel? = nil
  @State private var selection: TrackerSelection? = nil
  @Bindable private var update = AppUpdate.shared

  @FocusedValue(\.activeHotlineModel) private var activeHotline: HotlineState?
  @FocusedValue(\.activeServerState) private var activeServerState: ServerState?
  
  private var modelContainer: ModelContainer = {
    let schema = Schema([
      Bookmark.self,
      // ChatMessage.self
    ])
    
    // For records we want shared across devices.
    let cloudKitConfiguration = ModelConfiguration(
      schema: Schema([Bookmark.self]),
      isStoredInMemoryOnly: false,
      cloudKitDatabase: .private("iCloud.co.goodmake.hotline")
    )
    
    // For records we only need stored locally.
//    let localConfiguration = ModelConfiguration(
//      schema: Schema([ChatMessage.self]),
//      isStoredInMemoryOnly: false
//    )
    
    let modelContainer = try! ModelContainer(for: schema, configurations: [cloudKitConfiguration])
    
    // Print local SwiftData sqlite file.
//    print(modelContainer.configurations.first?.url.path(percentEncoded: false))
    
    return modelContainer
  }()
    
  var body: some Scene {
    // MARK: Tracker Window
    Window("Servers", id: "servers") {
      TrackerView(selection: $selection)
        .frame(minWidth: 250, minHeight: 250)
    }
    .modelContainer(self.modelContainer)
    .defaultSize(width: 700, height: 550)
    .defaultPosition(.center)
    .keyboardShortcut(.init("R"), modifiers: .command)
    .onChange(of: AppLaunchState.shared.launchState) {
      if AppLaunchState.shared.launchState == .launched {
        if Prefs.shared.showBannerToolbar {
          showBannerWindow()
        }
      }
    }
    .onChange(of: self.update.showWindow) {
      if self.update.showWindow {
        self.openWindow(id: "update")
      }
    }
    
    // MARK: About Box
    Window("About", id: "about") {
      AboutView()
        .background(Color.hotlineRed, ignoresSafeAreaEdges: .all)
        .windowFullScreenBehavior(.disabled)
        .toolbar(removing: .title)
        .gesture(WindowDragGesture())
        .background(
          WindowConfigurator { window in
            window.titlebarAppearsTransparent = true
            window.titlebarSeparatorStyle = .none
            window.isMovableByWindowBackground = true
            
            if let closeButton = window.standardWindowButton(.closeButton) {
              closeButton.isHidden = false   // make sure it’s visible
              closeButton.isEnabled = true
            }
            
            if let btn = window.standardWindowButton(.zoomButton) {
              btn.isHidden = true
            }
            
            if let btn = window.standardWindowButton(.miniaturizeButton) {
              btn.isHidden = true
            }
          }
        )
    }
    .windowResizability(.contentSize)
    .windowStyle(.hiddenTitleBar)
    .restorationBehavior(.disabled)
    .defaultPosition(.center)
    .commandsRemoved() // Remove About that was automatically added to Window menu.
    .commands {
      CommandGroup(replacing: CommandGroupPlacement.appInfo) {
        Button("About Hotline") {
          openWindow(id: "about")
        }
                
        Button("Check for Updates...") {
          Task {
            await AppUpdate.shared.checkForUpdatesManually()
          }
        }
      }
    }
    
    // MARK: Update Window
    Window("New Update", id: "update") {
      AppUpdateView()
        .windowFullScreenBehavior(.disabled)
    }
    .windowResizability(.contentSize)
    .windowStyle(.hiddenTitleBar)
    .restorationBehavior(.disabled)
    .defaultPosition(.center)
    .commandsRemoved()
    
    // MARK: Server Window
    WindowGroup(id: "server", for: Server.self) { server in
      ServerView(server: server)
        .frame(minWidth: 430, minHeight: 300)
    } defaultValue: {
      Server(name: nil, description: nil, address: "")
    }
    .modelContainer(self.modelContainer)
    .defaultSize(width: 690, height: 760)
    .defaultPosition(.center)
    .onChange(of: activeServerState) {
      AppState.shared.activeServerState = activeServerState
    }
    .onChange(of: activeHotline) {
      AppState.shared.activeHotline = activeHotline
    }
    .commands {
      CommandGroup(replacing: .newItem) {
        Button("Connect to Server...") {
          openWindow(id: "server")
        }
        .keyboardShortcut(.init("K"), modifiers: .command)
      }
      CommandGroup(before: .singleWindowList) {
        Button("Toolbar") {
          toggleBannerWindow()
        }
        .keyboardShortcut(.init("\\"), modifiers: [.shift, .command])
      }
      CommandGroup(after: .help) {
        Divider()
        Button("Request Feature...") {
          if let url = URL(string: "https://github.com/mierau/hotline/issues/new?labels=enhancement") {
            openURL(url)
          }
        }
        Button("Report Bug...") {
          if let url = URL(string: "https://github.com/mierau/hotline/issues/new?labels=bug") {
            openURL(url)
          }
        }
        Divider()
        Button("Open Latest Release Page...") {
          if let url = URL(string: "https://github.com/mierau/hotline/releases/latest") {
            openURL(url)
          }
        }
      }
      CommandMenu("Server") {
        Button("Connect") {
          guard let selection else {
            return
          }
          connect(to: selection)
        }
        .disabled(selection == nil || selection?.server == nil)
        .keyboardShortcut(.downArrow, modifiers: .command)
        Button("Disconnect") {
          if let hotline = activeHotline {
            Task {
              await hotline.disconnect()
            }
          }
        }
        .disabled(activeHotline?.status == .disconnected)
        Divider()
        Button("Broadcast Message...") {
          // TODO: Implement broadcast message when user is allowed.
        }
        .disabled(true)
        .keyboardShortcut(.init("B"), modifiers: .command)
        Divider()
        Button("Show Chat") {
          activeServerState?.selection = .chat
        }
        .disabled(activeHotline?.status != .loggedIn)
        .keyboardShortcut(.init("1"), modifiers: .command)
        Button("Show Message Board") {
          activeServerState?.selection = .board
        }
        .disabled(activeHotline?.status != .loggedIn)
        .keyboardShortcut(.init("2"), modifiers: .command)
        Button("Show News") {
          activeServerState?.selection = .news
        }
        .disabled(activeHotline?.status != .loggedIn || (activeHotline?.serverVersion ?? 0) < 151)
        .keyboardShortcut(.init("3"), modifiers: .command)
        Button("Show Files") {
          activeServerState?.selection = .files
        }
        .disabled(activeHotline?.status != .loggedIn)
        .keyboardShortcut(.init("4"), modifiers: .command)
        Button("Show Accounts") {
          activeServerState?.selection = .accounts
        }
        .disabled(activeHotline?.status != .loggedIn || activeHotline?.access?.contains(.canOpenUsers) != true  )
        .keyboardShortcut(.init("5"), modifiers: .command)
      }
    }
    
    // MARK: Settings Window
    Settings {
      SettingsView()
    }

    // MARK: Transfers Window
    Window("Transfers", id: "transfers") {
      TransfersView()
        .frame(minWidth: 500, minHeight: 200)
    }
    .defaultSize(width: 600, height: 400)
    .defaultPosition(.center)
    .keyboardShortcut(.init("T"), modifiers: [.shift, .command])
        
    // MARK: Image Preview Window
    WindowGroup(id: "preview-image", for: PreviewFileInfo.self) { $info in
      FilePreviewImageView(info: $info)
    }
    .windowResizability(.contentSize)
    .windowStyle(.titleBar)
    .windowToolbarStyle(.unifiedCompact(showsTitle: true))
    .defaultSize(width: 350, height: 150)
    .defaultPosition(.center)
    .restorationBehavior(.disabled)
    
    // MARK: Text Preview Window
    WindowGroup(id: "preview-text", for: PreviewFileInfo.self) { $info in
      FilePreviewTextView(info: $info)
    }
    .windowResizability(.automatic)
    .windowStyle(.titleBar)
    .windowToolbarStyle(.unifiedCompact(showsTitle: true))
    .defaultSize(width: 450, height: 550)
    .defaultPosition(.center)
    .restorationBehavior(.disabled)

    // MARK: QuickLook Preview Window
    WindowGroup(id: "preview-quicklook", for: PreviewFileInfo.self) { $info in
      FilePreviewQuickLookView(info: $info)
    }
    .windowManagerRole(.associated)
    .windowResizability(.automatic)
    .windowStyle(.titleBar)
    .windowToolbarStyle(.unifiedCompact(showsTitle: true))
    .defaultSize(width: 450, height: 550)
    .defaultPosition(.center)
    .restorationBehavior(.disabled)
  }

  func connect(to item: TrackerSelection) {
    if let server = item.server {
      openWindow(id: "server", value: server)
    }
  }

  func showBannerWindow() {
    if hotlinePanel == nil {
      hotlinePanel = HotlinePanel(HotlinePanelView())
    }
    
    if hotlinePanel?.isVisible == false {
      hotlinePanel?.orderFront(nil)
      Prefs.shared.showBannerToolbar = true
    }
  }
  
  func toggleBannerWindow() {
    if hotlinePanel == nil {
      hotlinePanel = HotlinePanel(HotlinePanelView())
    }
    
    if hotlinePanel?.isVisible == true {
      hotlinePanel?.orderOut(nil)
      Prefs.shared.showBannerToolbar = false
    }
    else {
      hotlinePanel?.orderFront(nil)
      Prefs.shared.showBannerToolbar = true
    }
  }
}