Repository navigation
feat(clipboard): sync Windows clipboard images to Android - #92
Conversation
Decode Deskflow DIB payloads, convert them to PNG off the input event loop, and publish them through a restricted FileProvider. Bound transfer and image sizes, retain recent images, and discard stale clipboard work across newer transfers or connection changes while preserving text sync. Add protocol, image, lifecycle, resource-aware JVM and Android device tests. Seed the installed-version fixture explicitly for resource-aware test runs.
Reviewer's GuideData structuresDefine the clipboard payload and transfer-reassembly limits, validation, and failure behavior that the receiving pipeline depends on.
APIExtend clipboard synchronization to track sessions and transfer sequences while keeping outgoing synchronization text-only.
Uses of the APIConnect incoming clipboard events and service lifecycle to asynchronous image delivery, session invalidation, and cache cleanup.
ImplementationDecode image payloads into PNG-backed clipboard items, publish them through FileProvider, and safely retain or prune cached files.
ConfigurationDeclare the restricted clipboard image provider and its cache-only shared path.
Configure shared clipboard fixtures for JVM and device tests and enable Android resources in unit tests.
Make the connection generation visible across asynchronous clipboard work.
DocumentationDocument image clipboard usage, format and size limits, Android URI behavior, and validation guidance.
TestsProvide shared DIB, clipboard-blob, and protocol-event fixtures for clipboard test suites.
Test image format parsing, chunked protocol transfers, limits, sequence handling, and text deduplication.
Test receiver conflation, stale-work invalidation, and recovery after allocation or conversion failures.
Test DIB decoding, PNG output, provider scope, and clipboard/cache lifecycle on JVM and Android.
Seed the installed-version fixture explicitly for resource-aware Robolectric tests.
Synchronize the first readiness poll before advancing the virtual timeout in the UHID test.
Tips and commandsInteracting with Sourcery
Customizing Your ExperienceAccess your dashboard to:
Getting Help
|
There was a problem hiding this comment.
Hey - I've found 4 issues
Prompt for AI Agents
Please address the comments from this code review:
## Individual Comments
### Comment 1
<location path="app/src/main/java/com/inputleaf/android/clipboard/ClipboardCodec.kt" line_range="68" />
<code_context>
expected = String(data, Charsets.US_ASCII).trim('\u0000').trim().toLongOrNull() ?: -1L
- // Oversize or unreadable transfers are skipped to the end chunk.
- buffer = if (expected in 0..maxBytes.toLong()) ByteArrayOutputStream(expected.toInt()) else null
+ buffer = if (expected in 0..maxBytes.toLong()) ByteArray(expected.toInt()) else null
}
MARK_DATA -> buffer?.let {
</code_context>
<issue_to_address>
**Large transfers stop clipboard processing**
When a server advertises a large transfer while the app has insufficient heap, or the transfer stalls before its end chunk, `ClipboardAssembler.accept` eagerly allocates the advertised buffer and retains it until an end, new start, or session reset; an `OutOfMemoryError` escapes `ClipboardReceiver.accept` on the event loop and stops clipboard processing, while an incomplete transfer pins up to 32 MiB and adds memory pressure.
Avoid allocating the full advertised buffer up front and ensure allocation failures do not escape the receiver event loop.
</issue_to_address>
### Comment 2
<location path="app/src/main/java/com/inputleaf/android/clipboard/DeviceClipboard.kt" line_range="37-40" />
<code_context>
+ content.text?.let { ClipData.newPlainText("Input Leaf", it) } ?: return
+ }
+ withContext(Dispatchers.Main) {
+ if (isCurrent()) {
+ val manager = context.getSystemService(ClipboardManager::class.java)
+ if (manager != null) {
+ manager.setPrimaryClip(clip)
+ published = true
+ onApplied()
</code_context>
<issue_to_address>
**Obsolete transfers overwrite newer clipboard content**
When a newer transfer or session reset invalidates the current revision after `isCurrent()` returns but before `setPrimaryClip`, `DeviceClipboard.apply` passes the currentness check and then publishes the stale conversion; the obsolete content overwrites the clipboard and remains there if the newer transfer does not complete.
Make the currentness check and clipboard publication atomic with respect to transfer and session invalidation.
</issue_to_address>
### Comment 3
<location path="app/src/main/java/com/inputleaf/android/clipboard/DeviceClipboard.kt" line_range="37" />
<code_context>
+ content.text?.let { ClipData.newPlainText("Input Leaf", it) } ?: return
+ }
+ withContext(Dispatchers.Main) {
+ if (isCurrent()) {
+ val manager = context.getSystemService(ClipboardManager::class.java)
+ if (manager != null) {
</code_context>
<issue_to_address>
**Local copies are overwritten by incoming content**
When the user copies new content while an incoming image is being converted, `DeviceClipboard.apply` checks only the server-update revision, which does not change for a local clipboard copy, so it publishes the older image and loses the user's newer content.
Invalidate pending applies when the local clipboard changes, or include local clipboard changes in the currentness check.
</issue_to_address>
### Comment 4
<location path="app/src/main/java/com/inputleaf/android/clipboard/ClipboardSync.kt" line_range="30" />
<code_context>
+ val blob = assembler.accept(event.mark, event.data)
+ if (event.mark == ClipboardAssembler.MARK_END) sequence = null
+ val content = blob?.let(ClipboardCodec::unmarshall) ?: return null
+ content.text?.let { lastSynced = it }
+ return content
}
</code_context>
<issue_to_address>
**Image clipboard suppresses later text**
When the server replaces synced text with an image-only clipboard and the device later copies that same text, `ClipboardSync` leaves `lastSynced` holding the previous text when received content has no text, so `onLeave` treats the device copy as already synced and does not send it while the server still owns the image.
Clear or otherwise reset `lastSynced` when received content has no text.
</issue_to_address>| if (isCurrent()) { | ||
| val manager = context.getSystemService(ClipboardManager::class.java) | ||
| if (manager != null) { | ||
| manager.setPrimaryClip(clip) |
There was a problem hiding this comment.
🟡 Medium · Obsolete transfers overwrite newer clipboard content
When a newer transfer or session reset invalidates the current revision after isCurrent() returns but before setPrimaryClip, DeviceClipboard.apply passes the currentness check and then publishes the stale conversion; the obsolete content overwrites the clipboard and remains there if the newer transfer does not complete.
Make the currentness check and clipboard publication atomic with respect to transfer and session invalidation.
Prompt for AI agents
In `app/src/main/java/com/inputleaf/android/clipboard/DeviceClipboard.kt` at lines 37-40:
**Obsolete transfers overwrite newer clipboard content**
When a newer transfer or session reset invalidates the current revision after `isCurrent()` returns but before `setPrimaryClip`, `DeviceClipboard.apply` passes the currentness check and then publishes the stale conversion; the obsolete content overwrites the clipboard and remains there if the newer transfer does not complete.
Make the currentness check and clipboard publication atomic with respect to transfer and session invalidation.| content.text?.let { ClipData.newPlainText("Input Leaf", it) } ?: return | ||
| } | ||
| withContext(Dispatchers.Main) { | ||
| if (isCurrent()) { |
There was a problem hiding this comment.
🟡 Medium · Local copies are overwritten by incoming content
When the user copies new content while an incoming image is being converted, DeviceClipboard.apply checks only the server-update revision, which does not change for a local clipboard copy, so it publishes the older image and loses the user's newer content.
Invalidate pending applies when the local clipboard changes, or include local clipboard changes in the currentness check.
Prompt for AI agents
In `app/src/main/java/com/inputleaf/android/clipboard/DeviceClipboard.kt` at line 37:
**Local copies are overwritten by incoming content**
When the user copies new content while an incoming image is being converted, `DeviceClipboard.apply` checks only the server-update revision, which does not change for a local clipboard copy, so it publishes the older image and loses the user's newer content.
Invalidate pending applies when the local clipboard changes, or include local clipboard changes in the currentness check.Run the API 33+ notification permission rule before ActivityScenarioRule so a fresh-install permission dialog cannot take foreground clipboard focus. Keep older Android versions on an empty permission rule.
Wait for the reader to observe POLLERR before advancing the test clock. An empty pipe cannot provide the existing drain-based synchronization, so CI could expire the virtual deadline before the reader's first poll. Keep the exact poll-count and timeout assertions unchanged.
Codecov Report✅ All modified and coverable lines are covered by tests. 📢 Thoughts on this report? Let us know! |
anasvhora284
left a comment
There was a problem hiding this comment.
Thanks, this is a really solid feature, and the tests and docs are great. A few things before merging:
- Text + image on the clipboard: when Windows offers both (e.g. copying cells in Excel, which also adds a bitmap),
DeviceClipboard.applypublishes only the image URI, so pasting into a text field gets nothing. Could you put both in oneClipData.Item(text, null, uri), or prefer text when it's present? - Silently rejected images:
DibImage.decoderejectscompression != 0, so 32-bit BI_BITFIELDS DIBs (common with V4/V5 headers) are dropped, as is anything over 8 MP (e.g. a dual-4K screenshot). Please accept BI_BITFIELDS with the standard BGRA masks, and log a line when an image is rejected so it's clear why nothing pasted. - Upfront allocation:
ClipboardAssemblerallocates the declared size (up to 32 MiB) on START, on the main thread, with no OOM handling there. On low-RAM phones with a previous image still converting this can crash the service. Growing the buffer as chunks arrive, or catching OOM and skipping the transfer, would avoid it.
Smaller:
reset()now clearslastSynced, so after a reconnect the server's own text can be echoed back on the first Leave. I'd keeplastSyncedacross sessions.connectGenerationis read from IO viaisCurrentGeneration; please mark it@Volatile.- Clipboard PNGs stay in
cacheDir/clipboard-imagesacross sessions. Clearing old ones on disconnect or service start would be nicer for privacy. ClipboardFixturesis duplicated intestandandroidTest; a shared source set would keep them in sync.
One more request: could you add the other direction too, Android to PC? When an image is on the phone's clipboard (root/Shizuku can read it, like the text sync does now), encode it as a 32-bit BI_RGB DIB and send it as the bitmap format on Leave, so a screenshot copied on the phone pastes on the PC. Happy for that to be in this PR or a follow-up, whichever is easier for you.
|
Thanks for the detailed review! I'll address the feedback and improve this PR. As for Android-to-PC image sync, I may work on it in a follow-up PR, depending on my availability.☕ |
No issues! take your time.
I think, I will work on Android to PC Feature in upcoming days so check if already implemented or not before starting and if you do start let me know here. And thanks a lot for your contributions to this app ✨. |
Preserve text alongside images and decode standard 32-bit BI_BITFIELDS. Handle receive-buffer allocation failures, log rejections, retain reconnect deduplication, and safely clean unused image files on service startup. Share clipboard fixtures and add regression coverage for mixed pasting, bitfield alpha, allocation recovery, server changes and cache lifecycles. Validated with 49 clipboard JVM tests, 33 Android 16 device tests, 13 Android 17 clipboard tests, and physical Windows/Android acceptance. The 12 full-suite Windows failures match the unmodified upstream baseline.
|
I've pushed the updates addressing your review feedback. Please take another look when you have time.☕ As for Android-to-PC image sync, I'll leave that to you. Looking forward to the upcoming releases!🍃 |
anasvhora284
left a comment
There was a problem hiding this comment.
Thanks! I went through the update and every point is addressed: mixed text + image clips, BI_BITFIELDS, the allocation failure, reconnect dedup, @Volatile and the shared fixtures. The full JVM suite (752 tests) passes and the build is clean on my side too. I'll take Android-to-PC images from here.
Summary
Add Windows-to-Android image clipboard synchronization over the existing Deskflow/Input Leap clipboard channel, allowing screenshots and copied images to be pasted into Android apps.
Implementation
Validation
Manual testing: Verified on a Lenovo Xiaoxin 12.7 running DerpFest Android 17 with Windows Deskflow and Shizuku. Tested screenshots, browser images, Excel text/image pasting, 4K images, repeated copies, reconnection, and service restart.
Notes
AI Assistance
Implementation and tests were developed with assistance from OpenAI Codex.