| @@ -6,97 +6,6 @@ import OrgHighlight |
| 6 | import OrgPresentation |
6 | import OrgPresentation |
| 7 | import UIKit |
7 | import UIKit |
| 8 | |
8 | |
| 9 | /// Ranges read by TextKit's delegate callbacks. |
| |
| 10 | final class LockedRanges: @unchecked Sendable { |
| |
| 11 | private let lock = NSLock() |
| |
| 12 | private var ranges: [Range<Int>] = [] |
| |
| 13 | private var starts: Set<Int> = [] |
| |
| 14 | |
| |
| 15 | func set(_ new: [Range<Int>], folded: Set<Int>) { lock.withLock { ranges = new; starts = folded } } |
| |
| 16 | var all: [Range<Int>] { lock.withLock { ranges } } |
| |
| 17 | func covers(_ start: Int, _ end: Int) -> Bool { lock.withLock { ranges.contains { $0.lowerBound <= start && end <= $0.upperBound } } } |
| |
| 18 | func isFolded(_ start: Int) -> Bool { lock.withLock { starts.contains(start) } } |
| |
| 19 | var folded: Set<Int> { lock.withLock { starts } } |
| |
| 20 | func containing(_ offset: Int) -> Range<Int>? { lock.withLock { ranges.first { $0.contains(offset) } } } |
| |
| 21 | } |
| |
| 22 | |
| |
| 23 | /// What layout fragments draw beyond the text, read by TextKit's delegate callbacks. |
| |
| 24 | final class FragmentStyle: @unchecked Sendable { |
| |
| 25 | private let lock = NSLock() |
| |
| 26 | private var band: (color: UIColor, width: CGFloat) = (.clear, 0) |
| |
| 27 | private var selected: (range: Range<Int>, color: UIColor)? |
| |
| 28 | |
| |
| 29 | func set(blockBackground color: UIColor, width: CGFloat) { lock.withLock { band = (color, width) } } |
| |
| 30 | var blockBand: (color: UIColor, width: CGFloat) { lock.withLock { band } } |
| |
| 31 | /// The selection, which a block's fragment draws over its band, as the Mac's fragments do. |
| |
| 32 | func set(selection range: Range<Int>?, color: UIColor) { lock.withLock { selected = range.map { ($0, color) } } } |
| |
| 33 | var selection: (range: Range<Int>, color: UIColor)? { lock.withLock { selected } } |
| |
| 34 | } |
| |
| 35 | |
| |
| 36 | /// A text view that offers hardware-keyboard presses to the editor's keymap first. |
| |
| 37 | final class KeyedTextView: UITextView { |
| |
| 38 | var keyHandler: ((UIKey) -> Bool)? |
| |
| 39 | /// Keys the editor took, whose release the text system doesn't see. Optional: made by |
| |
| 40 | /// UIKit's `init(usingTextLayoutManager:)`, the view skips Swift's default values. |
| |
| 41 | private var handled: Set<UIKeyboardHIDUsage>? |
| |
| 42 | /// Called after each layout pass, as the view's size settles. |
| |
| 43 | var onLayout: (() -> Void)? |
| |
| 44 | /// The text container's width while lines are truncated. |
| |
| 45 | static let truncatedWidth: CGFloat = 100_000 |
| |
| 46 | |
| |
| 47 | /// Long lines run off the right edge and the view scrolls sideways. |
| |
| 48 | var truncates: Bool { |
| |
| 49 | get { !textContainer.widthTracksTextView } |
| |
| 50 | set { |
| |
| 51 | textContainer.widthTracksTextView = !newValue |
| |
| 52 | if newValue { |
| |
| 53 | textContainer.size = CGSize(width: Self.truncatedWidth, height: CGFloat.greatestFiniteMagnitude) |
| |
| 54 | } else { |
| |
| 55 | textContainer.size = CGSize(width: bounds.width - textContainerInset.left - textContainerInset.right, height: CGFloat.greatestFiniteMagnitude) |
| |
| 56 | contentOffset.x = 0 |
| |
| 57 | } |
| |
| 58 | showsHorizontalScrollIndicator = newValue |
| |
| 59 | setNeedsLayout() |
| |
| 60 | } |
| |
| 61 | } |
| |
| 62 | |
| |
| 63 | override func layoutSubviews() { |
| |
| 64 | // The text view sets its container's width to its own when it lays out. |
| |
| 65 | if truncates, textContainer.size.width != Self.truncatedWidth { |
| |
| 66 | textContainer.size = CGSize(width: Self.truncatedWidth, height: CGFloat.greatestFiniteMagnitude) |
| |
| 67 | } |
| |
| 68 | super.layoutSubviews() |
| |
| 69 | // The text view sizes its content to its own width; truncated lines need the widest |
| |
| 70 | // laid-out line's. |
| |
| 71 | if truncates, let manager = textLayoutManager { |
| |
| 72 | let width = ceil(manager.usageBoundsForTextContainer.maxX + textContainerInset.left + textContainerInset.right) |
| |
| 73 | if contentSize.width < width { contentSize.width = width } |
| |
| 74 | } |
| |
| 75 | onLayout?() |
| |
| 76 | } |
| |
| 77 | |
| |
| 78 | override func pressesBegan(_ presses: Set<UIPress>, with event: UIPressesEvent?) { |
| |
| 79 | var rest: Set<UIPress> = [] |
| |
| 80 | for press in presses { |
| |
| 81 | if let key = press.key, keyHandler?(key) == true { |
| |
| 82 | handled = (handled ?? []).union([key.keyCode]) |
| |
| 83 | } else { |
| |
| 84 | rest.insert(press) |
| |
| 85 | } |
| |
| 86 | } |
| |
| 87 | if !rest.isEmpty { super.pressesBegan(rest, with: event) } |
| |
| 88 | } |
| |
| 89 | |
| |
| 90 | override func pressesEnded(_ presses: Set<UIPress>, with event: UIPressesEvent?) { |
| |
| 91 | let rest = presses.filter { press in |
| |
| 92 | guard let code = press.key?.keyCode, handled?.contains(code) == true else { return true } |
| |
| 93 | handled?.remove(code) |
| |
| 94 | return false |
| |
| 95 | } |
| |
| 96 | if !rest.isEmpty { super.pressesEnded(rest, with: event) } |
| |
| 97 | } |
| |
| 98 | } |
| |
| 99 | |
| |
| 100 | /// The iOS editor: a TextKit 2 text view that is the open file's live state, as the Mac's |
9 | /// The iOS editor: a TextKit 2 text view that is the open file's live state, as the Mac's |
| 101 | /// `OrgEditor` is. Typing and undo go through the text view and into the document; commands |
10 | /// `OrgEditor` is. Typing and undo go through the text view and into the document; commands |
| 102 | /// run on the document and apply their edits as one undo step; headings, drawers and blocks |
11 | /// run on the document and apply their edits as one undo step; headings, drawers and blocks |
| @@ -154,32 +63,32 @@ final class MobileEditor: NSObject, DocumentBuffer { |
| 154 | /// Tags used across the workspace, for completion. |
63 | /// Tags used across the workspace, for completion. |
| 155 | var knownTags: @Sendable () -> [String] = { [] } |
64 | var knownTags: @Sendable () -> [String] = { [] } |
| 156 | |
65 | |
| 157 | private var theme: MobileTheme |
66 | var theme: MobileTheme |
| 158 | private(set) var fold = FoldState() |
67 | internal(set) var fold = FoldState() |
| 159 | private var globalVisibility: GlobalVisibility? |
68 | var globalVisibility: GlobalVisibility? |
| 160 | let hidden = LockedRanges() |
69 | let hidden = LockedRanges() |
| 161 | /// Blocks drawn on a band. |
70 | /// Blocks drawn on a band. |
| 162 | let shaded = LockedRanges() |
71 | let shaded = LockedRanges() |
| 163 | let fragmentStyle = FragmentStyle() |
72 | let fragmentStyle = FragmentStyle() |
| 164 | private var selectionColor: UIColor = .clear |
73 | var selectionColor: UIColor = .clear |
| 165 | /// `org-indent-mode` and `org-hide-leading-stars`, from the settings and `#+STARTUP`. |
74 | /// `org-indent-mode` and `org-hide-leading-stars`, from the settings and `#+STARTUP`. |
| 166 | private var indented = true |
75 | var indented = true |
| 167 | private var hideStars = false |
76 | var hideStars = false |
| 168 | /// One paragraph style per indent pair. |
77 | /// One paragraph style per indent pair. |
| 169 | private var paragraphStyles: [[Int]: NSParagraphStyle] = [:] |
78 | var paragraphStyles: [[Int]: NSParagraphStyle] = [:] |
| 170 | /// The line last revealed while markup is hidden, to hide again when the caret leaves. |
79 | /// The line last revealed while markup is hidden, to hide again when the caret leaves. |
| 171 | private var revealedLine: NSRange? |
80 | var revealedLine: NSRange? |
| 172 | /// `org-toggle-inline-images`: lines that are only an image link show the image. |
81 | /// `org-toggle-inline-images`: lines that are only an image link show the image. |
| 173 | private(set) var showsImages = false |
82 | internal(set) var showsImages = false |
| 174 | /// The view width images were last sized for. |
83 | /// The view width images were last sized for. |
| 175 | private var imageWidth: CGFloat = 0 |
84 | var imageWidth: CGFloat = 0 |
| 176 | /// The file's folder, for relative image paths. |
85 | /// The file's folder, for relative image paths. |
| 177 | let baseDirectory: URL? |
86 | let baseDirectory: URL? |
| 178 | private static let imageCache = NSCache<NSString, UIImage>() |
87 | static let imageCache = NSCache<NSString, UIImage>() |
| 179 | private var loading = false |
88 | var loading = false |
| 180 | private var restyleScheduled: Range<Int>? |
89 | var restyleScheduled: Range<Int>? |
| 181 | /// Narrowed table columns (`org-table-shrink`). |
90 | /// Narrowed table columns (`org-table-shrink`). |
| 182 | private var shrunk = ShrunkColumns() |
91 | var shrunk = ShrunkColumns() |
| 183 | /// A command's edits being applied, which keep shrunk columns narrow. |
92 | /// A command's edits being applied, which keep shrunk columns narrow. |
| 184 | private var commandEditing = false |
93 | private var commandEditing = false |
| 185 | |
94 | |
| @@ -504,451 +413,13 @@ final class MobileEditor: NSObject, DocumentBuffer { |
| 504 | } |
413 | } |
| 505 | |
414 | |
| 506 | /// Starts after the edit move with it; ones inside it go. |
415 | /// Starts after the edit move with it; ones inside it go. |
| 507 | private static func map(_ starts: Set<Int>, _ old: Range<Int>, _ delta: Int) -> Set<Int> { |
416 | static func map(_ starts: Set<Int>, _ old: Range<Int>, _ delta: Int) -> Set<Int> { |
| 508 | Set(starts.compactMap { start in |
417 | Set(starts.compactMap { start in |
| 509 | if start >= old.upperBound { return start + delta } |
418 | if start >= old.upperBound { return start + delta } |
| 510 | return start <= old.lowerBound ? start : nil |
419 | return start <= old.lowerBound ? start : nil |
| 511 | }) |
420 | }) |
| 512 | } |
421 | } |
| 513 | |
422 | |
| 514 | // MARK: - Styling |
| |
| 515 | |
| |
| 516 | private func load(_ text: String) { |
| |
| 517 | loading = true |
| |
| 518 | textView.textStorage.setAttributedString(NSAttributedString(string: text, attributes: theme.base)) |
| |
| 519 | loading = false |
| |
| 520 | shaded.set(Presentation.shadedBlocks(document.tree), folded: []) |
| |
| 521 | restyle(0..<(text as NSString).length) |
| |
| 522 | textView.typingAttributes = theme.base |
| |
| 523 | } |
| |
| 524 | |
| |
| 525 | /// The text view's own colors, and the block band's. |
| |
| 526 | private func applyThemeToView() { |
| |
| 527 | textView.backgroundColor = theme.color("background") ?? .systemBackground |
| |
| 528 | textView.tintColor = theme.color("cursor") |
| |
| 529 | textView.typingAttributes = theme.base |
| |
| 530 | fragmentStyle.set(blockBackground: theme.color("block-background") ?? .clear, width: textView.bounds.width) |
| |
| 531 | themeSelection() |
| |
| 532 | } |
| |
| 533 | |
| |
| 534 | /// The selection in the theme's selection color: the text view's selection display |
| |
| 535 | /// interaction draws it with our highlight view; the cursor and handles keep the tint. |
| |
| 536 | private func themeSelection() { |
| |
| 537 | guard let interaction = textView.interactions.lazy.compactMap({ $0 as? UITextSelectionDisplayInteraction }).first else { return } |
| |
| 538 | let view = interaction.highlightView as? SelectionHighlightView ?? SelectionHighlightView() |
| |
| 539 | view.color = theme.color("selection") ?? UIColor.tintColor.withAlphaComponent(0.25) |
| |
| 540 | if interaction.highlightView !== view { interaction.highlightView = view } |
| |
| 541 | selectionColor = view.color |
| |
| 542 | } |
| |
| 543 | |
| |
| 544 | /// The highlight view draws under the text, so a block's band would cover it: blocks the |
| |
| 545 | /// selection enters or leaves are laid out again to draw it over their band. |
| |
| 546 | private func redrawSelectedBlocks() { |
| |
| 547 | let selected = textView.selectedRange |
| |
| 548 | let range = selected.length > 0 ? selected.location..<NSMaxRange(selected) : nil |
| |
| 549 | let old = fragmentStyle.selection?.range |
| |
| 550 | fragmentStyle.set(selection: range, color: selectionColor) |
| |
| 551 | let touched = [old, range].compactMap { $0 } |
| |
| 552 | redraw(blocks: shaded.all.filter { block in touched.contains { $0.overlaps(block) } }) |
| |
| 553 | } |
| |
| 554 | |
| |
| 555 | /// Lays `blocks` out again and asks their fragments, which are kept across layout passes, |
| |
| 556 | /// to draw again. |
| |
| 557 | private func redraw(blocks: [Range<Int>]) { |
| |
| 558 | guard let manager = textView.textLayoutManager, let content = manager.textContentManager else { return } |
| |
| 559 | for block in blocks { |
| |
| 560 | guard let start = content.location(content.documentRange.location, offsetBy: block.lowerBound), |
| |
| 561 | let end = content.location(start, offsetBy: block.count), |
| |
| 562 | let textRange = NSTextRange(location: start, end: end) else { continue } |
| |
| 563 | manager.invalidateRenderingAttributes(for: textRange) |
| |
| 564 | manager.invalidateLayout(for: textRange) |
| |
| 565 | } |
| |
| 566 | textView.setNeedsDisplay() |
| |
| 567 | } |
| |
| 568 | |
| |
| 569 | /// The band behind blocks spans the view's width, or the widest line's when truncated; |
| |
| 570 | /// images are as wide as the view allows. Only the blocks read the band's width, so a |
| |
| 571 | /// wider line in a truncated file, which widens the band on each layout pass, redraws |
| |
| 572 | /// the blocks alone: laying the whole file out again moves the text under the view. |
| |
| 573 | private func viewResized() { |
| |
| 574 | let band = fragmentStyle.blockBand |
| |
| 575 | let width = max(textView.bounds.width, truncatesLines ? textView.contentSize.width : 0) |
| |
| 576 | let resized = imageWidth != textView.bounds.width |
| |
| 577 | guard band.width != width || resized else { return } |
| |
| 578 | fragmentStyle.set(blockBackground: band.color, width: width) |
| |
| 579 | imageWidth = textView.bounds.width |
| |
| 580 | guard resized else { |
| |
| 581 | redraw(blocks: shaded.all) |
| |
| 582 | return |
| |
| 583 | } |
| |
| 584 | keepingTopLine { |
| |
| 585 | if showsImages { restyle(0..<textView.textStorage.length) } |
| |
| 586 | if let manager = textView.textLayoutManager { |
| |
| 587 | manager.invalidateRenderingAttributes(for: manager.documentRange) |
| |
| 588 | manager.invalidateLayout(for: manager.documentRange) |
| |
| 589 | } |
| |
| 590 | } |
| |
| 591 | } |
| |
| 592 | |
| |
| 593 | /// Styles the whole file again. |
| |
| 594 | private func restyleAll() { |
| |
| 595 | let interval = Perf.begin("editor.restyleAll") |
| |
| 596 | defer { interval.end() } |
| |
| 597 | keepingTopLine { |
| |
| 598 | restyle(0..<textView.textStorage.length) |
| |
| 599 | if let manager = textView.textLayoutManager { manager.invalidateLayout(for: manager.documentRange) } |
| |
| 600 | } |
| |
| 601 | } |
| |
| 602 | |
| |
| 603 | /// Lays out `ranges` again, each widened to whole lines and to the line before it: the |
| |
| 604 | /// heading or opening line of a fold, whose fragment draws the fold mark. Laying out the |
| |
| 605 | /// whole file again makes TextKit estimate the height of everything above the view afresh, |
| |
| 606 | /// which moves the text under it. |
| |
| 607 | private func invalidateLayout(lines ranges: [Range<Int>]) { |
| |
| 608 | guard !ranges.isEmpty, let manager = textView.textLayoutManager, let content = manager.textContentManager else { return } |
| |
| 609 | let text = textView.textStorage.string as NSString |
| |
| 610 | for range in ranges { |
| |
| 611 | let lower = text.lineRange(for: NSRange(location: max(0, min(range.lowerBound, text.length) - 1), length: 0)).location |
| |
| 612 | let upper = NSMaxRange(text.lineRange(for: NSRange(location: min(range.upperBound, text.length), length: 0))) |
| |
| 613 | guard let start = content.location(content.documentRange.location, offsetBy: lower), |
| |
| 614 | let end = content.location(start, offsetBy: upper - lower), |
| |
| 615 | let textRange = NSTextRange(location: start, end: end) else { continue } |
| |
| 616 | manager.invalidateLayout(for: textRange) |
| |
| 617 | } |
| |
| 618 | } |
| |
| 619 | |
| |
| 620 | /// Runs `change`, which lays the whole file out again, and brings the line that was at the |
| |
| 621 | /// top of the view back there. TextKit estimates the height of text it hasn't laid out, |
| |
| 622 | /// so the same scroll position lands on different text after a fresh layout. |
| |
| 623 | private func keepingTopLine(_ change: () -> Void) { |
| |
| 624 | guard let manager = textView.textLayoutManager, let content = manager.textContentManager else { return change() } |
| |
| 625 | let inset = textView.textContainerInset |
| |
| 626 | let top = textView.contentOffset.y + textView.adjustedContentInset.top - inset.top |
| |
| 627 | let start = content.documentRange.location |
| |
| 628 | let anchor = manager.textLayoutFragment(for: CGPoint(x: 0, y: max(0, top))).map { |
| |
| 629 | (offset: content.offset(from: start, to: $0.rangeInElement.location), within: top - $0.layoutFragmentFrame.minY) |
| |
| 630 | } |
| |
| 631 | change() |
| |
| 632 | guard let anchor, anchor.offset > 0, let location = content.location(start, offsetBy: anchor.offset), |
| |
| 633 | let above = NSTextRange(location: start, end: location) else { return } |
| |
| 634 | manager.ensureLayout(for: above) |
| |
| 635 | guard let fragment = manager.textLayoutFragment(for: location) else { return } |
| |
| 636 | let frame = fragment.layoutFragmentFrame |
| |
| 637 | manager.ensureLayout(for: CGRect(x: 0, y: frame.minY, width: frame.width, height: 2 * textView.bounds.height)) |
| |
| 638 | // The view grows to the laid-out height on its next layout pass; the scroll needs it now. |
| |
| 639 | let needed = manager.usageBoundsForTextContainer.maxY + inset.top + inset.bottom |
| |
| 640 | if textView.contentSize.height < needed { textView.contentSize.height = needed } |
| |
| 641 | let y = frame.minY + inset.top + max(0, min(anchor.within, frame.height)) - textView.adjustedContentInset.top |
| |
| 642 | textView.contentOffset = CGPoint(x: textView.contentOffset.x, y: y) |
| |
| 643 | } |
| |
| 644 | |
| |
| 645 | /// Styles are set after the edit has been processed, as TextKit asks. |
| |
| 646 | private func scheduleRestyle(_ range: Range<Int>) { |
| |
| 647 | if let pending = restyleScheduled { |
| |
| 648 | restyleScheduled = min(pending.lowerBound, range.lowerBound)..<max(pending.upperBound, range.upperBound) |
| |
| 649 | return |
| |
| 650 | } |
| |
| 651 | restyleScheduled = range |
| |
| 652 | DispatchQueue.main.async { [weak self] in |
| |
| 653 | guard let self, let range = self.restyleScheduled else { return } |
| |
| 654 | self.restyleScheduled = nil |
| |
| 655 | self.shaded.set(Presentation.shadedBlocks(self.document.tree), folded: []) |
| |
| 656 | // Small files are restyled whole: a heading or block line changes what follows it. |
| |
| 657 | let length = self.textView.textStorage.length |
| |
| 658 | self.restyle(length < 60_000 ? 0..<length : range) |
| |
| 659 | self.updateHidden() |
| |
| 660 | self.textView.typingAttributes = self.theme.base |
| |
| 661 | } |
| |
| 662 | } |
| |
| 663 | |
| |
| 664 | private var caretLine: NSRange { |
| |
| 665 | let text = textView.textStorage.string as NSString |
| |
| 666 | return text.lineRange(for: NSRange(location: min(textView.selectedRange.location, text.length), length: 0)) |
| |
| 667 | } |
| |
| 668 | |
| |
| 669 | /// Sets attributes for the whole lines in `range`, as the Mac editor does. |
| |
| 670 | private func restyle(_ range: Range<Int>) { |
| |
| 671 | let interval = Perf.begin("editor.restyle") |
| |
| 672 | defer { interval.end() } |
| |
| 673 | let storage = textView.textStorage |
| |
| 674 | let ns = storage.string as NSString |
| |
| 675 | guard ns.length > 0 else { return } |
| |
| 676 | let lower = min(range.lowerBound, ns.length) |
| |
| 677 | let lines = ns.lineRange(for: NSRange(location: lower, length: min(range.count, ns.length - lower))) |
| |
| 678 | let whole = lines.location..<NSMaxRange(lines) |
| |
| 679 | storage.beginEditing() |
| |
| 680 | storage.setAttributes(theme.base, range: lines) |
| |
| 681 | if indented { |
| |
| 682 | for line in Presentation.lineIndents(document.tree, in: whole) { |
| |
| 683 | storage.addAttribute(.paragraphStyle, value: paragraphStyle(line.firstLine, line.wrapped), range: NSRange(line.range)) |
| |
| 684 | } |
| |
| 685 | } |
| |
| 686 | let revealed = caretLine |
| |
| 687 | var scriptExclusions: [Range<Int>] = [] |
| |
| 688 | for run in Presentation.styles(document.tree, in: whole, highlighter: Self.highlighter) { |
| |
| 689 | let clipped = NSIntersectionRange(NSRange(run.range), lines) |
| |
| 690 | guard clipped.length > 0 else { continue } |
| |
| 691 | if Presentation.skipsLeadingStars(run.role, indented: indented, hideStars: hideStars) { continue } |
| |
| 692 | if !showMarkup, Presentation.hidesWithMarkup(run.role, options: options), NSIntersectionRange(clipped, revealed).length == 0 { |
| |
| 693 | storage.addAttributes(theme.hidden, range: clipped) |
| |
| 694 | } else { |
| |
| 695 | theme.apply(run.role, to: storage, range: clipped) |
| |
| 696 | } |
| |
| 697 | if Presentation.excludesScripts(run.role) { scriptExclusions.append(run.range) } |
| |
| 698 | } |
| |
| 699 | if !showMarkup, options.prettyEntities { prettify(whole, in: storage, revealed: revealed, scriptExclusions: scriptExclusions) } |
| |
| 700 | applyShrunk(whole, in: storage) |
| |
| 701 | applyImages(whole, in: storage, revealed: revealed) |
| |
| 702 | storage.endEditing() |
| |
| 703 | } |
| |
| 704 | |
| |
| 705 | private func paragraphStyle(_ firstLine: Int, _ wrapped: Int) -> NSParagraphStyle { |
| |
| 706 | if let style = paragraphStyles[[firstLine, wrapped]] { return style } |
| |
| 707 | let style = theme.paragraphStyle(firstLine: firstLine, wrapped: wrapped) |
| |
| 708 | paragraphStyles[[firstLine, wrapped]] = style |
| |
| 709 | return style |
| |
| 710 | } |
| |
| 711 | |
| |
| 712 | /// `org-pretty-entities`: entities drawn as their character over the entity's last |
| |
| 713 | /// character (the rest hidden), sub/superscripts raised without their markers. |
| |
| 714 | private func prettify(_ range: Range<Int>, in storage: NSTextStorage, revealed: NSRange, scriptExclusions: [Range<Int>]) { |
| |
| 715 | let runs = Presentation.prettyRuns( |
| |
| 716 | storage.string as NSString, in: range, revealedLine: revealed.location, inBlock: { shaded.containing($0) != nil }, |
| |
| 717 | scriptExclusions: scriptExclusions, subSuperscriptsNeedBraces: options.subSuperscriptsNeedBraces |
| |
| 718 | ) |
| |
| 719 | for (lineStart, run) in runs { |
| |
| 720 | switch run { |
| |
| 721 | case .entity(let r, let display): |
| |
| 722 | let start = lineStart + r.lowerBound |
| |
| 723 | let last = lineStart + r.upperBound - 1 |
| |
| 724 | let color = storage.attribute(.foregroundColor, at: last, effectiveRange: nil) as? UIColor ?? theme.foreground |
| |
| 725 | if last > start { storage.addAttributes(theme.hidden, range: NSRange(location: start, length: last - start)) } |
| |
| 726 | storage.addAttributes([.foregroundColor: UIColor.clear, .orgEntityDisplay: display, .orgEntityColor: color], range: NSRange(location: last, length: 1)) |
| |
| 727 | case .script(let markers, let body, let superscript): |
| |
| 728 | for marker in markers { |
| |
| 729 | storage.addAttributes(theme.hidden, range: NSRange(location: lineStart + marker.lowerBound, length: marker.count)) |
| |
| 730 | } |
| |
| 731 | let size = theme.font.pointSize |
| |
| 732 | storage.addAttributes([ |
| |
| 733 | .font: theme.font.withSize(size * 0.7), |
| |
| 734 | .baselineOffset: (superscript ? 0.3 : -0.3) * size, |
| |
| 735 | ], range: NSRange(location: lineStart + body.lowerBound, length: body.count)) |
| |
| 736 | } |
| |
| 737 | } |
| |
| 738 | } |
| |
| 739 | |
| |
| 740 | /// Moving to another line shows its markup and hides the last one's. |
| |
| 741 | private func revealCaretLine() { |
| |
| 742 | guard !showMarkup else { return } |
| |
| 743 | let line = caretLine |
| |
| 744 | guard line != revealedLine else { return } |
| |
| 745 | let text = textView.textStorage.string as NSString |
| |
| 746 | // The old line may have moved with edits since; restyle the line now at its start. |
| |
| 747 | let old = revealedLine.flatMap { $0.location <= text.length ? text.lineRange(for: NSRange(location: $0.location, length: 0)) : nil } |
| |
| 748 | revealedLine = line |
| |
| 749 | for range in [old, line].compactMap({ $0 }) { |
| |
| 750 | restyle(range.location..<NSMaxRange(range)) |
| |
| 751 | } |
| |
| 752 | } |
| |
| 753 | |
| |
| 754 | // MARK: - Shrunk table columns |
| |
| 755 | |
| |
| 756 | /// C-c TAB in a table: `org-table-toggle-column-width`; `shrink` for `org-table-shrink`, |
| |
| 757 | /// `expand` for `org-table-expand`. |
| |
| 758 | private func tableColumnWidth(_ id: String) { |
| |
| 759 | switch shrunk.change(for: id, at: textView.selectedRange.location, in: textView.textStorage.string) { |
| |
| 760 | case .notInTable: onMessage?("Not in a table") |
| |
| 761 | case .set(let columns, let table): setShrunk(columns, in: table) |
| |
| 762 | case .ask(let table, let current, let max): |
| |
| 763 | onPrompt?(Prompt(key: "columns", message: "Column ranges (e.g. 2-4 6-):")) { [weak self] answer in |
| |
| 764 | guard let self, let answer else { return } |
| |
| 765 | self.setShrunk(ShrunkColumns.toggled(current, TableShrink.columns(answer, max: max)), in: table) |
| |
| 766 | } |
| |
| 767 | } |
| |
| 768 | } |
| |
| 769 | |
| |
| 770 | /// Narrows `columns` of `table` and widens its others. |
| |
| 771 | private func setShrunk(_ columns: [Int], in table: Range<Int>) { |
| |
| 772 | shrunk.set(columns, in: table, text: textView.textStorage.string) |
| |
| 773 | restyle(table) |
| |
| 774 | invalidateLayout(lines: [table]) |
| |
| 775 | } |
| |
| 776 | |
| |
| 777 | /// Hides each shrunk segment's text and draws its display where the text was, as pretty |
| |
| 778 | /// entities draw theirs. |
| |
| 779 | private func applyShrunk(_ range: Range<Int>, in storage: NSTextStorage) { |
| |
| 780 | guard !shrunk.isEmpty else { return } |
| |
| 781 | let cell = theme.column |
| |
| 782 | for segment in shrunk.segments where segment.range.overlaps(range) && segment.range.upperBound <= storage.length { |
| |
| 783 | let r = segment.range |
| |
| 784 | let shown = segment.display.count |
| |
| 785 | let kept = min(shown, r.count) |
| |
| 786 | if r.count > kept { storage.addAttributes(theme.hidden, range: NSRange(location: r.lowerBound, length: r.count - kept)) } |
| |
| 787 | guard kept > 0 else { continue } |
| |
| 788 | let visible = NSRange(location: r.upperBound - kept, length: kept) |
| |
| 789 | let color = storage.attribute(.foregroundColor, at: visible.location, effectiveRange: nil) as? UIColor ?? theme.foreground |
| |
| 790 | storage.addAttribute(.foregroundColor, value: UIColor.clear, range: visible) |
| |
| 791 | storage.addAttributes([.orgEntityDisplay: segment.display, .orgEntityColor: color], range: NSRange(location: visible.location, length: 1)) |
| |
| 792 | if shown > kept { storage.addAttribute(.kern, value: CGFloat(shown - kept) * cell, range: NSRange(location: NSMaxRange(visible) - 1, length: 1)) } |
| |
| 793 | } |
| |
| 794 | } |
| |
| 795 | |
| |
| 796 | // MARK: - Inline images |
| |
| 797 | |
| |
| 798 | private func toggleImages() { |
| |
| 799 | showsImages.toggle() |
| |
| 800 | restyleAll() |
| |
| 801 | if showsImages { |
| |
| 802 | let ns = textView.textStorage.string as NSString |
| |
| 803 | var count = 0 |
| |
| 804 | var offset = 0 |
| |
| 805 | while offset < ns.length { |
| |
| 806 | let line = ns.lineRange(for: NSRange(location: offset, length: 0)) |
| |
| 807 | if let image = InlineImages.image(atLine: line.location, in: ns), Self.loadImage(image.path, relativeTo: baseDirectory) != nil { count += 1 } |
| |
| 808 | offset = NSMaxRange(line) |
| |
| 809 | } |
| |
| 810 | onMessage?("\(count) images displayed inline") |
| |
| 811 | } else { |
| |
| 812 | onMessage?("Inline image display turned off") |
| |
| 813 | } |
| |
| 814 | } |
| |
| 815 | |
| |
| 816 | /// An image link's image, by its path or one relative to `baseDirectory`. |
| |
| 817 | static func loadImage(_ path: String, relativeTo baseDirectory: URL?) -> UIImage? { |
| |
| 818 | let expanded = (path as NSString).expandingTildeInPath |
| |
| 819 | let url: URL |
| |
| 820 | if expanded.hasPrefix("/") { |
| |
| 821 | url = URL(fileURLWithPath: expanded) |
| |
| 822 | } else if let baseDirectory { |
| |
| 823 | url = baseDirectory.appendingPathComponent(expanded) |
| |
| 824 | } else { |
| |
| 825 | return nil |
| |
| 826 | } |
| |
| 827 | let modified = (try? url.resourceValues(forKeys: [.contentModificationDateKey]))?.contentModificationDate?.timeIntervalSince1970 ?? 0 |
| |
| 828 | let key = "\(url.path)|\(modified)" as NSString |
| |
| 829 | if let cached = Self.imageCache.object(forKey: key) { return cached } |
| |
| 830 | guard let image = UIImage(contentsOfFile: url.path) else { return nil } |
| |
| 831 | Self.imageCache.setObject(image, forKey: key) |
| |
| 832 | return image |
| |
| 833 | } |
| |
| 834 | |
| |
| 835 | /// Image lines in `range` show the image over the link, which is hidden unless the caret is |
| |
| 836 | /// on the line. |
| |
| 837 | private func applyImages(_ range: Range<Int>, in storage: NSTextStorage, revealed: NSRange) { |
| |
| 838 | guard showsImages else { return } |
| |
| 839 | let text = storage.string as NSString |
| |
| 840 | let inset = textView.textContainerInset |
| |
| 841 | let maxWidth = max(80, textView.bounds.width - inset.left - inset.right - 40) |
| |
| 842 | var location = range.lowerBound |
| |
| 843 | while location < range.upperBound, location < text.length { |
| |
| 844 | let line = text.lineRange(for: NSRange(location: location, length: 0)) |
| |
| 845 | location = NSMaxRange(line) |
| |
| 846 | guard let image = InlineImages.image(atLine: line.location, in: text), let picture = Self.loadImage(image.path, relativeTo: baseDirectory) else { continue } |
| |
| 847 | let width = min(image.width.map(CGFloat.init) ?? picture.size.width, maxWidth) |
| |
| 848 | let height = picture.size.width > 0 ? width * picture.size.height / picture.size.width : 0 |
| |
| 849 | let content = NSRange(location: line.location, length: line.length - (text.substring(with: line).hasSuffix("\n") ? 1 : 0)) |
| |
| 850 | // Invisible, keeping the line's height. |
| |
| 851 | if line.location != revealed.location, content.length > 0 { |
| |
| 852 | storage.addAttributes([.foregroundColor: UIColor.clear, .underlineStyle: 0], range: content) |
| |
| 853 | } |
| |
| 854 | storage.addAttribute(.orgImage, value: InlineImageBox(image: picture, size: CGSize(width: width, height: height)), range: NSRange(location: line.location, length: max(1, content.length))) |
| |
| 855 | let style = (storage.attribute(.paragraphStyle, at: line.location, effectiveRange: nil) as? NSParagraphStyle)?.mutableCopy() as? NSMutableParagraphStyle ?? NSMutableParagraphStyle() |
| |
| 856 | // The image sits where the line is; the spacing makes room for the rest of it. |
| |
| 857 | style.paragraphSpacing = max(0, height + 4 - theme.font.lineHeight) |
| |
| 858 | storage.addAttribute(.paragraphStyle, value: style, range: line) |
| |
| 859 | } |
| |
| 860 | } |
| |
| 861 | |
| |
| 862 | // MARK: - Truncation |
| |
| 863 | |
| |
| 864 | /// `toggle-truncate-lines`: long lines run off the right edge, scrolling sideways, instead |
| |
| 865 | /// of wrapping. |
| |
| 866 | var truncatesLines: Bool { |
| |
| 867 | get { (textView as? KeyedTextView)?.truncates ?? false } |
| |
| 868 | set { |
| |
| 869 | guard newValue != truncatesLines, let view = textView as? KeyedTextView else { return } |
| |
| 870 | keepingTopLine { |
| |
| 871 | view.truncates = newValue |
| |
| 872 | if let manager = textView.textLayoutManager { manager.invalidateLayout(for: manager.documentRange) } |
| |
| 873 | } |
| |
| 874 | } |
| |
| 875 | } |
| |
| 876 | |
| |
| 877 | // MARK: - Folding |
| |
| 878 | |
| |
| 879 | func setFolds(_ state: FoldState) { |
| |
| 880 | fold = state |
| |
| 881 | updateHidden() |
| |
| 882 | } |
| |
| 883 | |
| |
| 884 | private func updateHidden() { |
| |
| 885 | let tree = document.tree |
| |
| 886 | let wrappers = fold.wrapperFolds.compactMap { Wrappers.starting(at: $0, in: tree)?.hidden } |
| |
| 887 | let before = hidden.folded |
| |
| 888 | let oldHidden = hidden.all |
| |
| 889 | hidden.set( |
| |
| 890 | Presentation.hiddenRanges(tree, folds: fold.folds, bodyFolds: fold.bodyFolds, wrapperRanges: wrappers), |
| |
| 891 | folded: fold.folds.union(fold.bodyFolds).union(fold.wrapperFolds) |
| |
| 892 | ) |
| |
| 893 | // Lines that gain or lose their `…` are made again: TextKit keeps a shown line's fragment. |
| |
| 894 | let storage = textView.textStorage |
| |
| 895 | let changed = before.symmetricDifference(hidden.folded).filter { $0 < storage.length } |
| |
| 896 | if !changed.isEmpty { |
| |
| 897 | let text = storage.string as NSString |
| |
| 898 | storage.beginEditing() |
| |
| 899 | for start in changed { storage.edited(.editedAttributes, range: text.lineRange(for: NSRange(location: start, length: 0)), changeInLength: 0) } |
| |
| 900 | storage.endEditing() |
| |
| 901 | } |
| |
| 902 | invalidateLayout(lines: Array(Set(oldHidden).symmetricDifference(hidden.all))) |
| |
| 903 | textView.setNeedsDisplay() |
| |
| 904 | } |
| |
| 905 | |
| |
| 906 | /// TAB at the caret: a heading cycles, a drawer or block opens or closes. |
| |
| 907 | @discardableResult |
| |
| 908 | func cycleAtCaret() -> Bool { |
| |
| 909 | guard let next = Presentation.cycle(at: textView.selectedRange.location, in: document.tree, fold) else { return false } |
| |
| 910 | setFolds(next) |
| |
| 911 | return true |
| |
| 912 | } |
| |
| 913 | |
| |
| 914 | /// Shift-TAB: overview, contents, show all. |
| |
| 915 | func cycleGlobal() { |
| |
| 916 | let (visibility, state) = Presentation.cycleGlobal(from: globalVisibility, in: document.tree, wrapperFolds: fold.wrapperFolds) |
| |
| 917 | globalVisibility = visibility |
| |
| 918 | setFolds(state) |
| |
| 919 | } |
| |
| 920 | |
| |
| 921 | /// Opens the folds hiding `offset`. |
| |
| 922 | func unfold(around offset: Int) { |
| |
| 923 | var state = fold |
| |
| 924 | for entry in Presentation.outline(document.tree) where entry.start < offset && offset < entry.end { |
| |
| 925 | state.folds.remove(entry.start) |
| |
| 926 | state.bodyFolds.remove(entry.start) |
| |
| 927 | } |
| |
| 928 | for start in state.wrapperFolds where Wrappers.starting(at: start, in: document.tree)?.hidden.contains(offset) == true { |
| |
| 929 | state.wrapperFolds.remove(start) |
| |
| 930 | } |
| |
| 931 | if state != fold { setFolds(state) } |
| |
| 932 | } |
| |
| 933 | |
| |
| 934 | /// Shows the heading at `offset`, unfolded, at the top. |
| |
| 935 | func reveal(_ offset: Int) { |
| |
| 936 | let length = textView.textStorage.length |
| |
| 937 | let target = min(max(0, offset), length) |
| |
| 938 | unfold(around: target) |
| |
| 939 | textView.selectedRange = NSRange(location: target, length: 0) |
| |
| 940 | textView.scrollRangeToVisible(NSRange(location: target, length: 0)) |
| |
| 941 | } |
| |
| 942 | |
| |
| 943 | /// The caret left hidden text (a tap past a fold): what hides it opens. |
| |
| 944 | fileprivate func selectionChanged() { |
| |
| 945 | let interval = Perf.begin("editor.selection") |
| |
| 946 | defer { interval.end() } |
| |
| 947 | redrawSelectedBlocks() |
| |
| 948 | let caret = textView.selectedRange.location |
| |
| 949 | if hidden.containing(caret) != nil { unfold(around: caret) } |
| |
| 950 | revealCaretLine() |
| |
| 951 | } |
| |
| 952 | } |
423 | } |
| 953 | |
424 | |
| 954 | extension MobileEditor: UITextViewDelegate { |
425 | extension MobileEditor: UITextViewDelegate { |
| @@ -1057,153 +528,4 @@ extension MobileEditor: NSTextLayoutManagerDelegate { |
| 1057 | return fragment |
528 | return fragment |
| 1058 | } |
529 | } |
| 1059 | } |
530 | } |
| 1060 | |
| |
| 1061 | extension NSAttributedString.Key { |
| |
| 1062 | /// The character an entity shows as, on the entity's last character. |
| |
| 1063 | static let orgEntityDisplay = NSAttributedString.Key("OrgEntityDisplay") |
| |
| 1064 | /// The color the entity's character is drawn in. |
| |
| 1065 | static let orgEntityColor = NSAttributedString.Key("OrgEntityColor") |
| |
| 1066 | /// The image an image link's line shows under it. |
| |
| 1067 | static let orgImage = NSAttributedString.Key("OrgImage") |
| |
| 1068 | } |
| |
| 1069 | |
| |
| 1070 | final class InlineImageBox: NSObject, @unchecked Sendable { |
| |
| 1071 | let image: UIImage |
| |
| 1072 | let size: CGSize |
| |
| 1073 | init(image: UIImage, size: CGSize) { |
| |
| 1074 | self.image = image |
| |
| 1075 | self.size = size |
| |
| 1076 | } |
| |
| 1077 | } |
| |
| 1078 | |
| |
| 1079 | /// Selected text's background, in one color however the rects overlap. |
| |
| 1080 | final class SelectionHighlightView: UIView, UITextSelectionHighlightView { |
| |
| 1081 | var selectionRects: [UITextSelectionRect] = [] { didSet { setNeedsDisplay() } } |
| |
| 1082 | var color: UIColor = .clear { didSet { setNeedsDisplay() } } |
| |
| 1083 | |
| |
| 1084 | override init(frame: CGRect) { |
| |
| 1085 | super.init(frame: frame) |
| |
| 1086 | isOpaque = false |
| |
| 1087 | backgroundColor = .clear |
| |
| 1088 | isUserInteractionEnabled = false |
| |
| 1089 | registerForTraitChanges([UITraitUserInterfaceStyle.self]) { (view: SelectionHighlightView, _) in view.setNeedsDisplay() } |
| |
| 1090 | } |
| |
| 1091 | |
| |
| 1092 | required init?(coder: NSCoder) { fatalError("init(coder:) is not used") } |
| |
| 1093 | |
| |
| 1094 | override func draw(_ rect: CGRect) { |
| |
| 1095 | let path = UIBezierPath() |
| |
| 1096 | for selection in selectionRects where !selection.rect.isEmpty { path.append(UIBezierPath(rect: selection.rect)) } |
| |
| 1097 | color.setFill() |
| |
| 1098 | path.fill() |
| |
| 1099 | } |
| |
| 1100 | } |
| |
| 1101 | |
| |
| 1102 | /// A line drawn with more than its text, as the Mac editor's fragments draw them: a folded |
| |
| 1103 | /// line's ellipsis, a block's band across the view, an image under an image link, and pretty |
| |
| 1104 | /// entities' characters where the entities' last (invisible) characters sit. |
| |
| 1105 | final class OrgLineFragment: NSTextLayoutFragment, @unchecked Sendable { |
| |
| 1106 | var folded = false |
| |
| 1107 | var band: (color: UIColor, width: CGFloat)? |
| |
| 1108 | var image: InlineImageBox? |
| |
| 1109 | /// For a block's lines: where the fragment starts, and where the selection is read. |
| |
| 1110 | var start = 0 |
| |
| 1111 | var style: FragmentStyle? |
| |
| 1112 | |
| |
| 1113 | static func image(_ string: NSAttributedString) -> InlineImageBox? { |
| |
| 1114 | var found: InlineImageBox? |
| |
| 1115 | string.enumerateAttribute(.orgImage, in: NSRange(location: 0, length: string.length)) { value, _, stop in |
| |
| 1116 | if let box = value as? InlineImageBox { found = box; stop.pointee = true } |
| |
| 1117 | } |
| |
| 1118 | return found |
| |
| 1119 | } |
| |
| 1120 | |
| |
| 1121 | static func hasEntities(_ string: NSAttributedString) -> Bool { |
| |
| 1122 | var found = false |
| |
| 1123 | string.enumerateAttribute(.orgEntityDisplay, in: NSRange(location: 0, length: string.length)) { value, _, stop in |
| |
| 1124 | if value != nil { found = true; stop.pointee = true } |
| |
| 1125 | } |
| |
| 1126 | return found |
| |
| 1127 | } |
| |
| 1128 | |
| |
| 1129 | private var bandRect: CGRect? { |
| |
| 1130 | guard let band else { return nil } |
| |
| 1131 | // Not under the empty line TextKit adds after a final newline. |
| |
| 1132 | let height = textLineFragments.last { $0.characterRange.length > 0 }?.typographicBounds.maxY ?? layoutFragmentFrame.height |
| |
| 1133 | // The width as it is now: the view may have been laid out since this fragment was made. |
| |
| 1134 | let width = style?.blockBand.width ?? band.width |
| |
| 1135 | return CGRect(x: -layoutFragmentFrame.minX, y: 0, width: max(width, layoutFragmentFrame.maxX), height: height) |
| |
| 1136 | } |
| |
| 1137 | |
| |
| 1138 | private var imageRect: CGRect? { |
| |
| 1139 | guard let image, let line = textLineFragments.first else { return nil } |
| |
| 1140 | return CGRect(x: line.typographicBounds.minX, y: line.typographicBounds.minY + 2, width: image.size.width, height: image.size.height) |
| |
| 1141 | } |
| |
| 1142 | |
| |
| 1143 | override var renderingSurfaceBounds: CGRect { |
| |
| 1144 | var bounds = super.renderingSurfaceBounds |
| |
| 1145 | if folded { bounds = bounds.insetBy(dx: -40, dy: 0).offsetBy(dx: 40, dy: 0) } |
| |
| 1146 | for rect in [bandRect, imageRect].compactMap({ $0 }) { bounds = bounds.union(rect) } |
| |
| 1147 | return bounds |
| |
| 1148 | } |
| |
| 1149 | |
| |
| 1150 | override func draw(at point: CGPoint, in context: CGContext) { |
| |
| 1151 | if let band, let rect = bandRect { |
| |
| 1152 | context.saveGState() |
| |
| 1153 | context.setFillColor(band.color.cgColor) |
| |
| 1154 | context.fill(rect.offsetBy(dx: point.x, dy: point.y)) |
| |
| 1155 | context.restoreGState() |
| |
| 1156 | drawSelection(at: point, in: context, bandRect: rect) |
| |
| 1157 | } |
| |
| 1158 | super.draw(at: point, in: context) |
| |
| 1159 | UIGraphicsPushContext(context) |
| |
| 1160 | defer { UIGraphicsPopContext() } |
| |
| 1161 | drawEntities(at: point) |
| |
| 1162 | if let image, let rect = imageRect { image.image.draw(in: rect.offsetBy(dx: point.x, dy: point.y)) } |
| |
| 1163 | if folded, let line = textLineFragments.first(where: { $0.characterRange.length > 0 }) ?? textLineFragments.first { |
| |
| 1164 | let bounds = line.typographicBounds |
| |
| 1165 | let ellipsis = NSAttributedString(string: " …", attributes: [ |
| |
| 1166 | .font: UIFont.monospacedSystemFont(ofSize: UIFont.systemFontSize, weight: .regular), |
| |
| 1167 | .foregroundColor: UIColor.secondaryLabel, |
| |
| 1168 | ]) |
| |
| 1169 | ellipsis.draw(at: CGPoint(x: point.x + bounds.maxX, y: point.y + bounds.minY)) |
| |
| 1170 | } |
| |
| 1171 | } |
| |
| 1172 | |
| |
| 1173 | /// The selected part of each line, over the band; a selection running past a line's end |
| |
| 1174 | /// fills to the band's edge. |
| |
| 1175 | private func drawSelection(at point: CGPoint, in context: CGContext, bandRect: CGRect) { |
| |
| 1176 | guard let selection = style?.selection else { return } |
| |
| 1177 | context.saveGState() |
| |
| 1178 | context.setFillColor(selection.color.cgColor) |
| |
| 1179 | for line in textLineFragments where line.characterRange.length > 0 { |
| |
| 1180 | let lineStart = start + line.characterRange.location |
| |
| 1181 | let lineEnd = lineStart + line.characterRange.length |
| |
| 1182 | let from = max(selection.range.lowerBound, lineStart), to = min(selection.range.upperBound, lineEnd) |
| |
| 1183 | guard from < to || (from == to && selection.range.upperBound > lineEnd && from == lineEnd) else { continue } |
| |
| 1184 | let bounds = line.typographicBounds |
| |
| 1185 | // From the margin when the selection began on an earlier line, as the system draws it. |
| |
| 1186 | let margin = bandRect.minX + (textLayoutManager?.textContainer?.lineFragmentPadding ?? 0) |
| |
| 1187 | let x1 = selection.range.lowerBound < lineStart ? margin : bounds.minX + line.locationForCharacter(at: from - start).x |
| |
| 1188 | let x2 = selection.range.upperBound >= lineEnd ? bandRect.maxX : bounds.minX + line.locationForCharacter(at: to - start).x |
| |
| 1189 | context.fill(CGRect(x: point.x + x1, y: point.y + bounds.minY, width: max(0, x2 - x1), height: bounds.height)) |
| |
| 1190 | } |
| |
| 1191 | context.restoreGState() |
| |
| 1192 | } |
| |
| 1193 | |
| |
| 1194 | private func drawEntities(at point: CGPoint) { |
| |
| 1195 | guard let string = (textElement as? NSTextParagraph)?.attributedString else { return } |
| |
| 1196 | string.enumerateAttribute(.orgEntityDisplay, in: NSRange(location: 0, length: string.length)) { value, range, _ in |
| |
| 1197 | guard let display = value as? String, |
| |
| 1198 | let line = textLineFragments.first(where: { NSLocationInRange(range.location, $0.characterRange) }) else { return } |
| |
| 1199 | var attributes = string.attributes(at: range.location, effectiveRange: nil) |
| |
| 1200 | attributes[.foregroundColor] = attributes[.orgEntityColor] ?? UIColor.label |
| |
| 1201 | attributes[.orgEntityDisplay] = nil |
| |
| 1202 | attributes[.orgEntityColor] = nil |
| |
| 1203 | let x = line.locationForCharacter(at: range.location).x |
| |
| 1204 | let bounds = line.typographicBounds |
| |
| 1205 | NSAttributedString(string: display, attributes: attributes).draw(at: CGPoint(x: point.x + bounds.minX + x, y: point.y + bounds.minY)) |
| |
| 1206 | } |
| |
| 1207 | } |
| |
| 1208 | } |
| |
| 1209 | #endif |
531 | #endif |