SPB Git

Repository Public

ExportComposer.swift 6.4 KB 97 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Editor/ExportComposer.swift3// Description: Attributed text of a note for printing, PDF and RTF: same styling as the editor, with list markers and check boxes written as characters (the on-screen decorations are drawn by the layout engine and do not exist outside it).4import AppKit5import SPNotesDocument67@MainActor public enum ExportComposer {8    /// `title` becomes a first heading. Colours are fixed (black on white): paper has one appearance.9    public static func attributedString(title: String?, document: NoteDocument, theme: EditorTheme = EditorTheme(fontSize: 12, fontDesign: .system), resources: AtomResources?, keepAttachments: Bool) -> NSAttributedString {10        let codec = DocumentCodec(theme: theme, resources: resources)11        let out = NSMutableAttributedString()12        NSAppearance(named: .aqua)?.performAsCurrentDrawingAppearance {13            out.append(codec.attributedString(from: document))14        }15        let ns = out.string as NSString16        var ranges: [NSRange] = []; var loc = 017        while loc < ns.length { let r = ns.paragraphRange(for: NSRange(location: loc, length: 0)); ranges.append(r); loc = NSMaxRange(r) }18        for r in ranges.reversed() {19            guard let deco = out.attribute(.spDecoration, at: r.location, effectiveRange: nil) as? ParaDecoration else { continue }20            let font = (out.attribute(.font, at: r.location, effectiveRange: nil) as? NSFont) ?? theme.baseFont()21            let para = ((out.attribute(.paragraphStyle, at: r.location, effectiveRange: nil) as? NSParagraphStyle)?.mutableCopy() as? NSMutableParagraphStyle) ?? NSMutableParagraphStyle()22            var prefix: String?23            switch deco.marker {24            case .bullet(let level): prefix = ["•", "◦", "▪"][level % 3] + "\t"25            case .number(let n): prefix = n + "\t"26            case .checkbox(let on): prefix = (on ? "☑" : "☐") + "\t"27            case .disclosure: prefix = "▸ "28            case nil: break29            }30            if let prefix {31                para.firstLineHeadIndent = deco.markerX + 232                para.tabStops = [NSTextTab(textAlignment: .left, location: para.headIndent)]33                out.insert(NSAttributedString(string: prefix, attributes: [.font: theme.baseFont(), .foregroundColor: NSColor.darkGray, .paragraphStyle: para]), at: r.location)34                out.addAttribute(.paragraphStyle, value: para, range: NSRange(location: r.location, length: r.length + (prefix as NSString).length))35            }36            if deco.panel != nil { out.addAttribute(.backgroundColor, value: NSColor(white: 0.95, alpha: 1), range: NSRange(location: r.location, length: r.length + ((prefix ?? "") as NSString).length)) }37            _ = font38        }39        // fixed colours for paper; semantic attributes are of no use outside the editor40        let all = NSRange(location: 0, length: out.length)41        out.enumerateAttribute(.foregroundColor, in: all) { v, r, _ in42            guard let c = v as? NSColor else { return }43            var fixed = NSColor.black44            NSAppearance(named: .aqua)?.performAsCurrentDrawingAppearance { fixed = c.usingColorSpace(.sRGB) ?? .black }45            out.addAttribute(.foregroundColor, value: fixed, range: r)46        }47        if !keepAttachments {48            out.enumerateAttribute(.attachment, in: all, options: .reverse) { v, r, _ in49                guard let a = v as? AtomAttachment else { return }50                let text: String51                switch a.node.type {52                case "mention": text = "@" + (a.node.attrs?["label"]?.string ?? "")53                case "horizontalRule": text = "———"54                case "image": text = "[image : \(a.node.attrs?["alt"]?.string ?? "")]"55                case "fileBlock": text = "[fichier : \(a.node.attrs?["name"]?.string ?? "")]"56                default: text = NoteDocument(lines: [Line(blockAtom: a.node)]).plainText()57                }58                var attrs = out.attributes(at: r.location, effectiveRange: nil); attrs[.attachment] = nil59                out.replaceCharacters(in: r, with: NSAttributedString(string: text, attributes: attrs))60            }61        }62        for k in [NSAttributedString.Key.spPara, .spMarks, .spDecoration, .spInlineNode, .toolTip, .cursor] { out.removeAttribute(k, range: NSRange(location: 0, length: out.length)) }63        if let title, !title.isEmpty {64            let p = NSMutableParagraphStyle(); p.paragraphSpacing = 1065            out.insert(NSAttributedString(string: title + "\n", attributes: [.font: theme.baseFont(size: theme.fontSize * 1.9, bold: true), .foregroundColor: NSColor.black, .paragraphStyle: p]), at: 0)66        }67        return out68    }6970    /// Paginated PDF (A4 or US Letter according to the system), laid out with the classic text engine.71    public static func pdf(_ text: NSAttributedString, to url: URL) -> Bool {72        let info = NSPrintInfo(dictionary: [.jobDisposition: NSPrintInfo.JobDisposition.save, .jobSavingURL: url])73        info.topMargin = 56; info.bottomMargin = 56; info.leftMargin = 60; info.rightMargin = 6074        info.horizontalPagination = .fit; info.verticalPagination = .automatic; info.isVerticallyCentered = false75        let width = info.paperSize.width - info.leftMargin - info.rightMargin76        let view = NSTextView(frame: CGRect(x: 0, y: 0, width: width, height: 100))77        _ = view.layoutManager // classic engine: reliable pagination78        view.textContainerInset = .zero; view.textContainer?.lineFragmentPadding = 079        view.textStorage?.setAttributedString(text)80        view.layoutManager?.ensureLayout(for: view.textContainer!)81        view.sizeToFit()82        let op = NSPrintOperation(view: view, printInfo: info)83        op.showsPrintPanel = false; op.showsProgressPanel = false84        return op.run()85    }8687    public static func printView(_ text: NSAttributedString) -> NSPrintOperation {88        let info = NSPrintInfo.shared.copy() as! NSPrintInfo89        info.topMargin = 56; info.bottomMargin = 56; info.leftMargin = 60; info.rightMargin = 60; info.isVerticallyCentered = false90        info.horizontalPagination = .fit; info.verticalPagination = .automatic91        let view = NSTextView(frame: CGRect(x: 0, y: 0, width: info.paperSize.width - 120, height: 100))92        _ = view.layoutManager93        view.textContainerInset = .zero; view.textStorage?.setAttributedString(text); view.sizeToFit()94        return NSPrintOperation(view: view, printInfo: info)95    }96}97
Files main
Menu

Theme