Fastest and only macOS Dictation app with on-device STT and custom trained AI enhancement model. Windows, iOS testflight! Android, Linux waitlist open! A local Wispr Flow alternative. Follow https://x.com/fluidvoiceapp for more
restore image clipboard
grohith327b11847557824
diff --git a/Sources/Fluid/ContentView.swift b/Sources/Fluid/ContentView.swiftindex d3e0efee..36275f5d 100644--- a/Sources/Fluid/ContentView.swift+++ b/Sources/Fluid/ContentView.swift@@ -2578,7 +2578,7 @@ struct ContentView: View {case .targetUnavailable, .targetRestoreFailed:"Could not restore the target text field"case .clipboardSnapshotFailed:- "Clipboard is too large or complex to preserve"+ "Clipboard contents could not be preserved exactly"case .clipboardWriteFailed:"Could not prepare the clipboard"case .pasteCommandFailed:diff --git a/Sources/Fluid/Services/PasteDeliveryCoordinator.swift b/Sources/Fluid/Services/PasteDeliveryCoordinator.swiftindex d6809fe8..a74d16dd 100644--- a/Sources/Fluid/Services/PasteDeliveryCoordinator.swift+++ b/Sources/Fluid/Services/PasteDeliveryCoordinator.swift@@ -22,7 +22,13 @@ enum TextDeliveryResult: Equatable {struct PasteboardSnapshot: Equatable {struct Item: Equatable {- let representations: [String: Data]+ struct Representation: Equatable {+ let type: NSPasteboard.PasteboardType+ let data: Data+ }++ /// AppKit uses source order as representation preference, so this must remain ordered.+ let representations: [Representation]}let items: [Item]@@ -30,7 +36,7 @@ struct PasteboardSnapshot: Equatable {@MainActorprotocol PasteboardManaging: AnyObject {- func captureBoundedSnapshot() -> PasteboardSnapshot?+ func captureSnapshot() -> PasteboardSnapshot?func writeTemporaryText(_ text: String, sessionID: String) -> Boolfunc writeIntentionalText(_ text: String) -> Boolfunc isOwned(sessionID: String, expectedText: String) -> Bool@@ -50,9 +56,6 @@ final class SystemPasteboardManager: PasteboardManaging {private static let sessionType = NSPasteboard.PasteboardType("\(Bundle.main.bundleIdentifier ?? "com.FluidApp.Fluid").PasteSession")- static let maximumRepresentationBytes = 4 * 1024 * 1024- static let maximumSnapshotBytes = 16 * 1024 * 1024- static let maximumItems = 100private let pasteboard: NSPasteboard@@ -60,62 +63,82 @@ final class SystemPasteboardManager: PasteboardManaging {self.pasteboard = pasteboard}- func captureBoundedSnapshot() -> PasteboardSnapshot? {- var totalBytes = 0- let sourceItems = self.pasteboard.pasteboardItems ?? []- guard sourceItems.count <= Self.maximumItems else {- self.logSnapshotFailure(reason: "too_many_items", itemCount: sourceItems.count, totalBytes: totalBytes)- return nil- }-- var items: [PasteboardSnapshot.Item] = []- for sourceItem in sourceItems {- guard !sourceItem.types.isEmpty else {- self.logSnapshotFailure(reason: "empty_item", itemCount: sourceItems.count, totalBytes: totalBytes)- return nil- }-- var representations: [String: Data] = [:]- for type in sourceItem.types {- guard let data = sourceItem.data(forType: type) else {- self.logSnapshotFailure(- reason: "unavailable_representation",- itemCount: sourceItems.count,- totalBytes: totalBytes,- type: type+ func captureSnapshot() -> PasteboardSnapshot? {+ for attempt in 1...2 {+ let startingChangeCount = self.pasteboard.changeCount+ guard let sourceItems = self.pasteboard.pasteboardItems else {+ let endingChangeCount = self.pasteboard.changeCount+ if endingChangeCount != startingChangeCount {+ self.logSnapshotRetry(+ attempt: attempt,+ startingChangeCount: startingChangeCount,+ endingChangeCount: endingChangeCount)- return nil+ continue}- guard data.count <= Self.maximumRepresentationBytes else {- self.logSnapshotFailure(- reason: "representation_too_large",- itemCount: sourceItems.count,- totalBytes: totalBytes,- type: type- )- return nil+ self.logSnapshotFailure(+ reason: "pasteboard_items_unavailable",+ itemCount: 0,+ itemIndex: -1,+ totalBytes: 0+ )+ return nil+ }+ var items: [PasteboardSnapshot.Item] = []+ var totalBytes = 0+ var totalRepresentations = 0+ var failure: (reason: String, itemIndex: Int, type: NSPasteboard.PasteboardType?)?++ itemLoop: for (itemIndex, sourceItem) in sourceItems.enumerated() {+ let sourceTypes = sourceItem.types+ guard !sourceTypes.isEmpty else {+ failure = ("empty_item", itemIndex, nil)+ break}- guard data.count <= Self.maximumSnapshotBytes - totalBytes else {- self.logSnapshotFailure(- reason: "snapshot_too_large",- itemCount: sourceItems.count,- totalBytes: totalBytes,- type: type- )- return nil++ var representations: [PasteboardSnapshot.Item.Representation] = []+ representations.reserveCapacity(sourceTypes.count)+ for type in sourceTypes {+ guard let data = sourceItem.data(forType: type) else {+ failure = ("unavailable_representation", itemIndex, type)+ break itemLoop+ }+ representations.append(.init(type: type, data: data))+ totalBytes += data.count+ totalRepresentations += 1}- representations[type.rawValue] = data- totalBytes += data.count+ items.append(.init(representations: representations))}- items.append(PasteboardSnapshot.Item(representations: representations))++ let endingChangeCount = self.pasteboard.changeCount+ guard endingChangeCount == startingChangeCount else {+ self.logSnapshotRetry(+ attempt: attempt,+ startingChangeCount: startingChangeCount,+ endingChangeCount: endingChangeCount+ )+ continue+ }++ if let failure {+ self.logSnapshotFailure(+ reason: failure.reason,+ itemCount: sourceItems.count,+ itemIndex: failure.itemIndex,+ totalBytes: totalBytes,+ type: failure.type+ )+ return nil+ }++ self.log(+ "clipboard_snapshot_complete items=\(items.count) representations=\(totalRepresentations) bytes=\(totalBytes)"+ )+ return PasteboardSnapshot(items: items)}- DebugLogger.shared.benchmark(- "TYPING_BENCH",- message: "clipboard_snapshot_complete items=\(items.count) bytes=\(totalBytes)",- source: "TypingBenchmark"- )- return PasteboardSnapshot(items: items)+ self.log("clipboard_snapshot_failed reason=clipboard_changed_during_snapshot")+ return nil}func writeTemporaryText(_ text: String, sessionID: String) -> Bool {@@ -150,8 +173,8 @@ final class SystemPasteboardManager: PasteboardManaging {var items: [NSPasteboardItem] = []for snapshotItem in snapshot.items {let item = NSPasteboardItem()- for (rawType, data) in snapshotItem.representations {- guard item.setData(data, forType: NSPasteboard.PasteboardType(rawType)) else {+ for representation in snapshotItem.representations {+ guard item.setData(representation.data, forType: representation.type) else {return false}}@@ -165,15 +188,28 @@ final class SystemPasteboardManager: PasteboardManaging {private func logSnapshotFailure(reason: String,itemCount: Int,+ itemIndex: Int,totalBytes: Int,type: NSPasteboard.PasteboardType? = nil) {- DebugLogger.shared.benchmark(- "TYPING_BENCH",- message: "clipboard_snapshot_failed reason=\(reason) items=\(itemCount) bytes=\(totalBytes) type=\(type?.rawValue ?? "nil")",- source: "TypingBenchmark"+ self.log(+ "clipboard_snapshot_failed reason=\(reason) items=\(itemCount) itemIndex=\(itemIndex) bytes=\(totalBytes) type=\(type?.rawValue ?? "nil")"+ )+ }++ private func logSnapshotRetry(+ attempt: Int,+ startingChangeCount: Int,+ endingChangeCount: Int+ ) {+ self.log(+ "clipboard_snapshot_retry attempt=\(attempt) startChangeCount=\(startingChangeCount) endChangeCount=\(endingChangeCount)")}++ private func log(_ message: String) {+ DebugLogger.shared.benchmark("TYPING_BENCH", message: message, source: "TypingBenchmark")+ }}@MainActor@@ -378,7 +414,7 @@ final class PasteDeliveryCoordinator {{return lease.originalSnapshot}- return self.pasteboard.captureBoundedSnapshot()+ return self.pasteboard.captureSnapshot()}private func restoreAfterFailure(diff --git a/Tests/FluidDictationIntegrationTests/PasteDeliveryCoordinatorTests.swift b/Tests/FluidDictationIntegrationTests/PasteDeliveryCoordinatorTests.swiftindex 80b3bdef..cda25739 100644--- a/Tests/FluidDictationIntegrationTests/PasteDeliveryCoordinatorTests.swift+++ b/Tests/FluidDictationIntegrationTests/PasteDeliveryCoordinatorTests.swift@@ -317,10 +317,12 @@ private final class FakePasteboardManager: PasteboardManaging {self.temporaryWriteSucceeds = temporaryWriteSucceeds}- func captureBoundedSnapshot() -> PasteboardSnapshot? {+ func captureSnapshot() -> PasteboardSnapshot? {guard self.snapshotSucceeds else { return nil }return PasteboardSnapshot(items: [- .init(representations: [NSPasteboard.PasteboardType.string.rawValue: Data(self.text.utf8)]),+ .init(representations: [+ .init(type: .string, data: Data(self.text.utf8)),+ ]),])}@@ -348,7 +350,7 @@ private final class FakePasteboardManager: PasteboardManaging {self.restoreCount += 1self.sessionID = nilself.isTemporary = false- guard let data = snapshot.items.first?.representations[NSPasteboard.PasteboardType.string.rawValue],+ guard let data = snapshot.items.first?.representations.first(where: { $0.type == .string })?.data,let restoredText = String(data: data, encoding: .utf8)else {self.text = ""diff --git a/Tests/FluidDictationIntegrationTests/TypingServiceTransientPasteboardTests.swift b/Tests/FluidDictationIntegrationTests/TypingServiceTransientPasteboardTests.swiftindex 6a0f0ccc..7b40b964 100644--- a/Tests/FluidDictationIntegrationTests/TypingServiceTransientPasteboardTests.swift+++ b/Tests/FluidDictationIntegrationTests/TypingServiceTransientPasteboardTests.swift@@ -120,39 +120,114 @@ final class TypingServiceTransientPasteboardTests: XCTestCase {let secondItem = NSPasteboardItem()XCTAssertTrue(secondItem.setString("second", forType: .string))XCTAssertTrue(pasteboard.writeObjects([originalItem, secondItem]))+ let originalItems = try XCTUnwrap(pasteboard.pasteboardItems)+ let originalTypes = originalItems.map(\.types)+ let originalRepresentations = originalItems.map { item in+ item.types.map { type in item.data(forType: type) }+ }let manager = SystemPasteboardManager(pasteboard: pasteboard)- let snapshot = try XCTUnwrap(manager.captureBoundedSnapshot())+ let snapshot = try XCTUnwrap(manager.captureSnapshot())XCTAssertTrue(manager.writeTemporaryText("temporary", sessionID: "session"))XCTAssertTrue(manager.restore(snapshot))let restoredItems = try XCTUnwrap(pasteboard.pasteboardItems)XCTAssertEqual(restoredItems.count, 2)+ XCTAssertEqual(restoredItems.map(\.types), originalTypes)+ XCTAssertEqual(+ restoredItems.map { item in item.types.map { type in item.data(forType: type) } },+ originalRepresentations+ )let restoredItem = restoredItems[0]XCTAssertEqual(restoredItem.string(forType: .string), "original")XCTAssertEqual(restoredItem.data(forType: customType), customData)XCTAssertEqual(restoredItems[1].string(forType: .string), "second")}- func testOversizedSnapshotFailsWithoutChangingPasteboard() {+ func testSnapshotRestoresImageBeforeTextInOriginalPreferenceOrder() throws {let pasteboard = self.makePasteboard()defer { pasteboard.releaseGlobally() }- let customType = NSPasteboard.PasteboardType("com.fluidvoice.tests.oversized")- let originalData = Data(- repeating: 0xab,- count: SystemPasteboardManager.maximumRepresentationBytes + 1++ let bitmap = try XCTUnwrap(+ NSBitmapImageRep(+ bitmapDataPlanes: nil,+ pixelsWide: 2,+ pixelsHigh: 2,+ bitsPerSample: 8,+ samplesPerPixel: 4,+ hasAlpha: true,+ isPlanar: false,+ colorSpaceName: .deviceRGB,+ bytesPerRow: 0,+ bitsPerPixel: 0+ ))+ bitmap.setColor(NSColor(deviceRed: 0, green: 0, blue: 1, alpha: 1), atX: 0, y: 0)+ bitmap.setColor(NSColor(deviceRed: 1, green: 0, blue: 0, alpha: 1), atX: 1, y: 0)+ bitmap.setColor(NSColor(deviceRed: 0, green: 1, blue: 0, alpha: 1), atX: 0, y: 1)+ bitmap.setColor(NSColor(deviceRed: 1, green: 1, blue: 1, alpha: 1), atX: 1, y: 1)+ let imageData = try XCTUnwrap(bitmap.representation(using: .tiff, properties: [:]))+ let originalItem = NSPasteboardItem()+ XCTAssertTrue(originalItem.setData(imageData, forType: .tiff))+ XCTAssertTrue(originalItem.setString("image text fallback", forType: .string))+ XCTAssertTrue(pasteboard.writeObjects([originalItem]))+ let originalTypes = try XCTUnwrap(pasteboard.pasteboardItems?.first?.types)+ XCTAssertEqual(originalTypes.first, .tiff)++ let manager = SystemPasteboardManager(pasteboard: pasteboard)+ let snapshot = try XCTUnwrap(manager.captureSnapshot())+ XCTAssertEqual(snapshot.items.first?.representations.map(\.type), originalTypes)+ XCTAssertTrue(manager.writeTemporaryText("temporary", sessionID: "session"))+ XCTAssertTrue(manager.restore(snapshot))++ let restoredItem = try XCTUnwrap(pasteboard.pasteboardItems?.first)+ XCTAssertEqual(restoredItem.types, originalTypes)+ XCTAssertEqual(restoredItem.data(forType: .tiff), imageData)+ XCTAssertEqual(restoredItem.string(forType: .string), "image text fallback")+ let restoredImageData = try XCTUnwrap(restoredItem.data(forType: .tiff))+ XCTAssertNotNil(NSImage(data: restoredImageData))+ }++ func testLargeRepresentationIsSnapshottedAndRestoredWithoutSizeLimit() throws {+ let pasteboard = self.makePasteboard()+ defer { pasteboard.releaseGlobally() }+ let customType = NSPasteboard.PasteboardType("com.fluidvoice.tests.large")+ let originalData = Data(repeating: 0xab, count: 20 * 1024 * 1024)let originalItem = NSPasteboardItem()XCTAssertTrue(originalItem.setData(originalData, forType: customType))XCTAssertTrue(pasteboard.writeObjects([originalItem]))- let changeCount = pasteboard.changeCount- XCTAssertNil(SystemPasteboardManager(pasteboard: pasteboard).captureBoundedSnapshot())+ let manager = SystemPasteboardManager(pasteboard: pasteboard)+ let snapshot = try XCTUnwrap(manager.captureSnapshot())+ XCTAssertEqual(snapshot.items.first?.representations.first?.data, originalData)+ XCTAssertTrue(manager.writeTemporaryText("temporary", sessionID: "session"))+ XCTAssertTrue(manager.restore(snapshot))- XCTAssertEqual(pasteboard.changeCount, changeCount)XCTAssertEqual(pasteboard.data(forType: customType), originalData)}+ func testMoreThanOneHundredItemsAreSnapshottedAndRestored() throws {+ let pasteboard = self.makePasteboard()+ defer { pasteboard.releaseGlobally() }+ let originalItems = (0..<101).map { index in+ let item = NSPasteboardItem()+ XCTAssertTrue(item.setString("item \(index)", forType: .string))+ return item+ }+ XCTAssertTrue(pasteboard.writeObjects(originalItems))++ let manager = SystemPasteboardManager(pasteboard: pasteboard)+ let snapshot = try XCTUnwrap(manager.captureSnapshot())+ XCTAssertEqual(snapshot.items.count, 101)+ XCTAssertTrue(manager.writeTemporaryText("temporary", sessionID: "session"))+ XCTAssertTrue(manager.restore(snapshot))++ let restoredItems = try XCTUnwrap(pasteboard.pasteboardItems)+ XCTAssertEqual(restoredItems.count, 101)+ XCTAssertEqual(restoredItems.first?.string(forType: .string), "item 0")+ XCTAssertEqual(restoredItems.last?.string(forType: .string), "item 100")+ }+private func makePasteboard() -> NSPasteboard {let name = NSPasteboard.Name("com.fluidvoice.tests.transient.\(UUID().uuidString)")let pasteboard = NSPasteboard(name: name)