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