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