#if os(iOS) import UIKit import XCTest @testable import DocsKit /// The iPhone's page breaks on TextKit 2 (S3, `DocsPhonePages`): a 20-page /// document, paged, edited through the text view (a Return, a deleted /// paragraph, a pasted run of paragraphs, typing that changes a line count). /// After each edit, once the pages have placed everything: /// - no line starts in a page gap or crosses a page's bottom margin (a /// paragraph taller than a page's body is the one exception, and the /// fixture has none); /// - every break is laid out where the pages placed it; /// - every line is where a fresh view of the same text, laid out whole, /// puts it. @MainActor final class PhonePaginationTests: XCTestCase { func testBreaksFollowEditsAndMatchAWholeLayout() async throws { DocsFonts.register() let window = UIWindow(frame: CGRect(x: 0, y: 0, width: 402, height: 874)) window.makeKeyAndVisible() defer { window.isHidden = true } let state = SurfaceState(width: 402) let text = state.text text.frame = window.bounds text.paged = true window.addSubview(text) defer { text.removeFromSuperview() } state.markPendingOnEdit = false state.publish(SurfaceFixture.projection(SurfaceFixture.pages(20)), generation: 1, dirty: nil) text.layoutIfNeeded() try check(text, "at open") let storage = text.textStorage func edit(_ range: NSRange, _ replacement: String, _ what: String) throws { if text.delegate?.textView?(text, shouldChangeTextIn: range, replacementText: replacement) ?? true { storage.replaceCharacters(in: range, with: NSAttributedString(string: replacement, attributes: text.typingAttributes)) text.selectedRange = NSRange(location: range.location + replacement.utf16.count, length: 0) text.delegate?.textViewDidChange?(text) } text.layoutIfNeeded() try check(text, what) } let string = { storage.string as NSString } try edit(NSRange(location: string().range(of: "\n", range: NSRange(location: 2000, length: string().length - 2000)).location, length: 0), "\n", "a Return") let paragraph = string().paragraphRange(for: NSRange(location: 9000, length: 0)) try edit(paragraph, "", "a deleted paragraph") 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") try edit(NSRange(location: 15000, length: 0), String(repeating: "More words. ", count: 9), "typing that adds lines") try edit(NSRange(location: 15000, length: 108), "", "deleting them again") } /// A peer's keys far above the screen (Fable on #180): through the /// surface's publication path, as a peer's change arrives. A key that /// leaves its paragraph's lines as they were lays out that paragraph /// and nothing else; one that adds a line moves the text only as far /// as the next page break, which takes it up. Either way the screen /// stays where a whole layout puts it, its breaks where they were /// placed, and nothing on it moves. func testAPeersKeysAboveTheScreenLayOutOnlyTheirParagraph() throws { DocsFonts.register() let window = UIWindow(frame: CGRect(x: 0, y: 0, width: 402, height: 874)) window.makeKeyAndVisible() defer { window.isHidden = true } let state = SurfaceState(width: 402) let text = state.text text.frame = window.bounds text.paged = true window.addSubview(text) defer { text.removeFromSuperview() } state.markPendingOnEdit = false var nodes = SurfaceFixture.pages(20) state.publish(SurfaceFixture.projection(nodes), generation: 1, dirty: nil) text.layoutIfNeeded() text.paginateEverything() text.setContentOffset(CGPoint(x: 0, y: text.contentSize.height - text.bounds.height * 2), animated: false) text.layoutIfNeeded() let peer = try XCTUnwrap(nodes.firstIndex { $0.id == "p1-2" }) let wrap = String(repeating: "Words to wrap the line. ", count: 3) for (what, typed) in [("a peer's key", "x"), ("a peer's key that adds a line", wrap), ("a peer's key", "y")] { let shown = Self.screen(text) nodes[peer].children?[0].runs?[0].insert += typed let relaid = DocsProbes.relaidParagraphs let offset = text.contentOffset.y state.publish(SurfaceFixture.projection(nodes), generation: 1, dirty: ["p1-2"]) text.layoutIfNeeded() XCTAssertEqual(text.contentOffset.y, offset, "\(what): the screen does not scroll") XCTAssertEqual(DocsProbes.relaidParagraphs - relaid, 0, "\(what): nothing laid out again from the top down to the screen") XCTAssertTrue(state.string.contains(typed), what) // Nothing on screen moved (the text there is the same text). let after = Self.screen(text) XCTAssertEqual(after.map(\.rect.minY), shown.map(\.rect.minY), "\(what): nothing on screen moved") try checkScreen(text, what) } } /// A peer's added line above the screen where no page break takes it /// up (Fable's delta review, F1): unpaged, and paged on the screen's top /// page. Everything on screen moves down a line, so the screen scrolls /// by that line and nothing on it moves; it is where a whole layout puts /// it, and so is a screen above it and the screen again. func testAPeersLineAboveTheScreenUnpaged() async throws { try await peerLineAbove(paged: false) } func testAPeersLineOnTheScreensTopPage() async throws { try await peerLineAbove(paged: true) } private func peerLineAbove(paged: Bool) async throws { DocsFonts.register() let window = UIWindow(frame: CGRect(x: 0, y: 0, width: 402, height: 874)) window.makeKeyAndVisible() defer { window.isHidden = true } let state = SurfaceState(width: 402) let text = state.text text.frame = window.bounds text.paged = paged window.addSubview(text) defer { text.removeFromSuperview() } state.markPendingOnEdit = false var nodes = SurfaceFixture.pages(20) // The peer's paragraph, marked: the fixture's paragraphs repeat. let peer = try XCTUnwrap(nodes.firstIndex { $0.id == "p9-1" }) let original = nodes[peer].children?[0].runs?[0].insert ?? "" nodes[peer].children?[0].runs?[0].insert = "The peer's paragraph. " + original state.publish(SurfaceFixture.projection(nodes), generation: 1, dirty: nil) text.layoutIfNeeded() text.paginateEverything() let layout = try XCTUnwrap(text.textLayoutManager), content = try XCTUnwrap(layout.textContentManager) // With the next paragraph on its page. let found = (text.textStorage.string as NSString).range(of: "The peer's paragraph. ") XCTAssertNotEqual(found.location, NSNotFound) let index = try XCTUnwrap(text.pages.paragraph(at: found.location)) XCTAssertEqual(text.pages.paragraphs[index + 1].extra, 0, "the next paragraph is on its page") func frame(_ at: Int) throws -> CGRect { let location = try XCTUnwrap(content.location(content.documentRange.location, offsetBy: text.pages.range(of: at).location)) return try XCTUnwrap(layout.textLayoutFragment(for: location)).layoutFragmentFrame } // The screen starts at the next paragraph, the caret in it. let next = try frame(index + 1) text.setContentOffset(CGPoint(x: 0, y: next.minY + text.textContainerInset.top - text.adjustedContentInset.top + 2), animated: false) text.layoutIfNeeded() XCTAssertTrue(text.becomeFirstResponder()) text.selectedRange = NSRange(location: text.pages.range(of: index + 1).location + 5, length: 0) text.delegate?.textViewDidChangeSelection?(text) text.layoutIfNeeded() try checkScreen(text, "before the line") let before = try frame(index).height, offset = text.contentOffset.y let caret = text.caretRect(for: try XCTUnwrap(text.selectedTextRange).start).minY - offset let words = " A peer's words, enough of them to wrap onto a new line." nodes[peer].children?[0].runs?[0].insert += words // As the replica publishes a peer's change: a new generation, the // selection mapped past what was inserted above it. state.allowed = 2 state.selection = NSRange(location: text.selectedRange.location + words.utf16.count, length: 0) state.publish(SurfaceFixture.projection(nodes), generation: 2, dirty: ["p9-1"]) text.layoutIfNeeded() let line = try frame(index).height - before XCTAssertGreaterThan(line, 10, "the peer added a line") XCTAssertEqual(text.contentOffset.y - offset, line, accuracy: 0.5, "the screen scrolls by the line") XCTAssertEqual(text.caretRect(for: try XCTUnwrap(text.selectedTextRange).start).minY - text.contentOffset.y, caret, accuracy: 0.5, "the caret stays where it was on screen") try checkScreen(text, "after the line") let here = text.contentOffset.y text.setContentOffset(CGPoint(x: 0, y: here - text.bounds.height), animated: false) text.layoutIfNeeded() try checkScreen(text, "a screen up") text.setContentOffset(CGPoint(x: 0, y: here), animated: false) text.layoutIfNeeded() try checkScreen(text, "and down again") } /// Breaks a key moves below the screen wait for idle (Fable's delta /// review, F2): idle rebuilds them, with nothing on screen moving, and a /// jump to the end afterwards lands where a whole layout puts it. func testIdleBuildsTheBreaksAKeyLeftBelowTheScreen() async throws { DocsFonts.register() let window = UIWindow(frame: CGRect(x: 0, y: 0, width: 402, height: 874)) window.makeKeyAndVisible() defer { window.isHidden = true } let state = SurfaceState(width: 402) let text = state.text text.frame = window.bounds text.paged = true window.addSubview(text) defer { text.removeFromSuperview() } state.markPendingOnEdit = false var nodes = SurfaceFixture.pages(20) state.publish(SurfaceFixture.projection(nodes), generation: 1, dirty: nil) text.layoutIfNeeded() text.paginateEverything() text.setContentOffset(CGPoint(x: 0, y: 1200), animated: false) text.layoutIfNeeded() // Settled: idle has nothing left from the open. let settled = Date().addingTimeInterval(3) while text.isMeasuringWhileIdle && Date() < settled { try await Task.sleep(for: .milliseconds(20)) } XCTAssertFalse(text.isMeasuringWhileIdle) // A peer's lines above the screen, enough to move every break after. let peer = try XCTUnwrap(nodes.firstIndex { $0.id == "p0-1" }) nodes[peer].children?[0].runs?[0].insert += String(repeating: " A peer's words, enough of them to wrap onto a new line.", count: 5) state.publish(SurfaceFixture.projection(nodes), generation: 1, dirty: ["p0-1"]) text.layoutIfNeeded() XCTAssertTrue(text.pages.hasChanges, "breaks below the screen wait") let offset = text.contentOffset.y let deadline = Date().addingTimeInterval(3) while text.pages.hasChanges && Date() < deadline { try await Task.sleep(for: .milliseconds(20)) } text.layoutIfNeeded() XCTAssertFalse(text.pages.hasChanges, "idle built them") XCTAssertEqual(text.contentOffset.y, offset, accuracy: 0.5, "with nothing on screen moving") try checkScreen(text, "after idle") text.setContentOffset(CGPoint(x: 0, y: text.contentSize.height - text.bounds.height), animated: false) text.layoutIfNeeded() try checkScreen(text, "a jump to the end") } /// After a peer's key above the screen, idle finishes the restack once /// typing pauses (Fable's delta review, F3), so scrolling on does not /// walk from the top on every frame. func testIdleFinishesTheRestack() async throws { DocsFonts.register() let window = UIWindow(frame: CGRect(x: 0, y: 0, width: 402, height: 874)) window.makeKeyAndVisible() defer { window.isHidden = true } let state = SurfaceState(width: 402) let text = state.text text.frame = window.bounds text.paged = true window.addSubview(text) defer { text.removeFromSuperview() } state.markPendingOnEdit = false var nodes = SurfaceFixture.pages(20) state.publish(SurfaceFixture.projection(nodes), generation: 1, dirty: nil) text.layoutIfNeeded() text.paginateEverything() text.setContentOffset(CGPoint(x: 0, y: 1200), animated: false) text.layoutIfNeeded() func settle() async throws { let deadline = Date().addingTimeInterval(3) while text.isMeasuringWhileIdle && Date() < deadline { try await Task.sleep(for: .milliseconds(20)) } XCTAssertFalse(text.isMeasuringWhileIdle) } try await settle() let peer = try XCTUnwrap(nodes.firstIndex { $0.id == "p0-1" }) nodes[peer].children?[0].runs?[0].insert += "x" state.publish(SurfaceFixture.projection(nodes), generation: 1, dirty: ["p0-1"]) text.layoutIfNeeded() try await settle() XCTAssertNil(text.pages.editedFrom, "the restack is finished") let walks = DocsProbes.restackWalks for step in 1...3 { text.setContentOffset(CGPoint(x: 0, y: 1200 + CGFloat(step) * 300), animated: false) text.layoutIfNeeded() } XCTAssertEqual(DocsProbes.restackWalks, walks, "scrolling on walks nothing from the top") try checkScreen(text, "scrolled on") } /// Marked text (Fable on #180, required 2): composing in the paragraph /// that carries a page break's space, growing it by a line, moves the /// break, but its fragment is not built again (an attribute edit of the /// paragraph being composed) until the composition ends; then it is, /// and the break is where it was placed. func testABreakWaitsForACompositionToEnd() throws { DocsFonts.register() let window = UIWindow(frame: CGRect(x: 0, y: 0, width: 402, height: 874)) window.makeKeyAndVisible() defer { window.isHidden = true } let state = SurfaceState(width: 402) let text = state.text text.frame = window.bounds text.paged = true window.addSubview(text) defer { text.removeFromSuperview() } state.markPendingOnEdit = false state.publish(SurfaceFixture.projection(SurfaceFixture.pages(6)), generation: 1, dirty: nil) text.layoutIfNeeded() text.paginateEverything() // The first break, and the paragraph before it, which carries its space. let broken = try XCTUnwrap(text.pages.paragraphs.indices.first { $0 > 0 && text.pages.paragraphs[$0].extra > 0 }) let carrier = text.pages.range(of: broken - 1) text.setContentOffset(CGPoint(x: 0, y: max(0, (text.pages.paragraphs[broken].bottom ?? 0) - 400)), animated: false) text.layoutIfNeeded() XCTAssertTrue(text.becomeFirstResponder()) text.selectedRange = NSRange(location: carrier.location + carrier.length - 1, length: 0) let changes = DocsProbes.pageBreakChanges // Japanese input, as an IME marks it: enough to add a line. let marked = String(repeating: "にほんごのにゅうりょく", count: 4) text.setMarkedText(marked, selectedRange: NSRange(location: marked.utf16.count, length: 0)) text.layoutIfNeeded() XCTAssertNotNil(text.markedTextRange, "still composing") XCTAssertEqual(DocsProbes.pageBreakChanges, changes, "no break built again while composing") text.unmarkText() text.layoutIfNeeded() XCTAssertNil(text.markedTextRange) XCTAssertGreaterThan(DocsProbes.pageBreakChanges, changes, "the break is built again once the composition ends") try checkScreen(text, "after the composition") } /// The idle measuring stops when a pass gets nowhere (Fable on #180): /// an empty document has a paragraph that cannot be measured, and the /// loop must not wake every 2 ms for ever. func testIdleMeasuringStopsWhenItGetsNowhere() async throws { let window = UIWindow(frame: CGRect(x: 0, y: 0, width: 402, height: 874)) window.makeKeyAndVisible() defer { window.isHidden = true } let text = DocsTextView(frame: window.bounds) text.paged = true window.addSubview(text) defer { text.removeFromSuperview() } text.layoutIfNeeded() try await Task.sleep(for: .milliseconds(100)) XCTAssertFalse(text.isMeasuringWhileIdle, "an empty document leaves nothing running") } /// The screen's lines, by where they are drawn. private static func screen(_ text: DocsTextView) -> [(range: NSRange, rect: CGRect)] { PhoneLargeDocumentTests.lines(in: text, near: text.contentOffset.y, height: text.bounds.height).filter { $0.range.length > 0 } } /// The screen's lines where a fresh view of the same text, laid out /// whole, puts them, and its breaks where they were placed. private func checkScreen(_ text: DocsTextView, _ when: String) throws { let layout = try XCTUnwrap(text.textLayoutManager) let content = try XCTUnwrap(layout.textContentManager) let shown = Self.screen(text) XCTAssertGreaterThan(shown.count, 10, when) let whole = DocsTextView(frame: text.frame) whole.paged = text.paged text.superview?.addSubview(whole) defer { whole.removeFromSuperview() } whole.attributedText = text.attributedText whole.layoutIfNeeded() whole.paginateEverything() let reference = Dictionary(PhoneLargeDocumentTests.lines(in: whole, near: 0, height: .greatestFiniteMagnitude) .map { ($0.range.location, $0.rect) }, uniquingKeysWith: { a, _ in a }) var differ = 0 for line in shown { guard let other = reference[line.range.location] else { differ += 1; continue } if abs(other.minY - line.rect.minY) > 0.5 { differ += 1 } } XCTAssertEqual(differ, 0, "\(when): lines on screen away from where a whole layout puts them") guard let first = shown.first?.range.location, let last = shown.last?.range.location, let from = text.pages.paragraph(at: first), let to = text.pages.paragraph(at: last) else { return } for index in from...to where text.pages.paragraphs[index].extra > 0 { guard let location = content.location(content.documentRange.location, offsetBy: text.pages.range(of: index).location), let fragment = layout.textLayoutFragment(for: location), let placed = text.pages.paragraphs[index].bottom.map({ $0 - (text.pages.paragraphs[index].height ?? 0) }) else { continue } let top = fragment.layoutFragmentFrame.minY + (fragment.textLineFragments.first?.typographicBounds.minY ?? 0) XCTAssertEqual(top, placed, accuracy: 0.5, "\(when): a break on screen laid out where it was placed") } } /// A one-line document scrolls to its page's foot (its bottom margin and /// page number), not only to its text's end. func testAShortDocumentScrollsToItsPagesFoot() throws { DocsFonts.register() let window = UIWindow(frame: CGRect(x: 0, y: 0, width: 402, height: 874)) window.makeKeyAndVisible() defer { window.isHidden = true } let text = DocsTextView(frame: window.bounds) text.paged = true window.addSubview(text) defer { text.removeFromSuperview() } text.attributedText = NSAttributedString(string: "One line.", attributes: [.font: DocsFonts.defaultFont()]) text.layoutIfNeeded() XCTAssertGreaterThanOrEqual(text.contentSize.height, text.headerHeight + DocsPageGeometry.paperHeight - 0.5) text.paged = false text.layoutIfNeeded() XCTAssertLessThan(text.contentSize.height, DocsPageGeometry.paperHeight, "pageless, the content is the text's") } /// Everything placed, then the three checks. private func check(_ text: DocsTextView, _ when: String) throws { text.paginateEverything() let layout = try XCTUnwrap(text.textLayoutManager) let content = try XCTUnwrap(layout.textContentManager) let geometry = text.geometry let lines = PhoneLargeDocumentTests.lines(in: text, near: 0, height: .greatestFiniteMagnitude) XCTAssertGreaterThan(lines.count, 100, when) var straddling = 0 for line in lines where line.range.length > 0 { let y = line.rect.minY - text.headerHeight let top = CGFloat(geometry.page(at: y)) * geometry.stride + DocsPageGeometry.verticalMargin if y < top - 0.01 || y + line.rect.height > top + geometry.bodyHeight + 0.01 { straddling += 1 } } XCTAssertEqual(straddling, 0, "\(when): lines in a gap or across a page's bottom margin") var off = 0 for index in text.pages.paragraphs.indices where text.pages.paragraphs[index].extra > 0 { guard let location = content.location(content.documentRange.location, offsetBy: text.pages.range(of: index).location), let fragment = layout.textLayoutFragment(for: location), let placed = text.pages.paragraphs[index].bottom.map({ $0 - (text.pages.paragraphs[index].height ?? 0) }) else { continue } let top = fragment.layoutFragmentFrame.minY + (fragment.textLineFragments.first?.typographicBounds.minY ?? 0) if abs(top - placed) > 0.5 { off += 1 } } XCTAssertEqual(off, 0, "\(when): breaks laid out away from where they were placed") // A fresh view of the same text, laid out whole. let whole = DocsTextView(frame: text.frame) whole.paged = true text.superview?.addSubview(whole) defer { whole.removeFromSuperview() } whole.attributedText = text.attributedText whole.layoutIfNeeded() whole.paginateEverything() let reference = Dictionary(PhoneLargeDocumentTests.lines(in: whole, near: 0, height: .greatestFiniteMagnitude) .map { ($0.range.location, $0.rect) }, uniquingKeysWith: { a, _ in a }) var differ = 0 for line in lines where line.range.length > 0 { guard let other = reference[line.range.location] else { differ += 1; continue } if abs(other.minY - line.rect.minY) > 0.5 { differ += 1 } } XCTAssertEqual(differ, 0, "\(when): lines away from where a whole layout puts them") } } #endif