SPB Git

Repository Public

WorkbookDocument.swift 12.8 KB 243 lines swift

1import AppKit2import SwiftUI3import UniformTypeIdentifiers4import SheetCore5import SheetIO6import SheetUI78extension UTType {9    static let orixWorkbook = UTType(exportedAs: "ai.spboucher.orix.sheet.workbook")10}1112/// One open workbook. Native `.orixsheet` packages are edited in place (autosave, versions);13/// every other format is IMPORTED into an untitled workbook so that saving can never silently14/// drop what the foreign format cannot hold. Writing those formats is an explicit Export.15@MainActor16final class WorkbookDocument: NSDocument {17    nonisolated static let nativeType = "ai.spboucher.orix.sheet.workbook"1819    private(set) var session: WorkbookSession20    private(set) var preserved: PreservedParts?21    private(set) var importIssues: [CompatibilityIssue] = []22    private(set) var importedFrom: URL?23    private(set) var hasMacros = false24    private(set) var hasExternalLinks = false2526    override init() {27        session = WorkbookSession(workbook: Workbook(sheetNames: [NSLocalizedString("Sheet1", comment: "")]), locale: AppSettings.shared.locale)28        session.zoom = Double(AppSettings.shared.defaultZoomPercent) / 10029        super.init()30    }3132    /// New document from a prepared workbook (templates, automation).33    convenience init(workbook: Workbook, displayName: String?) {34        self.init()35        adopt(workbook, trustValues: false)36        if let displayName { self.displayName = displayName }37    }3839    private func adopt(_ workbook: Workbook, trustValues: Bool) {40        session = WorkbookSession(workbook: workbook, trustCachedValues: trustValues, locale: AppSettings.shared.locale)41        session.zoom = Double(AppSettings.shared.defaultZoomPercent) / 10042        session.syncCalcThreshold = AppSettings.shared.backgroundCalcThreshold43        session.undoManager = undoManager44        // changes that are not undoable (scripts, pipelines, scenarios stored in the workbook) still mark the document edited45        session.onChange = { [weak self] in self?.updateChangeCount(.changeDone) }46    }4748    nonisolated override class var autosavesInPlace: Bool { true }49    nonisolated override class func canConcurrentlyReadDocuments(ofType typeName: String) -> Bool { false }5051    nonisolated static func format(forType typeName: String, url: URL?) -> FileFormat {52        switch typeName {53        case nativeType: return .orixsheet54        case "org.openxmlformats.spreadsheetml.sheet": return .xlsx55        case "org.openxmlformats.spreadsheetml.sheet.macroenabled": return .xlsm56        case "public.comma-separated-values-text": return .csv57        case "public.tab-separated-values-text": return .tsv58        case "org.oasis-open.opendocument.spreadsheet": return .ods59        case "public.json": return url?.pathExtension.lowercased() == "jsonl" ? .jsonl : .json60        default: return url.flatMap { FileFormat.detect(url: $0) } ?? .orixsheet61        }62    }6364    // MARK: Reading6566    nonisolated override func read(from url: URL, ofType typeName: String) throws {67        try MainActor.assumeIsolated { try self.readOnMain(from: url, ofType: typeName) }68    }6970    private func readOnMain(from url: URL, ofType typeName: String) throws {71        let format = FileFormat.detect(url: url) ?? Self.format(forType: typeName, url: url)72        let result = try WorkbookReader.load(url: url, format: format)73        guard !result.workbook.sheets.isEmpty else { throw SheetIOError.invalidWorkbook(NSLocalizedString("The file contains no sheet.", comment: "")) }74        preserved = result.preserved75        importIssues = result.issues76        hasMacros = result.hasMacros77        hasExternalLinks = result.hasExternalLinks78        // our own files carry values computed by this engine; foreign files are recalculated79        adopt(result.workbook, trustValues: format == .orixsheet)80        if format != .orixsheet {81            importedFrom = url82            session.recalculateAll()83        }84    }8586    // MARK: Writing8788    nonisolated override func write(to url: URL, ofType typeName: String) throws {89        try MainActor.assumeIsolated { try self.writeOnMain(to: url, ofType: typeName) }90    }9192    private func writeOnMain(to url: URL, ofType typeName: String) throws {93        let format = Self.format(forType: typeName, url: url)94        session.workbook.properties.modified = Date()95        if session.workbook.properties.created == nil { session.workbook.properties.created = Date() }96        var options = SaveOptions()97        options.native.appVersion = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String ?? "1.0"98        options.csv.formatter = Self.displayFormatter(date1904: session.workbook.date1904)99        session.engine.lock.lock()100        defer { session.engine.lock.unlock() }101        _ = try WorkbookWriter.save(session.workbook, to: url, format: format, options: options, preserved: preserved)102    }103104    nonisolated static func displayFormatter(date1904: Bool) -> @Sendable (Cell, CellStyle) -> String {105        let provider = FormatDisplayProvider()106        return { cell, style in provider.display(cell.computed, format: style.numberFormat, maxChars: nil, date1904: date1904).text }107    }108109    nonisolated override func writableTypes(for saveOperation: NSDocument.SaveOperationType) -> [String] { [Self.nativeType] }110    nonisolated override func fileNameExtension(forType typeName: String, saveOperation: NSDocument.SaveOperationType) -> String? { "orixsheet" }111112    override func close() {113        for handler in Features.closeHandlers { handler(session) }114        super.close()115    }116117    // MARK: Windows118119    override func makeWindowControllers() {120        session.undoManager = undoManager121        let window = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 1320, height: 840), styleMask: [.titled, .closable, .miniaturizable, .resizable],122                              backing: .buffered, defer: false)123        window.titlebarAppearsTransparent = false124        window.toolbarStyle = .unifiedCompact125        window.minSize = NSSize(width: 760, height: 480)126        window.tabbingMode = .preferred127        window.contentView = NSHostingView(rootView: DocumentRootView(document: self))128        window.setFrameAutosaveName("ORIXSheetDocumentWindow")129        if window.frame.width < 800 { window.setContentSize(NSSize(width: 1320, height: 840)); window.center() }130        let controller = NSWindowController(window: window)131        controller.shouldCascadeWindows = true132        addWindowController(controller)133134        if let source = importedFrom {135            // imported files become untitled ORIX workbooks: Save asks for a location, Export writes other formats136            let name = source.deletingPathExtension().lastPathComponent137            fileURL = nil138            fileType = Self.nativeType139            displayName = name140            updateChangeCount(.changeDone)141        }142        if !importIssues.isEmpty || hasMacros || hasExternalLinks {143            DispatchQueue.main.asyncAfter(deadline: .now() + 0.4) { [weak self] in self?.showImportReport() }144        }145    }146147    var window: NSWindow? { windowControllers.first?.window }148149    func showImportReport() {150        guard let window else { return }151        var issues = importIssues152        if hasMacros { issues.insert(CompatibilityIssue(severity: .warning, feature: NSLocalizedString("Macros", comment: ""), detail: NSLocalizedString("This workbook contains VBA macros. ORIX Sheet never runs macros; they are kept only if you export as .xlsm.", comment: "")), at: 0) }153        if hasExternalLinks { issues.insert(CompatibilityIssue(severity: .warning, feature: NSLocalizedString("External links", comment: ""), detail: NSLocalizedString("This workbook refers to other files. ORIX Sheet does not fetch external data; cached values are shown.", comment: "")), at: 0) }154        CompatibilityReport.present(title: String(format: NSLocalizedString("Imported from %@", comment: ""), importedFrom?.lastPathComponent ?? ""),155                                    message: NSLocalizedString("The file was converted into an ORIX Sheet workbook. The original file is untouched.", comment: ""),156                                    issues: issues, confirmTitle: nil, on: window) { _ in }157    }158159    // MARK: Export160161    func export(as format: FileFormat) {162        guard let window else { return }163        if session.isEditing, !session.commitEdit(move: nil) { return }164        let issues = WorkbookWriter.preflight(session.workbook, format: format, preserved: preserved)165        let proceed: () -> Void = { [weak self] in166            guard let self else { return }167            let panel = NSSavePanel()168            panel.nameFieldStringValue = (self.displayName as NSString).deletingPathExtension + "." + format.fileExtension169            panel.allowedContentTypes = [UTType(filenameExtension: format.fileExtension) ?? .data]170            panel.canCreateDirectories = true171            panel.beginSheetModal(for: window) { response in172                guard response == .OK, let url = panel.url else { return }173                do {174                    var options = SaveOptions()175                    options.csv.formatter = Self.displayFormatter(date1904: self.session.workbook.date1904)176                    options.csv.sheetIndex = self.session.sheetIndex177                    options.json.sheetIndex = self.session.sheetIndex178                    if format == .tsv { options.csv.delimiter = "\t" }179                    self.session.engine.lock.lock()180                    defer { self.session.engine.lock.unlock() }181                    _ = try WorkbookWriter.save(self.session.workbook, to: url, format: format, options: options, preserved: self.preserved)182                    self.session.statusMessage = String(format: NSLocalizedString("Exported %@", comment: ""), url.lastPathComponent)183                } catch {184                    self.presentError(error, modalFor: window, delegate: nil, didPresent: nil, contextInfo: nil)185                }186            }187        }188        if issues.isEmpty { proceed(); return }189        CompatibilityReport.present(title: String(format: NSLocalizedString("Exporting to %@", comment: ""), format.displayName),190                                    message: NSLocalizedString("This format cannot hold everything in the workbook. Review what will change before exporting; your ORIX workbook is not modified.", comment: ""),191                                    issues: issues, confirmTitle: NSLocalizedString("Export Anyway", comment: ""), on: window) { ok in if ok { proceed() } }192    }193194    func exportPDF(allSheets: Bool) {195        guard let window else { return }196        let panel = NSSavePanel()197        panel.nameFieldStringValue = (displayName as NSString).deletingPathExtension + ".pdf"198        panel.allowedContentTypes = [.pdf]199        panel.beginSheetModal(for: window) { [weak self] response in200            guard let self, response == .OK, let url = panel.url else { return }201            let sheets = allSheets ? Array(self.session.workbook.sheets.indices.filter { !self.session.workbook.sheets[$0].meta.isHidden }) : nil202            let data = PrintRenderer.pdfData(session: self.session, sheets: sheets, fileName: self.displayName)203            do { try data.write(to: url, options: .atomic); self.session.statusMessage = String(format: NSLocalizedString("Exported %@", comment: ""), url.lastPathComponent) }204            catch { self.presentError(error, modalFor: window, delegate: nil, didPresent: nil, contextInfo: nil) }205        }206    }207208    // MARK: Printing209210    nonisolated override func printOperation(withSettings printSettings: [NSPrintInfo.AttributeKey: Any]) throws -> NSPrintOperation {211        MainActor.assumeIsolated { UncheckedSendableBox(self.makePrintOperation()) }.value212    }213214    private func makePrintOperation() -> NSPrintOperation {215        let view = SheetPrintView(session: session, fileName: displayName)216        let info = (printInfo.copy() as? NSPrintInfo) ?? NSPrintInfo()217        let p = session.sheet.meta.print218        info.paperSize = NSSize(width: p.landscape ? max(p.paperWidthPt, p.paperHeightPt) : min(p.paperWidthPt, p.paperHeightPt),219                                height: p.landscape ? min(p.paperWidthPt, p.paperHeightPt) : max(p.paperWidthPt, p.paperHeightPt))220        info.orientation = p.landscape ? .landscape : .portrait221        info.topMargin = 0; info.bottomMargin = 0; info.leftMargin = 0; info.rightMargin = 0222        info.horizontalPagination = .clip; info.verticalPagination = .clip223        info.isHorizontallyCentered = false; info.isVerticallyCentered = false224        let op = NSPrintOperation(view: view, printInfo: info)225        op.jobTitle = displayName226        return op227    }228}229230/// Root SwiftUI view of a document window.231struct DocumentRootView: View {232    let document: WorkbookDocument233    var body: some View {234        WorkbookView(session: document.session)235            .frame(minWidth: 760, minHeight: 440)236    }237}238239struct UncheckedSendableBox<T>: @unchecked Sendable {240    let value: T241    init(_ v: T) { value = v }242}243
Files main
Menu

Theme