Sources/OrgstarMobile/MobileFragments.swift
408 lines · 21053 bytes
31 symbols in this file
LockedRangessetcoversisFoldedcontainingFragmentStylesetsetKeyedTextViewlayoutSubviewspressesBeganpressesEndedEditorFindfindInteractioncompareperformTextSearchmatchesisWorddecorateclearAllDecoratedFoundTextLatexBoxInlineImageBoxSelectionHighlightViewdrawOrgLineFragmenthasImageshasLatexhasEntitiesdrawdrawSelectiondrawEntities
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 find bar's session, which opens folded text before a result shows.
48 var find: EditorFind?
49 /// The text container's width while lines are truncated.
50 static let truncatedWidth: CGFloat = 100_000
51 /// The widest the text runs, centred in a wider view; 0 for the view's width.
52 var textWidth: CGFloat = 0 {
53 didSet { if textWidth != oldValue { setNeedsLayout() } }
54 }
55 /// The side inset without a text width.
56 static let sideInset: CGFloat = 8
57
58 /// Long lines run off the right edge and the view scrolls sideways.
59 var truncates: Bool {
60 get { !textContainer.widthTracksTextView }
61 set {
62 textContainer.widthTracksTextView = !newValue
63 if newValue {
64 textContainer.size = CGSize(width: Self.truncatedWidth, height: CGFloat.greatestFiniteMagnitude)
65 } else {
66 textContainer.size = CGSize(width: bounds.width - textContainerInset.left - textContainerInset.right, height: CGFloat.greatestFiniteMagnitude)
67 contentOffset.x = 0
68 }
69 showsHorizontalScrollIndicator = newValue
70 setNeedsLayout()
71 }
72 }
73
74 override func layoutSubviews() {
75 let side = textWidth > 0 && !truncates ? max(Self.sideInset, floor((bounds.width - textWidth - 2 * textContainer.lineFragmentPadding) / 2)) : Self.sideInset
76 if textContainerInset.left != side {
77 textContainerInset.left = side
78 textContainerInset.right = side
79 }
80 // The text view sets its container's width to its own when it lays out.
81 if truncates, textContainer.size.width != Self.truncatedWidth {
82 textContainer.size = CGSize(width: Self.truncatedWidth, height: CGFloat.greatestFiniteMagnitude)
83 }
84 super.layoutSubviews()
85 // The text view sizes its content to its own width; truncated lines need the widest
86 // laid-out line's.
87 if truncates, let manager = textLayoutManager {
88 let width = ceil(manager.usageBoundsForTextContainer.maxX + textContainerInset.left + textContainerInset.right)
89 if contentSize.width < width { contentSize.width = width }
90 }
91 onLayout?()
92 }
93
94 override func pressesBegan(_ presses: Set<UIPress>, with event: UIPressesEvent?) {
95 var rest: Set<UIPress> = []
96 for press in presses {
97 if let key = press.key, keyHandler?(key) == true {
98 handled = (handled ?? []).union([key.keyCode])
99 } else {
100 rest.insert(press)
101 }
102 }
103 if !rest.isEmpty { super.pressesBegan(rest, with: event) }
104 }
105
106 override func pressesEnded(_ presses: Set<UIPress>, with event: UIPressesEvent?) {
107 let rest = presses.filter { press in
108 guard let code = press.key?.keyCode, handled?.contains(code) == true else { return true }
109 handled?.remove(code)
110 return false
111 }
112 if !rest.isEmpty { super.pressesEnded(rest, with: event) }
113 }
114}
115
116/// The editor's find: the file's text searched, folded text opened before a result shows, and that result selected.
117final class EditorFind: NSObject, @preconcurrency UITextSearching, UIFindInteractionDelegate {
118 nonisolated(unsafe) private weak var view: UITextView?
119 private let found: (Int) -> Void
120
121 init(view: UITextView, found: @escaping (Int) -> Void) {
122 self.view = view
123 self.found = found
124 }
125
126 func findInteraction(_ interaction: UIFindInteraction, sessionFor view: UIView) -> UIFindSession? {
127 UITextSearchingFindSession(searchableObject: self)
128 }
129
130 var selectedTextRange: UITextRange? { view?.selectedTextRange }
131
132 func compare(_ foundRange: UITextRange, toRange: UITextRange, document: AnyHashable??) -> ComparisonResult {
133 view?.compare(foundRange, toRange: toRange, document: document) ?? .orderedSame
134 }
135
136 nonisolated func performTextSearch(queryString: String, options: UITextSearchOptions, resultAggregator: UITextSearchAggregator<AnyHashable?>) {
137 // The aggregator takes results from any thread; the view's ranges are made on the main thread.
138 nonisolated(unsafe) let aggregator = resultAggregator
139 let search = {
140 MainActor.assumeIsolated {
141 guard let view = self.view else { return }
142 for found in Self.matches(of: queryString, in: view.textStorage.string as NSString, options: options) {
143 guard let start = view.position(from: view.beginningOfDocument, offset: found.lowerBound),
144 let end = view.position(from: start, offset: found.count),
145 let range = view.textRange(from: start, to: end) else { continue }
146 aggregator.foundRange(range, searchString: queryString, document: nil)
147 }
148 }
149 aggregator.finishedSearching()
150 }
151 if Thread.isMainThread { search() } else { DispatchQueue.main.sync(execute: search) }
152 }
153
154 /// Where `query` is in `text`, as the find bar's options ask: case, and matching a word's
155 /// start or a whole word.
156 static func matches(of query: String, in text: NSString, options: UITextSearchOptions) -> [Range<Int>] {
157 func isWord(_ index: Int) -> Bool {
158 guard index >= 0, index < text.length, let scalar = Unicode.Scalar(text.character(at: index)) else { return false }
159 return CharacterSet.alphanumerics.contains(scalar)
160 }
161 var matches: [Range<Int>] = []
162 var from = 0
163 while from < text.length {
164 let found = text.range(of: query, options: options.stringCompareOptions, range: NSRange(location: from, length: text.length - from))
165 guard found.location != NSNotFound, found.length > 0 else { break }
166 from = NSMaxRange(found)
167 switch options.wordMatchMethod {
168 case .startsWith: if isWord(found.location - 1) { continue }
169 case .fullWord: if isWord(found.location - 1) || isWord(NSMaxRange(found)) { continue }
170 default: break
171 }
172 matches.append(found.location..<NSMaxRange(found))
173 }
174 return matches
175 }
176
177 func decorate(foundTextRange: UITextRange, document: AnyHashable??, usingStyle style: UITextSearchFoundTextStyle) {
178 guard let view else { return }
179 view.decorate(foundTextRange: foundTextRange, document: document, usingStyle: style)
180 guard style == .highlighted else { return }
181 let start = view.offset(from: view.beginningOfDocument, to: foundTextRange.start)
182 found(start)
183 // The result shown is selected, as the Mac's find selects it.
184 view.selectedTextRange = foundTextRange
185 view.scrollRangeToVisible(NSRange(location: start, length: view.offset(from: foundTextRange.start, to: foundTextRange.end)))
186 }
187
188 func clearAllDecoratedFoundText() { view?.clearAllDecoratedFoundText() }
189}
190
191extension NSAttributedString.Key {
192 /// The character an entity shows as, on the entity's last character.
193 static let orgEntityDisplay = NSAttributedString.Key("OrgEntityDisplay")
194 /// The color the entity's character is drawn in.
195 static let orgEntityColor = NSAttributedString.Key("OrgEntityColor")
196 /// An image link's image, on the link's line or on its first character.
197 static let orgImage = NSAttributedString.Key("OrgImage")
198 /// A LaTeX fragment's typeset math, on its first character.
199 static let orgLatex = NSAttributedString.Key("OrgLatex")
200}
201
202final class LatexBox: NSObject, @unchecked Sendable {
203 let rendering: LatexPreview.Rendering
204 /// An environment's image sits at the start of its first line, under the line's top.
205 let environment: Bool
206 init(_ rendering: LatexPreview.Rendering, environment: Bool) {
207 self.rendering = rendering
208 self.environment = environment
209 }
210}
211
212final class InlineImageBox: NSObject, @unchecked Sendable {
213 let image: UIImage
214 let size: CGSize
215 /// Drawn under the text, which shows while the caret is on the line.
216 let below: Bool
217 /// In the line's text where the link is, on a character as wide and as tall as the image;
218 /// otherwise the link is all the line holds.
219 let inText: Bool
220 init(image: UIImage, size: CGSize, below: Bool = false, inText: Bool = false) {
221 self.image = image
222 self.size = size
223 self.below = below
224 self.inText = inText
225 }
226}
227
228/// Selected text's background, in one color however the rects overlap.
229final class SelectionHighlightView: UIView, UITextSelectionHighlightView {
230 var selectionRects: [UITextSelectionRect] = [] { didSet { setNeedsDisplay() } }
231 var color: UIColor = .clear { didSet { setNeedsDisplay() } }
232
233 override init(frame: CGRect) {
234 super.init(frame: frame)
235 isOpaque = false
236 backgroundColor = .clear
237 isUserInteractionEnabled = false
238 registerForTraitChanges([UITraitUserInterfaceStyle.self]) { (view: SelectionHighlightView, _) in view.setNeedsDisplay() }
239 }
240
241 required init?(coder: NSCoder) { fatalError("init(coder:) is not used") }
242
243 override func draw(_ rect: CGRect) {
244 let path = UIBezierPath()
245 for selection in selectionRects where !selection.rect.isEmpty { path.append(UIBezierPath(rect: selection.rect)) }
246 color.setFill()
247 path.fill()
248 }
249}
250
251/// A line drawn with more than its text, as the Mac editor's fragments draw them: a folded
252/// line's ellipsis, a block's band across the view, image links' images, and pretty
253/// entities' characters where the entities' last (invisible) characters sit.
254final class OrgLineFragment: NSTextLayoutFragment, @unchecked Sendable {
255 var folded = false
256 var band: (color: UIColor, width: CGFloat)?
257 /// For a block's lines: where the fragment starts, and where the selection is read.
258 var start = 0
259 var style: FragmentStyle?
260
261 static func hasImages(_ string: NSAttributedString) -> Bool {
262 var found = false
263 string.enumerateAttribute(.orgImage, in: NSRange(location: 0, length: string.length)) { value, _, stop in
264 if value != nil { found = true; stop.pointee = true }
265 }
266 return found
267 }
268
269 /// Each image and where it goes: a line's image over or under the line, an image in the
270 /// text on its hidden link, or under the paragraph, side by side, while the links show.
271 private var imageFrames: [(box: InlineImageBox, frame: CGRect)] {
272 guard let string = (textElement as? NSTextParagraph)?.attributedString, let first = textLineFragments.first else { return [] }
273 let last = textLineFragments.last { $0.characterRange.length > 0 } ?? first
274 var out: [(InlineImageBox, CGRect)] = []
275 var under = first.typographicBounds.minX
276 string.enumerateAttribute(.orgImage, in: NSRange(location: 0, length: string.length)) { value, range, _ in
277 guard let box = value as? InlineImageBox else { return }
278 if !box.inText {
279 out.append((box, CGRect(origin: CGPoint(x: first.typographicBounds.minX, y: (box.below ? first.typographicBounds.maxY : first.typographicBounds.minY) + 2), size: box.size)))
280 } else if box.below {
281 out.append((box, CGRect(origin: CGPoint(x: under, y: last.typographicBounds.maxY + 2), size: box.size)))
282 under += box.size.width + 4
283 } else if let line = textLineFragments.first(where: { NSLocationInRange(range.location, $0.characterRange) }) {
284 let bounds = line.typographicBounds
285 let ascender = (string.attribute(.font, at: range.location, effectiveRange: nil) as? UIFont)?.ascender ?? box.size.height
286 out.append((box, CGRect(origin: CGPoint(x: bounds.minX + line.locationForCharacter(at: range.location).x, y: bounds.minY + line.glyphOrigin.y - ascender), size: box.size)))
287 }
288 }
289 return out
290 }
291
292 static func hasLatex(_ string: NSAttributedString) -> Bool {
293 var found = false
294 string.enumerateAttribute(.orgLatex, in: NSRange(location: 0, length: string.length)) { value, _, stop in
295 if value != nil { found = true; stop.pointee = true }
296 }
297 return found
298 }
299
300 /// Each LaTeX preview and where it goes: on the line's baseline where its hidden fragment
301 /// starts, or at the top of an environment's first line.
302 private var latexBoxes: [(box: LatexBox, frame: CGRect)] {
303 guard let string = (textElement as? NSTextParagraph)?.attributedString else { return [] }
304 var out: [(LatexBox, CGRect)] = []
305 string.enumerateAttribute(.orgLatex, in: NSRange(location: 0, length: string.length)) { value, range, _ in
306 guard let box = value as? LatexBox,
307 let line = textLineFragments.first(where: { NSLocationInRange(range.location, $0.characterRange) }) else { return }
308 let bounds = line.typographicBounds
309 let size = box.rendering.size
310 let x = bounds.minX + line.locationForCharacter(at: range.location).x
311 if box.environment {
312 out.append((box, CGRect(x: x, y: bounds.minY + 2, width: size.width, height: size.height)))
313 } else {
314 let baseline = bounds.minY + line.glyphOrigin.y
315 out.append((box, CGRect(x: x, y: max(bounds.minY, baseline - (size.height - box.rendering.descent)), width: size.width, height: size.height)))
316 }
317 }
318 return out
319 }
320
321 static func hasEntities(_ string: NSAttributedString) -> Bool {
322 var found = false
323 string.enumerateAttribute(.orgEntityDisplay, in: NSRange(location: 0, length: string.length)) { value, _, stop in
324 if value != nil { found = true; stop.pointee = true }
325 }
326 return found
327 }
328
329 var bandRect: CGRect? {
330 guard let band else { return nil }
331 // Not under the empty line TextKit adds after a final newline.
332 let height = textLineFragments.last { $0.characterRange.length > 0 }?.typographicBounds.maxY ?? layoutFragmentFrame.height
333 // The width as it is now: the view may have been laid out since this fragment was made.
334 let width = style?.blockBand.width ?? band.width
335 return CGRect(x: -layoutFragmentFrame.minX, y: 0, width: max(width, layoutFragmentFrame.maxX), height: height)
336 }
337
338 override var renderingSurfaceBounds: CGRect {
339 var bounds = super.renderingSurfaceBounds
340 if folded { bounds = bounds.insetBy(dx: -40, dy: 0).offsetBy(dx: 40, dy: 0) }
341 for rect in [bandRect].compactMap({ $0 }) + imageFrames.map(\.frame) + latexBoxes.map(\.frame) { bounds = bounds.union(rect) }
342 return bounds
343 }
344
345 override func draw(at point: CGPoint, in context: CGContext) {
346 if let band, let rect = bandRect {
347 context.saveGState()
348 context.setFillColor(band.color.cgColor)
349 context.fill(rect.offsetBy(dx: point.x, dy: point.y))
350 context.restoreGState()
351 drawSelection(at: point, in: context, bandRect: rect)
352 }
353 super.draw(at: point, in: context)
354 UIGraphicsPushContext(context)
355 defer { UIGraphicsPopContext() }
356 drawEntities(at: point)
357 for (box, frame) in imageFrames { box.image.draw(in: frame.offsetBy(dx: point.x, dy: point.y)) }
358 for (box, frame) in latexBoxes {
359 UIImage(cgImage: box.rendering.image, scale: CGFloat(box.rendering.image.width) / max(1, box.rendering.size.width), orientation: .up)
360 .draw(in: frame.offsetBy(dx: point.x, dy: point.y))
361 }
362 if folded, let line = textLineFragments.first(where: { $0.characterRange.length > 0 }) ?? textLineFragments.first {
363 let bounds = line.typographicBounds
364 let ellipsis = NSAttributedString(string: " …", attributes: [
365 .font: UIFont.monospacedSystemFont(ofSize: UIFont.systemFontSize, weight: .regular),
366 .foregroundColor: UIColor.secondaryLabel,
367 ])
368 ellipsis.draw(at: CGPoint(x: point.x + bounds.maxX, y: point.y + bounds.minY))
369 }
370 }
371
372 /// The selected part of each line, over the band; a selection running past a line's end
373 /// fills to the band's edge.
374 private func drawSelection(at point: CGPoint, in context: CGContext, bandRect: CGRect) {
375 guard let selection = style?.selection else { return }
376 context.saveGState()
377 context.setFillColor(selection.color.cgColor)
378 for line in textLineFragments where line.characterRange.length > 0 {
379 let lineStart = start + line.characterRange.location
380 let lineEnd = lineStart + line.characterRange.length
381 let from = max(selection.range.lowerBound, lineStart), to = min(selection.range.upperBound, lineEnd)
382 guard from < to || (from == to && selection.range.upperBound > lineEnd && from == lineEnd) else { continue }
383 let bounds = line.typographicBounds
384 // From the margin when the selection began on an earlier line, as the system draws it.
385 let margin = bandRect.minX + (textLayoutManager?.textContainer?.lineFragmentPadding ?? 0)
386 let x1 = selection.range.lowerBound < lineStart ? margin : bounds.minX + line.locationForCharacter(at: from - start).x
387 let x2 = selection.range.upperBound >= lineEnd ? bandRect.maxX : bounds.minX + line.locationForCharacter(at: to - start).x
388 context.fill(CGRect(x: point.x + x1, y: point.y + bounds.minY, width: max(0, x2 - x1), height: bounds.height))
389 }
390 context.restoreGState()
391 }
392
393 private func drawEntities(at point: CGPoint) {
394 guard let string = (textElement as? NSTextParagraph)?.attributedString else { return }
395 string.enumerateAttribute(.orgEntityDisplay, in: NSRange(location: 0, length: string.length)) { value, range, _ in
396 guard let display = value as? String,
397 let line = textLineFragments.first(where: { NSLocationInRange(range.location, $0.characterRange) }) else { return }
398 var attributes = string.attributes(at: range.location, effectiveRange: nil)
399 attributes[.foregroundColor] = attributes[.orgEntityColor] ?? UIColor.label
400 attributes[.orgEntityDisplay] = nil
401 attributes[.orgEntityColor] = nil
402 let x = line.locationForCharacter(at: range.location).x
403 let bounds = line.typographicBounds
404 NSAttributedString(string: display, attributes: attributes).draw(at: CGPoint(x: point.x + bounds.minX + x, y: point.y + bounds.minY))
405 }
406 }
407}
408#endif