Skip to content

feat(clipboard): sync Windows clipboard images to Android - #92

Merged
anasvhora284 merged 5 commits into
anasvhora284:masterfrom
Kirara-kaka:feat/windows-image-clipboard
Nov 21, 2026
Merged

anasvhora284 merged 5 commits into
anasvhora284:masterfrom
Kirara-kaka:feat/windows-image-clipboard

Conversation

@Kirara-kaka

@Kirara-kaka Kirara-kaka commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

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

  • Support 24/32-bit BI_RGB and standard 32-bit BI_BITFIELDS DIBs, including alpha, row padding, and image orientation.
  • Publish PNG images through a private FileProvider, preserving accompanying text and temporary URI permissions.
  • Process images asynchronously, preventing stale transfers from overwriting newer clipboard content.
  • Enforce transfer and image size limits, handle allocation failures, log rejected images, and clean up unused cached files.
  • Preserve existing bidirectional text synchronization. Image synchronization remains Windows to Android only.

Validation

  • JVM tests: All 49 clipboard tests pass, including 42 new tests covering protocol parsing, image decoding, 4K transfers, malformed data, and session handling.
  • Android tests: All 13 clipboard instrumentation tests pass on Android 17 (API 37). The full Android 16 (API 36.1) suite passes all 33 tests with coverage generated.
  • Full Windows JVM suite: 752 tests (739 passed, 12 failed, 1 skipped). All 12 failures also occur on the unmodified upstream baseline.
  • Release build: R8 build, signing, alignment, and emulator installation/launch checks passed.

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

  • Supports clipboard images, not Explorer file-copy operations.
  • Large images require an appropriate Deskflow clipboard size setting. The current transfer limit is 32 MiB.
  • See the image clipboard documentation for supported formats and limitations.

AI Assistance

Implementation and tests were developed with assistance from OpenAI Codex.

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.
@sourcery-ai

sourcery-ai Bot commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

Reviewer's Guide

Data structures

Define the clipboard payload and transfer-reassembly limits, validation, and failure behavior that the receiving pipeline depends on.

  • app/src/main/java/com/inputleaf/android/clipboard/ClipboardCodec.kt L3-13, L52-68, L74-98 (+3 small edits)
  • app/src/main/java/com/inputleaf/android/clipboard/DibImage.kt L1-76

API

Extend clipboard synchronization to track sessions and transfer sequences while keeping outgoing synchronization text-only.

  • app/src/main/java/com/inputleaf/android/clipboard/ClipboardSync.kt L5-41

Uses of the API

Connect incoming clipboard events and service lifecycle to asynchronous image delivery, session invalidation, and cache cleanup.

  • app/src/main/java/com/inputleaf/android/clipboard/ClipboardReceiver.kt L1-63
  • app/src/main/java/com/inputleaf/android/service/ConnectionService.kt L71-84, L122-130 (+7 small edits)

Implementation

Decode image payloads into PNG-backed clipboard items, publish them through FileProvider, and safely retain or prune cached files.

  • app/src/main/java/com/inputleaf/android/clipboard/ClipboardImageProvider.kt L1-6
  • app/src/main/java/com/inputleaf/android/clipboard/DeviceClipboard.kt L1-118

Configuration

Declare the restricted clipboard image provider and its cache-only shared path.

  • app/src/main/AndroidManifest.xml L90-100
  • app/src/main/res/xml/clipboard_paths.xml L1-4

Configure shared clipboard fixtures for JVM and device tests and enable Android resources in unit tests.

  • app/build.gradle.kts L60-69

Make the connection generation visible across asynchronous clipboard work.

  • app/src/main/java/com/inputleaf/android/service/ConnectionCoordinator.kt L52

Documentation

Document image clipboard usage, format and size limits, Android URI behavior, and validation guidance.

  • docs/image-clipboard.md L1-37

Tests

Provide shared DIB, clipboard-blob, and protocol-event fixtures for clipboard test suites.

  • app/src/sharedTest/java/com/inputleaf/android/clipboard/ClipboardFixtures.kt L1-50

Test image format parsing, chunked protocol transfers, limits, sequence handling, and text deduplication.

  • app/src/test/java/com/inputleaf/android/clipboard/ClipboardImageSyncTest.kt L1-118
  • app/src/test/java/com/inputleaf/android/clipboard/ClipboardSyncTest.kt L113-145, L150

Test receiver conflation, stale-work invalidation, and recovery after allocation or conversion failures.

  • app/src/test/java/com/inputleaf/android/clipboard/ClipboardReceiverTest.kt L1-109

Test DIB decoding, PNG output, provider scope, and clipboard/cache lifecycle on JVM and Android.

  • app/src/androidTest/java/com/inputleaf/android/clipboard/DeviceClipboardDeviceTest.kt L1-282
  • app/src/test/java/com/inputleaf/android/clipboard/DeviceClipboardTest.kt L1-157
  • app/src/test/java/com/inputleaf/android/clipboard/DibImageTest.kt L1-142

Seed the installed-version fixture explicitly for resource-aware Robolectric tests.

  • app/src/test/java/com/inputleaf/android/update/UpdateServiceContextJvmTest.kt L18, L29-32

Synchronize the first readiness poll before advancing the virtual timeout in the UHID test.

  • app/src/test/java/com/inputleaf/android/shizuku/uhid/UhidChannelReadinessTest.kt L302-308 (+4 small edits)

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨

Comment on lines +37 to +40
if (isCurrent()) {
val manager = context.getSystemService(ClipboardManager::class.java)
if (manager != null) {
manager.setPrimaryClip(clip)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 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()) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 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

codecov Bot commented Nov 20, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

@anasvhora284 anasvhora284 left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, this is a really solid feature, and the tests and docs are great. A few things before merging:

  1. Text + image on the clipboard: when Windows offers both (e.g. copying cells in Excel, which also adds a bitmap), DeviceClipboard.apply publishes only the image URI, so pasting into a text field gets nothing. Could you put both in one ClipData.Item(text, null, uri), or prefer text when it's present?
  2. Silently rejected images: DibImage.decode rejects compression != 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.
  3. Upfront allocation: ClipboardAssembler allocates 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 clears lastSynced, so after a reconnect the server's own text can be echoed back on the first Leave. I'd keep lastSynced across sessions.
  • connectGeneration is read from IO via isCurrentGeneration; please mark it @Volatile.
  • Clipboard PNGs stay in cacheDir/clipboard-images across sessions. Clearing old ones on disconnect or service start would be nicer for privacy.
  • ClipboardFixtures is duplicated in test and androidTest; 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.

@Kirara-kaka

Copy link
Copy Markdown
Contributor Author

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.☕

@anasvhora284

Copy link
Copy Markdown
Owner

Thanks for the detailed review! I'll address the feedback and improve this PR.

No issues! take your time.

As for Android-to-PC image sync, I may work on it in a follow-up PR, depending on my availability.☕

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 ✨.
Much appreciated 👍.

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.
@Kirara-kaka

Copy link
Copy Markdown
Contributor Author

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 anasvhora284 left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@anasvhora284
anasvhora284 merged commit 68b594e into anasvhora284:master Nov 21, 2026
5 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants