diff --git a/README.md b/README.md index 5deee28..d21e681 100644 --- a/README.md +++ b/README.md @@ -434,6 +434,14 @@ In UIKit, set `isSelectable` on `TranscriptTextView`. On devices that have Writing Tools, the edit menu can offer them for the selected text, as in a `UITextView`. Turn them off with `.showsWritingTools(false)`, or with `showsWritingTools` on `TranscriptTextView`. +Copy puts two forms of the selected text on the pasteboard. The plain text is readable as Markdown, with list +markers, quote prefixes and tables (see `copyText(in:)` on `TranscriptDocument`). The rich text is RTF, with the +fonts of the text, bold, italic, code, links, strikethrough and underline. The system font has a private name that +some apps do not find, so the RTF names Helvetica Neue in its place, with the same size, bold and italic. It has no +colors, so pasted text takes the colors of the place it goes to. Its list markers, quote prefixes, tables and rules are +the characters of the plain text, not RTF lists or tables. Text in a table cell keeps its bold, italic, code and +links. An app that reads plain text gets the plain text. + ### VoiceOver VoiceOver reads the text block by block. Headings are in the rotor's list of headings, list items start with their diff --git a/Sources/TranscriptKit/Model/RichCopy.swift b/Sources/TranscriptKit/Model/RichCopy.swift new file mode 100644 index 0000000..d1e164d --- /dev/null +++ b/Sources/TranscriptKit/Model/RichCopy.swift @@ -0,0 +1,96 @@ +import Foundation +import UniformTypeIdentifiers +#if canImport(UIKit) +import UIKit +#elseif canImport(AppKit) +import AppKit +#endif + +extension TranscriptDocument { + /// What copying `range` puts on the pasteboard, as one item by type + /// identifier: the plain text of `copyText(in:)`, and the same text as + /// RTF, with the fonts of `style`, links, strikethrough and underline. + /// The RTF has no colors, so pasted text takes the colors of the place + /// it goes to. The system font becomes Helvetica Neue, with the same + /// size, bold and italic. + func pasteboardItem(in range: Range, style: TranscriptStyle) -> [String: Any] { + let text = Self.withPublicFonts(copiedText(in: range, style: style)) + var item: [String: Any] = [UTType.utf8PlainText.identifier: text.string] + if let rtf = try? text.data(from: NSRange(location: 0, length: text.length), + documentAttributes: [.documentType: NSAttributedString.DocumentType.rtf]) { + item[UTType.rtf.identifier] = rtf + } + return item + } + + /// `text` with each font that has a private name (the system fonts, + /// whose names start with a period) changed to a public font of the + /// same size and traits. Apps that find a font by its name in the RTF + /// can fail to find a private name, and show another font. + static func withPublicFonts(_ text: NSAttributedString) -> NSAttributedString { + let result = NSMutableAttributedString(attributedString: text) + let whole = NSRange(location: 0, length: result.length) + text.enumerateAttribute(TranscriptStyle.fontKey, in: whole) { value, range, _ in + guard let value else { return } + let font = value as! CTFont + let name = CTFontCopyPostScriptName(font) as String + guard name.hasPrefix(".") else { return } + result.addAttribute(TranscriptStyle.fontKey, value: publicFont(like: font), range: range) + } + return result + } + + private static func publicFont(like font: CTFont) -> CTFont { + let traits = CTFontGetSymbolicTraits(font) + let size = CTFontGetSize(font) + let name = traits.contains(.traitMonoSpace) ? "Menlo-Regular" : "HelveticaNeue" + let base = CTFontCreateWithName(name as CFString, size, nil) + let wanted = traits.intersection([.traitBold, .traitItalic]) + guard !wanted.isEmpty else { return base } + return CTFontCreateCopyWithSymbolicTraits(base, 0, nil, wanted, wanted) ?? base + } + + /// Styles the spans of `block` in `piece`, which holds the block's text + /// from UTF-16 offset `start` on: the fonts of bold, italic and code, and + /// links, strikethrough and underline, with the attributes that other + /// apps read. + func styleSpans(of block: TranscriptBlock, from start: Int, in piece: NSMutableAttributedString, style: TranscriptStyle) { + let length = piece.length + let spans = block.spans.compactMap { span -> InlineSpan? in + let lower = min(max(span.range.lowerBound - start, 0), length) + let upper = min(max(span.range.upperBound - start, 0), length) + guard lower < upper else { return nil } + var shifted = span + shifted.range = lower.. = [0, length] + for span in spans { + cuts.insert(span.range.lowerBound) + cuts.insert(span.range.upperBound) + } + let sorted = cuts.sorted() + for (lower, upper) in zip(sorted, sorted.dropFirst()) { + var traits: InlineSpan.Traits = [] + var link: String? + for span in spans where span.range.lowerBound <= lower && span.range.upperBound >= upper { + traits.formUnion(span.traits) + if let destination = destination(of: span) { link = destination } + } + let range = NSRange(location: lower, length: upper - lower) + if !traits.intersection([.bold, .italic, .code]).isEmpty { + piece.addAttribute(TranscriptStyle.fontKey, value: style.font(for: block.kind, traits: traits), range: range) + } + if traits.contains(.strikethrough) { + piece.addAttribute(.strikethroughStyle, value: NSUnderlineStyle.single.rawValue, range: range) + } + if traits.contains(.underline) { + piece.addAttribute(.underlineStyle, value: NSUnderlineStyle.single.rawValue, range: range) + } + if let link, let url = URL(string: link) { + piece.addAttribute(.link, value: url, range: range) + } + } + } +} diff --git a/Sources/TranscriptKit/Model/TranscriptDocument.swift b/Sources/TranscriptKit/Model/TranscriptDocument.swift index 4eb56b3..1d73a11 100644 --- a/Sources/TranscriptKit/Model/TranscriptDocument.swift +++ b/Sources/TranscriptKit/Model/TranscriptDocument.swift @@ -420,7 +420,15 @@ public struct TranscriptDocument: Equatable, Sendable { /// Markdown tables and images as their alt text, with a blank line /// between blocks that are not neighbouring list content. public func copyText(in range: Range) -> String { - var result = "" + copiedText(in: range, style: nil).string + } + + /// The text of `copyText(in:)`, with the fonts of `style`, links, + /// strikethrough and underline when `style` is set, and no attributes + /// otherwise. + func copiedText(in range: Range, style: TranscriptStyle?) -> NSAttributedString { + let result = NSMutableAttributedString() + let separatorAttributes = style.map { [TranscriptStyle.fontKey: $0.font(for: .paragraph)] } ?? [:] var previousWasInList = false var start = 0 for block in blocks { @@ -431,25 +439,26 @@ public struct TranscriptDocument: Equatable, Sendable { let lower = max(range.lowerBound, start) let upper = min(range.upperBound, start + length) let includesStart = range.lowerBound <= start && range.upperBound > start - var piece: String + let attributes = style.map { [TranscriptStyle.fontKey: $0.font(for: block.kind)] } ?? [:] + var piece: NSMutableAttributedString switch block.kind { case .rule: guard includesStart else { continue } - piece = "---" + piece = NSMutableAttributedString(string: "---", attributes: attributes) case .table(let table): guard lower < upper || includesStart else { continue } - piece = Self.markdownTable(table, text: block.text, local: (lower - start)..<(upper - start)) + piece = markdownTable(table, of: block, local: (lower - start)..<(upper - start), attributes: attributes, style: style) case .paragraph, .heading, .code: guard lower < upper else { continue } let local = NSRange(location: lower - start, length: upper - lower) - let text = NSMutableString(string: (block.text as NSString).substring(with: local)) + piece = NSMutableAttributedString(string: (block.text as NSString).substring(with: local), attributes: attributes) + if let style { styleSpans(of: block, from: local.location, in: piece, style: style) } // Images by their alt text and formulas by their LaTeX, last // first so offsets stay valid. for span in block.spans.reversed() where local.contains(span.range.lowerBound) { guard let replacement = span.image?.alt ?? span.math?.source else { continue } - text.replaceCharacters(in: NSRange(location: span.range.lowerBound - local.location, length: 1), with: replacement) + piece.replaceCharacters(in: NSRange(location: span.range.lowerBound - local.location, length: 1), with: replacement) } - piece = text as String } // Container prefixes: the first line gets the list marker, later @@ -481,27 +490,49 @@ public struct TranscriptDocument: Equatable, Sendable { // A selection that starts inside the block starts mid-line. if !includesStart { firstPrefix = "" } if !firstPrefix.isEmpty || !restPrefix.isEmpty { - let lines = piece.components(separatedBy: "\n") - piece = lines.enumerated().map { ($0.offset == 0 ? firstPrefix : restPrefix) + $0.element }.joined(separator: "\n") + let prefixed = NSMutableAttributedString() + var lineStart = 0 + func appendLine(upTo end: Int) { + let prefix = lineStart == 0 ? firstPrefix : restPrefix + if !prefix.isEmpty { prefixed.append(NSAttributedString(string: prefix, attributes: attributes)) } + prefixed.append(piece.attributedSubstring(from: NSRange(location: lineStart, length: end - lineStart))) + lineStart = end + } + for (offset, unit) in piece.string.utf16.enumerated() where unit == 0x0A { appendLine(upTo: offset + 1) } + appendLine(upTo: piece.length) + piece = prefixed } let isInList = block.listLevel > 0 - if !result.isEmpty { result += previousWasInList && isInList ? "\n" : "\n\n" } - result += piece + if result.length > 0 { + result.append(NSAttributedString(string: previousWasInList && isInList ? "\n" : "\n\n", attributes: separatorAttributes)) + } + result.append(piece) previousWasInList = isInList } return result } - /// The rows of `table` that `local` touches, as a Markdown table. - private static func markdownTable(_ table: TranscriptTable, text: String, local: Range) -> String { - let string = text as NSString - var lines: [String] = [] + /// The rows of `table` that `local` touches, as a Markdown table. With + /// `style`, each cell keeps the styles of its spans. + private func markdownTable(_ table: TranscriptTable, of block: TranscriptBlock, local: Range, + attributes: [NSAttributedString.Key: Any], style: TranscriptStyle?) -> NSMutableAttributedString { + let string = block.text as NSString + let result = NSMutableAttributedString() + func append(_ text: String) { result.append(NSAttributedString(string: text, attributes: attributes)) } for (index, row) in table.rows.enumerated() { guard let first = row.first, let last = row.last, first.lowerBound < max(local.upperBound, local.lowerBound + 1), last.upperBound >= local.lowerBound else { continue } - let cells = row.map { string.substring(with: NSRange(location: $0.lowerBound, length: $0.count)) } - lines.append("| " + cells.joined(separator: " | ") + " |") + if result.length > 0 { append("\n") } + append("| ") + for (column, cell) in row.enumerated() { + if column > 0 { append(" | ") } + let range = NSRange(location: cell.lowerBound, length: cell.count) + let piece = NSMutableAttributedString(string: string.substring(with: range), attributes: attributes) + if let style { styleSpans(of: block, from: cell.lowerBound, in: piece, style: style) } + result.append(piece) + } + append(" |") if index == 0 { let rule = table.alignments.map { alignment -> String in switch alignment { @@ -510,9 +541,9 @@ public struct TranscriptDocument: Equatable, Sendable { case .trailing: return "---:" } } - lines.append("| " + rule.joined(separator: " | ") + " |") + append("\n| " + rule.joined(separator: " | ") + " |") } } - return lines.joined(separator: "\n") + return result } } diff --git a/Sources/TranscriptKit/iOS/TranscriptTextView.swift b/Sources/TranscriptKit/iOS/TranscriptTextView.swift index 8d2dc69..e0a8938 100644 --- a/Sources/TranscriptKit/iOS/TranscriptTextView.swift +++ b/Sources/TranscriptKit/iOS/TranscriptTextView.swift @@ -1800,6 +1800,7 @@ public final class TranscriptTextView: UIView, UITextInput, UIGestureRecognizerD /// the view resign, and the selection must stay for them. @discardableResult public override func becomeFirstResponder() -> Bool { + addTextInteractionIfNeeded() let became = super.becomeFirstResponder() if became { NotificationCenter.default.post(name: Self.didBecomeFirstResponder, object: self) } return became @@ -1860,10 +1861,14 @@ public final class TranscriptTextView: UIView, UITextInput, UIGestureRecognizerD } } + /// Puts the selected text on the pasteboard as plain text, readable as + /// Markdown (see `TranscriptDocument.copyText(in:)`), and as rich text + /// with the fonts, links, strikethrough and underline of the text. In the + /// rich text, Helvetica Neue takes the place of the system font. nonisolated public override func copy(_ sender: Any?) { onMainThread { guard let range = selectedRange else { return } - UIPasteboard.general.string = shownDocument.copyText(in: range) + UIPasteboard.general.setItems([shownDocument.pasteboardItem(in: range, style: currentLayout.style)]) } } diff --git a/Tests/TranscriptKitTests/MarkdownTests.swift b/Tests/TranscriptKitTests/MarkdownTests.swift index b7202c3..78214a3 100644 --- a/Tests/TranscriptKitTests/MarkdownTests.swift +++ b/Tests/TranscriptKitTests/MarkdownTests.swift @@ -267,6 +267,22 @@ func displayedTextOnlyGrowsWhileStreaming(newlinesAsLineBreaks: Bool) { #expect(document.copyText(in: 0..<5) == "Intro") } +@Test func copyTextPrefixesEveryLineOfABlock() { + let document = MarkdownStreamParser.document(from: "> quoted\n> ```\n> a\n> b\n> ```\n\n- item\n\n ```\n x\n y\n ```\n- last\n") + #expect(document.copyText(in: 0.. quoted + + > a + > b + + - item + x + y + - last + """) + #expect(document.copyText(in: 3.. a\n> b")) +} + @Test func linkHitTestingFindsOnlyTheLinkGlyphs() { let document = MarkdownStreamParser.document(from: "Go to [the site](https://example.com) now") let layout = DocumentLayout(document: document, width: 400) diff --git a/Tests/TranscriptKitTests/RichCopyTests.swift b/Tests/TranscriptKitTests/RichCopyTests.swift new file mode 100644 index 0000000..ecd0b8f --- /dev/null +++ b/Tests/TranscriptKitTests/RichCopyTests.swift @@ -0,0 +1,201 @@ +import CoreText +import Foundation +import Testing +import UniformTypeIdentifiers +@testable import TranscriptKit +#if canImport(UIKit) +import UIKit +#elseif canImport(AppKit) +import AppKit +#endif + +private let markdown = """ +# Title + +Some **bold**, *italic*, `code`, ~~gone~~, under and a [link](https://example.com/a) with an ![alt](u.png) image. + +- one + - nested **item** +2. two + +> quoted *words* + +```swift +let x = 1 +``` + +| a | b | +| - | - | +| **heavy** | [cell](https://example.com/c) | + +--- + +Math \\(x^2\\) and a [ref][r]. + +[r]: https://example.com/r +""" + +private func font(_ text: NSAttributedString, at offset: Int) -> CTFont? { + text.attribute(TranscriptStyle.fontKey, at: offset, effectiveRange: nil).map { $0 as! CTFont } +} + +private func traits(_ text: NSAttributedString, at offset: Int) -> CTFontSymbolicTraits { + font(text, at: offset).map { CTFontGetSymbolicTraits($0) } ?? [] +} + +private func offset(of string: String, in text: NSAttributedString) -> Int { + (text.string as NSString).range(of: string).location +} + +@Test func richCopyHasTheTextOfPlainCopy() { + let document = MarkdownStreamParser.document(from: markdown) + let style = TranscriptStyle() + let length = document.utf16Count + for range in [0.. CTFontGetSize(body)) + #expect(traits(text, at: offset(of: "bold", in: text)).contains(.traitBold)) + #expect(traits(text, at: offset(of: "italic", in: text)).contains(.traitItalic)) + #expect(traits(text, at: offset(of: "words", in: text)).contains(.traitItalic)) + #expect(traits(text, at: offset(of: "item", in: text)).contains(.traitBold)) + #expect(traits(text, at: offset(of: "code", in: text)).contains(.traitMonoSpace)) + #expect(traits(text, at: offset(of: "let x", in: text)).contains(.traitMonoSpace)) + #expect(!traits(text, at: offset(of: "Some", in: text)).contains(.traitBold)) + + let link = text.attribute(.link, at: offset(of: "link", in: text), effectiveRange: nil) as? URL + #expect(link == URL(string: "https://example.com/a")) + let reference = text.attribute(.link, at: offset(of: "ref", in: text), effectiveRange: nil) as? URL + #expect(reference == URL(string: "https://example.com/r")) + #expect(text.attribute(.link, at: offset(of: "Some", in: text), effectiveRange: nil) == nil) + #expect(text.attribute(.strikethroughStyle, at: offset(of: "gone", in: text), effectiveRange: nil) as? Int + == NSUnderlineStyle.single.rawValue) + #expect(text.attribute(.underlineStyle, at: offset(of: "under", in: text), effectiveRange: nil) as? Int + == NSUnderlineStyle.single.rawValue) + #expect(text.attribute(.underlineStyle, at: offset(of: "Some", in: text), effectiveRange: nil) == nil) + + #expect(traits(text, at: offset(of: "heavy", in: text)).contains(.traitBold)) + #expect(!traits(text, at: offset(of: "| a", in: text)).contains(.traitBold)) + let cell = text.attribute(.link, at: offset(of: "cell", in: text), effectiveRange: nil) as? URL + #expect(cell == URL(string: "https://example.com/c")) + #expect(text.attribute(.link, at: offset(of: "| a", in: text), effectiveRange: nil) == nil) + + // Replaced and added text keeps the font of the block it is in. + #expect(font(text, at: offset(of: "alt", in: text)) != nil) + #expect(font(text, at: offset(of: "\\(x^2\\)", in: text)) != nil) + #expect(font(text, at: offset(of: "- one", in: text)) != nil) + #expect(font(text, at: offset(of: "> quoted", in: text)) != nil) +} + +@Test func richCopyStylesOnlyTheSelectedPartOfASpan() { + let document = MarkdownStreamParser.document(from: "plain **bold text** end") + let text = document.copiedText(in: 8..<18, style: TranscriptStyle()) + #expect(text.string == "ld text en") + #expect(traits(text, at: 0).contains(.traitBold)) + #expect(traits(text, at: 6).contains(.traitBold)) + #expect(!traits(text, at: 8).contains(.traitBold)) +} + +@Test func pasteboardItemHasPlainTextAndRTF() throws { + let document = MarkdownStreamParser.document(from: markdown) + let range = 0.. NSFontTraitMask { + let font = read.attribute(.font, at: offset(of: string, in: read), effectiveRange: nil) as? NSFont + return font.map { NSFontManager.shared.traits(of: $0) } ?? [] + } + #expect(readTraits("bold").contains(.boldFontMask)) + #expect(readTraits("italic").contains(.italicFontMask)) + #expect(!readTraits("Some").contains(.boldFontMask)) + let codeFont = read.attribute(.font, at: offset(of: "let x", in: read), effectiveRange: nil) as? NSFont + #expect(codeFont?.isFixedPitch == true) + func readLink(_ string: String) -> String? { + let link = read.attribute(.link, at: offset(of: string, in: read), effectiveRange: nil) + return (link as? URL)?.absoluteString ?? link as? String + } + #expect(readLink("link") == "https://example.com/a") + #expect(readLink("cell") == "https://example.com/c") + #expect(readTraits("heavy").contains(.boldFontMask)) + #expect(read.attribute(.strikethroughStyle, at: offset(of: "gone", in: read), effectiveRange: nil) as? Int + == NSUnderlineStyle.single.rawValue) + #expect(read.attribute(.underlineStyle, at: offset(of: "under", in: read), effectiveRange: nil) as? Int + == NSUnderlineStyle.single.rawValue) + #endif +} + +@Test func richCopyNamesOnlyPublicFonts() throws { + let document = MarkdownStreamParser.document(from: markdown + "\n\n***both*** and **bold *mixed***") + let text = TranscriptDocument.withPublicFonts(document.copiedText(in: 0.. = [] + text.enumerateAttribute(TranscriptStyle.fontKey, in: NSRange(location: 0, length: text.length)) { value, _, _ in + guard let value else { return } + let name = CTFontCopyPostScriptName(value as! CTFont) as String + names.insert(name) + #expect(!name.hasPrefix(".")) + #expect(CTFontCopyPostScriptName(CTFontCreateWithName(name as CFString, 12, nil)) as String == name) + } + #expect(!names.isEmpty) + + let body = try #require(font(text, at: offset(of: "Some", in: text))) + let heading = try #require(font(text, at: offset(of: "Title", in: text))) + #expect(CTFontGetSize(heading) > CTFontGetSize(body)) + #expect(traits(text, at: offset(of: "Title", in: text)).contains(.traitBold)) + #expect(traits(text, at: offset(of: "bold", in: text)).contains(.traitBold)) + #expect(!traits(text, at: offset(of: "bold", in: text)).contains(.traitItalic)) + #expect(traits(text, at: offset(of: "italic", in: text)).contains(.traitItalic)) + #expect(!traits(text, at: offset(of: "italic", in: text)).contains(.traitBold)) + #expect(traits(text, at: offset(of: "both", in: text)).isSuperset(of: [.traitBold, .traitItalic])) + #expect(traits(text, at: offset(of: "mixed", in: text)).isSuperset(of: [.traitBold, .traitItalic])) + #expect(!traits(text, at: offset(of: "Some", in: text)).contains(.traitBold)) + #expect(traits(text, at: offset(of: "code", in: text)).contains(.traitMonoSpace)) + #expect(traits(text, at: offset(of: "let x", in: text)).contains(.traitMonoSpace)) + + let item = document.pasteboardItem(in: 0..