oficina / docs Public

Clone
git clone https://amadan.net/oficina/docs

Plain git — no account needed to clone.

Download

Download this file

1#if os(iOS)
2import UIKit
3import XCTest
4@testable import DocsKit
5
6/// The iPhone's page breaks on TextKit 2 (S3, `DocsPhonePages`): a 20-page
7/// document, paged, edited through the text view (a Return, a deleted
8/// paragraph, a pasted run of paragraphs, typing that changes a line count).
9/// After each edit, once the pages have placed everything:
10/// - no line starts in a page gap or crosses a page's bottom margin (a
11/// paragraph taller than a page's body is the one exception, and the
12/// fixture has none);
13/// - every break is laid out where the pages placed it;
14/// - every line is where a fresh view of the same text, laid out whole,
15/// puts it.
16@MainActor final class PhonePaginationTests: XCTestCase {
17 func testBreaksFollowEditsAndMatchAWholeLayout() async throws {
18 DocsFonts.register()
19 let window = UIWindow(frame: CGRect(x: 0, y: 0, width: 402, height: 874))
20 window.makeKeyAndVisible()
21 defer { window.isHidden = true }
22 let state = SurfaceState(width: 402)
23 let text = state.text
24 text.frame = window.bounds
25 text.paged = true
26 window.addSubview(text)
27 defer { text.removeFromSuperview() }
28 state.markPendingOnEdit = false
29 state.publish(SurfaceFixture.projection(SurfaceFixture.pages(20)), generation: 1, dirty: nil)
30 text.layoutIfNeeded()
31 try check(text, "at open")
32
33 let storage = text.textStorage
34 func edit(_ range: NSRange, _ replacement: String, _ what: String) throws {
35 if text.delegate?.textView?(text, shouldChangeTextIn: range, replacementText: replacement) ?? true {
36 storage.replaceCharacters(in: range, with: NSAttributedString(string: replacement, attributes: text.typingAttributes))
37 text.selectedRange = NSRange(location: range.location + replacement.utf16.count, length: 0)
38 text.delegate?.textViewDidChange?(text)
39 }
40 text.layoutIfNeeded()
41 try check(text, what)
42 }
43 let string = { storage.string as NSString }
44 try edit(NSRange(location: string().range(of: "\n", range: NSRange(location: 2000, length: string().length - 2000)).location, length: 0), "\n", "a Return")
45 let paragraph = string().paragraphRange(for: NSRange(location: 9000, length: 0))
46 try edit(paragraph, "", "a deleted paragraph")
47 try edit(NSRange(location: 4000, length: 0), String(repeating: "Pasted words that wrap across the line. ", count: 12) + "\nA second pasted paragraph.\n", "a pasted run of paragraphs")
48 try edit(NSRange(location: 15000, length: 0), String(repeating: "More words. ", count: 9), "typing that adds lines")
49 try edit(NSRange(location: 15000, length: 108), "", "deleting them again")
50 }
51
52 /// A peer's keys far above the screen (Fable on #180): through the
53 /// surface's publication path, as a peer's change arrives. A key that
54 /// leaves its paragraph's lines as they were lays out that paragraph
55 /// and nothing else; one that adds a line moves the text only as far
56 /// as the next page break, which takes it up. Either way the screen
57 /// stays where a whole layout puts it, its breaks where they were
58 /// placed, and nothing on it moves.
59 func testAPeersKeysAboveTheScreenLayOutOnlyTheirParagraph() throws {
60 DocsFonts.register()
61 let window = UIWindow(frame: CGRect(x: 0, y: 0, width: 402, height: 874))
62 window.makeKeyAndVisible()
63 defer { window.isHidden = true }
64 let state = SurfaceState(width: 402)
65 let text = state.text
66 text.frame = window.bounds
67 text.paged = true
68 window.addSubview(text)
69 defer { text.removeFromSuperview() }
70 state.markPendingOnEdit = false
71 var nodes = SurfaceFixture.pages(20)
72 state.publish(SurfaceFixture.projection(nodes), generation: 1, dirty: nil)
73 text.layoutIfNeeded()
74 text.paginateEverything()
75 text.setContentOffset(CGPoint(x: 0, y: text.contentSize.height - text.bounds.height * 2), animated: false)
76 text.layoutIfNeeded()
77 let peer = try XCTUnwrap(nodes.firstIndex { $0.id == "p1-2" })
78 let wrap = String(repeating: "Words to wrap the line. ", count: 3)
79 for (what, typed) in [("a peer's key", "x"), ("a peer's key that adds a line", wrap), ("a peer's key", "y")] {
80 let shown = Self.screen(text)
81 nodes[peer].children?[0].runs?[0].insert += typed
82 let relaid = DocsProbes.relaidParagraphs
83 let offset = text.contentOffset.y
84 state.publish(SurfaceFixture.projection(nodes), generation: 1, dirty: ["p1-2"])
85 text.layoutIfNeeded()
86 XCTAssertEqual(text.contentOffset.y, offset, "\(what): the screen does not scroll")
87 XCTAssertEqual(DocsProbes.relaidParagraphs - relaid, 0, "\(what): nothing laid out again from the top down to the screen")
88 XCTAssertTrue(state.string.contains(typed), what)
89 // Nothing on screen moved (the text there is the same text).
90 let after = Self.screen(text)
91 XCTAssertEqual(after.map(\.rect.minY), shown.map(\.rect.minY), "\(what): nothing on screen moved")
92 try checkScreen(text, what)
93 }
94 }
95
96 /// A peer's added line above the screen where no page break takes it
97 /// up (Fable's delta review, F1): unpaged, and paged on the screen's top
98 /// page. Everything on screen moves down a line, so the screen scrolls
99 /// by that line and nothing on it moves; it is where a whole layout puts
100 /// it, and so is a screen above it and the screen again.
101 func testAPeersLineAboveTheScreenUnpaged() async throws { try await peerLineAbove(paged: false) }
102 func testAPeersLineOnTheScreensTopPage() async throws { try await peerLineAbove(paged: true) }
103
104 private func peerLineAbove(paged: Bool) async throws {
105 DocsFonts.register()
106 let window = UIWindow(frame: CGRect(x: 0, y: 0, width: 402, height: 874))
107 window.makeKeyAndVisible()
108 defer { window.isHidden = true }
109 let state = SurfaceState(width: 402)
110 let text = state.text
111 text.frame = window.bounds
112 text.paged = paged
113 window.addSubview(text)
114 defer { text.removeFromSuperview() }
115 state.markPendingOnEdit = false
116 var nodes = SurfaceFixture.pages(20)
117 // The peer's paragraph, marked: the fixture's paragraphs repeat.
118 let peer = try XCTUnwrap(nodes.firstIndex { $0.id == "p9-1" })
119 let original = nodes[peer].children?[0].runs?[0].insert ?? ""
120 nodes[peer].children?[0].runs?[0].insert = "The peer's paragraph. " + original
121 state.publish(SurfaceFixture.projection(nodes), generation: 1, dirty: nil)
122 text.layoutIfNeeded()
123 text.paginateEverything()
124 let layout = try XCTUnwrap(text.textLayoutManager), content = try XCTUnwrap(layout.textContentManager)
125 // With the next paragraph on its page.
126 let found = (text.textStorage.string as NSString).range(of: "The peer's paragraph. ")
127 XCTAssertNotEqual(found.location, NSNotFound)
128 let index = try XCTUnwrap(text.pages.paragraph(at: found.location))
129 XCTAssertEqual(text.pages.paragraphs[index + 1].extra, 0, "the next paragraph is on its page")
130 func frame(_ at: Int) throws -> CGRect {
131 let location = try XCTUnwrap(content.location(content.documentRange.location, offsetBy: text.pages.range(of: at).location))
132 return try XCTUnwrap(layout.textLayoutFragment(for: location)).layoutFragmentFrame
133 }
134 // The screen starts at the next paragraph, the caret in it.
135 let next = try frame(index + 1)
136 text.setContentOffset(CGPoint(x: 0, y: next.minY + text.textContainerInset.top - text.adjustedContentInset.top + 2), animated: false)
137 text.layoutIfNeeded()
138 XCTAssertTrue(text.becomeFirstResponder())
139 text.selectedRange = NSRange(location: text.pages.range(of: index + 1).location + 5, length: 0)
140 text.delegate?.textViewDidChangeSelection?(text)
141 text.layoutIfNeeded()
142 try checkScreen(text, "before the line")
143 let before = try frame(index).height, offset = text.contentOffset.y
144 let caret = text.caretRect(for: try XCTUnwrap(text.selectedTextRange).start).minY - offset
145 let words = " A peer's words, enough of them to wrap onto a new line."
146 nodes[peer].children?[0].runs?[0].insert += words
147 // As the replica publishes a peer's change: a new generation, the
148 // selection mapped past what was inserted above it.
149 state.allowed = 2
150 state.selection = NSRange(location: text.selectedRange.location + words.utf16.count, length: 0)
151 state.publish(SurfaceFixture.projection(nodes), generation: 2, dirty: ["p9-1"])
152 text.layoutIfNeeded()
153 let line = try frame(index).height - before
154 XCTAssertGreaterThan(line, 10, "the peer added a line")
155 XCTAssertEqual(text.contentOffset.y - offset, line, accuracy: 0.5, "the screen scrolls by the line")
156 XCTAssertEqual(text.caretRect(for: try XCTUnwrap(text.selectedTextRange).start).minY - text.contentOffset.y, caret, accuracy: 0.5,
157 "the caret stays where it was on screen")
158 try checkScreen(text, "after the line")
159 let here = text.contentOffset.y
160 text.setContentOffset(CGPoint(x: 0, y: here - text.bounds.height), animated: false)
161 text.layoutIfNeeded()
162 try checkScreen(text, "a screen up")
163 text.setContentOffset(CGPoint(x: 0, y: here), animated: false)
164 text.layoutIfNeeded()
165 try checkScreen(text, "and down again")
166 }
167
168 /// Breaks a key moves below the screen wait for idle (Fable's delta
169 /// review, F2): idle rebuilds them, with nothing on screen moving, and a
170 /// jump to the end afterwards lands where a whole layout puts it.
171 func testIdleBuildsTheBreaksAKeyLeftBelowTheScreen() async throws {
172 DocsFonts.register()
173 let window = UIWindow(frame: CGRect(x: 0, y: 0, width: 402, height: 874))
174 window.makeKeyAndVisible()
175 defer { window.isHidden = true }
176 let state = SurfaceState(width: 402)
177 let text = state.text
178 text.frame = window.bounds
179 text.paged = true
180 window.addSubview(text)
181 defer { text.removeFromSuperview() }
182 state.markPendingOnEdit = false
183 var nodes = SurfaceFixture.pages(20)
184 state.publish(SurfaceFixture.projection(nodes), generation: 1, dirty: nil)
185 text.layoutIfNeeded()
186 text.paginateEverything()
187 text.setContentOffset(CGPoint(x: 0, y: 1200), animated: false)
188 text.layoutIfNeeded()
189 // Settled: idle has nothing left from the open.
190 let settled = Date().addingTimeInterval(3)
191 while text.isMeasuringWhileIdle && Date() < settled { try await Task.sleep(for: .milliseconds(20)) }
192 XCTAssertFalse(text.isMeasuringWhileIdle)
193 // A peer's lines above the screen, enough to move every break after.
194 let peer = try XCTUnwrap(nodes.firstIndex { $0.id == "p0-1" })
195 nodes[peer].children?[0].runs?[0].insert += String(repeating: " A peer's words, enough of them to wrap onto a new line.", count: 5)
196 state.publish(SurfaceFixture.projection(nodes), generation: 1, dirty: ["p0-1"])
197 text.layoutIfNeeded()
198 XCTAssertTrue(text.pages.hasChanges, "breaks below the screen wait")
199 let offset = text.contentOffset.y
200 let deadline = Date().addingTimeInterval(3)
201 while text.pages.hasChanges && Date() < deadline { try await Task.sleep(for: .milliseconds(20)) }
202 text.layoutIfNeeded()
203 XCTAssertFalse(text.pages.hasChanges, "idle built them")
204 XCTAssertEqual(text.contentOffset.y, offset, accuracy: 0.5, "with nothing on screen moving")
205 try checkScreen(text, "after idle")
206 text.setContentOffset(CGPoint(x: 0, y: text.contentSize.height - text.bounds.height), animated: false)
207 text.layoutIfNeeded()
208 try checkScreen(text, "a jump to the end")
209 }
210
211 /// After a peer's key above the screen, idle finishes the restack once
212 /// typing pauses (Fable's delta review, F3), so scrolling on does not
213 /// walk from the top on every frame.
214 func testIdleFinishesTheRestack() async throws {
215 DocsFonts.register()
216 let window = UIWindow(frame: CGRect(x: 0, y: 0, width: 402, height: 874))
217 window.makeKeyAndVisible()
218 defer { window.isHidden = true }
219 let state = SurfaceState(width: 402)
220 let text = state.text
221 text.frame = window.bounds
222 text.paged = true
223 window.addSubview(text)
224 defer { text.removeFromSuperview() }
225 state.markPendingOnEdit = false
226 var nodes = SurfaceFixture.pages(20)
227 state.publish(SurfaceFixture.projection(nodes), generation: 1, dirty: nil)
228 text.layoutIfNeeded()
229 text.paginateEverything()
230 text.setContentOffset(CGPoint(x: 0, y: 1200), animated: false)
231 text.layoutIfNeeded()
232 func settle() async throws {
233 let deadline = Date().addingTimeInterval(3)
234 while text.isMeasuringWhileIdle && Date() < deadline { try await Task.sleep(for: .milliseconds(20)) }
235 XCTAssertFalse(text.isMeasuringWhileIdle)
236 }
237 try await settle()
238 let peer = try XCTUnwrap(nodes.firstIndex { $0.id == "p0-1" })
239 nodes[peer].children?[0].runs?[0].insert += "x"
240 state.publish(SurfaceFixture.projection(nodes), generation: 1, dirty: ["p0-1"])
241 text.layoutIfNeeded()
242 try await settle()
243 XCTAssertNil(text.pages.editedFrom, "the restack is finished")
244 let walks = DocsProbes.restackWalks
245 for step in 1...3 {
246 text.setContentOffset(CGPoint(x: 0, y: 1200 + CGFloat(step) * 300), animated: false)
247 text.layoutIfNeeded()
248 }
249 XCTAssertEqual(DocsProbes.restackWalks, walks, "scrolling on walks nothing from the top")
250 try checkScreen(text, "scrolled on")
251 }
252
253 /// Marked text (Fable on #180, required 2): composing in the paragraph
254 /// that carries a page break's space, growing it by a line, moves the
255 /// break, but its fragment is not built again (an attribute edit of the
256 /// paragraph being composed) until the composition ends; then it is,
257 /// and the break is where it was placed.
258 func testABreakWaitsForACompositionToEnd() throws {
259 DocsFonts.register()
260 let window = UIWindow(frame: CGRect(x: 0, y: 0, width: 402, height: 874))
261 window.makeKeyAndVisible()
262 defer { window.isHidden = true }
263 let state = SurfaceState(width: 402)
264 let text = state.text
265 text.frame = window.bounds
266 text.paged = true
267 window.addSubview(text)
268 defer { text.removeFromSuperview() }
269 state.markPendingOnEdit = false
270 state.publish(SurfaceFixture.projection(SurfaceFixture.pages(6)), generation: 1, dirty: nil)
271 text.layoutIfNeeded()
272 text.paginateEverything()
273 // The first break, and the paragraph before it, which carries its space.
274 let broken = try XCTUnwrap(text.pages.paragraphs.indices.first { $0 > 0 && text.pages.paragraphs[$0].extra > 0 })
275 let carrier = text.pages.range(of: broken - 1)
276 text.setContentOffset(CGPoint(x: 0, y: max(0, (text.pages.paragraphs[broken].bottom ?? 0) - 400)), animated: false)
277 text.layoutIfNeeded()
278 XCTAssertTrue(text.becomeFirstResponder())
279 text.selectedRange = NSRange(location: carrier.location + carrier.length - 1, length: 0)
280 let changes = DocsProbes.pageBreakChanges
281 // Japanese input, as an IME marks it: enough to add a line.
282 let marked = String(repeating: "にほんごのにゅうりょく", count: 4)
283 text.setMarkedText(marked, selectedRange: NSRange(location: marked.utf16.count, length: 0))
284 text.layoutIfNeeded()
285 XCTAssertNotNil(text.markedTextRange, "still composing")
286 XCTAssertEqual(DocsProbes.pageBreakChanges, changes, "no break built again while composing")
287 text.unmarkText()
288 text.layoutIfNeeded()
289 XCTAssertNil(text.markedTextRange)
290 XCTAssertGreaterThan(DocsProbes.pageBreakChanges, changes, "the break is built again once the composition ends")
291 try checkScreen(text, "after the composition")
292 }
293
294 /// The idle measuring stops when a pass gets nowhere (Fable on #180):
295 /// an empty document has a paragraph that cannot be measured, and the
296 /// loop must not wake every 2 ms for ever.
297 func testIdleMeasuringStopsWhenItGetsNowhere() async throws {
298 let window = UIWindow(frame: CGRect(x: 0, y: 0, width: 402, height: 874))
299 window.makeKeyAndVisible()
300 defer { window.isHidden = true }
301 let text = DocsTextView(frame: window.bounds)
302 text.paged = true
303 window.addSubview(text)
304 defer { text.removeFromSuperview() }
305 text.layoutIfNeeded()
306 try await Task.sleep(for: .milliseconds(100))
307 XCTAssertFalse(text.isMeasuringWhileIdle, "an empty document leaves nothing running")
308 }
309
310 /// The screen's lines, by where they are drawn.
311 private static func screen(_ text: DocsTextView) -> [(range: NSRange, rect: CGRect)] {
312 PhoneLargeDocumentTests.lines(in: text, near: text.contentOffset.y, height: text.bounds.height).filter { $0.range.length > 0 }
313 }
314
315 /// The screen's lines where a fresh view of the same text, laid out
316 /// whole, puts them, and its breaks where they were placed.
317 private func checkScreen(_ text: DocsTextView, _ when: String) throws {
318 let layout = try XCTUnwrap(text.textLayoutManager)
319 let content = try XCTUnwrap(layout.textContentManager)
320 let shown = Self.screen(text)
321 XCTAssertGreaterThan(shown.count, 10, when)
322 let whole = DocsTextView(frame: text.frame)
323 whole.paged = text.paged
324 text.superview?.addSubview(whole)
325 defer { whole.removeFromSuperview() }
326 whole.attributedText = text.attributedText
327 whole.layoutIfNeeded()
328 whole.paginateEverything()
329 let reference = Dictionary(PhoneLargeDocumentTests.lines(in: whole, near: 0, height: .greatestFiniteMagnitude)
330 .map { ($0.range.location, $0.rect) }, uniquingKeysWith: { a, _ in a })
331 var differ = 0
332 for line in shown {
333 guard let other = reference[line.range.location] else { differ += 1; continue }
334 if abs(other.minY - line.rect.minY) > 0.5 { differ += 1 }
335 }
336 XCTAssertEqual(differ, 0, "\(when): lines on screen away from where a whole layout puts them")
337 guard let first = shown.first?.range.location, let last = shown.last?.range.location,
338 let from = text.pages.paragraph(at: first), let to = text.pages.paragraph(at: last) else { return }
339 for index in from...to where text.pages.paragraphs[index].extra > 0 {
340 guard let location = content.location(content.documentRange.location, offsetBy: text.pages.range(of: index).location),
341 let fragment = layout.textLayoutFragment(for: location),
342 let placed = text.pages.paragraphs[index].bottom.map({ $0 - (text.pages.paragraphs[index].height ?? 0) }) else { continue }
343 let top = fragment.layoutFragmentFrame.minY + (fragment.textLineFragments.first?.typographicBounds.minY ?? 0)
344 XCTAssertEqual(top, placed, accuracy: 0.5, "\(when): a break on screen laid out where it was placed")
345 }
346 }
347
348 /// A one-line document scrolls to its page's foot (its bottom margin and
349 /// page number), not only to its text's end.
350 func testAShortDocumentScrollsToItsPagesFoot() throws {
351 DocsFonts.register()
352 let window = UIWindow(frame: CGRect(x: 0, y: 0, width: 402, height: 874))
353 window.makeKeyAndVisible()
354 defer { window.isHidden = true }
355 let text = DocsTextView(frame: window.bounds)
356 text.paged = true
357 window.addSubview(text)
358 defer { text.removeFromSuperview() }
359 text.attributedText = NSAttributedString(string: "One line.", attributes: [.font: DocsFonts.defaultFont()])
360 text.layoutIfNeeded()
361 XCTAssertGreaterThanOrEqual(text.contentSize.height, text.headerHeight + DocsPageGeometry.paperHeight - 0.5)
362 text.paged = false
363 text.layoutIfNeeded()
364 XCTAssertLessThan(text.contentSize.height, DocsPageGeometry.paperHeight, "pageless, the content is the text's")
365 }
366
367 /// Everything placed, then the three checks.
368 private func check(_ text: DocsTextView, _ when: String) throws {
369 text.paginateEverything()
370 let layout = try XCTUnwrap(text.textLayoutManager)
371 let content = try XCTUnwrap(layout.textContentManager)
372 let geometry = text.geometry
373 let lines = PhoneLargeDocumentTests.lines(in: text, near: 0, height: .greatestFiniteMagnitude)
374 XCTAssertGreaterThan(lines.count, 100, when)
375 var straddling = 0
376 for line in lines where line.range.length > 0 {
377 let y = line.rect.minY - text.headerHeight
378 let top = CGFloat(geometry.page(at: y)) * geometry.stride + DocsPageGeometry.verticalMargin
379 if y < top - 0.01 || y + line.rect.height > top + geometry.bodyHeight + 0.01 { straddling += 1 }
380 }
381 XCTAssertEqual(straddling, 0, "\(when): lines in a gap or across a page's bottom margin")
382 var off = 0
383 for index in text.pages.paragraphs.indices where text.pages.paragraphs[index].extra > 0 {
384 guard let location = content.location(content.documentRange.location, offsetBy: text.pages.range(of: index).location),
385 let fragment = layout.textLayoutFragment(for: location),
386 let placed = text.pages.paragraphs[index].bottom.map({ $0 - (text.pages.paragraphs[index].height ?? 0) }) else { continue }
387 let top = fragment.layoutFragmentFrame.minY + (fragment.textLineFragments.first?.typographicBounds.minY ?? 0)
388 if abs(top - placed) > 0.5 { off += 1 }
389 }
390 XCTAssertEqual(off, 0, "\(when): breaks laid out away from where they were placed")
391 // A fresh view of the same text, laid out whole.
392 let whole = DocsTextView(frame: text.frame)
393 whole.paged = true
394 text.superview?.addSubview(whole)
395 defer { whole.removeFromSuperview() }
396 whole.attributedText = text.attributedText
397 whole.layoutIfNeeded()
398 whole.paginateEverything()
399 let reference = Dictionary(PhoneLargeDocumentTests.lines(in: whole, near: 0, height: .greatestFiniteMagnitude)
400 .map { ($0.range.location, $0.rect) }, uniquingKeysWith: { a, _ in a })
401 var differ = 0
402 for line in lines where line.range.length > 0 {
403 guard let other = reference[line.range.location] else { differ += 1; continue }
404 if abs(other.minY - line.rect.minY) > 0.5 { differ += 1 }
405 }
406 XCTAssertEqual(differ, 0, "\(when): lines away from where a whole layout puts them")
407 }
408}
409#endif
410