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