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