diff --git a/AppTests/ConnectionModelTests.swift b/AppTests/ConnectionModelTests.swift index a4e00c6..be60fdb 100644 --- a/AppTests/ConnectionModelTests.swift +++ b/AppTests/ConnectionModelTests.swift @@ -128,7 +128,7 @@ struct ConnectionModelTests { /// The parser answers from its own isolation, so conditions that read it have to await. private func waitUntil(_ condition: @MainActor () async -> Bool) async throws { - let deadline = ContinuousClock.now.advanced(by: .seconds(5)) + let deadline = ContinuousClock.now.advanced(by: .seconds(20)) while await !condition() { guard ContinuousClock.now < deadline else { throw WaitError.timedOut } try await Task.sleep(for: .milliseconds(1)) diff --git a/AppTests/TailscaleImportPresentationTests.swift b/AppTests/TailscaleImportPresentationTests.swift index af7d01f..67afa3d 100644 --- a/AppTests/TailscaleImportPresentationTests.swift +++ b/AppTests/TailscaleImportPresentationTests.swift @@ -121,7 +121,7 @@ final class TailscaleImportPresentationTests: XCTestCase { @MainActor private func waitUntil(_ message: String, condition: @MainActor () -> Bool) async throws { - let deadline = ContinuousClock.now.advanced(by: .seconds(5)) + let deadline = ContinuousClock.now.advanced(by: .seconds(20)) while !condition() { guard ContinuousClock.now < deadline else { XCTFail(message) diff --git a/AppTests/TerminalResizeTests.swift b/AppTests/TerminalResizeTests.swift index 5f8a8b2..b8f4b7d 100644 --- a/AppTests/TerminalResizeTests.swift +++ b/AppTests/TerminalResizeTests.swift @@ -105,7 +105,7 @@ final class TerminalResizeTests: XCTestCase { @MainActor private func waitUntil(_ description: String, condition: @MainActor () -> Bool) async throws { - let deadline = ContinuousClock.now.advanced(by: .seconds(3)) + let deadline = ContinuousClock.now.advanced(by: .seconds(20)) while !condition() { guard ContinuousClock.now < deadline else { XCTFail(description) diff --git a/AppTests/WorkspaceLayoutTests.swift b/AppTests/WorkspaceLayoutTests.swift index d093799..ad1e312 100644 --- a/AppTests/WorkspaceLayoutTests.swift +++ b/AppTests/WorkspaceLayoutTests.swift @@ -136,7 +136,7 @@ final class WorkspaceLayoutTests: XCTestCase { @MainActor private func waitUntil(_ description: String, condition: @MainActor () -> Bool) async throws { - let deadline = ContinuousClock.now.advanced(by: .seconds(5)) + let deadline = ContinuousClock.now.advanced(by: .seconds(20)) while !condition() { guard ContinuousClock.now < deadline else { XCTFail(description) diff --git a/AppTests/WorkspaceSessionStoreTests.swift b/AppTests/WorkspaceSessionStoreTests.swift index 594480e..62beef9 100644 --- a/AppTests/WorkspaceSessionStoreTests.swift +++ b/AppTests/WorkspaceSessionStoreTests.swift @@ -59,7 +59,7 @@ struct WorkspaceSessionStoreTests { } private func waitUntil(_ condition: @MainActor () -> Bool) async throws { - let deadline = ContinuousClock.now.advanced(by: .seconds(5)) + let deadline = ContinuousClock.now.advanced(by: .seconds(20)) while !condition() { guard ContinuousClock.now < deadline else { throw WaitError.timedOut } try await Task.sleep(for: .milliseconds(1)) diff --git a/spike/GhosttyEngine/Sources/GhosttyEngine/GhosttyEngine.swift b/spike/GhosttyEngine/Sources/GhosttyEngine/GhosttyEngine.swift index 9c69177..145e706 100644 --- a/spike/GhosttyEngine/Sources/GhosttyEngine/GhosttyEngine.swift +++ b/spike/GhosttyEngine/Sources/GhosttyEngine/GhosttyEngine.swift @@ -740,6 +740,13 @@ import TerminalCore return nil } + // From here to the store, every entry this drops is one this engine is displacing with + // an image it has just decoded — its own older pixels, whether through the count cap + // below or through the budget reaching back into this owner. A fresh snapshot is + // already on its way, so none of it is announced. See `removeImage(_:)`. + isMakingRoomForOwnImage = true + defer { isMakingRoomForOwnImage = false } + // Replacing the pixels of an id already held: give back the old bytes first, so the // budget never counts two generations of the same image at once. if imageCache[id] != nil { removeImage(id) } @@ -760,22 +767,53 @@ import TerminalCore return (converted, Int(width), Int(height), generation) } - /// `TerminalImageBudgetOwner`: the workspace evicting this engine's image to make room for - /// another session's. The budget has already removed its accounting entry. - public func evictImage(_ id: UInt32) { removeImage(id) } + /// True while this engine is displacing its own pixels with an image it has just decoded, + /// so the budget calling back into it is not another session taking the memory away. + private var isMakingRoomForOwnImage = false + + /// `TerminalImageBudgetOwner`: the budget evicting this engine's image. The budget has + /// already removed its accounting entry. + /// + /// Announced unless this engine asked for the room itself. A memory warning, or another + /// session's image displacing this one, is memory being taken away from a frame that may + /// be the last one a hidden session ever draws — exactly what #26 was about. This engine + /// making room for its own next frame is not, and announcing it once per frame is what + /// made stepping through a video strobe. + public func evictImage(_ id: UInt32) { + if isMakingRoomForOwnImage { removeImage(id) } else { evictImageAnnouncing(id) } + } /// Drops one image's pixels, its accounting, and the snapshot still holding them. Without /// the callback the published snapshot keeps the bytes alive in a hidden view's last frame /// and the eviction frees nothing — `onImageCacheInvalidated` was declared here and never /// called (#26). - private func removeImage(_ id: UInt32) { - guard imageCache.removeValue(forKey: id) != nil else { return } - imageBudget?.release(imageID: id, owner: self) + private func evictImageAnnouncing(_ id: UInt32) { + guard removeImage(id) else { return } previous = nil onImageCacheInvalidated?() changed() } + /// Drops one image's pixels and its accounting without asking the caller for anything. + /// + /// The announcement above costs a frame. `ConnectionModel` answers it by clearing the + /// published snapshot and scheduling another, so the view draws its background colour once + /// before the replacement arrives. That is the right trade for an eviction, where the whole + /// point is to stop a frame already on screen from keeping the bytes alive. + /// + /// It is the wrong trade for bookkeeping. Reaping an entry whose image the library has + /// already dropped, or replacing one generation of an image with the next, leaves the frame + /// on screen still being the frame the terminal means, and nothing is waiting on its + /// memory — the snapshot that replaces it is already being built. Announcing those made a + /// repaint that deletes an image flash the terminal's background on this engine, which is + /// the flicker choosing this engine is supposed to avoid. + @discardableResult + private func removeImage(_ id: UInt32) -> Bool { + guard imageCache.removeValue(forKey: id) != nil else { return false } + imageBudget?.release(imageID: id, owner: self) + return true + } + private func releaseAllImages() { guard !imageCache.isEmpty else { return } imageCache.removeAll(keepingCapacity: true) diff --git a/spike/GhosttyEngine/Tests/GhosttyEngineTests/GhosttyEngineMemoryTests.swift b/spike/GhosttyEngine/Tests/GhosttyEngineTests/GhosttyEngineMemoryTests.swift index fde8588..0ab2681 100644 --- a/spike/GhosttyEngine/Tests/GhosttyEngineTests/GhosttyEngineMemoryTests.swift +++ b/spike/GhosttyEngine/Tests/GhosttyEngineTests/GhosttyEngineMemoryTests.swift @@ -73,6 +73,70 @@ struct GhosttyEngineMemoryTests { #expect(displays == 1) } + /// Deleting an image is the ordinary end of a Kitty image's life — `icat` does it, and so + /// does any full-screen program that repaints. The engine has to give the bytes back, and + /// it must not ask the app to drop the frame it is showing to do it: `ConnectionModel` + /// answers `onImageCacheInvalidated` by publishing a nil snapshot, so the terminal draws + /// its background colour for a frame. Announcing this reap is what made a repaint flash + /// black on this engine while `SwiftTermEngine` stayed steady. + @Test func deletingAnImageGivesItsBytesBackWithoutDroppingTheFrame() throws { + let budget = TerminalImageBudget(maximumTotalBytes: 1 << 20) + let engine = try #require(GhosttyEngine(columns: 20, rows: 6, imageBudget: budget)) + engine.setCellSize(width: 8, height: 16) + engine.feed(kittyImage(id: 1, width: 8, height: 8)) + #expect(engine.snapshot().images.map(\.id) == [1]) + #expect(budget.totalBytes == 8 * 8 * 4) + + var invalidations = 0 + engine.onImageCacheInvalidated = { invalidations += 1 } + // a=d,d=I deletes one image by id, its pixels included. + engine.feed(Data("\u{1b}_Ga=d,d=I,i=1\u{1b}\\".utf8)) + #expect(engine.snapshot().images.isEmpty) + #expect(budget.totalBytes == 0) + #expect(invalidations == 0) + } + + /// The same for one generation of an image replacing another, which is how an animated or + /// repeatedly redrawn image arrives. The frame on screen holds the previous pixels of an + /// image that still exists, which is a frame, not stale data. + @Test func replacingAnImagesPixelsDoesNotDropTheFrame() throws { + let budget = TerminalImageBudget(maximumTotalBytes: 1 << 20) + let engine = try #require(GhosttyEngine(columns: 20, rows: 6, imageBudget: budget)) + engine.setCellSize(width: 8, height: 16) + engine.feed(kittyImage(id: 1, width: 8, height: 8)) + #expect(engine.snapshot().images.map(\.id) == [1]) + + var invalidations = 0 + engine.onImageCacheInvalidated = { invalidations += 1 } + engine.feed(kittyImage(id: 1, width: 4, height: 4)) + #expect(engine.snapshot().images.map(\.id) == [1]) + #expect(budget.totalBytes == 4 * 4 * 4) + #expect(invalidations == 0) + } + + /// Stepping through a video: a new image id per frame, for long enough that both ceilings + /// start displacing earlier frames — the count cap first, then the workspace's byte budget + /// reaching back into this engine. Neither is another session taking memory away, so + /// neither may ask the app to drop the frame on screen. Announcing them put a background + /// coloured frame between every pair of video frames on this engine. + @Test func steppingThroughVideoFramesNeverDropsTheFrameOnScreen() throws { + // Sixteen 8x8 frames fit; the seventeenth has to displace one, and every frame after + // it does the same. + let budget = TerminalImageBudget(maximumTotalBytes: 16 * 8 * 8 * 4) + let engine = try #require(GhosttyEngine(columns: 20, rows: 6, imageBudget: budget)) + engine.setCellSize(width: 8, height: 16) + var invalidations = 0 + engine.onImageCacheInvalidated = { invalidations += 1 } + + for frame in 1...80 { + engine.feed(kittyImage(id: UInt32(frame), width: 8, height: 8)) + _ = engine.snapshot() + } + #expect(invalidations == 0) + // Silence is not the budget going unenforced: the ceiling still holds. + #expect(budget.totalBytes <= 16 * 8 * 8 * 4) + } + @Test func oneImageLargerThanTheCeilingIsRefusedRatherThanDecoded() throws { // Four pixels of RGBA is sixteen bytes, so a ceiling of eight cannot hold it. The // engine used to have no byte ceiling at all: a count of 64 entries admitted 64 images