Sources/OrgApp/Printing.swift
270 lines · 13570 bytes
20 symbols in this file
1import Foundation
2import OrgCore
3import OrgPresentation
4import PDFKit
5#if os(macOS)
6import AppKit
7#else
8import UIKit
9#endif
10
11/// What Print… prints of an org file.
12public enum PrintScope: Sendable, Equatable {
13 case file
14 /// The subtree containing this offset, as Export Subtree exports it.
15 case subtree(Int)
16 /// The selected text, with the file's keywords.
17 case selection(Range<Int>)
18}
19
20/// Printing: the page PDF export makes, with its margins, font and page numbers, through the
21/// system's print panel. A file's text comes from its buffer, as PDF export takes it, so an
22/// entry encrypted on disk prints as its message unless it was decrypted in the editor. The
23/// agenda prints as `AgendaPrint` lays it out.
24@MainActor
25public enum Printing {
26 /// The commands that print an org file: `app.print`, `app.print-subtree`, `app.print-selection`.
27 public static let commands = ["app.print", "app.print-subtree", "app.print-selection"]
28
29 /// When set, jobs are saved to this PDF file without the panel, for checking from scripts.
30 nonisolated(unsafe) public static var saveTo: URL?
31
32 /// The page PDF export makes of `scope` of `text`, the buffer of the org file at `path`; nil
33 /// before the first heading for a subtree, and for an empty selection.
34 public static func page(_ text: String, path: String, scope: PrintScope, settings: OrgSettings, codeStyle: HTMLCodeStyle?, language: String) -> String? {
35 let printed: String
36 switch scope {
37 case .file:
38 printed = text
39 case .subtree(let caret):
40 guard let subtree = ExportScope.subtree(text, at: caret, settings: settings) else { return nil }
41 printed = subtree
42 case .selection(let range):
43 guard !range.isEmpty else { return nil }
44 printed = ExportScope.region(text, range, settings: settings)
45 }
46 let base = ((path as NSString).lastPathComponent as NSString).deletingPathExtension
47 return HTMLExport.page(printed, fallbackTitle: base, settings: settings, path: path, codeStyle: codeStyle, language: language)
48 }
49
50 /// The job's name: the page's title.
51 nonisolated static func title(_ html: String) -> String {
52 guard let match = html.firstMatch(of: /<title>([^<]*)<\/title>/) else { return "" }
53 return String(match.1).replacingOccurrences(of: "<", with: "<").replacingOccurrences(of: ">", with: ">")
54 .replacingOccurrences(of: """, with: "\"").replacingOccurrences(of: "&", with: "&")
55 }
56
57 /// `html` laid out in pages as PDF export lays it out, then shown in the print panel.
58 /// `directory` is where relative image links are read from.
59 public static func show(html: String, directory: URL?) async throws {
60 try await present(try await pages(html: html, directory: directory), title: title(html), saveTo: saveTo)
61 }
62
63 /// `html` as the pages PDF export makes, with the PDF settings.
64 static func pages(html: String, directory: URL?) async throws -> Data {
65 try await PDFExport.pdf(html: html, directory: directory, options: OrgPreferences.pdfOptions())
66 }
67
68 #if os(macOS)
69 /// The pages in the print panel, a sheet on the key window, with its paper size, orientation
70 /// and preview; or, with `saveTo`, saved there without the panel. The pages already have
71 /// their margins; the printer's own scales them to fit.
72 static func present(_ data: Data, title: String, saveTo: URL?) async throws {
73 guard let document = PDFDocument(data: data) else { throw PDFExport.Failure(description: "The pages couldn't be made.") }
74 let info = (NSPrintInfo.shared.copy() as? NSPrintInfo) ?? NSPrintInfo()
75 info.topMargin = 0
76 info.bottomMargin = 0
77 info.leftMargin = 0
78 info.rightMargin = 0
79 if let saveTo {
80 info.jobDisposition = .save
81 info.dictionary()[NSPrintInfo.AttributeKey.jobSavingURL] = saveTo
82 }
83 guard let operation = document.printOperation(for: info, scalingMode: .pageScaleDownToFit, autoRotate: true) else {
84 throw PDFExport.Failure(description: "The pages couldn't be printed.")
85 }
86 operation.jobTitle = title
87 operation.showsPrintPanel = saveTo == nil
88 operation.printPanel.options.formUnion([.showsPaperSize, .showsOrientation, .showsScaling, .showsPreview])
89 // A sheet on the key window; saved without a panel, on a window never shown, as PDF
90 // export renders its pages.
91 let window = (saveTo == nil ? NSApp.keyWindow ?? NSApp.mainWindow ?? NSApp.windows.first(where: \.isVisible) : nil)
92 ?? NSWindow(contentRect: CGRect(x: 0, y: 0, width: 100, height: 100), styleMask: .borderless, backing: .buffered, defer: true)
93 let done = Done()
94 await withCheckedContinuation { continuation in
95 done.continuation = continuation
96 operation.runModal(for: window, delegate: done, didRun: #selector(Done.printOperationDidRun(_:success:contextInfo:)), contextInfo: nil)
97 }
98 }
99
100 private final class Done: NSObject {
101 var continuation: CheckedContinuation<Void, Never>?
102
103 @objc func printOperationDidRun(_ operation: NSPrintOperation, success: Bool, contextInfo: UnsafeMutableRawPointer?) {
104 continuation?.resume()
105 continuation = nil
106 }
107 }
108 #else
109 /// The pages in the system's print sheet.
110 static func present(_ data: Data, title: String, saveTo: URL?) async throws {
111 let info = UIPrintInfo.printInfo()
112 info.jobName = title
113 info.outputType = .general
114 let controller = UIPrintInteractionController.shared
115 controller.printInfo = info
116 controller.printingItem = data
117 controller.present(animated: true)
118 }
119 #endif
120}
121
122/// The agenda as shown, as a page to print: the title, then each day's header with its overdue
123/// entries, rows and time grid, or the entries of a list view, or each block's.
124public enum AgendaPrint {
125 public enum Part: Equatable, Sendable {
126 /// A block's title.
127 case heading(String)
128 /// A day; `overdueShown` false leaves today's overdue entries folded, as the view can.
129 case day(AgendaDayGroup, overdueShown: Bool)
130 /// The entries of a TODO list, match or search.
131 case entries([AgendaRow])
132 }
133
134 /// The page for `parts` under `title`, with `subtitle` (the folders shown, the filter) below it.
135 public static func page(title: String, subtitle: String? = nil, parts: [Part], today: Int, calendar: Calendar = .current, locale: Locale = .current) -> String {
136 var body = "<h1 class=\"title\">\(escape(title))</h1>\n"
137 if let subtitle, !subtitle.isEmpty { body += "<p class=\"subtitle\">\(escape(subtitle))</p>\n" }
138 for part in parts {
139 switch part {
140 case .heading(let text):
141 body += "<h2>\(escape(text))</h2>\n"
142 case .day(let group, let overdueShown):
143 body += "<h3\(group.isToday ? " class=\"today\"" : "")>\(escape(dayHeader(group, today: today, calendar: calendar, locale: locale)))</h3>\n"
144 if group.isToday, !group.overdue.isEmpty {
145 body += "<p class=\"overdue\">\(escape(String(localized: "Overdue", bundle: .main))) \(group.overdue.count)</p>\n"
146 if overdueShown { body += table(group.overdue) }
147 }
148 if group.rows.isEmpty {
149 body += "<p class=\"empty\">\(escape(String(localized: "Nothing scheduled", bundle: .main)))</p>\n"
150 } else {
151 // A page isn't live: no current-time line.
152 body += table(group.lines(now: 0).compactMap { line -> Line? in
153 switch line {
154 case .row(let index): .row(group.rows[index])
155 case .grid(let time): .grid(time)
156 case .now: nil
157 }
158 })
159 }
160 case .entries(let rows):
161 body += rows.isEmpty ? "<p class=\"empty\">\(escape(String(localized: "No entries", bundle: .main)))</p>\n" : table(rows, gutter: false)
162 }
163 }
164 return """
165 <!DOCTYPE html>
166 <html lang="\(escape(locale.language.languageCode?.identifier ?? "en"))">
167 <head>
168 <meta charset="utf-8">
169 <title>\(escape(title))</title>
170 <style>
171 body { font-family: -apple-system, sans-serif; line-height: 1.35; }
172 h1.title { font-size: 16pt; margin: 0 0 2pt; }
173 p.subtitle { color: #666; margin: 0 0 8pt; }
174 h2 { font-size: 13pt; margin: 14pt 0 4pt; }
175 h3 { font-size: 11pt; margin: 12pt 0 4pt; padding-bottom: 2pt; border-bottom: 0.5pt solid #bbb; }
176 h3.today { font-weight: 800; }
177 p.overdue { color: #b00; font-weight: 600; margin: 4pt 0; }
178 p.empty { color: #666; margin: 4pt 0; }
179 table { border-collapse: collapse; width: 100%; }
180 td { vertical-align: top; padding: 2pt 6pt 2pt 0; }
181 td.gutter { width: 80pt; white-space: nowrap; color: #444; font-variant-numeric: tabular-nums; }
182 tr.overdue td.gutter { color: #b00; }
183 tr.done .title { color: #777; text-decoration: line-through; }
184 tr.grid td { color: #999; font-size: 9pt; border-top: 0.5pt dashed #ccc; padding-top: 1pt; padding-bottom: 1pt; }
185 .meta { color: #666; font-size: 9pt; }
186 .todo { font-weight: 700; }
187 </style>
188 </head>
189 <body>
190 \(body)</body>
191 </html>
192
193 """
194 }
195
196 private enum Line {
197 case row(AgendaRow)
198 case grid(Int)
199 }
200
201 private static func table(_ rows: [AgendaRow], gutter: Bool = true) -> String {
202 table(rows.map(Line.row), gutter: gutter)
203 }
204
205 private static func table(_ lines: [Line], gutter: Bool = true) -> String {
206 var html = "<table>\n"
207 for line in lines {
208 switch line {
209 case .grid(let time):
210 html += "<tr class=\"grid\"><td class=\"gutter\">\(String(format: "%02d:%02d", time / 100, time % 100))</td><td></td></tr>\n"
211 case .row(let row):
212 let classes = [row.status == .overdue ? "overdue" : nil, row.isDone ? "done" : nil].compactMap { $0 }
213 html += "<tr\(classes.isEmpty ? "" : " class=\"\(classes.joined(separator: " "))\"")>"
214 if gutter { html += "<td class=\"gutter\">\(row.gutterLines.map(escape).joined(separator: "<br>"))</td>" }
215 html += "<td>\(entry(row))</td></tr>\n"
216 }
217 }
218 return html + "</table>\n"
219 }
220
221 /// The category, detail, progress and tags over the TODO keyword, priority and title, as
222 /// the view's rows have them.
223 private static func entry(_ row: AgendaRow) -> String {
224 let meta = [row.category, row.prefixDetail, row.progress, row.detail].compactMap { $0 }.filter { !$0.isEmpty }
225 + (row.tags.isEmpty ? [] : [":" + row.tags.joined(separator: ":") + ":"])
226 var html = meta.isEmpty ? "" : "<div class=\"meta\">\(meta.map(escape).joined(separator: " · "))</div>"
227 var title: [String] = []
228 if let todo = row.todo { title.append("<span class=\"todo\">\(escape(todo))</span>") }
229 if let priority = row.priority { title.append("[#\(escape(priority))]") }
230 title.append("<span class=\"title\">\(escape(row.title))</span>")
231 html += "<div>\(title.joined(separator: " "))</div>"
232 return html
233 }
234
235 /// `Today · Thursday 26 November 2026`.
236 static func dayHeader(_ group: AgendaDayGroup, today: Int, calendar: Calendar, locale: Locale) -> String {
237 let formatter = DateFormatter()
238 formatter.locale = locale
239 formatter.calendar = calendar
240 formatter.timeZone = calendar.timeZone
241 formatter.setLocalizedDateFormatFromTemplate("EEEEdMMMMy")
242 let date = formatter.string(from: group.date(calendar: calendar))
243 return group.relativeName(today: today).map { $0 + " · " + date } ?? date
244 }
245
246 static func escape(_ s: String) -> String {
247 s.replacingOccurrences(of: "&", with: "&").replacingOccurrences(of: "<", with: "<")
248 .replacingOccurrences(of: ">", with: ">").replacingOccurrences(of: "\"", with: """)
249 }
250}
251
252extension AgendaModel {
253 /// What the view shows, as `AgendaPrint` lays it out: its days, its entries, or each block's
254 /// title over its days or entries, with `filter` and empty days as the view has them.
255 public func printParts(showAllDates: Bool, filter: AgendaFilter, overdueShown: Bool) -> [AgendaPrint.Part] {
256 let rows = { (list: [AgendaItem]) in list.filter(filter.keeps).compactMap { AgendaRow(item: $0, day: self.today, today: self.today) } }
257 switch mode {
258 case .agenda:
259 return groups(showAllDates: showAllDates, filter: filter).map { .day($0, overdueShown: overdueShown) }
260 case .blocks:
261 return blocks.flatMap { block -> [AgendaPrint.Part] in
262 [.heading(block.header)] + (block.isAgenda
263 ? groups(block, showAllDates: showAllDates, filter: filter).map { .day($0, overdueShown: overdueShown) }
264 : [.entries(rows(block.list))])
265 }
266 default:
267 return [.entries(rows(list))]
268 }
269 }
270}