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