Sources/OrgstarMobile/MobileFragments.swift

310 lines · 15409 bytes

  1#if os(iOS)
  2import OrgApp
  3import OrgCore
  4import OrgDocument
  5import OrgHighlight
  6import OrgPresentation
  7import UIKit
  8
  9/// Ranges read by TextKit's delegate callbacks.
 10final 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.
 24final 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.
 37final class KeyedTextView: UITextView {
 38    var keyHandler: ((UIKey) -> Bool)?
 39    /// Files dropped and an image pasted; each returns whether it took them.
 40    var onFiles: (([URL]) -> Bool)?
 41    var onImage: ((Data, String) -> Bool)?
 42    /// Keys the editor took, whose release the text system doesn't see. Optional: made by
 43    /// UIKit's `init(usingTextLayoutManager:)`, the view skips Swift's default values.
 44    private var handled: Set<UIKeyboardHIDUsage>?
 45    /// Called after each layout pass, as the view's size settles.
 46    var onLayout: (() -> Void)?
 47    /// The text container's width while lines are truncated.
 48    static let truncatedWidth: CGFloat = 100_000
 49    /// The widest the text runs, centred in a wider view; 0 for the view's width.
 50    var textWidth: CGFloat = 0 {
 51        didSet { if textWidth != oldValue { setNeedsLayout() } }
 52    }
 53    /// The side inset without a text width.
 54    static let sideInset: CGFloat = 8
 55
 56    /// Long lines run off the right edge and the view scrolls sideways.
 57    var truncates: Bool {
 58        get { !textContainer.widthTracksTextView }
 59        set {
 60            textContainer.widthTracksTextView = !newValue
 61            if newValue {
 62                textContainer.size = CGSize(width: Self.truncatedWidth, height: CGFloat.greatestFiniteMagnitude)
 63            } else {
 64                textContainer.size = CGSize(width: bounds.width - textContainerInset.left - textContainerInset.right, height: CGFloat.greatestFiniteMagnitude)
 65                contentOffset.x = 0
 66            }
 67            showsHorizontalScrollIndicator = newValue
 68            setNeedsLayout()
 69        }
 70    }
 71
 72    override func layoutSubviews() {
 73        let side = textWidth > 0 && !truncates ? max(Self.sideInset, floor((bounds.width - textWidth - 2 * textContainer.lineFragmentPadding) / 2)) : Self.sideInset
 74        if textContainerInset.left != side {
 75            textContainerInset.left = side
 76            textContainerInset.right = side
 77        }
 78        // The text view sets its container's width to its own when it lays out.
 79        if truncates, textContainer.size.width != Self.truncatedWidth {
 80            textContainer.size = CGSize(width: Self.truncatedWidth, height: CGFloat.greatestFiniteMagnitude)
 81        }
 82        super.layoutSubviews()
 83        // The text view sizes its content to its own width; truncated lines need the widest
 84        // laid-out line's.
 85        if truncates, let manager = textLayoutManager {
 86            let width = ceil(manager.usageBoundsForTextContainer.maxX + textContainerInset.left + textContainerInset.right)
 87            if contentSize.width < width { contentSize.width = width }
 88        }
 89        onLayout?()
 90    }
 91
 92    override func pressesBegan(_ presses: Set<UIPress>, with event: UIPressesEvent?) {
 93        var rest: Set<UIPress> = []
 94        for press in presses {
 95            if let key = press.key, keyHandler?(key) == true {
 96                handled = (handled ?? []).union([key.keyCode])
 97            } else {
 98                rest.insert(press)
 99            }
100        }
101        if !rest.isEmpty { super.pressesBegan(rest, with: event) }
102    }
103
104    override func pressesEnded(_ presses: Set<UIPress>, with event: UIPressesEvent?) {
105        let rest = presses.filter { press in
106            guard let code = press.key?.keyCode, handled?.contains(code) == true else { return true }
107            handled?.remove(code)
108            return false
109        }
110        if !rest.isEmpty { super.pressesEnded(rest, with: event) }
111    }
112}
113
114extension NSAttributedString.Key {
115    /// The character an entity shows as, on the entity's last character.
116    static let orgEntityDisplay = NSAttributedString.Key("OrgEntityDisplay")
117    /// The color the entity's character is drawn in.
118    static let orgEntityColor = NSAttributedString.Key("OrgEntityColor")
119    /// The image an image link's line shows under it.
120    static let orgImage = NSAttributedString.Key("OrgImage")
121    /// A LaTeX fragment's typeset math, on its first character.
122    static let orgLatex = NSAttributedString.Key("OrgLatex")
123}
124
125final class LatexBox: NSObject, @unchecked Sendable {
126    let rendering: LatexPreview.Rendering
127    /// An environment's image sits at the start of its first line, under the line's top.
128    let environment: Bool
129    init(_ rendering: LatexPreview.Rendering, environment: Bool) {
130        self.rendering = rendering
131        self.environment = environment
132    }
133}
134
135final class InlineImageBox: NSObject, @unchecked Sendable {
136    let image: UIImage
137    let size: CGSize
138    /// Drawn under the line's text, which shows while the caret is on it.
139    let below: Bool
140    init(image: UIImage, size: CGSize, below: Bool = false) {
141        self.image = image
142        self.size = size
143        self.below = below
144    }
145}
146
147/// Selected text's background, in one color however the rects overlap.
148final class SelectionHighlightView: UIView, UITextSelectionHighlightView {
149    var selectionRects: [UITextSelectionRect] = [] { didSet { setNeedsDisplay() } }
150    var color: UIColor = .clear { didSet { setNeedsDisplay() } }
151
152    override init(frame: CGRect) {
153        super.init(frame: frame)
154        isOpaque = false
155        backgroundColor = .clear
156        isUserInteractionEnabled = false
157        registerForTraitChanges([UITraitUserInterfaceStyle.self]) { (view: SelectionHighlightView, _) in view.setNeedsDisplay() }
158    }
159
160    required init?(coder: NSCoder) { fatalError("init(coder:) is not used") }
161
162    override func draw(_ rect: CGRect) {
163        let path = UIBezierPath()
164        for selection in selectionRects where !selection.rect.isEmpty { path.append(UIBezierPath(rect: selection.rect)) }
165        color.setFill()
166        path.fill()
167    }
168}
169
170/// A line drawn with more than its text, as the Mac editor's fragments draw them: a folded
171/// line's ellipsis, a block's band across the view, an image under an image link, and pretty
172/// entities' characters where the entities' last (invisible) characters sit.
173final class OrgLineFragment: NSTextLayoutFragment, @unchecked Sendable {
174    var folded = false
175    var band: (color: UIColor, width: CGFloat)?
176    var image: InlineImageBox?
177    /// For a block's lines: where the fragment starts, and where the selection is read.
178    var start = 0
179    var style: FragmentStyle?
180
181    static func image(_ string: NSAttributedString) -> InlineImageBox? {
182        var found: InlineImageBox?
183        string.enumerateAttribute(.orgImage, in: NSRange(location: 0, length: string.length)) { value, _, stop in
184            if let box = value as? InlineImageBox { found = box; stop.pointee = true }
185        }
186        return found
187    }
188
189    static func hasLatex(_ string: NSAttributedString) -> Bool {
190        var found = false
191        string.enumerateAttribute(.orgLatex, in: NSRange(location: 0, length: string.length)) { value, _, stop in
192            if value != nil { found = true; stop.pointee = true }
193        }
194        return found
195    }
196
197    /// Each LaTeX preview and where it goes: on the line's baseline where its hidden fragment
198    /// starts, or at the top of an environment's first line.
199    private var latexBoxes: [(box: LatexBox, frame: CGRect)] {
200        guard let string = (textElement as? NSTextParagraph)?.attributedString else { return [] }
201        var out: [(LatexBox, CGRect)] = []
202        string.enumerateAttribute(.orgLatex, in: NSRange(location: 0, length: string.length)) { value, range, _ in
203            guard let box = value as? LatexBox,
204                  let line = textLineFragments.first(where: { NSLocationInRange(range.location, $0.characterRange) }) else { return }
205            let bounds = line.typographicBounds
206            let size = box.rendering.size
207            let x = bounds.minX + line.locationForCharacter(at: range.location).x
208            if box.environment {
209                out.append((box, CGRect(x: x, y: bounds.minY + 2, width: size.width, height: size.height)))
210            } else {
211                let baseline = bounds.minY + line.glyphOrigin.y
212                out.append((box, CGRect(x: x, y: max(bounds.minY, baseline - (size.height - box.rendering.descent)), width: size.width, height: size.height)))
213            }
214        }
215        return out
216    }
217
218    static func hasEntities(_ string: NSAttributedString) -> Bool {
219        var found = false
220        string.enumerateAttribute(.orgEntityDisplay, in: NSRange(location: 0, length: string.length)) { value, _, stop in
221            if value != nil { found = true; stop.pointee = true }
222        }
223        return found
224    }
225
226    var bandRect: CGRect? {
227        guard let band else { return nil }
228        // Not under the empty line TextKit adds after a final newline.
229        let height = textLineFragments.last { $0.characterRange.length > 0 }?.typographicBounds.maxY ?? layoutFragmentFrame.height
230        // The width as it is now: the view may have been laid out since this fragment was made.
231        let width = style?.blockBand.width ?? band.width
232        return CGRect(x: -layoutFragmentFrame.minX, y: 0, width: max(width, layoutFragmentFrame.maxX), height: height)
233    }
234
235    private var imageRect: CGRect? {
236        guard let image, let line = textLineFragments.first else { return nil }
237        return CGRect(x: line.typographicBounds.minX, y: (image.below ? line.typographicBounds.maxY : line.typographicBounds.minY) + 2, width: image.size.width, height: image.size.height)
238    }
239
240    override var renderingSurfaceBounds: CGRect {
241        var bounds = super.renderingSurfaceBounds
242        if folded { bounds = bounds.insetBy(dx: -40, dy: 0).offsetBy(dx: 40, dy: 0) }
243        for rect in [bandRect, imageRect].compactMap({ $0 }) + latexBoxes.map(\.frame) { bounds = bounds.union(rect) }
244        return bounds
245    }
246
247    override func draw(at point: CGPoint, in context: CGContext) {
248        if let band, let rect = bandRect {
249            context.saveGState()
250            context.setFillColor(band.color.cgColor)
251            context.fill(rect.offsetBy(dx: point.x, dy: point.y))
252            context.restoreGState()
253            drawSelection(at: point, in: context, bandRect: rect)
254        }
255        super.draw(at: point, in: context)
256        UIGraphicsPushContext(context)
257        defer { UIGraphicsPopContext() }
258        drawEntities(at: point)
259        if let image, let rect = imageRect { image.image.draw(in: rect.offsetBy(dx: point.x, dy: point.y)) }
260        for (box, frame) in latexBoxes {
261            UIImage(cgImage: box.rendering.image, scale: CGFloat(box.rendering.image.width) / max(1, box.rendering.size.width), orientation: .up)
262                .draw(in: frame.offsetBy(dx: point.x, dy: point.y))
263        }
264        if folded, let line = textLineFragments.first(where: { $0.characterRange.length > 0 }) ?? textLineFragments.first {
265            let bounds = line.typographicBounds
266            let ellipsis = NSAttributedString(string: " …", attributes: [
267                .font: UIFont.monospacedSystemFont(ofSize: UIFont.systemFontSize, weight: .regular),
268                .foregroundColor: UIColor.secondaryLabel,
269            ])
270            ellipsis.draw(at: CGPoint(x: point.x + bounds.maxX, y: point.y + bounds.minY))
271        }
272    }
273
274    /// The selected part of each line, over the band; a selection running past a line's end
275    /// fills to the band's edge.
276    private func drawSelection(at point: CGPoint, in context: CGContext, bandRect: CGRect) {
277        guard let selection = style?.selection else { return }
278        context.saveGState()
279        context.setFillColor(selection.color.cgColor)
280        for line in textLineFragments where line.characterRange.length > 0 {
281            let lineStart = start + line.characterRange.location
282            let lineEnd = lineStart + line.characterRange.length
283            let from = max(selection.range.lowerBound, lineStart), to = min(selection.range.upperBound, lineEnd)
284            guard from < to || (from == to && selection.range.upperBound > lineEnd && from == lineEnd) else { continue }
285            let bounds = line.typographicBounds
286            // From the margin when the selection began on an earlier line, as the system draws it.
287            let margin = bandRect.minX + (textLayoutManager?.textContainer?.lineFragmentPadding ?? 0)
288            let x1 = selection.range.lowerBound < lineStart ? margin : bounds.minX + line.locationForCharacter(at: from - start).x
289            let x2 = selection.range.upperBound >= lineEnd ? bandRect.maxX : bounds.minX + line.locationForCharacter(at: to - start).x
290            context.fill(CGRect(x: point.x + x1, y: point.y + bounds.minY, width: max(0, x2 - x1), height: bounds.height))
291        }
292        context.restoreGState()
293    }
294
295    private func drawEntities(at point: CGPoint) {
296        guard let string = (textElement as? NSTextParagraph)?.attributedString else { return }
297        string.enumerateAttribute(.orgEntityDisplay, in: NSRange(location: 0, length: string.length)) { value, range, _ in
298            guard let display = value as? String,
299                  let line = textLineFragments.first(where: { NSLocationInRange(range.location, $0.characterRange) }) else { return }
300            var attributes = string.attributes(at: range.location, effectiveRange: nil)
301            attributes[.foregroundColor] = attributes[.orgEntityColor] ?? UIColor.label
302            attributes[.orgEntityDisplay] = nil
303            attributes[.orgEntityColor] = nil
304            let x = line.locationForCharacter(at: range.location).x
305            let bounds = line.typographicBounds
306            NSAttributedString(string: display, attributes: attributes).draw(at: CGPoint(x: point.x + bounds.minX + x, y: point.y + bounds.minY))
307        }
308    }
309}
310#endif