Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Editor/NoteFragment.swift3// Description: Copy, paste and drag of note content: a private pasteboard type that keeps the structure, plus plain text and RTF for other applications, and conversion of foreign rich text.4import AppKit5import SPNotesDocument6import UniformTypeIdentifiers78/// A piece of a note on the pasteboard: the lines of the selection as a small document.9@MainActor public struct NoteFragment {10 public static let pasteboardType = NSPasteboard.PasteboardType("ai.spboucher.spnotes.fragment")11 public let document: NoteDocument1213 public init(document: NoteDocument) { self.document = document }1415 /// The selection as lines. A selection inside one block is an inline fragment: it loses its block structure, so16 /// pasting half a list item into a sentence does not create a list.17 public init(text: NSAttributedString, range: NSRange) {18 let sub = NSMutableAttributedString(attributedString: text.attributedSubstring(from: range))19 let multi = (sub.string as NSString).range(of: "\n").location != NSNotFound20 if !sub.string.hasSuffix("\n"), sub.length > 0 { sub.append(NSAttributedString(string: "\n", attributes: [.spPara: sub.attribute(.spPara, at: sub.length - 1, effectiveRange: nil) ?? ParaStyle(), .spMarks: MarkSet.none])) }21 var lines = DocumentCodec.lines(from: sub, in: NSRange(location: 0, length: sub.length))22 if !multi, lines.count == 1, case .inline = lines[0].content, lines[0].type != "codeBlock" { lines[0] = Line(path: [], type: "paragraph", attrs: [:], content: lines[0].content) }23 document = NoteDocument(lines: lines)24 }2526 public init?(pasteboard: NSPasteboard) {27 guard let data = pasteboard.data(forType: Self.pasteboardType), let doc = try? NoteDocument(json: data) else { return nil }28 document = doc29 }30 public var data: Data? { try? document.jsonData() }3132 /// Foreign rich text (RTF from Pages, Mail, Notes, a browser) → lines: bold, italic, underline, strike-through, links,33 /// bulleted and numbered lists. Fonts, sizes and colours of the source are deliberately not imported.34 public static func lines(fromForeign text: NSAttributedString) -> [Line] {35 var out: [Line] = []36 let ns = text.string as NSString37 var loc = 0; var key = 138 var openList: (type: String, container: Container)?39 while loc < ns.length {40 let pr = ns.paragraphRange(for: NSRange(location: loc, length: 0)); loc = NSMaxRange(pr)41 var content = pr; while content.length > 0, [0x0A, 0x0D, 0x2029].contains(Int(ns.character(at: NSMaxRange(content) - 1))) { content.length -= 1 }42 var runs: [InlineRun] = []43 let lists = (text.attribute(.paragraphStyle, at: pr.location, effectiveRange: nil) as? NSParagraphStyle)?.textLists ?? []44 var skip = 045 if !lists.isEmpty {46 // the marker ("\t•\t", "\t1.\t") is part of the characters: drop it47 let s = ns.substring(with: content)48 if let r = s.range(of: #"^\t?[^\t]{0,8}\t"#, options: .regularExpression) { skip = (String(s[r]) as NSString).length }49 }50 if content.length - skip > 0 {51 text.enumerateAttributes(in: NSRange(location: content.location + skip, length: content.length - skip)) { attrs, r, _ in52 if attrs[.attachment] != nil { return }53 var marks: [PMMark] = []54 if let f = attrs[.font] as? NSFont { let t = f.fontDescriptor.symbolicTraits; if t.contains(.bold) { marks.append(PMMark(type: "bold")) }; if t.contains(.italic) { marks.append(PMMark(type: "italic")) }; if t.contains(.monoSpace) { marks.append(PMMark(type: "code")) } }55 if let u = attrs[.underlineStyle] as? Int, u != 0, attrs[.link] == nil { marks.append(PMMark(type: "underline")) }56 if let s = attrs[.strikethroughStyle] as? Int, s != 0 { marks.append(PMMark(type: "strike")) }57 if let l = attrs[.link] { let href = (l as? URL)?.absoluteString ?? (l as? String) ?? ""; if href.hasPrefix("http") || href.hasPrefix("mailto:") { marks.append(PMMark(type: "link", attrs: ["href": .string(href)])) } }58 let s = ns.substring(with: r).replacingOccurrences(of: "\u{2028}", with: "\n").replacingOccurrences(of: "\u{FFFC}", with: "")59 if !s.isEmpty { runs.append(.text(s, marks: marks)) }60 }61 }62 var path: [Container] = []63 if let l = lists.last {64 let type = l.markerFormat.rawValue.contains("decimal") || l.markerFormat.rawValue.contains("alpha") || l.markerFormat.rawValue.contains("roman") ? "orderedList" : "bulletList"65 if openList?.type != type { openList = (type, Container(key: key, type: type, attrs: type == "orderedList" ? ["start": .int(1)] : [:])); key += 1 }66 path = [openList!.container, Container(key: key, type: "listItem")]; key += 167 } else { openList = nil }68 out.append(Line(path: path, type: "paragraph", attrs: [:], content: .inline(DocumentCodec.coalesce(runs, code: false))))69 }70 return out71 }72}7374extension NoteTextView {75 public override var writablePasteboardTypes: [NSPasteboard.PasteboardType] { [NoteFragment.pasteboardType, .rtf, .string] }76 public override var readablePasteboardTypes: [NSPasteboard.PasteboardType] { [NoteFragment.pasteboardType, .fileURL, .png, .tiff, .rtf, .string] }7778 public override func writeSelection(to pboard: NSPasteboard, type: NSPasteboard.PasteboardType) -> Bool {79 let sel = selectedRange(); guard sel.length > 0 else { return false }80 let fragment = NoteFragment(text: storage, range: sel)81 switch type {82 case NoteFragment.pasteboardType:83 guard let d = fragment.data else { return false }84 return pboard.setData(d, forType: type)85 case .string:86 return pboard.setString(fragment.document.plainText(), forType: .string)87 case .rtf:88 let visual = NSMutableAttributedString(attributedString: storage.attributedSubstring(from: sel))89 visual.enumerateAttribute(.attachment, in: NSRange(location: 0, length: visual.length), options: .reverse) { v, r, _ in90 guard let a = v as? AtomAttachment else { return }91 let text = a.node.type == "mention" ? "@" + (a.node.attrs?["label"]?.string ?? "") : NoteDocument(lines: [Line(blockAtom: a.node)]).plainText()92 visual.replaceCharacters(in: r, with: text)93 }94 for k in [NSAttributedString.Key.spPara, .spMarks, .spDecoration, .spInlineNode, .toolTip, .cursor] { visual.removeAttribute(k, range: NSRange(location: 0, length: visual.length)) }95 visual.addAttribute(.foregroundColor, value: NSColor.black, range: NSRange(location: 0, length: visual.length))96 guard let d = try? visual.data(from: NSRange(location: 0, length: visual.length), documentAttributes: [.documentType: NSAttributedString.DocumentType.rtf]) else { return false }97 return pboard.setData(d, forType: .rtf)98 default: return super.writeSelection(to: pboard, type: type)99 }100 }101102 public override func preferredPasteboardType(from available: [NSPasteboard.PasteboardType], restrictedToTypesFrom allowed: [NSPasteboard.PasteboardType]?) -> NSPasteboard.PasteboardType? {103 for t in readablePasteboardTypes where available.contains(t) && (allowed?.contains(t) ?? true) { return t }104 return nil105 }106107 public override func readSelection(from pboard: NSPasteboard, type: NSPasteboard.PasteboardType) -> Bool {108 let style = paraStyle(at: selectedRange().location)109 switch type {110 case NoteFragment.pasteboardType:111 guard let f = NoteFragment(pasteboard: pboard) else { return false }112 if style.isCode { insertPlain(f.document.plainText()); return true }113 insert(f.document, actionName: "Coller"); return true114 case .fileURL:115 let urls = (pboard.readObjects(forClasses: [NSURL.self], options: [.urlReadingFileURLsOnly: true]) as? [URL]) ?? []116 guard !urls.isEmpty else { return false }117 noteDelegate?.noteTextView(self, receive: urls, images: [], at: selectedRange().location); return true118 case .png, .tiff:119 guard let data = pboard.data(forType: type), let image = NSImage(data: data) else { return false }120 noteDelegate?.noteTextView(self, receive: [], images: [image], at: selectedRange().location); return true121 case .rtf:122 guard !style.isCode, let data = pboard.data(forType: .rtf), let rich = NSAttributedString(rtf: data, documentAttributes: nil) else { return readSelection(from: pboard, type: .string) }123 insert(NoteDocument(lines: NoteFragment.lines(fromForeign: rich)), actionName: "Coller"); return true124 case .string:125 guard let s = pboard.string(forType: .string) else { return false }126 insertPlain(s); return true127 default: return super.readSelection(from: pboard, type: type)128 }129 }130131 /// Plain text at the caret: one paragraph per line (the lines of the block, inside code).132 public func insertPlain(_ string: String) {133 let s = string.replacingOccurrences(of: "\r\n", with: "\n").replacingOccurrences(of: "\r", with: "\n")134 let sel = selectedRange(); let style = paraStyle(at: sel.location)135 if style.isCode {136 replace(sel, with: NSAttributedString(string: s, attributes: [.spPara: style, .spMarks: MarkSet.none]), select: NSRange(location: sel.location + (s as NSString).length, length: 0), actionName: "Coller")137 return138 }139 let parts = s.components(separatedBy: "\n")140 if parts.count == 1 {141 guard !style.isAtom else { insert(NoteDocument(lines: [Line(type: "paragraph", content: .inline([.text(s, marks: [])]))]), actionName: "Coller"); return }142 replace(sel, with: NSAttributedString(string: s, attributes: [.spPara: style, .spMarks: activeMarks()]), select: NSRange(location: sel.location + (s as NSString).length, length: 0), actionName: "Coller")143 return144 }145 var lines = parts.map { Line(type: "paragraph", content: .inline($0.isEmpty ? [] : [.text($0, marks: [])])) }146 if lines.last.map({ if case .inline(let r) = $0.content { return r.isEmpty }; return false }) == true, lines.count > 1 { lines.removeLast() }147 insert(NoteDocument(lines: lines), actionName: "Coller")148 }149150 public override func pasteAsPlainText(_ sender: Any?) { if let s = NSPasteboard.general.string(forType: .string) { insertPlain(s) } }151 /// Edit ▸ Paste as Markdown: the text on the pasteboard is read as Markdown (headings, lists, tables, code).152 @objc public func pasteAsMarkdown(_ sender: Any?) { if let s = NSPasteboard.general.string(forType: .string) { insertMarkdown(s, actionName: "Coller le Markdown") } }153154 public override func validateUserInterfaceItem(_ item: NSValidatedUserInterfaceItem) -> Bool {155 if item.action == #selector(pasteAsMarkdown(_:)) { return isEditable && NSPasteboard.general.string(forType: .string) != nil }156 return super.validateUserInterfaceItem(item)157 }158}159