Repository Public
1// ORIX Docs2// File: App/Sources/Document/ORIXDocument.swift3// Description: The NSDocument: reading and importing, safe native saving, autosave in place, versions, revert, and window creation.4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai7import AppKit8import SwiftUI9import UniformTypeIdentifiers10import DocModel11import DocContainer12import DocAutomation1314final class ORIXDocument: NSDocument {15 nonisolated static let nativeType = "ai.spboucher.orix.docs.document"16 nonisolated let store = ModelStore()17 private(set) var session: DocumentSession?1819 nonisolated override class var autosavesInPlace: Bool { true }20 nonisolated override class var preservesVersions: Bool { true }21 nonisolated override class var autosavesDrafts: Bool { true }2223 nonisolated static func format(forType typeName: String, url: URL? = nil) -> DocFormat {24 if let ext = url?.pathExtension, let f = DocFormat(fileExtension: ext) { return f }25 guard let type = UTType(typeName) else { return .orixdoc }26 if type.identifier == nativeType { return .orixdoc }27 if type.conforms(to: UTType("org.openxmlformats.wordprocessingml.document") ?? .data) && type.identifier.contains("wordprocessingml") { return .docx }28 if type.conforms(to: .rtf) { return .rtf }29 if type.conforms(to: .pdf) { return .pdf }30 if type.conforms(to: .html) { return .html }31 if type.identifier == "net.daringfireball.markdown" { return .markdown }32 if type.conforms(to: .plainText) { return .txt }33 return .orixdoc34 }3536 // MARK: Reading3738 override nonisolated func read(from url: URL, ofType typeName: String) throws {39 let format = ORIXDocument.format(forType: typeName, url: url)40 let data = try Data(contentsOf: url)41 do {42 var result = try DocumentConverter.importDocument(data, format: format, baseURL: url.deletingLastPathComponent())43 if format != .orixdoc, result.document.meta.title.isEmpty { result.document.meta.title = url.deletingPathExtension().lastPathComponent }44 let recovered = format == .orixdoc && result.warnings.contains { $0.feature == "Damaged document" }45 store.setImported(result.document, warnings: result.warnings, format: format == .orixdoc && !recovered ? nil : format)46 } catch {47 throw NSError(domain: NSCocoaErrorDomain, code: NSFileReadCorruptFileError, userInfo: [48 NSLocalizedDescriptionKey: String(localized: "“\(url.lastPathComponent)” could not be opened."),49 NSLocalizedRecoverySuggestionErrorKey: "\(error)"])50 }51 // Revert and version restore read into an open document: refresh the session on the main thread.52 DispatchQueue.main.async { [weak self] in53 guard let self, let session = self.session else { return }54 session.reload(self.store.document)55 self.presentImportWarningsIfNeeded()56 }57 }5859 // MARK: Writing6061 override nonisolated func data(ofType typeName: String) throws -> Data {62 var doc = store.document63 doc.meta.modified = Date()64 return try DocumentConverter.export(doc, format: .orixdoc).data65 }6667 override nonisolated func canAsynchronouslyWrite(to url: URL, ofType typeName: String, for saveOperation: NSDocument.SaveOperationType) -> Bool { true }6869 nonisolated override func writableTypes(for saveOperation: NSDocument.SaveOperationType) -> [String] { [ORIXDocument.nativeType] }7071 override func prepareSavePanel(_ savePanel: NSSavePanel) -> Bool {72 savePanel.allowedContentTypes = [UTType(ORIXDocument.nativeType) ?? .data]73 savePanel.isExtensionHidden = false74 return true75 }7677 // MARK: Windows7879 override func makeWindowControllers() {80 let session = DocumentSession(store: store, author: AppSettings.shared.reviewerName)81 session.undoManager = undoManager82 session.document = self83 self.session = session84 let controller = DocumentWindowController(session: session)85 addWindowController(controller)86 // A foreign file is imported, never edited in place: saving asks for a new .orixdoc file and the original stays untouched.87 if store.importedFormat != nil {88 let name = fileURL?.deletingPathExtension().lastPathComponent89 fileURL = nil90 fileType = ORIXDocument.nativeType91 if let name { displayName = name }92 updateChangeCount(.changeReadOtherContents)93 store.clearImported()94 }95 presentImportWarningsIfNeeded()96 LaunchOptions.shared.apply(to: session)97 }9899 func presentImportWarningsIfNeeded() {100 let warnings = store.takeWarnings()101 guard !warnings.isEmpty, let session else { return }102 session.importWarnings = warnings103 if warnings.contains(where: { $0.severity != .info }) { session.activeSheet = .importWarnings }104 }105106 /// Creates an untitled document from a model (templates, comparison results, reports).107 @discardableResult108 static func openUntitled(_ model: DocumentModel, displayName: String? = nil) -> ORIXDocument {109 let doc = ORIXDocument()110 doc.store.document = model111 doc.fileType = nativeType112 NSDocumentController.shared.addDocument(doc)113 doc.makeWindowControllers()114 if let displayName { doc.displayName = displayName }115 doc.showWindows()116 return doc117 }118119 // MARK: Printing120121 override func printOperation(withSettings printSettings: [NSPrintInfo.AttributeKey: Any]) throws -> NSPrintOperation {122 guard let session else { throw CocoaError(.featureUnsupported) }123 let result = try DocumentConverter.export(session.doc, format: .pdf)124 guard let pdf = PDFPrintSource(data: result.data) else { throw CocoaError(.fileWriteUnknown) }125 let info = NSPrintInfo(dictionary: printSettings.reduce(into: [NSPrintInfo.AttributeKey: Any]()) { $0[$1.key] = $1.value })126 info.horizontalPagination = .fit; info.verticalPagination = .fit127 info.topMargin = 0; info.bottomMargin = 0; info.leftMargin = 0; info.rightMargin = 0128 if let first = session.layout.pages.first {129 info.paperSize = first.size130 info.orientation = first.size.width > first.size.height ? .landscape : .portrait131 }132 guard let op = pdf.printOperation(info) else { throw CocoaError(.featureUnsupported) }133 return op134 }135}136137import PDFKit138139/// Prints the published PDF, so paper output is the same as the exported file.140struct PDFPrintSource {141 let document: PDFDocument142 init?(data: Data) { guard let d = PDFDocument(data: data) else { return nil }; document = d }143 func printOperation(_ info: NSPrintInfo) -> NSPrintOperation? {144 document.printOperation(for: info, scalingMode: .pageScaleNone, autoRotate: true)145 }146}147