Cotton code
157 lines · 9.0 KB · SwiftRaw
// Pictures at once (CONTRACT.md "Pictures at once", 23 Nov 2026). The owner,// on Comms build 23: opening a chat, its pictures took one to two seconds to// appear, blank boxes meanwhile. Every picture now carries a small preview in// its message, drawn on the first frame at the picture's true size.//// Chat Dev's invented chats (-chat-warm-seed YES) carry previews as a phone// that makes them sends them. -chat-warm-picture-wait <s> holds every// picture's file that long, as a server far away; -chat-warm-send-picture <s>// holds the upload; -chat-warm-freeable <bytes> lets Storage free that much.// At the default text size and the largest.import XCTestfinal class ChatPicturesAtOnceTests: XCTestCase {    private let meera = "11111111-1111-4111-8111-0000000000e1"    private let asha = "11111111-1111-4111-8111-0000000000a1"    private static let largest = ["-UIPreferredContentSizeCategoryName", "UICTContentSizeCategoryAccessibilityXXXL"]    override func setUp() { continueAfterFailure = false }    private func launched(_ extra: [String]) -> XCUIApplication {        let app = XCUIApplication()        app.launchArguments += ["-chat-warm-seed", "YES"] + extra        app.launch()        return app    }    private func bubble(_ app: XCUIApplication, _ id: String) -> XCUIElement {        app.descendants(matching: .any)["chat-bubble-\(id)"].firstMatch    }    private func keep(_ name: String) {        let shot = XCTAttachment(screenshot: XCUIScreen.main.screenshot())        shot.name = name        shot.lifetime = .keepAlways        add(shot)    }    /// The colour at `point` on the screen now.    private func ink(at point: CGPoint) -> [Int] {        let image = XCUIScreen.main.screenshot().image        let cg = image.cgImage!        let scale = CGFloat(cg.width) / image.size.width        var bytes = [UInt8](repeating: 0, count: cg.width * cg.height * 4)        let context = CGContext(data: &bytes, width: cg.width, height: cg.height, bitsPerComponent: 8, bytesPerRow: cg.width * 4,                                space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue)!        context.draw(cg, in: CGRect(x: 0, y: 0, width: cg.width, height: cg.height))        let x = min(cg.width - 1, max(0, Int(point.x * scale))), y = min(cg.height - 1, max(0, Int(point.y * scale)))        let i = (y * cg.width + x) * 4        return [Int(bytes[i]), Int(bytes[i + 1]), Int(bytes[i + 2])]    }    /// Whether `ink` is the empty tile's own ground (#F0EBE3 by day): a blank box.    private func blank(_ ink: [Int]) -> Bool {        abs(ink[0] - 0xF0) < 8 && abs(ink[1] - 0xEB) < 8 && abs(ink[2] - 0xE3) < 8    }    /// The picture's tile in a photo bubble: the bubble's widest image-shaped part, its centre a little above the caption.    private func tileCentre(_ element: XCUIElement) -> CGPoint {        let f = element.frame        // Theirs stand at the left after the face; the tile is 248 points wide and at least 150 tall from the bubble's top.        return CGPoint(x: min(f.maxX - 20, f.minX + 124 + 44), y: f.minY + 70)    }    private func noBlankBoxOnOpen(_ extra: [String], shot: String) {        let app = launched(["-chat-warm-open", meera, "-chat-warm-picture-wait", "6"] + extra)        XCTAssertTrue(app.tables["chat-thread"].waitForExistence(timeout: 30), "the chat opened")        let photo = bubble(app, "m-media-1")        XCTAssertTrue(photo.waitForExistence(timeout: 10), "the photo stands")        // At the largest text the chat opens below it: brought into view (its file is asked only once it shows).        let window = app.windows.firstMatch.frame        let inView = { photo.frame.minY > window.minY + 110 && photo.frame.minY + 160 < window.maxY - 130 }        for _ in 0..<8 where !inView() {            // Dragged by what is measured, held at the end so nothing flings: the photo's top to 200 points down.            let dy = max(-300, min(300, window.minY + 200 - photo.frame.minY))            let start = app.windows.firstMatch.coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 0.5))            start.press(forDuration: 0.05, thenDragTo: start.withOffset(CGVector(dx: 0, dy: dy)), withVelocity: .slow, thenHoldForDuration: 0.4)        }        XCTAssertTrue(inView(), "the photo is on screen: \(photo.frame) in \(window)")        // The file is held six seconds: what stands now is the preview the message carried.        let point = tileCentre(photo)        let seen = ink(at: point)        XCTAssertFalse(blank(seen), "the picture's preview stands at once, never a blank box: \(seen) at \(point) in \(photo.frame)")        keep(shot)        XCTAssertFalse(photo.label.contains("Picture not available"), photo.label)    }    // RULE (a): a chat with pictures shows no blank box on open, while the pictures' files are still on their way.    func testAChatWithPicturesShowsNoBlankBoxOnOpen() {        noBlankBoxOnOpen([], shot: "pictures-open-preview")    }    func testNoBlankBoxAtTheLargestText() {        noBlankBoxOnOpen(Self.largest, shot: "pictures-open-preview-largest")    }    // RULE (a, c): scrolling a long chat of pictures whose files are slow, no picture that comes into view is a blank box.    func testScrollingALongChatOfPicturesShowsNoBlankBox() {        let app = launched(["-chat-warm-long", "600", "-chat-warm-pictures", "YES", "-chat-warm-open", "chat-warm-long", "-chat-warm-picture-wait", "4"])        let table = app.tables["chat-thread"]        XCTAssertTrue(table.waitForExistence(timeout: 30), "the chat opened")        var looked = 0, blanks = 0        for round in 0..<8 {            table.swipeDown(velocity: .fast)            let shown = app.descendants(matching: .any).matching(NSPredicate(format: "identifier BEGINSWITH 'chat-bubble-long-'")).allElementsBoundByIndex            for element in shown where element.frame.height > 160 && element.frame.minY > 120 && element.frame.maxY < app.frame.maxY - 140 {                guard let n = Int(element.identifier.replacingOccurrences(of: "chat-bubble-long-", with: "")), n % 3 == 0 else { continue }                looked += 1                if blank(ink(at: tileCentre(element))) { blanks += 1 }            }            if round == 3 { keep("pictures-long-scroll") }        }        XCTAssertGreaterThan(looked, 4, "pictures came into view")        XCTAssertEqual(blanks, 0, "of \(looked) pictures seen while scrolling, \(blanks) were blank boxes")    }    // RULE (d): a picture sent shows at once from the phone's own file, before the server answers (the upload is held).    func testASentPictureShowsBeforeTheServerAnswers() {        let app = launched(["-chat-warm-open", asha, "-chat-warm-send-picture", "10", "-chat-warm-picture-wait", "10"])        XCTAssertTrue(app.tables["chat-thread"].waitForExistence(timeout: 30), "the chat opened")        let single = bubble(app, "seed-sent-2")        XCTAssertTrue(single.waitForExistence(timeout: 8), "the picture sent stands")        // The invented pictures sent are cool blue-green; the tile's own ground is warm.        let f = single.frame        let seen = ink(at: CGPoint(x: f.midX, y: f.midY))        XCTAssertGreaterThan(seen[1], seen[0] + 10, "the phone's own picture, while the upload is still held: \(seen)")        keep("pictures-sent-at-once")    }    // RULE (e): Free up space takes the full pictures that are safely in the account, never the previews: a chat    // opened after it still shows every picture's preview at once while its file comes back.    func testFreeUpSpaceKeepsPreviews() {        let app = launched(["-chat-warm-place", "you", "-chat-warm-you", "storage", "-chat-warm-freeable", "12000000"])        let free = app.descendants(matching: .any)["settings-free-up"].firstMatch        XCTAssertTrue(free.waitForExistence(timeout: 60), "Storage offers Free up space")        let label = free.label        free.tap()        // It asks first; the seed's ask is in the button's own words.        let yes = app.buttons.matching(NSPredicate(format: "label == %@ AND identifier != %@", label, "settings-free-up")).firstMatch        XCTAssertTrue(yes.waitForExistence(timeout: 10), "it asks first")        yes.tap()        app.descendants(matching: .any)["you-storage-page-back"].firstMatch.tap()        let chats = app.buttons["chat-place-chats"]        XCTAssertTrue(chats.waitForExistence(timeout: 10))        chats.tap()        let row = app.descendants(matching: .any)["chat-row-\(meera)"].firstMatch        XCTAssertTrue(row.waitForExistence(timeout: 10), "Meera's chat in the list")        row.tap()        let photo = bubble(app, "m-media-1")        XCTAssertTrue(photo.waitForExistence(timeout: 10), "the photo stands")        let window = app.windows.firstMatch.frame        XCTAssertTrue(photo.frame.minY > window.minY + 110 && photo.frame.minY + 160 < window.maxY - 130, "the photo is on screen: \(photo.frame)")        let seen = ink(at: tileCentre(photo))        XCTAssertFalse(blank(seen), "after Free up space the preview still stands: \(seen)")        keep("pictures-after-free-up")    }}