Repository navigation
Expand file tree
/
Copy pathWideTableOverlay.swift
More file actions
347 lines (304 loc) · 14 KB
/
Copy pathWideTableOverlay.swift
File metadata and controls
347 lines (304 loc) · 14 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
//
// WideTableOverlay.swift
// MarkdownEngine
//
// NSScrollView subview of NativeTextView hosting a wide-table image with
// native horizontal scrolling. Sidesteps TextKit 2's fragment surface
// cache that defeats in-fragment custom scrolling.
//
import AppKit
// MARK: - Faint scroller
/// Legacy scroller with a fainter knob.
final class SubtleScroller: NSScroller {
override func drawKnobSlot(in slot: NSRect, highlight: Bool) {
// Transparent track — only the knob is drawn.
}
override func drawKnob() {
let knob = rect(for: .knob)
guard knob.width > 1, knob.height > 1 else { return }
let thickness: CGFloat = 5
let pill = knob.insetBy(dx: 2, dy: max(0, (knob.height - thickness) / 2))
NSColor.secondaryLabelColor.withAlphaComponent(0.3).setFill() // ← faintness; tweak here
NSBezierPath(roundedRect: pill, xRadius: pill.height / 2, yRadius: pill.height / 2).fill()
}
}
// MARK: - Overlay view
final class WideTableOverlay: NSScrollView {
/// Hash of table source; key for offset persistence + reconcile lookup.
let sourceID: Int
/// Document index of the table anchor; click on image moves caret here.
var anchorTextLocation: Int
/// Weak parent ref for offset persistence + caret forwarding.
weak var ownerTextView: NativeTextView?
/// Table's left-edge offset (breakout: text-column left); scrollable space.
var leftContentInset: CGFloat = 0 {
didSet {
guard abs(contentInsets.left - leftContentInset) > 0.5 else { return }
contentInsets = NSEdgeInsets(top: 0, left: leftContentInset, bottom: 0, right: 0)
}
}
private let tableImageView: WideTableImageView
init(sourceID: Int, image: NSImage, ownerTextView: NativeTextView, anchorLocation: Int) {
self.sourceID = sourceID
self.anchorTextLocation = anchorLocation
self.ownerTextView = ownerTextView
self.tableImageView = WideTableImageView(frame: CGRect(origin: .zero, size: image.size))
tableImageView.image = image
tableImageView.imageScaling = .scaleNone
tableImageView.imageAlignment = .alignTopLeft
super.init(frame: .zero)
hasHorizontalScroller = true
hasVerticalScroller = false
// Auto-hide: only show the scroller when the table actually overflows.
autohidesScrollers = true
borderType = .noBorder
drawsBackground = false
// Legacy scroller, fainter knob (see SubtleScroller).
scrollerStyle = .legacy
let subtleScroller = SubtleScroller()
subtleScroller.scrollerStyle = .legacy
horizontalScroller = subtleScroller
horizontalScrollElasticity = .allowed
verticalScrollElasticity = .none
usesPredominantAxisScrolling = true
horizontalScroller?.controlSize = .small
automaticallyAdjustsContentInsets = false
documentView = tableImageView
tableImageView.ownerOverlay = self
NotificationCenter.default.addObserver(
self, selector: #selector(scrollOffsetDidChange),
name: NSScrollView.didLiveScrollNotification, object: self
)
NotificationCenter.default.addObserver(
self, selector: #selector(scrollOffsetDidChange),
name: NSScrollView.didEndLiveScrollNotification, object: self
)
}
required init?(coder: NSCoder) { fatalError("init(coder:) not supported") }
deinit { NotificationCenter.default.removeObserver(self) }
/// Clamp vertical scroll to 0 on every layout — kills sub-pixel wobble.
override func tile() {
super.tile()
let origin = contentView.bounds.origin
if origin.y != 0 {
contentView.scroll(to: NSPoint(x: origin.x, y: 0))
reflectScrolledClipView(contentView)
}
}
/// Forward everything except clearly-horizontal events to the outer
/// document scroll. Zero-delta phase/momentum lifecycle events count
/// as "not horizontal" so the outer scroll view still receives the
/// gesture-ended notifications it needs to stop cleanly.
override func scrollWheel(with event: NSEvent) {
if abs(event.scrollingDeltaX) > abs(event.scrollingDeltaY) {
super.scrollWheel(with: event)
} else {
nextResponder?.scrollWheel(with: event)
}
}
/// Swap the rendered image after a restyle regenerated it.
func updateImage(_ image: NSImage) {
if tableImageView.image !== image {
tableImageView.image = image
tableImageView.frame = CGRect(origin: .zero, size: image.size)
}
}
var horizontalOffset: CGFloat {
get { contentView.bounds.origin.x }
set {
contentView.scroll(to: NSPoint(x: max(0, newValue), y: 0))
reflectScrolledClipView(contentView)
}
}
@objc private func scrollOffsetDidChange() {
ownerTextView?.tableHorizontalScrollOffsets[sourceID] = horizontalOffset
}
}
// MARK: - Document view inside the overlay
/// Forwards mouseDown to caret-into-table (so clicking switches to edit mode).
final class WideTableImageView: NSImageView {
weak var ownerOverlay: WideTableOverlay?
override func mouseDown(with event: NSEvent) {
guard let overlay = ownerOverlay,
let textView = overlay.ownerTextView else {
super.mouseDown(with: event)
return
}
let location = overlay.anchorTextLocation
let docLen = (textView.string as NSString).length
guard location >= 0, location <= docLen else {
super.mouseDown(with: event)
return
}
textView.window?.makeFirstResponder(textView)
textView.setSelectedRange(NSRange(location: location, length: 0))
}
}
// MARK: - NativeTextView reconcile extension
extension NativeTextView {
/// Coalesce overlay updates to one per runloop tick (resize fires bursts).
/// The first run is synchronous to avoid a load flash.
/// Width-change restyles can reconcile immediately so the visible overlay
/// never trails the storage attributes by one resize turn.
func updateWideTableOverlays(
immediately: Bool = false,
layoutAlreadySettled: Bool = false,
knownWideTableAnchorRanges: [NSRange]? = nil
) {
if immediately || wideTableOverlays.isEmpty {
pendingWideTableOverlayUpdate = false
performWideTableOverlayUpdate(
layoutAlreadySettled: layoutAlreadySettled,
knownWideTableAnchorRanges: knownWideTableAnchorRanges
)
return
}
if pendingWideTableOverlayUpdate { return }
pendingWideTableOverlayUpdate = true
RunLoop.main.perform(inModes: [.default, .eventTracking]) { [weak self] in
guard let self else { return }
guard self.pendingWideTableOverlayUpdate else { return }
self.pendingWideTableOverlayUpdate = false
self.performWideTableOverlayUpdate()
}
}
/// Cheap per-frame overlay reposition on width change (no layout) — keeps tables glued to the text during resize.
func repositionWideTableOverlaysForWidthChange(insetDelta: CGFloat) {
guard configuration.readingWidth != nil, !wideTableOverlays.isEmpty else { return }
// Overlays live in the full-width reading-column container; span its visible width.
let hostBounds = (superview ?? self).bounds
for (_, overlay) in wideTableOverlays {
var f = overlay.frame
f.origin.x = hostBounds.minX
f.size.width = hostBounds.width
overlay.frame = f
overlay.leftContentInset = max(0, overlay.leftContentInset + insetDelta)
}
}
/// Walk storage; create / position / destroy overlays to match attrs.
func performWideTableOverlayUpdate(
layoutAlreadySettled: Bool = false,
knownWideTableAnchorRanges: [NSRange]? = nil
) {
guard let storage = textStorage,
let bridge = layoutBridge,
let container = bridge.firstTextContainer,
let tlm = textLayoutManager else {
removeAllWideTableOverlays()
return
}
let containerWidth = container.size.width
guard containerWidth.isFinite, containerWidth > 0 else { return }
// Breakout: tables span full width, flush with the text column's left.
let breakout = configuration.readingWidth != nil
// Breakout host: the full-width reading-column container, else the text view itself.
let host: NSView = breakout ? (superview ?? self) : self
let hostBounds = host.bounds
let anchorRanges: [NSRange]
if let knownWideTableAnchorRanges {
anchorRanges = knownWideTableAnchorRanges
} else {
// Ordinary edits do not carry table results, so discover anchors
// once. Width restyles pass their exact new anchor set and avoid
// this full-storage walk entirely.
let scanStarted = DispatchTime.now().uptimeNanoseconds
var discovered: [NSRange] = []
let fullRange = NSRange(location: 0, length: storage.length)
storage.enumerateAttribute(
.scrollableBlockSourceID,
in: fullRange,
options: []
) { value, attrRange, _ in
if value is Int { discovered.append(attrRange) }
}
anchorRanges = discovered
let scanMs = Double(
DispatchTime.now().uptimeNanoseconds - scanStarted
) / 1_000_000
if scanMs > 0.3 {
PerfTrace.stamp(
"wideTableOverlay.anchorScan",
scanMs,
"wide=\(anchorRanges.isEmpty ? 0 : 1) docLen=\(storage.length)"
)
}
}
guard !anchorRanges.isEmpty else {
removeAllWideTableOverlays()
return
}
var seenSourceIDs: Set<Int> = []
// Settle layout before measuring — stale fragments would yield wrong anchor Ys.
let overlayT0 = DispatchTime.now().uptimeNanoseconds
if !layoutAlreadySettled {
tlm.ensureLayout(for: tlm.documentRange)
}
PerfTrace.stamp("wideTableOverlay.ensureLayout(fullDoc)",
Double(DispatchTime.now().uptimeNanoseconds - overlayT0) / 1_000_000,
"settled=\(layoutAlreadySettled ? 1 : 0) docLen=\(storage.length)")
for attrRange in anchorRanges {
guard attrRange.location != NSNotFound,
attrRange.location >= 0,
attrRange.length > 0,
attrRange.length <= storage.length,
attrRange.location <= storage.length - attrRange.length,
let sourceID = storage.attribute(
.scrollableBlockSourceID,
at: attrRange.location,
effectiveRange: nil
) as? Int,
let image = storage.attribute(
.latexImage,
at: attrRange.location,
effectiveRange: nil
) as? NSImage else { continue }
seenSourceIDs.insert(sourceID)
let anchorRect = bridge.boundingRect(forCharacterRange: attrRange, in: container)
guard !anchorRect.isEmpty else { continue }
let totalHeight = (storage.attribute(.scrollableBlockTotalHeight, at: attrRange.location, effectiveRange: nil) as? CGFloat) ?? image.size.height
// In breakout the overlay lives in the container and spans its visible width,
// so the column's left edge is measured from the container's visible left.
let anchorTopLeft = NSPoint(x: textContainerOrigin.x + anchorRect.minX,
y: textContainerOrigin.y + anchorRect.minY)
let anchorInHost = convert(anchorTopLeft, to: host)
let columnLeft = breakout ? anchorInHost.x - hostBounds.minX : anchorTopLeft.x
let overlayFrame: NSRect = breakout
? NSRect(x: hostBounds.minX, y: anchorInHost.y, width: hostBounds.width, height: totalHeight)
: NSRect(x: columnLeft, y: anchorTopLeft.y, width: containerWidth, height: totalHeight)
// Breakout: table starts at the text column's left edge; the left margin is scrollable space.
let leftContentInset: CGFloat = breakout ? max(0, columnLeft) : 0
if let existing = wideTableOverlays[sourceID] {
if !existing.frame.equalTo(overlayFrame) {
// Invalidate both old + new region so the vacated area redraws.
host.setNeedsDisplay(existing.frame)
existing.frame = overlayFrame
host.setNeedsDisplay(overlayFrame)
}
existing.leftContentInset = leftContentInset
existing.updateImage(image)
existing.anchorTextLocation = attrRange.location
} else {
let overlay = WideTableOverlay(
sourceID: sourceID, image: image,
ownerTextView: self, anchorLocation: attrRange.location
)
overlay.frame = overlayFrame
overlay.leftContentInset = leftContentInset
host.addSubview(overlay)
wideTableOverlays[sourceID] = overlay
let savedOffset = tableHorizontalScrollOffsets[sourceID] ?? 0
if savedOffset > 0 { overlay.horizontalOffset = savedOffset }
}
}
for (sourceID, overlay) in wideTableOverlays where !seenSourceIDs.contains(sourceID) {
host.setNeedsDisplay(overlay.frame)
overlay.removeFromSuperview()
wideTableOverlays.removeValue(forKey: sourceID)
}
}
/// Drop all overlays synchronously (file switch path).
func removeAllWideTableOverlays() {
for (_, overlay) in wideTableOverlays { overlay.removeFromSuperview() }
wideTableOverlays.removeAll()
}
}