Branchwell

PulseCanvas / app · pulsecanvas.ai / Sources / PulseCanvas / RadioView.swift

Raw 27.3 KB on 1cf89eeacc946d122aba3a62ada6cb1600fbf757
1import AppKit
2import Combine
3import SwiftUI
4
5@MainActor
6struct RadioLibraryView: View {
7 @ObservedObject var radio: RadioController
8 let dismiss: () -> Void
9 @State private var source = ""
10 @State private var opening = true
11
12 var body: some View {
13 VStack(alignment: .leading, spacing: 14) {
14 HStack {
15 Label("PulseCanvas Radio", systemImage: "dot.radiowaves.left.and.right").font(.title2)
16 Spacer()
17 Button("Done", action: dismiss)
18 }
19 Text("Music and visuals on shuffle. Choose all, favorites, or a station.")
20 .foregroundStyle(.secondary)
21 if Bundle.main.object(forInfoDictionaryKey: "PulseCanvasRadioDeveloperMode") as? Bool == true {
22 DisclosureGroup("Library source") {
23 HStack {
24 TextField("HTTPS catalog URL", text: $source).textFieldStyle(.roundedBorder)
25 .accessibilityLabel("Radio catalog URL")
26 Button("Load library") {
27 if let url = URL(string: source.trimmingCharacters(in: .whitespacesAndNewlines)), url.scheme == "https" {
28 radio.loadCatalog(at: url)
29 }
30 }.disabled(URL(string: source)?.scheme != "https" || radio.isCatalogLoading)
31 }
32 }
33 HStack {
34 Button("Open local library…", action: openLocalLibrary)
35 Text("Choose a folder containing catalog.json and its audio files.").font(.caption).foregroundStyle(.secondary)
36 }
37 }
38 Divider()
39 if opening || radio.isCatalogLoading {
40 VStack(spacing: 16) {
41 ProgressView().controlSize(.large).tint(Color.white)
42 Text("Loading Radio…").font(.headline)
43 Text("Getting stations and songs ready.").font(.callout).foregroundStyle(.secondary)
44 }.frame(maxWidth: .infinity, maxHeight: .infinity)
45 .accessibilityElement(children: .combine)
46 } else {
47 HStack {
48 Text(radio.favoriteSongsOnly ? "Favorite songs" : radio.stationTitle).font(.headline)
49 Spacer()
50 Button {
51 if radio.isActive { radio.next() } else { radio.start() }
52 dismiss()
53 } label: {
54 Label(radio.isActive ? "Next song" : "Play radio",
55 systemImage: radio.isActive ? "forward.end.fill" : "play.fill")
56 .frame(minWidth: 104)
57 }
58 .buttonStyle(StudioButtonStyle(treatment: .primary))
59 .disabled(!radio.canStart)
60 }
61 RadioMusicGroupPicker(radio: radio)
62 if let message = radio.visualizerGroupMessage {
63 HStack {
64 Text(message).font(.caption).foregroundStyle(.secondary)
65 Spacer()
66 VisualizerRandomizerPicker(compact: true)
67 }
68 }
69 if let station = radio.stations.first(where: { $0.id == radio.stationID }), !radio.favoriteSongsOnly && !radio.isPersonalMusic {
70 Text(station.description).font(.caption).foregroundStyle(.secondary)
71 }
72 if radio.favoriteSongsOnly {
73 FavoriteSongsView(radio: radio) { song in
74 radio.playFavoriteSong(song)
75 if radio.isActive { dismiss() }
76 }
77 } else if let catalog = radio.catalog {
78 List(Array(catalog.tracks.enumerated()), id: \.element.id) { index, track in
79 HStack(spacing: 8) {
80 Button {
81 radio.start(at: index); dismiss()
82 } label: {
83 HStack {
84 Image(systemName: radio.isActive && radio.currentIndex == index ? "speaker.wave.2.fill" : "play.circle")
85 VStack(alignment: .leading, spacing: 3) {
86 Text(track.title)
87 Text(track.genre).font(.caption).foregroundStyle(.secondary)
88 }
89 Spacer()
90 Text(String(format: "%d:%02d", Int(track.duration) / 60, Int(track.duration) % 60))
91 .monospacedDigit().foregroundStyle(.secondary)
92 }.padding(.vertical, 4).contentShape(Rectangle())
93 }.buttonStyle(.plain)
94 if radio.canFavoriteCurrentSong {
95 Button { radio.toggleFavoriteSong(track) } label: {
96 Image(systemName: radio.isFavoriteSong(track) ? "heart.fill" : "heart")
97 .frame(width: 44, height: 44).contentShape(Rectangle())
98 }.buttonStyle(.plain)
99 .accessibilityLabel("\(radio.isFavoriteSong(track) ? "Unfavorite" : "Favorite") song \(track.title)")
100 }
101 }
102 }.frame(minHeight: 160, maxHeight: .infinity).disabled(radio.isCatalogLoading)
103 } else {
104 ContentUnavailableView("Choose a radio library", systemImage: "music.note.list",
105 description: Text("Your radio library will appear here when it finishes loading."))
106 .frame(height: 220)
107 }
108 }
109 HStack {
110 if radio.isLoading { ProgressView().controlSize(.small) }
111 Text(radio.isCatalogLoading ? "" : radio.status).font(.callout).foregroundStyle(.secondary).lineLimit(2)
112 Spacer()
113 if radio.isActive { Button("Leave radio") { radio.leave(); dismiss() } }
114 }
115 if radio.isPersonalMusic, let notice = radio.folderImportNotice {
116 Text(notice).font(.caption).foregroundStyle(.secondary)
117 }
118 Text(radio.isPersonalMusic ? "Folder songs are copied to this Mac and loop continuously in Radio. They stay out of Studio." : "Radio downloads music to this Mac for playback and analysis. Your own soundtracks stay on your Mac.")
119 .font(.caption).foregroundStyle(.secondary)
120 }.padding(24).frame(width: 670, height: 650)
121 .onAppear { source = radio.sourceText; radio.loadSavedCatalogIfNeeded(refresh: !radio.isActive); opening = false }
122 .onChange(of: radio.isActive) { _, active in if active && radio.favoriteSongsOnly { dismiss() } }
123 }
124
125 private func openLocalLibrary() {
126 let picker = NSOpenPanel()
127 picker.canChooseFiles = false; picker.canChooseDirectories = true; picker.allowsMultipleSelection = false
128 picker.message = "Choose the radio library folder containing catalog.json and the audio folder"
129 guard picker.runModal() == .OK, let folder = picker.url else { return }
130 let index = FileManager.default.fileExists(atPath: folder.appendingPathComponent("stations.json").path) ? "stations.json" : "catalog.json"
131 radio.loadCatalog(at: folder.appendingPathComponent(index), access: SecurityScopedAccess(url: folder))
132 }
133}
134
135@MainActor
136struct FavoriteSongsView: View {
137 @ObservedObject var radio: RadioController
138 let play: (FavoriteRadioSong) -> Void
139
140 var body: some View {
141 VStack(alignment: .leading, spacing: 12) {
142 HStack {
143 Text("Favorite songs").font(.headline)
144 Spacer()
145 Text("\(radio.favoriteSongs.count) songs")
146 .font(.caption).foregroundStyle(.secondary)
147 }
148 Button {
149 radio.playFavoriteStation()
150 } label: {
151 Label("Play favorite songs", systemImage: "shuffle")
152 }.buttonStyle(StudioButtonStyle(treatment: .primary))
153 .disabled(radio.favoriteSongs.isEmpty || radio.isCatalogLoading || radio.isLoading)
154 Text("Choose a song to open Radio and start listening.").font(.callout).foregroundStyle(.secondary)
155 if radio.favoriteSongs.isEmpty {
156 ContentUnavailableView("No favorite songs yet", systemImage: "heart",
157 description: Text("Tap a song’s heart in Radio to save it here."))
158 .frame(maxWidth: .infinity, maxHeight: .infinity)
159 } else {
160 ScrollView {
161 LazyVStack(spacing: 6) {
162 ForEach(radio.favoriteSongs.sorted { $0.track.title.localizedStandardCompare($1.track.title) == .orderedAscending }) { song in
163 HStack(spacing: 0) {
164 Button { play(song) } label: {
165 HStack(spacing: 12) {
166 Image(systemName: "play.circle.fill").font(.title2).foregroundStyle(.white)
167 VStack(alignment: .leading, spacing: 4) {
168 Text(song.track.title).font(.system(size: 13, weight: .medium)).lineLimit(1)
169 Text(song.track.genre).font(.caption).foregroundStyle(.secondary).lineLimit(1)
170 }
171 Spacer(minLength: 8)
172 }.padding(12).frame(maxWidth: .infinity, minHeight: 56).contentShape(Rectangle())
173 }.buttonStyle(.plain).accessibilityLabel("Play \(song.track.title) in Radio")
174 Button { radio.toggleFavoriteSong(song.track) } label: {
175 Image(systemName: "heart.fill").foregroundStyle(.white)
176 .frame(width: 44, height: 56).contentShape(Rectangle())
177 }.buttonStyle(.plain).accessibilityLabel("Unfavorite song \(song.track.title)")
178 }.background(.white.opacity(0.04), in: RoundedRectangle(cornerRadius: 10))
179 }
180 }
181 }
182 }
183 if radio.isCatalogLoading || radio.isLoading {
184 HStack { ProgressView().controlSize(.small); Text(radio.status).font(.caption) }
185 } else if let error = radio.favoritePlaybackError {
186 Text(error).font(.caption).foregroundStyle(.secondary)
187 }
188 }.frame(minHeight: 220)
189 .task { await radio.refreshFavoriteSongs() }
190 }
191}
192
193/// The editor's Library keeps visualizer browsing and saved songs in separate tabs.
194@MainActor
195struct PulseCanvasLibraryView: View {
196 @ObservedObject var radio: RadioController
197 let selected: Int
198 var appearance: ((Int) -> VisualPreset)? = nil
199 let choose: (Int) -> Void
200 let dismiss: () -> Void
201 @State private var favoriteSongsSelected = false
202
203 var body: some View {
204 VStack(spacing: 0) {
205 HStack(spacing: 8) {
206 Button { favoriteSongsSelected = false } label: { Label("Visualizers", systemImage: "square.grid.2x2") }
207 .buttonStyle(StudioButtonStyle(treatment: favoriteSongsSelected ? .secondary : .accent, compact: true))
208 Button { favoriteSongsSelected = true } label: { Label("Favorite songs", systemImage: "heart") }
209 .buttonStyle(StudioButtonStyle(treatment: favoriteSongsSelected ? .accent : .secondary, compact: true))
210 Spacer()
211 }.padding(.horizontal, 18).padding(.top, 18)
212 if favoriteSongsSelected {
213 FavoriteSongsView(radio: radio) { song in
214 radio.playFavoriteSong(song)
215 if radio.isActive { dismiss() }
216 }.padding(18).frame(height: 560)
217 } else {
218 VisualizerBrowser(selected: selected, heading: "Visualizers", appearance: appearance, choose: choose)
219 }
220 HStack { Spacer(); Button("Done", action: dismiss).buttonStyle(StudioButtonStyle(compact: true)) }.padding(18)
221 }.frame(width: 680)
222 .onChange(of: radio.isActive) { _, active in if active && favoriteSongsSelected { dismiss() } }
223 }
224}
225
226/// An independent listening surface: there are no Studio cards or appearance editors.
227@MainActor
228struct RadioPlayerView: View {
229 @ObservedObject var radio: RadioController
230 @ObservedObject var audio: AudioController
231 @ObservedObject var render: RenderState
232 @ObservedObject private var presets = ProjectMPresets.shared
233 @State private var playbackRevision = 0
234 @StateObject private var presentation = RadioPresentationController()
235 @State private var controlsVisible = true
236 @State private var hideControls: Task<Void, Never>?
237 @State private var showLibrary = false
238 @State private var trackingMenus = 0
239
240 var body: some View {
241 ZStack(alignment: .bottom) {
242 Color.black.ignoresSafeArea()
243 VisualizerView(state: render).ignoresSafeArea()
244 .modifier(VisualizerFavoriteGesture {
245 presets.favorite(render.scene, appearance: VisualPreset(render: render))
246 })
247 if controlsVisible || !radio.isPlaybackRequested || radio.isLoading {
248 controls.padding(20)
249 .transition(.opacity)
250 }
251 }.background(Color.black)
252 .background(StudioWindowReader(attach: presentation.attach).frame(width: 0, height: 0))
253 .background(RadioPointerActivity(activity: revealControls).frame(width: 0, height: 0))
254 .contentShape(Rectangle())
255 .onAppear { revealControls() }
256 .onChange(of: presentation.isFullScreen) { _, _ in revealControls() }
257 .onChange(of: audio.isPlaying) { _, _ in revealControls() }
258 .onChange(of: showLibrary) { _, _ in revealControls() }
259 .onReceive(NotificationCenter.default.publisher(for: NSMenu.didBeginTrackingNotification)) { _ in
260 trackingMenus += 1; hideControls?.cancel()
261 }
262 .onReceive(NotificationCenter.default.publisher(for: NSMenu.didEndTrackingNotification)) { _ in
263 trackingMenus = max(0, trackingMenus - 1)
264 if trackingMenus == 0 { revealControls() }
265 }
266 .onDisappear { hideControls?.cancel(); presentation.restore() }
267 .sheet(isPresented: $showLibrary) {
268 RadioLibraryView(radio: radio) { showLibrary = false }
269 .dismissOnOutsideClick { showLibrary = false }
270 }
271 }
272
273 private var visualizerRow: some View {
274 VStack(alignment: .leading, spacing: 12) {
275 ViewThatFits(in: .horizontal) {
276 HStack(spacing: 16) {
277 Label("Radio", systemImage: "dot.radiowaves.left.and.right").font(.headline)
278 currentVisualizer
279 visualizerControls
280 Spacer(minLength: 8)
281 presentationControls
282 }
283 VStack(alignment: .leading, spacing: 12) {
284 HStack(spacing: 16) {
285 Label("Radio", systemImage: "dot.radiowaves.left.and.right").font(.headline)
286 currentVisualizer
287 Spacer(minLength: 8)
288 presentationControls
289 }
290 HStack { visualizerControls; Spacer(minLength: 0) }
291 }
292 }
293 if let message = radio.visualizerGroupMessage {
294 Text(message).font(.caption).foregroundStyle(.secondary)
295 }
296 }
297 }
298
299 @ViewBuilder private var currentVisualizer: some View {
300 if !radio.sceneTitle.isEmpty {
301 HStack(spacing: 8) {
302 Button {
303 presets.toggleFavorite(render.scene, appearance: VisualPreset(render: render))
304 revealControls()
305 } label: {
306 Image(systemName: presets.isFavorite(render.scene) ? "heart.fill" : "heart")
307 }
308 .buttonStyle(StudioButtonStyle(compact: true, circular: true))
309 .accessibilityLabel(presets.isFavorite(render.scene) ? "Unfavorite visualizer" : "Favorite visualizer")
310 .help(presets.isFavorite(render.scene) ? "Remove \(radio.sceneTitle) from Favorites" : "Add \(radio.sceneTitle) to Favorites")
311 VStack(alignment: .leading, spacing: 2) {
312 Text("Visualizer").font(.caption2).foregroundStyle(.secondary)
313 Text(radio.sceneTitle).font(.callout.weight(.medium))
314 .lineLimit(1).truncationMode(.tail)
315 }
316 .help(radio.sceneTitle)
317 .accessibilityElement(children: .combine)
318
319 }
320 .frame(maxWidth: 320, alignment: .leading)
321 }
322 }
323
324
325 private var visualizerControls: some View {
326 HStack(spacing: 12) {
327 Button { radio.randomizeCurrentVisualizer(); revealControls() } label: {
328 Label("Randomize", systemImage: "shuffle")
329 }.buttonStyle(StudioButtonStyle(compact: true))
330 .help("Choose another visualizer from the selected group without restarting the song")
331 .disabled(!radio.canRandomizeVisualizer)
332 VisualizerRandomizerPicker(compact: true)
333 .onChange(of: radio.visualizerGroup) { _, _ in revealControls() }
334 Picker("Bars per visualizer", selection: $radio.barsPerVisualizer) {
335 ForEach(RadioController.barChoices, id: \.self) { Text("\($0) bars").tag($0) }
336 }.labelsHidden().frame(width: 96).controlSize(.large)
337 .help("How many bars each Radio visualizer plays")
338 }.fixedSize(horizontal: true, vertical: false)
339 }
340
341 private var presentationControls: some View {
342 HStack(spacing: 12) {
343 Button {
344 presentation.toggle(); revealControls()
345 } label: {
346 Label(presentation.isFullScreen ? "Exit full screen" : "Present",
347 systemImage: presentation.isFullScreen ? "arrow.down.right.and.arrow.up.left" : "arrow.up.left.and.arrow.down.right")
348 }.buttonStyle(StudioButtonStyle(compact: true))
349 Button("Back to editor") { radio.leave() }.buttonStyle(StudioButtonStyle(compact: true))
350 }.fixedSize(horizontal: true, vertical: false)
351 }
352
353 private var controls: some View {
354 let _ = playbackRevision
355 return VStack(alignment: .leading, spacing: 12) {
356 visualizerRow
357 Divider().overlay(.white.opacity(0.12))
358 HStack(spacing: 16) {
359 VStack(alignment: .leading, spacing: 4) {
360 HStack(spacing: 8) {
361 if let track = radio.currentTrack, radio.canFavoriteCurrentSong {
362 Button { radio.toggleFavoriteSong(track); revealControls() } label: {
363 Image(systemName: radio.isFavoriteSong(track) ? "heart.fill" : "heart")
364 }.buttonStyle(StudioButtonStyle(compact: true, circular: true))
365 .disabled(radio.isLoading)
366 .accessibilityLabel(radio.isFavoriteSong(track) ? "Unfavorite song" : "Favorite song")
367 .help("Save or remove this song in Library → Favorite songs")
368 }
369 Text(radio.isLoading ? String(localized: "Preparing next song…") : radio.currentTrack?.title ?? String(localized: "Radio"))
370 .font(.title3.weight(.semibold)).lineLimit(1)
371
372 }.frame(minHeight: 44)
373 Text(radio.isLoading || !audio.isPlaying ? radio.status : radio.currentTrack?.genre ?? "")
374 .font(.callout).foregroundStyle(.secondary).lineLimit(1).frame(height: 17)
375 }
376 Spacer()
377 RadioMusicGroupPicker(radio: radio).frame(width: 240)
378 .onChange(of: radio.musicGroupID) { _, _ in revealControls() }
379 Button { showLibrary = true; revealControls() } label: {
380 Label("Library", systemImage: "music.note.list")
381 }.buttonStyle(StudioButtonStyle(compact: true))
382 }
383 HStack(spacing: 18) {
384 Button { radio.togglePlayback() } label: {
385 Label(radio.isPlaybackRequested ? "Pause" : "Play", systemImage: radio.isPlaybackRequested ? "pause.fill" : "play.fill")
386 .frame(width: 68)
387 }.buttonStyle(StudioButtonStyle(treatment: .primary, compact: true))
388 Button { radio.next() } label: { Label("Skip", systemImage: "forward.end.fill") }
389 .buttonStyle(StudioButtonStyle(compact: true)).disabled(!radio.canStart)
390 Slider(value: Binding(get: { radio.canSeek ? audio.progress : 0 }, set: { radio.seek(fraction: $0) }), in: 0...1)
391 .disabled(!radio.canSeek).accessibilityLabel("Radio song position")
392 Text("\(format(audio.playbackSeconds)) / \(format(audio.duration))").monospacedDigit().font(.caption)
393 .frame(width: 112, alignment: .trailing)
394 Image(systemName: "speaker.wave.2")
395 Slider(value: $radio.volume, in: 0...1).frame(width: 80).accessibilityLabel("Radio volume")
396 }
397 }.padding(20).background(.ultraThinMaterial, in: RoundedRectangle(cornerRadius: 16))
398 .onReceive(audio.visualizationUpdated.throttle(for: .milliseconds(100), scheduler: RunLoop.main, latest: true)) { playbackRevision &+= 1 }
399 }
400
401 private func format(_ value: Double) -> String {
402 let seconds = max(0, Int(value)); return String(format: "%d:%02d", seconds / 60, seconds % 60)
403 }
404
405 private func revealControls() {
406 hideControls?.cancel()
407 withAnimation(.easeOut(duration: 0.2)) { controlsVisible = true }
408 hideControls = Task { @MainActor in
409 do { try await Task.sleep(for: .seconds(3)) } catch { return }
410 guard audio.isPlaying, !radio.isLoading, !showLibrary, trackingMenus == 0 else { return }
411 withAnimation(.easeOut(duration: 0.3)) { controlsVisible = false }
412 }
413 }
414}
415
416@MainActor
417private struct RadioMusicGroupPicker: View {
418 @ObservedObject var radio: RadioController
419 var body: some View {
420 Menu {
421 Button("All music") { radio.selectMusicGroup("all-music") }
422 ForEach(radio.isPersonalMusic ? [] : radio.stations.filter { $0.id != "all-music" }) { station in
423 Button(station.title) { radio.selectMusicGroup(station.id) }
424 }
425 Button("Favorite songs") { radio.selectMusicGroup("favorite-songs") }
426 Divider()
427 if radio.hasPersonalMusic { Button("My music folder") { radio.usePersonalMusic() } }
428 Button("Choose music folder…") {
429 let picker = NSOpenPanel()
430 picker.canChooseFiles = false; picker.canChooseDirectories = true
431 picker.allowsMultipleSelection = false
432 picker.message = "Copy an album or music folder for continuous Radio playback. Up to 500 songs; subfolders are included. These songs stay out of Studio."
433 if picker.runModal() == .OK, let folder = picker.url { radio.importMusicFolder(folder) }
434 }
435 Toggle("Shuffle songs", isOn: $radio.shuffle)
436 } label: {
437 Label(radio.isPersonalMusic ? radio.stationTitle : radio.favoriteSongsOnly ? "Favorite songs" : radio.stationTitle,
438 systemImage: radio.isPersonalMusic ? "folder.badge.music.note" : "antenna.radiowaves.left.and.right")
439 }.controlSize(.large).disabled(radio.isCatalogLoading)
440 .accessibilityLabel("Radio music source")
441 }
442}
443
444/// Native renderer surfaces can consume SwiftUI hover tracking. Observe actual
445/// pointer events in this Radio window without consuming clicks or monitoring other apps.
446private struct RadioPointerActivity: NSViewRepresentable {
447 let activity: () -> Void
448 func makeNSView(context: Context) -> RadioPointerView {
449 let view = RadioPointerView()
450 view.activity = activity
451 return view
452 }
453 func updateNSView(_ view: RadioPointerView, context: Context) { view.activity = activity }
454 static func dismantleNSView(_ view: RadioPointerView, coordinator: ()) { view.stop() }
455}
456
457private final class RadioPointerView: NSView {
458 var activity: () -> Void = {}
459 private var monitor: Any?
460 private weak var monitoredWindow: NSWindow?
461 private var previousMouseMovedEvents = false
462 private var lastActivity = -Double.infinity
463
464 override func viewDidMoveToWindow() {
465 super.viewDidMoveToWindow()
466 stop()
467 guard let window else { return }
468 monitoredWindow = window
469 previousMouseMovedEvents = window.acceptsMouseMovedEvents
470 window.acceptsMouseMovedEvents = true
471 monitor = NSEvent.addLocalMonitorForEvents(matching: [.mouseMoved, .leftMouseDown, .rightMouseDown, .scrollWheel]) { [weak self] event in
472 MainActor.assumeIsolated {
473 guard let self, event.window === self.monitoredWindow else { return }
474 let now = ProcessInfo.processInfo.systemUptime
475 guard now - self.lastActivity >= 0.1 else { return }
476 self.lastActivity = now
477 self.activity()
478 }
479 return event
480 }
481 }
482
483 func stop() {
484 if let monitor { NSEvent.removeMonitor(monitor); self.monitor = nil }
485 monitoredWindow?.acceptsMouseMovedEvents = previousMouseMovedEvents
486 monitoredWindow = nil
487 }
488}
489
490/// Radio always fills the window. Its full-screen state never reads export aspect settings.
491@MainActor
492final class RadioPresentationController: NSObject, ObservableObject {
493 @Published private(set) var isFullScreen = false
494 private weak var window: NSWindow?
495 private var startedFullScreen: Bool?
496 private var keyboardMonitor: Any?
497
498 override init() {
499 super.init()
500 NotificationCenter.default.addObserver(self, selector: #selector(changed(_:)), name: NSWindow.didEnterFullScreenNotification, object: nil)
501 NotificationCenter.default.addObserver(self, selector: #selector(changed(_:)), name: NSWindow.didExitFullScreenNotification, object: nil)
502 }
503
504 func attach(_ window: NSWindow?) {
505 self.window = window
506 guard let window else { return }
507 let full = window.styleMask.contains(.fullScreen)
508 if startedFullScreen == nil { startedFullScreen = full }
509 if isFullScreen != full { isFullScreen = full }
510 if keyboardMonitor == nil {
511 keyboardMonitor = NSEvent.addLocalMonitorForEvents(matching: .keyDown) { [weak self] event in
512 guard let self, self.isFullScreen, event.keyCode == 53,
513 event.modifierFlags.intersection([.command, .control, .option, .shift]).isEmpty else { return event }
514 if !event.isARepeat { self.toggle() }
515 return nil
516 }
517 }
518 }
519
520 func toggle() { window?.toggleFullScreen(nil) }
521
522 func restore() {
523 if let keyboardMonitor { NSEvent.removeMonitor(keyboardMonitor); self.keyboardMonitor = nil }
524 if startedFullScreen == false, window?.styleMask.contains(.fullScreen) == true { window?.toggleFullScreen(nil) }
525 }
526
527 @objc private func changed(_ notification: Notification) {
528 guard let source = notification.object as? NSWindow, source === window else { return }
529 isFullScreen = source.styleMask.contains(.fullScreen)
530 }
531}