Skip to content

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

The phone as touchpad, keyboard and presentation remote for the PC

Bee107cd83e0128
diff --git a/README.md b/README.md
index 6202598..a818402 100644
--- a/README.md
+++ b/README.md
@@ -128,6 +128,17 @@ tests; there are no releases yet.
clipboard, or save one or many to a folder you pick (`Downloads\Nectarlink`
by default). New photos and screenshots from the phone also pop up on the PC
with a preview, ready to save or copy.
+- **Touchpad, keyboard and presentation remote**: control the PC from the
+ phone — a touchpad with one-finger move, tap to click, two-finger tap for
+ right-click, two-finger scroll, double-tap-and-hold drag and adjustable
+ speed; soft-keyboard typing with a bar of modifier and special keys (`Ctrl`,
+ `Alt`, `Shift`, `Win`, `Esc`, `Tab`, arrows, `Home`/`End`, `PgUp`/`PgDn`,
+ `Del` and shortcuts); and a presentation mode with Next/Previous slide (plus
+ the phone's volume buttons while open), Start/End show, Black screen, and a
+ hold-for-laser pointer that draws an accent-colored dot on the PC screen
+ following the phone's gyroscope or finger. Off by default on the PC, with a
+ one-time prompt the first time a phone asks and a per-phone toggle in
+ Settings.
- **Media** both ways: what plays on the phone shows on the PC, in the app and
in Windows' own media flyout (so the keyboard's media keys work too), and
what plays on the PC shows in the phone's media controls, with artwork and
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 871d14c..f695ca0 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
@@ -120,6 +120,13 @@ class Core(context: Context, private val scope: CoroutineScope) : EventListener
* it removes. Runs once the node is up.
*/
private val notificationOps = Channel<suspend (NectarlinkNode) -> Unit>(Channel.UNLIMITED)
+
+ /**
+ * Remote input for PCs, sent one after another: a button's release must
+ * never overtake its press (or the PC's button would stay down), nor a
+ * laser update its "off".
+ */
+ private val remoteOps = Channel<suspend (NectarlinkNode) -> Unit>(Channel.UNLIMITED)
private val _state = MutableStateFlow(CoreState())
private val _messages = MutableSharedFlow<String>(extraBufferCapacity = 8)
private var node: NectarlinkNode? = null
@@ -203,6 +210,11 @@ class Core(context: Context, private val scope: CoroutineScope) : EventListener
runCatching { op(started) }.onFailure { Log.w(TAG, "notification update failed", it) }
}
}
+ scope.launch {
+ for (op in remoteOps) {
+ runCatching { op(started) }.onFailure { Log.w(TAG, "remote input failed", it) }
+ }
+ }
}
}
@@ -543,6 +555,71 @@ class Core(context: Context, private val scope: CoroutineScope) : EventListener
}
}
+ // ---- Remote input (phone -> PC) ----
+
+ /** Checks whether a PC accepts mouse, keyboard and presentation input from this phone. */
+ suspend fun remoteCheck(id: String): RemoteAccess {
+ startJob?.join()
+ val node = node ?: return RemoteAccess.Offline
+ return try {
+ node.remoteCheck(id)
+ RemoteAccess.Allowed
+ } catch (e: NectarlinkException) {
+ when (e) {
+ is NectarlinkException.Denied -> RemoteAccess.Denied
+ is NectarlinkException.Unsupported -> RemoteAccess.Unsupported
+ else -> RemoteAccess.Offline
+ }
+ }
+ }
+
+ /** Moves a PC's cursor by `(dx, dy)` logical pixels over QUIC datagrams. */
+ fun remoteMove(id: String, dx: Float, dy: Float) {
+ remoteOps.trySend { runCatching { it.remoteMove(id, dx, dy) } }
+ }
+
+ /** Scrolls on a PC (`dy` > 0 scrolls down, `dx` > 0 scrolls right, in wheel notches). */
+ fun remoteScroll(id: String, dx: Float, dy: Float, fast: Boolean = true) {
+ remoteOps.trySend { runCatching { it.remoteScroll(id, dx, dy, fast) } }
+ }
+
+ /** Presses, releases or clicks a mouse button (`"left"`, `"right"` or `"middle"`). */
+ fun remoteButton(id: String, button: String, action: String, onStatus: ((RemoteAccess) -> Unit)? = null) =
+ remoteCommand(onStatus) { it.remoteButton(id, button, action) }
+
+ /** Types Unicode text on a PC. */
+ fun remoteText(id: String, text: String, onStatus: ((RemoteAccess) -> Unit)? = null) =
+ remoteCommand(onStatus) { it.remoteText(id, text) }
+
+ /** Presses a named key or shortcut with optional modifiers on a PC. */
+ fun remoteKey(id: String, key: String, mods: List<String> = emptyList(), onStatus: ((RemoteAccess) -> Unit)? = null) =
+ remoteCommand(onStatus) { it.remoteKey(id, key, mods) }
+
+ /** Sends a presentation slide command (`"next"`, `"previous"`, `"start"`, `"stop"`, `"black"`). */
+ fun remoteSlide(id: String, action: String, onStatus: ((RemoteAccess) -> Unit)? = null) =
+ remoteCommand(onStatus) { it.remoteSlide(id, action) }
+
+ /** Moves or hides the laser pointer on a PC (`x`, `y` in `0..1`). */
+ fun remoteLaser(id: String, on: Boolean, x: Float = 0.5f, y: Float = 0.5f) {
+ remoteOps.trySend { runCatching { it.remoteLaser(id, on, x, y) } }
+ }
+
+ private fun remoteCommand(onStatus: ((RemoteAccess) -> Unit)?, block: suspend (NectarlinkNode) -> Unit) {
+ remoteOps.trySend { node ->
+ try {
+ block(node)
+ onStatus?.invoke(RemoteAccess.Allowed)
+ } catch (e: NectarlinkException) {
+ val status = when (e) {
+ is NectarlinkException.Denied -> RemoteAccess.Denied
+ is NectarlinkException.Unsupported -> RemoteAccess.Unsupported
+ else -> RemoteAccess.Offline
+ }
+ onStatus?.invoke(status)
+ }
+ }
+ }
+
/** Reconnects to PCs that aren't connected and syncs connected ones. */
fun refresh() {
refreshNotificationAccess()
@@ -577,6 +654,8 @@ class Core(context: Context, private val scope: CoroutineScope) : EventListener
else -> "Something went wrong."
}
+ enum class RemoteAccess { Allowed, Denied, Offline, Unsupported }
+
private companion object {
const val TAG = "Nectarlink"
/** Offered while notification access is granted (docs/protocol/capabilities.md). */
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 507fb47..c739012 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
@@ -132,6 +132,7 @@ data class CoreState(
is Event.ContactsChanged,
is Event.SmsChanged,
is Event.Mirroring,
+ is Event.RemoteInputRequested,
-> this
}
diff --git a/android/app/src/main/kotlin/app/nectarlink/android/ui/MainActivity.kt b/android/app/src/main/kotlin/app/nectarlink/android/ui/MainActivity.kt
index 7eaa381..5ce4a15 100644
--- a/android/app/src/main/kotlin/app/nectarlink/android/ui/MainActivity.kt
+++ b/android/app/src/main/kotlin/app/nectarlink/android/ui/MainActivity.kt
@@ -47,12 +47,20 @@ import app.nectarlink.android.core.PairingState
import app.nectarlink.android.service.ConnectionService
import app.nectarlink.android.ui.home.HomeScreen
import app.nectarlink.android.ui.pairing.PairingActions
+import android.view.KeyEvent
import app.nectarlink.android.core.LocalNetwork
import app.nectarlink.android.ui.pairing.PairingScreen
+import app.nectarlink.android.ui.remote.RemoteMode
+import app.nectarlink.android.ui.remote.RemoteScreen
import app.nectarlink.android.ui.settings.SettingsScreen
import app.nectarlink.android.ui.theme.NectarlinkTheme
class MainActivity : ComponentActivity() {
+ @Volatile
+ private var activeRemotePcId: String? = null
+ private var requestedRemotePc by mutableStateOf<String?>(null)
+ private var requestedRemoteMode by mutableStateOf(RemoteMode.Touchpad)
+
private val permissions =
registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) {
// The local network may have just been allowed: reconnect now.
@@ -72,7 +80,10 @@ class MainActivity : ComponentActivity() {
if (LocalNetwork.needed()) add(LocalNetwork.PERMISSION)
}.filter { checkSelfPermission(it) != android.content.pm.PackageManager.PERMISSION_GRANTED }
if (wanted.isNotEmpty()) permissions.launch(wanted.toTypedArray())
- if (savedInstanceState == null) handlePairingLink(intent)
+ if (savedInstanceState == null) {
+ handlePairingLink(intent)
+ handleRemoteIntent(intent)
+ }
setContent {
val appearance by preferences.appearance.collectAsStateWithLifecycle()
@@ -89,7 +100,15 @@ class MainActivity : ComponentActivity() {
// Every screen sits on the theme's background, not the
// window's (which can't follow the app's own light/dark choice).
Surface(color = MaterialTheme.colorScheme.background) {
- App(core, state, preferences)
+ App(
+ core = core,
+ state = state,
+ preferences = preferences,
+ requestedRemotePc = requestedRemotePc,
+ requestedRemoteMode = requestedRemoteMode,
+ onRemoteConsumed = { requestedRemotePc = null },
+ onActiveRemoteChanged = { activeRemotePcId = it },
+ )
}
}
}
@@ -106,6 +125,48 @@ class MainActivity : ComponentActivity() {
override fun onNewIntent(intent: Intent) {
super.onNewIntent(intent)
handlePairingLink(intent)
+ handleRemoteIntent(intent)
+ }
+
+ override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
+ val pcId = activeRemotePcId
+ if (pcId != null) {
+ when (keyCode) {
+ KeyEvent.KEYCODE_VOLUME_DOWN -> {
+ if (event?.repeatCount == 0) {
+ (application as NectarlinkApplication).core.remoteSlide(pcId, "next")
+ }
+ return true
+ }
+ KeyEvent.KEYCODE_VOLUME_UP -> {
+ if (event?.repeatCount == 0) {
+ (application as NectarlinkApplication).core.remoteSlide(pcId, "previous")
+ }
+ return true
+ }
+ }
+ }
+ return super.onKeyDown(keyCode, event)
+ }
+
+ override fun onKeyUp(keyCode: Int, event: KeyEvent?): Boolean {
+ if (activeRemotePcId != null &&
+ (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN || keyCode == KeyEvent.KEYCODE_VOLUME_UP)
+ ) {
+ return true
+ }
+ return super.onKeyUp(keyCode, event)
+ }
+
+ private fun handleRemoteIntent(intent: Intent?) {
+ val pc = intent?.getStringExtra("remote_pc") ?: return
+ val mode = intent.getStringExtra("remote_mode")
+ requestedRemoteMode = if (mode.equals("presentation", ignoreCase = true)) {
+ RemoteMode.Presentation
+ } else {
+ RemoteMode.Touchpad
+ }
+ requestedRemotePc = pc
}
/**
@@ -126,12 +187,37 @@ class MainActivity : ComponentActivity() {
private enum class Tab { Home, Settings }
@Composable
-private fun App(core: Core, state: CoreState, preferences: Preferences) {
+private fun App(
+ core: Core,
+ state: CoreState,
+ preferences: Preferences,
+ requestedRemotePc: String?,
+ requestedRemoteMode: RemoteMode,
+ onRemoteConsumed: () -> Unit,
+ onActiveRemoteChanged: (String?) -> Unit,
+) {
var tab by rememberSaveable { mutableStateOf(Tab.Home) }
var pairing by rememberSaveable { mutableStateOf(false) }
+ var remotePcId by rememberSaveable { mutableStateOf<String?>(null) }
+ var remoteInitialMode by rememberSaveable { mutableStateOf(RemoteMode.Touchpad) }
val snackbar = remember { SnackbarHostState() }
LaunchedEffect(Unit) { core.messages.collect { snackbar.showSnackbar(it) } }
+ LaunchedEffect(requestedRemotePc, state.devices) {
+ val req = requestedRemotePc ?: return@LaunchedEffect
+ val target = if (req == "first") state.devices.firstOrNull()?.id else state.device(req)?.id
+ if (target != null) {
+ remoteInitialMode = requestedRemoteMode
+ remotePcId = target
+ onRemoteConsumed()
+ }
+ }
+
+ val remoteDevice = remotePcId?.let { state.device(it) }
+ LaunchedEffect(remoteDevice?.id) {
+ onActiveRemoteChanged(remoteDevice?.id)
+ }
+
val actions = remember(core) {
object : PairingActions {
override fun visible(open: Boolean) = core.setPairingScreenOpen(open)
@@ -153,6 +239,22 @@ private fun App(core: Core, state: CoreState, preferences: Preferences) {
BackHandler(enabled = pairing && state.devices.isNotEmpty()) { core.resetPairing(); pairing = false }
PairingScreen(state, actions, cancellable = state.devices.isNotEmpty()) { pairing = false }
}
+ remoteDevice != null -> {
+ BackHandler { remotePcId = null }
+ val sensitivity by preferences.touchpadSensitivity.collectAsStateWithLifecycle()
+ Scaffold(
+ snackbarHost = { SnackbarHost(snackbar) },
+ ) { padding ->
+ RemoteScreen(
+ device = remoteDevice,
+ core = core,
+ sensitivity = sensitivity,
+ initialMode = remoteInitialMode,
+ onBack = { remotePcId = null },
+ modifier = Modifier.fillMaxSize().padding(padding),
+ )
+ }
+ }
else -> Scaffold(
snackbarHost = { SnackbarHost(snackbar) },
bottomBar = {
@@ -181,6 +283,10 @@ private fun App(core: Core, state: CoreState, preferences: Preferences) {
onPairNew = { pairing = true },
onRefresh = core::refresh,
onPower = core::pcPower,
+ onRemote = { id ->
+ remoteInitialMode = RemoteMode.Touchpad
+ remotePcId = id
+ },
updater = (LocalContext.current.applicationContext as NectarlinkApplication).updater,
onSendFiles = core::sendFiles,
onSendFolder = core::sendFolder,
@@ -192,6 +298,8 @@ private fun App(core: Core, state: CoreState, preferences: Preferences) {
state = state,
appearance = preferences.appearance.collectAsStateWithLifecycle().value,
onAppearance = preferences::update,
+ touchpadSensitivity = preferences.touchpadSensitivity.collectAsStateWithLifecycle().value,
+ onTouchpadSensitivity = preferences::updateTouchpadSensitivity,
onUnpair = core::unpair,
onPairNew = { pairing = true },
onAccessChanged = core::refreshNotificationAccess,
diff --git a/android/app/src/main/kotlin/app/nectarlink/android/ui/Preferences.kt b/android/app/src/main/kotlin/app/nectarlink/android/ui/Preferences.kt
index 1290761..fb91bdb 100644
--- a/android/app/src/main/kotlin/app/nectarlink/android/ui/Preferences.kt
+++ b/android/app/src/main/kotlin/app/nectarlink/android/ui/Preferences.kt
@@ -14,6 +14,9 @@ class Preferences(context: Context) {
private val _appearance = MutableStateFlow(load())
val appearance: StateFlow<Appearance> = _appearance.asStateFlow()
+ private val _touchpadSensitivity = MutableStateFlow(prefs.getFloat(TOUCHPAD_SENSITIVITY, 1.0f).coerceIn(0.4f, 3.0f))
+ val touchpadSensitivity: StateFlow<Float> = _touchpadSensitivity.asStateFlow()
+
private fun load(): Appearance {
val defaults = Appearance()
return Appearance(
@@ -35,10 +38,17 @@ class Preferences(context: Context) {
_appearance.value = next
}
+ fun updateTouchpadSensitivity(sensitivity: Float) {
+ val clamped = sensitivity.coerceIn(0.4f, 3.0f)
+ prefs.edit { putFloat(TOUCHPAD_SENSITIVITY, clamped) }
+ _touchpadSensitivity.value = clamped
+ }
+
private companion object {
const val THEME = "theme"
const val MODE = "mode"
const val SEED = "seed"
const val DYNAMIC = "dynamic_color"
+ const val TOUCHPAD_SENSITIVITY = "touchpad_sensitivity"
}
}
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 a51ae53..e8aaf93 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
@@ -81,6 +81,7 @@ fun HomeScreen(
onPairNew: () -> Unit,
onRefresh: () -> Unit,
onPower: (pcId: String, sleep: Boolean) -> Unit,
+ onRemote: (pcId: String) -> Unit,
updater: AppUpdater,
onSendFiles: (pcId: String, uris: List<Uri>) -> Unit,
onSendFolder: (pcId: String, tree: Uri) -> Unit,
@@ -196,7 +197,7 @@ fun HomeScreen(
) { askPhotos.launch(RecentPhotos.permissions) }
}
}
- items(state.devices, key = { it.id }) { device -> PcCard(device, onRing, onSendFiles, onSendFolder, onPower) }
+ items(state.devices, key = { it.id }) { device -> PcCard(device, onRing, onSendFiles, onSendFolder, onPower, onRemote) }
if (state.transfers.isNotEmpty()) {
item { TransfersCard(state, onCancelTransfer) }
}
@@ -239,6 +240,7 @@ private fun PcCard(
onSendFiles: (String, List<Uri>) -> Unit,
onSendFolder: (String, Uri) -> Unit,
onPower: (String, Boolean) -> Unit,
+ onRemote: (String) -> Unit,
) {
val pickFiles = rememberLauncherForActivityResult(ActivityResultContracts.OpenMultipleDocuments()) { uris ->
if (uris.isNotEmpty()) onSendFiles(device.id, uris)
@@ -307,6 +309,12 @@ private fun PcCard(
) {
Text(stringResource(if (ringing) R.string.action_stop_ringing else R.string.action_ring_pc))
}
+ FilledTonalButton(
+ colors = tonal,
+ onClick = { onRemote(device.id) },
+ ) {
+ Text(stringResource(R.string.action_remote_pc))
+ }
FilledTonalButton(
enabled = device.online,
colors = tonal,
diff --git a/android/app/src/main/kotlin/app/nectarlink/android/ui/remote/RemoteScreen.kt b/android/app/src/main/kotlin/app/nectarlink/android/ui/remote/RemoteScreen.kt
new file mode 100644
index 0000000..05716e4
--- /dev/null
+++ b/android/app/src/main/kotlin/app/nectarlink/android/ui/remote/RemoteScreen.kt
@@ -0,0 +1,747 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+package app.nectarlink.android.ui.remote
+
+import android.app.Activity
+import android.content.Context
+import android.hardware.Sensor
+import android.hardware.SensorEvent
+import android.hardware.SensorEventListener
+import android.hardware.SensorManager
+import android.view.WindowManager
+import androidx.compose.foundation.BorderStroke
+import androidx.compose.foundation.Canvas
+import androidx.compose.foundation.gestures.awaitEachGesture
+import androidx.compose.foundation.gestures.awaitFirstDown
+import androidx.compose.foundation.horizontalScroll
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Box
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.PaddingValues
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.Spacer
+import androidx.compose.foundation.layout.fillMaxSize
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.height
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.layout.size
+import androidx.compose.foundation.layout.width
+import androidx.compose.foundation.rememberScrollState
+import androidx.compose.foundation.shape.CircleShape
+import androidx.compose.foundation.text.KeyboardActions
+import androidx.compose.foundation.text.KeyboardOptions
+import androidx.compose.material3.Button
+import androidx.compose.material3.ButtonDefaults
+import androidx.compose.material3.FilledTonalButton
+import androidx.compose.material3.FilterChip
+import androidx.compose.material3.MaterialTheme
+import androidx.compose.material3.OutlinedButton
+import androidx.compose.material3.OutlinedTextField
+import androidx.compose.material3.SegmentedButton
+import androidx.compose.material3.SegmentedButtonDefaults
+import androidx.compose.material3.SingleChoiceSegmentedButtonRow
+import androidx.compose.material3.Surface
+import androidx.compose.material3.Text
+import androidx.compose.material3.TextButton
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.DisposableEffect
+import androidx.compose.runtime.LaunchedEffect
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableFloatStateOf
+import androidx.compose.runtime.mutableStateListOf
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.remember
+import androidx.compose.runtime.saveable.rememberSaveable
+import androidx.compose.runtime.setValue
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.focus.FocusRequester
+import androidx.compose.ui.focus.focusRequester
+import androidx.compose.ui.geometry.Offset
+import androidx.compose.ui.input.pointer.pointerInput
+import androidx.compose.ui.input.pointer.positionChange
+import androidx.compose.ui.platform.LocalContext
+import androidx.compose.ui.platform.LocalSoftwareKeyboardController
+import androidx.compose.ui.platform.LocalView
+import androidx.compose.ui.res.stringResource
+import androidx.compose.ui.text.input.ImeAction
+import androidx.compose.ui.text.style.TextAlign
+import androidx.compose.ui.unit.dp
+import app.nectarlink.android.R
+import app.nectarlink.android.core.Core
+import app.nectarlink.android.core.Device
+import kotlinx.coroutines.delay
+import kotlin.math.hypot
+
+enum class RemoteMode { Touchpad, Presentation }
+
+@Composable
+fun RemoteScreen(
+ device: Device,
+ core: Core,
+ sensitivity: Float,
+ onBack: () -> Unit,
+ modifier: Modifier = Modifier,
+ initialMode: RemoteMode = RemoteMode.Touchpad,
+) {
+ val view = LocalView.current
+ val context = LocalContext.current
+
+ // Keep the phone's screen on while controlling the PC, and release any
+ // held laser/button when leaving.
+ DisposableEffect(view, device.id) {
+ val window = (context as? Activity)?.window
+ val prevKeepOn = view.keepScreenOn
+ view.keepScreenOn = true
+ window?.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
+ onDispose {
+ view.keepScreenOn = prevKeepOn
+ window?.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
+ core.remoteLaser(device.id, false)
+ }
+ }
+
+ var mode by rememberSaveable(initialMode) { mutableStateOf(initialMode) }
+ var access by remember(device.id) { mutableStateOf(Core.RemoteAccess.Allowed) }
+
+ // Check access on entry and poll while denied so the prompt banner clears
+ // as soon as the user clicks Allow on the PC.
+ LaunchedEffect(device.id, device.online) {
+ if (!device.online) {
+ access = Core.RemoteAccess.Offline
+ return@LaunchedEffect
+ }
+ access = core.remoteCheck(device.id)
+ while (access == Core.RemoteAccess.Denied && device.online) {
+ delay(1_500)
+ access = core.remoteCheck(device.id)
+ }
+ }
+
+ val onStatus: (Core.RemoteAccess) -> Unit = { next -> access = next }
+
+ Column(
+ modifier = modifier
+ .fillMaxSize()
+ .padding(horizontal = 16.dp, vertical = 12.dp),
+ verticalArrangement = Arrangement.spacedBy(12.dp),
+ ) {
+ // Header: Back, PC name, online dot
+ Row(
+ modifier = Modifier.fillMaxWidth(),
+ verticalAlignment = Alignment.CenterVertically,
+ ) {
+ TextButton(
+ onClick = onBack,
+ contentPadding = PaddingValues(horizontal = 12.dp, vertical = 8.dp),
+ ) {
+ Text("← " + stringResource(R.string.action_back), style = MaterialTheme.typography.labelLarge)
+ }
+ Spacer(Modifier.width(4.dp))
+ Text(
+ device.name,
+ style = MaterialTheme.typography.titleLarge,
+ modifier = Modifier.weight(1f),
+ )
+ Surface(
+ shape = CircleShape,
+ color = if (device.online) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.outline,
+ modifier = Modifier.size(10.dp),
+ ) {}
+ }
+
+ // Mode switcher: Touchpad | Presentation
+ SingleChoiceSegmentedButtonRow(Modifier.fillMaxWidth()) {
+ SegmentedButton(
+ selected = mode == RemoteMode.Touchpad,
+ onClick = { mode = RemoteMode.Touchpad },
+ shape = SegmentedButtonDefaults.itemShape(0, 2),
+ ) {
+ Text(stringResource(R.string.remote_mode_touchpad))
+ }
+ SegmentedButton(
+ selected = mode == RemoteMode.Presentation,
+ onClick = { mode = RemoteMode.Presentation },
+ shape = SegmentedButtonDefaults.itemShape(1, 2),
+ ) {
+ Text(stringResource(R.string.remote_mode_presentation))
+ }
+ }
+
+ // Status banner when offline, denied, or unsupported
+ when {
+ !device.online || access == Core.RemoteAccess.Offline -> StatusBanner(
+ title = null,
+ text = stringResource(R.string.remote_offline_text, device.name),
+ )
+ access == Core.RemoteAccess.Denied -> StatusBanner(
+ title = stringResource(R.string.remote_denied_title, device.name),
+ text = stringResource(R.string.remote_denied_text, device.name),
+ )
+ access == Core.RemoteAccess.Unsupported -> StatusBanner(
+ title = null,
+ text = stringResource(R.string.remote_unsupported_text, device.name),
+ )
+ }
+
+ when (mode) {
+ RemoteMode.Touchpad -> TouchpadView(
+ pcId = device.id,
+ pcName = device.name,
+ core = core,
+ sensitivity = sensitivity,
+ onStatus = onStatus,
+ modifier = Modifier.weight(1f),
+ )
+ RemoteMode.Presentation -> PresentationView(
+ pcId = device.id,
+ pcName = device.name,
+ core = core,
+ onStatus = onStatus,
+ modifier = Modifier.weight(1f),
+ )
+ }
+ }
+}
+
+@Composable
+private fun StatusBanner(title: String?, text: String) {
+ Surface(
+ shape = MaterialTheme.shapes.large,
+ color = MaterialTheme.colorScheme.secondaryContainer,
+ contentColor = MaterialTheme.colorScheme.onSecondaryContainer,
+ ) {
+ Column(Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 12.dp)) {
+ if (title != null) {
+ Text(title, style = MaterialTheme.typography.titleSmall)
+ Spacer(Modifier.height(2.dp))
+ }
+ Text(text, style = MaterialTheme.typography.bodySmall)
+ }
+ }
+}
+
+@Composable
+private fun TouchpadView(
+ pcId: String,
+ pcName: String,
+ core: Core,
+ sensitivity: Float,
+ onStatus: (Core.RemoteAccess) -> Unit,
+ modifier: Modifier = Modifier,
+) {
+ var showKeyboard by rememberSaveable { mutableStateOf(false) }
+ var textBuffer by remember { mutableStateOf("") }
+ val activeMods = remember { mutableStateListOf<String>() }
+ var dragging by remember { mutableStateOf(false) }
+ var touchPoint by remember { mutableStateOf<Offset?>(null) }
+
+ val focusRequester = remember { FocusRequester() }
+ val keyboardController = LocalSoftwareKeyboardController.current
+
+ LaunchedEffect(showKeyboard) {
+ if (showKeyboard) {
+ focusRequester.requestFocus()
+ keyboardController?.show()
+ } else {
+ keyboardController?.hide()
+ }
+ }
+
+ Column(
+ modifier = modifier.fillMaxWidth(),
+ verticalArrangement = Arrangement.spacedBy(10.dp),
+ ) {
+ // Big touchpad surface
+ val primaryColor = MaterialTheme.colorScheme.primary
+ val outlineColor = MaterialTheme.colorScheme.outlineVariant
+ Surface(
+ shape = MaterialTheme.shapes.extraLarge,
+ color = MaterialTheme.colorScheme.surfaceContainerHigh,
+ border = BorderStroke(
+ width = if (dragging) 2.dp else 1.dp,
+ color = if (dragging) primaryColor else outlineColor,
+ ),
+ modifier = Modifier
+ .weight(1f)
+ .fillMaxWidth()
+ .pointerInput(pcId, sensitivity) {
+ val tapSlop = viewConfiguration.touchSlop
+ val tapTimeoutMs = 240L
+ val doubleTapWindowMs = 260L
+ var lastSingleTapTime = 0L
+
+ awaitEachGesture {
+ val firstDown = awaitFirstDown(requireUnconsumed = false)
+ val downTime = System.currentTimeMillis()
+ var maxPointers = 1
+ var totalMoved = 0f
+ var scrollAccumX = 0f
+ var scrollAccumY = 0f
+ var isDragHold = (downTime - lastSingleTapTime) <= doubleTapWindowMs
+ var dragStarted = false
+
+ touchPoint = firstDown.position
+
+ while (true) {
+ val event = awaitPointerEvent()
+ val pressed = event.changes.filter { it.pressed }
+ if (pressed.isEmpty()) break
+
+ if (pressed.size > maxPointers) {
+ maxPointers = pressed.size
+ if (dragStarted) {
+ core.remoteButton(pcId, "left", "up", onStatus)
+ dragStarted = false
+ dragging = false
+ }
+ isDragHold = false
+ }
+
+ if (pressed.size == 1 && maxPointers == 1) {
+ val change = pressed[0]
+ touchPoint = change.position
+ val delta = change.positionChange()
+ val dist = hypot(delta.x, delta.y)
+ totalMoved += dist
+
+ if (isDragHold && !dragStarted && totalMoved > tapSlop * 0.6f) {
+ dragStarted = true
+ dragging = true
+ core.remoteButton(pcId, "left", "down", onStatus)
+ }
+
+ if (dist > 0.2f) {
+ val scaledDx = delta.x * sensitivity
+ val scaledDy = delta.y * sensitivity
+ core.remoteMove(pcId, scaledDx, scaledDy)
+ change.consume()
+ }
+ } else if (pressed.size >= 2) {
+ touchPoint = pressed[0].position
+ var avgDx = 0f
+ var avgDy = 0f
+ for (c in pressed) {
+ val d = c.positionChange()
+ avgDx += d.x
+ avgDy += d.y
+ c.consume()
+ }
+ avgDx /= pressed.size
+ avgDy /= pressed.size
+ totalMoved += hypot(avgDx, avgDy)
+
+ scrollAccumX += avgDx
+ scrollAccumY += avgDy
+ val stepPx = 18f
+ if (kotlin.math.abs(scrollAccumX) >= stepPx || kotlin.math.abs(scrollAccumY) >= stepPx) {
+ val notchesX = -(scrollAccumX / 48f)
+ val notchesY = -(scrollAccumY / 36f)
+ scrollAccumX = 0f
+ scrollAccumY = 0f
+ core.remoteScroll(pcId, notchesX, notchesY, fast = true)
+ }
+ }
+ }
+
+ touchPoint = null
+ val elapsed = System.currentTimeMillis() - downTime
+ if (dragStarted) {
+ core.remoteButton(pcId, "left", "up", onStatus)
+ dragging = false
+ lastSingleTapTime = 0L
+ } else if (elapsed <= tapTimeoutMs && totalMoved <= tapSlop * 1.5f) {
+ if (maxPointers == 1) {
+ lastSingleTapTime = System.currentTimeMillis()
+ core.remoteButton(pcId, "left", "click", onStatus)
+ } else if (maxPointers == 2) {
+ lastSingleTapTime = 0L
+ core.remoteButton(pcId, "right", "click", onStatus)
+ }
+ } else {
+ lastSingleTapTime = 0L
+ }
+ }
+ },
+ ) {
+ Box(Modifier.fillMaxSize()) {
+ Canvas(Modifier.fillMaxSize()) {
+ touchPoint?.let { pt ->
+ drawCircle(
+ color = primaryColor.copy(alpha = 0.22f),
+ radius = 28.dp.toPx(),
+ center = pt,
+ )
+ drawCircle(
+ color = primaryColor.copy(alpha = 0.65f),
+ radius = 6.dp.toPx(),
+ center = pt,
+ )
+ }
+ }
+ Text(
+ stringResource(R.string.remote_touchpad_hint),
+ style = MaterialTheme.typography.bodySmall,
+ color = MaterialTheme.colorScheme.onSurfaceVariant,
+ textAlign = TextAlign.Center,
+ modifier = Modifier
+ .align(Alignment.BottomCenter)
+ .padding(horizontal = 20.dp, vertical = 14.dp),
+ )
+ }
+ }
+
+ // Mouse buttons + Keyboard toggle row
+ Row(
+ modifier = Modifier.fillMaxWidth(),
+ horizontalArrangement = Arrangement.spacedBy(8.dp),
+ ) {
+ FilledTonalButton(
+ onClick = { core.remoteButton(pcId, "left", "click", onStatus) },
+ contentPadding = PaddingValues(horizontal = 10.dp, vertical = 8.dp),
+ modifier = Modifier.weight(1f).height(48.dp),
+ ) {
+ Text(stringResource(R.string.remote_left_click), maxLines = 1)
+ }
+ OutlinedButton(
+ onClick = { core.remoteButton(pcId, "middle", "click", onStatus) },
+ contentPadding = PaddingValues(horizontal = 10.dp, vertical = 8.dp),
+ modifier = Modifier.weight(1f).height(48.dp),
+ ) {
+ Text(stringResource(R.string.remote_middle_click), maxLines = 1)
+ }
+ FilledTonalButton(
+ onClick = { core.remoteButton(pcId, "right", "click", onStatus) },
+ contentPadding = PaddingValues(horizontal = 10.dp, vertical = 8.dp),
+ modifier = Modifier.weight(1f).height(48.dp),
+ ) {
+ Text(stringResource(R.string.remote_right_click), maxLines = 1)
+ }
+ Button(
+ onClick = { showKeyboard = !showKeyboard },
+ contentPadding = PaddingValues(horizontal = 14.dp, vertical = 8.dp),
+ modifier = Modifier.height(48.dp),
+ ) {
+ Text(stringResource(R.string.remote_keyboard), maxLines = 1)
+ }
+ }
+
+ // Special keys & modifiers bar (always accessible in Touchpad mode)
+ SpecialKeysBar(
+ activeMods = activeMods,
+ onToggleMod = { mod ->
+ if (mod in activeMods) activeMods.remove(mod) else activeMods.add(mod)
+ },
+ onKey = { key, forceMods ->
+ val mods = forceMods ?: activeMods.toList()
+ core.remoteKey(pcId, key, mods, onStatus)
+ if (forceMods == null) activeMods.clear()
+ },
+ )
+
+ // Soft keyboard input row when toggled open
+ if (showKeyboard) {
+ OutlinedTextField(
+ value = textBuffer,
+ onValueChange = { next ->
+ if (next.length > textBuffer.length) {
+ val added = next.substring(textBuffer.length)
+ if (activeMods.isNotEmpty() && added.length == 1 && added[0].isLetterOrDigit()) {
+ core.remoteKey(pcId, added.lowercase(), activeMods.toList(), onStatus)
+ activeMods.clear()
+ } else {
+ core.remoteText(pcId, added, onStatus)
+ }
+ } else if (next.length < textBuffer.length) {
+ core.remoteKey(pcId, "backspace", activeMods.toList(), onStatus)
+ activeMods.clear()
+ }
+ textBuffer = " "
+ },
+ placeholder = { Text(stringResource(R.string.remote_type_placeholder, pcName)) },
+ singleLine = true,
+ keyboardOptions = KeyboardOptions(imeAction = ImeAction.Send),
+ keyboardActions = KeyboardActions(
+ onSend = {
+ core.remoteKey(pcId, "enter", activeMods.toList(), onStatus)
+ activeMods.clear()
+ },
+ ),
+ modifier = Modifier
+ .fillMaxWidth()
+ .focusRequester(focusRequester),
+ )
+ }
+ }
+}
+
+@Composable
+private fun SpecialKeysBar(
+ activeMods: List<String>,
+ onToggleMod: (String) -> Unit,
+ onKey: (key: String, forceMods: List<String>?) -> Unit,
+) {
+ Row(
+ modifier = Modifier
+ .fillMaxWidth()
+ .horizontalScroll(rememberScrollState()),
+ horizontalArrangement = Arrangement.spacedBy(6.dp),
+ verticalAlignment = Alignment.CenterVertically,
+ ) {
+ val mods = listOf("ctrl" to "Ctrl", "alt" to "Alt", "shift" to "Shift", "win" to "Win")
+ for ((id, label) in mods) {
+ FilterChip(
+ selected = id in activeMods,
+ onClick = { onToggleMod(id) },
+ label = { Text(label) },
+ )
+ }
+
+ val keys = listOf(
+ "escape" to "Esc",
+ "tab" to "Tab",
+ "left" to "←",
+ "up" to "↑",
+ "down" to "↓",
+ "right" to "→",
+ "backspace" to "Bksp",
+ "enter" to "Enter",
+ "space" to "Space",
+ "home" to "Home",
+ "end" to "End",
+ "page_up" to "PgUp",
+ "page_down" to "PgDn",
+ "delete" to "Del",
+ )
+ for ((key, label) in keys) {
+ OutlinedButton(
+ onClick = { onKey(key, null) },
+ contentPadding = PaddingValues(horizontal = 12.dp, vertical = 6.dp),
+ ) {
+ Text(label, style = MaterialTheme.typography.labelMedium)
+ }
+ }
+
+ val shortcuts = listOf(
+ "copy" to "Copy",
+ "paste" to "Paste",
+ "undo" to "Undo",
+ )
+ for ((shortcut, label) in shortcuts) {
+ OutlinedButton(
+ onClick = { onKey(shortcut, emptyList()) },
+ contentPadding = PaddingValues(horizontal = 12.dp, vertical = 6.dp),
+ ) {
+ Text(label, style = MaterialTheme.typography.labelMedium)
+ }
+ }
+ }
+}
+
+@Composable
+private fun PresentationView(
+ pcId: String,
+ pcName: String,
+ core: Core,
+ onStatus: (Core.RemoteAccess) -> Unit,
+ modifier: Modifier = Modifier,
+) {
+ val context = LocalContext.current
+ var laserHeld by remember { mutableStateOf(false) }
+ var laserX by remember { mutableFloatStateOf(0.5f) }
+ var laserY by remember { mutableFloatStateOf(0.5f) }
+
+ // While held, say it again every second even if it hasn't moved: the PC
+ // hides a dot that stops hearing from its phone.
+ LaunchedEffect(laserHeld, pcId) {
+ while (laserHeld) {
+ delay(1000)
+ core.remoteLaser(pcId, true, laserX, laserY)
+ }
+ }
+
+ // Follow the phone's gyroscope / rotation vector while the laser button is held.
+ DisposableEffect(laserHeld, pcId) {
+ if (!laserHeld) return@DisposableEffect onDispose {}
+
+ val sensorManager = context.getSystemService(Context.SENSOR_SERVICE) as? SensorManager
+ val rotationSensor = sensorManager?.getDefaultSensor(Sensor.TYPE_GAME_ROTATION_VECTOR)
+ ?: sensorManager?.getDefaultSensor(Sensor.TYPE_ROTATION_VECTOR)
+
+ var baseYaw: Float? = null
+ var basePitch: Float? = null
+ val rotationMatrix = FloatArray(9)
+ val orientation = FloatArray(3)
+
+ val listener = object : SensorEventListener {
+ override fun onSensorChanged(event: SensorEvent) {
+ SensorManager.getRotationMatrixFromVector(rotationMatrix, event.values)
+ SensorManager.getOrientation(rotationMatrix, orientation)
+ val yaw = orientation[0]
+ val pitch = orientation[1]
+ val bYaw = baseYaw ?: yaw.also { baseYaw = it }
+ val bPitch = basePitch ?: pitch.also { basePitch = it }
+
+ // ~35 degrees (~0.6 rad) full sweep across the screen
+ var dYaw = yaw - bYaw
+ if (dYaw > Math.PI.toFloat()) dYaw -= (2.0 * Math.PI).toFloat()
+ if (dYaw < -Math.PI.toFloat()) dYaw += (2.0 * Math.PI).toFloat()
+ val dPitch = pitch - bPitch
+
+ val nx = (0.5f + dYaw / 0.65f).coerceIn(0f, 1f)
+ val ny = (0.5f + dPitch / 0.50f).coerceIn(0f, 1f)
+ laserX = nx
+ laserY = ny
+ core.remoteLaser(pcId, true, nx, ny)
+ }
+
+ override fun onAccuracyChanged(sensor: Sensor?, accuracy: Int) {}
+ }
+
+ if (rotationSensor != null) {
+ sensorManager?.registerListener(listener, rotationSensor, SensorManager.SENSOR_DELAY_GAME)
+ }
+ onDispose {
+ sensorManager?.unregisterListener(listener)
+ }
+ }
+
+ Column(
+ modifier = modifier.fillMaxWidth(),
+ verticalArrangement = Arrangement.spacedBy(12.dp),
+ ) {
+ // Huge Next Slide button (easy to hit without looking)
+ Button(
+ onClick = { core.remoteSlide(pcId, "next", onStatus) },
+ shape = MaterialTheme.shapes.extraLarge,
+ modifier = Modifier
+ .fillMaxWidth()
+ .height(116.dp),
+ ) {
+ Text(
+ stringResource(R.string.remote_slide_next),
+ style = MaterialTheme.typography.headlineMedium,
+ )
+ }
+
+ // Previous Slide button
+ FilledTonalButton(
+ onClick = { core.remoteSlide(pcId, "previous", onStatus) },
+ shape = MaterialTheme.shapes.extraLarge,
+ modifier = Modifier
+ .fillMaxWidth()
+ .height(72.dp),
+ ) {
+ Text(
+ stringResource(R.string.remote_slide_prev),
+ style = MaterialTheme.typography.titleLarge,
+ )
+ }
+
+ // Start / End / Black screen row
+ Row(
+ modifier = Modifier.fillMaxWidth(),
+ horizontalArrangement = Arrangement.spacedBy(8.dp),
+ ) {
+ OutlinedButton(
+ onClick = { core.remoteSlide(pcId, "start", onStatus) },
+ contentPadding = PaddingValues(horizontal = 8.dp, vertical = 8.dp),
+ modifier = Modifier.weight(1f).height(48.dp),
+ ) {
+ Text(stringResource(R.string.remote_slide_start), maxLines = 1)
+ }
+ OutlinedButton(
+ onClick = { core.remoteSlide(pcId, "stop", onStatus) },
+ contentPadding = PaddingValues(horizontal = 8.dp, vertical = 8.dp),
+ modifier = Modifier.weight(1f).height(48.dp),
+ ) {
+ Text(stringResource(R.string.remote_slide_stop), maxLines = 1)
+ }
+ OutlinedButton(
+ onClick = { core.remoteSlide(pcId, "black", onStatus) },
+ contentPadding = PaddingValues(horizontal = 8.dp, vertical = 8.dp),
+ modifier = Modifier.weight(1f).height(48.dp),
+ ) {
+ Text(stringResource(R.string.remote_slide_black), maxLines = 1)
+ }
+ }
+
+ // Hold for laser pointer pad (supports both gyroscope tilt and finger drag)
+ val primaryColor = MaterialTheme.colorScheme.primary
+ Surface(
+ shape = MaterialTheme.shapes.extraLarge,
+ color = if (laserHeld) MaterialTheme.colorScheme.primaryContainer else MaterialTheme.colorScheme.surfaceContainerHigh,
+ contentColor = if (laserHeld) MaterialTheme.colorScheme.onPrimaryContainer else MaterialTheme.colorScheme.onSurface,
+ border = BorderStroke(
+ width = if (laserHeld) 2.dp else 1.dp,
+ color = if (laserHeld) primaryColor else MaterialTheme.colorScheme.outlineVariant,
+ ),
+ modifier = Modifier
+ .weight(1f)
+ .fillMaxWidth()
+ .pointerInput(pcId) {
+ awaitEachGesture {
+ val down = awaitFirstDown(requireUnconsumed = false)
+ val w = size.width.coerceAtLeast(1).toFloat()
+ val h = size.height.coerceAtLeast(1).toFloat()
+ laserX = (down.position.x / w).coerceIn(0f, 1f)
+ laserY = (down.position.y / h).coerceIn(0f, 1f)
+ laserHeld = true
+ core.remoteLaser(pcId, true, laserX, laserY)
+
+ while (true) {
+ val event = awaitPointerEvent()
+ val active = event.changes.firstOrNull { it.pressed } ?: break
+ val d = active.positionChange()
+ if (hypot(d.x, d.y) > 0.5f) {
+ laserX = (active.position.x / w).coerceIn(0f, 1f)
+ laserY = (active.position.y / h).coerceIn(0f, 1f)
+ core.remoteLaser(pcId, true, laserX, laserY)
+ active.consume()
+ }
+ }
+
+ laserHeld = false
+ core.remoteLaser(pcId, false)
+ }
+ },
+ ) {
+ Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
+ if (laserHeld) {
+ Canvas(Modifier.fillMaxSize()) {
+ val pt = Offset(laserX * size.width, laserY * size.height)
+ drawCircle(
+ color = primaryColor.copy(alpha = 0.28f),
+ radius = 26.dp.toPx(),
+ center = pt,
+ )
+ drawCircle(
+ color = primaryColor,
+ radius = 8.dp.toPx(),
+ center = pt,
+ )
+ }
+ }
+ Column(
+ horizontalAlignment = Alignment.CenterHorizontally,
+ modifier = Modifier.padding(20.dp),
+ ) {
+ Text(
+ stringResource(
+ if (laserHeld) R.string.remote_laser_active else R.string.remote_laser_hold,
+ pcName,
+ ),
+ style = MaterialTheme.typography.titleMedium,
+ textAlign = TextAlign.Center,
+ )
+ Spacer(Modifier.height(6.dp))
+ Text(
+ stringResource(R.string.remote_volume_hint),
+ style = MaterialTheme.typography.bodySmall,
+ color = MaterialTheme.colorScheme.onSurfaceVariant,
+ textAlign = TextAlign.Center,
+ )
+ }
+ }
+ }
+ }
+}
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.kt
index 921c031..9fba2f2 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
@@ -25,6 +25,7 @@ import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.SegmentedButton
import androidx.compose.material3.SegmentedButtonDefaults
import androidx.compose.material3.SingleChoiceSegmentedButtonRow
+import androidx.compose.material3.Slider
import androidx.compose.material3.Surface
import androidx.compose.material3.Switch
import androidx.compose.material3.Text
@@ -70,6 +71,8 @@ fun SettingsScreen(
state: CoreState,
appearance: Appearance,
onAppearance: ((Appearance) -> Appearance) -> Unit,
+ touchpadSensitivity: Float,
+ onTouchpadSensitivity: (Float) -> Unit,
onUnpair: (String) -> Unit,
onPairNew: () -> Unit,
onAccessChanged: () -> Unit,
@@ -132,6 +135,26 @@ fun SettingsScreen(
ElevatedAccess()
}
+ Section(stringResource(R.string.settings_remote)) {
+ Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth()) {
+ Text(
+ stringResource(R.string.settings_touchpad_sensitivity),
+ style = MaterialTheme.typography.titleSmall,
+ modifier = Modifier.weight(1f),
+ )
+ Text(
+ stringResource(R.string.settings_touchpad_sensitivity_value, touchpadSensitivity),
+ style = MaterialTheme.typography.bodyMedium,
+ color = MaterialTheme.colorScheme.onSurfaceVariant,
+ )
+ }
+ Slider(
+ value = touchpadSensitivity,
+ onValueChange = onTouchpadSensitivity,
+ valueRange = 0.5f..2.5f,
+ )
+ }
+
Section(stringResource(R.string.settings_appearance)) {
Label(stringResource(R.string.settings_theme))
Choice(
diff --git a/android/app/src/main/res/values/strings.xml b/android/app/src/main/res/values/strings.xml
index 06533e9..4e51e77 100644
--- a/android/app/src/main/res/values/strings.xml
+++ b/android/app/src/main/res/values/strings.xml
@@ -217,4 +217,31 @@
<item quantity="one">%1$d item</item>
<item quantity="other">%1$d items</item>
</plurals>
+
+ <!-- Remote input (touchpad, keyboard & presentation) -->
+ <string name="action_remote_pc">Control PC</string>
+ <string name="action_back">Back</string>
+ <string name="settings_remote">Control your PC</string>
+ <string name="settings_touchpad_sensitivity">Touchpad speed</string>
+ <string name="settings_touchpad_sensitivity_value">%1$.1f×</string>
+ <string name="remote_mode_touchpad">Touchpad</string>
+ <string name="remote_mode_presentation">Presentation</string>
+ <string name="remote_touchpad_hint">Drag to move · Tap to click · Two fingers to right-click or scroll · Double-tap and hold to drag</string>
+ <string name="remote_left_click">Left</string>
+ <string name="remote_right_click">Right</string>
+ <string name="remote_middle_click">Middle</string>
+ <string name="remote_keyboard">Keyboard</string>
+ <string name="remote_type_placeholder">Type on %1$s…</string>
+ <string name="remote_denied_title">Allow control on %1$s</string>
+ <string name="remote_denied_text">On %1$s, allow control from this phone in Nectarlink\'s prompt or in Settings › Devices.</string>
+ <string name="remote_offline_text">%1$s isn\'t connected right now.</string>
+ <string name="remote_unsupported_text">Update Nectarlink on %1$s to control it from this phone.</string>
+ <string name="remote_slide_next">Next slide</string>
+ <string name="remote_slide_prev">Previous</string>
+ <string name="remote_slide_start">Start show</string>
+ <string name="remote_slide_stop">End show</string>
+ <string name="remote_slide_black">Black screen</string>
+ <string name="remote_laser_hold">Hold for laser pointer</string>
+ <string name="remote_laser_active">Laser on %1$s — tilt phone or drag here</string>
+ <string name="remote_volume_hint">Volume buttons also change slides while this screen is open.</string>
</resources>
diff --git a/core/nectarlink-cli/src/main.rs b/core/nectarlink-cli/src/main.rs
index d7d2064..6a09450 100644
--- a/core/nectarlink-cli/src/main.rs
+++ b/core/nectarlink-cli/src/main.rs
@@ -210,6 +210,12 @@ enum Command {
#[command(subcommand)]
action: InputArg,
},
+ /// Control a paired PC's mouse, keyboard or presentation (use with --as-phone).
+ Remote {
+ device: String,
+ #[command(subcommand)]
+ action: RemoteArg,
+ },
/// 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.
@@ -394,6 +400,82 @@ enum InputArg {
Type { text: String },
}
+#[derive(Debug, Subcommand)]
+enum RemoteArg {
+ /// Move the PC's mouse cursor by (dx, dy) pixels.
+ Move {
+ #[arg(allow_hyphen_values = true)]
+ dx: f32,
+ #[arg(allow_hyphen_values = true)]
+ dy: f32,
+ },
+ /// Click, press (--down) or release (--up) a mouse button.
+ Click {
+ #[arg(value_enum, default_value_t = MouseButtonArg::Left)]
+ button: MouseButtonArg,
+ /// Press and hold the button down.
+ #[arg(long, conflicts_with = "up")]
+ down: bool,
+ /// Release the button.
+ #[arg(long, conflicts_with = "down")]
+ up: bool,
+ },
+ /// Scroll the mouse wheel by (dx, dy) notches (positive dy scrolls down).
+ Scroll {
+ #[arg(allow_hyphen_values = true)]
+ dx: f32,
+ #[arg(allow_hyphen_values = true)]
+ dy: f32,
+ },
+ /// Type Unicode text on the PC.
+ Type { text: String },
+ /// Press a named key or shortcut (enter, backspace, tab, escape, space,
+ /// up, down, left, right, copy, paste, undo, ...) with optional modifiers.
+ Key {
+ key: String,
+ #[arg(long)]
+ ctrl: bool,
+ #[arg(long)]
+ alt: bool,
+ #[arg(long)]
+ shift: bool,
+ #[arg(long)]
+ win: bool,
+ },
+ /// Control a presentation on the PC (next, previous, start, stop, black).
+ Slide {
+ #[arg(value_enum)]
+ action: SlideArg,
+ },
+ /// Show the laser pointer at normalized (x, y) in 0..=1, or hide it with --off.
+ Laser {
+ #[arg(required_unless_present = "off")]
+ x: Option<f32>,
+ #[arg(required_unless_present = "off")]
+ y: Option<f32>,
+ /// Hide the laser pointer overlay.
+ #[arg(long)]
+ off: bool,
+ },
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
+enum MouseButtonArg {
+ Left,
+ Right,
+ Middle,
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
+enum SlideArg {
+ Next,
+ #[value(alias = "prev")]
+ Previous,
+ Start,
+ Stop,
+ Black,
+}
+
#[derive(Debug, Subcommand)]
enum SmsArg {
/// The latest conversations.
@@ -1547,20 +1629,34 @@ impl Platform for TerminalPlatform {
}
Ok(())
}
+ fn remote_input(&self, _peer: &DeviceId, input: nectarlink_core::RemoteInput) -> Result<(), String> {
+ println!("Remote input: {input:?}");
+ Ok(())
+ }
}
-#[tokio::main]
-async fn main() -> Result<()> {
- let cli = Cli::parse();
- tracing_subscriber::fmt()
- .with_env_filter(tracing_subscriber::EnvFilter::try_new(&cli.log).unwrap_or_else(|_| "warn".into()))
- .with_writer(std::io::stderr)
- .init();
-
- let node = Box::pin(start_node(&cli)).await?;
- let result = Box::pin(run(&cli, &node)).await;
- node.shutdown().await;
- result
+fn main() -> Result<()> {
+ std::thread::Builder::new()
+ .name("main".into())
+ .stack_size(8 * 1024 * 1024)
+ .spawn(|| {
+ tokio::runtime::Builder::new_multi_thread().enable_all().build()?.block_on(async {
+ let cli = Cli::parse();
+ tracing_subscriber::fmt()
+ .with_env_filter(
+ tracing_subscriber::EnvFilter::try_new(&cli.log).unwrap_or_else(|_| "warn".into()),
+ )
+ .with_writer(std::io::stderr)
+ .init();
+
+ let node = Box::pin(start_node(&cli)).await?;
+ let result = Box::pin(run(&cli, &node)).await;
+ node.shutdown().await;
+ result
+ })
+ })?
+ .join()
+ .unwrap_or_else(|_| bail!("main thread panicked"))
}
async fn start_node(cli: &Cli) -> Result<Node> {
@@ -1847,6 +1943,91 @@ async fn run(cli: &Cli, node: &Node) -> Result<()> {
tokio::time::sleep(Duration::from_millis(500)).await;
println!("Sent.");
}
+ Command::Remote { device, action } => {
+ use nectarlink_core::{ButtonAction, KeyMod, MouseButton, RemoteInput, SlideAction};
+ if !cli.as_phone {
+ bail!("remote input is sent by phones: add --as-phone");
+ }
+ let id = resolve(node, device)?;
+ wait_until_online(node, id).await?;
+ match action {
+ RemoteArg::Move { dx, dy } => {
+ node.remote_check(id).await.context("the PC refused remote input")?;
+ node.remote_move(id, *dx, *dy).await.context("move not sent")?;
+ tokio::time::sleep(Duration::from_millis(200)).await;
+ }
+ RemoteArg::Click { button, down, up } => {
+ let button = match button {
+ MouseButtonArg::Left => MouseButton::Left,
+ MouseButtonArg::Right => MouseButton::Right,
+ MouseButtonArg::Middle => MouseButton::Middle,
+ };
+ let action = if *down {
+ ButtonAction::Down
+ } else if *up {
+ ButtonAction::Up
+ } else {
+ ButtonAction::Click
+ };
+ node.remote_input(id, RemoteInput::Button { button, action })
+ .await
+ .context("the PC refused remote input")?;
+ }
+ RemoteArg::Scroll { dx, dy } => {
+ node.remote_input(id, RemoteInput::Scroll { dx: *dx, dy: *dy })
+ .await
+ .context("the PC refused remote input")?;
+ }
+ RemoteArg::Type { text } => {
+ node.remote_input(id, RemoteInput::Text { text: text.clone() })
+ .await
+ .context("the PC refused remote input")?;
+ }
+ RemoteArg::Key { key, ctrl, alt, shift, win } => {
+ let mut mods = Vec::new();
+ if *ctrl {
+ mods.push(KeyMod::Ctrl);
+ }
+ if *alt {
+ mods.push(KeyMod::Alt);
+ }
+ if *shift {
+ mods.push(KeyMod::Shift);
+ }
+ if *win {
+ mods.push(KeyMod::Win);
+ }
+ node.remote_input(id, RemoteInput::Key { key: key.clone(), mods })
+ .await
+ .context("the PC refused remote input")?;
+ }
+ RemoteArg::Slide { action } => {
+ let action = match action {
+ SlideArg::Next => SlideAction::Next,
+ SlideArg::Previous => SlideAction::Previous,
+ SlideArg::Start => SlideAction::Start,
+ SlideArg::Stop => SlideAction::Stop,
+ SlideArg::Black => SlideAction::Black,
+ };
+ node.remote_input(id, RemoteInput::Slide { action })
+ .await
+ .context("the PC refused remote input")?;
+ }
+ RemoteArg::Laser { x, y, off } => {
+ if *off {
+ node.remote_laser(id, false, 0.0, 0.0)
+ .await
+ .context("the PC refused remote input")?;
+ } else {
+ let (x, y) = (x.unwrap_or(0.5), y.unwrap_or(0.5));
+ node.remote_check(id).await.context("the PC refused remote input")?;
+ node.remote_laser(id, true, x, y).await.context("laser not sent")?;
+ tokio::time::sleep(Duration::from_millis(200)).await;
+ }
+ }
+ }
+ println!("Sent.");
+ }
Command::Apps { device, at } => {
let id = resolve(node, device)?;
if !at.is_empty() {
@@ -2745,6 +2926,11 @@ fn print_event(node: &Node, event: &NodeEvent) {
NodeEvent::CallLogChanged { device } => println!("{}: call log changed", name(device)),
NodeEvent::ContactsChanged { device } => println!("{}: contacts changed", name(device)),
NodeEvent::PhotosChanged { device } => println!("{}: photo library changed", name(device)),
+ NodeEvent::RemoteInputRequested { device } => println!(
+ "{}: asked to control mouse and keyboard (allow with: nectarlink toggle {} remote_input on)",
+ name(device),
+ device.short()
+ ),
NodeEvent::PhotoAdded { device, photo } => println!(
"{}: new {} {} ({} bytes, preview {} bytes)",
name(device),
diff --git a/core/nectarlink-core/src/config.rs b/core/nectarlink-core/src/config.rs
index e192a40..e68819a 100644
--- a/core/nectarlink-core/src/config.rs
+++ b/core/nectarlink-core/src/config.rs
@@ -268,6 +268,16 @@ pub trait Platform: Send + Sync + 'static {
) -> Result<(), MediaError> {
Err(MediaError::Unsupported)
}
+
+ /// Inject pointer, keyboard or presentation input from a paired phone
+ /// (`docs/protocol/remote.md`).
+ fn remote_input(
+ &self,
+ _peer: &nectarlink_protocol::DeviceId,
+ _input: crate::RemoteInput,
+ ) -> Result<(), String> {
+ Err("this device doesn't take remote input".into())
+ }
}
/// A platform that does nothing; useful for tests and headless tools.
diff --git a/core/nectarlink-core/src/events.rs b/core/nectarlink-core/src/events.rs
index 88f1b7f..2074a64 100644
--- a/core/nectarlink-core/src/events.rs
+++ b/core/nectarlink-core/src/events.rs
@@ -163,4 +163,10 @@ pub enum NodeEvent {
device: DeviceId,
thread: Option<String>,
},
+ /// A paired phone asked to control this PC's mouse and keyboard while its
+ /// `remote_input` toggle is off (emitted once per phone so the UI can show
+ /// a one-time prompt).
+ RemoteInputRequested {
+ device: DeviceId,
+ },
}
diff --git a/core/nectarlink-core/src/features.rs b/core/nectarlink-core/src/features.rs
index f082ca7..6e280fc 100644
--- a/core/nectarlink-core/src/features.rs
+++ b/core/nectarlink-core/src/features.rs
@@ -335,6 +335,8 @@ pub const DEVICE_TOGGLES: &[(&str, bool)] = &[
("photos", true),
("pc_actions", true),
("mirroring", true),
+ // Controlling this PC's mouse and keyboard is opt-in.
+ ("remote_input", false),
// Browsing the PC's files from anywhere is opt-in.
("remote_files", false),
];
diff --git a/core/nectarlink-core/src/lib.rs b/core/nectarlink-core/src/lib.rs
index 697dc11..4ff3d6f 100644
--- a/core/nectarlink-core/src/lib.rs
+++ b/core/nectarlink-core/src/lib.rs
@@ -21,6 +21,7 @@ mod node;
mod notifications;
mod pairing;
mod photos;
+pub mod remote;
mod session;
mod sms;
mod store;
@@ -71,6 +72,7 @@ pub use nectarlink_protocol::{
};
pub use node::Node;
pub use notifications::NotificationError;
+pub use remote::{ButtonAction, INPUT_INJECT, KeyMod, MouseButton, RemoteInput, SlideAction, remote_keys};
pub use transfer::{
Direction, FileSource, OutgoingFile, Transfer, TransferFailure, TransferState, outgoing_paths,
safe_file_name,
diff --git a/core/nectarlink-core/src/node.rs b/core/nectarlink-core/src/node.rs
index fe17788..d4d5bc7 100644
--- a/core/nectarlink-core/src/node.rs
+++ b/core/nectarlink-core/src/node.rs
@@ -122,6 +122,8 @@ pub(crate) struct Shared {
pub(crate) calls: crate::calls::Current,
/// Stop signals for phone screens shown here, by phone.
pub(crate) mirror_stops: Mutex<HashMap<MirrorStop, Arc<tokio::sync::Notify>>>,
+ /// Per-peer rate limiters and prompt state for remote input.
+ pub(crate) remote: Mutex<crate::remote::RemoteState>,
pub data_dir: std::path::PathBuf,
/// Where received files go.
pub downloads_dir: std::path::PathBuf,
@@ -294,6 +296,7 @@ impl Shared {
}
lock(&self.links).remove(peer);
lock(&self.matrices).remove(peer);
+ lock(&self.remote).remove_peer(peer);
if existed {
self.emit(NodeEvent::DeviceRemoved(*peer));
}
@@ -619,6 +622,7 @@ impl Node {
players: Default::default(),
calls: Default::default(),
mirror_stops: Mutex::new(HashMap::new()),
+ remote: Mutex::new(Default::default()),
data_dir: config.data_dir.clone(),
downloads_dir: config.downloads_dir.clone().unwrap_or_else(|| config.data_dir.join("received")),
transfers: Mutex::new(HashMap::new()),
@@ -1143,6 +1147,41 @@ impl Node {
crate::photos::fetch_many(&self.shared, &session, ids).await
}
+ // ---- Remote input (docs/protocol/remote.md) ----
+
+ /// Checks whether a paired PC currently accepts remote input from this
+ /// phone. If `remote_input` is off on the PC, returns [`Error::Denied`]
+ /// and triggers the PC's one-time prompt the first time.
+ pub async fn remote_check(&self, peer: DeviceId) -> Result<()> {
+ let session = self.connected(&peer)?;
+ crate::remote::check(&self.shared, &session).await
+ }
+
+ /// Sends a remote input event to a paired PC.
+ pub async fn remote_input(&self, peer: DeviceId, input: crate::RemoteInput) -> Result<()> {
+ let session = self.connected(&peer)?;
+ crate::remote::input(&self.shared, &session, input).await
+ }
+
+ /// Sends relative pointer motion `(dx, dy)` in a QUIC datagram (never on
+ /// the control stream).
+ pub async fn remote_move(&self, peer: DeviceId, dx: f32, dy: f32) -> Result<()> {
+ let session = self.connected(&peer)?;
+ crate::remote::move_pointer(&self.shared, &session, dx, dy).await
+ }
+
+ /// Sends smooth scroll `(dx, dy)` in a QUIC datagram.
+ pub async fn remote_scroll_fast(&self, peer: DeviceId, dx: f32, dy: f32) -> Result<()> {
+ let session = self.connected(&peer)?;
+ crate::remote::scroll_fast(&self.shared, &session, dx, dy).await
+ }
+
+ /// Sends a laser pointer update to a paired PC (`x`, `y` in `0.0..=1.0`).
+ pub async fn remote_laser(&self, peer: DeviceId, on: bool, x: f32, y: f32) -> Result<()> {
+ let session = self.connected(&peer)?;
+ crate::remote::laser(&self.shared, &session, on, x, y).await
+ }
+
// ---- Media (docs/protocol/media.md) ----
/// This device's media players changed (most relevant first); sent to
diff --git a/core/nectarlink-core/src/remote.rs b/core/nectarlink-core/src/remote.rs
new file mode 100644
index 0000000..85430cf
--- /dev/null
+++ b/core/nectarlink-core/src/remote.rs
@@ -0,0 +1,345 @@
+// SPDX-License-Identifier: MPL-2.0
+//! Phone as touchpad, keyboard and presentation remote (`docs/protocol/remote.md`).
+
+use std::{
+ collections::{HashMap, HashSet},
+ sync::Arc,
+ time::{Duration, Instant},
+};
+
+use bytes::Bytes;
+use iroh::endpoint::{RecvStream, SendStream};
+pub use nectarlink_protocol::messages::{
+ ButtonAction, KeyMod, MouseButton, RemoteInput, SlideAction, remote_keys,
+};
+use nectarlink_protocol::{
+ DeviceId, Envelope, ErrorCode,
+ messages::{StreamHeader, remote, types},
+ read_frame, write_frame,
+};
+
+use crate::{Error, NodeEvent, Result, node::Shared, session::Session};
+
+/// Capability ID announced by a desktop that can inject mouse, keyboard and
+/// presentation input (`docs/protocol/remote.md` §1).
+pub const INPUT_INJECT: &str = "input.inject";
+
+/// Per-device toggle name on the PC (off by default).
+pub(crate) const TOGGLE: &str = "remote_input";
+
+const TIMEOUT: Duration = Duration::from_secs(5);
+
+/// Maximum rate of incoming datagrams (`move`, `scroll`, `laser`) per peer.
+const DATAGRAM_RATE_PER_SEC: f64 = 240.0;
+const DATAGRAM_BURST: f64 = 60.0;
+
+/// Maximum rate of incoming control-stream `remote.input` requests per peer.
+const CONTROL_RATE_PER_SEC: f64 = 60.0;
+const CONTROL_BURST: f64 = 30.0;
+
+/// Simple token bucket for per-peer input rate limiting.
+#[derive(Debug, Clone)]
+pub(crate) struct TokenBucket {
+ tokens: f64,
+ capacity: f64,
+ rate_per_sec: f64,
+ last: Instant,
+}
+
+impl TokenBucket {
+ pub fn new(capacity: f64, rate_per_sec: f64, now: Instant) -> Self {
+ Self { tokens: capacity, capacity, rate_per_sec, last: now }
+ }
+
+ pub fn take(&mut self, now: Instant) -> bool {
+ let elapsed = now.saturating_duration_since(self.last).as_secs_f64();
+ self.last = now;
+ self.tokens = (self.tokens + elapsed * self.rate_per_sec).min(self.capacity);
+ if self.tokens >= 1.0 {
+ self.tokens -= 1.0;
+ true
+ } else {
+ false
+ }
+ }
+}
+
+#[derive(Debug)]
+struct PeerLimiter {
+ datagram: TokenBucket,
+ control: TokenBucket,
+}
+
+impl PeerLimiter {
+ fn new(now: Instant) -> Self {
+ Self {
+ datagram: TokenBucket::new(DATAGRAM_BURST, DATAGRAM_RATE_PER_SEC, now),
+ control: TokenBucket::new(CONTROL_BURST, CONTROL_RATE_PER_SEC, now),
+ }
+ }
+}
+
+/// Per-node state for remote input: rate limiters and one-time prompt tracking.
+#[derive(Debug, Default)]
+pub(crate) struct RemoteState {
+ peers: HashMap<DeviceId, PeerLimiter>,
+ /// Peers that already triggered the one-time prompt while `remote_input`
+ /// was off.
+ prompted: HashSet<DeviceId>,
+}
+
+impl RemoteState {
+ pub fn allow_datagram(&mut self, peer: DeviceId, now: Instant) -> bool {
+ self.peers.entry(peer).or_insert_with(|| PeerLimiter::new(now)).datagram.take(now)
+ }
+
+ pub fn allow_control(&mut self, peer: DeviceId, now: Instant) -> bool {
+ self.peers.entry(peer).or_insert_with(|| PeerLimiter::new(now)).control.take(now)
+ }
+
+ /// Records that `peer` asked for remote input while the toggle was off.
+ /// Returns `true` the first time for that peer.
+ pub fn mark_prompted(&mut self, peer: DeviceId) -> bool {
+ self.prompted.insert(peer)
+ }
+
+ pub fn remove_peer(&mut self, peer: &DeviceId) {
+ self.peers.remove(peer);
+ self.prompted.remove(peer);
+ }
+}
+
+fn peer_offers(shared: &Shared, peer: &DeviceId, cap: &str) -> Result<bool> {
+ Ok(shared.store.get_peer(peer)?.is_some_and(|p| p.caps.contains(cap)))
+}
+
+fn we_offer(shared: &Shared, cap: &str) -> bool {
+ shared.local_capabilities().iter().any(|c| c == cap)
+}
+
+fn check_allowed(shared: &Shared, peer: &DeviceId) -> std::result::Result<(), (ErrorCode, &'static str)> {
+ if !we_offer(shared, INPUT_INJECT) {
+ return Err((ErrorCode::Unsupported, "remote input is not supported here"));
+ }
+ if !shared.toggle_on(peer, TOGGLE) {
+ let first_time = shared.remote.lock().unwrap_or_else(|e| e.into_inner()).mark_prompted(*peer);
+ if first_time {
+ shared.emit(NodeEvent::RemoteInputRequested { device: *peer });
+ }
+ return Err((ErrorCode::Denied, "remote input is turned off for this device"));
+ }
+ Ok(())
+}
+
+/// Checks whether `peer` (a PC) currently accepts remote input from this phone.
+pub(crate) async fn check(shared: &Arc<Shared>, session: &Arc<Session>) -> Result<()> {
+ if !peer_offers(shared, &session.peer, INPUT_INJECT)? {
+ return Err(Error::Unsupported);
+ }
+ session.request(Envelope::empty(types::REMOTE_CHECK), TIMEOUT).await?.expect(types::OK)?;
+ Ok(())
+}
+
+/// Sends a remote input event to `peer` (a PC).
+///
+/// Discrete actions travel on the control stream. If `input` is
+/// [`RemoteInput::Move`], permission is checked first and the motion itself is
+/// sent as a QUIC datagram, never on the control stream.
+pub(crate) async fn input(shared: &Arc<Shared>, session: &Arc<Session>, event: RemoteInput) -> Result<()> {
+ if !event.is_valid() {
+ return Err(Error::Protocol("invalid remote input".into()));
+ }
+ if !peer_offers(shared, &session.peer, INPUT_INJECT)? {
+ return Err(Error::Unsupported);
+ }
+ if let RemoteInput::Move { dx, dy } = event {
+ check(shared, session).await?;
+ return move_pointer(shared, session, dx, dy).await;
+ }
+ let env = Envelope::new(types::REMOTE_INPUT, &event)?;
+ session.request(env, TIMEOUT).await?.expect(types::OK)?;
+ Ok(())
+}
+
+/// Sends relative pointer motion `(dx, dy)` in a QUIC datagram (or a dedicated
+/// `remote/motion` stream if datagrams are unavailable), never on the control
+/// stream.
+pub(crate) async fn move_pointer(
+ shared: &Arc<Shared>,
+ session: &Arc<Session>,
+ dx: f32,
+ dy: f32,
+) -> Result<()> {
+ let event = RemoteInput::Move { dx, dy };
+ if !event.is_valid() {
+ return Err(Error::Protocol("pointer motion out of bounds".into()));
+ }
+ send_datagram(shared, session, &event).await
+}
+
+/// Sends smooth scroll `(dx, dy)` in a QUIC datagram.
+pub(crate) async fn scroll_fast(
+ shared: &Arc<Shared>,
+ session: &Arc<Session>,
+ dx: f32,
+ dy: f32,
+) -> Result<()> {
+ let event = RemoteInput::Scroll { dx, dy };
+ if !event.is_valid() {
+ return Err(Error::Protocol("scroll delta out of bounds".into()));
+ }
+ send_datagram(shared, session, &event).await
+}
+
+/// Sends a laser pointer update. While `on` is `true`, positions travel in
+/// QUIC datagrams; when `on` is `false`, a datagram and a control-stream
+/// `remote.input` are both sent so the dot reliably hides.
+pub(crate) async fn laser(
+ shared: &Arc<Shared>,
+ session: &Arc<Session>,
+ on: bool,
+ x: f32,
+ y: f32,
+) -> Result<()> {
+ let event = RemoteInput::Laser { on, x, y };
+ if !event.is_valid() {
+ return Err(Error::Protocol("laser coordinates out of bounds".into()));
+ }
+ if on {
+ send_datagram(shared, session, &event).await
+ } else {
+ let _ = send_datagram(shared, session, &event).await;
+ input(shared, session, event).await
+ }
+}
+
+async fn send_datagram(shared: &Arc<Shared>, session: &Arc<Session>, event: &RemoteInput) -> Result<()> {
+ if !peer_offers(shared, &session.peer, INPUT_INJECT)? {
+ return Err(Error::Unsupported);
+ }
+ let bytes = Bytes::from(event.to_datagram());
+ if session.send_datagram(bytes).is_ok() {
+ return Ok(());
+ }
+ // Fallback if QUIC datagrams are disabled on this transport: open a
+ // dedicated stream (still never the control stream).
+ let (mut send, _recv) = session.open_bi().await?;
+ let header =
+ StreamHeader { svc: remote::SERVICE.into(), op: remote::OP_MOTION.into(), v: remote::VERSION };
+ let header = Envelope::new(types::STREAM, &header)?;
+ write_frame(&mut send, &header.to_cbor()).await?;
+ let frame = Envelope::new(types::REMOTE_INPUT, event)?;
+ write_frame(&mut send, &frame.to_cbor()).await?;
+ let _ = send.finish();
+ Ok(())
+}
+
+/// Handles incoming `remote.*` requests on the control stream.
+pub(crate) async fn handle(shared: &Arc<Shared>, session: &Arc<Session>, env: &Envelope) -> Result<bool> {
+ let reply = match env.t.as_str() {
+ types::REMOTE_CHECK => match check_allowed(shared, &session.peer) {
+ Ok(()) => Envelope::empty(types::OK),
+ Err((code, msg)) => Envelope::error(code, msg),
+ },
+ types::REMOTE_INPUT => match check_allowed(shared, &session.peer) {
+ Err((code, msg)) => Envelope::error(code, msg),
+ Ok(()) => match env.body::<RemoteInput>() {
+ Ok(event) if event.is_control_allowed() && event.is_valid() => {
+ let allowed = shared
+ .remote
+ .lock()
+ .unwrap_or_else(|e| e.into_inner())
+ .allow_control(session.peer, Instant::now());
+ if !allowed {
+ Envelope::error(ErrorCode::Denied, "rate limit exceeded")
+ } else {
+ let platform = shared.platform.clone();
+ let peer = session.peer;
+ match tokio::task::spawn_blocking(move || platform.remote_input(&peer, event)).await {
+ Ok(Ok(())) => Envelope::empty(types::OK),
+ Ok(Err(e)) => Envelope::error(ErrorCode::Internal, e),
+ Err(_) => Envelope::error(ErrorCode::Internal, "input task failed"),
+ }
+ }
+ }
+ _ => Envelope::error(ErrorCode::BadMessage, "invalid remote input"),
+ },
+ },
+ _ => return Ok(false),
+ };
+ session.send(reply.reply_to(env.id)).await?;
+ Ok(true)
+}
+
+/// Handles an incoming QUIC datagram from `peer`.
+pub(crate) fn handle_datagram(shared: &Arc<Shared>, peer: DeviceId, bytes: &[u8]) {
+ if check_allowed(shared, &peer).is_err() {
+ return;
+ }
+ let Ok(event) = RemoteInput::from_datagram(bytes) else {
+ return;
+ };
+ let allowed =
+ shared.remote.lock().unwrap_or_else(|e| e.into_inner()).allow_datagram(peer, Instant::now());
+ if !allowed {
+ return;
+ }
+ let _ = shared.platform.remote_input(&peer, event);
+}
+
+/// Handles a fallback `remote/motion` stream when QUIC datagrams aren't used.
+pub(crate) async fn receive_motion(
+ shared: Arc<Shared>,
+ peer: DeviceId,
+ mut send: SendStream,
+ mut recv: RecvStream,
+) {
+ while let Ok(Some(bytes)) = read_frame(&mut recv).await {
+ if check_allowed(&shared, &peer).is_err() {
+ break;
+ }
+ let Ok(env) = Envelope::from_cbor(&bytes) else { break };
+ let Ok(event) = env.expect_body::<RemoteInput>(types::REMOTE_INPUT) else { break };
+ if !event.is_datagram_allowed() || !event.is_valid() {
+ break;
+ }
+ let allowed =
+ shared.remote.lock().unwrap_or_else(|e| e.into_inner()).allow_datagram(peer, Instant::now());
+ if allowed {
+ let _ = shared.platform.remote_input(&peer, event);
+ }
+ }
+ let _ = send.finish();
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn token_bucket_enforces_burst_and_refills() {
+ let start = Instant::now();
+ let mut b = TokenBucket::new(3.0, 10.0, start);
+ assert!(b.take(start));
+ assert!(b.take(start));
+ assert!(b.take(start));
+ assert!(!b.take(start), "burst exhausted");
+
+ // 100 ms later at 10/s refills 1 token.
+ let later = start + Duration::from_millis(100);
+ assert!(b.take(later));
+ assert!(!b.take(later));
+ }
+
+ #[test]
+ fn prompt_is_emitted_once_per_peer() {
+ let mut state = RemoteState::default();
+ let a = DeviceId([1; 32]);
+ let b = DeviceId([2; 32]);
+ assert!(state.mark_prompted(a));
+ assert!(!state.mark_prompted(a), "second ask from same peer does not re-prompt");
+ assert!(state.mark_prompted(b));
+ state.remove_peer(&a);
+ assert!(state.mark_prompted(a), "unpairing resets prompt state");
+ }
+}
diff --git a/core/nectarlink-core/src/session.rs b/core/nectarlink-core/src/session.rs
index 1c5196b..129d929 100644
--- a/core/nectarlink-core/src/session.rs
+++ b/core/nectarlink-core/src/session.rs
@@ -170,6 +170,7 @@ impl Session {
_ = reader(&s, recv, &weak) => {}
_ = heartbeat(&s, &weak) => {}
_ = streams(&s, &weak) => {}
+ _ = datagrams(&s, &weak) => {}
_ = s.conn.closed() => {}
}
cancel.cancel();
@@ -215,6 +216,16 @@ impl Session {
!self.cancel.is_cancelled() && self.conn.close_reason().is_none()
}
+ /// Sends a QUIC datagram (protocol v0 §4).
+ pub fn send_datagram(&self, data: bytes::Bytes) -> Result<()> {
+ self.conn.send_datagram(data).map_err(crate::error::net)
+ }
+
+ /// Opens a bidirectional stream on the session connection.
+ pub async fn open_bi(&self) -> Result<(SendStream, RecvStream)> {
+ self.conn.open_bi().await.map_err(crate::error::net)
+ }
+
/// Queues a one-way message.
pub async fn send(&self, env: Envelope) -> Result<()> {
self.outbox.send(env).await.map_err(|_| Error::Offline)
@@ -389,6 +400,7 @@ async fn handle(shared: &Arc<Shared>, session: &Arc<Session>, env: Envelope) ->
t if t.starts_with("contacts.") && crate::contacts::handle(shared, session, &env).await? => {}
t if t.starts_with("sms.") && crate::sms::handle(shared, session, &env).await? => {}
t if t.starts_with("mirror.") && crate::mirror::handle(shared, session, &env).await? => {}
+ t if t.starts_with("remote.") && crate::remote::handle(shared, session, &env).await? => {}
other => {
if env.id.is_some() {
let reply = Envelope::error(ErrorCode::Unsupported, format!("unknown message type {other}"));
@@ -417,6 +429,22 @@ async fn streams(session: &Arc<Session>, shared: &Weak<Shared>) {
}
}
+async fn datagrams(session: &Arc<Session>, shared: &Weak<Shared>) {
+ loop {
+ match session.conn.read_datagram().await {
+ Ok(bytes) => {
+ let Some(shared) = shared.upgrade() else { return };
+ crate::remote::handle_datagram(&shared, session.peer, &bytes);
+ }
+ Err(_) => {
+ // If datagrams aren't available on this connection, stay parked
+ // until the session ends rather than tearing it down.
+ std::future::pending::<()>().await;
+ }
+ }
+ }
+}
+
async fn heartbeat(session: &Arc<Session>, shared: &Weak<Shared>) {
let started = Instant::now();
let mut interval = tokio::time::interval(HEARTBEAT_INTERVAL);
diff --git a/core/nectarlink-core/src/transfer.rs b/core/nectarlink-core/src/transfer.rs
index 823afb1..d6e7d4a 100644
--- a/core/nectarlink-core/src/transfer.rs
+++ b/core/nectarlink-core/src/transfer.rs
@@ -563,6 +563,13 @@ pub(crate) async fn accept_stream(
Some(h) if h.svc == mirror::SERVICE && h.op == mirror::OP_AUDIO && h.v == mirror::VERSION => {
crate::mirror::receive_audio(shared, session.peer, send, recv).await;
}
+ Some(h)
+ if h.svc == nectarlink_protocol::messages::remote::SERVICE
+ && h.op == nectarlink_protocol::messages::remote::OP_MOTION
+ && h.v == 1 =>
+ {
+ crate::remote::receive_motion(shared, session.peer, send, recv).await;
+ }
_ => {
let reply = Envelope::error(ErrorCode::Unsupported, "unknown stream");
let _ = write_frame(&mut send, &reply.to_cbor()).await;
diff --git a/core/nectarlink-core/tests/two_devices.rs b/core/nectarlink-core/tests/two_devices.rs
index 18cec9f..6f21444 100644
--- a/core/nectarlink-core/tests/two_devices.rs
+++ b/core/nectarlink-core/tests/two_devices.rs
@@ -40,6 +40,7 @@ struct RecordingPlatform {
photos: Mutex<std::collections::HashMap<String, std::path::PathBuf>>,
/// Optional barrier `open_photo` waits on to simulate a slow platform call.
photo_barrier: Mutex<Option<Arc<std::sync::Barrier>>>,
+ remote_inputs: Mutex<Vec<nectarlink_core::RemoteInput>>,
}
impl Platform for RecordingPlatform {
@@ -381,6 +382,14 @@ impl Platform for RecordingPlatform {
self.media.lock().unwrap().push((player.to_owned(), action, position));
Ok(())
}
+ fn remote_input(
+ &self,
+ _peer: &nectarlink_core::DeviceId,
+ input: nectarlink_core::RemoteInput,
+ ) -> Result<(), String> {
+ self.remote_inputs.lock().unwrap().push(input);
+ Ok(())
+ }
}
#[derive(Debug, Default)]
@@ -2058,3 +2067,120 @@ async fn gallery_albums_paging_thumbs_download_and_toggles() {
assert!(matches!(pc.node.photo_thumbs(phone_id, vec!["media:4".into()]).await, Err(Error::Denied)));
assert!(matches!(pc.node.fetch_photos(phone_id, vec!["media:4".into()]).await, Err(Error::Denied)));
}
+
+#[tokio::test(flavor = "multi_thread")]
+async fn remote_input_needs_toggle_and_delivers_motion_keys_and_slides() {
+ use nectarlink_core::{
+ ButtonAction, INPUT_INJECT, KeyMod, MouseButton, RemoteInput, SlideAction, remote_keys,
+ };
+
+ 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());
+
+ // Without `input.inject` on the PC, remote input is unsupported.
+ assert!(matches!(phone.node.remote_check(pc_id).await, Err(Error::Unsupported)));
+ assert!(matches!(
+ phone
+ .node
+ .remote_input(
+ pc_id,
+ RemoteInput::Button { button: MouseButton::Left, action: ButtonAction::Click }
+ )
+ .await,
+ Err(Error::Unsupported)
+ ));
+
+ // The PC announces `input.inject`.
+ pc.node.update_power(PowerLevel::NotApplicable, vec!["media.control".into(), INPUT_INJECT.into()]).await;
+ wait_for(&mut phone, "input.remote available on phone", |e| match e {
+ NodeEvent::Capabilities(m)
+ if m.device == pc_id && m.state("input.remote") == Some(FeatureState::Available) =>
+ {
+ Some(())
+ }
+ _ => None,
+ })
+ .await;
+
+ // On the PC, `remote_input` is off by default: the first ask is refused and
+ // triggers the one-time prompt event on the PC.
+ let toggles = pc.node.device_toggles(phone_id).unwrap();
+ assert!(toggles.contains(&("remote_input", false)));
+ assert!(matches!(phone.node.remote_check(pc_id).await, Err(Error::Denied)));
+ wait_for(&mut pc, "remote input prompt", |e| match e {
+ NodeEvent::RemoteInputRequested { device } if *device == phone_id => Some(()),
+ _ => None,
+ })
+ .await;
+
+ // While the toggle is off, discrete and datagram inputs are both refused.
+ assert!(matches!(
+ phone
+ .node
+ .remote_input(
+ pc_id,
+ RemoteInput::Button { button: MouseButton::Left, action: ButtonAction::Click }
+ )
+ .await,
+ Err(Error::Denied)
+ ));
+ assert!(matches!(
+ phone.node.remote_input(pc_id, RemoteInput::Move { dx: 10.0, dy: 20.0 }).await,
+ Err(Error::Denied)
+ ));
+ phone.node.remote_move(pc_id, 10.0, 20.0).await.unwrap();
+ tokio::time::sleep(Duration::from_millis(50)).await;
+ assert!(pc.platform.remote_inputs.lock().unwrap().is_empty(), "nothing injected while toggle is off");
+
+ // The PC user enables `remote_input` for this phone.
+ pc.node.set_device_toggle(phone_id, "remote_input", true).unwrap();
+ with_timeout("remote_check allowed", phone.node.remote_check(pc_id)).await.unwrap();
+
+ // Pointer motion (datagram), buttons, drag, scroll, text, keys, slides, and laser.
+ phone.node.remote_move(pc_id, 18.5, -12.0).await.unwrap();
+ let deadline = tokio::time::Instant::now() + WAIT;
+ loop {
+ if pc.platform.remote_inputs.lock().unwrap().contains(&RemoteInput::Move { dx: 18.5, dy: -12.0 }) {
+ break;
+ }
+ assert!(tokio::time::Instant::now() < deadline, "timed out waiting for move datagram");
+ tokio::time::sleep(Duration::from_millis(20)).await;
+ }
+
+ let events = vec![
+ RemoteInput::Button { button: MouseButton::Left, action: ButtonAction::Click },
+ RemoteInput::Button { button: MouseButton::Right, action: ButtonAction::Click },
+ RemoteInput::Button { button: MouseButton::Left, action: ButtonAction::Down },
+ RemoteInput::Button { button: MouseButton::Left, action: ButtonAction::Up },
+ RemoteInput::Scroll { dx: 0.0, dy: -3.0 },
+ RemoteInput::Text { text: "Hello Nectarlink 🐝".into() },
+ RemoteInput::Key { key: remote_keys::ENTER.into(), mods: vec![] },
+ RemoteInput::Key { key: "c".into(), mods: vec![KeyMod::Ctrl] },
+ RemoteInput::Key { key: remote_keys::COPY.into(), mods: vec![] },
+ RemoteInput::Slide { action: SlideAction::Next },
+ RemoteInput::Slide { action: SlideAction::Previous },
+ RemoteInput::Slide { action: SlideAction::Black },
+ ];
+ for ev in &events {
+ with_timeout("remote_input", phone.node.remote_input(pc_id, ev.clone())).await.unwrap();
+ }
+ with_timeout("laser off", phone.node.remote_laser(pc_id, false, 0.0, 0.0)).await.unwrap();
+
+ let recorded = pc.platform.remote_inputs.lock().unwrap().clone();
+ for ev in &events {
+ assert!(recorded.contains(ev), "missing {ev:?} in {recorded:?}");
+ }
+ assert!(recorded.contains(&RemoteInput::Laser { on: false, x: 0.0, y: 0.0 }));
+
+ // Invalid inputs are rejected.
+ assert!(
+ phone
+ .node
+ .remote_input(pc_id, RemoteInput::Key { key: "unknown_key".into(), mods: vec![] })
+ .await
+ .is_err()
+ );
+ assert!(phone.node.remote_move(pc_id, 99999.0, 0.0).await.is_err());
+}
diff --git a/core/nectarlink-ffi/src/lib.rs b/core/nectarlink-ffi/src/lib.rs
index 4db562b..a64dc38 100644
--- a/core/nectarlink-ffi/src/lib.rs
+++ b/core/nectarlink-ffi/src/lib.rs
@@ -458,6 +458,11 @@ pub enum Event {
PhotosChanged {
id: String,
},
+ /// A paired phone asked to control this PC while `remote_input` is off
+ /// (PCs only).
+ RemoteInputRequested {
+ id: String,
+ },
}
/// What a mirroring video packet holds (docs/protocol/mirror.md).
@@ -1220,6 +1225,9 @@ impl From<NodeEvent> for Event {
NodeEvent::Mirroring { device, session, on } => {
Event::Mirroring { id: device.to_string(), session, on }
}
+ NodeEvent::RemoteInputRequested { device } => {
+ Event::RemoteInputRequested { id: device.to_string() }
+ }
}
}
}
@@ -1917,6 +1925,118 @@ impl NectarlinkNode {
self.run(async move { Ok(node.open_link(id, url).await?) }).await
}
+ // ---- Remote input (touchpad, keyboard, presentation) ----
+
+ /// Checks whether a paired PC allows remote mouse/keyboard input from this
+ /// phone (`NectarlinkError::Denied` when `remote_input` is off on the PC,
+ /// which also triggers a one-time confirmation prompt there).
+ pub async fn remote_check(&self, id: String) -> Result<()> {
+ let id = parse_id(&id)?;
+ let node = self.node.clone();
+ self.run(async move { Ok(node.remote_check(id).await?) }).await
+ }
+
+ /// Moves a paired PC's mouse cursor by `(dx, dy)` logical pixels over
+ /// QUIC datagrams (or the `remote/motion` stream fallback).
+ pub async fn remote_move(&self, id: String, dx: f32, dy: f32) -> Result<()> {
+ let id = parse_id(&id)?;
+ let node = self.node.clone();
+ self.run(async move { Ok(node.remote_move(id, dx, dy).await?) }).await
+ }
+
+ /// Scrolls on a paired PC (`dy` > 0 scrolls down, `dx` > 0 scrolls right,
+ /// in wheel notches). When `fast` is true, sends over QUIC datagrams.
+ pub async fn remote_scroll(&self, id: String, dx: f32, dy: f32, fast: bool) -> Result<()> {
+ let id = parse_id(&id)?;
+ let node = self.node.clone();
+ self.run(async move {
+ if fast {
+ Ok(node.remote_scroll_fast(id, dx, dy).await?)
+ } else {
+ Ok(node.remote_input(id, core::RemoteInput::Scroll { dx, dy }).await?)
+ }
+ })
+ .await
+ }
+
+ /// Presses, releases or clicks a mouse button (`"left"`, `"right"` or
+ /// `"middle"`; `action`: `"down"`, `"up"` or `"click"`) on a paired PC.
+ pub async fn remote_button(&self, id: String, button: String, action: String) -> Result<()> {
+ let id = parse_id(&id)?;
+ let button = match button.as_str() {
+ "left" => core::MouseButton::Left,
+ "right" => core::MouseButton::Right,
+ "middle" => core::MouseButton::Middle,
+ _ => return Err(NectarlinkError::Internal { reason: format!("invalid mouse button: {button}") }),
+ };
+ let action = match action.as_str() {
+ "down" => core::ButtonAction::Down,
+ "up" => core::ButtonAction::Up,
+ "click" => core::ButtonAction::Click,
+ _ => {
+ return Err(NectarlinkError::Internal { reason: format!("invalid button action: {action}") });
+ }
+ };
+ let node = self.node.clone();
+ self.run(
+ async move { Ok(node.remote_input(id, core::RemoteInput::Button { button, action }).await?) },
+ )
+ .await
+ }
+
+ /// Types Unicode text on a paired PC.
+ pub async fn remote_text(&self, id: String, text: String) -> Result<()> {
+ let id = parse_id(&id)?;
+ let node = self.node.clone();
+ self.run(async move { Ok(node.remote_input(id, core::RemoteInput::Text { text }).await?) }).await
+ }
+
+ /// Presses a named key or shortcut (`key`) with optional modifiers
+ /// (`"ctrl"`, `"alt"`, `"shift"`, `"win"`) on a paired PC.
+ pub async fn remote_key(&self, id: String, key: String, mods: Vec<String>) -> Result<()> {
+ let id = parse_id(&id)?;
+ let mut parsed_mods = Vec::with_capacity(mods.len());
+ for m in mods {
+ let km = match m.as_str() {
+ "ctrl" => core::KeyMod::Ctrl,
+ "alt" => core::KeyMod::Alt,
+ "shift" => core::KeyMod::Shift,
+ "win" => core::KeyMod::Win,
+ _ => return Err(NectarlinkError::Internal { reason: format!("invalid key modifier: {m}") }),
+ };
+ parsed_mods.push(km);
+ }
+ let node = self.node.clone();
+ self.run(async move {
+ Ok(node.remote_input(id, core::RemoteInput::Key { key, mods: parsed_mods }).await?)
+ })
+ .await
+ }
+
+ /// Sends a presentation slide command (`"next"`, `"previous"`, `"start"`,
+ /// `"stop"` or `"black"`) to a paired PC.
+ pub async fn remote_slide(&self, id: String, action: String) -> Result<()> {
+ let id = parse_id(&id)?;
+ let action = match action.as_str() {
+ "next" => core::SlideAction::Next,
+ "previous" | "prev" => core::SlideAction::Previous,
+ "start" => core::SlideAction::Start,
+ "stop" => core::SlideAction::Stop,
+ "black" => core::SlideAction::Black,
+ _ => return Err(NectarlinkError::Internal { reason: format!("invalid slide action: {action}") }),
+ };
+ let node = self.node.clone();
+ self.run(async move { Ok(node.remote_input(id, core::RemoteInput::Slide { action }).await?) }).await
+ }
+
+ /// Moves or hides the laser pointer overlay on a paired PC (`x`, `y` in
+ /// `0.0..=1.0`).
+ pub async fn remote_laser(&self, id: String, on: bool, x: f32, y: f32) -> Result<()> {
+ let id = parse_id(&id)?;
+ let node = self.node.clone();
+ self.run(async move { Ok(node.remote_laser(id, on, x, y).await?) }).await
+ }
+
/// Opens this phone's screen stream to a PC that asked (after the user
/// agreed).
pub async fn mirror_open(&self, pc_id: String) -> Result<Arc<MirrorStream>> {
diff --git a/core/nectarlink-protocol/src/messages.rs b/core/nectarlink-protocol/src/messages.rs
index 11031ca..57c8c5d 100644
--- a/core/nectarlink-protocol/src/messages.rs
+++ b/core/nectarlink-protocol/src/messages.rs
@@ -68,6 +68,8 @@ pub mod types {
pub const MIRROR_RESIZE: &str = "mirror.resize";
pub const MIRROR_INPUT: &str = "mirror.input";
pub const MIRROR_APPS: &str = "mirror.apps";
+ pub const REMOTE_CHECK: &str = "remote.check";
+ pub const REMOTE_INPUT: &str = "remote.input";
}
/// What kind of device this is.
@@ -1628,6 +1630,255 @@ pub struct PeerIdentity {
pub device: DeviceInfo,
}
+/// Limits and wire constants for `remote.*` (`docs/protocol/remote.md`).
+pub mod remote {
+ /// One-byte QUIC datagram channel tag (`docs/protocol/v0.md` §4).
+ pub const DATAGRAM_TAG: u8 = 0x01;
+ /// Largest datagram body accepted after [`DATAGRAM_TAG`].
+ pub const MAX_DATAGRAM_BYTES: usize = 256;
+ /// Largest relative pointer step (`dx` or `dy`), in logical pixels.
+ pub const MAX_MOVE_DELTA: f32 = 4000.0;
+ /// Largest scroll step (`dx` or `dy`), in wheel notches.
+ pub const MAX_SCROLL_DELTA: f32 = 200.0;
+ /// Most UTF-8 bytes in one `Text` event.
+ pub const MAX_TEXT_BYTES: usize = 256;
+ /// Most modifiers on a key press.
+ pub const MAX_MODS: usize = 4;
+ /// Stream service and operation when falling back from datagrams.
+ pub const SERVICE: &str = "remote";
+ pub const OP_MOTION: &str = "motion";
+ pub const VERSION: u32 = 1;
+}
+
+/// A mouse button on the PC (`docs/protocol/remote.md` §3).
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
+#[serde(rename_all = "lowercase")]
+pub enum MouseButton {
+ Left,
+ Right,
+ Middle,
+}
+
+/// What to do with a [`MouseButton`].
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "lowercase")]
+pub enum ButtonAction {
+ Down,
+ Up,
+ Click,
+}
+
+/// A modifier held during a [`RemoteInput::Key`] press.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
+#[serde(rename_all = "lowercase")]
+pub enum KeyMod {
+ Ctrl,
+ Alt,
+ Shift,
+ Win,
+}
+
+/// A presentation remote action (`docs/protocol/remote.md` §3).
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "snake_case")]
+pub enum SlideAction {
+ Next,
+ Previous,
+ Start,
+ Stop,
+ Black,
+}
+
+/// Keys and shortcuts accepted by [`RemoteInput::Key`].
+pub mod remote_keys {
+ use super::KeyMod;
+
+ pub const ENTER: &str = "enter";
+ pub const BACKSPACE: &str = "backspace";
+ pub const TAB: &str = "tab";
+ pub const ESCAPE: &str = "escape";
+ pub const SPACE: &str = "space";
+ pub const LEFT: &str = "left";
+ pub const RIGHT: &str = "right";
+ pub const UP: &str = "up";
+ pub const DOWN: &str = "down";
+ pub const HOME: &str = "home";
+ pub const END: &str = "end";
+ pub const PAGE_UP: &str = "page_up";
+ pub const PAGE_DOWN: &str = "page_down";
+ pub const DELETE: &str = "delete";
+ pub const F1: &str = "f1";
+ pub const F2: &str = "f2";
+ pub const F3: &str = "f3";
+ pub const F4: &str = "f4";
+ pub const F5: &str = "f5";
+ pub const F6: &str = "f6";
+ pub const F7: &str = "f7";
+ pub const F8: &str = "f8";
+ pub const F9: &str = "f9";
+ pub const F10: &str = "f10";
+ pub const F11: &str = "f11";
+ pub const F12: &str = "f12";
+ pub const WIN: &str = "win";
+
+ pub const NAMED: &[&str] = &[
+ ENTER, BACKSPACE, TAB, ESCAPE, SPACE, LEFT, RIGHT, UP, DOWN, HOME, END, PAGE_UP, PAGE_DOWN, DELETE,
+ F1, F2, F3, F4, F5, F6, F7, F8, F9, F10, F11, F12, WIN,
+ ];
+
+ /// Common shortcut aliases (`mods` must be empty when using an alias).
+ pub const COPY: &str = "copy";
+ pub const PASTE: &str = "paste";
+ pub const CUT: &str = "cut";
+ pub const UNDO: &str = "undo";
+ pub const SELECT_ALL: &str = "select_all";
+ pub const TASK_VIEW: &str = "task_view";
+ pub const LOCK: &str = "lock";
+
+ pub const SHORTCUTS: &[&str] = &[COPY, PASTE, CUT, UNDO, SELECT_ALL, TASK_VIEW, LOCK];
+
+ /// Whether `key` and `mods` form a valid [`super::RemoteInput::Key`].
+ pub fn is_valid(key: &str, mods: &[KeyMod]) -> bool {
+ if mods.len() > super::remote::MAX_MODS {
+ return false;
+ }
+ // Reject duplicate modifiers.
+ for (i, m) in mods.iter().enumerate() {
+ if mods[i + 1..].contains(m) {
+ return false;
+ }
+ }
+ if NAMED.contains(&key) {
+ return true;
+ }
+ if SHORTCUTS.contains(&key) {
+ return mods.is_empty();
+ }
+ // Single ASCII lowercase letter or digit is valid when combined with at
+ // least one modifier (e.g. Ctrl+C, Win+L, Alt+1).
+ if let [b] = key.as_bytes() {
+ return !mods.is_empty() && (b.is_ascii_lowercase() || b.is_ascii_digit());
+ }
+ false
+ }
+}
+
+/// An input event sent from a phone to a PC (`docs/protocol/remote.md`).
+#[derive(Clone, PartialEq, Serialize, Deserialize)]
+#[serde(tag = "type", rename_all = "lowercase")]
+pub enum RemoteInput {
+ /// Relative pointer motion in logical pixels (`dx` right, `dy` down).
+ /// Travels in QUIC datagrams (or the `remote/motion` stream), never on the
+ /// control stream.
+ Move { dx: f32, dy: f32 },
+ /// Mouse button press, release or click.
+ Button { button: MouseButton, action: ButtonAction },
+ /// Smooth or stepped scroll in wheel notches (`dx` right, `dy` vertical).
+ Scroll { dx: f32, dy: f32 },
+ /// Typed Unicode text.
+ Text { text: String },
+ /// A named key, modified key, or shortcut.
+ Key {
+ key: String,
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ mods: Vec<KeyMod>,
+ },
+ /// A presentation remote action.
+ Slide { action: SlideAction },
+ /// Laser pointer position on the PC's primary screen (`0.0..=1.0`).
+ Laser {
+ on: bool,
+ #[serde(default)]
+ x: f32,
+ #[serde(default)]
+ y: f32,
+ },
+}
+
+/// Never prints typed text (protocol v0 §11).
+impl std::fmt::Debug for RemoteInput {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ match self {
+ RemoteInput::Move { dx, dy } => write!(f, "Move({dx}, {dy})"),
+ RemoteInput::Button { button, action } => write!(f, "Button({button:?}, {action:?})"),
+ RemoteInput::Scroll { dx, dy } => write!(f, "Scroll({dx}, {dy})"),
+ RemoteInput::Text { text } => write!(f, "Text({} bytes)", text.len()),
+ RemoteInput::Key { key, mods } if mods.is_empty() => write!(f, "Key({key})"),
+ RemoteInput::Key { key, mods } => write!(f, "Key({mods:?}+{key})"),
+ RemoteInput::Slide { action } => write!(f, "Slide({action:?})"),
+ RemoteInput::Laser { on: false, .. } => f.write_str("Laser(off)"),
+ RemoteInput::Laser { on: true, x, y } => write!(f, "Laser({x}, {y})"),
+ }
+ }
+}
+
+impl RemoteInput {
+ pub fn is_valid(&self) -> bool {
+ match self {
+ RemoteInput::Move { dx, dy } => {
+ dx.is_finite()
+ && dy.is_finite()
+ && dx.abs() <= remote::MAX_MOVE_DELTA
+ && dy.abs() <= remote::MAX_MOVE_DELTA
+ }
+ RemoteInput::Button { .. } => true,
+ RemoteInput::Scroll { dx, dy } => {
+ dx.is_finite()
+ && dy.is_finite()
+ && dx.abs() <= remote::MAX_SCROLL_DELTA
+ && dy.abs() <= remote::MAX_SCROLL_DELTA
+ }
+ RemoteInput::Text { text } => {
+ !text.is_empty()
+ && text.len() <= remote::MAX_TEXT_BYTES
+ && !text.chars().any(char::is_control)
+ }
+ RemoteInput::Key { key, mods } => remote_keys::is_valid(key, mods),
+ RemoteInput::Slide { .. } => true,
+ RemoteInput::Laser { on, x, y } => {
+ x.is_finite()
+ && y.is_finite()
+ && (!*on || ((0.0..=1.0).contains(x) && (0.0..=1.0).contains(y)))
+ }
+ }
+ }
+
+ /// Whether this event may travel in a lossy QUIC datagram.
+ pub fn is_datagram_allowed(&self) -> bool {
+ matches!(self, RemoteInput::Move { .. } | RemoteInput::Scroll { .. } | RemoteInput::Laser { .. })
+ }
+
+ /// Whether this event may travel in a `remote.input` control request.
+ /// Pointer motion (`Move`) never uses the control stream.
+ pub fn is_control_allowed(&self) -> bool {
+ !matches!(self, RemoteInput::Move { .. })
+ }
+
+ /// Encodes a datagram prefixed with [`remote::DATAGRAM_TAG`].
+ pub fn to_datagram(&self) -> Vec<u8> {
+ let mut out = vec![remote::DATAGRAM_TAG];
+ ciborium::into_writer(self, &mut out).expect("writing to a Vec cannot fail");
+ out
+ }
+
+ /// Decodes and validates a datagram prefixed with [`remote::DATAGRAM_TAG`].
+ pub fn from_datagram(bytes: &[u8]) -> Result<Self, crate::ProtocolError> {
+ if bytes.first().copied() != Some(remote::DATAGRAM_TAG) {
+ return Err(crate::ProtocolError::BadMessage("unknown datagram channel tag".into()));
+ }
+ let body = &bytes[1..];
+ if body.is_empty() || body.len() > remote::MAX_DATAGRAM_BYTES {
+ return Err(crate::ProtocolError::FrameTooLarge(body.len()));
+ }
+ let input: Self =
+ ciborium::from_reader(body).map_err(|e| crate::ProtocolError::BadMessage(e.to_string()))?;
+ if !input.is_valid() || !input.is_datagram_allowed() {
+ return Err(crate::ProtocolError::BadMessage("invalid remote input datagram".into()));
+ }
+ Ok(input)
+ }
+}
+
#[cfg(test)]
mod tests {
use super::*;
@@ -1933,4 +2184,61 @@ mod tests {
let multi = PhotoGet { id: String::new(), ids: vec!["p1".into(), "p2".into()] };
assert_eq!(multi.requested_ids(), vec!["p1".to_owned(), "p2".to_owned()]);
}
+
+ #[test]
+ fn remote_input_validates_and_round_trips() {
+ // Datagram round-trip for move, scroll, and laser.
+ let mv = RemoteInput::Move { dx: 12.5, dy: -8.0 };
+ assert!(mv.is_valid() && mv.is_datagram_allowed() && !mv.is_control_allowed());
+ let dgram = mv.to_datagram();
+ assert_eq!(dgram[0], remote::DATAGRAM_TAG);
+ assert_eq!(RemoteInput::from_datagram(&dgram).unwrap(), mv);
+
+ let laser = RemoteInput::Laser { on: true, x: 0.25, y: 0.75 };
+ assert_eq!(RemoteInput::from_datagram(&laser.to_datagram()).unwrap(), laser);
+ let laser_off = RemoteInput::Laser { on: false, x: 0.0, y: 0.0 };
+ assert_eq!(RemoteInput::from_datagram(&laser_off.to_datagram()).unwrap(), laser_off);
+
+ // Button or key in a datagram is rejected.
+ let click = RemoteInput::Button { button: MouseButton::Left, action: ButtonAction::Click };
+ assert!(click.is_valid() && click.is_control_allowed() && !click.is_datagram_allowed());
+ assert!(RemoteInput::from_datagram(&click.to_datagram()).is_err());
+
+ // Bounds checks.
+ assert!(!RemoteInput::Move { dx: 5000.0, dy: 0.0 }.is_valid());
+ assert!(!RemoteInput::Move { dx: f32::NAN, dy: 0.0 }.is_valid());
+ assert!(!RemoteInput::Scroll { dx: 0.0, dy: 250.0 }.is_valid());
+ assert!(!RemoteInput::Laser { on: true, x: 1.2, y: 0.5 }.is_valid());
+ assert!(!RemoteInput::Laser { on: true, x: -0.1, y: 0.5 }.is_valid());
+
+ // Text and keys.
+ let text = RemoteInput::Text { text: "Hello 🐝 नमस्ते".into() };
+ assert!(text.is_valid());
+ assert!(!format!("{text:?}").contains("Hello"));
+ assert!(!RemoteInput::Text { text: String::new() }.is_valid());
+ assert!(!RemoteInput::Text { text: "bad\nnewline".into() }.is_valid());
+ assert!(!RemoteInput::Text { text: "x".repeat(remote::MAX_TEXT_BYTES + 1) }.is_valid());
+
+ for k in remote_keys::NAMED {
+ assert!(RemoteInput::Key { key: (*k).into(), mods: vec![] }.is_valid(), "{k}");
+ }
+ for s in remote_keys::SHORTCUTS {
+ assert!(RemoteInput::Key { key: (*s).into(), mods: vec![] }.is_valid(), "{s}");
+ assert!(!RemoteInput::Key { key: (*s).into(), mods: vec![KeyMod::Ctrl] }.is_valid(), "{s}");
+ }
+ assert!(RemoteInput::Key { key: "c".into(), mods: vec![KeyMod::Ctrl] }.is_valid());
+ assert!(RemoteInput::Key { key: "z".into(), mods: vec![KeyMod::Ctrl, KeyMod::Shift] }.is_valid());
+ assert!(
+ !RemoteInput::Key { key: "c".into(), mods: vec![] }.is_valid(),
+ "unmodified letter uses Text"
+ );
+ assert!(!RemoteInput::Key { key: "c".into(), mods: vec![KeyMod::Ctrl, KeyMod::Ctrl] }.is_valid());
+ assert!(!RemoteInput::Key { key: "f13".into(), mods: vec![] }.is_valid());
+ assert!(!RemoteInput::Key { key: "power".into(), mods: vec![] }.is_valid());
+
+ // Slide round-trip on the control stream.
+ let slide = RemoteInput::Slide { action: SlideAction::Next };
+ let env = Envelope::new(types::REMOTE_INPUT, &slide).unwrap();
+ assert_eq!(env.body::<RemoteInput>().unwrap(), slide);
+ }
}
diff --git a/desktop/app/Cargo.toml b/desktop/app/Cargo.toml
index b451596..59c931d 100644
--- a/desktop/app/Cargo.toml
+++ b/desktop/app/Cargo.toml
@@ -56,6 +56,7 @@ windows = { workspace = true, features = [
"Win32_System_Shutdown",
"Win32_System_Threading",
"Win32_System_WinRT",
+ "Win32_UI_Input_KeyboardAndMouse",
"Win32_UI_Shell",
"Win32_UI_WindowsAndMessaging",
"Win32_NetworkManagement_IpHelper",
diff --git a/desktop/app/build.rs b/desktop/app/build.rs
index b303be1..b53c6e5 100644
--- a/desktop/app/build.rs
+++ b/desktop/app/build.rs
@@ -17,6 +17,7 @@ mod mark;
const QML: &[&str] = &[
"qml/App.qml",
+ "qml/LaserOverlay.qml",
"qml/MainWindow.qml",
"qml/MirrorWindow.qml",
"qml/components/AppsSheet.qml",
diff --git a/desktop/app/qml/App.qml b/desktop/app/qml/App.qml
index b0cce7e..95183e9 100644
--- a/desktop/app/qml/App.qml
+++ b/desktop/app/qml/App.qml
@@ -11,6 +11,7 @@ QtObject {
id: app
property MainWindow mainWindow: null
+ readonly property LaserOverlay laserOverlay: LaserOverlay {}
// A window for each phone screen or app being mirrored. The model
// keeps a row per window (by key), so a window lives as long as its
// mirroring, whatever else changes.
@@ -87,5 +88,11 @@ QtObject {
app.mainWindow.flash()
}
}
+ function onRemotePromptDeviceIdChanged() {
+ if (AppController.remotePromptDeviceId.length > 0) {
+ app.showMain()
+ app.mainWindow.flash()
+ }
+ }
}
}
diff --git a/desktop/app/qml/LaserOverlay.qml b/desktop/app/qml/LaserOverlay.qml
new file mode 100644
index 0000000..deb2fd2
--- /dev/null
+++ b/desktop/app/qml/LaserOverlay.qml
@@ -0,0 +1,60 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+import QtQuick
+import QtQuick.Window
+import app.nectarlink
+
+// Click-through, always-on-top laser pointer dot controlled by a paired phone
+// in presentation mode (docs/protocol/remote.md).
+Window {
+ id: overlay
+
+ flags: Qt.Tool | Qt.FramelessWindowHint | Qt.WindowStaysOnTopHint
+ | Qt.WindowTransparentForInput | Qt.WindowDoesNotAcceptFocus
+ color: "transparent"
+ width: 56
+ height: 56
+ visible: dotRoot.opacity > 0.01
+
+ x: Math.round(Screen.virtualX + AppController.laserX * Math.max(1, Screen.width) - width / 2)
+ y: Math.round(Screen.virtualY + AppController.laserY * Math.max(1, Screen.height) - height / 2)
+
+ Item {
+ id: dotRoot
+ anchors.fill: parent
+ opacity: AppController.laserActive ? 1.0 : 0.0
+ Behavior on opacity {
+ NumberAnimation {
+ duration: Theme.reduceMotion ? 0 : 160
+ easing.type: Easing.OutCubic
+ }
+ }
+
+ Rectangle {
+ anchors.centerIn: parent
+ width: 48
+ height: 48
+ radius: 24
+ color: Theme.primary
+ opacity: 0.28
+ }
+
+ Rectangle {
+ anchors.centerIn: parent
+ width: 28
+ height: 28
+ radius: 14
+ color: Theme.primary
+ opacity: 0.58
+ }
+
+ Rectangle {
+ anchors.centerIn: parent
+ width: 14
+ height: 14
+ radius: 7
+ color: Theme.primary
+ border.width: 2
+ border.color: "#FFFFFF"
+ }
+ }
+}
diff --git a/desktop/app/qml/MainWindow.qml b/desktop/app/qml/MainWindow.qml
index f3d5fc7..9f60140 100644
--- a/desktop/app/qml/MainWindow.qml
+++ b/desktop/app/qml/MainWindow.qml
@@ -284,6 +284,54 @@ NativeWindow {
}
}
+ Sheet {
+ id: remotePromptSheet
+ opened: AppController.remotePromptDeviceId.length > 0
+ cardWidth: 420
+ onOpenedChanged: {
+ if (!opened && AppController.remotePromptDeviceId.length > 0)
+ AppController.dismissRemotePrompt()
+ }
+ Column {
+ width: parent.width
+ spacing: 16
+ Avatar {
+ anchors.horizontalCenter: parent.horizontalCenter
+ width: 56; height: 56
+ iconPath: Icons.phone
+ emphasized: true
+ }
+ Txt {
+ width: parent.width
+ horizontalAlignment: Text.AlignHCenter
+ text: qsTr("Allow %1 to control this PC?").arg(AppController.remotePromptDeviceName)
+ role: "headline"
+ wrapMode: Text.WordWrap
+ }
+ Txt {
+ width: parent.width
+ horizontalAlignment: Text.AlignHCenter
+ text: qsTr("%1 wants to move the mouse, type, and control presentations on this PC. You can change this anytime in Settings.").arg(AppController.remotePromptDeviceName)
+ role: "body"
+ muted: true
+ wrapMode: Text.WordWrap
+ }
+ Row {
+ anchors.right: parent.right
+ spacing: 10
+ Button {
+ variant: "text"
+ text: qsTr("Not now")
+ onClicked: AppController.dismissRemotePrompt()
+ }
+ Button {
+ text: qsTr("Allow")
+ onClicked: AppController.allowRemoteInput(AppController.remotePromptDeviceId)
+ }
+ }
+ }
+ }
+
CaptionButtons {
id: captionButtons
window: window
diff --git a/desktop/app/qml/pages/SettingsPage.qml b/desktop/app/qml/pages/SettingsPage.qml
index 52c6f08..85622a4 100644
--- a/desktop/app/qml/pages/SettingsPage.qml
+++ b/desktop/app/qml/pages/SettingsPage.qml
@@ -27,6 +27,7 @@ Item {
media: qsTr("Media playing on either device"),
photos: qsTr("Photos"),
pc_actions: qsTr("Lock and sleep this PC"),
+ remote_input: qsTr("Control this PC's mouse and keyboard"),
remote_files: qsTr("Browse this PC's files while away")
})
diff --git a/desktop/app/src/bridge/app.rs b/desktop/app/src/bridge/app.rs
index 16bbec6..da9e970 100644
--- a/desktop/app/src/bridge/app.rs
+++ b/desktop/app/src/bridge/app.rs
@@ -71,6 +71,15 @@ pub mod qobject {
#[qproperty(QString, update_version)]
/// Checking for or installing an update.
#[qproperty(bool, update_busy)]
+ /// Device ID and name of a phone asking to control this PC for the
+ /// first time while `remote_input` is off ("" when none).
+ #[qproperty(QString, remote_prompt_device_id)]
+ #[qproperty(QString, remote_prompt_device_name)]
+ /// Whether the presentation laser pointer overlay is showing, and its
+ /// normalized position on the primary screen (`0.0..=1.0`).
+ #[qproperty(bool, laser_active)]
+ #[qproperty(f32, laser_x)]
+ #[qproperty(f32, laser_y)]
type AppController = super::AppControllerRust;
/// Asks a paired device to ring (or stop).
@@ -79,6 +88,13 @@ pub mod qobject {
/// Stops this PC ringing.
#[qinvokable]
fn stop_ringing(self: Pin<&mut AppController>);
+ /// Allows a paired phone to control this PC's mouse and keyboard (from
+ /// the one-time prompt sheet).
+ #[qinvokable]
+ fn allow_remote_input(self: Pin<&mut AppController>, device: &QString);
+ /// Dismisses the one-time remote input prompt without enabling the toggle.
+ #[qinvokable]
+ fn dismiss_remote_prompt(self: Pin<&mut AppController>);
/// Reconnects to phones that aren't connected and syncs connected
/// ones (notifications, media).
#[qinvokable]
@@ -164,6 +180,11 @@ pub struct AppControllerRust {
can_update: bool,
update_version: QString,
update_busy: bool,
+ remote_prompt_device_id: QString,
+ remote_prompt_device_name: QString,
+ laser_active: bool,
+ laser_x: f32,
+ laser_y: f32,
tray: Option<tray::Tray>,
}
@@ -274,7 +295,7 @@ impl cxx_qt::Initialize for qobject::AppController {
*CONTROLLER.get_or_init(Mutex::default).lock().unwrap_or_else(|e| e.into_inner()) = Some(qt.clone());
super::subscribe(
qt.clone(),
- Changes::STATUS | Changes::DEVICES | Changes::CAPABILITIES | Changes::RINGING,
+ Changes::STATUS | Changes::DEVICES | Changes::CAPABILITIES | Changes::RINGING | Changes::REMOTE,
Self::refresh,
);
super::subscribe(qt.clone(), Changes::UPDATE, |object| {
@@ -364,8 +385,12 @@ fn ring_device(device: DeviceId, on: bool) {
impl qobject::AppController {
fn refresh(mut self: Pin<&mut Self>) {
let hub = &core_host::host().hub;
- let (status, devices, ringing, online, caps_version, battery) = hub.read(|s| {
+ let (status, devices, ringing, online, caps_version, battery, remote_prompt, laser) = hub.read(|s| {
let ringing = s.ringing_from.and_then(|id| s.name_of(&id)).unwrap_or_default();
+ let remote_prompt = s.remote_prompt.map(|id| {
+ let name = s.name_of(&id).unwrap_or_else(|| id.short());
+ (id.to_string(), name)
+ });
let connected: Vec<_> =
s.devices.iter().filter(|d| matches!(d.link, LinkState::Online { .. })).collect();
// With one phone connected, the tray shows its battery.
@@ -376,7 +401,16 @@ impl qobject::AppController {
}),
_ => None,
};
- (s.core_status(), s.devices.len(), ringing, connected.len(), s.matrices_version, battery)
+ (
+ s.core_status(),
+ s.devices.len(),
+ ringing,
+ connected.len(),
+ s.matrices_version,
+ battery,
+ remote_prompt,
+ s.laser,
+ )
});
let (status_text, error) = match &status {
CoreStatus::Starting => ("starting", String::new()),
@@ -391,6 +425,19 @@ impl qobject::AppController {
self.as_mut().set_error(QString::from(&error));
self.as_mut().set_has_devices(devices > 0);
self.as_mut().set_ringing_from(QString::from(&ringing));
+ let (prompt_id, prompt_name) = remote_prompt.unwrap_or_default();
+ self.as_mut().set_remote_prompt_device_id(QString::from(&prompt_id));
+ self.as_mut().set_remote_prompt_device_name(QString::from(&prompt_name));
+ match laser {
+ Some((_, x, y)) => {
+ self.as_mut().set_laser_x(x);
+ self.as_mut().set_laser_y(y);
+ self.as_mut().set_laser_active(true);
+ }
+ None => {
+ self.as_mut().set_laser_active(false);
+ }
+ }
// Truncation is fine: QML only compares revisions for equality.
self.as_mut().set_caps_revision(caps_version as i32);
@@ -444,6 +491,19 @@ impl qobject::AppController {
.update(|s| if s.ringing_from.take().is_some() { Changes::RINGING } else { Changes::NONE });
}
+ pub fn allow_remote_input(mut self: Pin<&mut Self>, device: &QString) {
+ self.as_mut().set_device_toggle(device, &QString::from("remote_input"), true);
+ core_host::host()
+ .hub
+ .update(|s| if s.remote_prompt.take().is_some() { Changes::REMOTE } else { Changes::NONE });
+ }
+
+ pub fn dismiss_remote_prompt(self: Pin<&mut Self>) {
+ core_host::host()
+ .hub
+ .update(|s| if s.remote_prompt.take().is_some() { Changes::REMOTE } else { Changes::NONE });
+ }
+
pub fn unpair(self: Pin<&mut Self>, device: &QString) {
let (Some(id), Some(node)) = (super::parse_device(device), core_host::node()) else { return };
core_host::spawn(async move {
@@ -475,9 +535,23 @@ impl qobject::AppController {
pub fn set_device_toggle(mut self: Pin<&mut Self>, device: &QString, name: &QString, on: bool) {
let (Some(id), Some(node)) = (super::parse_device(device), core_host::node()) else { return };
- if let Err(e) = node.set_device_toggle(id, &String::from(name), on) {
+ let name_str = String::from(name);
+ if let Err(e) = node.set_device_toggle(id, &name_str, on) {
show_message(describe(&e));
}
+ if name_str == "remote_input" {
+ if !on {
+ crate::remote::stop_all();
+ }
+ core_host::host().hub.update(|s| {
+ if s.remote_prompt == Some(id) {
+ s.remote_prompt = None;
+ Changes::REMOTE
+ } else {
+ Changes::NONE
+ }
+ });
+ }
let revision = self.toggles_revision.wrapping_add(1);
self.as_mut().set_toggles_revision(revision);
}
diff --git a/desktop/app/src/core_host.rs b/desktop/app/src/core_host.rs
index a1ea13e..5997cf0 100644
--- a/desktop/app/src/core_host.rs
+++ b/desktop/app/src/core_host.rs
@@ -104,6 +104,7 @@ async fn run(data_dir: PathBuf, platform: Arc<dyn Platform>) {
nectarlink_core::SMS_SHOW.into(),
nectarlink_core::MIRROR_VIEW.into(),
nectarlink_core::MIRROR_LISTEN.into(),
+ nectarlink_core::INPUT_INJECT.into(),
];
let node = match Node::start(config, platform).await {
Ok(node) => node,
@@ -154,6 +155,7 @@ async fn run(data_dir: PathBuf, platform: Arc<dyn Platform>) {
crate::calls::on_event(&event);
crate::messages::on_event(&event);
crate::mirror::on_event(&event);
+ crate::remote::on_event(&event);
crate::transfers::on_event(&event);
crate::send_to::on_event(&event);
crate::battery::on_event(&event);
diff --git a/desktop/app/src/main.rs b/desktop/app/src/main.rs
index d9078d3..d483a35 100644
--- a/desktop/app/src/main.rs
+++ b/desktop/app/src/main.rs
@@ -27,6 +27,7 @@ mod notifications;
mod palette;
mod photos;
mod qr;
+mod remote;
mod send_to;
mod settings;
mod startup;
@@ -94,6 +95,14 @@ impl Platform for DesktopPlatform {
) -> Option<std::sync::Arc<dyn nectarlink_core::MirrorSink>> {
mirror::sink(peer, session)
}
+ fn remote_input(
+ &self,
+ peer: &nectarlink_core::DeviceId,
+ input: nectarlink_core::RemoteInput,
+ ) -> Result<(), String> {
+ remote::handle_input(peer, input);
+ Ok(())
+ }
}
/// Command-line options (also used by shortcuts and autostart).
diff --git a/desktop/app/src/remote.rs b/desktop/app/src/remote.rs
new file mode 100644
index 0000000..5be13cd
--- /dev/null
+++ b/desktop/app/src/remote.rs
@@ -0,0 +1,87 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+//! Dispatches remote touchpad, keyboard and presentation input from a paired
+//! phone to `win::input` and updates the laser pointer overlay state.
+
+use std::{
+ sync::atomic::{AtomicU64, Ordering},
+ time::Duration,
+};
+
+use nectarlink_core::{DeviceId, LinkState, NodeEvent, RemoteInput};
+
+use crate::{core_host, state::Changes, win};
+
+/// When the laser pointer last heard from its phone (ms since the Unix
+/// epoch; 0 when it's off). The phone repeats it every second while held,
+/// so a dot that stops hearing (the phone left) is hidden.
+static LASER_SEEN: AtomicU64 = AtomicU64::new(0);
+const LASER_TIMEOUT: Duration = Duration::from_secs(4);
+
+fn now_ms() -> u64 {
+ std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.as_millis() as u64)
+}
+
+fn hide_laser() {
+ LASER_SEEN.store(0, Ordering::SeqCst);
+ core_host::host().hub.update(|s| if s.laser.take().is_some() { Changes::REMOTE } else { Changes::NONE });
+}
+
+pub fn handle_input(peer: &DeviceId, input: RemoteInput) {
+ match input {
+ RemoteInput::Move { dx, dy } => win::input::move_relative(dx, dy),
+ RemoteInput::Button { button, action } => win::input::mouse_button(button, action),
+ RemoteInput::Scroll { dx, dy } => win::input::scroll(dx, dy),
+ RemoteInput::Text { text } => win::input::type_text(&text),
+ RemoteInput::Key { key, mods } => win::input::press_key(&key, &mods),
+ RemoteInput::Slide { action } => win::input::slide(action),
+ RemoteInput::Laser { on: true, x, y } => {
+ let x = x.clamp(0.0, 1.0);
+ let y = y.clamp(0.0, 1.0);
+ let peer = *peer;
+ core_host::host().hub.update(|s| {
+ let next = Some((peer, x, y));
+ if s.laser == next {
+ return Changes::NONE;
+ }
+ s.laser = next;
+ Changes::REMOTE
+ });
+ // One watchdog while it's shown.
+ if LASER_SEEN.swap(now_ms(), Ordering::SeqCst) == 0 {
+ core_host::spawn(async {
+ loop {
+ tokio::time::sleep(Duration::from_millis(500)).await;
+ let seen = LASER_SEEN.load(Ordering::SeqCst);
+ if seen == 0 {
+ return;
+ }
+ if now_ms().saturating_sub(seen) > LASER_TIMEOUT.as_millis() as u64 {
+ hide_laser();
+ return;
+ }
+ }
+ });
+ }
+ }
+ RemoteInput::Laser { on: false, .. } => hide_laser(),
+ }
+}
+
+/// Clears any active laser pointer and releases held mouse buttons (e.g. when
+/// `remote_input` is turned off).
+pub fn stop_all() {
+ win::input::release_held_buttons();
+ hide_laser();
+}
+
+pub fn on_event(event: &NodeEvent) {
+ match event {
+ NodeEvent::LinkChanged { link: LinkState::Offline { .. }, .. } | NodeEvent::DeviceRemoved(_) => {
+ win::input::release_held_buttons();
+ }
+ NodeEvent::RemoteInputRequested { .. } => {
+ core_host::host().hub.update(|s| s.apply(event));
+ }
+ _ => {}
+ }
+}
diff --git a/desktop/app/src/state.rs b/desktop/app/src/state.rs
index 8651dc8..730206b 100644
--- a/desktop/app/src/state.rs
+++ b/desktop/app/src/state.rs
@@ -17,7 +17,7 @@ use nectarlink_core::{
/// Which parts of the state changed, so listeners refresh only what they show.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
-pub struct Changes(u16);
+pub struct Changes(u32);
impl Changes {
pub const NONE: Changes = Changes(0);
@@ -44,6 +44,8 @@ impl Changes {
pub const CALLS: Changes = Changes(1 << 14);
/// A phone's photo gallery (kept by crate::photos).
pub const PHOTOS: Changes = Changes(1 << 15);
+ /// Remote input prompt or laser pointer overlay state.
+ pub const REMOTE: Changes = Changes(1 << 16);
pub fn is_empty(self) -> bool {
self.0 == 0
@@ -237,6 +239,10 @@ pub struct AppState {
/// Notifications that went away, newest first, while history is kept.
pub history: Vec<HistoryEntry>,
pub history_enabled: bool,
+ /// Phone asking to control this PC for the first time while `remote_input` is off.
+ pub remote_prompt: Option<DeviceId>,
+ /// Active laser pointer overlay (`(device, x, y)` in `0.0..=1.0`).
+ pub laser: Option<(DeviceId, f32, f32)>,
}
impl AppState {
@@ -305,6 +311,14 @@ impl AppState {
self.ringing_from = None;
changes |= Changes::RINGING;
}
+ if self.remote_prompt == Some(*id) {
+ self.remote_prompt = None;
+ changes |= Changes::REMOTE;
+ }
+ if self.laser.is_some_and(|(d, _, _)| d == *id) {
+ self.laser = None;
+ changes |= Changes::REMOTE;
+ }
let notifications = self.notifications.len();
self.notifications.retain(|n| n.device != *id);
if self.notifications.len() != notifications {
@@ -341,6 +355,13 @@ impl AppState {
self.ringing_from = next;
Changes::RINGING
}
+ NodeEvent::RemoteInputRequested { device } => {
+ if self.remote_prompt == Some(*device) {
+ return Changes::NONE;
+ }
+ self.remote_prompt = Some(*device);
+ Changes::REMOTE
+ }
NodeEvent::Discovered(found) => {
match self.discovered.iter_mut().find(|d| d.id == found.id) {
Some(existing) if existing == found => return Changes::NONE,
diff --git a/desktop/app/src/win/input.rs b/desktop/app/src/win/input.rs
new file mode 100644
index 0000000..110c7e3
--- /dev/null
+++ b/desktop/app/src/win/input.rs
@@ -0,0 +1,346 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+//! Synthesizes mouse and keyboard input on Windows (`SendInput`) for a paired
+//! phone acting as a touchpad, keyboard or presentation remote
+//! (`docs/protocol/remote.md`).
+
+use std::sync::Mutex;
+
+use nectarlink_core::{ButtonAction, KeyMod, MouseButton, PowerAction, SlideAction};
+use windows::Win32::UI::{
+ Input::KeyboardAndMouse::{
+ INPUT, INPUT_0, INPUT_KEYBOARD, INPUT_MOUSE, KEYBD_EVENT_FLAGS, KEYBDINPUT, KEYEVENTF_EXTENDEDKEY,
+ KEYEVENTF_KEYUP, KEYEVENTF_UNICODE, MOUSE_EVENT_FLAGS, MOUSEEVENTF_HWHEEL, MOUSEEVENTF_LEFTDOWN,
+ MOUSEEVENTF_LEFTUP, MOUSEEVENTF_MIDDLEDOWN, MOUSEEVENTF_MIDDLEUP, MOUSEEVENTF_MOVE,
+ MOUSEEVENTF_RIGHTDOWN, MOUSEEVENTF_RIGHTUP, MOUSEEVENTF_WHEEL, MOUSEINPUT, SendInput, VIRTUAL_KEY,
+ VK_A, VK_B, VK_BACK, VK_C, VK_CONTROL, VK_DELETE, VK_DOWN, VK_END, VK_ESCAPE, VK_F1, VK_F5, VK_HOME,
+ VK_INSERT, VK_LEFT, VK_LWIN, VK_MEDIA_NEXT_TRACK, VK_MEDIA_PLAY_PAUSE, VK_MEDIA_PREV_TRACK, VK_MENU,
+ VK_NEXT, VK_PRIOR, VK_RETURN, VK_RIGHT, VK_SHIFT, VK_SPACE, VK_TAB, VK_UP, VK_V, VK_VOLUME_DOWN,
+ VK_VOLUME_MUTE, VK_VOLUME_UP, VK_X, VK_Y, VK_Z,
+ },
+ WindowsAndMessaging::WHEEL_DELTA,
+};
+
+/// Fractional remainders for sub-pixel pointer motion and sub-notch scrolling,
+/// plus which mouse buttons are currently held down by remote input.
+#[derive(Default)]
+struct InputState {
+ move_rem_x: f32,
+ move_rem_y: f32,
+ scroll_rem_x: f32,
+ scroll_rem_y: f32,
+ held_left: bool,
+ held_right: bool,
+ held_middle: bool,
+}
+
+static STATE: Mutex<InputState> = Mutex::new(InputState {
+ move_rem_x: 0.0,
+ move_rem_y: 0.0,
+ scroll_rem_x: 0.0,
+ scroll_rem_y: 0.0,
+ held_left: false,
+ held_right: false,
+ held_middle: false,
+});
+
+fn send_inputs(inputs: &[INPUT]) {
+ if inputs.is_empty() {
+ return;
+ }
+ // SAFETY: `inputs` is a valid slice of `INPUT` structs.
+ unsafe {
+ let _ = SendInput(inputs, std::mem::size_of::<INPUT>() as i32);
+ }
+}
+
+fn mouse_input(dx: i32, dy: i32, mouse_data: i32, flags: MOUSE_EVENT_FLAGS) -> INPUT {
+ INPUT {
+ r#type: INPUT_MOUSE,
+ Anonymous: INPUT_0 {
+ mi: MOUSEINPUT { dx, dy, mouseData: mouse_data as u32, dwFlags: flags, time: 0, dwExtraInfo: 0 },
+ },
+ }
+}
+
+fn vk_input(vk: VIRTUAL_KEY, extended: bool, up: bool) -> INPUT {
+ let mut flags = KEYBD_EVENT_FLAGS(0);
+ if extended {
+ flags |= KEYEVENTF_EXTENDEDKEY;
+ }
+ if up {
+ flags |= KEYEVENTF_KEYUP;
+ }
+ INPUT {
+ r#type: INPUT_KEYBOARD,
+ Anonymous: INPUT_0 { ki: KEYBDINPUT { wVk: vk, wScan: 0, dwFlags: flags, time: 0, dwExtraInfo: 0 } },
+ }
+}
+
+fn unicode_input(unit: u16, up: bool) -> INPUT {
+ let mut flags = KEYEVENTF_UNICODE;
+ if up {
+ flags |= KEYEVENTF_KEYUP;
+ }
+ INPUT {
+ r#type: INPUT_KEYBOARD,
+ Anonymous: INPUT_0 {
+ ki: KEYBDINPUT { wVk: VIRTUAL_KEY(0), wScan: unit, dwFlags: flags, time: 0, dwExtraInfo: 0 },
+ },
+ }
+}
+
+/// Moves the mouse cursor relatively by `(dx, dy)` pixels, keeping fractions
+/// for the next move. Windows applies the user's pointer speed (and "enhance
+/// pointer precision") to relative motion itself.
+pub fn move_relative(dx: f32, dy: f32) {
+ if !dx.is_finite() || !dy.is_finite() {
+ return;
+ }
+ let (ix, iy) = {
+ let mut s = STATE.lock().unwrap_or_else(|e| e.into_inner());
+ let total_x = s.move_rem_x + dx;
+ let total_y = s.move_rem_y + dy;
+ let ix = total_x.round() as i32;
+ let iy = total_y.round() as i32;
+ s.move_rem_x = total_x - (ix as f32);
+ s.move_rem_y = total_y - (iy as f32);
+ (ix, iy)
+ };
+ if ix != 0 || iy != 0 {
+ send_inputs(&[mouse_input(ix, iy, 0, MOUSEEVENTF_MOVE)]);
+ }
+}
+
+/// Presses, releases or clicks a mouse button.
+pub fn mouse_button(button: MouseButton, action: ButtonAction) {
+ let (down_flag, up_flag) = match button {
+ MouseButton::Left => (MOUSEEVENTF_LEFTDOWN, MOUSEEVENTF_LEFTUP),
+ MouseButton::Right => (MOUSEEVENTF_RIGHTDOWN, MOUSEEVENTF_RIGHTUP),
+ MouseButton::Middle => (MOUSEEVENTF_MIDDLEDOWN, MOUSEEVENTF_MIDDLEUP),
+ };
+ {
+ let mut s = STATE.lock().unwrap_or_else(|e| e.into_inner());
+ let slot = match button {
+ MouseButton::Left => &mut s.held_left,
+ MouseButton::Right => &mut s.held_right,
+ MouseButton::Middle => &mut s.held_middle,
+ };
+ *slot = matches!(action, ButtonAction::Down);
+ }
+ match action {
+ ButtonAction::Down => send_inputs(&[mouse_input(0, 0, 0, down_flag)]),
+ ButtonAction::Up => send_inputs(&[mouse_input(0, 0, 0, up_flag)]),
+ ButtonAction::Click => {
+ send_inputs(&[mouse_input(0, 0, 0, down_flag), mouse_input(0, 0, 0, up_flag)]);
+ }
+ }
+}
+
+/// Releases any mouse buttons still held down by remote input.
+pub fn release_held_buttons() {
+ let (left, right, middle) = {
+ let mut s = STATE.lock().unwrap_or_else(|e| e.into_inner());
+ let held = (s.held_left, s.held_right, s.held_middle);
+ s.held_left = false;
+ s.held_right = false;
+ s.held_middle = false;
+ s.move_rem_x = 0.0;
+ s.move_rem_y = 0.0;
+ s.scroll_rem_x = 0.0;
+ s.scroll_rem_y = 0.0;
+ held
+ };
+ let mut inputs = Vec::new();
+ if left {
+ inputs.push(mouse_input(0, 0, 0, MOUSEEVENTF_LEFTUP));
+ }
+ if right {
+ inputs.push(mouse_input(0, 0, 0, MOUSEEVENTF_RIGHTUP));
+ }
+ if middle {
+ inputs.push(mouse_input(0, 0, 0, MOUSEEVENTF_MIDDLEUP));
+ }
+ send_inputs(&inputs);
+}
+
+/// Scrolls the mouse wheel smoothly (`dy` > 0 scrolls down, `dx` > 0 scrolls right,
+/// in wheel notches of `WHEEL_DELTA = 120`).
+pub fn scroll(dx: f32, dy: f32) {
+ if !dx.is_finite() || !dy.is_finite() {
+ return;
+ }
+ let delta = WHEEL_DELTA as f32;
+ let (wx, wy) = {
+ let mut s = STATE.lock().unwrap_or_else(|e| e.into_inner());
+ // Protocol: positive dy = scroll down = negative Win32 wheel delta.
+ // Protocol: positive dx = scroll right = positive Win32 horizontal wheel delta.
+ let total_x = s.scroll_rem_x + dx * delta;
+ let total_y = s.scroll_rem_y - dy * delta;
+ let wx = total_x.round() as i32;
+ let wy = total_y.round() as i32;
+ s.scroll_rem_x = total_x - (wx as f32);
+ s.scroll_rem_y = total_y - (wy as f32);
+ (wx, wy)
+ };
+ let mut inputs = Vec::with_capacity(2);
+ if wy != 0 {
+ inputs.push(mouse_input(0, 0, wy, MOUSEEVENTF_WHEEL));
+ }
+ if wx != 0 {
+ inputs.push(mouse_input(0, 0, wx, MOUSEEVENTF_HWHEEL));
+ }
+ send_inputs(&inputs);
+}
+
+/// Types arbitrary Unicode text via `KEYEVENTF_UNICODE` (including surrogate
+/// pairs for non-BMP characters like emoji).
+pub fn type_text(text: &str) {
+ let mut inputs = Vec::with_capacity(text.len() * 2);
+ for ch in text.chars() {
+ if ch == '\r' {
+ continue;
+ }
+ if ch == '\n' {
+ inputs.push(vk_input(VK_RETURN, false, false));
+ inputs.push(vk_input(VK_RETURN, false, true));
+ continue;
+ }
+ let mut buf = [0u16; 2];
+ let units = ch.encode_utf16(&mut buf);
+ for &unit in units.iter() {
+ inputs.push(unicode_input(unit, false));
+ }
+ for &unit in units.iter().rev() {
+ inputs.push(unicode_input(unit, true));
+ }
+ }
+ send_inputs(&inputs);
+}
+
+/// Resolves a protocol key or shortcut name into `(VIRTUAL_KEY, is_extended, extra_mods)`.
+fn resolve_key(key: &str) -> Option<(VIRTUAL_KEY, bool, &'static [KeyMod])> {
+ const CTRL: &[KeyMod] = &[KeyMod::Ctrl];
+ const WIN: &[KeyMod] = &[KeyMod::Win];
+ const NONE: &[KeyMod] = &[];
+
+ Some(match key {
+ "copy" => (VK_C, false, CTRL),
+ "paste" => (VK_V, false, CTRL),
+ "cut" => (VK_X, false, CTRL),
+ "undo" => (VK_Z, false, CTRL),
+ "redo" => (VK_Y, false, CTRL),
+ "select_all" => (VK_A, false, CTRL),
+ "task_view" => (VK_TAB, false, WIN),
+ "enter" => (VK_RETURN, false, NONE),
+ "backspace" => (VK_BACK, false, NONE),
+ "tab" => (VK_TAB, false, NONE),
+ "escape" => (VK_ESCAPE, false, NONE),
+ "space" => (VK_SPACE, false, NONE),
+ "delete" => (VK_DELETE, true, NONE),
+ "insert" => (VK_INSERT, true, NONE),
+ "up" => (VK_UP, true, NONE),
+ "down" => (VK_DOWN, true, NONE),
+ "left" => (VK_LEFT, true, NONE),
+ "right" => (VK_RIGHT, true, NONE),
+ "home" => (VK_HOME, true, NONE),
+ "end" => (VK_END, true, NONE),
+ "page_up" => (VK_PRIOR, true, NONE),
+ "page_down" => (VK_NEXT, true, NONE),
+ "f1" => (VK_F1, false, NONE),
+ "f2" => (VIRTUAL_KEY(VK_F1.0 + 1), false, NONE),
+ "f3" => (VIRTUAL_KEY(VK_F1.0 + 2), false, NONE),
+ "f4" => (VIRTUAL_KEY(VK_F1.0 + 3), false, NONE),
+ "f5" => (VK_F5, false, NONE),
+ "f6" => (VIRTUAL_KEY(VK_F1.0 + 5), false, NONE),
+ "f7" => (VIRTUAL_KEY(VK_F1.0 + 6), false, NONE),
+ "f8" => (VIRTUAL_KEY(VK_F1.0 + 7), false, NONE),
+ "f9" => (VIRTUAL_KEY(VK_F1.0 + 8), false, NONE),
+ "f10" => (VIRTUAL_KEY(VK_F1.0 + 9), false, NONE),
+ "f11" => (VIRTUAL_KEY(VK_F1.0 + 10), false, NONE),
+ "f12" => (VIRTUAL_KEY(VK_F1.0 + 11), false, NONE),
+ "volume_up" => (VK_VOLUME_UP, true, NONE),
+ "volume_down" => (VK_VOLUME_DOWN, true, NONE),
+ "volume_mute" => (VK_VOLUME_MUTE, true, NONE),
+ "play_pause" => (VK_MEDIA_PLAY_PAUSE, true, NONE),
+ "next_track" => (VK_MEDIA_NEXT_TRACK, true, NONE),
+ "prev_track" => (VK_MEDIA_PREV_TRACK, true, NONE),
+ s if s.len() == 1 => {
+ let b = s.as_bytes()[0];
+ if b.is_ascii_lowercase() {
+ (VIRTUAL_KEY(u16::from(b - b'a' + b'A')), false, NONE)
+ } else if b.is_ascii_digit() {
+ (VIRTUAL_KEY(u16::from(b)), false, NONE)
+ } else {
+ return None;
+ }
+ }
+ _ => return None,
+ })
+}
+
+fn mod_vk(m: KeyMod) -> (VIRTUAL_KEY, bool) {
+ match m {
+ KeyMod::Ctrl => (VK_CONTROL, false),
+ KeyMod::Alt => (VK_MENU, false),
+ KeyMod::Shift => (VK_SHIFT, false),
+ KeyMod::Win => (VK_LWIN, true),
+ }
+}
+
+/// Presses a named key or shortcut with optional modifiers.
+pub fn press_key(key: &str, mods: &[KeyMod]) {
+ if key == "lock" {
+ let _ = crate::links::power(PowerAction::Lock);
+ return;
+ }
+ let Some((vk, extended, preset_mods)) = resolve_key(key) else {
+ return;
+ };
+ let mut all_mods: Vec<KeyMod> = Vec::with_capacity(4);
+ for &m in preset_mods.iter().chain(mods.iter()) {
+ if !all_mods.contains(&m) {
+ all_mods.push(m);
+ }
+ }
+ let mut inputs = Vec::with_capacity(all_mods.len() * 2 + 2);
+ for &m in &all_mods {
+ let (mvk, mext) = mod_vk(m);
+ inputs.push(vk_input(mvk, mext, false));
+ }
+ inputs.push(vk_input(vk, extended, false));
+ inputs.push(vk_input(vk, extended, true));
+ for &m in all_mods.iter().rev() {
+ let (mvk, mext) = mod_vk(m);
+ inputs.push(vk_input(mvk, mext, true));
+ }
+ send_inputs(&inputs);
+}
+
+/// Executes a presentation slide action.
+pub fn slide(action: SlideAction) {
+ let (vk, extended) = match action {
+ SlideAction::Next => (VK_NEXT, true),
+ SlideAction::Previous => (VK_PRIOR, true),
+ SlideAction::Start => (VK_F5, false),
+ SlideAction::Stop => (VK_ESCAPE, false),
+ SlideAction::Black => (VK_B, false),
+ };
+ send_inputs(&[vk_input(vk, extended, false), vk_input(vk, extended, true)]);
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn resolves_named_keys_and_shortcuts() {
+ assert_eq!(resolve_key("enter"), Some((VK_RETURN, false, &[][..])));
+ assert_eq!(resolve_key("up"), Some((VK_UP, true, &[][..])));
+ assert_eq!(resolve_key("copy"), Some((VK_C, false, &[KeyMod::Ctrl][..])));
+ assert_eq!(resolve_key("paste"), Some((VK_V, false, &[KeyMod::Ctrl][..])));
+ assert_eq!(resolve_key("task_view"), Some((VK_TAB, false, &[KeyMod::Win][..])));
+ assert_eq!(resolve_key("a"), Some((VK_A, false, &[][..])));
+ assert_eq!(resolve_key("f5"), Some((VK_F5, false, &[][..])));
+ assert!(resolve_key("unknown_key").is_none());
+ }
+}
diff --git a/desktop/app/src/win/mod.rs b/desktop/app/src/win/mod.rs
index f3d0e6e..dfe5b34 100644
--- a/desktop/app/src/win/mod.rs
+++ b/desktop/app/src/win/mod.rs
@@ -13,6 +13,7 @@ pub mod h264;
pub mod http;
pub mod icon;
pub mod image;
+pub mod input;
pub mod media_sessions;
pub mod net;
pub mod shell;
diff --git a/docs/PLAN.md b/docs/PLAN.md
index b26e1de..62296c0 100644
--- a/docs/PLAN.md
+++ b/docs/PLAN.md
@@ -199,7 +199,7 @@ current Android. Talking through the PC comes with the HFP item above.
### 3.10 Remote input & control
| Feature | Tier |
|---|---|
-| Phone as **touchpad + keyboard** for PC, presentation remote (with laser pointer) | P1 🟢 |
+| Phone as **touchpad + keyboard** for PC, presentation remote (with laser pointer) ✅ | P1 🟢 |
| **Air mouse**: point the phone and its gyroscope moves the PC cursor, for presentations and couch use | P1 🟢 |
| **Voice typing into PC**: hold a button on the phone, speak, and the text (from the phone's own speech engine) is typed into the PC's focused field | P1 🟢 |
| Type on the phone with the PC keyboard (without mirroring) | P1 🟣 |
diff --git a/docs/architecture/capabilities.md b/docs/architecture/capabilities.md
index a481b2e..44f42ed 100644
--- a/docs/architecture/capabilities.md
+++ b/docs/architecture/capabilities.md
@@ -120,8 +120,9 @@ the OS (`android` → phone, `windows`/`macos` → desktop).
## Per-device toggles
-`notifications`, `messages`, `calls`, `clipboard`, `photos`, `pc_actions`
-(on by default) and `remote_files` (off by default). Toggles are this
+`notifications`, `messages`, `calls`, `contacts`, `clipboard`, `files`,
+`media`, `photos`, `pc_actions`, `mirroring` (on by default) and
+`remote_input`, `remote_files` (off by default). Toggles are this
device's policy for that peer and are stored locally, so a feature the PC
user switched off is Locked on the PC while the phone may still show it as
Available. Everything else in the matrix is identical on both devices.
diff --git a/docs/protocol/capabilities.md b/docs/protocol/capabilities.md
index e60be15..1c9e108 100644
--- a/docs/protocol/capabilities.md
+++ b/docs/protocol/capabilities.md
@@ -65,6 +65,6 @@ capability is missing.
| `mirror.view` | Shows a phone's screen ([mirroring](mirror.md)) | app update |
| `mirror.listen` | Plays a mirrored phone's sound ([mirroring](mirror.md)) | app update |
| `files.browse` | Lets a paired phone browse and fetch its files | app update |
-| `input.inject` | Accepts pointer and keyboard input (touchpad, air mouse, voice typing) | app update |
+| `input.inject` | Accepts pointer, keyboard and presentation input ([remote input](remote.md)) | app update |
| `deck.actions` | Runs Deck actions | app update |
| `addon.vcam` | The virtual camera add-on is installed | installing the add-on |
diff --git a/docs/protocol/remote.md b/docs/protocol/remote.md
new file mode 100644
index 0000000..b733b04
--- /dev/null
+++ b/docs/protocol/remote.md
@@ -0,0 +1,130 @@
+# Remote input service (protocol v0)
+
+> Status: **draft.** Builds on [protocol v0](v0.md); breaking changes are
+> allowed until v1. License: CC BY 4.0.
+
+A phone acts as a touchpad, keyboard, and presentation remote for a paired PC.
+
+## 1. Capability and permission
+
+| ID | Offered by | Meaning |
+|---|---|---|
+| `input.inject` | desktop | Accepts pointer, keyboard, and presentation input from a paired phone |
+
+Input is governed by the `remote_input` per-device toggle on the PC, which is
+**off by default**. While `remote_input` is off for a phone:
+
+- The PC refuses every input from that phone (`DENIED` on control requests;
+ datagrams are dropped without injecting anything).
+- The first time a phone asks while the toggle is off, the PC prompts the user
+ once to allow or decline remote input for that phone. The user can also
+ change the toggle at any time in the phone's device settings on the PC.
+
+## 2. Transport
+
+### 2.1 QUIC datagrams (channel tag `0x01`)
+
+Continuous, loss-tolerant motion travels in QUIC datagrams (`RFC 9221`,
+[protocol v0 §4](v0.md)) prefixed with the one-byte channel tag `0x01`,
+followed by at most 256 bytes of CBOR-encoded `Input`:
+
+```
++--------+-----------------------+
+| 0x01 | CBOR Input (≤ 256 B) |
++--------+-----------------------+
+```
+
+If QUIC datagrams are unavailable on a connection, the sender opens a
+unidirectional stream with header `{ svc: "remote", op: "motion", v: 1 }` and
+sends length-prefixed CBOR `Input` frames there. Pointer motion (`type =
+"move"`) **MUST NOT** be sent on the control stream.
+
+Datagram-eligible `Input` variants:
+
+```
+{ type: "move", dx: float32, dy: float32 }
+{ type: "scroll", dx: float32, dy: float32 }
+{ type: "laser", on: bool, x?: float32, y?: float32 }
+```
+
+### 2.2 Control stream requests
+
+Discrete actions that must arrive — and permission checks when opening the
+remote screen — use control-stream requests:
+
+```
+t = "remote.check" id = n b = {}
+t = "ok" re = n
+
+t = "remote.input" id = n b = Input
+t = "ok" re = n
+```
+
+**`remote.check`** verifies whether the PC currently accepts remote input from
+the sender. If `remote_input` is off, the PC replies with `DENIED` and shows
+its one-time prompt if it hasn't already asked for this phone.
+
+**`remote.input`** executes a discrete input action (`button`, `scroll`,
+`text`, `key`, `slide`, or `laser`). Sending `type = "move"` in `remote.input`
+is rejected with `BAD_MESSAGE`. Errors: `UNSUPPORTED` when the receiver does
+not offer `input.inject`, `DENIED` when `remote_input` is off for the sender
+or rate-limited, `BAD_MESSAGE` when values are out of bounds or name an
+unknown key.
+
+## 3. Input payloads
+
+```
+Input =
+ | { type: "move", dx: float32, dy: float32 }
+ | { type: "button", button: Button, action: ButtonAction }
+ | { type: "scroll", dx: float32, dy: float32 }
+ | { type: "text", text: text }
+ | { type: "key", key: text, mods?: [KeyMod] }
+ | { type: "slide", action: SlideAction }
+ | { type: "laser", on: bool, x?: float32, y?: float32 }
+
+Button = "left" | "right" | "middle"
+ButtonAction = "down" | "up" | "click"
+KeyMod = "ctrl" | "alt" | "shift" | "win"
+SlideAction = "next" | "previous" | "start" | "stop" | "black"
+```
+
+- **Pointer motion (`move`):** relative displacement in logical pixels (`dx`
+ right, `dy` down), each finite and within `[-4000, 4000]`. Dragging holds a
+ button with `button` `down`, sends `move` datagrams, and finishes with
+ `button` `up`.
+- **Buttons (`button`):** `left`, `right`, or `middle` mouse button `down`,
+ `up`, or `click` (press and release). If a session ends or `remote_input` is
+ turned off while a button is held down, the PC releases the held button.
+- **Scroll (`scroll`):** horizontal (`dx`, positive right) and vertical (`dy`,
+ positive down/towards the user or wheel delta; on Windows `dy > 0` scrolls
+ up / standard wheel ticks, `dx > 0` scrolls right) in wheel notches
+ (fractions allowed for smooth scrolling), each finite and within
+ `[-200, 200]`.
+- **Text (`text`):** 1–256 UTF-8 bytes of printable Unicode text (no control
+ characters). Injected as Unicode characters (`KEYEVENTF_UNICODE` on Windows)
+ so non-Latin scripts and emojis work regardless of keyboard layout.
+- **Keys (`key`):**
+ - Named keys: `enter`, `backspace`, `tab`, `escape`, `space`, `left`,
+ `right`, `up`, `down`, `home`, `end`, `page_up`, `page_down`, `delete`,
+ `f1`–`f12`, `win`.
+ - Modified keys: a single ASCII lowercase letter (`a`–`z`) or digit
+ (`0`–`9`) when `mods` is non-empty (up to 4 modifiers from `ctrl`, `alt`,
+ `shift`, `win`).
+ - Named shortcuts (with empty `mods`): `copy` (`Ctrl+C`), `paste`
+ (`Ctrl+V`), `cut` (`Ctrl+X`), `undo` (`Ctrl+Z`), `select_all` (`Ctrl+A`),
+ `task_view` (`Win+Tab`), `lock` (`Win+L`).
+- **Presentation (`slide`):** `next` (next slide), `previous` (previous
+ slide), `start` (`F5`), `stop` (`Escape`), `black` (`B`).
+- **Laser pointer (`laser`):** when `on` is `true`, `x` and `y` are finite
+ fractions of the PC's primary screen (`0.0..=1.0`, left-to-right and
+ top-to-bottom). The PC draws a bright dot in a frameless, always-on-top,
+ click-through overlay window and fades it out when `on` is `false` or updates
+ stop arriving.
+
+## 4. Validation and rate limiting
+
+- The PC validates all bounds and key names before touching the OS input APIs.
+- Per-peer token buckets bound incoming rates (240 datagrams/s with burst 60;
+ 60 control requests/s with burst 30).
+- Implementations **MUST NOT** log typed `text` (v0 §11).
diff --git a/docs/protocol/v0.md b/docs/protocol/v0.md
index a1b03d7..84f092f 100644
--- a/docs/protocol/v0.md
+++ b/docs/protocol/v0.md
@@ -8,8 +8,8 @@ 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),
-[clipboard](clipboard.md), [files](files.md), [media](media.md) and
-[actions](actions.md) so far;
+[clipboard](clipboard.md), [files](files.md), [media](media.md),
+[actions](actions.md) and [remote](remote.md) so far;
mirroring follows.
Key words **MUST**, **SHOULD** and **MAY** are used as in RFC 2119.