Your Android phone and your Windows PC, working as one. Local-first, end-to-end encrypted, no account.
Control the phone from the PC while it's mirrored (Assist)
Bee8be0575a58c7
diff --git a/README.md b/README.mdindex fd97c53..5b3b353 100644--- a/README.md+++ b/README.md@@ -89,9 +89,11 @@ place and tested; the user-facing features of Phase 1 come next.on the phone, share them from any app or pick them in Nectarlink. They land in `Downloads\Nectarlink` on the PC and`Download/Nectarlink` on the phone, with progress, cancelling, and transfersthat pick up where they left off after a dropped connection.-- **Screen mirroring** (view): see the phone's screen on the PC, in a- window of its own, at up to 1920 pixels and 60 frames a second, hardware- encoded on the phone. Android asks each time; stop it from either side.+- **Screen mirroring**: see the phone's screen on the PC, in a window of+ its own, at up to 1920 pixels and 60 frames a second, hardware encoded on+ the phone; Android asks each time. Turn on **Control from your PC** in+ the phone's Nectarlink settings to tap, swipe, scroll and type with the+ PC's mouse and keyboard (right-click is Back).- **Texts** on the PC: a Messages page with the phone's conversations(pictures included), to reply or start a new one; texts go out throughthe phone.diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xmlindex 05dc955..20bc9d4 100644--- a/android/app/src/main/AndroidManifest.xml+++ b/android/app/src/main/AndroidManifest.xml@@ -162,6 +162,21 @@android:taskAffinity=""android:theme="@android:style/Theme.Translucent.NoTitleBar" />+ <!-- The PC's mouse and keyboard on the mirrored screen (Assist); the+ user turns it on in Android's accessibility settings. -->+ <service+ android:name=".mirror.InputService"+ android:exported="true"+ android:label="@string/input_service_label"+ android:permission="android.permission.BIND_ACCESSIBILITY_SERVICE">+ <intent-filter>+ <action android:name="android.accessibilityservice.AccessibilityService" />+ </intent-filter>+ <meta-data+ android:name="android.accessibilityservice"+ android:resource="@xml/input_service" />+ </service>+<serviceandroid:name=".mirror.MirrorService"android:exported="false"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.ktindex a4b4892..5e15209 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@@ -17,6 +17,7 @@ import app.nectarlink.android.files.TransferNotificationsimport app.nectarlink.android.Rimport app.nectarlink.android.notifications.NotificationListenerimport app.nectarlink.android.calls.PhoneCalls+import app.nectarlink.android.mirror.InputServiceimport app.nectarlink.android.mirror.MirrorRequestsimport app.nectarlink.android.photos.RecentPhotosimport app.nectarlink.android.sms.PhoneSms@@ -160,7 +161,7 @@ class Core(context: Context, private val scope: CoroutineScope) : EventListenersmsAccess = PhoneSms.hasAll(context),)}- started.updatePower(PowerLevel.BASIC, capabilities(NotificationListener.hasAccess(context)))+ started.updatePower(powerLevel(), capabilities(NotificationListener.hasAccess(context)))scope.launch(Dispatchers.Main) {if (_state.value.photoAccess) photos.start()calls.start()@@ -184,7 +185,7 @@ class Core(context: Context, private val scope: CoroutineScope) : EventListener_state.update { it.copy(notificationAccess = granted) }scope.launch(Dispatchers.Main) { if (granted) phoneMedia.start() else phoneMedia.stop() }notificationOps.trySend { node ->- node.updatePower(PowerLevel.BASIC, capabilities(granted))+ node.updatePower(powerLevel(), capabilities(granted))node.notificationsReset(showing)}}@@ -208,6 +209,8 @@ class Core(context: Context, private val scope: CoroutineScope) : EventListenerval photoAccess = RecentPhotos.hasAccess(context)val callAccess = PhoneCalls.hasAll(context)val smsAccess = PhoneSms.hasAll(context)+ val inputAccess = InputService.running+ val inputChanged = inputAccess != _state.value.inputAccessval photosChanged = photoAccess != _state.value.photoAccessval callsChanged = callAccess != _state.value.callAccessval smsChanged = smsAccess != _state.value.smsAccess@@ -218,16 +221,17 @@ class Core(context: Context, private val scope: CoroutineScope) : EventListenerphotoAccess = photoAccess,callAccess = callAccess,smsAccess = smsAccess,+ inputAccess = inputAccess,)}if (granted && NotificationListener.instance == null) {NotificationListenerService.requestRebind(NotificationListener.component(context))}- if ((photosChanged || callsChanged || smsChanged) && node != null) {+ if ((photosChanged || callsChanged || smsChanged || inputChanged) && node != null) {if (photoAccess) photos.start() else photos.stop()if (PhoneCalls.canFollow(context)) calls.start() else calls.stop()if (PhoneSms.canRead(context)) sms.start() else sms.stop()- notificationOps.trySend { it.updatePower(PowerLevel.BASIC, capabilities(_state.value.notificationAccess)) }+ notificationOps.trySend { it.updatePower(powerLevel(), capabilities(_state.value.notificationAccess)) }}}@@ -366,7 +370,11 @@ class Core(context: Context, private val scope: CoroutineScope) : EventListener(if (PhoneCalls.canFollow(context)) listOf("call.state") else emptyList()) +(if (PhoneCalls.canControl(context)) listOf("call.control") else emptyList()) +(if (PhoneSms.canRead(context)) listOf("sms.read") else emptyList()) +- (if (PhoneSms.canSend(context)) listOf("sms.send") else emptyList())+ (if (PhoneSms.canSend(context)) listOf("sms.send") else emptyList()) ++ (if (InputService.running) listOf("mirror.input") else emptyList())++ /** Assist when the user turned on control from the PC (docs/PLAN.md §4.6). */+ private fun powerLevel(): PowerLevel = if (InputService.running) PowerLevel.ASSIST else PowerLevel.BASIC// ---- Pairing ----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.ktindex dd7a2de..bd2100e 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@@ -62,6 +62,8 @@ data class CoreState(val ringingFrom: String? = null,/** Whether the user let Nectarlink read notifications (to mirror them). */val notificationAccess: Boolean = false,+ /** Whether the user turned on control from the PC (the accessibility service). */+ val inputAccess: Boolean = false,/** Whether the user let Nectarlink read and send texts (for PCs). */val smsAccess: Boolean = false,/** Whether the user let Nectarlink follow and answer calls (to show them on PCs). */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.ktindex 35912b5..6157ba1 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@@ -12,6 +12,7 @@ import app.nectarlink.android.clipboard.PhoneClipboardimport app.nectarlink.android.notifications.NotificationListenerimport app.nectarlink.android.media.PhoneMediaimport app.nectarlink.android.photos.RecentPhotos+import app.nectarlink.android.mirror.InputServiceimport app.nectarlink.android.mirror.MirrorRequestimport app.nectarlink.android.mirror.MirrorRequestsimport app.nectarlink.android.mirror.MirrorService@@ -22,6 +23,7 @@ import app.nectarlink.core.SmsPartDataimport app.nectarlink.core.SmsThreadimport app.nectarlink.core.FileToSendimport app.nectarlink.core.MediaAction+import app.nectarlink.core.MirrorInputEventimport app.nectarlink.core.NotificationFailureimport app.nectarlink.core.Platform@@ -72,6 +74,8 @@ internal class PhonePlatform(override fun mirrorKeyframeRequested(pcId: String) = MirrorService.keyframe(pcId)+ override fun mirrorInput(pcId: String, input: MirrorInputEvent) = InputService.handle(input)+override fun smsThreads(limit: UInt): List<SmsThread> = sms().threads(limit.toInt())override fun smsMessages(thread: String, before: Long?, limit: UInt): List<SmsMessage> =diff --git a/android/app/src/main/kotlin/app/nectarlink/android/mirror/InputService.kt b/android/app/src/main/kotlin/app/nectarlink/android/mirror/InputService.ktnew file mode 100644index 0000000..25fe259--- /dev/null+++ b/android/app/src/main/kotlin/app/nectarlink/android/mirror/InputService.kt@@ -0,0 +1,230 @@+// SPDX-License-Identifier: GPL-3.0-or-later+package app.nectarlink.android.mirror++import android.accessibilityservice.AccessibilityService+import android.accessibilityservice.GestureDescription+import android.content.ComponentName+import android.content.Context+import android.graphics.Path+import android.os.Build+import android.os.Bundle+import android.os.Handler+import android.os.Looper+import android.os.SystemClock+import android.provider.Settings+import android.util.Log+import android.view.WindowManager+import android.view.accessibility.AccessibilityEvent+import android.view.accessibility.AccessibilityNodeInfo+import app.nectarlink.android.NectarlinkApplication+import app.nectarlink.core.MirrorInputEvent+import app.nectarlink.core.TouchPhase+import kotlin.math.abs+import kotlin.math.hypot++/**+ * The PC's mouse and keyboard on this phone while its screen is mirrored+ * (Assist level, docs/protocol/mirror.md): an accessibility service, which+ * the user turns on once. Clicks become taps, holds long presses, drags+ * swipes (played when the button comes up: Android plays a gesture whole),+ * the wheel scrolls, and typing goes into the focused text field.+ */+class InputService : AccessibilityService() {+ private val main = Handler(Looper.getMainLooper())++ /** The finger's way so far, as fractions of the screen, and when it went down. */+ private val stroke = mutableListOf<Pair<Float, Float>>()+ private var downAt = 0L++ // Wheel notches are gathered briefly into one swipe.+ private var scrollX = 0f+ private var scrollY = 0f+ private var scrollDx = 0f+ private var scrollDy = 0f+ private val flushScroll = Runnable { scroll() }++ override fun onServiceConnected() {+ instance = this+ (application as NectarlinkApplication).core.refreshNotificationAccess()+ }++ override fun onUnbind(intent: android.content.Intent?): Boolean {+ instance = null+ (application as NectarlinkApplication).core.refreshNotificationAccess()+ return super.onUnbind(intent)+ }++ override fun onDestroy() {+ if (instance === this) instance = null+ super.onDestroy()+ }++ override fun onAccessibilityEvent(event: AccessibilityEvent?) {}++ override fun onInterrupt() {}++ private fun handle(input: MirrorInputEvent) {+ when (input) {+ is MirrorInputEvent.Touch -> touch(input.action, input.x, input.y)+ is MirrorInputEvent.Scroll -> {+ scrollX = input.x+ scrollY = input.y+ scrollDx += input.dx+ scrollDy += input.dy+ main.removeCallbacks(flushScroll)+ main.postDelayed(flushScroll, SCROLL_GATHER_MS)+ }+ is MirrorInputEvent.Key -> key(input.key)+ is MirrorInputEvent.Text -> type(input.text)+ }+ }++ // ---- Touch ----++ private fun touch(action: TouchPhase, x: Float, y: Float) {+ when (action) {+ TouchPhase.DOWN -> {+ stroke.clear()+ stroke += x to y+ downAt = SystemClock.uptimeMillis()+ }+ TouchPhase.MOVE -> if (stroke.isNotEmpty()) stroke += x to y+ TouchPhase.UP -> {+ if (stroke.isEmpty()) return+ stroke += x to y+ val held = SystemClock.uptimeMillis() - downAt+ val (w, h) = screen()+ val points = stroke.map { (px, py) -> px * w to py * h }+ stroke.clear()+ val travelled = points.zipWithNext { a, b -> hypot(b.first - a.first, b.second - a.second) }.sum()+ val path = Path().apply {+ moveTo(points.first().first, points.first().second)+ points.drop(1).forEach { (px, py) -> lineTo(px, py) }+ }+ val duration = when {+ // Barely moved: a tap, or a long press when held.+ travelled < TAP_SLOP_FRACTION * w -> if (held >= LONG_PRESS_MS) held.coerceAtMost(MAX_GESTURE_MS) else TAP_MS+ else -> held.coerceIn(MIN_SWIPE_MS, MAX_GESTURE_MS)+ }+ gesture(path, duration)+ }+ }+ }++ private fun scroll() {+ val (w, h) = screen()+ val x = scrollX * w+ val y = scrollY * h+ // Wheel down shows what's below: the finger moves up.+ val dx = (-scrollDx * SCROLL_STEP_FRACTION * w).coerceIn(-x + 1, w - x - 1)+ val dy = (-scrollDy * SCROLL_STEP_FRACTION * h).coerceIn(-y + 1, h - y - 1)+ scrollDx = 0f+ scrollDy = 0f+ if (abs(dx) < 1 && abs(dy) < 1) return+ gesture(Path().apply { moveTo(x, y); lineTo(x + dx, y + dy) }, SCROLL_MS)+ }++ private fun gesture(path: Path, durationMs: Long) {+ val description = GestureDescription.Builder()+ .addStroke(GestureDescription.StrokeDescription(path, 0, durationMs.coerceAtLeast(1)))+ .build()+ if (!dispatchGesture(description, null, null)) Log.i(TAG, "a gesture wasn't played")+ }++ /** The screen's size in pixels, as it's turned now. */+ private fun screen(): Pair<Float, Float> {+ val windows = getSystemService(WindowManager::class.java)+ return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {+ windows.maximumWindowMetrics.bounds.let { it.width().toFloat() to it.height().toFloat() }+ } else {+ val metrics = android.util.DisplayMetrics()+ @Suppress("DEPRECATION")+ windows.defaultDisplay.getRealMetrics(metrics)+ metrics.widthPixels.toFloat() to metrics.heightPixels.toFloat()+ }+ }++ // ---- Keys and text ----++ private fun key(key: String) {+ when (key) {+ "back" -> performGlobalAction(GLOBAL_ACTION_BACK)+ "home" -> performGlobalAction(GLOBAL_ACTION_HOME)+ "recents" -> performGlobalAction(GLOBAL_ACTION_RECENTS)+ "notifications" -> performGlobalAction(GLOBAL_ACTION_NOTIFICATIONS)+ "enter" -> focused()?.let { node ->+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {+ node.performAction(AccessibilityNodeInfo.AccessibilityAction.ACTION_IME_ENTER.id)+ }+ }+ "backspace" -> edit { text, start, end -> if (start != end) Edit(text.removeRange(start, end), start) else if (start > 0) Edit(text.removeRange(start - 1, start), start - 1) else null }+ "delete" -> edit { text, start, end -> if (start != end) Edit(text.removeRange(start, end), start) else if (end < text.length) Edit(text.removeRange(end, end + 1), start) else null }+ "left" -> edit { text, start, _ -> Edit(text, (start - 1).coerceAtLeast(0)) }+ "right" -> edit { text, _, end -> Edit(text, (end + 1).coerceAtMost(text.length)) }+ }+ }++ private fun type(typed: String) = edit { text, start, end -> Edit(text.replaceRange(start, end, typed), start + typed.length) }++ private data class Edit(val text: String, val cursor: Int)++ /** Changes the focused text field: its text and selection in, the new text and cursor out. */+ private fun edit(change: (String, Int, Int) -> Edit?) {+ val node = focused() ?: return+ if (!node.isEditable) return+ val showingHint = Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && node.isShowingHintText+ val text = if (showingHint) "" else node.text?.toString().orEmpty()+ val start = node.textSelectionStart.takeIf { it in 0..text.length } ?: text.length+ val end = node.textSelectionEnd.takeIf { it in start..text.length } ?: start+ val result = change(text, start, end) ?: return+ if (result.text != text) {+ node.performAction(+ AccessibilityNodeInfo.ACTION_SET_TEXT,+ Bundle().apply { putCharSequence(AccessibilityNodeInfo.ACTION_ARGUMENT_SET_TEXT_CHARSEQUENCE, result.text) },+ )+ }+ node.performAction(+ AccessibilityNodeInfo.ACTION_SET_SELECTION,+ Bundle().apply {+ putInt(AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_START_INT, result.cursor)+ putInt(AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_END_INT, result.cursor)+ },+ )+ }++ private fun focused(): AccessibilityNodeInfo? = findFocus(AccessibilityNodeInfo.FOCUS_INPUT)++ companion object {+ private const val TAG = "InputService"+ private const val TAP_MS = 40L+ private const val LONG_PRESS_MS = 450L+ private const val MIN_SWIPE_MS = 80L+ private const val MAX_GESTURE_MS = 3000L+ private const val TAP_SLOP_FRACTION = 0.015f+ private const val SCROLL_STEP_FRACTION = 0.12f+ private const val SCROLL_MS = 120L+ private const val SCROLL_GATHER_MS = 40L++ @Volatile private var instance: InputService? = null++ /** Whether the user turned it on (and Android has it running). */+ val running: Boolean get() = instance != null++ /** The PC's input; ignored while the service is off. */+ fun handle(input: MirrorInputEvent) {+ val service = instance ?: return+ service.main.post { service.handle(input) }+ }++ /** Whether it's turned on in Settings (it may not be running yet). */+ fun enabled(context: Context): Boolean {+ val enabled = Settings.Secure.getString(context.contentResolver, Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES).orEmpty()+ val me = ComponentName(context, InputService::class.java)+ return enabled.split(':').any { ComponentName.unflattenFromString(it) == me }+ }++ /** Android's accessibility settings, where the user turns it on. */+ fun settingsIntent(): android.content.Intent =+ android.content.Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS).addFlags(android.content.Intent.FLAG_ACTIVITY_NEW_TASK)+ }+}diff --git a/android/app/src/main/kotlin/app/nectarlink/android/ui/settings/SettingsScreen.kt b/android/app/src/main/kotlin/app/nectarlink/android/ui/settings/SettingsScreen.ktindex fd5630f..a26b4a0 100644--- a/android/app/src/main/kotlin/app/nectarlink/android/ui/settings/SettingsScreen.kt+++ b/android/app/src/main/kotlin/app/nectarlink/android/ui/settings/SettingsScreen.kt@@ -43,6 +43,7 @@ import androidx.compose.ui.semantics.semanticsimport androidx.compose.ui.unit.dpimport app.nectarlink.android.BuildConfigimport app.nectarlink.android.R+import app.nectarlink.android.mirror.InputServiceimport app.nectarlink.android.update.AppUpdaterimport app.nectarlink.android.update.CheckForUpdatesimport app.nectarlink.android.core.CoreState@@ -79,6 +80,10 @@ fun SettingsScreen(NotificationAccess(state.notificationAccess)}+ Section(stringResource(R.string.settings_control)) {+ ControlAccess(state.inputAccess)+ }+Section(stringResource(R.string.settings_appearance)) {Label(stringResource(R.string.settings_theme))Choice(@@ -220,6 +225,28 @@ private fun NotificationAccess(granted: Boolean) {}}+/** Control from the PC: Nectarlink's accessibility service, turned on in Android's settings. */+@Composable+private fun ControlAccess(on: Boolean) {+ val context = LocalContext.current+ Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth()) {+ Column(Modifier.weight(1f).padding(end = 12.dp)) {+ Text(stringResource(R.string.control_title), style = MaterialTheme.typography.titleSmall)+ Text(+ stringResource(if (on) R.string.control_on else R.string.control_off),+ style = MaterialTheme.typography.bodySmall,+ color = MaterialTheme.colorScheme.onSurfaceVariant,+ )+ }+ val open = { context.startActivity(InputService.settingsIntent()) }+ if (on) {+ OutlinedButton(onClick = open) { Text(stringResource(R.string.action_manage)) }+ } else {+ Button(onClick = open) { Text(stringResource(R.string.action_allow)) }+ }+ }+}+@Composableprivate fun Section(title: String, content: @Composable () -> Unit) {Text(diff --git a/android/app/src/main/res/values/strings.xml b/android/app/src/main/res/values/strings.xmlindex cbb78fd..d78435e 100644--- a/android/app/src/main/res/values/strings.xml+++ b/android/app/src/main/res/values/strings.xml@@ -67,6 +67,12 @@<string name="media_previous">Previous</string><string name="action_send_files">Send files</string><string name="action_send_folder">Send a folder</string>+ <string name="input_service_label">Nectarlink: control from your PC</string>+ <string name="input_service_description">Lets you use your PC\'s mouse and keyboard on this phone while its screen is shown on the PC: clicks become taps, drags swipes, and typing goes into the text field you\'re in. Nectarlink uses it only while you share your screen with a paired PC, and reads nothing else.</string>+ <string name="settings_control">Control from your PC</string>+ <string name="control_title">Use your PC\'s mouse and keyboard</string>+ <string name="control_on">On: while your screen is shown on your PC, you can tap, swipe and type from there.</string>+ <string name="control_off">While your screen is shown on your PC, tap, swipe and type from there. Turn on Nectarlink in Accessibility.</string><string name="channel_mirroring">Screen sharing</string><string name="channel_mirror_requests">Screen sharing requests</string><string name="mirror_request_title">%1$s wants to see your screen</string>diff --git a/android/app/src/main/res/xml/input_service.xml b/android/app/src/main/res/xml/input_service.xmlnew file mode 100644index 0000000..e8cacf1--- /dev/null+++ b/android/app/src/main/res/xml/input_service.xml@@ -0,0 +1,11 @@+<?xml version="1.0" encoding="utf-8"?>+<!-- The PC's mouse and keyboard while the screen is mirrored: gestures,+ and typing into the focused text field. It listens to no events. -->+<accessibility-service xmlns:android="http://schemas.android.com/apk/res/android"+ android:accessibilityEventTypes="typeWindowStateChanged"+ android:accessibilityFeedbackType="feedbackGeneric"+ android:accessibilityFlags="flagDefault"+ android:canPerformGestures="true"+ android:canRetrieveWindowContent="true"+ android:description="@string/input_service_description"+ android:notificationTimeout="100" />diff --git a/core/nectarlink-cli/src/main.rs b/core/nectarlink-cli/src/main.rsindex 61a3780..9db0e96 100644--- a/core/nectarlink-cli/src/main.rs+++ b/core/nectarlink-cli/src/main.rs@@ -176,6 +176,13 @@ enum Command {#[arg(long)]at: Vec<std::net::SocketAddr>,},+ /// Use a paired phone's screen: tap at x,y (fractions of the screen),+ /// swipe, scroll, press a key (back, home, recents, enter...) or type.+ Input {+ device: String,+ #[command(subcommand)]+ action: InputArg,+ },/// Act as a phone sharing its screen (use with --as-phone): when a PC/// asks, streams an H.264 file (Annex B, with access unit delimiters) in/// a loop at `fps`. Stays online.@@ -283,6 +290,15 @@ impl From<MediaCommandArg> for MediaAction {static MEDIA_COMMANDS: std::sync::OnceLock<tokio::sync::mpsc::UnboundedSender<(MediaAction, Option<u64>)>> =std::sync::OnceLock::new();+#[derive(Debug, Subcommand)]+enum InputArg {+ Tap { x: f32, y: f32 },+ Swipe { x1: f32, y1: f32, x2: f32, y2: f32 },+ Scroll { x: f32, y: f32, notches: f32 },+ Key { key: String },+ Type { text: String },+}+#[derive(Debug, Subcommand)]enum SmsArg {/// The latest conversations.@@ -735,6 +751,43 @@ async fn run(cli: &Cli, node: &Node) -> Result<()> {node.update_power(node_power(cli), offers).await;watch(node, true).await?;}+ Command::Input { device, action } => {+ use nectarlink_core::{MirrorInput, TouchAction};+ let mut offers = cli.offers.clone();+ offers.push(nectarlink_core::MIRROR_VIEW.into());+ node.update_power(node_power(cli), offers).await;+ let id = resolve(node, device)?;+ wait_until_online(node, id).await?;+ let touch = |action, x, y| MirrorInput::Touch { action, x, y };+ let inputs = match action {+ InputArg::Tap { x, y } => {+ vec![touch(TouchAction::Down, *x, *y), touch(TouchAction::Up, *x, *y)]+ }+ InputArg::Swipe { x1, y1, x2, y2 } => (0..=10)+ .map(|i| {+ let t = i as f32 / 10.0;+ let action = match i {+ 0 => TouchAction::Down,+ 10 => TouchAction::Up,+ _ => TouchAction::Move,+ };+ touch(action, x1 + (x2 - x1) * t, y1 + (y2 - y1) * t)+ })+ .collect(),+ InputArg::Scroll { x, y, notches } => {+ vec![MirrorInput::Scroll { x: *x, y: *y, dx: 0.0, dy: *notches }]+ }+ InputArg::Key { key } => vec![MirrorInput::Key { key: key.clone() }],+ InputArg::Type { text } => vec![MirrorInput::Text { text: text.clone() }],+ };+ for input in inputs {+ node.mirror_input(id, input).await.context("not sent")?;+ tokio::time::sleep(Duration::from_millis(30)).await;+ }+ // Let it leave before this client goes.+ tokio::time::sleep(Duration::from_millis(500)).await;+ println!("Sent.");+ }Command::Mirror { device, out, seconds, at } => {let recording = std::sync::Arc::new(Recording::default());*recording.file.lock().unwrap() =diff --git a/core/nectarlink-core/src/config.rs b/core/nectarlink-core/src/config.rsindex c75641c..941c2d4 100644--- a/core/nectarlink-core/src/config.rs+++ b/core/nectarlink-core/src/config.rs@@ -147,6 +147,10 @@ pub trait Platform: Send + Sync + 'static {/// The PC stopped watching: stop sharing the screen.fn mirror_stop_requested(&self, _peer: &nectarlink_protocol::DeviceId) {}+ /// The PC's mouse or keyboard on this phone's mirrored screen (checked,+ /// and only while it offers `mirror.input`). Must return quickly.+ fn mirror_input(&self, _peer: &nectarlink_protocol::DeviceId, _input: crate::MirrorInput) {}+/// The PC's decoder needs a fresh start: encode a keyframe next.fn mirror_keyframe_requested(&self, _peer: &nectarlink_protocol::DeviceId) {}diff --git a/core/nectarlink-core/src/features.rs b/core/nectarlink-core/src/features.rsindex 358a431..390c4c5 100644--- a/core/nectarlink-core/src/features.rs+++ b/core/nectarlink-core/src/features.rs@@ -658,7 +658,12 @@ pub const FEATURES: &[FeatureDef] = &[FeatureDef {id: "mirroring.control",group: FeatureGroup::Mirroring,- requires: &[phone("mirror.capture", UPDATE), phone("mirror.input", ASSIST)],+ requires: &[+ phone("mirror.capture", UPDATE),+ phone("mirror.input", ASSIST),+ desktop("mirror.view", UPDATE),+ DeviceToggle("mirroring"),+ ],partial: None,},FeatureDef {diff --git a/core/nectarlink-core/src/lib.rs b/core/nectarlink-core/src/lib.rsindex d3e2467..71d640d 100644--- a/core/nectarlink-core/src/lib.rs+++ b/core/nectarlink-core/src/lib.rs@@ -42,10 +42,15 @@ pub use nectarlink_protocol::messages::clip::{pub use nectarlink_protocol::{DeviceId, PacketKind,messages::{- Battery, CLIP_MAX_BYTES, CallState, DeviceInfo, DeviceKind, MediaPlayer, MirrorConfig, MirrorStart,- Notification, NotificationAction, PhotoNew as Photo, PowerLevel, SmsMessage, SmsPart, SmsThread,+ Battery, CLIP_MAX_BYTES, CallState, DeviceInfo, DeviceKind, MediaPlayer, MirrorConfig, MirrorInput,+ MirrorStart, Notification, NotificationAction, PhotoNew as Photo, PowerLevel, SmsMessage, SmsPart,+ SmsThread, TouchAction,calls::{CONTROL as CALLS_CONTROL, SHOW as CALLS_SHOW, STATE as CALLS_STATE},- mirror::{CAPTURE as MIRROR_CAPTURE, VIEW as MIRROR_VIEW},+ mirror::{+ CAPTURE as MIRROR_CAPTURE, INPUT as MIRROR_INPUT, MAX_TEXT_BYTES as MIRROR_MAX_TEXT_BYTES,+ VIEW as MIRROR_VIEW,+ },+ mirror_keys,photos::{MAX_THUMB_BYTES as PHOTO_MAX_THUMB_BYTES, READ as PHOTOS_READ, SHOW as PHOTOS_SHOW},sms::{READ as SMS_READ, SEND as SMS_SEND, SHOW as SMS_SHOW},},diff --git a/core/nectarlink-core/src/mirror.rs b/core/nectarlink-core/src/mirror.rsindex c322ce3..dd374c6 100644--- a/core/nectarlink-core/src/mirror.rs+++ b/core/nectarlink-core/src/mirror.rs@@ -15,7 +15,7 @@ use std::sync::{use iroh::endpoint::{RecvStream, SendStream, VarInt};use nectarlink_protocol::{DeviceId, Envelope, ErrorCode, PacketKind,- messages::{MirrorConfig, MirrorStart, StreamHeader, mirror, types},+ messages::{MirrorConfig, MirrorInput, MirrorStart, StreamHeader, mirror, types},read_video_packet, video_packet_header, write_frame,};use tokio::sync::mpsc;@@ -64,6 +64,18 @@ pub(crate) async fn stop(session: &Session) -> Result<()> {Ok(())}+/// Mouse and keyboard on a phone's mirrored screen (not answered: input+/// is only worth it right away).+pub(crate) async fn input(shared: &Shared, session: &Session, input: MirrorInput) -> Result<()> {+ if !shared.toggle_on(&session.peer, TOGGLE) {+ return Err(Error::Denied);+ }+ if !input.is_valid() {+ return Err(Error::Protocol("invalid input".into()));+ }+ session.send(Envelope::new(types::MIRROR_INPUT, &input)?).await+}+pub(crate) async fn request_keyframe(session: &Session) {let _ = session.send(Envelope::empty(types::MIRROR_KEYFRAME)).await;}@@ -142,6 +154,14 @@ pub(crate) async fn handle(shared: &Arc<Shared>, session: &Arc<Session>, env: &Etypes::MIRROR_KEYFRAME => {tokio::task::spawn_blocking(move || platform.mirror_keyframe_requested(&peer));}+ types::MIRROR_INPUT => {+ let input: MirrorInput = env.body()?;+ let allowed = shared.toggle_on(&peer, TOGGLE)+ && shared.local_capabilities().iter().any(|c| c == mirror::INPUT);+ if allowed && input.is_valid() {+ platform.mirror_input(&peer, input);+ }+ }_ => return Ok(false),}Ok(true)diff --git a/core/nectarlink-core/src/node.rs b/core/nectarlink-core/src/node.rsindex dabfc9d..43f672f 100644--- a/core/nectarlink-core/src/node.rs+++ b/core/nectarlink-core/src/node.rs@@ -948,6 +948,12 @@ impl Node {}}+ /// The PC's mouse and keyboard on a phone's mirrored screen.+ pub async fn mirror_input(&self, peer: DeviceId, input: crate::MirrorInput) -> Result<()> {+ let session = self.connected(&peer)?;+ crate::mirror::input(&self.shared, &session, input).await+ }+/// Opens this phone's video stream to a PC that asked for the screen.pub async fn mirror_open(&self, peer: DeviceId) -> Result<crate::MirrorStream> {let session = self.connected(&peer)?;diff --git a/core/nectarlink-core/tests/two_devices.rs b/core/nectarlink-core/tests/two_devices.rsindex 6821c06..31ff25d 100644--- a/core/nectarlink-core/tests/two_devices.rs+++ b/core/nectarlink-core/tests/two_devices.rs@@ -95,6 +95,9 @@ impl Platform for RecordingPlatform {fn mirror_keyframe_requested(&self, _peer: &nectarlink_core::DeviceId) {self.mirror_asks.lock().unwrap().push("keyframe".into());}+ fn mirror_input(&self, _peer: &nectarlink_core::DeviceId, input: nectarlink_core::MirrorInput) {+ self.mirror_asks.lock().unwrap().push(format!("{input:?}"));+ }fn sms_threads(&self, limit: u32) -> Result<Vec<nectarlink_core::SmsThread>, String> {let thread = |i: u32| nectarlink_core::SmsThread {id: i.to_string(),@@ -1032,7 +1035,12 @@ async fn folders_arrive_with_their_layout() {async fn the_phone_screen_streams_to_the_pc() {use nectarlink_core::{MirrorSend, PacketKind};let mut pc = device_with("Desktop", DeviceKind::Desktop, &[nectarlink_core::MIRROR_VIEW]).await;- let mut phone = device_with("Pixel", DeviceKind::Phone, &[nectarlink_core::MIRROR_CAPTURE]).await;+ let mut phone = device_with(+ "Pixel",+ DeviceKind::Phone,+ &[nectarlink_core::MIRROR_CAPTURE, nectarlink_core::MIRROR_INPUT],+ )+ .await;pair_qr(&mut pc, &mut phone).await;let (pc_id, phone_id) = (pc.node.device_id(), phone.node.device_id());@@ -1063,6 +1071,14 @@ async fn the_phone_screen_streams_to_the_pc() {assert_eq!(*screen.got.lock().unwrap(), ["config 1080x2400", "key 1 90000", "frame 16667 4000"]);pc.node.mirror_keyframe(phone_id).await;+ // The PC's mouse on the phone's screen; nonsense never leaves the PC.+ use nectarlink_core::{MirrorInput, TouchAction};+ pc.node+ .mirror_input(phone_id, MirrorInput::Touch { action: TouchAction::Down, x: 0.5, y: 0.25 })+ .await+ .unwrap();+ pc.node.mirror_input(phone_id, MirrorInput::Key { key: "back".into() }).await.unwrap();+ assert!(pc.node.mirror_input(phone_id, MirrorInput::Key { key: "power".into() }).await.is_err());// The PC stops watching: the phone hears it, and its stream closes.pc.node.mirror_stop(phone_id).await;wait_for(&mut pc, "stopped", |e| matches!(e, NodeEvent::Mirroring { on: false, .. }).then_some(())).await;@@ -1075,7 +1091,9 @@ async fn the_phone_screen_streams_to_the_pc() {}assert!(stream.is_closed(), "the phone's stream closes");let asks = phone.platform.mirror_asks.lock().unwrap().clone();- assert!(asks.contains(&"keyframe".to_owned()) && asks.contains(&"stop".to_owned()), "{asks:?}");+ for wanted in ["keyframe", "Touch(Down)", "Key(back)", "stop"] {+ assert!(asks.iter().any(|a| a == wanted), "{wanted}: {asks:?}");+ }}#[tokio::test(flavor = "multi_thread")]diff --git a/core/nectarlink-ffi/src/lib.rs b/core/nectarlink-ffi/src/lib.rsindex 84b01bb..d6251b5 100644--- a/core/nectarlink-ffi/src/lib.rs+++ b/core/nectarlink-ffi/src/lib.rs@@ -455,6 +455,70 @@ pub enum VideoPacketKind {Keyframe,}+/// The PC's mouse or keyboard on the mirrored screen. Positions are+/// fractions of the screen (0 to 1).+#[derive(Clone, PartialEq, uniffi::Enum)]+pub enum MirrorInputEvent {+ Touch {+ action: TouchPhase,+ x: f32,+ y: f32,+ },+ /// The mouse wheel, in notches (positive: down / right).+ Scroll {+ x: f32,+ y: f32,+ dx: f32,+ dy: f32,+ },+ /// "back", "home", "recents", "enter", "backspace", "delete", "left",+ /// "right", "up", "down", "tab" or "notifications".+ Key {+ key: String,+ },+ Text {+ text: String,+ },+}++/// Never prints typed text (protocol v0 §11).+impl std::fmt::Debug for MirrorInputEvent {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ match self {+ MirrorInputEvent::Text { text } => write!(f, "Text({} bytes)", text.len()),+ MirrorInputEvent::Touch { action, .. } => write!(f, "Touch({action:?})"),+ MirrorInputEvent::Scroll { .. } => f.write_str("Scroll"),+ MirrorInputEvent::Key { key } => write!(f, "Key({key})"),+ }+ }+}++#[derive(Debug, Clone, Copy, PartialEq, Eq, uniffi::Enum)]+pub enum TouchPhase {+ Down,+ Move,+ Up,+}++impl From<core::MirrorInput> for MirrorInputEvent {+ fn from(input: core::MirrorInput) -> Self {+ match input {+ core::MirrorInput::Touch { action, x, y } => MirrorInputEvent::Touch {+ action: match action {+ core::TouchAction::Down => TouchPhase::Down,+ core::TouchAction::Move => TouchPhase::Move,+ core::TouchAction::Up => TouchPhase::Up,+ },+ x,+ y,+ },+ core::MirrorInput::Scroll { x, y, dx, dy } => MirrorInputEvent::Scroll { x, y, dx, dy },+ core::MirrorInput::Key { key } => MirrorInputEvent::Key { key },+ core::MirrorInput::Text { text } => MirrorInputEvent::Text { text },+ }+ }+}+/// What became of a video packet.#[derive(Debug, Clone, Copy, PartialEq, Eq, uniffi::Enum)]pub enum MirrorSendResult {@@ -1108,6 +1172,9 @@ pub trait Platform: Send + Sync {fn mirror_stop_requested(&self, pc_id: String);/// The PC needs a keyframe.fn mirror_keyframe_requested(&self, pc_id: String);+ /// The PC's mouse or keyboard on the mirrored screen (only while this+ /// phone offers `mirror.input`). Return quickly.+ fn mirror_input(&self, pc_id: String, input: MirrorInputEvent);/// A PC asked for the latest conversations, newest first.fn sms_threads(&self, limit: u32) -> Vec<SmsThread>;/// A PC asked for a conversation's messages before `before` (Unix ms;@@ -1193,6 +1260,9 @@ impl core::Platform for PlatformAdapter {fn mirror_keyframe_requested(&self, peer: &DeviceId) {self.0.mirror_keyframe_requested(peer.to_string());}+ fn mirror_input(&self, peer: &DeviceId, input: core::MirrorInput) {+ self.0.mirror_input(peer.to_string(), input.into());+ }fn sms_threads(&self, limit: u32) -> Result<Vec<core::SmsThread>, String> {Ok(self.0diff --git a/core/nectarlink-protocol/src/messages.rs b/core/nectarlink-protocol/src/messages.rsindex 37c500e..8e4d51c 100644--- a/core/nectarlink-protocol/src/messages.rs+++ b/core/nectarlink-protocol/src/messages.rs@@ -53,6 +53,7 @@ pub mod types {pub const MIRROR_START: &str = "mirror.start";pub const MIRROR_STOP: &str = "mirror.stop";pub const MIRROR_KEYFRAME: &str = "mirror.keyframe";+ pub const MIRROR_INPUT: &str = "mirror.input";}/// What kind of device this is.@@ -478,6 +479,10 @@ pub mod mirror {pub const VERSION: u32 = 1;/// Stream reset code: mirroring stopped.pub const STOPPED: u32 = 11;+ /// Offered by phones that take input from the PC while mirrored.+ pub const INPUT: &str = "mirror.input";+ /// Typed text in one message: at most this many bytes.+ pub const MAX_TEXT_BYTES: usize = 4096;pub const H264: &str = "h264";}@@ -492,6 +497,80 @@ pub struct MirrorStart {pub bitrate: u32,}+/// Body of `mirror.input`: the PC's mouse and keyboard, on the mirrored+/// screen. Positions are fractions of the screen (0 at the left or top, 1+/// at the right or bottom), so they hold at any size.+#[derive(Clone, PartialEq, Serialize, Deserialize)]+#[serde(tag = "type", rename_all = "lowercase")]+pub enum MirrorInput {+ /// A finger: down, moved, up (the phone turns these into taps, long+ /// presses and swipes).+ Touch { action: TouchAction, x: f32, y: f32 },+ /// The mouse wheel at a point, in notches (positive: down / right).+ Scroll { x: f32, y: f32, dx: f32, dy: f32 },+ /// A key with no text: one of [`mirror_keys`].+ Key { key: String },+ /// Typed text, into what has the focus.+ Text { text: String },+}++#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "lowercase")]+pub enum TouchAction {+ Down,+ Move,+ Up,+}++/// Keys `mirror.input` can send.+pub mod mirror_keys {+ pub const BACK: &str = "back";+ pub const HOME: &str = "home";+ pub const RECENTS: &str = "recents";+ pub const ENTER: &str = "enter";+ pub const BACKSPACE: &str = "backspace";+ pub const DELETE: &str = "delete";+ pub const LEFT: &str = "left";+ pub const RIGHT: &str = "right";+ pub const UP: &str = "up";+ pub const DOWN: &str = "down";+ pub const TAB: &str = "tab";+ pub const NOTIFICATIONS: &str = "notifications";+ pub const ALL: &[&str] =+ &[BACK, HOME, RECENTS, ENTER, BACKSPACE, DELETE, LEFT, RIGHT, UP, DOWN, TAB, NOTIFICATIONS];+}++/// Never prints typed text (protocol v0 §11).+impl std::fmt::Debug for MirrorInput {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ match self {+ MirrorInput::Touch { action, .. } => write!(f, "Touch({action:?})"),+ MirrorInput::Scroll { .. } => f.write_str("Scroll"),+ MirrorInput::Key { key } => write!(f, "Key({key})"),+ MirrorInput::Text { text } => write!(f, "Text({} bytes)", text.len()),+ }+ }+}++impl MirrorInput {+ pub fn is_valid(&self) -> bool {+ let on_screen = |v: f32| v.is_finite() && (0.0..=1.0).contains(&v);+ match self {+ MirrorInput::Touch { x, y, .. } => on_screen(*x) && on_screen(*y),+ MirrorInput::Scroll { x, y, dx, dy } => {+ on_screen(*x)+ && on_screen(*y)+ && dx.is_finite()+ && dy.is_finite()+ && dx.abs() <= 100.0+ && dy.abs() <= 100.0+ }+ MirrorInput::Key { key } => mirror_keys::ALL.contains(&key.as_str()),+ MirrorInput::Text { text } => !text.is_empty() && text.len() <= mirror::MAX_TEXT_BYTES,+ }+ }+}+/// The format of a mirroring stream (a config packet's data, in CBOR).#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]pub struct MirrorConfig {@@ -1165,6 +1244,20 @@ mod tests {assert!(!format!("{:?}", offer("Secret")).contains("Secret"));}+ #[test]+ fn mirror_input_is_checked() {+ let touch = MirrorInput::Touch { action: TouchAction::Down, x: 0.5, y: 1.0 };+ assert!(touch.is_valid());+ let env = Envelope::new(types::MIRROR_INPUT, &touch).unwrap();+ assert_eq!(env.body::<MirrorInput>().unwrap(), touch);+ assert!(!MirrorInput::Touch { action: TouchAction::Up, x: 1.5, y: 0.0 }.is_valid());+ assert!(!MirrorInput::Touch { action: TouchAction::Up, x: f32::NAN, y: 0.0 }.is_valid());+ assert!(MirrorInput::Key { key: "back".into() }.is_valid());+ assert!(!MirrorInput::Key { key: "power".into() }.is_valid());+ assert!(!MirrorInput::Text { text: String::new() }.is_valid());+ assert!(!format!("{:?}", MirrorInput::Text { text: "secret".into() }).contains("secret"));+ }+#[test]fn texts_to_send_are_checked() {let send = SmsSend { to: vec!["+15550100".into()], body: "On my way".into() };diff --git a/desktop/app/qml/MirrorWindow.qml b/desktop/app/qml/MirrorWindow.qmlindex c0924e2..955f99d 100644--- a/desktop/app/qml/MirrorWindow.qml+++ b/desktop/app/qml/MirrorWindow.qml@@ -43,6 +43,117 @@ Window {id: videoanchors.fill: parentstream: Mirror.device+ focus: true++ // Where on the phone's screen a point in the window is (0 to 1).+ function at(x, y) {+ const r = pictureRect()+ return { x: (x - r.x) / Math.max(1, r.width), y: (y - r.y) / Math.max(1, r.height),+ inside: x >= r.x && x <= r.x + r.width && y >= r.y && y <= r.y + r.height }+ }++ // The mouse: left is a finger, right is Back, middle is Home.+ MouseArea {+ anchors.fill: parent+ enabled: Mirror.canControl && Mirror.phase === "showing"+ acceptedButtons: Qt.LeftButton | Qt.RightButton | Qt.MiddleButton+ cursorShape: enabled ? Qt.PointingHandCursor : Qt.ArrowCursor+ property bool down: false+ property double lastMove: 0+ onPressed: (mouse) => {+ video.forceActiveFocus()+ const p = video.at(mouse.x, mouse.y)+ if (mouse.button === Qt.RightButton) { Mirror.key("back"); return }+ if (mouse.button === Qt.MiddleButton) { Mirror.key("home"); return }+ if (!p.inside) return+ down = true+ Mirror.touch("down", p.x, p.y)+ }+ onPositionChanged: (mouse) => {+ if (!down) return+ // About 60 a second is plenty for a finger.+ const now = Date.now()+ if (now - lastMove < 16) return+ lastMove = now+ const p = video.at(mouse.x, mouse.y)+ Mirror.touch("move", p.x, p.y)+ }+ onReleased: (mouse) => {+ if (!down) return+ down = false+ const p = video.at(mouse.x, mouse.y)+ Mirror.touch("up", p.x, p.y)+ }+ onWheel: (wheel) => {+ const p = video.at(wheel.x, wheel.y)+ if (p.inside)+ Mirror.scroll(p.x, p.y, -wheel.angleDelta.x / 120, -wheel.angleDelta.y / 120)+ }+ }++ // The keyboard: text goes into the phone's text field; a few keys+ // have phone meanings.+ Keys.onPressed: (event) => {+ if (!Mirror.canControl || Mirror.phase !== "showing")+ return+ const keys = {}+ keys[Qt.Key_Escape] = "back"+ keys[Qt.Key_Back] = "back"+ keys[Qt.Key_Home] = "home"+ keys[Qt.Key_Return] = "enter"+ keys[Qt.Key_Enter] = "enter"+ keys[Qt.Key_Backspace] = "backspace"+ keys[Qt.Key_Delete] = "delete"+ keys[Qt.Key_Left] = "left"+ keys[Qt.Key_Right] = "right"+ keys[Qt.Key_Up] = "up"+ keys[Qt.Key_Down] = "down"+ keys[Qt.Key_Tab] = "tab"+ if ((event.modifiers & Qt.ControlModifier) && event.key === Qt.Key_V) {+ Mirror.paste()+ event.accepted = true+ } else if (keys[event.key] !== undefined) {+ Mirror.key(keys[event.key])+ event.accepted = true+ } else if (event.text.length > 0 && !(event.modifiers & (Qt.ControlModifier | Qt.AltModifier))+ && event.text.charCodeAt(0) >= 32) {+ Mirror.text(event.text)+ event.accepted = true+ }+ }+ }++ // How to control it, until the phone allows it.+ Rectangle {+ anchors.left: parent.left+ anchors.right: parent.right+ anchors.bottom: parent.bottom+ anchors.margins: 12+ height: hint.implicitHeight + 20+ radius: Theme.radiusMd+ visible: Mirror.phase === "showing" && video.frameSize.width > 0 && !Mirror.canControl && !hintClose.closed+ color: Qt.rgba(0, 0, 0, 0.72)+ Txt {+ id: hint+ anchors.left: parent.left+ anchors.right: hintClose.left+ anchors.margins: 10+ anchors.verticalCenter: parent.verticalCenter+ wrapMode: Text.WordWrap+ role: "bodySmall"+ color: "white"+ text: qsTr("To use your mouse and keyboard on the phone, open Nectarlink on the phone and turn on Control from your PC in Settings.")+ }+ IconButton {+ id: hintClose+ property bool closed: false+ anchors.right: parent.right+ anchors.verticalCenter: parent.verticalCenter+ iconPath: Icons.close+ iconColor: "white"+ label: qsTr("Hide")+ onClicked: closed = true+ }}// Before the picture: waiting for the phone, or why it ended.diff --git a/desktop/app/src/bridge/mirror.rs b/desktop/app/src/bridge/mirror.rsindex 9785614..f23b535 100644--- a/desktop/app/src/bridge/mirror.rs+++ b/desktop/app/src/bridge/mirror.rs@@ -31,6 +31,8 @@ pub mod qobject {#[qproperty(QString, phase)]/// Why it ended, when there's something to say.#[qproperty(QString, reason)]+ /// The PC's mouse and keyboard work on the phone.+ #[qproperty(bool, can_control, cxx_name = "canControl")]type Mirror = super::MirrorRust;}@@ -44,6 +46,22 @@ pub mod qobject {/// Closes the window and stops mirroring.#[qinvokable]fn stop(self: Pin<&mut Mirror>);+ /// A finger on the screen: "down", "move" or "up", at a fraction of+ /// the screen's width and height.+ #[qinvokable]+ fn touch(self: &Mirror, action: &QString, x: f64, y: f64);+ /// The mouse wheel, in notches (positive: down / right).+ #[qinvokable]+ fn scroll(self: &Mirror, x: f64, y: f64, dx: f64, dy: f64);+ /// A key without text ("back", "home", "enter"...).+ #[qinvokable]+ fn key(self: &Mirror, key: &QString);+ /// Typed text.+ #[qinvokable]+ fn text(self: &Mirror, text: &QString);+ /// Types the PC's clipboard text on the phone.+ #[qinvokable]+ fn paste(self: &Mirror);}}@@ -53,12 +71,13 @@ pub struct MirrorRust {name: QString,phase: QString,reason: QString,+ can_control: bool,shown: Option<DeviceId>,}impl cxx_qt::Initialize for qobject::Mirror {fn initialize(self: Pin<&mut Self>) {- super::subscribe(self.qt_thread(), Changes::MIRROR, Self::refresh);+ super::subscribe(self.qt_thread(), Changes::MIRROR | Changes::CAPABILITIES, Self::refresh);}}@@ -68,6 +87,11 @@ impl qobject::Mirror {self.as_mut().set_phase(QString::default());return;};+ let control = crate::core_host::host().hub.read(|s| {+ s.matrices.get(&device).and_then(|m| m.state("mirroring.control"))+ == Some(nectarlink_core::FeatureState::Available)+ });+ self.as_mut().set_can_control(control);let (phase, reason) = match mirror::phase(&device) {None => ("", String::new()),Some(Phase::Asking) => ("asking", String::new()),@@ -91,6 +115,59 @@ impl qobject::Mirror {self.refresh();}+ fn send(&self, input: nectarlink_core::MirrorInput) {+ if let (Some(device), true) = (self.rust().shown, self.rust().can_control) {+ mirror::input(device, input);+ }+ }++ pub fn touch(&self, action: &QString, x: f64, y: f64) {+ use nectarlink_core::TouchAction;+ let action = match String::from(action).as_str() {+ "down" => TouchAction::Down,+ "move" => TouchAction::Move,+ "up" => TouchAction::Up,+ _ => return,+ };+ self.send(nectarlink_core::MirrorInput::Touch { action, x: fraction(x), y: fraction(y) });+ }++ pub fn scroll(&self, x: f64, y: f64, dx: f64, dy: f64) {+ self.send(nectarlink_core::MirrorInput::Scroll {+ x: fraction(x),+ y: fraction(y),+ dx: dx.clamp(-100.0, 100.0) as f32,+ dy: dy.clamp(-100.0, 100.0) as f32,+ });+ }++ pub fn key(&self, key: &QString) {+ self.send(nectarlink_core::MirrorInput::Key { key: String::from(key) });+ }++ pub fn text(&self, text: &QString) {+ let text = String::from(text);+ if !text.is_empty() && text.len() <= nectarlink_core::MIRROR_MAX_TEXT_BYTES {+ self.send(nectarlink_core::MirrorInput::Text { text });+ }+ }++ pub fn paste(&self) {+ if let crate::win::clipboard::Clip::Text(text) = crate::win::clipboard::read() {+ // Long text goes in pieces, each a whole number of characters.+ let mut piece = String::new();+ for c in text.chars() {+ if piece.len() + c.len_utf8() > nectarlink_core::MIRROR_MAX_TEXT_BYTES {+ self.send(nectarlink_core::MirrorInput::Text { text: std::mem::take(&mut piece) });+ }+ piece.push(c);+ }+ if !piece.is_empty() {+ self.send(nectarlink_core::MirrorInput::Text { text: piece });+ }+ }+ }+pub fn stop(mut self: Pin<&mut Self>) {if let Some(id) = self.as_mut().rust_mut().shown.take() {mirror::stop(id);@@ -100,3 +177,8 @@ impl qobject::Mirror {self.set_phase(QString::default());}}++/// A position on the screen, kept on it.+fn fraction(v: f64) -> f32 {+ if v.is_finite() { v.clamp(0.0, 1.0) as f32 } else { 0.0 }+}diff --git a/desktop/app/src/mirror.rs b/desktop/app/src/mirror.rsindex 56f2987..d913a1a 100644--- a/desktop/app/src/mirror.rs+++ b/desktop/app/src/mirror.rs@@ -101,6 +101,27 @@ pub fn on_event(event: &NodeEvent) {}}+/// The PC's mouse and keyboard on the shown phone, sent in order.+pub fn input(device: DeviceId, input: nectarlink_core::MirrorInput) {+ static QUEUE: std::sync::OnceLock<+ tokio::sync::mpsc::UnboundedSender<(DeviceId, nectarlink_core::MirrorInput)>,+ > = std::sync::OnceLock::new();+ let queue = QUEUE.get_or_init(|| {+ let (queue, mut inputs) = tokio::sync::mpsc::unbounded_channel();+ core_host::spawn(async move {+ while let Some((device, input)) = inputs.recv().await {+ if let Some(node) = core_host::node()+ && let Err(e) = node.mirror_input(device, input).await+ {+ tracing::debug!(error = %e, "input didn't reach the phone");+ }+ }+ });+ queue+ });+ let _ = queue.send((device, input));+}+/// Where the core puts a phone's video: only for phones this PC asked.pub fn sink(device: &DeviceId) -> Option<Arc<dyn MirrorSink>> {matches!(phase(device), Some(Phase::Asking | Phase::Showing))diff --git a/docs/protocol/mirror.md b/docs/protocol/mirror.mdindex 3f8401e..b4f8bc8 100644--- a/docs/protocol/mirror.md+++ b/docs/protocol/mirror.md@@ -5,7 +5,7 @@A PC shows a phone's screen. The phone's user agrees each time (Androidasks); the phone then streams its screen as H.264 on a stream of its own.-This version is view-only: controlling the phone comes later.+The PC can also use the phone with its mouse and keyboard (§4).## 1. Capabilities@@ -13,6 +13,7 @@ This version is view-only: controlling the phone comes later.|---|---|---|| `mirror.capture` | phone | Shares its screen when its user agrees || `mirror.view` | PC | Shows a phone's screen |+| `mirror.input` | phone | Takes the PC's mouse and keyboard while mirrored (Assist: an accessibility service the user turns on; Elevated: injected input) |Both devices must allow it: the `mirroring` device toggle, on by default,on each side.@@ -62,7 +63,33 @@ u64 time // capture time in microseconds, big-endian (only differences meanPackets are at most 8 MiB. Video is BT.709, limited range.-## 4. Latency over completeness+## 4. Input++```+t = "mirror.input" b = { type: "touch", action: "down" | "move" | "up", x: float, y: float }+ | { type: "scroll", x: float, y: float, dx: float, dy: float }+ | { type: "key", key: text }+ | { type: "text", text: text }+```++Sent by the PC, not answered (input is only worth it right away), and+only to phones that offer `mirror.input`. Positions are fractions of the+screen as the phone shows it now (0 at the left or top, 1 at the right or+bottom), so they hold at any size and rotation.++- `touch`: one finger. At Assist, Android plays a gesture whole, so the+ phone turns each down–up into a tap (barely moved), a long press (held+ 450 ms or more) or a swipe along the way it went, when it comes up.+- `scroll`: the mouse wheel at a point, in notches (positive: down or+ right); the phone swipes the other way.+- `key`: `back`, `home`, `recents`, `notifications`, `enter`, `backspace`,+ `delete`, `left`, `right`, `up`, `down` or `tab`. Others are dropped.+- `text`: typed text (at most 4 KiB), into the focused text field.++The Windows app maps the left button to a finger, right-click to Back,+middle-click to Home and Ctrl+V to typing the PC's clipboard.++## 5. Latency over completenessThe stream is reliable, so a slow network would otherwise build up delay.Instead, the phone keeps only a few packets waiting to go out: when that's@@ -71,7 +98,7 @@ its encoder for one. The PC likewise decodes everything it gets but showsonly the newest picture when it's behind, and asks for a keyframe when apicture doesn't decode.-## 5. Privacy+## 6. PrivacyThe screen is never recorded or logged by either side. Android shows thatthe screen is being shared (in the status bar), and the user can stop it