Sources/OrgstarMobile/MobileFragments.swift
248 lines · 12133 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 /// 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
100extension NSAttributedString.Key {
101 /// The character an entity shows as, on the entity's last character.
102 static let orgEntityDisplay = NSAttributedString.Key("OrgEntityDisplay")
103 /// The color the entity's character is drawn in.
104 static let orgEntityColor = NSAttributedString.Key("OrgEntityColor")
105 /// The image an image link's line shows under it.
106 static let orgImage = NSAttributedString.Key("OrgImage")
107}
108
109final class InlineImageBox: NSObject, @unchecked Sendable {
110 let image: UIImage
111 let size: CGSize
112 init(image: UIImage, size: CGSize) {
113 self.image = image
114 self.size = size
115 }
116}
117
118/// Selected text's background, in one color however the rects overlap.
119final class SelectionHighlightView: UIView, UITextSelectionHighlightView {
120 var selectionRects: [UITextSelectionRect] = [] { didSet { setNeedsDisplay() } }
121 var color: UIColor = .clear { didSet { setNeedsDisplay() } }
122
123 override init(frame: CGRect) {
124 super.init(frame: frame)
125 isOpaque = false
126 backgroundColor = .clear
127 isUserInteractionEnabled = false
128 registerForTraitChanges([UITraitUserInterfaceStyle.self]) { (view: SelectionHighlightView, _) in view.setNeedsDisplay() }
129 }
130
131 required init?(coder: NSCoder) { fatalError("init(coder:) is not used") }
132
133 override func draw(_ rect: CGRect) {
134 let path = UIBezierPath()
135 for selection in selectionRects where !selection.rect.isEmpty { path.append(UIBezierPath(rect: selection.rect)) }
136 color.setFill()
137 path.fill()
138 }
139}
140
141/// A line drawn with more than its text, as the Mac editor's fragments draw them: a folded
142/// line's ellipsis, a block's band across the view, an image under an image link, and pretty
143/// entities' characters where the entities' last (invisible) characters sit.
144final class OrgLineFragment: NSTextLayoutFragment, @unchecked Sendable {
145 var folded = false
146 var band: (color: UIColor, width: CGFloat)?
147 var image: InlineImageBox?
148 /// For a block's lines: where the fragment starts, and where the selection is read.
149 var start = 0
150 var style: FragmentStyle?
151
152 static func image(_ string: NSAttributedString) -> InlineImageBox? {
153 var found: InlineImageBox?
154 string.enumerateAttribute(.orgImage, in: NSRange(location: 0, length: string.length)) { value, _, stop in
155 if let box = value as? InlineImageBox { found = box; stop.pointee = true }
156 }
157 return found
158 }
159
160 static func hasEntities(_ string: NSAttributedString) -> Bool {
161 var found = false
162 string.enumerateAttribute(.orgEntityDisplay, in: NSRange(location: 0, length: string.length)) { value, _, stop in
163 if value != nil { found = true; stop.pointee = true }
164 }
165 return found
166 }
167
168 var bandRect: CGRect? {
169 guard let band else { return nil }
170 // Not under the empty line TextKit adds after a final newline.
171 let height = textLineFragments.last { $0.characterRange.length > 0 }?.typographicBounds.maxY ?? layoutFragmentFrame.height
172 // The width as it is now: the view may have been laid out since this fragment was made.
173 let width = style?.blockBand.width ?? band.width
174 return CGRect(x: -layoutFragmentFrame.minX, y: 0, width: max(width, layoutFragmentFrame.maxX), height: height)
175 }
176
177 private var imageRect: CGRect? {
178 guard let image, let line = textLineFragments.first else { return nil }
179 return CGRect(x: line.typographicBounds.minX, y: line.typographicBounds.minY + 2, width: image.size.width, height: image.size.height)
180 }
181
182 override var renderingSurfaceBounds: CGRect {
183 var bounds = super.renderingSurfaceBounds
184 if folded { bounds = bounds.insetBy(dx: -40, dy: 0).offsetBy(dx: 40, dy: 0) }
185 for rect in [bandRect, imageRect].compactMap({ $0 }) { bounds = bounds.union(rect) }
186 return bounds
187 }
188
189 override func draw(at point: CGPoint, in context: CGContext) {
190 if let band, let rect = bandRect {
191 context.saveGState()
192 context.setFillColor(band.color.cgColor)
193 context.fill(rect.offsetBy(dx: point.x, dy: point.y))
194 context.restoreGState()
195 drawSelection(at: point, in: context, bandRect: rect)
196 }
197 super.draw(at: point, in: context)
198 UIGraphicsPushContext(context)
199 defer { UIGraphicsPopContext() }
200 drawEntities(at: point)
201 if let image, let rect = imageRect { image.image.draw(in: rect.offsetBy(dx: point.x, dy: point.y)) }
202 if folded, let line = textLineFragments.first(where: { $0.characterRange.length > 0 }) ?? textLineFragments.first {
203 let bounds = line.typographicBounds
204 let ellipsis = NSAttributedString(string: " …", attributes: [
205 .font: UIFont.monospacedSystemFont(ofSize: UIFont.systemFontSize, weight: .regular),
206 .foregroundColor: UIColor.secondaryLabel,
207 ])
208 ellipsis.draw(at: CGPoint(x: point.x + bounds.maxX, y: point.y + bounds.minY))
209 }
210 }
211
212 /// The selected part of each line, over the band; a selection running past a line's end
213 /// fills to the band's edge.
214 private func drawSelection(at point: CGPoint, in context: CGContext, bandRect: CGRect) {
215 guard let selection = style?.selection else { return }
216 context.saveGState()
217 context.setFillColor(selection.color.cgColor)
218 for line in textLineFragments where line.characterRange.length > 0 {
219 let lineStart = start + line.characterRange.location
220 let lineEnd = lineStart + line.characterRange.length
221 let from = max(selection.range.lowerBound, lineStart), to = min(selection.range.upperBound, lineEnd)
222 guard from < to || (from == to && selection.range.upperBound > lineEnd && from == lineEnd) else { continue }
223 let bounds = line.typographicBounds
224 // From the margin when the selection began on an earlier line, as the system draws it.
225 let margin = bandRect.minX + (textLayoutManager?.textContainer?.lineFragmentPadding ?? 0)
226 let x1 = selection.range.lowerBound < lineStart ? margin : bounds.minX + line.locationForCharacter(at: from - start).x
227 let x2 = selection.range.upperBound >= lineEnd ? bandRect.maxX : bounds.minX + line.locationForCharacter(at: to - start).x
228 context.fill(CGRect(x: point.x + x1, y: point.y + bounds.minY, width: max(0, x2 - x1), height: bounds.height))
229 }
230 context.restoreGState()
231 }
232
233 private func drawEntities(at point: CGPoint) {
234 guard let string = (textElement as? NSTextParagraph)?.attributedString else { return }
235 string.enumerateAttribute(.orgEntityDisplay, in: NSRange(location: 0, length: string.length)) { value, range, _ in
236 guard let display = value as? String,
237 let line = textLineFragments.first(where: { NSLocationInRange(range.location, $0.characterRange) }) else { return }
238 var attributes = string.attributes(at: range.location, effectiveRange: nil)
239 attributes[.foregroundColor] = attributes[.orgEntityColor] ?? UIColor.label
240 attributes[.orgEntityDisplay] = nil
241 attributes[.orgEntityColor] = nil
242 let x = line.locationForCharacter(at: range.location).x
243 let bounds = line.typographicBounds
244 NSAttributedString(string: display, attributes: attributes).draw(at: CGPoint(x: point.x + bounds.minX + x, y: point.y + bounds.minY))
245 }
246 }
247}
248#endif