import Cocoa import Foundation import SwiftUI struct AppState { var selectedEvolution: StageType = .general var mapBeingDeleted: Map? = nil } enum AppAction { case selectEvolution(evolution: StageType) case exportMapAsImage(map: Map) case exportMapAsText(map: Map) } func appStateReducer(state: inout AppState, action: AppAction) { switch action { case .selectEvolution(let evolution): state.selectedEvolution = evolution case .exportMapAsImage(let map): let window = NSWindow( contentRect: .init( origin: .zero, size: .init( width: NSScreen.main!.frame.width, height: NSScreen.main!.frame.height)), styleMask: [.closable], backing: .buffered, defer: false) window.title = map.title ?? "Untitled Map" window.isOpaque = true window.center() window.isMovableByWindowBackground = true window.makeKeyAndOrderFront(nil) let renderView = MapRenderView( content: map.content ?? "", evolution: Stage.stages(state.selectedEvolution)) let view = NSHostingView(rootView: renderView) window.contentView = view let imageRepresentation = view.bitmapImageRepForCachingDisplay(in: view.bounds)! view.cacheDisplay(in: view.bounds, to: imageRepresentation) let image = NSImage(cgImage: imageRepresentation.cgImage!, size: view.bounds.size) let dialog = NSSavePanel() dialog.title = "Save Map" dialog.showsResizeIndicator = false dialog.canCreateDirectories = true dialog.showsHiddenFiles = false dialog.allowedFileTypes = ["png"] dialog.nameFieldStringValue = map.title ?? "Untitled Map" if dialog.runModal() == NSApplication.ModalResponse.OK { let result = dialog.url if result != nil { image.writePNG(toURL: result!) print("saved at \(result!)") } } else { print("Cancel") } window.orderOut(nil) case .exportMapAsText(let map): let dialog = NSSavePanel() dialog.title = "Save Map Text" dialog.showsResizeIndicator = false dialog.canCreateDirectories = true dialog.showsHiddenFiles = false dialog.allowedFileTypes = ["txt"] dialog.nameFieldStringValue = map.title ?? "Untitled Map" if let content = map.content { if dialog.runModal() == NSApplication.ModalResponse.OK { let result = dialog.url if let result = result { try? content.write(to: result, atomically: true, encoding: String.Encoding.utf8) } } else { print("Cancel") } } } } typealias AppStore = Store