Skip to content

Your Android phone and your Windows PC, working as one. Local-first, end-to-end encrypted, no account.

Share the clipboard between PC and phone

Bee351fa06f8d1f
diff --git a/README.md b/README.md
index 7bd33a2..ab375ca 100644
--- a/README.md
+++ b/README.md
@@ -74,6 +74,10 @@ place and tested; the user-facing features of Phase 1 come next.
a feed in the app, with the app's icon. Reply inline, run their actions
(such as "Mark as read") or dismiss them from the PC; what's cleared on one
side is cleared on the other.
+- **Clipboard**: text you copy on the PC is ready to paste on the phone. From
+ the phone, send it with the Quick Settings tile, the share sheet or a button
+ in the app (Android lets only the app in front read the clipboard).
+ Passwords that password managers mark private are never sent.
- **Capability matrix**: both apps compute which features work for a pair of
devices and what would enable the rest, so the interface never offers
something that can't work.
@@ -85,8 +89,8 @@ place and tested; the user-facing features of Phase 1 come next.
connection service, and an identity key protected by the Android Keystore.
- **Command-line client** for development and testing (`nectarlink`).
-**Next (Phase 1)**: clipboard, file transfer, media controls, notification
-filters and history, and a Windows installer. Mirroring, messages, calls and the other
+**Next (Phase 1)**: file transfer (and images on the clipboard), media
+controls, notification filters and history, and a Windows installer. Mirroring, messages, calls and the other
features in the plan follow in later phases.
## Screenshots
diff --git a/android/README.md b/android/README.md
index b71b438..ed13d83 100644
--- a/android/README.md
+++ b/android/README.md
@@ -38,6 +38,10 @@ sources; nothing generated is checked in except the theme tokens
access) that hands notifications to the core for mirroring, and reads them
(messaging-style content, actions, app icons); replies and actions from a
PC run through `core/PhonePlatform`.
+- `clipboard/`: sending text to the PC (share sheet, Quick Settings tile,
+ the connection notification's button) through `SendActivity`, which reads
+ the clipboard once it has focus, as Android requires; and writing text a
+ PC sent.
- `service/ConnectionService`: a "connected device" foreground service that
keeps the phone reachable and holds the Wi-Fi multicast lock local
discovery needs.
diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml
index 96ef446..d577139 100644
--- a/android/app/src/main/AndroidManifest.xml
+++ b/android/app/src/main/AndroidManifest.xml
@@ -59,6 +59,35 @@
</intent-filter>
</activity>
+ <!-- Sending text to the PC: shared from other apps, or the clipboard
+ (from the tile and the connection notification). No screen of
+ its own. -->
+ <activity
+ android:name=".clipboard.SendActivity"
+ android:exported="true"
+ android:excludeFromRecents="true"
+ android:label="@string/clip_share_label"
+ android:noHistory="true"
+ android:taskAffinity=""
+ android:theme="@android:style/Theme.Translucent.NoTitleBar">
+ <intent-filter>
+ <action android:name="android.intent.action.SEND" />
+ <category android:name="android.intent.category.DEFAULT" />
+ <data android:mimeType="text/plain" />
+ </intent-filter>
+ </activity>
+
+ <service
+ android:name=".clipboard.ClipboardTileService"
+ android:exported="true"
+ android:icon="@drawable/ic_clipboard"
+ android:label="@string/clip_tile_label"
+ android:permission="android.permission.BIND_QUICK_SETTINGS_TILE">
+ <intent-filter>
+ <action android:name="android.service.quicksettings.action.QS_TILE" />
+ </intent-filter>
+ </service>
+
<!-- Mirroring notifications to PCs; the user grants access in Settings. -->
<service
android:name=".notifications.NotificationListener"
diff --git a/android/app/src/main/kotlin/app/nectarlink/android/clipboard/ClipboardTileService.kt b/android/app/src/main/kotlin/app/nectarlink/android/clipboard/ClipboardTileService.kt
new file mode 100644
index 0000000..4f1c766
--- /dev/null
+++ b/android/app/src/main/kotlin/app/nectarlink/android/clipboard/ClipboardTileService.kt
@@ -0,0 +1,24 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+package app.nectarlink.android.clipboard
+
+import android.annotation.SuppressLint
+import android.app.PendingIntent
+import android.os.Build
+import android.service.quicksettings.TileService
+
+/** The "Send clipboard" Quick Settings tile. */
+class ClipboardTileService : TileService() {
+ @SuppressLint("StartActivityAndCollapseDeprecated") // The Intent overload is the only one before Android 14.
+ override fun onClick() {
+ super.onClick()
+ val intent = SendActivity.sendClipboardIntent(this)
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
+ startActivityAndCollapse(
+ PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT),
+ )
+ } else {
+ @Suppress("DEPRECATION")
+ startActivityAndCollapse(intent)
+ }
+ }
+}
diff --git a/android/app/src/main/kotlin/app/nectarlink/android/clipboard/PhoneClipboard.kt b/android/app/src/main/kotlin/app/nectarlink/android/clipboard/PhoneClipboard.kt
new file mode 100644
index 0000000..ad69fe9
--- /dev/null
+++ b/android/app/src/main/kotlin/app/nectarlink/android/clipboard/PhoneClipboard.kt
@@ -0,0 +1,45 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+package app.nectarlink.android.clipboard
+
+import android.content.ClipData
+import android.content.ClipDescription
+import android.content.ClipboardManager
+import android.content.Context
+import android.os.Build
+
+/**
+ * The phone's clipboard. Android lets an app read it only while that app
+ * is in front (and focused); writing works any time.
+ */
+object PhoneClipboard {
+ sealed interface Read {
+ data class Text(val text: String) : Read
+ /** Marked sensitive by the app it came from (a password manager): never sent. */
+ data object Private : Read
+ data object Empty : Read
+ }
+
+ fun read(context: Context): Read {
+ val clip = manager(context)?.primaryClip ?: return Read.Empty
+ if (clip.description.isSensitive()) return Read.Private
+ val text = (0 until clip.itemCount)
+ .firstNotNullOfOrNull { clip.getItemAt(it).coerceToText(context)?.toString()?.takeIf(String::isNotBlank) }
+ return text?.let { Read.Text(it) } ?: Read.Empty
+ }
+
+ /** Puts text a PC sent on the clipboard. */
+ fun write(context: Context, text: String): Boolean =
+ runCatching { manager(context)?.setPrimaryClip(ClipData.newPlainText("Nectarlink", text)) != null }
+ .getOrDefault(false)
+
+ private fun manager(context: Context) = context.getSystemService(ClipboardManager::class.java)
+
+ private fun ClipDescription.isSensitive(): Boolean {
+ val key = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
+ ClipDescription.EXTRA_IS_SENSITIVE
+ } else {
+ "android.content.extra.IS_SENSITIVE"
+ }
+ return extras?.getBoolean(key) == true
+ }
+}
diff --git a/android/app/src/main/kotlin/app/nectarlink/android/clipboard/SendActivity.kt b/android/app/src/main/kotlin/app/nectarlink/android/clipboard/SendActivity.kt
new file mode 100644
index 0000000..f61ae27
--- /dev/null
+++ b/android/app/src/main/kotlin/app/nectarlink/android/clipboard/SendActivity.kt
@@ -0,0 +1,71 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+package app.nectarlink.android.clipboard
+
+import android.app.Activity
+import android.content.Context
+import android.content.Intent
+import android.os.Bundle
+import android.widget.Toast
+import app.nectarlink.android.NectarlinkApplication
+import app.nectarlink.android.R
+import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.SupervisorJob
+import kotlinx.coroutines.cancel
+import kotlinx.coroutines.launch
+
+/**
+ * Sends text to the connected PCs, without a screen of its own: text shared
+ * from another app, or the clipboard (from the Quick Settings tile or the
+ * connection notification). Android lets only the focused app read the
+ * clipboard, which is why this is an activity: it reads once it has focus.
+ */
+class SendActivity : Activity() {
+ private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main)
+ private var sent = false
+
+ override fun onCreate(savedInstanceState: Bundle?) {
+ super.onCreate(savedInstanceState)
+ if (intent?.action == Intent.ACTION_SEND) {
+ val text = intent.getCharSequenceExtra(Intent.EXTRA_TEXT)?.toString()
+ if (text.isNullOrBlank()) finishWith(getString(R.string.clip_nothing_shared)) else send(text)
+ }
+ // The clipboard is read in onWindowFocusChanged.
+ }
+
+ override fun onWindowFocusChanged(hasFocus: Boolean) {
+ super.onWindowFocusChanged(hasFocus)
+ if (!hasFocus || sent || intent?.action != ACTION_SEND_CLIPBOARD) return
+ when (val clip = PhoneClipboard.read(this)) {
+ is PhoneClipboard.Read.Text -> send(clip.text)
+ PhoneClipboard.Read.Private -> finishWith(getString(R.string.clip_private))
+ PhoneClipboard.Read.Empty -> finishWith(getString(R.string.clip_empty))
+ }
+ }
+
+ private fun send(text: String) {
+ sent = true
+ val core = (application as NectarlinkApplication).core
+ scope.launch { finishWith(core.sendClipboard(text)) }
+ }
+
+ private fun finishWith(message: String) {
+ sent = true
+ Toast.makeText(applicationContext, message, Toast.LENGTH_SHORT).show()
+ finish()
+ }
+
+ override fun onDestroy() {
+ scope.cancel()
+ super.onDestroy()
+ }
+
+ companion object {
+ const val ACTION_SEND_CLIPBOARD = "app.nectarlink.action.SEND_CLIPBOARD"
+
+ fun sendClipboardIntent(context: Context): Intent =
+ Intent(context, SendActivity::class.java)
+ .setAction(ACTION_SEND_CLIPBOARD)
+ .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_NO_ANIMATION)
+ }
+}
diff --git a/android/app/src/main/kotlin/app/nectarlink/android/core/Core.kt b/android/app/src/main/kotlin/app/nectarlink/android/core/Core.kt
index 5139589..a603faf 100644
--- a/android/app/src/main/kotlin/app/nectarlink/android/core/Core.kt
+++ b/android/app/src/main/kotlin/app/nectarlink/android/core/Core.kt
@@ -6,6 +6,7 @@ import android.net.wifi.WifiManager
import android.service.notification.NotificationListenerService
import android.util.Log
import app.nectarlink.android.BuildConfig
+import app.nectarlink.android.R
import app.nectarlink.android.notifications.NotificationListener
import app.nectarlink.core.Event
import app.nectarlink.core.EventListener
@@ -100,6 +101,7 @@ class Core(context: Context, private val scope: CoroutineScope) : EventListener
battery.start()
network.start()
}
+ started.updatePower(PowerLevel.BASIC, capabilities(NotificationListener.hasAccess(context)))
scope.launch {
for (op in notificationOps) {
runCatching { op(started) }.onFailure { Log.w(TAG, "notification update failed", it) }
@@ -117,7 +119,7 @@ class Core(context: Context, private val scope: CoroutineScope) : EventListener
fun notificationAccessChanged(granted: Boolean, showing: List<Notification>) {
_state.update { it.copy(notificationAccess = granted) }
notificationOps.trySend { node ->
- node.updatePower(PowerLevel.BASIC, if (granted) NOTIFICATION_CAPABILITIES else emptyList())
+ node.updatePower(PowerLevel.BASIC, capabilities(granted))
node.notificationsReset(showing)
}
}
@@ -148,6 +150,38 @@ class Core(context: Context, private val scope: CoroutineScope) : EventListener
_state.update { it.reduce(event) }
}
+ // ---- Clipboard ----
+
+ /**
+ * Sends text to every connected PC; returns what to tell the user.
+ * Waits for the core when the app was just launched to send.
+ */
+ suspend fun sendClipboard(text: String): String {
+ startJob?.join()
+ val node = node ?: return context.getString(R.string.clip_no_pc)
+ val pcs = _state.value.devices.filter { it.online }
+ if (pcs.isEmpty()) return context.getString(R.string.clip_no_pc)
+ val sentTo = mutableListOf<String>()
+ var failure: String? = null
+ for (pc in pcs) {
+ try {
+ node.sendClipboard(pc.id, text)
+ sentTo += pc.name
+ } catch (e: NectarlinkException) {
+ failure = when (e) {
+ is NectarlinkException.Denied -> context.getString(R.string.clip_off_for, pc.name)
+ is NectarlinkException.TooLarge -> context.getString(R.string.clip_too_large)
+ else -> describe(e)
+ }
+ }
+ }
+ return if (sentTo.isNotEmpty()) context.getString(R.string.clip_sent_to, sentTo.joinToString()) else failure.orEmpty()
+ }
+
+ /** What this phone offers PCs (docs/protocol/capabilities.md). */
+ private fun capabilities(notificationAccess: Boolean): List<String> =
+ CLIPBOARD_CAPABILITIES + if (notificationAccess) NOTIFICATION_CAPABILITIES else emptyList()
+
// ---- Pairing ----
/**
@@ -245,5 +279,7 @@ class Core(context: Context, private val scope: CoroutineScope) : EventListener
const val TAG = "Nectarlink"
/** Offered while notification access is granted (docs/protocol/capabilities.md). */
val NOTIFICATION_CAPABILITIES = listOf("notify.mirror", "notify.reply")
+ /** Accepting the PC's clipboard, and sending this one when asked. */
+ val CLIPBOARD_CAPABILITIES = listOf("clip.write", "clip.share")
}
}
diff --git a/android/app/src/main/kotlin/app/nectarlink/android/core/CoreState.kt b/android/app/src/main/kotlin/app/nectarlink/android/core/CoreState.kt
index 36a9ab3..bc400a8 100644
--- a/android/app/src/main/kotlin/app/nectarlink/android/core/CoreState.kt
+++ b/android/app/src/main/kotlin/app/nectarlink/android/core/CoreState.kt
@@ -96,6 +96,8 @@ data class CoreState(
if (pairing == PairingState.Idle) this else copy(pairing = PairingState.Failed(event.failure))
// PCs don't send notifications; nothing for the phone to show.
is Event.NotificationsReset, is Event.NotificationPosted, is Event.NotificationRemoved -> this
+ // Android shows its own "copied" confirmation.
+ is Event.ClipboardReceived -> this
}
private fun update(id: String, change: (Device) -> Device): CoreState =
diff --git a/android/app/src/main/kotlin/app/nectarlink/android/core/PhonePlatform.kt b/android/app/src/main/kotlin/app/nectarlink/android/core/PhonePlatform.kt
index 055e111..89664cd 100644
--- a/android/app/src/main/kotlin/app/nectarlink/android/core/PhonePlatform.kt
+++ b/android/app/src/main/kotlin/app/nectarlink/android/core/PhonePlatform.kt
@@ -8,6 +8,7 @@ import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.Bundle
+import app.nectarlink.android.clipboard.PhoneClipboard
import app.nectarlink.android.notifications.NotificationListener
import app.nectarlink.core.NotificationFailure
import app.nectarlink.core.Platform
@@ -23,6 +24,8 @@ internal class PhonePlatform(context: Context, private val ringer: Ringer) : Pla
override fun stopRinging() = ringer.stopRinging()
+ override fun setClipboard(text: String): Boolean = PhoneClipboard.write(context, text)
+
override fun dismissNotification(key: String) {
val listener = NotificationListener.instance ?: throw NotificationFailure.Unsupported()
listener.dismiss(key)
diff --git a/android/app/src/main/kotlin/app/nectarlink/android/service/ConnectionService.kt b/android/app/src/main/kotlin/app/nectarlink/android/service/ConnectionService.kt
index af6b4c6..27c8162 100644
--- a/android/app/src/main/kotlin/app/nectarlink/android/service/ConnectionService.kt
+++ b/android/app/src/main/kotlin/app/nectarlink/android/service/ConnectionService.kt
@@ -17,6 +17,7 @@ import androidx.lifecycle.LifecycleService
import androidx.lifecycle.lifecycleScope
import app.nectarlink.android.NectarlinkApplication
import app.nectarlink.android.R
+import app.nectarlink.android.clipboard.SendActivity
import app.nectarlink.android.core.CoreState
import app.nectarlink.android.ui.MainActivity
import kotlinx.coroutines.flow.distinctUntilChanged
@@ -91,7 +92,7 @@ class ConnectionService : LifecycleService() {
status.paired == 0 -> getString(R.string.notification_not_paired)
else -> getString(R.string.notification_waiting)
}
- return NotificationCompat.Builder(this, CHANNEL_CONNECTION)
+ val builder = NotificationCompat.Builder(this, CHANNEL_CONNECTION)
.setSmallIcon(R.drawable.ic_notification)
.setContentTitle(text)
.setContentIntent(openApp())
@@ -99,7 +100,13 @@ class ConnectionService : LifecycleService() {
.setSilent(true)
.setCategory(NotificationCompat.CATEGORY_SERVICE)
.setForegroundServiceBehavior(NotificationCompat.FOREGROUND_SERVICE_IMMEDIATE)
- .build()
+ if (status.connected.isNotEmpty()) {
+ val send = PendingIntent.getActivity(
+ this, 2, SendActivity.sendClipboardIntent(this), PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT,
+ )
+ builder.addAction(0, getString(R.string.action_send_clipboard), send)
+ }
+ return builder.build()
}
private fun ringingNotification(from: String): Notification {
diff --git a/android/app/src/main/kotlin/app/nectarlink/android/ui/home/HomeScreen.kt b/android/app/src/main/kotlin/app/nectarlink/android/ui/home/HomeScreen.kt
index caba277..7e4f72a 100644
--- a/android/app/src/main/kotlin/app/nectarlink/android/ui/home/HomeScreen.kt
+++ b/android/app/src/main/kotlin/app/nectarlink/android/ui/home/HomeScreen.kt
@@ -35,6 +35,7 @@ import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import app.nectarlink.android.R
+import app.nectarlink.android.clipboard.SendActivity
import app.nectarlink.android.core.BackgroundAccess
import app.nectarlink.android.core.CoreState
import app.nectarlink.android.core.Device
@@ -164,14 +165,23 @@ private fun PcCard(device: Device, onRing: (String, Boolean) -> Unit) {
)
}
Spacer(Modifier.height(20.dp))
- Button(
- enabled = device.online,
- onClick = {
- ringing = !ringing
- onRing(device.id, ringing)
- },
- ) {
- Text(stringResource(if (ringing) R.string.action_stop_ringing else R.string.action_ring_pc))
+ val context = LocalContext.current
+ Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
+ Button(
+ enabled = device.online,
+ onClick = {
+ ringing = !ringing
+ onRing(device.id, ringing)
+ },
+ ) {
+ Text(stringResource(if (ringing) R.string.action_stop_ringing else R.string.action_ring_pc))
+ }
+ FilledTonalButton(
+ enabled = device.online,
+ onClick = { context.startActivity(SendActivity.sendClipboardIntent(context)) },
+ ) {
+ Text(stringResource(R.string.action_send_clipboard))
+ }
}
}
}
diff --git a/android/app/src/main/res/drawable/ic_clipboard.xml b/android/app/src/main/res/drawable/ic_clipboard.xml
new file mode 100644
index 0000000..100f7ee
--- /dev/null
+++ b/android/app/src/main/res/drawable/ic_clipboard.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- SPDX-License-Identifier: GPL-3.0-or-later -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="24" android:viewportHeight="24">
+ <path android:pathData="M9,3h6v4H9zM16,5h2a2,2 0,0 1,2,2v12a2,2 0,0 1,-2,2H6a2,2 0,0 1,-2,-2V7a2,2 0,0 1,2,-2h2"
+ android:strokeColor="#FF000000" android:strokeWidth="1.8" android:strokeLineCap="round"
+ android:strokeLineJoin="round" android:fillColor="#00000000" />
+</vector>
diff --git a/android/app/src/main/res/values/strings.xml b/android/app/src/main/res/values/strings.xml
index 21395ee..7110370 100644
--- a/android/app/src/main/res/values/strings.xml
+++ b/android/app/src/main/res/values/strings.xml
@@ -56,6 +56,16 @@
<string name="notifications_off">Nectarlink needs notification access to show this phone’s notifications on your PC.</string>
<string name="notifications_restricted">Switch greyed out? Open App info, tap ⋮, choose “Allow restricted settings”, then try again.</string>
<string name="action_allow">Allow</string>
+ <string name="clip_share_label">Send to PC</string>
+ <string name="clip_tile_label">Send clipboard</string>
+ <string name="action_send_clipboard">Send clipboard</string>
+ <string name="clip_sent_to">Sent to %1$s</string>
+ <string name="clip_no_pc">No PC is connected right now.</string>
+ <string name="clip_off_for">The clipboard is turned off for %1$s.</string>
+ <string name="clip_too_large">That’s too much text to send at once.</string>
+ <string name="clip_private">What you copied is marked private by its app, so it wasn’t sent.</string>
+ <string name="clip_empty">There’s no text on the clipboard.</string>
+ <string name="clip_nothing_shared">There’s no text to send.</string>
<string name="background_title">Stay reachable in the background</string>
<string name="background_text">Your phone pauses Nectarlink to save battery, so your PC can’t reach it, and replies and dismissals from the PC time out. Let it run in the background.</string>
<string name="action_manage">Manage</string>
diff --git a/core/nectarlink-cli/src/main.rs b/core/nectarlink-cli/src/main.rs
index 1fe6ff9..62bde94 100644
--- a/core/nectarlink-cli/src/main.rs
+++ b/core/nectarlink-cli/src/main.rs
@@ -111,6 +111,8 @@ enum Command {
},
/// Stay online and print events until Ctrl+C.
Run,
+ /// Put text on a paired device's clipboard.
+ Clip { device: String, text: String },
/// Dismiss a phone's notification (`run` prints the keys).
Dismiss { device: String, key: String },
/// Run an action of a phone's notification, or reply to it.
@@ -164,6 +166,10 @@ impl Platform for TerminalPlatform {
fn stop_ringing(&self) {
println!("🔕 Stopped ringing.");
}
+ fn set_clipboard(&self, text: &str) -> Result<(), String> {
+ println!("Clipboard from a paired device: {text}");
+ Ok(())
+ }
fn dismiss_notification(&self, key: &str) -> Result<(), NotificationError> {
println!("The PC dismissed {key}");
Ok(())
@@ -278,6 +284,12 @@ async fn run(cli: &Cli, node: &Node) -> Result<()> {
node.ring(id, !off).await.context("ring failed")?;
println!("{}", if *off { "Stopped ringing." } else { "Ringing…" });
}
+ Command::Clip { device, text } => {
+ let id = resolve(node, device)?;
+ wait_until_online(node, id).await?;
+ node.send_clipboard(id, text.clone()).await.context("clipboard failed")?;
+ println!("Sent.");
+ }
Command::Dismiss { device, key } => {
let id = resolve(node, device)?;
wait_until_online(node, id).await?;
diff --git a/core/nectarlink-core/src/clipboard.rs b/core/nectarlink-core/src/clipboard.rs
new file mode 100644
index 0000000..85cf8a6
--- /dev/null
+++ b/core/nectarlink-core/src/clipboard.rs
@@ -0,0 +1,50 @@
+// SPDX-License-Identifier: MPL-2.0
+//! The clipboard service (docs/protocol/clipboard.md): copied text sent to
+//! a paired device, which puts it on its own clipboard.
+
+use std::sync::Arc;
+
+use nectarlink_protocol::{
+ Envelope, ErrorCode,
+ messages::{ClipSet, types},
+};
+
+use crate::{Result, events::NodeEvent, node::Shared, session::Session};
+
+/// The device toggle that allows the clipboard for a device.
+pub(crate) const TOGGLE: &str = "clipboard";
+
+/// Handles `clip.set`. Returns false for other message types.
+pub(crate) async fn handle(shared: &Arc<Shared>, session: &Arc<Session>, env: &Envelope) -> Result<bool> {
+ if env.t != types::CLIP_SET {
+ return Ok(false);
+ }
+ let peer = session.peer;
+ let reply = if !shared.toggle_on(&peer, TOGGLE) {
+ Envelope::error(ErrorCode::Denied, "the clipboard is off for this device")
+ } else {
+ match env.body::<ClipSet>() {
+ Ok(clip) if clip.is_valid() => {
+ let platform = shared.platform.clone();
+ let written = tokio::task::spawn_blocking(move || platform.set_clipboard(&clip.text)).await;
+ match written {
+ Ok(Ok(())) => {
+ shared.emit(NodeEvent::ClipboardReceived { device: peer });
+ Envelope::empty(types::OK)
+ }
+ Ok(Err(reason)) => {
+ tracing::warn!(reason, "can't write the clipboard");
+ Envelope::error(ErrorCode::Internal, "can't write the clipboard")
+ }
+ Err(e) => {
+ tracing::warn!(error = %e, "clipboard writer failed");
+ Envelope::error(ErrorCode::Internal, "can't write the clipboard")
+ }
+ }
+ }
+ _ => Envelope::error(ErrorCode::BadMessage, "clipboard text is empty or too large"),
+ }
+ };
+ session.send(reply.reply_to(env.id)).await?;
+ Ok(true)
+}
diff --git a/core/nectarlink-core/src/config.rs b/core/nectarlink-core/src/config.rs
index a0744da..2516b66 100644
--- a/core/nectarlink-core/src/config.rs
+++ b/core/nectarlink-core/src/config.rs
@@ -82,6 +82,12 @@ pub trait Platform: Send + Sync + 'static {
) -> Result<(), NotificationError> {
Err(NotificationError::Unsupported)
}
+
+ /// Put text on this device's clipboard (a paired device sent it).
+ /// `Err` holds a reason for logs, never the text.
+ fn set_clipboard(&self, _text: &str) -> Result<(), String> {
+ Err("this device has no clipboard".into())
+ }
}
/// A platform that does nothing; useful for tests and headless tools.
diff --git a/core/nectarlink-core/src/error.rs b/core/nectarlink-core/src/error.rs
index a76c41b..a0327a3 100644
--- a/core/nectarlink-core/src/error.rs
+++ b/core/nectarlink-core/src/error.rs
@@ -28,6 +28,8 @@ pub enum Error {
Unsupported,
#[error("it no longer exists")]
NotFound,
+ #[error("too large to send")]
+ TooLarge,
#[error("no pairing in progress")]
NotPairing,
#[error("invalid pairing link: {0}")]
diff --git a/core/nectarlink-core/src/events.rs b/core/nectarlink-core/src/events.rs
index 3deda90..ceb3983 100644
--- a/core/nectarlink-core/src/events.rs
+++ b/core/nectarlink-core/src/events.rs
@@ -115,4 +115,8 @@ pub enum NodeEvent {
device: DeviceId,
key: String,
},
+ /// A device put text on this device's clipboard.
+ ClipboardReceived {
+ device: DeviceId,
+ },
}
diff --git a/core/nectarlink-core/src/lib.rs b/core/nectarlink-core/src/lib.rs
index 910a8f8..32a065d 100644
--- a/core/nectarlink-core/src/lib.rs
+++ b/core/nectarlink-core/src/lib.rs
@@ -6,6 +6,7 @@
//! changes is reported as a [`NodeEvent`]. See
//! `docs/architecture/core-api.md` for the design.
+mod clipboard;
mod config;
mod error;
mod events;
@@ -26,7 +27,9 @@ pub use features::{CapabilityMatrix, FeatureState};
pub use identity::{KeyProtector, PlainKeyProtector, default_protector};
pub use nectarlink_protocol::{
DeviceId,
- messages::{Battery, DeviceInfo, DeviceKind, Notification, NotificationAction, PowerLevel},
+ messages::{
+ Battery, CLIP_MAX_BYTES, DeviceInfo, DeviceKind, Notification, NotificationAction, PowerLevel,
+ },
pairing::PairingUri,
};
pub use node::Node;
diff --git a/core/nectarlink-core/src/node.rs b/core/nectarlink-core/src/node.rs
index 08ecb4d..7cdc382 100644
--- a/core/nectarlink-core/src/node.rs
+++ b/core/nectarlink-core/src/node.rs
@@ -20,7 +20,8 @@ use iroh_mdns_address_lookup::{DiscoveryEvent, MdnsAddressLookup};
use nectarlink_protocol::{
ALPN_PAIR, ALPN_SESSION, DeviceId, Envelope, ErrorCode,
messages::{
- Battery, DeviceInfo, HelloUpdate, Notification, NotifyAction, NotifyKey, PowerLevel, Ring, types,
+ Battery, ClipSet, DeviceInfo, HelloUpdate, Notification, NotifyAction, NotifyKey, PowerLevel, Ring,
+ types,
},
pairing::PairingUri,
};
@@ -125,6 +126,17 @@ impl Shared {
lock(&self.sessions).values().filter(|s| s.is_alive()).cloned().collect()
}
+ /// Whether a device toggle (see [`features::DEVICE_TOGGLES`]) is on for
+ /// `peer`; unknown toggles are off.
+ pub fn toggle_on(&self, peer: &DeviceId, toggle: &str) -> bool {
+ self.store
+ .toggles(peer)
+ .ok()
+ .and_then(|t| t.get(toggle).copied())
+ .or_else(|| features::toggle_default(toggle))
+ .unwrap_or(false)
+ }
+
/// The capabilities this device offers right now.
pub fn local_capabilities(&self) -> Vec<String> {
self.local.read().unwrap_or_else(|e| e.into_inner()).capabilities()
@@ -774,6 +786,27 @@ impl Node {
}
}
+ // ---- Clipboard (docs/protocol/clipboard.md) ----
+
+ /// Puts text on a paired device's clipboard. Fails with
+ /// [`Error::Denied`] when the user turned the clipboard off for that
+ /// device (here or there), and [`Error::TooLarge`] beyond
+ /// [`crate::CLIP_MAX_BYTES`].
+ pub async fn send_clipboard(&self, peer: DeviceId, text: String) -> Result<()> {
+ if text.is_empty() {
+ return Ok(());
+ }
+ if text.len() > nectarlink_protocol::messages::CLIP_MAX_BYTES {
+ return Err(Error::TooLarge);
+ }
+ if !self.shared.toggle_on(&peer, crate::clipboard::TOGGLE) {
+ return Err(Error::Denied);
+ }
+ let env = Envelope::new(types::CLIP_SET, &ClipSet { text })?;
+ self.request(peer, env).await?.expect(types::OK)?;
+ Ok(())
+ }
+
// ---- Notifications (docs/protocol/notifications.md) ----
/// A notification appeared or changed on this phone; sent to every
diff --git a/core/nectarlink-core/src/notifications.rs b/core/nectarlink-core/src/notifications.rs
index 6be203e..fd40171 100644
--- a/core/nectarlink-core/src/notifications.rs
+++ b/core/nectarlink-core/src/notifications.rs
@@ -152,12 +152,7 @@ fn approx_size(n: &Notification) -> usize {
impl Shared {
/// Whether the user allows notifications for `peer` on this device.
pub(crate) fn notifications_allowed(&self, peer: &DeviceId) -> bool {
- self.store
- .toggles(peer)
- .ok()
- .and_then(|t| t.get(TOGGLE).copied())
- .or_else(|| crate::features::toggle_default(TOGGLE))
- .unwrap_or(false)
+ self.toggle_on(peer, TOGGLE)
}
/// Sessions that should get this phone's notifications: connected PCs
@@ -169,7 +164,7 @@ impl Shared {
.collect()
}
- fn is_desktop(&self, peer: &DeviceId) -> bool {
+ pub(crate) fn is_desktop(&self, peer: &DeviceId) -> bool {
self.store.get_peer(peer).ok().flatten().is_some_and(|p| role_of(&p.info) == Some(Role::Desktop))
}
diff --git a/core/nectarlink-core/src/session.rs b/core/nectarlink-core/src/session.rs
index 94aae59..03539f0 100644
--- a/core/nectarlink-core/src/session.rs
+++ b/core/nectarlink-core/src/session.rs
@@ -338,6 +338,7 @@ async fn handle(shared: &Arc<Shared>, session: &Arc<Session>, env: Envelope) ->
shared.forget_peer(&peer).await?;
}
t if t.starts_with("notify.") && crate::notifications::handle(shared, session, &env).await? => {}
+ t if t.starts_with("clip.") && crate::clipboard::handle(shared, session, &env).await? => {}
other => {
if env.id.is_some() {
let reply = Envelope::error(ErrorCode::Unsupported, format!("unknown message type {other}"));
diff --git a/core/nectarlink-core/tests/two_devices.rs b/core/nectarlink-core/tests/two_devices.rs
index 539d6d1..695e7f8 100644
--- a/core/nectarlink-core/tests/two_devices.rs
+++ b/core/nectarlink-core/tests/two_devices.rs
@@ -24,6 +24,7 @@ struct RecordingPlatform {
rings: Mutex<Vec<bool>>,
dismissed: Mutex<Vec<String>>,
actions: Mutex<Vec<(String, String, Option<String>)>>,
+ clipboard: Mutex<Vec<String>>,
}
impl Platform for RecordingPlatform {
@@ -49,6 +50,10 @@ impl Platform for RecordingPlatform {
self.actions.lock().unwrap().push((key.to_owned(), action.to_owned(), reply.map(str::to_owned)));
Ok(())
}
+ fn set_clipboard(&self, text: &str) -> Result<(), String> {
+ self.clipboard.lock().unwrap().push(text.to_owned());
+ Ok(())
+ }
}
struct TestDevice {
@@ -531,3 +536,36 @@ async fn notification_toggles_are_honored_on_both_devices() {
pc.node.set_device_toggle(phone_id, "notifications", true).unwrap();
assert_eq!(wait_for(&mut pc, "synced again", snapshot).await, 1);
}
+
+#[tokio::test(flavor = "multi_thread")]
+async fn clipboard_text_goes_both_ways_with_consent() {
+ let mut pc = device("Desktop", DeviceKind::Desktop).await;
+ let mut phone = device("Pixel", DeviceKind::Phone).await;
+ pair_qr(&mut pc, &mut phone).await;
+ let (pc_id, phone_id) = (pc.node.device_id(), phone.node.device_id());
+
+ with_timeout("pc to phone", pc.node.send_clipboard(phone_id, "from the PC".into())).await.expect("sent");
+ assert_eq!(*phone.platform.clipboard.lock().unwrap(), ["from the PC"]);
+ wait_for(&mut phone, "clipboard received", |e| match e {
+ NodeEvent::ClipboardReceived { device } if *device == pc_id => Some(()),
+ _ => None,
+ })
+ .await;
+
+ with_timeout("phone to pc", phone.node.send_clipboard(pc_id, "from the phone ✓".into()))
+ .await
+ .expect("sent");
+ assert_eq!(*pc.platform.clipboard.lock().unwrap(), ["from the phone ✓"]);
+
+ // The receiver turned the clipboard off for the sender.
+ phone.node.set_device_toggle(pc_id, "clipboard", false).unwrap();
+ let denied = with_timeout("denied", pc.node.send_clipboard(phone_id, "nope".into())).await;
+ assert!(matches!(denied, Err(Error::Denied)), "{denied:?}");
+ // The sender turned it off: nothing leaves.
+ let not_sent = with_timeout("not sent", phone.node.send_clipboard(pc_id, "nope".into())).await;
+ assert!(matches!(not_sent, Err(Error::Denied)), "{not_sent:?}");
+ assert_eq!(phone.platform.clipboard.lock().unwrap().len(), 1);
+
+ let huge = "x".repeat(nectarlink_core::CLIP_MAX_BYTES + 1);
+ assert!(matches!(pc.node.send_clipboard(phone_id, huge).await, Err(Error::TooLarge)));
+}
diff --git a/core/nectarlink-ffi/src/lib.rs b/core/nectarlink-ffi/src/lib.rs
index 9e417bd..e97fd1b 100644
--- a/core/nectarlink-ffi/src/lib.rs
+++ b/core/nectarlink-ffi/src/lib.rs
@@ -241,6 +241,10 @@ pub enum Event {
id: String,
key: String,
},
+ /// A device put text on this phone's clipboard.
+ ClipboardReceived {
+ id: String,
+ },
}
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error, uniffi::Error)]
@@ -263,6 +267,8 @@ pub enum NectarlinkError {
Unsupported,
#[error("it no longer exists")]
NotFound,
+ #[error("too large to send")]
+ TooLarge,
#[error("no pairing in progress")]
NotPairing,
#[error("invalid pairing link")]
@@ -290,6 +296,7 @@ impl From<core::Error> for NectarlinkError {
}
core::Error::Unsupported => NectarlinkError::Unsupported,
core::Error::NotFound => NectarlinkError::NotFound,
+ core::Error::TooLarge => NectarlinkError::TooLarge,
core::Error::NotPairing => NectarlinkError::NotPairing,
core::Error::InvalidPairingLink(_) => NectarlinkError::InvalidPairingLink,
core::Error::Network(reason) => NectarlinkError::Network { reason },
@@ -535,6 +542,7 @@ impl From<NodeEvent> for Event {
NodeEvent::NotificationRemoved { device, key } => {
Event::NotificationRemoved { id: device.to_string(), key }
}
+ NodeEvent::ClipboardReceived { device } => Event::ClipboardReceived { id: device.to_string() },
}
}
}
@@ -592,6 +600,8 @@ pub trait Platform: Send + Sync {
action: String,
reply: Option<String>,
) -> Result<(), NotificationFailure>;
+ /// A PC sent this text: put it on the clipboard. False if that failed.
+ fn set_clipboard(&self, text: String) -> bool;
}
/// Encrypts the device key at rest (Android: a Keystore key).
@@ -633,6 +643,9 @@ impl core::Platform for PlatformAdapter {
) -> Result<(), core::NotificationError> {
Ok(self.0.run_notification_action(key.to_owned(), action.to_owned(), reply.map(str::to_owned))?)
}
+ fn set_clipboard(&self, text: &str) -> Result<(), String> {
+ if self.0.set_clipboard(text.to_owned()) { Ok(()) } else { Err("the clipboard rejected it".into()) }
+ }
}
struct KeyProtectorAdapter(Arc<dyn KeyProtector>);
@@ -813,6 +826,15 @@ impl NectarlinkNode {
Ok(self.node.set_device_toggle(parse_id(&id)?, &name, enabled)?)
}
+ // ---- Clipboard ----
+
+ /// Puts text on a paired PC's clipboard.
+ pub async fn send_clipboard(&self, id: String, text: String) -> Result<()> {
+ let id = parse_id(&id)?;
+ let node = self.node.clone();
+ self.run(async move { Ok(node.send_clipboard(id, text).await?) }).await
+ }
+
// ---- Notifications ----
/// A notification appeared or changed on this phone.
diff --git a/core/nectarlink-protocol/src/messages.rs b/core/nectarlink-protocol/src/messages.rs
index fc4a979..3805bde 100644
--- a/core/nectarlink-protocol/src/messages.rs
+++ b/core/nectarlink-protocol/src/messages.rs
@@ -31,6 +31,8 @@ pub mod types {
pub const NOTIFY_POSTED: &str = "notify.posted";
pub const NOTIFY_REMOVED: &str = "notify.removed";
pub const NOTIFY_SYNC: &str = "notify.sync";
+
+ pub const CLIP_SET: &str = "clip.set";
pub const NOTIFY_DISMISS: &str = "notify.dismiss";
pub const NOTIFY_ACTION: &str = "notify.action";
}
@@ -315,6 +317,31 @@ impl std::fmt::Debug for NotifyAction {
}
}
+// ---- Clipboard (docs/protocol/clipboard.md) ----
+
+/// Largest clipboard text sent or accepted, in UTF-8 bytes.
+pub const CLIP_MAX_BYTES: usize = 512 * 1024;
+
+/// Body of `clip.set`.
+#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
+pub struct ClipSet {
+ pub text: String,
+}
+
+impl ClipSet {
+ /// Whether the text is within the spec's limits.
+ pub fn is_valid(&self) -> bool {
+ !self.text.is_empty() && self.text.len() <= CLIP_MAX_BYTES
+ }
+}
+
+/// Never prints content (protocol v0 §11).
+impl std::fmt::Debug for ClipSet {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.debug_struct("ClipSet").field("bytes", &self.text.len()).finish()
+ }
+}
+
/// A paired device identity as stored in trust stores and exchanged in tests.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PeerIdentity {
diff --git a/desktop/app/Cargo.toml b/desktop/app/Cargo.toml
index a387894..83324fa 100644
--- a/desktop/app/Cargo.toml
+++ b/desktop/app/Cargo.toml
@@ -44,6 +44,8 @@ windows = { workspace = true, features = [
"Win32_Security",
"Win32_System_Com",
"Win32_System_Com_StructuredStorage",
+ "Win32_System_DataExchange",
+ "Win32_System_Memory",
"Win32_System_Power",
"Win32_System_Registry",
"Win32_System_Threading",
diff --git a/desktop/app/qml/pages/HomePage.qml b/desktop/app/qml/pages/HomePage.qml
index e1f81e0..8376e76 100644
--- a/desktop/app/qml/pages/HomePage.qml
+++ b/desktop/app/qml/pages/HomePage.qml
@@ -208,10 +208,10 @@ Item {
ActionTile {
width: actions.tileWidth
title: qsTr("Send clipboard")
- subtitle: qsTr("To the phone")
+ subtitle: Preferences.autoClipboard ? qsTr("Copies go over by themselves") : qsTr("To the phone")
iconPath: Icons.clipboard
feature: home.feature("clipboard.pc_to_phone")
- ready: false
+ onClicked: AppController.sendClipboard(home.deviceId)
}
ActionTile {
width: actions.tileWidth
diff --git a/desktop/app/qml/pages/SettingsPage.qml b/desktop/app/qml/pages/SettingsPage.qml
index 7b7f25f..c719aee 100644
--- a/desktop/app/qml/pages/SettingsPage.qml
+++ b/desktop/app/qml/pages/SettingsPage.qml
@@ -137,15 +137,30 @@ Item {
Txt { text: qsTr("Behavior"); role: "label"; muted: true }
Card {
width: parent.width
- ListRow {
+ Column {
width: parent.width
- iconPath: Icons.power
- title: qsTr("Keep running when the window is closed")
- description: qsTr("Nectarlink stays in the notification area so your phone can reach this PC.")
- Toggle {
- label: qsTr("Keep running when the window is closed")
- checked: Preferences.closeToTray
- onToggled: (on) => Preferences.closeToTray = on
+ ListRow {
+ width: parent.width
+ iconPath: Icons.power
+ title: qsTr("Keep running when the window is closed")
+ description: qsTr("Nectarlink stays in the notification area so your phone can reach this PC.")
+ Toggle {
+ label: qsTr("Keep running when the window is closed")
+ checked: Preferences.closeToTray
+ onToggled: (on) => Preferences.closeToTray = on
+ }
+ }
+ Divider { width: parent.width }
+ ListRow {
+ width: parent.width
+ iconPath: Icons.clipboard
+ title: qsTr("Send what you copy to your phone")
+ description: qsTr("Text you copy on this PC is ready to paste on your phone. Passwords from password managers are never sent.")
+ Toggle {
+ label: qsTr("Send what you copy to your phone")
+ checked: Preferences.autoClipboard
+ onToggled: (on) => Preferences.autoClipboard = on
+ }
}
}
}
diff --git a/desktop/app/src/bridge/app.rs b/desktop/app/src/bridge/app.rs
index 8868605..28d7592 100644
--- a/desktop/app/src/bridge/app.rs
+++ b/desktop/app/src/bridge/app.rs
@@ -81,6 +81,11 @@ pub mod qobject {
#[qinvokable]
fn set_device_toggle(self: Pin<&mut AppController>, device: &QString, name: &QString, on: bool);
+ /// Sends what's copied on this PC to a device.
+ #[qinvokable]
+ #[cxx_name = "sendClipboard"]
+ fn send_clipboard(self: &AppController, device: &QString);
+
/// Re-reads whether Windows shows this app's notifications (the user
/// may have changed it in Settings).
#[qinvokable]
@@ -290,6 +295,12 @@ impl qobject::AppController {
self.refresh_toasts_enabled();
}
+ pub fn send_clipboard(&self, device: &QString) {
+ if let Some(id) = super::parse_device(device) {
+ crate::clipboard::send_now(id);
+ }
+ }
+
pub fn refresh_toasts_enabled(self: Pin<&mut Self>) {
self.set_toasts_enabled(win::toast::enabled());
}
diff --git a/desktop/app/src/bridge/prefs.rs b/desktop/app/src/bridge/prefs.rs
index b769703..749f966 100644
--- a/desktop/app/src/bridge/prefs.rs
+++ b/desktop/app/src/bridge/prefs.rs
@@ -39,6 +39,8 @@ pub mod qobject {
/// Mica behind the window.
#[qproperty(bool, backdrop)]
#[qproperty(bool, close_to_tray)]
+ /// Send what's copied on this PC to connected phones.
+ #[qproperty(bool, auto_clipboard)]
type Preferences = super::PreferencesRust;
}
@@ -52,6 +54,7 @@ pub struct PreferencesRust {
color_mode: QString,
backdrop: bool,
close_to_tray: bool,
+ auto_clipboard: bool,
}
impl cxx_qt::Initialize for qobject::Preferences {
@@ -69,6 +72,8 @@ impl cxx_qt::Initialize for qobject::Preferences {
}));
self.as_mut().set_backdrop(settings.backdrop);
self.as_mut().set_close_to_tray(settings.close_to_tray);
+ self.as_mut().set_auto_clipboard(settings.auto_clipboard);
+ crate::clipboard::set_auto_send(settings.auto_clipboard);
// Save after any change (connected after loading, so loading doesn't
// rewrite the file).
@@ -77,6 +82,12 @@ impl cxx_qt::Initialize for qobject::Preferences {
self.as_mut().on_color_mode_changed(|p| p.save()).release();
self.as_mut().on_backdrop_changed(|p| p.save()).release();
self.as_mut().on_close_to_tray_changed(|p| p.save()).release();
+ self.as_mut()
+ .on_auto_clipboard_changed(|p| {
+ crate::clipboard::set_auto_send(p.auto_clipboard);
+ p.save();
+ })
+ .release();
}
}
@@ -93,6 +104,7 @@ impl qobject::Preferences {
},
backdrop: p.backdrop,
close_to_tray: p.close_to_tray,
+ auto_clipboard: p.auto_clipboard,
};
save_in_background(settings);
}
diff --git a/desktop/app/src/clipboard.rs b/desktop/app/src/clipboard.rs
new file mode 100644
index 0000000..a74cfae
--- /dev/null
+++ b/desktop/app/src/clipboard.rs
@@ -0,0 +1,92 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+//! The clipboard between this PC and paired phones
+//! (docs/protocol/clipboard.md): what the user copies goes to connected
+//! phones (unless turned off in Settings), "Send clipboard" sends it on
+//! demand, and text from a phone lands on the Windows clipboard.
+
+use std::sync::atomic::{AtomicBool, Ordering};
+
+use nectarlink_core::{DeviceId, Error, FeatureState, LinkState, NodeEvent};
+
+use crate::{
+ bridge::app::{describe, show_message},
+ core_host,
+ win::clipboard::{self, Clip},
+};
+
+/// The "Send what you copy to your phone" preference.
+static AUTO_SEND: AtomicBool = AtomicBool::new(true);
+
+pub fn set_auto_send(on: bool) {
+ AUTO_SEND.store(on, Ordering::Relaxed);
+}
+
+/// Starts watching the Windows clipboard.
+pub fn start() {
+ clipboard::start(on_copy);
+}
+
+/// Connected phones that take this PC's clipboard (capable and allowed).
+fn receivers() -> Vec<DeviceId> {
+ core_host::host().hub.read(|s| {
+ s.devices
+ .iter()
+ .filter(|d| matches!(d.link, LinkState::Online { .. }))
+ .filter(|d| {
+ s.matrices.get(&d.id).and_then(|m| m.state("clipboard.pc_to_phone"))
+ == Some(FeatureState::Available)
+ })
+ .map(|d| d.id)
+ .collect()
+ })
+}
+
+/// The user copied text on this PC.
+fn on_copy(text: String) {
+ if !AUTO_SEND.load(Ordering::Relaxed) {
+ return;
+ }
+ let Some(node) = core_host::node() else { return };
+ for device in receivers() {
+ let (node, text) = (node.clone(), text.clone());
+ core_host::spawn(async move {
+ // Automatic: nothing to tell the user if a phone can't take it.
+ if let Err(e) = node.send_clipboard(device, text).await {
+ tracing::debug!(device = %device.short(), error = %e, "clipboard not sent");
+ }
+ });
+ }
+}
+
+/// "Send clipboard": sends what's copied to one device, and says how it went.
+pub fn send_now(device: DeviceId) {
+ let Some(node) = core_host::node() else { return };
+ let name = core_host::host().hub.read(|s| s.name_of(&device)).unwrap_or_else(|| "the phone".into());
+ let text = match clipboard::read() {
+ Clip::Text(text) => text,
+ Clip::Private => {
+ show_message("What you copied is marked private by its app, so it wasn't sent.");
+ return;
+ }
+ Clip::Empty => {
+ show_message("There's no text on the clipboard.");
+ return;
+ }
+ };
+ core_host::spawn(async move {
+ match node.send_clipboard(device, text).await {
+ Ok(()) => show_message(format!("Sent to {name}.")),
+ Err(Error::TooLarge) => show_message("That's too much text to send at once."),
+ Err(Error::Denied) => show_message(format!("The clipboard is turned off for {name}.")),
+ Err(e) => show_message(describe(&e)),
+ }
+ });
+}
+
+/// Feedback for clipboard events.
+pub fn on_event(event: &NodeEvent) {
+ if let NodeEvent::ClipboardReceived { device } = event {
+ let name = core_host::host().hub.read(|s| s.name_of(device)).unwrap_or_else(|| "your phone".into());
+ show_message(format!("Copied from {name}."));
+ }
+}
diff --git a/desktop/app/src/core_host.rs b/desktop/app/src/core_host.rs
index 1f54bd6..321c645 100644
--- a/desktop/app/src/core_host.rs
+++ b/desktop/app/src/core_host.rs
@@ -107,6 +107,7 @@ async fn run(data_dir: PathBuf, platform: Arc<dyn Platform>) {
Ok(event) => {
crate::notifications::apply(&event);
crate::notifications::update_toasts(&event);
+ crate::clipboard::on_event(&event);
}
Err(RecvError::Lagged(missed)) => {
// Resynchronize what can be re-read; transient events are lost.
diff --git a/desktop/app/src/main.rs b/desktop/app/src/main.rs
index a3d4f5f..867e36c 100644
--- a/desktop/app/src/main.rs
+++ b/desktop/app/src/main.rs
@@ -9,6 +9,7 @@
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
mod bridge;
+mod clipboard;
mod core_host;
mod icons;
mod logging;
@@ -48,6 +49,9 @@ impl Platform for DesktopPlatform {
fn stop_ringing(&self) {
win::sound::stop_ringing();
}
+ fn set_clipboard(&self, text: &str) -> Result<(), String> {
+ win::clipboard::write(text)
+ }
}
/// Command-line options (also used by shortcuts and autostart).
@@ -141,6 +145,7 @@ fn main() -> ExitCode {
}
watch_network();
start_toasts();
+ clipboard::start();
bridge::native::ffi::prepare_qt();
let mut app = QGuiApplication::new();
diff --git a/desktop/app/src/settings.rs b/desktop/app/src/settings.rs
index 5c6cd8a..058acc0 100644
--- a/desktop/app/src/settings.rs
+++ b/desktop/app/src/settings.rs
@@ -41,6 +41,8 @@ pub struct Settings {
pub backdrop: bool,
/// Closing the window keeps Nectarlink running in the tray.
pub close_to_tray: bool,
+ /// Send what's copied on this PC to connected phones.
+ pub auto_clipboard: bool,
}
impl Default for Settings {
@@ -51,6 +53,7 @@ impl Default for Settings {
color_mode: ColorMode::default(),
backdrop: true,
close_to_tray: true,
+ auto_clipboard: true,
}
}
}
@@ -110,6 +113,7 @@ mod tests {
color_mode: ColorMode::Dark,
backdrop: false,
close_to_tray: false,
+ auto_clipboard: false,
};
settings.save(dir.path()).unwrap();
assert_eq!(Settings::load(dir.path()), settings);
diff --git a/desktop/app/src/state.rs b/desktop/app/src/state.rs
index f409e46..90732ba 100644
--- a/desktop/app/src/state.rs
+++ b/desktop/app/src/state.rs
@@ -286,6 +286,8 @@ impl AppState {
self.notifications.retain(|n| !(n.device == *device && n.notification.key == *key));
if before == self.notifications.len() { Changes::NONE } else { Changes::NOTIFICATIONS }
}
+ // Feedback only (see crate::clipboard); nothing to keep.
+ NodeEvent::ClipboardReceived { .. } => Changes::NONE,
}
}
diff --git a/desktop/app/src/win/clipboard.rs b/desktop/app/src/win/clipboard.rs
new file mode 100644
index 0000000..a20098f
--- /dev/null
+++ b/desktop/app/src/win/clipboard.rs
@@ -0,0 +1,268 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+//! The Windows clipboard: watching for copied text, reading it and writing
+//! text a phone sent (docs/protocol/clipboard.md).
+//!
+//! A hidden message-only window on its own thread listens for clipboard
+//! changes and owns what Nectarlink writes, so text that came from a phone
+//! is never sent back. Content that password managers mark as private is
+//! never read for sending.
+
+use std::{
+ sync::{
+ Mutex, OnceLock,
+ atomic::{AtomicIsize, Ordering},
+ },
+ time::Duration,
+};
+
+use windows::{
+ Win32::{
+ Foundation::{GlobalFree, HANDLE, HGLOBAL, HWND, LPARAM, LRESULT, WPARAM},
+ System::{
+ DataExchange::{
+ AddClipboardFormatListener, CloseClipboard, EmptyClipboard, GetClipboardData,
+ GetClipboardOwner, IsClipboardFormatAvailable, OpenClipboard, RegisterClipboardFormatW,
+ SetClipboardData,
+ },
+ LibraryLoader::GetModuleHandleW,
+ Memory::{GMEM_MOVEABLE, GlobalAlloc, GlobalLock, GlobalSize, GlobalUnlock},
+ },
+ UI::WindowsAndMessaging::{
+ CreateWindowExW, DefWindowProcW, DispatchMessageW, GetMessageW, HWND_MESSAGE, MSG,
+ RegisterClassExW, WINDOW_EX_STYLE, WINDOW_STYLE, WM_CLIPBOARDUPDATE, WNDCLASSEXW,
+ },
+ },
+ core::{HSTRING, w},
+};
+
+/// Standard clipboard format for UTF-16 text.
+const CF_UNICODETEXT: u32 = 13;
+
+/// What's on the clipboard, for sending.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub enum Clip {
+ Text(String),
+ /// Marked private (a password manager): never sent.
+ Private,
+ /// Nothing that's text.
+ Empty,
+}
+
+type OnCopy = Box<dyn Fn(String) + Send + Sync>;
+
+/// The listener window, once started (as an isize: HWND isn't Send).
+static WINDOW: AtomicIsize = AtomicIsize::new(0);
+static ON_COPY: OnceLock<OnCopy> = OnceLock::new();
+/// The last text reported, so one copy reported several times (apps often
+/// write the clipboard in steps) is sent once.
+static LAST_REPORTED: Mutex<Option<String>> = Mutex::new(None);
+
+/// Starts watching the clipboard; `on_copy` gets each newly copied text
+/// that isn't private and didn't come from Nectarlink, on the watcher thread.
+pub fn start(on_copy: impl Fn(String) + Send + Sync + 'static) {
+ if ON_COPY.set(Box::new(on_copy)).is_err() {
+ return; // already started
+ }
+ let spawned = std::thread::Builder::new().name("clipboard".into()).spawn(|| {
+ if let Err(e) = run() {
+ tracing::warn!(error = %e, "can't watch the clipboard");
+ }
+ });
+ if let Err(e) = spawned {
+ tracing::warn!(error = %e, "can't watch the clipboard");
+ }
+}
+
+fn run() -> windows::core::Result<()> {
+ // SAFETY: standard class registration and message-only window creation;
+ // the window procedure only reads statics.
+ let hwnd = unsafe {
+ let instance = GetModuleHandleW(None)?;
+ let class = WNDCLASSEXW {
+ cbSize: std::mem::size_of::<WNDCLASSEXW>() as u32,
+ lpfnWndProc: Some(window_proc),
+ hInstance: instance.into(),
+ lpszClassName: w!("Nectarlink.Clipboard"),
+ ..Default::default()
+ };
+ RegisterClassExW(&class);
+ CreateWindowExW(
+ WINDOW_EX_STYLE(0),
+ w!("Nectarlink.Clipboard"),
+ w!("Nectarlink clipboard"),
+ WINDOW_STYLE(0),
+ 0,
+ 0,
+ 0,
+ 0,
+ Some(HWND_MESSAGE),
+ None,
+ Some(instance.into()),
+ None,
+ )?
+ };
+ WINDOW.store(hwnd.0 as isize, Ordering::Release);
+ // SAFETY: registering our own window for clipboard change messages.
+ unsafe { AddClipboardFormatListener(hwnd)? };
+ let mut msg = MSG::default();
+ // SAFETY: a plain message loop for this thread's window.
+ unsafe {
+ while GetMessageW(&mut msg, None, 0, 0).as_bool() {
+ DispatchMessageW(&msg);
+ }
+ }
+ Ok(())
+}
+
+unsafe extern "system" fn window_proc(hwnd: HWND, msg: u32, wparam: WPARAM, lparam: LPARAM) -> LRESULT {
+ if msg == WM_CLIPBOARDUPDATE {
+ on_clipboard_changed(hwnd);
+ return LRESULT(0);
+ }
+ // SAFETY: default handling for everything else.
+ unsafe { DefWindowProcW(hwnd, msg, wparam, lparam) }
+}
+
+fn on_clipboard_changed(hwnd: HWND) {
+ // What Nectarlink wrote (a phone's text) isn't sent back.
+ // SAFETY: GetClipboardOwner has no preconditions.
+ if unsafe { GetClipboardOwner() }.is_ok_and(|owner| owner == hwnd) {
+ return;
+ }
+ let Clip::Text(text) = read_with(Some(hwnd)) else { return };
+ {
+ let mut last = LAST_REPORTED.lock().unwrap_or_else(|e| e.into_inner());
+ if last.as_deref() == Some(text.as_str()) {
+ return;
+ }
+ *last = Some(text.clone());
+ }
+ if let Some(on_copy) = ON_COPY.get() {
+ on_copy(text);
+ }
+}
+
+fn window() -> Option<HWND> {
+ let raw = WINDOW.load(Ordering::Acquire);
+ (raw != 0).then_some(HWND(raw as *mut _))
+}
+
+/// What's on the clipboard now.
+pub fn read() -> Clip {
+ read_with(window())
+}
+
+/// Puts text on the clipboard (owned by the watcher window, so it isn't
+/// reported as a new copy).
+pub fn write(text: &str) -> Result<(), String> {
+ let owner = window().ok_or("the clipboard watcher isn't running")?;
+ let wide: Vec<u16> = text.encode_utf16().chain(std::iter::once(0)).collect();
+ let _open = Opened::open(Some(owner)).ok_or("the clipboard is busy")?;
+ // SAFETY: the clipboard is open; the global block is sized for `wide`,
+ // and ownership passes to the clipboard only when SetClipboardData
+ // succeeds (it's freed otherwise).
+ unsafe {
+ EmptyClipboard().map_err(|e| e.to_string())?;
+ let block = GlobalAlloc(GMEM_MOVEABLE, wide.len() * 2).map_err(|e| e.to_string())?;
+ let target = GlobalLock(block).cast::<u16>();
+ if target.is_null() {
+ let _ = GlobalFree(Some(block));
+ return Err("can't lock memory".into());
+ }
+ std::ptr::copy_nonoverlapping(wide.as_ptr(), target, wide.len());
+ let _ = GlobalUnlock(block);
+ if let Err(e) = SetClipboardData(CF_UNICODETEXT, Some(HANDLE(block.0))) {
+ let _ = GlobalFree(Some(block));
+ return Err(e.to_string());
+ }
+ }
+ *LAST_REPORTED.lock().unwrap_or_else(|e| e.into_inner()) = Some(text.to_owned());
+ Ok(())
+}
+
+/// The clipboard, opened; closed when dropped. Other apps hold it briefly
+/// while they write, so opening retries for a moment.
+struct Opened;
+
+impl Opened {
+ fn open(owner: Option<HWND>) -> Option<Opened> {
+ for _ in 0..20 {
+ // SAFETY: opening the clipboard for this thread; closed in Drop.
+ if unsafe { OpenClipboard(owner) }.is_ok() {
+ return Some(Opened);
+ }
+ std::thread::sleep(Duration::from_millis(15));
+ }
+ None
+ }
+}
+
+impl Drop for Opened {
+ fn drop(&mut self) {
+ // SAFETY: we opened it.
+ unsafe {
+ let _ = CloseClipboard();
+ }
+ }
+}
+
+fn format(name: &str) -> u32 {
+ // SAFETY: registering (or looking up) a named format.
+ unsafe { RegisterClipboardFormatW(&HSTRING::from(name)) }
+}
+
+fn read_with(owner: Option<HWND>) -> Clip {
+ // SAFETY: format availability checks need no open clipboard.
+ let has = |format: u32| format != 0 && unsafe { IsClipboardFormatAvailable(format) }.is_ok();
+ if !has(CF_UNICODETEXT) {
+ return Clip::Empty;
+ }
+ // Password managers and other apps mark private content this way.
+ if has(format("ExcludeClipboardContentFromMonitorProcessing")) || has(format("Clipboard Viewer Ignore")) {
+ return Clip::Private;
+ }
+ let Some(_open) = Opened::open(owner) else { return Clip::Empty };
+ if let Some(0) = read_dword(format("CanIncludeInClipboardHistory")) {
+ return Clip::Private;
+ }
+ // SAFETY: the clipboard is open; the data handle is valid until it's
+ // closed, and the text is read within the block's size.
+ let text = unsafe {
+ let Ok(handle) = GetClipboardData(CF_UNICODETEXT) else { return Clip::Empty };
+ let block = HGLOBAL(handle.0);
+ let units = GlobalSize(block) / 2;
+ let data = GlobalLock(block).cast::<u16>();
+ if data.is_null() {
+ return Clip::Empty;
+ }
+ let slice = std::slice::from_raw_parts(data, units);
+ let len = slice.iter().position(|&c| c == 0).unwrap_or(units);
+ let text = String::from_utf16_lossy(&slice[..len]);
+ let _ = GlobalUnlock(block);
+ text
+ };
+ if text.trim().is_empty() { Clip::Empty } else { Clip::Text(text) }
+}
+
+/// A DWORD-valued clipboard format, if present. The clipboard must be open.
+fn read_dword(format: u32) -> Option<u32> {
+ if format == 0 {
+ return None;
+ }
+ // SAFETY: the caller opened the clipboard; the block is read only if it
+ // holds at least four bytes.
+ unsafe {
+ let handle = GetClipboardData(format).ok()?;
+ let block = HGLOBAL(handle.0);
+ if GlobalSize(block) < 4 {
+ return None;
+ }
+ let data = GlobalLock(block).cast::<u32>();
+ if data.is_null() {
+ return None;
+ }
+ let value = data.read_unaligned();
+ let _ = GlobalUnlock(block);
+ Some(value)
+ }
+}
diff --git a/desktop/app/src/win/mod.rs b/desktop/app/src/win/mod.rs
index a5664ef..6b6d690 100644
--- a/desktop/app/src/win/mod.rs
+++ b/desktop/app/src/win/mod.rs
@@ -5,6 +5,7 @@
#![allow(unsafe_code)]
+pub mod clipboard;
pub mod icon;
pub mod net;
pub mod single_instance;
diff --git a/docs/protocol/capabilities.md b/docs/protocol/capabilities.md
index 9a710b9..0c40a33 100644
--- a/docs/protocol/capabilities.md
+++ b/docs/protocol/capabilities.md
@@ -34,7 +34,7 @@ capability is missing.
| `sms.read` | Reads SMS conversations | SMS permission |
| `sms.send` | Sends SMS | SMS permission |
| `call.state` | Reports incoming and ongoing calls | phone permission |
-| `clip.write` | Accepts clipboard content from the PC | app update |
+| `clip.write` | Accepts clipboard content from the PC ([clipboard service](clipboard.md)) | app update |
| `clip.share` | Sends the clipboard when the user taps "Send" | app update |
| `clip.read.auto` | Sends clipboard changes automatically, in the background | Elevated |
| `photos.read` | Lists and sends recent photos and screenshots | photos permission |
diff --git a/docs/protocol/clipboard.md b/docs/protocol/clipboard.md
new file mode 100644
index 0000000..1c59018
--- /dev/null
+++ b/docs/protocol/clipboard.md
@@ -0,0 +1,49 @@
+# Clipboard service (protocol v0)
+
+> Status: **draft.** Builds on [protocol v0](v0.md); breaking changes are
+> allowed until v1. License: CC BY 4.0.
+
+Copied text moves between paired devices: a PC sends what the user copies
+(automatically, unless turned off), and a phone sends its clipboard when
+the user asks (Android only lets the app in front read the clipboard;
+reading it in the background needs the Elevated power level).
+
+Images, rich text and files on the clipboard are not part of this version;
+they will travel over bulk streams with file transfer.
+
+## 1. Capabilities
+
+| ID | Offered by | Meaning |
+|---|---|---|
+| `clip.write` | phone | Accepts `clip.set` |
+| `clip.share` | phone | Sends its clipboard when the user asks |
+| `clip.read.auto` | phone | Sends clipboard changes on its own (Elevated) |
+
+A PC always accepts `clip.set` from a phone the user allows.
+
+## 2. Messages
+
+```
+t = "clip.set" id = n b = { text: text }
+t = "ok" re = n
+```
+
+**`clip.set`** puts `text` on the receiver's clipboard, replacing what's
+there. `text` is plain text of 1 byte to 512 KiB (UTF-8); senders **MUST NOT**
+send larger text and receivers reply `BAD_MESSAGE` to it.
+
+Errors: `DENIED` when the user turned the clipboard off for the sending
+device (the `clipboard` device toggle), `INTERNAL` when the clipboard
+couldn't be written.
+
+## 3. Rules
+
+- **Consent.** Each device sends and accepts only with the `clipboard`
+ toggle on for the other device.
+- **Sensitive content is never sent.** On Windows: clips marked
+ `ExcludeClipboardContentFromMonitorProcessing`, or with
+ `CanIncludeInClipboardHistory` set to 0 (what password managers use). On
+ Android: clips marked `ClipDescription.EXTRA_IS_SENSITIVE`.
+- **No echoes.** A device does not send text it just received with
+ `clip.set`.
+- Implementations **MUST NOT** log clipboard content (v0 §11).
diff --git a/docs/protocol/v0.md b/docs/protocol/v0.md
index e89a9ca..86b8e97 100644
--- a/docs/protocol/v0.md
+++ b/docs/protocol/v0.md
@@ -7,8 +7,8 @@ This document specifies how two Nectarlink devices find each other, pair,
connect and exchange messages. Version 0 covers the Phase 0 scope: identity,
pairing, the session handshake, capabilities, heartbeat and the first events
(device info, battery, ping). Feature services are specified in separate
-documents that build on this one: [notifications](notifications.md) so far;
-files, clipboard and mirroring follow.
+documents that build on this one: [notifications](notifications.md) and
+[clipboard](clipboard.md) so far; files and mirroring follow.
Key words **MUST**, **SHOULD** and **MAY** are used as in RFC 2119.