Repository Public
1// ORIX Docs2// File: App/Sources/Automation/DocumentIntents.swift3// Description: Shortcuts actions (App Intents) on the automation engine: Convert Document, Export as PDF, Audit Document and4// Document Statistics. They work on files in memory, open no window and send nothing over the network.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import AppIntents9import Foundation10import UniformTypeIdentifiers11import DocModel12import DocContainer13import DocAutomation1415/// The formats a Shortcuts action can write.16enum IntentDocumentFormat: String, AppEnum {17 case orixdoc, docx, pdf, rtf, markdown, html, txt1819 static let typeDisplayRepresentation: TypeDisplayRepresentation = "Document Format"20 static let caseDisplayRepresentations: [IntentDocumentFormat: DisplayRepresentation] = [21 .orixdoc: "ORIX Docs Document", .docx: "Word Document (DOCX)", .pdf: "PDF", .rtf: "Rich Text (RTF)",22 .markdown: "Markdown", .html: "Web Page (HTML)", .txt: "Plain Text"]2324 nonisolated var format: DocFormat { DocFormat(rawValue: rawValue) ?? .pdf }25}2627enum IntentAuditProfile: String, AppEnum {28 case standard, academic, business, minimal29 static let typeDisplayRepresentation: TypeDisplayRepresentation = "Audit Profile"30 static let caseDisplayRepresentations: [IntentAuditProfile: DisplayRepresentation] = [31 .standard: "Standard", .academic: "Academic", .business: "Business", .minimal: "Minimal"]32 nonisolated var profile: AuditProfile { AuditProfile(rawValue: rawValue) ?? .standard }33}3435enum IntentOutputStyle: String, AppEnum {36 case text, json37 static let typeDisplayRepresentation: TypeDisplayRepresentation = "Output"38 static let caseDisplayRepresentations: [IntentOutputStyle: DisplayRepresentation] = [.text: "Text", .json: "JSON"]39}4041enum DocumentIntentError: Error, CustomLocalizedStringResourceConvertible {42 case unknownType(String)43 case unreadable(String, String)44 case exportFailed(String)4546 var localizedStringResource: LocalizedStringResource {47 switch self {48 case .unknownType(let name): return "ORIX Docs cannot read “\(name)”: unknown file type."49 case .unreadable(let name, let why): return "“\(name)” could not be read: \(why)"50 case .exportFailed(let why): return "The document could not be written: \(why)"51 }52 }53}5455/// The engine calls shared by the actions. Pure functions of their input, run off the main actor.56nonisolated enum DocumentIntentEngine {57 struct Input: Sendable { var data: Data; var filename: String }5859 static func read(_ input: Input) throws -> DocumentModel {60 let ext = (input.filename as NSString).pathExtension61 guard let format = DocFormat(fileExtension: ext) else { throw DocumentIntentError.unknownType(input.filename) }62 do {63 var result = try DocumentConverter.importDocument(input.data, format: format, baseURL: nil)64 if result.document.meta.title.isEmpty, format != .orixdoc { result.document.meta.title = (input.filename as NSString).deletingPathExtension }65 return result.document66 } catch { throw DocumentIntentError.unreadable(input.filename, "\(error)") }67 }6869 static func convert(_ input: Input, to format: DocFormat, acceptChanges: Bool) throws -> (data: Data, filename: String) {70 var doc = try read(input)71 if acceptChanges { doc.resolveChanges(accept: true) }72 do {73 let data = try DocumentConverter.export(doc, format: format).data74 let base = (input.filename as NSString).deletingPathExtension75 return (data, (base.isEmpty ? "Document" : base) + "." + format.fileExtension)76 } catch { throw DocumentIntentError.exportFailed("\(error)") }77 }7879 static func audit(_ input: Input, profile: AuditProfile, json: Bool) throws -> String {80 let doc = try read(input)81 let findings = AutomationReports.audit(doc, profile: profile)82 if json { return String(decoding: try AutomationReports.auditJSON(findings, input: input.filename, profile: profile), as: UTF8.self) }83 return AutomationReports.auditText(findings, name: input.filename)84 }8586 static func statistics(_ input: Input, json: Bool) throws -> (text: String, words: Int) {87 let stats = AutomationReports.statistics(try read(input))88 if json { return (String(decoding: try AutomationReports.statisticsJSON(stats, input: input.filename), as: UTF8.self), stats.words) }89 return (AutomationReports.statisticsText(stats, name: input.filename), stats.words)90 }9192 static func contentType(_ format: DocFormat) -> UTType {93 if format == .orixdoc { return UTType("ai.spboucher.orix.docs.document") ?? .data }94 return UTType(filenameExtension: format.fileExtension) ?? .data95 }96}9798struct ConvertDocumentIntent: AppIntent {99 static let title: LocalizedStringResource = "Convert Document"100 static let description = IntentDescription("Converts a document to another format with ORIX Docs. Runs on this Mac; no window is opened.", categoryName: "Documents")101 static let openAppWhenRun = false102103 @Parameter(title: "Document", description: "A DOCX, RTF, Markdown, HTML, text, PDF or ORIX Docs file.")104 var document: IntentFile105 @Parameter(title: "Format", default: .pdf)106 var format: IntentDocumentFormat107 @Parameter(title: "Accept Tracked Changes", default: false)108 var acceptChanges: Bool109110 static var parameterSummary: some ParameterSummary {111 Summary("Convert \(\.$document) to \(\.$format)") { \.$acceptChanges }112 }113114 func perform() async throws -> some IntentResult & ReturnsValue<IntentFile> {115 let input = DocumentIntentEngine.Input(data: document.data, filename: document.filename)116 let target = format.format117 let accept = acceptChanges118 let output = try await Task.detached(priority: .userInitiated) { try DocumentIntentEngine.convert(input, to: target, acceptChanges: accept) }.value119 return .result(value: IntentFile(data: output.data, filename: output.filename, type: DocumentIntentEngine.contentType(target)))120 }121}122123struct ExportPDFIntent: AppIntent {124 static let title: LocalizedStringResource = "Export as PDF"125 static let description = IntentDescription("Publishes a document as a PDF with ORIX Docs, as if every tracked change were accepted. No window is opened.", categoryName: "Documents")126 static let openAppWhenRun = false127128 @Parameter(title: "Document")129 var document: IntentFile130131 static var parameterSummary: some ParameterSummary { Summary("Export \(\.$document) as PDF") }132133 func perform() async throws -> some IntentResult & ReturnsValue<IntentFile> {134 let input = DocumentIntentEngine.Input(data: document.data, filename: document.filename)135 let output = try await Task.detached(priority: .userInitiated) { try DocumentIntentEngine.convert(input, to: .pdf, acceptChanges: false) }.value136 return .result(value: IntentFile(data: output.data, filename: output.filename, type: .pdf))137 }138}139140struct AuditDocumentIntent: AppIntent {141 static let title: LocalizedStringResource = "Audit Document"142 static let description = IntentDescription("Checks a document's structure, references, captions and review leftovers, and returns the findings as text or JSON.", categoryName: "Documents")143 static let openAppWhenRun = false144145 @Parameter(title: "Document")146 var document: IntentFile147 @Parameter(title: "Profile", default: .standard)148 var profile: IntentAuditProfile149 @Parameter(title: "Output", default: .text)150 var output: IntentOutputStyle151152 static var parameterSummary: some ParameterSummary {153 Summary("Audit \(\.$document) with the \(\.$profile) profile") { \.$output }154 }155156 func perform() async throws -> some IntentResult & ReturnsValue<String> {157 let input = DocumentIntentEngine.Input(data: document.data, filename: document.filename)158 let chosen = profile.profile159 let json = output == .json160 let report = try await Task.detached(priority: .userInitiated) { try DocumentIntentEngine.audit(input, profile: chosen, json: json) }.value161 return .result(value: report)162 }163}164165struct DocumentStatisticsIntent: AppIntent {166 static let title: LocalizedStringResource = "Document Statistics"167 static let description = IntentDescription("Counts the pages, words, characters, paragraphs and objects of a document and estimates its reading time.", categoryName: "Documents")168 static let openAppWhenRun = false169170 @Parameter(title: "Document")171 var document: IntentFile172 @Parameter(title: "Output", default: .text)173 var output: IntentOutputStyle174175 static var parameterSummary: some ParameterSummary {176 Summary("Get statistics of \(\.$document)") { \.$output }177 }178179 func perform() async throws -> some IntentResult & ReturnsValue<String> {180 let input = DocumentIntentEngine.Input(data: document.data, filename: document.filename)181 let json = output == .json182 let report = try await Task.detached(priority: .userInitiated) { try DocumentIntentEngine.statistics(input, json: json) }.value183 return .result(value: report.text)184 }185}186187struct ORIXDocsShortcuts: AppShortcutsProvider {188 static var appShortcuts: [AppShortcut] {189 AppShortcut(intent: ConvertDocumentIntent(), phrases: ["Convert a document with \(.applicationName)", "Convert a file with \(.applicationName)"],190 shortTitle: "Convert Document", systemImageName: "arrow.left.arrow.right.square")191 AppShortcut(intent: ExportPDFIntent(), phrases: ["Export a PDF with \(.applicationName)", "Make a PDF with \(.applicationName)"],192 shortTitle: "Export as PDF", systemImageName: "doc.richtext")193 AppShortcut(intent: AuditDocumentIntent(), phrases: ["Audit a document with \(.applicationName)", "Check a document with \(.applicationName)"],194 shortTitle: "Audit Document", systemImageName: "checklist")195 AppShortcut(intent: DocumentStatisticsIntent(), phrases: ["Count the words of a document with \(.applicationName)", "Get document statistics with \(.applicationName)"],196 shortTitle: "Document Statistics", systemImageName: "number")197 }198}199