]> git.r.bdr.sh - rbdr/map/blob - Map/State/AppState.swift
e10efea00ab5ec1eeed8989fae02345d436c3789
[rbdr/map] / Map / State / AppState.swift
1 import Cocoa
2 import Foundation
3 import SwiftUI
4
5 struct AppState {
6 var selectedMap: Map? = nil
7 var mapBeingDeleted: Map? = nil
8 }
9
10 enum AppAction {
11 case selectMap(map: Map?)
12 case deleteMap(map: Map)
13 case exportMapAsImage(map: Map, evolution: StageType)
14 case exportMapAsText(map: Map)
15 }
16
17 func appStateReducer(state: inout AppState, action: AppAction) {
18
19 switch action {
20
21 case .selectMap(let map):
22 state.selectedMap = map
23
24 case .deleteMap(let map):
25 let context = PersistenceController.shared.container.viewContext
26
27 context.delete(map)
28 try? context.save()
29
30 case .exportMapAsImage(let map, let evolution):
31 let window = NSWindow(
32 contentRect: .init(
33 origin: .zero,
34 size: .init(
35 width: NSScreen.main!.frame.width,
36 height: NSScreen.main!.frame.height)),
37 styleMask: [.closable],
38 backing: .buffered,
39 defer: false)
40
41 window.title = map.title ?? "Untitled Map"
42 window.isOpaque = true
43 window.center()
44 window.isMovableByWindowBackground = true
45 window.makeKeyAndOrderFront(nil)
46
47 let renderView = MapRenderView(map: map, evolution: Stage.stages(evolution))
48
49 let view = NSHostingView(rootView: renderView)
50 window.contentView = view
51
52 let imageRepresentation = view.bitmapImageRepForCachingDisplay(in: view.bounds)!
53 view.cacheDisplay(in: view.bounds, to: imageRepresentation)
54 let image = NSImage(cgImage: imageRepresentation.cgImage!, size: view.bounds.size)
55
56 let dialog = NSSavePanel()
57
58 dialog.title = "Save Map"
59 dialog.showsResizeIndicator = false
60 dialog.canCreateDirectories = true
61 dialog.showsHiddenFiles = false
62 dialog.allowedFileTypes = ["png"]
63 dialog.nameFieldStringValue = map.title ?? "Untitled Map"
64
65 if dialog.runModal() == NSApplication.ModalResponse.OK {
66 let result = dialog.url
67
68 if result != nil {
69
70 image.writePNG(toURL: result!)
71 print("saved at \(result!)")
72 }
73 } else {
74 print("Cancel")
75 }
76 window.orderOut(nil)
77
78 case .exportMapAsText(let map):
79 let dialog = NSSavePanel()
80
81 dialog.title = "Save Map Text"
82 dialog.showsResizeIndicator = false
83 dialog.canCreateDirectories = true
84 dialog.showsHiddenFiles = false
85 dialog.allowedFileTypes = ["txt"]
86 dialog.nameFieldStringValue = map.title ?? "Untitled Map"
87
88 if let content = map.content {
89
90 if dialog.runModal() == NSApplication.ModalResponse.OK {
91 let result = dialog.url
92
93 if let result = result {
94 try? content.write(to: result, atomically: true, encoding: String.Encoding.utf8)
95 }
96 } else {
97 print("Cancel")
98 }
99 }
100 }
101 }
102
103 typealias AppStore = Store<AppState, AppAction>