Cotton code
155 lines · 8.6 KB · SwiftRaw
// Real flings on four lists under the fan, for scripts/perf/scroll.sh (291// row F: 120 Hz with no dropped frames scrolling any list while the fan folds// and blooms). The test launches the synthetic Home with 30 tiles and the// lists grown by `-list-rows`, waits for the script to attach its trace and// for the page pictures to be drawn, then for each tool turns the fan to its// tile with a tap and flings its list for a while: three fast flings down,// then three up, over and over. A fling down past `fan_collapse_scroll` folds// the fan into the record button's circle and a fling back up blooms it, so// every round is a fold and a bloom over a list in flight — what the owner// feels. A mark is printed at each edge so the script cuts the trace and the// frame meter's lines by wall-clock time://   scroll-sweep: mark <tool> <start|end> <unix seconds>import ObjectiveCimport XCTest/// XCTest waits for the app to go quiet after every touch it makes — a/// fling's momentum, the fan's spring — so the first runs of this sweep made/// three flings in ten seconds, all one way, and the fan never bloomed under/// a finger. A person flicks again while the list still runs; so the wait/// (XCTest's own, not a public setting) is turned off once the fan is up,/// and the sweep paces itself with sleeps.private func stopWaitingForQuiet() {    guard let process = NSClassFromString("XCUIApplicationProcess") else { return }    let one: @convention(block) (AnyObject, Bool) -> Void = { _, _ in }    let two: @convention(block) (AnyObject, Bool, Bool) -> Void = { _, _, _ in }    for (name, block) in [("waitForQuiescenceIncludingAnimationsIdle:", one as Any),                          ("waitForQuiescenceIncludingAnimationsIdle:isPreEvent:", two as Any)] {        guard let method = class_getInstanceMethod(process, NSSelectorFromString(name)) else { continue }        method_setImplementation(method, imp_implementationWithBlock(block))    }}@MainActorfinal class ScrollSweep: XCTestCase {    private func mark(_ phase: String, _ edge: String) {        print("scroll-sweep: mark \(phase) \(edge) \(String(format: "%.3f", Date().timeIntervalSince1970))")    }    private func number(_ name: String, _ fallback: Double) -> Double {        Double(ProcessInfo.processInfo.environment[name] ?? "") ?? fallback    }    /// The tools flung, in order. Their tiles stand next to one another    /// beside Me, where the fan opens (`-home-keys` below), so each is a tap    /// away from the one before it.    private var tools: [String] {        (ProcessInfo.processInfo.environment["SCROLL_TOOLS"] ?? "meetings|mood|people|email")            .split(separator: "|").map(String.init)    }    func testScroll() throws {        let app = XCUIApplication(bundleIdentifier: "com.cottondb.homepreview")        // The fan opens on Me, which the board inserts at the middle of its        // tiles: 30 tiles put Me at 15. Eleven other tools first put the four        // flung at 11 to 14, the first flung next to Me and each next one a        // step further, so every turn is a tap on a drawn neighbour (the arc        // draws only about three tiles each side).        let fillers = ["todos", "calendar", "notes", "journal", "locations", "reader", "alarms", "thoughts",                       "accounts", "documents", "news"]        app.launchArguments = [            "-home-tiles", "30",            "-home-keys", (fillers + tools.reversed()).joined(separator: "|"),            "-list-rows", String(Int(number("SCROLL_ROWS", 200))),            "-dev.frames.on", "YES",        ]        app.launch()        let fan = app.descendants(matching: .any)["home-fan"]        XCTAssertTrue(fan.waitForExistence(timeout: 60), "the fan is on screen")        stopWaitingForQuiet()        // The script attaches its trace, and the painter draws every tile's        // picture, before anything is measured.        mark("settle", "start")        Thread.sleep(forTimeInterval: number("SCROLL_SETTLE_S", 20))        mark("settle", "end")        let screen = app.windows.firstMatch.frame        let origin = app.coordinate(withNormalizedOffset: .zero)        let point = { (x: Double, y: Double) in origin.withOffset(CGVector(dx: screen.width * x, dy: screen.height * y)) }        // The page's own band, clear of the fan's deck at the foot even while        // it stands: a finger here scrolls the list, never turns the fan.        let high = point(0.5, 0.18)        let low = point(0.5, 0.52)        // Fast enough to leave the list running on after the finger lifts.        let fling = XCUIGestureVelocity(rawValue: number("SCROLL_VELOCITY", 2500))        let seconds = number("SCROLL_S", 10)        // Between flings: the list runs on under no finger for a moment, as        // between a reader's flicks, before the next one catches it.        let gap = number("SCROLL_GAP_S", 0.25)        for tool in tools {            try turn(app, to: tool, screen: screen)            // The tile's live page stands under its picture once the fan rests.            Thread.sleep(forTimeInterval: number("SCROLL_PAGE_S", 3))            mark(tool, "start")            let started = Date()            var flings = 0            while Date().timeIntervalSince(started) < seconds {                let down = (flings / 3) % 2 == 0                let (from, to) = down ? (low, high) : (high, low)                from.press(forDuration: 0.01, thenDragTo: to, withVelocity: fling, thenHoldForDuration: 0)                flings += 1                Thread.sleep(forTimeInterval: gap)            }            mark(tool, "end")            print("scroll-sweep: \(tool) \(flings) flings")            // Back to the list's top, so the fan blooms and its tiles take a tap.            for _ in 0 ..< 6 {                high.press(forDuration: 0.01, thenDragTo: low, withVelocity: fling, thenHoldForDuration: 0)                Thread.sleep(forTimeInterval: gap)            }            Thread.sleep(forTimeInterval: 2)        }    }    /// Turns the fan to `key`'s tile with a tap on it. A tile past the arc's    /// drawn reach has no frame; then the deck is swiped a step at a time,    /// first one way and then the other, until it is drawn. A fan still    /// folded is bloomed first with a swipe up on its circle.    private func turn(_ app: XCUIApplication, to key: String, screen: CGRect) throws {        let tile = app.descendants(matching: .any)["fan-tile-\(key)"]        let tiles = app.descendants(matching: .any).matching(NSPredicate(format: "identifier BEGINSWITH 'fan-tile-'"))        // Drawn: on screen with a frame (tiles past the arc's reach have        // none). Not `isHittable`: the deck takes its touches as one view, so        // XCTest calls no tile of it hittable.        func drawn(_ element: XCUIElement) -> Bool {            element.exists && element.frame.width > 0 && screen.intersects(element.frame)        }        print("scroll-sweep: tiles " + tiles.allElementsBoundByIndex            .map { "\($0.identifier)@\(Int($0.frame.midX)),\(Int($0.frame.midY))" }.joined(separator: " "))        if !tiles.allElementsBoundByIndex.contains(where: drawn) {            let circle = app.coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 0.93))            circle.press(forDuration: 0.01, thenDragTo: app.coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 0.6)))            Thread.sleep(forTimeInterval: 1)        }        var steps = 0        while !drawn(tile), steps < 12 {            let settled = try XCTUnwrap(tiles.allElementsBoundByIndex.filter(drawn).map(\.frame)                .min { abs($0.midX - screen.midX) < abs($1.midX - screen.midX) }, "a tile of the fan is drawn")            let row = settled.midY            let right = app.coordinate(withNormalizedOffset: .zero).withOffset(CGVector(dx: screen.width * 0.65, dy: row))            let left = app.coordinate(withNormalizedOffset: .zero).withOffset(CGVector(dx: screen.width * 0.35, dy: row))            let (from, to) = steps < 4 ? (left, right) : (right, left)            from.press(forDuration: 0.05, thenDragTo: to, withVelocity: .slow, thenHoldForDuration: 0.2)            Thread.sleep(forTimeInterval: 1)            steps += 1        }        XCTAssertTrue(drawn(tile), "\(key)'s tile is drawn on the fan")        tile.tap()        Thread.sleep(forTimeInterval: 1.5)        // The settled tile is the one drawn nearest the screen's middle.        let middle = tiles.allElementsBoundByIndex.filter(drawn)            .min { abs($0.frame.midX - screen.midX) < abs($1.frame.midX - screen.midX) }        print("scroll-sweep: turned to \(key), settled \(middle?.identifier ?? "none")")    }}