Your Android phone and your Windows PC, working as one. Local-first, end-to-end encrypted, no account.
Accessibility, mirroring extras, handoff, typing on the phone, a shelf
Beeebe0012b8d16
diff --git a/README.md b/README.mdindex a4cd7f3..a5fc95d 100644--- a/README.md+++ b/README.md@@ -77,8 +77,12 @@ tests; there are no releases yet.- **Lock, sleep or wake the PC** from the phone (when the PC is offline, Wakesends Wake-on-LAN magic packets to its stored network addresses, and the PC'sSettings shows whether its adapter has Wake on Magic Packet turned on), and- **links** both ways: share a link from any phone app to open it on the PC, or- send a copied link from the PC's tray to the phone.+ **Rich Handoff** both ways: share or send a web link, a map location or+ street address (`geo:` URI or Maps link), a YouTube/Vimeo/Twitch video link+ with its current playback timestamp (`--at-seconds` or active media session+ position), or a document (`Shift+Drop`, Command Palette, `nectarlink send --open`,+ or Android share sheet) that opens automatically in the default app when it+ arrives.- **Notifications** from the phone on the PC, as Windows notifications and ina feed in the app, with the app's icon. Reply inline, run their actions(such as "Mark as read") or dismiss them from the PC; what's cleared on one@@ -114,16 +118,28 @@ tests; there are no releases yet.- **Screen mirroring**: see the phone's screen on the PC, in a window ofits own, at up to 1920 pixels and 60 frames a second, hardware encoded onthe phone, with the phone's sound playing on the PC (Android 10 and- later; mute it from the window); Android asks each time. Turn on- **Control from your PC** in+ later; mute it from the window); Android asks each time. From the mirror+ window's toolbar or keyboard shortcuts, copy a screenshot to the clipboard+ (`Ctrl+Shift+C`), save a screenshot to `Downloads\Nectarlink` (`Ctrl+S`),+ record the mirror to an MP4 (`Ctrl+R`, H.264 passthrough with the phone's+ audio and no video re-encode), keep the phone awake while mirroring, or+ (with Wireless debugging) turn the phone's physical screen off while the+ mirror keeps running (and automatically turn it back on when mirroring+ ends). Turn on **Control from your PC** inthe phone's Nectarlink settings to tap, swipe, scroll and type with thePC's mouse and keyboard (right-click is Back), or set up **Wirelessdebugging** there once for real touch (live dragging) and keys, withnothing else to install; Nectarlink turns Wireless debugging back on by- itself after a reboot.+ itself after a reboot. You can also **type on the phone with the PC+ keyboard without mirroring** from the **Type on phone** card on Home or+ the Command Palette (live keystrokes, arrows, Backspace, Enter, `Ctrl+V`+ paste, and Unicode text), with a **Typing from <PC>** banner on the phone+ to stop it anytime.- **Phone apps in windows** on the PC: with Wireless debugging set up(Android 11 and later), pick any of the phone's apps (with a Recent row- for the ones opened most recently) and it opens in a window of its own with+ combining apps opened from the PC and apps with recent notifications), or+ click a phone notification in the feed, Notification history or its Windows+ notification popup, and the app opens in a window of its own withits own taskbar icon, running on the phone beside whatever its screen showsand without popping the phone's keyboard up on its screen; resize thewindow and the app re-lays out to fit, its size and position are remembered@@ -236,10 +252,14 @@ tests; there are no releases yet.which takes its colors from the desktop wallpaper, **My phone's colors**synced live from the phone's Material You wallpaper seed, or a preset seed,and Graphite), Mica, a- custom title bar with Snap Layouts, and a tray icon. In the background it+ custom title bar with Snap Layouts, a tray icon, global **Command Palette**+ (`Ctrl+Alt+Space`), and a slide-out **Shelf** edge panel (`Ctrl+Alt+S`, never+ steals focus, unloads completely when hidden) showing the latest photo,+ latest screenshot, current clip and recent received files — drag anything in+ to send to the phone or drag out to use in any app. In the background itunloads its window and caches (~27 MB private commit when started in the trayor ~60 MB after closing the window, with a ~5–10 MB active working set).-- **Android app**: pairing, home (with Timeline and Clipboard history) and settings, Material You colors (synced live to paired PCs), a background+- **Android app**: pairing, home (with Timeline and Clipboard history) and settings, Material You colors (synced live to paired PCs), a **home-screen widget** (PC connection status, Wake, and battery-free quick actions: Send clip, Ring PC, Lock PC), **Direct Share** targets for each paired PC in the Android share sheet, a Quick Settings tile, a backgroundconnection service, and an identity key protected by the Android Keystore.- **Connection Doctor** on the PC: finds what keeps the phone fromconnecting (firewall, a public network, a VPN) and fixes what it can.diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xmlindex f8cda8e..28d11d9 100644--- a/android/app/src/main/AndroidManifest.xml+++ b/android/app/src/main/AndroidManifest.xml@@ -16,6 +16,8 @@<uses-permission android:name="android.permission.FOREGROUND_SERVICE_CONNECTED_DEVICE" /><!-- Sharing the screen with a PC (each time, after Android's prompt). --><uses-permission android:name="android.permission.FOREGROUND_SERVICE_MEDIA_PROJECTION" />+ <!-- Keeping the phone awake while mirroring its screen to a PC. -->+ <uses-permission android:name="android.permission.WAKE_LOCK" /><!-- Voice recorder to PC while the screen is off or the app is in the background. --><uses-permission android:name="android.permission.FOREGROUND_SERVICE_MICROPHONE" /><!-- Streaming the camera to a PC as a webcam while the app is in the background. -->@@ -153,6 +155,16 @@<category android:name="android.intent.category.DEFAULT" /><data android:mimeType="*/*" /></intent-filter>+ <!-- Map locations (geo: URIs) opened with Nectarlink go straight to the PC. -->+ <intent-filter>+ <action android:name="android.intent.action.VIEW" />+ <category android:name="android.intent.category.DEFAULT" />+ <category android:name="android.intent.category.BROWSABLE" />+ <data android:scheme="geo" />+ </intent-filter>+ <meta-data+ android:name="android.app.shortcuts"+ android:resource="@xml/shortcuts" /></activity><receiver@@ -273,5 +285,21 @@android:name=".service.ConnectionService"android:exported="false"android:foregroundServiceType="connectedDevice" />++ <!-- Home-screen widget: paired PC connection status, Wake, and battery-free quick actions. -->+ <receiver+ android:name=".widget.PcWidgetProvider"+ android:exported="true"+ android:label="@string/widget_pc_title">+ <intent-filter>+ <action android:name="android.appwidget.action.APPWIDGET_UPDATE" />+ <action android:name="app.nectarlink.widget.ACTION_RING_PC" />+ <action android:name="app.nectarlink.widget.ACTION_LOCK_PC" />+ <action android:name="app.nectarlink.widget.ACTION_WAKE_PC" />+ </intent-filter>+ <meta-data+ android:name="android.appwidget.provider"+ android:resource="@xml/pc_widget_info" />+ </receiver></application></manifest>diff --git a/android/app/src/main/kotlin/app/nectarlink/android/camera/ContinuityCameraActivity.kt b/android/app/src/main/kotlin/app/nectarlink/android/camera/ContinuityCameraActivity.ktindex 1e0fb49..d6f59d8 100644--- a/android/app/src/main/kotlin/app/nectarlink/android/camera/ContinuityCameraActivity.kt+++ b/android/app/src/main/kotlin/app/nectarlink/android/camera/ContinuityCameraActivity.kt@@ -72,6 +72,10 @@ import androidx.compose.ui.layout.ContentScaleimport androidx.compose.ui.layout.onSizeChangedimport androidx.compose.ui.platform.LocalContextimport androidx.compose.ui.res.stringResource+import androidx.compose.ui.semantics.Role+import androidx.compose.ui.semantics.contentDescription+import androidx.compose.ui.semantics.role+import androidx.compose.ui.semantics.semanticsimport androidx.compose.ui.text.font.FontWeightimport androidx.compose.ui.unit.IntSizeimport androidx.compose.ui.unit.dp@@ -83,6 +87,7 @@ import androidx.lifecycle.compose.collectAsStateWithLifecycleimport app.nectarlink.android.NectarlinkApplicationimport app.nectarlink.android.Rimport app.nectarlink.android.ui.Preferences+import app.nectarlink.android.ui.theme.LocalReducedMotionimport app.nectarlink.android.ui.theme.NectarlinkThemeimport java.io.ByteArrayOutputStreamimport java.util.concurrent.Executors@@ -111,7 +116,7 @@ class ContinuityCameraActivity : ComponentActivity() {) { granted ->cameraPermissionGranted.value = grantedif (!granted) {- cancelAndFinish("Camera permission denied on phone")+ cancelAndFinish(getString(R.string.continuity_camera_permission_denied))}}@@ -190,7 +195,7 @@ class ContinuityCameraActivity : ComponentActivity() {)Spacer(Modifier.height(12.dp))Row(horizontalArrangement = Arrangement.spacedBy(12.dp)) {- OutlinedButton(onClick = { cancelAndFinish("Cancelled on phone") }) {+ OutlinedButton(onClick = { cancelAndFinish(getString(R.string.continuity_camera_cancelled)) }) {Text(stringResource(R.string.action_cancel))}Button(onClick = { permissionLauncher.launch(Manifest.permission.CAMERA) }) {@@ -221,7 +226,7 @@ class ContinuityCameraActivity : ComponentActivity() {(application as? NectarlinkApplication)?.core?.cancelCameraCapture(pcId = pcId,requestId = requestId,- reason = "Cancelled on phone",+ reason = getString(R.string.continuity_camera_cancelled),)}super.onDestroy()@@ -286,6 +291,7 @@ private fun ContinuityCameraScreen(val cameraExecutor = remember { Executors.newSingleThreadExecutor() }var imageCapture by remember { mutableStateOf<ImageCapture?>(null) }var boundCamera by remember { mutableStateOf<Camera?>(null) }+ val cancelledText = stringResource(R.string.continuity_camera_cancelled)BackHandler {if (capturedBitmap != null && !busy) {@@ -293,7 +299,7 @@ private fun ContinuityCameraScreen(rectifiedBitmap = nullshowRectifiedPreview = false} else if (!busy) {- onCancel("Cancelled on phone")+ onCancel(cancelledText)}}@@ -393,12 +399,14 @@ private fun ContinuityCameraScreen() {Column(modifier = Modifier.weight(1f)) {Text(- text = if (mode == "scan") "Scan document" else "Take photo",+ text = stringResource(+ if (mode == "scan") R.string.continuity_camera_scan_title else R.string.continuity_camera_photo_title,+ ),style = MaterialTheme.typography.titleMedium,fontWeight = FontWeight.SemiBold,)Text(- text = "For $pcName",+ text = stringResource(R.string.continuity_camera_for_pc, pcName),style = MaterialTheme.typography.bodySmall,color = MaterialTheme.colorScheme.onSurfaceVariant,)@@ -409,7 +417,7 @@ private fun ContinuityCameraScreen(FilterChip(selected = mode == "photo",onClick = { mode = "photo" },- label = { Text("Photo") },+ label = { Text(stringResource(R.string.continuity_camera_mode_photo)) },)FilterChip(selected = mode == "scan",@@ -417,14 +425,14 @@ private fun ContinuityCameraScreen(mode = "scan"useFrontCamera = false},- label = { Text("Scan") },+ label = { Text(stringResource(R.string.continuity_camera_mode_scan)) },)}}Spacer(Modifier.width(8.dp))TextButton(- onClick = { onCancel("Cancelled on phone") },+ onClick = { onCancel(cancelledText) },enabled = !busy,) {Text(stringResource(R.string.action_cancel))@@ -480,7 +488,7 @@ private fun ContinuityCameraScreen() {Image(bitmap = displayBitmap.asImageBitmap(),- contentDescription = null,+ contentDescription = stringResource(R.string.continuity_camera_preview_desc),contentScale = ContentScale.Fit,modifier = Modifier.fillMaxSize(),)@@ -503,7 +511,11 @@ private fun ContinuityCameraScreen(.background(Color.Black.copy(alpha = 0.45f)),contentAlignment = Alignment.Center,) {- CircularProgressIndicator()+ if (LocalReducedMotion.current) {+ CircularProgressIndicator(progress = { 0.75f })+ } else {+ CircularProgressIndicator()+ }}}}@@ -534,6 +546,9 @@ private fun ContinuityCameraScreen(}// Shutter button+ val shutterDesc = stringResource(+ if (mode == "scan") R.string.continuity_camera_shutter_scan else R.string.continuity_camera_shutter_photo,+ )Box(modifier = Modifier.size(72.dp)@@ -542,6 +557,10 @@ private fun ContinuityCameraScreen(.padding(6.dp).clip(CircleShape).background(MaterialTheme.colorScheme.primary)+ .semantics {+ role = Role.Button+ contentDescription = shutterDesc+ }.clickable(enabled = !busy) {val cap = imageCaptureif (cap == null) {@@ -629,12 +648,19 @@ private fun ContinuityCameraScreen(FilterChip(selected = enhanceScan,onClick = { enhanceScan = !enhanceScan },- label = { Text("Enhance document") },+ label = { Text(stringResource(R.string.continuity_camera_enhance)) },)FilterChip(selected = showRectifiedPreview,onClick = { showRectifiedPreview = !showRectifiedPreview },- label = { Text(if (showRectifiedPreview) "Adjust corners" else "Preview scan") },+ label = {+ Text(+ stringResource(+ if (showRectifiedPreview) R.string.continuity_camera_adjust_corners+ else R.string.continuity_camera_preview_scan,+ ),+ )+ },)}}@@ -652,7 +678,7 @@ private fun ContinuityCameraScreen(enabled = !busy,modifier = Modifier.weight(1f),) {- Text("Retake")+ Text(stringResource(R.string.continuity_camera_retake))}Button(onClick = {@@ -677,7 +703,12 @@ private fun ContinuityCameraScreen(enabled = !busy,modifier = Modifier.weight(1f),) {- Text(if (mode == "scan") "Send scan" else "Use photo")+ Text(+ stringResource(+ if (mode == "scan") R.string.continuity_camera_send_scan+ else R.string.continuity_camera_use_photo,+ ),+ )}}}@@ -712,6 +743,7 @@ private fun QuadCornerEditorOverlay() {val primaryColor = MaterialTheme.colorScheme.primaryval surfaceColor = MaterialTheme.colorScheme.surface+ val cornersDesc = stringResource(R.string.continuity_camera_corners_desc)val containerW = containerSize.width.toFloat()val containerH = containerSize.height.toFloat()@@ -742,6 +774,7 @@ private fun QuadCornerEditorOverlay(Canvas(modifier = Modifier.fillMaxSize()+ .semantics { contentDescription = cornersDesc }.pointerInput(drawW, drawH, offsetX, offsetY) {detectDragGestures(onDragStart = { startOffset ->diff --git a/android/app/src/main/kotlin/app/nectarlink/android/camera/ContinuityCameraRequest.kt b/android/app/src/main/kotlin/app/nectarlink/android/camera/ContinuityCameraRequest.ktindex 5b264fa..c0bd60b 100644--- a/android/app/src/main/kotlin/app/nectarlink/android/camera/ContinuityCameraRequest.kt+++ b/android/app/src/main/kotlin/app/nectarlink/android/camera/ContinuityCameraRequest.kt@@ -49,7 +49,7 @@ object ContinuityCameraRequests {context.getSystemService(NotificationManager::class.java)?.createNotificationChannel(NotificationChannel(CHANNEL,- "Camera capture requests",+ context.getString(R.string.channel_camera_requests),NotificationManager.IMPORTANCE_HIGH,),)@@ -101,14 +101,14 @@ object ContinuityCameraRequests {PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT,)val title = if (cleanMode == "scan") {- "$fromName wants to scan a document"+ context.getString(R.string.continuity_camera_request_scan_title, fromName)} else {- "$fromName wants to take a photo"+ context.getString(R.string.continuity_camera_request_photo_title, fromName)}val text = if (cleanMode == "scan") {- "Tap to scan a document with your camera."+ context.getString(R.string.continuity_camera_request_scan_text)} else {- "Tap to take a photo with your camera."+ context.getString(R.string.continuity_camera_request_photo_text)}val notification = NotificationCompat.Builder(context, CHANNEL).setSmallIcon(R.drawable.ic_notification)diff --git a/android/app/src/main/kotlin/app/nectarlink/android/clipboard/DirectShareTargets.kt b/android/app/src/main/kotlin/app/nectarlink/android/clipboard/DirectShareTargets.ktnew file mode 100644index 0000000..ee5cf03--- /dev/null+++ b/android/app/src/main/kotlin/app/nectarlink/android/clipboard/DirectShareTargets.kt@@ -0,0 +1,78 @@+// SPDX-License-Identifier: GPL-3.0-or-later+package app.nectarlink.android.clipboard++import android.app.Person+import android.content.Context+import android.content.Intent+import android.content.pm.ShortcutInfo+import android.content.pm.ShortcutManager+import android.graphics.drawable.Icon+import android.os.Build+import app.nectarlink.android.R+import app.nectarlink.android.core.Device++/**+ * Publishes Direct Share targets (Android 10+ dynamic sharing shortcuts) for each+ * paired PC so paired PCs appear directly in Android's system share sheet.+ */+object DirectShareTargets {+ const val CATEGORY_DIRECT_SHARE = "app.nectarlink.android.category.DIRECT_SHARE"+ private const val SHORTCUT_PREFIX = "pc:"++ private data class Snapshot(+ val id: String,+ val name: String,+ val online: Boolean,+ )++ @Volatile+ private var lastSynced: List<Snapshot>? = null++ fun pcIdFromShortcutId(shortcutId: String?): String? =+ shortcutId?.takeIf { it.startsWith(SHORTCUT_PREFIX) }?.removePrefix(SHORTCUT_PREFIX)?.takeIf { it.isNotBlank() }++ fun sync(context: Context, devices: List<Device>) {+ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) return+ val snapshot = devices.map { Snapshot(id = it.id, name = it.name, online = it.online) }+ if (snapshot == lastSynced) return+ val previousIds = lastSynced?.map { "$SHORTCUT_PREFIX${it.id}" }?.toSet().orEmpty()+ lastSynced = snapshot++ val shortcutManager = context.getSystemService(ShortcutManager::class.java) ?: return+ val maxShortcuts = shortcutManager.maxShortcutCountPerActivity.coerceIn(1, 8)+ val sorted = devices.sortedByDescending { it.online }.take(maxShortcuts)+ val fallbackName = context.getString(R.string.your_pc)++ val shortcuts = sorted.mapIndexed { index, device ->+ val label = device.name.ifBlank { fallbackName }+ val person = Person.Builder()+ .setName(label)+ .setKey(device.id)+ .build()+ val intent = Intent(context, SendActivity::class.java)+ .setAction(Intent.ACTION_SEND)+ .putExtra(SendActivity.EXTRA_PC_ID, device.id)+ ShortcutInfo.Builder(context, "$SHORTCUT_PREFIX${device.id}")+ .setShortLabel(label)+ .setLongLabel(label)+ .setIcon(Icon.createWithResource(context, R.mipmap.ic_launcher))+ .setCategories(setOf(CATEGORY_DIRECT_SHARE))+ .setLongLived(true)+ .setRank(index)+ .setPerson(person)+ .setIntent(intent)+ .build()+ }++ runCatching {+ shortcutManager.dynamicShortcuts = shortcuts+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {+ val activeIds = shortcuts.map { it.id }.toSet()+ val removed = (previousIds - activeIds).toList()+ if (removed.isNotEmpty()) {+ shortcutManager.removeLongLivedShortcuts(removed)+ }+ }+ }+ }+}diff --git a/android/app/src/main/kotlin/app/nectarlink/android/clipboard/SendActivity.kt b/android/app/src/main/kotlin/app/nectarlink/android/clipboard/SendActivity.ktindex 3252195..61740db 100644--- a/android/app/src/main/kotlin/app/nectarlink/android/clipboard/SendActivity.kt+++ b/android/app/src/main/kotlin/app/nectarlink/android/clipboard/SendActivity.kt@@ -31,12 +31,22 @@ class SendActivity : Activity() {super.onCreate(savedInstanceState)val intent = intent ?: return finish()when (intent.action) {+ Intent.ACTION_VIEW -> {+ val uri = intent.data+ if (uri != null && uri.scheme?.lowercase() == "geo") {+ val geo = uri.toString()+ sendLink(geo, geo)+ } else {+ finishWith(getString(R.string.clip_nothing_shared))+ }+ }Intent.ACTION_SEND -> {val stream = IntentCompat.getParcelableExtra(intent, Intent.EXTRA_STREAM, Uri::class.java)val text = intent.getCharSequenceExtra(Intent.EXTRA_TEXT)?.toString()+ val link = text?.let(::handoffUrl)when {- stream != null -> sendFiles(listOf(stream))- !text.isNullOrBlank() && webLink(text) != null -> sendLink(webLink(text)!!, text)+ stream != null -> sendFiles(listOf(stream), handoff = true)+ !text.isNullOrBlank() && link != null -> sendLink(link, text)!text.isNullOrBlank() -> send(text)else -> finishWith(getString(R.string.clip_nothing_shared))}@@ -49,21 +59,40 @@ class SendActivity : Activity() {// The clipboard is read in onWindowFocusChanged.}+ private fun targetPcId(): String? {+ val explicit = intent?.getStringExtra(EXTRA_PC_ID)?.takeIf { it.isNotBlank() }+ if (explicit != null) return explicit+ if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.Q) {+ val shortcutId = intent?.getStringExtra(Intent.EXTRA_SHORTCUT_ID)+ DirectShareTargets.pcIdFromShortcutId(shortcutId)?.let { return it }+ }+ return null+ }+/** Files go to one PC: the connected one, or the one the user picks. */- private fun sendFiles(uris: List<Uri>) {+ private fun sendFiles(uris: List<Uri>, handoff: Boolean = false) {sent = trueval core = (application as NectarlinkApplication).core+ val chosenPcId = targetPcId()+ if (chosenPcId != null) {+ val pc = core.state.value.device(chosenPcId)+ if (pc != null && pc.online) {+ core.sendFiles(pc.id, uris, handoff)+ finishWith(getString(R.string.transfer_sending, pc.name))+ return+ }+ }val pcs = core.state.value.devices.filter { it.online }when (pcs.size) {0 -> finishWith(getString(R.string.clip_no_pc))1 -> {- core.sendFiles(pcs[0].id, uris)+ core.sendFiles(pcs[0].id, uris, handoff)finishWith(getString(R.string.transfer_sending, pcs[0].name))}else -> AlertDialog.Builder(this).setTitle(R.string.transfer_pick_pc).setItems(pcs.map { it.name }.toTypedArray()) { _, which ->- core.sendFiles(pcs[which].id, uris)+ core.sendFiles(pcs[which].id, uris, handoff)finishWith(getString(R.string.transfer_sending, pcs[which].name))}.setOnCancelListener { finish() }@@ -83,13 +112,25 @@ class SendActivity : Activity() {}/**- * A shared link opens on the PC (the one that takes links; the user- * picks when there are several). With no such PC, it goes to the- * clipboard like other text.+ * A shared link, video with timestamp, or map location opens on the PC+ * (the one that takes links; the user picks when there are several).+ * With no such PC, it goes to the clipboard like other text.*/private fun sendLink(url: String, text: String) {sent = trueval core = (application as NectarlinkApplication).core+ val chosenPcId = targetPcId()+ if (chosenPcId != null) {+ val pc = core.state.value.device(chosenPcId)+ if (pc != null && pc.online) {+ if (pc.has("device.links_to_pc")) {+ scope.launch { finishWith(core.openLinkOnPc(pc.id, url)) }+ } else {+ send(text)+ }+ return+ }+ }val pcs = core.state.value.devices.filter { it.online && it.has("device.links_to_pc") }when (pcs.size) {0 -> send(text)@@ -107,13 +148,15 @@ class SendActivity : Activity() {private fun send(text: String) {sent = trueval core = (application as NectarlinkApplication).core- scope.launch { finishWith(core.sendClipboard(text)) }+ val pcId = targetPcId()+ scope.launch { finishWith(core.sendClipboard(text, pcId)) }}private fun sendImage(uri: Uri) {sent = trueval core = (application as NectarlinkApplication).core- scope.launch { finishWith(core.sendClipboardImage(uri)) }+ val pcId = targetPcId()+ scope.launch { finishWith(core.sendClipboardImage(uri, pcId)) }}private fun finishWith(message: String) {@@ -138,11 +181,28 @@ class SendActivity : Activity() {return link.takeIf { web && words.size <= 12 }}+ /**+ * Extracts a Handoff URL (web link, YouTube/video URL with timestamp,+ * `geo:` map URI, or street address converted to `geo:`) from shared text.+ */+ fun handoffUrl(text: String): String? {+ app.nectarlink.core.extractHandoffLink(text)?.let { return it.url }+ val suggestion = app.nectarlink.core.classifyClip(text)+ if (suggestion?.kind == app.nectarlink.core.ClipKind.STREET_ADDRESS) {+ return "geo:0,0?q=${Uri.encode(text.trim())}"+ }+ return webLink(text)+ }+const val ACTION_SEND_CLIPBOARD = "app.nectarlink.action.SEND_CLIPBOARD"+ const val EXTRA_PC_ID = "app.nectarlink.extra.PC_ID"- fun sendClipboardIntent(context: Context): Intent =+ fun sendClipboardIntent(context: Context, pcId: String? = null): Intent =Intent(context, SendActivity::class.java).setAction(ACTION_SEND_CLIPBOARD).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_NO_ANIMATION)+ .apply {+ if (!pcId.isNullOrEmpty()) putExtra(EXTRA_PC_ID, pcId)+ }}}diff --git a/android/app/src/main/kotlin/app/nectarlink/android/core/Core.kt b/android/app/src/main/kotlin/app/nectarlink/android/core/Core.ktindex bf006cd..6037954 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@@ -116,6 +116,7 @@ class Core(context: Context, private val scope: CoroutineScope) : EventListener},appWindows = AppWindows(this.context, scope, open = { pc -> mirrorOpen(pc) }, nameOf = { pc -> _state.value.nameOf(pc).orEmpty() }),nameOf = { pc -> _state.value.nameOf(pc).orEmpty() },+ onKeyboardFromPc = { pc, on -> setKeyboardFromPc(pc, on) },)private val storage = PhoneStorage(this.context) { path ->notificationOps.trySend { it.storageChanged(path) }@@ -282,6 +283,14 @@ class Core(context: Context, private val scope: CoroutineScope) : EventListener)}refreshDataRetention()+ app.nectarlink.android.clipboard.DirectShareTargets.sync(context, _state.value.devices)+ app.nectarlink.android.widget.PcWidgetProvider.refreshAll(context, _state.value)+ scope.launch {+ _state.collect { s ->+ app.nectarlink.android.clipboard.DirectShareTargets.sync(context, s.devices)+ app.nectarlink.android.widget.PcWidgetProvider.refreshAll(context, s)+ }+ }if (devices.isNotEmpty()) ConnectionService.start(context)scope.launch(Dispatchers.Main) {battery.start()@@ -450,13 +459,13 @@ class Core(context: Context, private val scope: CoroutineScope) : EventListenerif (_state.value.devices.isEmpty()) ConnectionService.stop(context)}is Event.Paired -> ConnectionService.start(context)- is Event.ClipboardReceived -> onClipboardReceived(event.id)- is Event.ClipboardHistoryChanged -> {+ is Event.ClipboardReceived -> scope.launch(Dispatchers.IO) { onClipboardReceived(event.id) }+ is Event.ClipboardHistoryChanged -> scope.launch(Dispatchers.IO) {refreshClipboardHistory()refreshTimeline()}- is Event.TimelineChanged -> refreshTimeline()- is Event.LocalSendChanged -> syncLocalSendState()+ is Event.TimelineChanged -> scope.launch(Dispatchers.IO) { refreshTimeline() }+ is Event.LocalSendChanged -> scope.launch(Dispatchers.IO) { syncLocalSendState() }else -> {}}}@@ -683,7 +692,8 @@ class Core(context: Context, private val scope: CoroutineScope) : EventListener* The files are opened right away: Android's permission to read a* shared item ends with the activity that received it.*/- fun sendFiles(pcId: String, uris: List<Uri>) = send(pcId, OutgoingFiles.open(context, uris))+ fun sendFiles(pcId: String, uris: List<Uri>, handoff: Boolean = false) =+ send(pcId, OutgoingFiles.open(context, uris), handoff)/** Sends a folder the user picked, with everything in it. */fun sendFolder(pcId: String, tree: Uri) {@@ -701,7 +711,7 @@ class Core(context: Context, private val scope: CoroutineScope) : EventListener}}- private fun send(pcId: String, files: List<FileToSend>) {+ private fun send(pcId: String, files: List<FileToSend>, handoff: Boolean = false) {if (files.isEmpty()) {_messages.tryEmit(context.getString(R.string.transfer_nothing))return@@ -710,7 +720,19 @@ class Core(context: Context, private val scope: CoroutineScope) : EventListenerstartJob?.join()val node = node ?: return@launchtry {- node.sendFiles(pcId, files)+ val singleFileName = if (files.size == 1) {+ when (val f = files[0]) {+ is FileToSend.Fd -> f.name.takeIf { f.folder == null }+ is FileToSend.Path -> f.name.takeIf { f.folder == null }+ }+ } else {+ null+ }+ if (handoff && singleFileName != null && app.nectarlink.core.isSafeHandoffDocument(singleFileName)) {+ node.sendHandoffFiles(pcId, files)+ } else {+ node.sendFiles(pcId, files)+ }} catch (e: NectarlinkException) {val name = _state.value.nameOf(pcId).orEmpty()_messages.tryEmit(@@ -768,28 +790,41 @@ class Core(context: Context, private val scope: CoroutineScope) : EventListener// ---- Clipboard ----/**- * Sends text to every connected PC; returns what to tell the user.- * Waits for the core when the app was just launched to send.+ * Sends text to every connected PC (or to `pcId` when chosen via Direct Share);+ * returns what to tell the user. Waits for the core when the app was just launched.*/- suspend fun sendClipboard(text: String): String =- sendToPcs(image = false) { node, pc -> node.sendClipboard(pc, text) }+ suspend fun sendClipboard(text: String, pcId: String? = null): String =+ sendToPcs(image = false, pcId = pcId) { node, pc -> node.sendClipboard(pc, text) }- /** Sends a copied image to the connected PCs; returns what to tell the user. */- suspend fun sendClipboardImage(uri: Uri): String {+ /** Sends a copied image to the connected PCs (or to `pcId`); returns what to tell the user. */+ suspend fun sendClipboardImage(uri: Uri, pcId: String? = null): String {startJob?.join()- if (_state.value.devices.none { it.online }) return context.getString(R.string.clip_no_pc)+ val targets = if (pcId != null) {+ _state.value.devices.filter { it.id == pcId && it.online }+ } else {+ _state.value.devices.filter { it.online }+ }+ if (targets.isEmpty()) return context.getString(R.string.clip_no_pc)val image = when (val read = withContext(Dispatchers.IO) { PhoneClipboard.readImage(context, uri) }) {is PhoneClipboard.ImageResult.Ready -> read.imagePhoneClipboard.ImageResult.TooLarge -> return context.getString(R.string.clip_image_too_large)PhoneClipboard.ImageResult.Unreadable -> return context.getString(R.string.clip_image_unreadable)}- return sendToPcs(image = true) { node, pc -> node.sendClipboardImage(pc, image.mime, image.bytes) }+ return sendToPcs(image = true, pcId = pcId) { node, pc -> node.sendClipboardImage(pc, image.mime, image.bytes) }}- private suspend fun sendToPcs(image: Boolean, send: suspend (NectarlinkNode, String) -> Unit): String {+ private suspend fun sendToPcs(+ image: Boolean,+ pcId: String? = null,+ send: suspend (NectarlinkNode, String) -> Unit,+ ): String {startJob?.join()val node = node ?: return context.getString(R.string.clip_no_pc)- val pcs = _state.value.devices.filter { it.online }+ val pcs = if (pcId != null) {+ _state.value.devices.filter { it.id == pcId && it.online }+ } else {+ _state.value.devices.filter { it.online }+ }if (pcs.isEmpty()) return context.getString(R.string.clip_no_pc)val sentTo = mutableListOf<String>()var failure: String? = null@@ -1173,9 +1208,10 @@ class Core(context: Context, private val scope: CoroutineScope) : EventListener/** Locks a PC, or puts it to sleep; says how it went. */fun pcPower(id: String, sleep: Boolean) {- val node = node ?: return- val name = _state.value.nameOf(id).orEmpty()scope.launch {+ startJob?.join()+ val node = node ?: return@launch+ val name = _state.value.nameOf(id).orEmpty()val message = try {node.pcPower(id, sleep)context.getString(if (sleep) R.string.pc_sleeping else R.string.pc_locked, name)@@ -1191,10 +1227,11 @@ class Core(context: Context, private val scope: CoroutineScope) : EventListener* up to ~60 s for it to connect before showing troubleshooting tips.*/fun wake(id: String) {- val node = node ?: returnwakeTimers.remove(id)?.cancel()_state.update { it.withWakeState(id, WakeState.Waking) }val timer = scope.launch(Dispatchers.IO) {+ startJob?.join()+ val node = node ?: return@launchrepeat(15) {delay(4_000)val dev = _state.value.device(id)@@ -1212,6 +1249,8 @@ class Core(context: Context, private val scope: CoroutineScope) : EventListener}wakeTimers[id] = timerscope.launch(Dispatchers.IO) {+ startJob?.join()+ val node = node ?: return@launchtry {node.wake(id)node.refresh()@@ -1228,13 +1267,24 @@ class Core(context: Context, private val scope: CoroutineScope) : EventListener}}- /** Opens a link on a PC; returns what to tell the user. */+ /** Opens a link, video with timestamp, or map location on a PC; returns what to tell the user. */suspend fun openLinkOnPc(id: String, url: String): String {startJob?.join()val node = node ?: return context.getString(R.string.clip_no_pc)val name = _state.value.nameOf(id).orEmpty()+ val handoff = app.nectarlink.core.extractHandoffLink(url)+ val finalUrl = if (+ handoff != null &&+ handoff.kind == app.nectarlink.core.HandoffKind.VIDEO_LINK &&+ handoff.timestampSecs == null+ ) {+ val activeSecs = phoneMedia.activePositionSeconds()+ if (activeSecs != null) app.nectarlink.core.withVideoTimestamp(handoff.url, activeSecs) else handoff.url+ } else {+ handoff?.url ?: url+ }return try {- node.openLink(id, url)+ node.openLink(id, finalUrl)context.getString(R.string.link_opened_on, name)} catch (e: NectarlinkException) {describe(e)@@ -1408,10 +1458,27 @@ class Core(context: Context, private val scope: CoroutineScope) : EventListener_state.update { it.copy(ringingFrom = null) }}+ /** Records whether `pcId` is currently typing on this phone without mirroring. */+ fun setKeyboardFromPc(pcId: String, on: Boolean) {+ _state.update {+ it.copy(keyboardFromPc = if (on) it.keyboardFromPc + pcId else it.keyboardFromPc - pcId)+ }+ }++ /** Stops remote keyboard typing from `pcId` and notifies the PC. */+ fun stopKeyboardFromPc(pcId: String) {+ _state.update { it.copy(keyboardFromPc = it.keyboardFromPc - pcId) }+ val currentNode = node ?: return+ scope.launch(Dispatchers.IO) {+ runCatching { currentNode.mirrorStop(pcId, 0u) }+ }+ }+/** Runs a command on the node, turning errors into a message. */private fun command(block: suspend (NectarlinkNode) -> Unit) {- val node = node ?: returnscope.launch {+ startJob?.join()+ val node = node ?: return@launchtry {block(node)} catch (e: NectarlinkException) {@@ -1421,11 +1488,11 @@ class Core(context: Context, private val scope: CoroutineScope) : EventListener}private fun describe(e: NectarlinkException): String = when (e) {- is NectarlinkException.Offline -> "The PC isn't connected right now."- is NectarlinkException.NotPaired -> "That PC isn't paired anymore."- is NectarlinkException.Timeout -> "The PC didn't answer in time."- is NectarlinkException.Unsupported -> "The PC's app doesn't support that yet."- else -> "Something went wrong."+ is NectarlinkException.Offline -> context.getString(R.string.error_not_connected)+ is NectarlinkException.NotPaired -> context.getString(R.string.error_not_paired)+ is NectarlinkException.Timeout -> context.getString(R.string.error_timed_out)+ is NectarlinkException.Unsupported -> context.getString(R.string.error_unsupported)+ else -> context.getString(R.string.error_generic)}enum class RemoteAccess { Allowed, Denied, Offline, Unsupported }diff --git a/android/app/src/main/kotlin/app/nectarlink/android/core/CoreState.kt b/android/app/src/main/kotlin/app/nectarlink/android/core/CoreState.ktindex 17ebfbf..4d06457 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@@ -136,6 +136,8 @@ data class CoreState(val localsendEnabled: Boolean = false,/** Nearby LocalSend devices discovered on the LAN. */val localsendPeers: List<LocalSendPeer> = emptyList(),+ /** IDs of paired PCs currently typing on this phone without mirroring. */+ val keyboardFromPc: Set<String> = emptySet(),) {fun device(id: String): Device? = devices.firstOrNull { it.id == id }@@ -177,13 +179,16 @@ data class CoreState(ringingFrom = if (ringingFrom == nameOf(event.id)) null else ringingFrom,storageRequestedFrom = if (storageRequestedFrom == event.id) null else storageRequestedFrom,webcamRequest = if (webcamRequest?.pcId == event.id) null else webcamRequest,+ keyboardFromPc = keyboardFromPc - event.id,)is Event.LinkChanged -> update(event.id) {it.copy(link = event.link,wakeState = if (event.link is Link.Online) WakeState.Idle else it.wakeState,)- }+ }.copy(+ keyboardFromPc = if (event.link is Link.Offline) keyboardFromPc - event.id else keyboardFromPc,+ )is Event.PeerInfoChanged -> update(event.id) {it.copy(name = event.info.name,diff --git a/android/app/src/main/kotlin/app/nectarlink/android/core/PhonePlatform.kt b/android/app/src/main/kotlin/app/nectarlink/android/core/PhonePlatform.ktindex 3cc8379..5368c99 100644--- a/android/app/src/main/kotlin/app/nectarlink/android/core/PhonePlatform.kt+++ b/android/app/src/main/kotlin/app/nectarlink/android/core/PhonePlatform.kt@@ -81,6 +81,8 @@ internal class PhonePlatform(private val appWindows: AppWindows,/** Resolves a paired PC's display name by ID. */private val nameOf: (String) -> String = { "" },+ /** Notifies when a PC starts or stops typing on this phone without mirroring. */+ private val onKeyboardFromPc: (String, Boolean) -> Unit = { _, _ -> },) : Platform {private val context = context.applicationContext@@ -123,12 +125,25 @@ internal class PhonePlatform(if (options.app != null) {appWindows.open(pcId, options)} else {- val request = MirrorRequest(pcId, options.maxSize.toInt(), options.fps.toInt(), options.bitrate.toInt(), options.audio)+ val request = MirrorRequest(+ pcId,+ options.maxSize.toInt(),+ options.fps.toInt(),+ options.bitrate.toInt(),+ options.audio,+ options.stayAwake,+ options.screenOff,+ )onMirror(pcId, request)}+ override fun mirrorPowerRequested(pcId: String, stayAwake: Boolean, screenOff: Boolean) {+ MirrorService.setPower(pcId, stayAwake, screenOff)+ }+override fun mirrorStopRequested(pcId: String, session: UInt) {if (session != SCREEN) return appWindows.close(pcId, session)+ onKeyboardFromPc(pcId, false)MirrorRequests.dismiss(context, pcId)MirrorService.stop(pcId)}@@ -143,6 +158,22 @@ internal class PhonePlatform(// Real events when Elevated runs; gestures through the accessibility service otherwise.override fun mirrorInput(pcId: String, session: UInt, input: MirrorInputEvent) {if (session != SCREEN) return appWindows.input(pcId, session, input)+ if (input is MirrorInputEvent.Key) {+ when (input.key) {+ "keyboard_on" -> {+ onKeyboardFromPc(pcId, true)+ return+ }+ "keyboard_off" -> {+ onKeyboardFromPc(pcId, false)+ return+ }+ }+ }+ if (input is MirrorInputEvent.Text && input.text.any { it.code > 127 } && InputService.running) {+ InputService.handle(input)+ return+ }if (!Elevated.handle(input)) InputService.handle(input)}diff --git a/android/app/src/main/kotlin/app/nectarlink/android/elevated/Elevated.kt b/android/app/src/main/kotlin/app/nectarlink/android/elevated/Elevated.ktindex 08bf900..70a9e12 100644--- a/android/app/src/main/kotlin/app/nectarlink/android/elevated/Elevated.kt+++ b/android/app/src/main/kotlin/app/nectarlink/android/elevated/Elevated.kt@@ -71,6 +71,7 @@ object Elevated {private var socket: java.net.Socket? = null/** Where the helper listens, and the token it wants, while it runs. */@Volatile private var helper: Pair<Int, String>? = null+ @Volatile private var screenOffRequested = falseval running: Boolean get() = input != null@@ -215,6 +216,7 @@ object Elevated {writer.flush()input = writer_state.value = State.Running+ if (screenOffRequested) send(writer, "P 0")// Watches the helper: when its shell ends, Elevated stops.Thread {runCatching { output.lineSequence().forEach { line -> Log.d(TAG, "helper: $line") } }@@ -249,6 +251,7 @@ object Elevated {suspend fun stop() = withContext(Dispatchers.IO) { lock.withLock { stopLocked() } }private fun stopLocked() {+ screenOffRequested = falseinput = nullhelper = nullrunCatching { socket?.close() }@@ -262,6 +265,7 @@ object Elevated {/** Forgets the pairing (the user turned Elevated off). */suspend fun forget() {+ screenOffRequested = falsestop()context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit { putBoolean(PAIRED, false) }runCatching { adb?.close() }@@ -301,9 +305,16 @@ object Elevated {is MirrorInputEvent.Scroll -> "S ${event.x * w} ${event.y * h} ${event.dx} ${event.dy}"is MirrorInputEvent.Key -> keys[event.key]?.let { "K $it" }?: if (event.key == "notifications" && display == null) "C cmd statusbar expand-notifications" else return true- // One line per piece: no line breaks inside.+ // One line per piece: no line breaks inside. Non-ASCII pieces are pasted via the clipboard.is MirrorInputEvent.Text -> return event.text.split(LINE_BREAK).withIndex().all { (i, piece) ->- (i == 0 || send(writer, "${to}K ${KeyEvent.KEYCODE_ENTER}")) && (piece.isEmpty() || send(writer, "${to}T $piece"))+ (i == 0 || send(writer, "${to}K ${KeyEvent.KEYCODE_ENTER}")) && when {+ piece.isEmpty() -> true+ piece.any { it.code > 127 } -> {+ app.nectarlink.android.clipboard.PhoneClipboard.write(context, piece)+ send(writer, "${to}K ${KeyEvent.KEYCODE_PASTE}")+ }+ else -> send(writer, "${to}T $piece")+ }}}return send(writer, line)@@ -315,6 +326,13 @@ object Elevated {return send(writer, "C $command")}+ /** Turns the physical screen panel off or back on while mirroring. */+ fun setScreenOff(off: Boolean): Boolean {+ screenOffRequested = off+ val writer = input ?: return false+ return send(writer, "P ${if (off) 0 else 1}")+ }+/*** Opens an app window: the helper runs [pkg] on a display of its own of* [width] × [height] pixels at [dpi], and streams it on the returneddiff --git a/android/app/src/main/kotlin/app/nectarlink/android/elevated/InputServer.kt b/android/app/src/main/kotlin/app/nectarlink/android/elevated/InputServer.ktindex e02a417..9995652 100644--- a/android/app/src/main/kotlin/app/nectarlink/android/elevated/InputServer.kt+++ b/android/app/src/main/kotlin/app/nectarlink/android/elevated/InputServer.kt@@ -28,6 +28,7 @@ import java.security.MessageDigest* K keycode a key, pressed and released* T text typed text (what the keyboard map can type)* C command... a shell command of a fixed set (see `allowed`)+ * P 0 / P 1 physical screen power off (0) or normal (1)* Any of these after `@display ` goes to that display (an app window's).** A connection whose first line (after the token) is@@ -38,8 +39,13 @@ import java.security.MessageDigest* connection closes the window.*/object InputServer {+ private const val POWER_MODE_OFF = 0+ private const val POWER_MODE_NORMAL = 2+private val windows = java.util.Collections.synchronizedSet(LinkedHashSet<AppDisplay>())@Volatile private var serverSocket: ServerSocket? = null+ @Volatile private var displayTurnedOff = false+ @Volatile private var savedBrightness: Int? = null@JvmStaticfun main(args: Array<String>) {@@ -84,11 +90,63 @@ object InputServer {line = runCatching { reader.nextLine() }.getOrNull()}} finally {+ if (displayTurnedOff) runCatching { setDisplayPower(true) }shutdown()}}}+ /** Turns the physical screen panel on or off while keeping the display pipeline alive for capture. */+ @android.annotation.SuppressLint("PrivateApi", "DiscouragedPrivateApi", "BlockedPrivateApi")+ private fun setDisplayPower(on: Boolean) {+ if (!on) {+ displayTurnedOff = true+ if (savedBrightness == null) {+ savedBrightness = runCatching {+ val proc = Runtime.getRuntime().exec(arrayOf("settings", "get", "system", "screen_brightness"))+ val out = proc.inputStream.bufferedReader().use { it.readText().trim().toIntOrNull() }+ proc.waitFor()+ out+ }.getOrNull()+ }+ } else {+ displayTurnedOff = false+ }+ runCatching {+ val sc = Class.forName("android.view.SurfaceControl")+ val token = runCatching {+ sc.getMethod("getInternalDisplayToken").invoke(null) as? android.os.IBinder+ }.getOrNull() ?: runCatching {+ val dc = runCatching {+ dalvik.system.PathClassLoader("/system/framework/services.jar", null)+ .loadClass("com.android.server.display.DisplayControl")+ }.getOrElse { Class.forName("com.android.server.display.DisplayControl") }+ val ids = dc.getMethod("getPhysicalDisplayIds").invoke(null) as? LongArray+ if (ids != null && ids.isNotEmpty()) {+ dc.getMethod("getPhysicalDisplayToken", Long::class.javaPrimitiveType)+ .invoke(null, ids[0]) as? android.os.IBinder+ } else {+ null+ }+ }.getOrNull() ?: return@runCatching+ sc.getMethod("setDisplayPowerMode", android.os.IBinder::class.java, Int::class.javaPrimitiveType)+ .invoke(null, token, if (on) POWER_MODE_NORMAL else POWER_MODE_OFF)+ }+ if (!on) {+ runCatching {+ Runtime.getRuntime().exec(arrayOf("settings", "put", "system", "screen_brightness", "0")).waitFor()+ }+ } else if (on) {+ val saved = savedBrightness+ if (saved != null) {+ savedBrightness = null+ runCatching {+ Runtime.getRuntime().exec(arrayOf("settings", "put", "system", "screen_brightness", saved.toString())).waitFor()+ }+ }+ }+ }+/*** Reads until `\n` (ignoring bare `\r` as a line break so embedded `\r`* in typed text can never start a second command).@@ -189,6 +247,7 @@ object InputServer {"C" -> if (allowedCommand(rest) && display < 0) {Runtime.getRuntime().exec(rest.split(' ').toTypedArray()).waitFor()}+ "P" -> if (display < 0) setDisplayPower(rest.trim() != "0")}}diff --git a/android/app/src/main/kotlin/app/nectarlink/android/files/TransferNotifications.kt b/android/app/src/main/kotlin/app/nectarlink/android/files/TransferNotifications.ktindex d82785d..39dbbbc 100644--- a/android/app/src/main/kotlin/app/nectarlink/android/files/TransferNotifications.kt+++ b/android/app/src/main/kotlin/app/nectarlink/android/files/TransferNotifications.kt@@ -82,11 +82,23 @@ internal object TransferNotifications {/*** Files from a PC are saved: tap to open the first one, or the- * Downloads list when a folder came.+ * Downloads list when a folder came. When `openOnArrival` is true for a+ * single safe document, attempts to open it immediately with the default app.*/fun received(context: Context, transfer: Transfer, files: List<ReceivedFiles.Published>, pcName: String) {- if (!allowed(context) || files.isEmpty()) return+ if (files.isEmpty()) returnval first = files[0]+ val isHandoffDoc = transfer.openOnArrival &&+ files.size == 1 &&+ transfer.files.toInt() == 1 &&+ app.nectarlink.core.isSafeHandoffDocument(first.name)+ val directView = Intent(Intent.ACTION_VIEW)+ .setDataAndType(first.uri, first.mime)+ .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_GRANT_READ_URI_PERMISSION)+ if (isHandoffDoc) {+ runCatching { context.startActivity(directView) }+ }+ if (!allowed(context)) returnval open = if (transfer.files.toInt() == transfer.names.size) {Intent.createChooser(Intent(Intent.ACTION_VIEW).setDataAndType(first.uri, first.mime).addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION),@@ -99,14 +111,22 @@ internal object TransferNotifications {context, idOf(transfer), open.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK),PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT,)- val notification = NotificationCompat.Builder(context, CHANNEL_RECEIVED)+ val from = pcName.ifEmpty { context.getString(R.string.your_pc) }+ val text = if (isHandoffDoc) {+ context.getString(R.string.handoff_doc_received_from, from)+ } else {+ context.getString(R.string.transfer_received_from, from)+ }+ val builder = NotificationCompat.Builder(context, CHANNEL_RECEIVED).setSmallIcon(R.drawable.ic_notification).setContentTitle(title(context, transfer))- .setContentText(context.getString(R.string.transfer_received_from, pcName))+ .setContentText(text).setContentIntent(tap).setAutoCancel(true)- .build()- post(context, idOf(transfer), notification)+ if (isHandoffDoc) {+ builder.addAction(0, context.getString(R.string.clip_action_open), tap)+ }+ post(context, idOf(transfer), builder.build())}private fun failed(context: Context, transfer: Transfer, pcName: String) {diff --git a/android/app/src/main/kotlin/app/nectarlink/android/links/LinkNotifications.kt b/android/app/src/main/kotlin/app/nectarlink/android/links/LinkNotifications.ktindex 488517e..9cae2a3 100644--- a/android/app/src/main/kotlin/app/nectarlink/android/links/LinkNotifications.kt+++ b/android/app/src/main/kotlin/app/nectarlink/android/links/LinkNotifications.kt@@ -36,28 +36,53 @@ object LinkNotifications {)}- /** Shows a link from a PC; false if notifications are off for the app. */+ /** Shows a link, video with timestamp, or map location from a PC; false if notifications are off. */fun show(context: Context, pcName: String, url: String): Boolean {if (ContextCompat.checkSelfPermission(context, Manifest.permission.POST_NOTIFICATIONS) !=PackageManager.PERMISSION_GRANTED) {return false}- val uri = url.toUri()+ val handoff = app.nectarlink.core.extractHandoffLink(url)+ val viewIntent = if (url.startsWith("geo:", ignoreCase = true)) {+ val geoIntent = Intent(Intent.ACTION_VIEW, url.toUri()).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)+ if (geoIntent.resolveActivity(context.packageManager) != null) {+ geoIntent+ } else {+ val webFallback = app.nectarlink.core.geoToMapsHttps(url) ?: url+ Intent(Intent.ACTION_VIEW, webFallback.toUri()).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)+ }+ } else {+ Intent(Intent.ACTION_VIEW, url.toUri()).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)+ }+ // When Nectarlink is in the foreground, Android allows opening the target right away.+ runCatching { context.startActivity(viewIntent) }+val open = PendingIntent.getActivity(context,url.hashCode(),- Intent(Intent.ACTION_VIEW, uri).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK),+ viewIntent,PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT,)- // "example.com/path", without the scheme, reads better.- val shown = url.substringAfter("://").removeSuffix("/")+ val from = pcName.ifEmpty { context.getString(R.string.your_pc) }+ val title = when (handoff?.kind) {+ app.nectarlink.core.HandoffKind.MAP_LOCATION -> context.getString(R.string.handoff_map_from, from)+ app.nectarlink.core.HandoffKind.VIDEO_LINK -> context.getString(R.string.handoff_video_from, from)+ else -> context.getString(R.string.link_from, from)+ }+ val shown = handoff?.label ?: url.substringAfter("://").removeSuffix("/")+ val actionLabel = when (handoff?.kind) {+ app.nectarlink.core.HandoffKind.MAP_LOCATION -> context.getString(R.string.clip_action_maps)+ app.nectarlink.core.HandoffKind.VIDEO_LINK -> context.getString(R.string.handoff_action_continue_video)+ else -> context.getString(R.string.clip_action_open)+ }val notification = NotificationCompat.Builder(context, CHANNEL).setSmallIcon(R.drawable.ic_notification)- .setContentTitle(context.getString(R.string.link_from, pcName.ifEmpty { context.getString(R.string.your_pc) }))+ .setContentTitle(title).setContentText(shown).setStyle(NotificationCompat.BigTextStyle().bigText(shown)).setContentIntent(open)+ .addAction(0, actionLabel, open).setAutoCancel(true).setCategory(NotificationCompat.CATEGORY_RECOMMENDATION).setPriority(NotificationCompat.PRIORITY_HIGH)diff --git a/android/app/src/main/kotlin/app/nectarlink/android/media/PhoneMedia.kt b/android/app/src/main/kotlin/app/nectarlink/android/media/PhoneMedia.ktindex a4f47c2..12bf6ac 100644--- a/android/app/src/main/kotlin/app/nectarlink/android/media/PhoneMedia.kt+++ b/android/app/src/main/kotlin/app/nectarlink/android/media/PhoneMedia.kt@@ -203,6 +203,23 @@ class PhoneMedia(context: Context, private val onChange: (List<MediaPlayer>) ->}}+ /** Current playback position in seconds of the active media session, if any. */+ fun activePositionSeconds(): UInt? {+ val list = lastSent ?: return null+ val first = list.firstOrNull { it.playing } ?: list.firstOrNull() ?: return null+ val baseMs = first.position?.toLong() ?: return null+ val elapsedMs = if (first.playing && lastSentAt > 0) {+ (SystemClock.elapsedRealtime() - lastSentAt).coerceAtLeast(0L)+ } else {+ 0L+ }+ val totalMs = (baseMs + elapsedMs).let { pos ->+ first.duration?.toLong()?.let { dur -> pos.coerceAtMost(dur) } ?: pos+ }+ val secs = (totalMs / 1000L).toInt()+ return if (secs > 0) secs.toUInt() else null+ }+/*** Artwork as a small JPEG, made once per track and picture size (apps* hand over a new copy of the same picture with every update).diff --git a/android/app/src/main/kotlin/app/nectarlink/android/mirror/InputService.kt b/android/app/src/main/kotlin/app/nectarlink/android/mirror/InputService.ktindex 4e406a6..e5341d6 100644--- a/android/app/src/main/kotlin/app/nectarlink/android/mirror/InputService.kt+++ b/android/app/src/main/kotlin/app/nectarlink/android/mirror/InputService.kt@@ -173,6 +173,15 @@ class InputService : AccessibilityService() {}"left" -> edit { text, start, _ -> Edit(text, if (start > 0) text.offsetByCodePoints(start, -1) else 0) }"right" -> edit { text, _, end -> Edit(text, if (end < text.length) text.offsetByCodePoints(end, 1) else text.length) }+ "up" -> edit { text, start, _ ->+ val prevNewline = text.lastIndexOf('\n', (start - 1).coerceAtLeast(0))+ Edit(text, if (prevNewline >= 0) prevNewline else 0)+ }+ "down" -> edit { text, _, end ->+ val nextNewline = text.indexOf('\n', end)+ Edit(text, if (nextNewline >= 0) (nextNewline + 1).coerceAtMost(text.length) else text.length)+ }+ "tab" -> focused()?.focusSearch(android.view.View.FOCUS_FORWARD)?.performAction(AccessibilityNodeInfo.ACTION_FOCUS)}}@@ -180,16 +189,35 @@ class InputService : AccessibilityService() {private data class Edit(val text: String, val cursor: Int)+ private var pendingText: String? = null+ private var pendingCursor: Int = 0+ private var pendingAt: Long = 0L+/** Changes the focused text field: its text and selection in, the new text and cursor out. */private fun edit(change: (String, Int, Int) -> Edit?) {val node = focused() ?: return- if (!node.isEditable) return+ if (!isNodeEditable(node)) return+ runCatching { node.refresh() }val showingHint = Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && node.isShowingHintText- val text = if (showingHint) "" else node.text?.toString().orEmpty()- val start = node.textSelectionStart.takeIf { it in 0..text.length } ?: text.length- val end = node.textSelectionEnd.takeIf { it in start..text.length } ?: start+ val rawText = if (showingHint) "" else node.text?.toString().orEmpty()+ val now = SystemClock.uptimeMillis()+ val usePending = pendingText != null && (now - pendingAt) < 350L && rawText != pendingText+ val text = if (usePending) pendingText!! else rawText+ val start = if (usePending || (rawText == pendingText && node.textSelectionStart <= 0 && pendingCursor > 0)) {+ pendingCursor.coerceIn(0, text.length)+ } else {+ node.textSelectionStart.takeIf { it in 0..text.length } ?: text.length+ }+ val end = if (usePending || (rawText == pendingText && node.textSelectionEnd <= 0 && pendingCursor > 0)) {+ start+ } else {+ node.textSelectionEnd.takeIf { it in start..text.length } ?: start+ }val result = change(text, start, end) ?: return- if (result.text != text) {+ pendingText = result.text+ pendingCursor = result.cursor+ pendingAt = now+ if (result.text != text || usePending) {node.performAction(AccessibilityNodeInfo.ACTION_SET_TEXT,Bundle().apply { putCharSequence(AccessibilityNodeInfo.ACTION_ARGUMENT_SET_TEXT_CHARSEQUENCE, result.text) },@@ -204,7 +232,35 @@ class InputService : AccessibilityService() {)}- private fun focused(): AccessibilityNodeInfo? = findFocus(AccessibilityNodeInfo.FOCUS_INPUT)+ private fun isNodeEditable(node: AccessibilityNodeInfo): Boolean =+ node.isEditable ||+ node.className == "android.widget.EditText" ||+ node.actionList.any { it.id == AccessibilityNodeInfo.ACTION_SET_TEXT }++ private fun focused(): AccessibilityNodeInfo? {+ findFocus(AccessibilityNodeInfo.FOCUS_INPUT)?.takeIf { isNodeEditable(it) }?.let { return it }+ findFocus(AccessibilityNodeInfo.FOCUS_ACCESSIBILITY)?.takeIf { isNodeEditable(it) }?.let { return it }+ val roots = buildList {+ rootInActiveWindow?.let { add(it) }+ runCatching { windows }.getOrNull()?.forEach { w -> w.root?.let { add(it) } }+ }+ for (root in roots) {+ findEditable(root, requireFocused = true)?.let { return it }+ }+ for (root in roots) {+ findEditable(root, requireFocused = false)?.let { return it }+ }+ return findFocus(AccessibilityNodeInfo.FOCUS_INPUT)+ }++ private fun findEditable(node: AccessibilityNodeInfo?, requireFocused: Boolean): AccessibilityNodeInfo? {+ if (node == null) return null+ if (isNodeEditable(node) && (!requireFocused || node.isFocused)) return node+ for (i in 0 until node.childCount) {+ findEditable(node.getChild(i), requireFocused)?.let { return it }+ }+ return null+ }companion object {private const val TAG = "InputService"diff --git a/android/app/src/main/kotlin/app/nectarlink/android/mirror/MirrorRequest.kt b/android/app/src/main/kotlin/app/nectarlink/android/mirror/MirrorRequest.ktindex dbb31af..edf29f4 100644--- a/android/app/src/main/kotlin/app/nectarlink/android/mirror/MirrorRequest.kt+++ b/android/app/src/main/kotlin/app/nectarlink/android/mirror/MirrorRequest.kt@@ -20,13 +20,23 @@ import androidx.core.content.ContextCompatimport app.nectarlink.android.R/** A PC asking for the screen (and its sound), with what it wants. */-data class MirrorRequest(val pcId: String, val maxSize: Int, val fps: Int, val bitrate: Int, val audio: Boolean) {+data class MirrorRequest(+ val pcId: String,+ val maxSize: Int,+ val fps: Int,+ val bitrate: Int,+ val audio: Boolean,+ val stayAwake: Boolean = false,+ val screenOff: Boolean = false,+) {fun toIntent(intent: Intent): Intent = intent.putExtra("pc", pcId).putExtra("maxSize", maxSize).putExtra("fps", fps).putExtra("bitrate", bitrate).putExtra("audio", audio)+ .putExtra("stayAwake", stayAwake)+ .putExtra("screenOff", screenOff)companion object {fun of(intent: Intent): MirrorRequest? = intent.getStringExtra("pc")?.let {@@ -36,6 +46,8 @@ data class MirrorRequest(val pcId: String, val maxSize: Int, val fps: Int, val bintent.getIntExtra("fps", 60),intent.getIntExtra("bitrate", 8_000_000),intent.getBooleanExtra("audio", false),+ intent.getBooleanExtra("stayAwake", false),+ intent.getBooleanExtra("screenOff", false),)}}diff --git a/android/app/src/main/kotlin/app/nectarlink/android/mirror/MirrorService.kt b/android/app/src/main/kotlin/app/nectarlink/android/mirror/MirrorService.ktindex cb7bfd6..3b57e5d 100644--- a/android/app/src/main/kotlin/app/nectarlink/android/mirror/MirrorService.kt+++ b/android/app/src/main/kotlin/app/nectarlink/android/mirror/MirrorService.kt@@ -40,6 +40,9 @@ class MirrorService : Service() {private var encoder: ScreenEncoder? = nullprivate var sound: SoundCapture? = nullprivate var pcId: String? = null+ private var wakeLock: android.os.PowerManager.WakeLock? = null+ private var stayAwake: Boolean = false+ private var screenOff: Boolean = falseoverride fun onBind(intent: Intent?): IBinder? = null@@ -71,6 +74,8 @@ class MirrorService : Service() {}projection = grantedpcId = pc+ stayAwake = intent.getBooleanExtra(EXTRA_STAY_AWAKE, false)+ screenOff = intent.getBooleanExtra(EXTRA_SCREEN_OFF, false)current = thisgranted.registerCallback(object : MediaProjection.Callback() {// The user stopped it (from the status bar, or by locking).@@ -95,12 +100,35 @@ class MirrorService : Service() {encoder = ScreenEncoder(this@MirrorService, running, stream, maxSize, fps, bitrate) {main.post { stopSharing() }}.also { it.start() }+ applyPower()}if (audio && SoundCapture.canCapture(this@MirrorService)) startSound(core, pc)}return START_NOT_STICKY}+ @Suppress("DEPRECATION")+ private fun applyPower() {+ val active = encoder != null && projection != null+ val wantWake = active && (stayAwake || screenOff)+ if (wantWake) {+ if (wakeLock == null) {+ wakeLock = getSystemService(android.os.PowerManager::class.java)?.newWakeLock(+ android.os.PowerManager.SCREEN_BRIGHT_WAKE_LOCK or android.os.PowerManager.ACQUIRE_CAUSES_WAKEUP,+ "nectarlink:mirror",+ )?.apply { setReferenceCounted(false) }+ }+ if (wakeLock?.isHeld == false) {+ runCatching { wakeLock?.acquire(4 * 60 * 60 * 1000L) }+ }+ } else {+ if (wakeLock?.isHeld == true) {+ runCatching { wakeLock?.release() }+ }+ }+ app.nectarlink.android.elevated.Elevated.setScreenOff(active && screenOff)+ }+/** The sound, on a stream of its own; the screen goes on without it if it can't. */private suspend fun startSound(core: app.nectarlink.android.core.Core, pc: String) {if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) return@@ -134,6 +162,11 @@ class MirrorService : Service() {}private fun stopSharing() {+ stayAwake = false+ screenOff = false+ runCatching { if (wakeLock?.isHeld == true) wakeLock?.release() }+ wakeLock = null+ app.nectarlink.android.elevated.Elevated.setScreenOff(false)encoder?.stop()encoder = nullsound?.stop()@@ -164,6 +197,8 @@ class MirrorService : Service() {private const val EXTRA_FPS = "fps"private const val EXTRA_BITRATE = "bitrate"private const val EXTRA_AUDIO = "audio"+ private const val EXTRA_STAY_AWAKE = "stayAwake"+ private const val EXTRA_SCREEN_OFF = "screenOff"/** The service sharing the screen now, if any. */@Volatile private var current: MirrorService? = null@@ -184,6 +219,8 @@ class MirrorService : Service() {.putExtra(EXTRA_FPS, request.fps).putExtra(EXTRA_BITRATE, request.bitrate).putExtra(EXTRA_AUDIO, request.audio)+ .putExtra(EXTRA_STAY_AWAKE, request.stayAwake)+ .putExtra(EXTRA_SCREEN_OFF, request.screenOff)ContextCompat.startForegroundService(context, intent)}@@ -197,5 +234,17 @@ class MirrorService : Service() {fun keyframe(pcId: String) {current?.takeIf { it.pcId == pcId }?.encoder?.requestKeyframe()}++ /** Updates keep-awake and screen-off state while mirroring to [pcId]. */+ fun setPower(pcId: String, stayAwake: Boolean, screenOff: Boolean) {+ val service = current ?: return+ service.main.post {+ if (service.pcId == pcId) {+ service.stayAwake = stayAwake+ service.screenOff = screenOff+ service.applyPower()+ }+ }+ }}}diff --git a/android/app/src/main/kotlin/app/nectarlink/android/notifications/TaskNotifications.kt b/android/app/src/main/kotlin/app/nectarlink/android/notifications/TaskNotifications.ktindex 0934b7b..6eb90c5 100644--- a/android/app/src/main/kotlin/app/nectarlink/android/notifications/TaskNotifications.kt+++ b/android/app/src/main/kotlin/app/nectarlink/android/notifications/TaskNotifications.kt@@ -91,7 +91,7 @@ object TaskNotifications {open: PendingIntent,groupKey: String,): Notification {- val title = task.title.trim().ifEmpty { "Task" }+ val title = task.title.trim().ifEmpty { context.getString(R.string.task_default_label) }val body = context.getString(R.string.task_running_on, from)val now = System.currentTimeMillis()val elapsedMs = task.elapsedMs.toLong().coerceAtLeast(0L)@@ -111,7 +111,7 @@ object TaskNotifications {.setCategory(Notification.CATEGORY_PROGRESS)if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.BAKLAVA) {runCatching { builder.setRequestPromotedOngoing(true) }- builder.setShortCriticalText(shortChipText(title))+ builder.setShortCriticalText(shortChipText(title, context))}return builder.build()}@@ -123,8 +123,8 @@ object TaskNotifications {open: PendingIntent,groupKey: String,): Notification {- val title = completionTitle(task.title, task.exitCode)- val body = completionBody(from, task.elapsedMs.toLong().coerceAtLeast(0L))+ val title = completionTitle(task.title, task.exitCode, context)+ val body = completionBody(from, task.elapsedMs.toLong().coerceAtLeast(0L), context)return Notification.Builder(context, CHANNEL_DONE).setSmallIcon(R.drawable.ic_notification).setContentTitle(title)@@ -141,34 +141,40 @@ object TaskNotifications {.build()}- internal fun completionTitle(rawTitle: String, exitCode: Int?): String {- val base = rawTitle.trim().ifEmpty { "Task" }+ internal fun completionTitle(rawTitle: String, exitCode: Int?, context: Context? = null): String {+ val base = rawTitle.trim().ifEmpty {+ context?.getString(R.string.task_default_label) ?: "Task"+ }return if (exitCode == null || exitCode == 0) {- "$base finished"+ context?.getString(R.string.task_finished_title, base) ?: "$base finished"} else {- "$base failed (exit $exitCode)"+ context?.getString(R.string.task_failed_title, base, exitCode) ?: "$base failed (exit $exitCode)"}}- internal fun completionBody(from: String, elapsedMs: Long): String {- val took = formatTook(elapsedMs)- return "$took · $from"+ internal fun completionBody(from: String, elapsedMs: Long, context: Context? = null): String {+ val took = formatTook(elapsedMs, context)+ return context?.getString(R.string.task_took_from, took, from) ?: "$took · $from"}- internal fun formatTook(elapsedMs: Long): String {+ internal fun formatTook(elapsedMs: Long, context: Context? = null): String {val totalSecs = (elapsedMs.coerceAtLeast(0L) + 500L) / 1000Lval hours = totalSecs / 3600Lval mins = (totalSecs % 3600L) / 60Lval secs = totalSecs % 60Lreturn when {- hours > 0L -> "Took ${hours}h %02dm".format(java.util.Locale.US, mins)- mins > 0L -> "Took ${mins}m %02ds".format(java.util.Locale.US, secs)- else -> "Took ${secs}s"+ hours > 0L -> context?.getString(R.string.task_took_hm, hours, mins)+ ?: "Took ${hours}h %02dm".format(java.util.Locale.US, mins)+ mins > 0L -> context?.getString(R.string.task_took_ms, mins, secs)+ ?: "Took ${mins}m %02ds".format(java.util.Locale.US, secs)+ else -> context?.getString(R.string.task_took_s, secs) ?: "Took ${secs}s"}}- internal fun shortChipText(title: String): String {- val trimmed = title.trim().ifEmpty { "Running" }+ internal fun shortChipText(title: String, context: Context? = null): String {+ val trimmed = title.trim().ifEmpty {+ context?.getString(R.string.task_running_short) ?: "Running"+ }return if (trimmed.length <= 7) trimmed else trimmed.take(6).trimEnd() + "…"}}diff --git a/android/app/src/main/kotlin/app/nectarlink/android/service/ConnectionService.kt b/android/app/src/main/kotlin/app/nectarlink/android/service/ConnectionService.ktindex 8639dc1..8ed5346 100644--- a/android/app/src/main/kotlin/app/nectarlink/android/service/ConnectionService.kt+++ b/android/app/src/main/kotlin/app/nectarlink/android/service/ConnectionService.kt@@ -105,7 +105,11 @@ class ConnectionService : LifecycleService() {private fun ongoingNotification(status: Status): Notification {val text = when {status.connected.size == 1 -> getString(R.string.notification_connected_to, status.connected[0])- status.connected.size > 1 -> getString(R.string.notification_connected_many, status.connected.size)+ status.connected.size > 1 -> resources.getQuantityString(+ R.plurals.notification_connected_pcs,+ status.connected.size,+ status.connected.size,+ )status.paired == 0 -> getString(R.string.notification_not_paired)else -> getString(R.string.notification_waiting)}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.ktindex 9d72a68..725a318 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@@ -56,6 +56,7 @@ import app.nectarlink.android.ui.recorder.RecorderScreenimport app.nectarlink.android.ui.remote.RemoteModeimport app.nectarlink.android.ui.remote.RemoteScreenimport app.nectarlink.android.ui.settings.SettingsScreen+import app.nectarlink.android.ui.theme.LocalReducedMotionimport app.nectarlink.android.ui.theme.NectarlinkThemeimport app.nectarlink.android.ui.webcam.WebcamScreen@@ -352,7 +353,11 @@ private fun App(when {state.status is CoreStatus.Starting -> Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {- CircularProgressIndicator()+ if (LocalReducedMotion.current) {+ CircularProgressIndicator(progress = { 0.75f })+ } else {+ CircularProgressIndicator()+ }}state.status is CoreStatus.Failed -> Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {Text(stringResource(R.string.core_failed, state.status.message))@@ -497,6 +502,7 @@ private fun App(onClearTimeline = core::clearTimeline,onResendTimelineEntry = core::resendTimelineEntry,onSetPcAudio = core::setPcAudio,+ onStopKeyboardFromPc = core::stopKeyboardFromPc,modifier = modifier,)Tab.Settings -> SettingsScreen(diff --git a/android/app/src/main/kotlin/app/nectarlink/android/ui/deck/DeckScreen.kt b/android/app/src/main/kotlin/app/nectarlink/android/ui/deck/DeckScreen.ktindex fa5bddc..50e5d78 100644--- a/android/app/src/main/kotlin/app/nectarlink/android/ui/deck/DeckScreen.kt+++ b/android/app/src/main/kotlin/app/nectarlink/android/ui/deck/DeckScreen.kt@@ -2,11 +2,13 @@package app.nectarlink.android.ui.deckimport android.app.Activity+import android.content.Contextimport android.content.res.Configurationimport android.view.HapticFeedbackConstantsimport android.view.WindowManagerimport androidx.compose.animation.core.Springimport androidx.compose.animation.core.animateFloatAsState+import androidx.compose.animation.core.snapimport androidx.compose.animation.core.springimport androidx.compose.foundation.BorderStrokeimport androidx.compose.foundation.Canvas@@ -71,6 +73,7 @@ import androidx.compose.ui.res.painterResourceimport androidx.compose.ui.res.stringResourceimport androidx.compose.ui.semantics.Roleimport androidx.compose.ui.semantics.contentDescription+import androidx.compose.ui.semantics.onClickimport androidx.compose.ui.semantics.roleimport androidx.compose.ui.semantics.semanticsimport androidx.compose.ui.text.font.FontWeight@@ -84,6 +87,7 @@ import app.nectarlink.android.Rimport app.nectarlink.android.core.Coreimport app.nectarlink.android.core.Deviceimport app.nectarlink.android.ui.home.PcAudioOutputsDialog+import app.nectarlink.android.ui.theme.LocalReducedMotionimport app.nectarlink.core.DeckLayoutimport app.nectarlink.core.DeckPageimport app.nectarlink.core.DeckState@@ -151,7 +155,8 @@ fun DeckScreen(}}- val layout = device.deckLayout ?: remember { fallbackDefaultLayout() }+ val reducedMotion = LocalReducedMotion.current+ val layout = device.deckLayout ?: remember(context) { fallbackDefaultLayout(context) }val liveState = device.deckState ?: DeckState(playing = false,volume = 50u,@@ -159,7 +164,7 @@ fun DeckScreen(micMuted = false,outputDevices = emptyList(),)- val pages = layout.pages.ifEmpty { fallbackDefaultLayout().pages }+ val pages = layout.pages.ifEmpty { fallbackDefaultLayout(context).pages }val pagerState = rememberPagerState(pageCount = { pages.size })Column(@@ -260,7 +265,13 @@ fun DeckScreen(FilterChip(selected = pagerState.currentPage == index,onClick = {- scope.launch { pagerState.animateScrollToPage(index) }+ scope.launch {+ if (reducedMotion) {+ pagerState.scrollToPage(index)+ } else {+ pagerState.animateScrollToPage(index)+ }+ }},label = {Text(@@ -357,6 +368,7 @@ private fun DeckAudioHeaderBar(var showOutputs by remember { mutableStateOf(false) }val shownVolume = draggingVolume?.roundToInt() ?: liveState.volume.toInt()val defaultOutput = liveState.outputDevices.firstOrNull { it.isDefault } ?: liveState.outputDevices.firstOrNull()+ val volumeLabel = stringResource(R.string.pc_audio_volume)Surface(shape = MaterialTheme.shapes.large,@@ -390,7 +402,9 @@ private fun DeckAudioHeaderBar(},onValueChangeFinished = { draggingVolume = null },valueRange = 0f..100f,- modifier = Modifier.weight(1f),+ modifier = Modifier+ .weight(1f)+ .semantics { contentDescription = volumeLabel },)Text(text = if (liveState.muted) {@@ -405,7 +419,7 @@ private fun DeckAudioHeaderBar(Row(modifier = Modifier.fillMaxWidth()- .clickable { showOutputs = true }+ .clickable(role = Role.Button) { showOutputs = true }.padding(horizontal = 4.dp, vertical = 2.dp),verticalAlignment = Alignment.CenterVertically,horizontalArrangement = Arrangement.SpaceBetween,@@ -465,7 +479,11 @@ private fun DeckBanner(}}if (onDismiss != null) {- TextButton(onClick = onDismiss) {+ val dismissLabel = stringResource(R.string.action_dismiss)+ TextButton(+ onClick = onDismiss,+ modifier = Modifier.semantics { contentDescription = dismissLabel },+ ) {Text("×", style = MaterialTheme.typography.titleMedium)}}@@ -543,6 +561,7 @@ private fun DeckTileButton(enabled: Boolean,onPress: () -> Unit,) {+ val reducedMotion = LocalReducedMotion.currentval badge = liveBadgeText(tile.kind, liveState)val highlighted = isLiveHighlighted(tile.kind, liveState)val palette = tilePalette(tile.color, highlighted)@@ -550,12 +569,16 @@ private fun DeckTileButton(var pressed by remember { mutableStateOf(false) }val scale by animateFloatAsState(- targetValue = if (pressed) 0.96f else 1f,- animationSpec = spring(stiffness = Spring.StiffnessHigh),+ targetValue = if (pressed && !reducedMotion) 0.96f else 1f,+ animationSpec = if (reducedMotion) snap() else spring(stiffness = Spring.StiffnessHigh),label = "tileScale",)- val a11yDescription = if (badge != null) "${tile.label}, $badge" else tile.label+ val a11yDescription = if (badge != null) {+ stringResource(R.string.deck_tile_with_badge, tile.label, badge)+ } else {+ tile.label+ }val fontScale = LocalConfiguration.current.fontScale.coerceIn(1f, 1.35f)val tileHeight = ((if (compact) 98 else 118) * fontScale).dp@@ -574,9 +597,15 @@ private fun DeckTileButton(scaleX = scalescaleY = scale}- .semantics {+ .semantics(mergeDescendants = true) {role = Role.ButtoncontentDescription = a11yDescription+ if (enabled) {+ onClick(label = a11yDescription) {+ onPress()+ true+ }+ }}.pointerInput(enabled, tile.id) {if (!enabled) return@pointerInput@@ -992,23 +1021,23 @@ private fun DrawScope.drawSpeakerCone(drawPath(cone, color = color, style = stroke)}-private fun fallbackDefaultLayout(): DeckLayout = DeckLayout(+private fun fallbackDefaultLayout(context: Context): DeckLayout = DeckLayout(pages = listOf(DeckPage(id = "main",- name = "Main",+ name = context.getString(R.string.deck_default_page_main),tiles = listOf(- DeckTile("play_pause", "Play / pause", "play", "amber", "media_play_pause"),- DeckTile("prev_track", "Previous", "skip_previous", "slate", "media_previous"),- DeckTile("next_track", "Next", "skip_next", "slate", "media_next"),- DeckTile("vol_down", "Volume down", "volume_down", "teal", "volume_down"),- DeckTile("vol_up", "Volume up", "volume_up", "teal", "volume_up"),- DeckTile("vol_mute", "Mute audio", "volume_off", "teal", "volume_mute"),- DeckTile("mic_mute", "Mic mute", "mic", "coral", "mic_mute"),- DeckTile("show_desktop", "Show desktop", "desktop", "blue", "show_desktop"),- DeckTile("switch_window", "Switch window", "switch_window", "blue", "switch_window"),- DeckTile("screenshot", "Screenshot", "screenshot", "violet", "screenshot"),- DeckTile("lock_pc", "Lock PC", "lock", "red", "lock_pc"),+ DeckTile("play_pause", context.getString(R.string.deck_default_play_pause), "play", "amber", "media_play_pause"),+ DeckTile("prev_track", context.getString(R.string.deck_default_previous), "skip_previous", "slate", "media_previous"),+ DeckTile("next_track", context.getString(R.string.deck_default_next), "skip_next", "slate", "media_next"),+ DeckTile("vol_down", context.getString(R.string.deck_default_volume_down), "volume_down", "teal", "volume_down"),+ DeckTile("vol_up", context.getString(R.string.deck_default_volume_up), "volume_up", "teal", "volume_up"),+ DeckTile("vol_mute", context.getString(R.string.deck_default_volume_mute), "volume_off", "teal", "volume_mute"),+ DeckTile("mic_mute", context.getString(R.string.deck_default_mic_mute), "mic", "coral", "mic_mute"),+ DeckTile("show_desktop", context.getString(R.string.deck_default_show_desktop), "desktop", "blue", "show_desktop"),+ DeckTile("switch_window", context.getString(R.string.deck_default_switch_window), "switch_window", "blue", "switch_window"),+ DeckTile("screenshot", context.getString(R.string.deck_default_screenshot), "screenshot", "violet", "screenshot"),+ DeckTile("lock_pc", context.getString(R.string.deck_default_lock_pc), "lock", "red", "lock_pc"),),),),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.ktindex 2236e2d..4deee96 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@@ -60,6 +60,10 @@ import androidx.compose.ui.layout.ContentScaleimport androidx.compose.ui.platform.LocalContextimport androidx.compose.ui.res.painterResourceimport androidx.compose.ui.res.stringResource+import androidx.compose.ui.semantics.Role+import androidx.compose.ui.semantics.contentDescription+import androidx.compose.ui.semantics.role+import androidx.compose.ui.semantics.semanticsimport androidx.compose.ui.text.style.TextOverflowimport androidx.compose.ui.unit.dpimport app.nectarlink.android.R@@ -76,6 +80,7 @@ import app.nectarlink.android.files.transferTitleimport app.nectarlink.android.notifications.NotificationListenerimport app.nectarlink.android.photos.RecentPhotosimport app.nectarlink.android.sms.PhoneSms+import app.nectarlink.android.ui.theme.LocalReducedMotionimport app.nectarlink.android.update.AppUpdaterimport app.nectarlink.android.update.UpdateCardimport android.app.DownloadManager@@ -145,6 +150,7 @@ fun HomeScreen(onClearTimeline: () -> Unit = {},onResendTimelineEntry: (entry: TimelineEntry) -> Unit = {},onSetPcAudio: (pcId: String, volume: Int?, muted: Boolean?) -> Unit = { _, _, _ -> },+ onStopKeyboardFromPc: (pcId: String) -> Unit = {},modifier: Modifier = Modifier,) {var showClipboardHistory by remember { mutableStateOf(false) }@@ -162,13 +168,16 @@ fun HomeScreen(modifier = Modifier.weight(1f),)// Reconnects and syncs with the PCs; spins once to say so.+ val reducedMotion = LocalReducedMotion.currentval spin = remember { androidx.compose.animation.core.Animatable(0f) }val scope = rememberCoroutineScope()IconButton(onClick = {onRefresh()- scope.launch {- spin.snapTo(0f)- spin.animateTo(360f, androidx.compose.animation.core.tween(700))+ if (!reducedMotion) {+ scope.launch {+ spin.snapTo(0f)+ spin.animateTo(360f, androidx.compose.animation.core.tween(700))+ }}}) {Icon(@@ -185,6 +194,12 @@ fun HomeScreen(state.ringingFrom?.let { from ->item { RingingBanner(from, onStopRinging) }}+ state.keyboardFromPc.forEach { pcId ->+ item(key = "keyboard_$pcId") {+ val pcName = state.nameOf(pcId) ?: stringResource(R.string.your_pc)+ KeyboardBanner(pcName, onStop = { onStopKeyboardFromPc(pcId) })+ }+ }state.webcamRequest?.let { req ->item {val pcName = state.nameOf(req.pcId) ?: stringResource(R.string.your_pc)@@ -422,6 +437,22 @@ private fun RingingBanner(from: String, onStop: () -> Unit) {}}+@Composable+private fun KeyboardBanner(from: String, onStop: () -> Unit) {+ Surface(shape = MaterialTheme.shapes.extraLarge, color = MaterialTheme.colorScheme.secondaryContainer) {+ Row(Modifier.fillMaxWidth().padding(20.dp), verticalAlignment = Alignment.CenterVertically) {+ Text(+ stringResource(R.string.keyboard_from_pc_banner, from),+ style = MaterialTheme.typography.titleMedium,+ color = MaterialTheme.colorScheme.onSecondaryContainer,+ modifier = Modifier.weight(1f),+ )+ Spacer(Modifier.width(12.dp))+ Button(onClick = onStop) { Text(stringResource(R.string.keyboard_stop)) }+ }+ }+}+@Composableprivate fun PcCard(device: Device,@@ -698,7 +729,11 @@ private fun PcCard(}if (!device.online && device.wakeState == WakeState.Waking) {Spacer(Modifier.height(14.dp))- LinearProgressIndicator(modifier = Modifier.fillMaxWidth())+ if (LocalReducedMotion.current) {+ LinearProgressIndicator(progress = { 0.5f }, modifier = Modifier.fillMaxWidth())+ } else {+ LinearProgressIndicator(modifier = Modifier.fillMaxWidth())+ }} else if (!device.online && device.wakeState == WakeState.TimedOut) {Spacer(Modifier.height(16.dp))Surface(@@ -734,6 +769,7 @@ private fun PcAudioCardSection(var showOutputs by remember { mutableStateOf(false) }val shownVolume = draggingVolume?.roundToInt() ?: deckState.volume.toInt()val defaultOutput = deckState.outputDevices.firstOrNull { it.isDefault } ?: deckState.outputDevices.firstOrNull()+ val volumeLabel = stringResource(R.string.pc_audio_volume)Surface(shape = MaterialTheme.shapes.large,@@ -758,7 +794,7 @@ private fun PcAudioCardSection(contentDescription = stringResource(if (deckState.muted) R.string.pc_audio_unmute else R.string.pc_audio_mute,),- tint = ink.copy(alpha = if (deckState.muted) 0.55f else 0.9f),+ tint = ink.copy(alpha = if (deckState.muted) 0.85f else 0.9f),modifier = Modifier.size(20.dp),)}@@ -775,7 +811,10 @@ private fun PcAudioCardSection(activeTrackColor = ink,inactiveTrackColor = ink.copy(alpha = 0.22f),),- modifier = Modifier.weight(1f).height(32.dp),+ modifier = Modifier+ .weight(1f)+ .height(32.dp)+ .semantics { contentDescription = volumeLabel },)Text(text = if (deckState.muted) {@@ -790,7 +829,7 @@ private fun PcAudioCardSection(Row(modifier = Modifier.fillMaxWidth()- .clickable { showOutputs = true }+ .clickable(role = Role.Button) { showOutputs = true }.padding(start = 38.dp, end = 4.dp, bottom = 2.dp),verticalAlignment = Alignment.CenterVertically,horizontalArrangement = Arrangement.SpaceBetween,@@ -798,7 +837,7 @@ private fun PcAudioCardSection(Text(text = defaultOutput.name,style = MaterialTheme.typography.labelSmall,- color = ink.copy(alpha = 0.68f),+ color = ink.copy(alpha = 0.85f),maxLines = 1,overflow = TextOverflow.Ellipsis,modifier = Modifier.weight(1f),@@ -808,7 +847,7 @@ private fun PcAudioCardSection(Text(text = "${deckState.outputDevices.size}",style = MaterialTheme.typography.labelSmall,- color = ink.copy(alpha = 0.55f),+ color = ink.copy(alpha = 0.85f),)}}@@ -902,7 +941,7 @@ private fun ClipboardHistoryCard(Surface(shape = MaterialTheme.shapes.extraLarge,color = MaterialTheme.colorScheme.surfaceContainer,- modifier = Modifier.fillMaxWidth().clickable(onClick = onOpen),+ modifier = Modifier.fillMaxWidth().clickable(role = Role.Button, onClick = onOpen),) {Column(Modifier.fillMaxWidth().padding(20.dp)) {Text(stringResource(R.string.clipboard_history_title), style = MaterialTheme.typography.titleMedium)@@ -957,12 +996,15 @@ private fun ClipboardHistoryDialog(text = {Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {if (entries.isNotEmpty()) {+ val searchLabel = stringResource(R.string.clipboard_history_search)OutlinedTextField(value = query,onValueChange = { query = it },- placeholder = { Text(stringResource(R.string.clipboard_history_search)) },+ placeholder = { Text(searchLabel) },singleLine = true,- modifier = Modifier.fillMaxWidth(),+ modifier = Modifier+ .fillMaxWidth()+ .semantics { contentDescription = searchLabel },)}when {@@ -1027,14 +1069,10 @@ private fun ClipboardHistoryRow(} else {DateUtils.getRelativeTimeSpanString(entry.timestamp * 1000L, now, DateUtils.MINUTE_IN_MILLIS).toString()}- val header = buildString {- append(direction)- append(" · ")- append(whenText)- if (entry.pinned) {- append(" · ")- append(stringResource(R.string.clipboard_history_pinned))- }+ val header = if (entry.pinned) {+ stringResource(R.string.clipboard_history_meta_pinned, direction, whenText)+ } else {+ stringResource(R.string.clipboard_history_meta, direction, whenText)}Surface(shape = MaterialTheme.shapes.large,@@ -1235,19 +1273,26 @@ private fun TransferRow(onAccept: (String) -> Unit,onCancel: (String) -> Unit,) {+ val context = LocalContext.currentval incoming = transfer.direction == TransferDirection.INCOMINGval status = transfer.status- val title = transferTitle(LocalContext.current.resources, transfer)+ val title = transferTitle(context.resources, transfer)val peerName = pc.ifEmpty { stringResource(R.string.localsend_nearby_device) }val detail = when (status) {is TransferStatus.Requested ->- stringResource(R.string.transfer_requested_from, peerName) +- " · " + Formatter.formatShortFileSize(LocalContext.current, transfer.total.toLong())+ stringResource(+ R.string.transfer_requested_from_size,+ peerName,+ Formatter.formatShortFileSize(context, transfer.total.toLong()),+ )is TransferStatus.Waiting -> stringResource(R.string.transfer_waiting, peerName)is TransferStatus.Running ->- stringResource(if (incoming) R.string.transfer_receiving else R.string.transfer_sending, peerName) +- " · " + Formatter.formatShortFileSize(LocalContext.current, transfer.done.toLong()) +- " / " + Formatter.formatShortFileSize(LocalContext.current, transfer.total.toLong())+ stringResource(+ if (incoming) R.string.transfer_receiving_progress else R.string.transfer_sending_progress,+ peerName,+ Formatter.formatShortFileSize(context, transfer.done.toLong()),+ Formatter.formatShortFileSize(context, transfer.total.toLong()),+ )is TransferStatus.Done ->if (incoming) stringResource(R.string.transfer_received_from, peerName) else stringResource(R.string.transfer_sent_to, peerName)is TransferStatus.Cancelled -> stringResource(R.string.transfer_cancelled)@@ -1264,7 +1309,12 @@ private fun TransferRow(Text(title, style = MaterialTheme.typography.titleSmall, maxLines = 1, overflow = TextOverflow.Ellipsis)if (status is TransferStatus.Running || status is TransferStatus.Waiting) {Spacer(Modifier.height(6.dp))- val progress = if (transfer.total == 0uL) 1f else (transfer.done.toDouble() / transfer.total.toDouble()).toFloat()+ val reducedMotion = LocalReducedMotion.current+ val progress = if (transfer.total == 0uL) {+ if (reducedMotion) 0.5f else 1f+ } else {+ (transfer.done.toDouble() / transfer.total.toDouble()).toFloat()+ }LinearProgressIndicator(progress = { progress }, modifier = Modifier.fillMaxWidth())}Spacer(Modifier.height(4.dp))@@ -1326,7 +1376,7 @@ private fun TimelineCard(Surface(shape = MaterialTheme.shapes.extraLarge,color = MaterialTheme.colorScheme.surfaceContainer,- modifier = Modifier.fillMaxWidth().clickable(onClick = onOpen),+ modifier = Modifier.fillMaxWidth().clickable(role = Role.Button, onClick = onOpen),) {Column(Modifier.fillMaxWidth().padding(20.dp)) {Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth()) {@@ -1345,7 +1395,7 @@ private fun TimelineCard(}Spacer(Modifier.height(4.dp))Text(- "${latest.title} · $direction",+ stringResource(R.string.timeline_latest_summary, latest.title, direction),style = MaterialTheme.typography.bodySmall,color = MaterialTheme.colorScheme.onSurfaceVariant,maxLines = 2,@@ -1410,12 +1460,15 @@ private fun TimelineDialog(},text = {Column(verticalArrangement = Arrangement.spacedBy(10.dp)) {+ val searchLabel = stringResource(R.string.timeline_search)OutlinedTextField(value = search,onValueChange = { search = it },- placeholder = { Text(stringResource(R.string.timeline_search)) },+ placeholder = { Text(searchLabel) },singleLine = true,- modifier = Modifier.fillMaxWidth(),+ modifier = Modifier+ .fillMaxWidth()+ .semantics { contentDescription = searchLabel },)Row(modifier = Modifier.fillMaxWidth().horizontalScroll(rememberScrollState()),diff --git a/android/app/src/main/kotlin/app/nectarlink/android/ui/pairing/PairingScreen.kt b/android/app/src/main/kotlin/app/nectarlink/android/ui/pairing/PairingScreen.ktindex d006d03..239feae 100644--- a/android/app/src/main/kotlin/app/nectarlink/android/ui/pairing/PairingScreen.kt+++ b/android/app/src/main/kotlin/app/nectarlink/android/ui/pairing/PairingScreen.kt@@ -2,11 +2,12 @@package app.nectarlink.android.ui.pairingimport androidx.compose.animation.AnimatedContent+import androidx.compose.animation.EnterTransition+import androidx.compose.animation.ExitTransitionimport androidx.compose.animation.fadeInimport androidx.compose.animation.fadeOutimport androidx.compose.animation.togetherWithimport androidx.compose.foundation.background-import androidx.compose.foundation.clickableimport androidx.compose.foundation.layout.Arrangementimport androidx.compose.foundation.layout.Boximport androidx.compose.foundation.layout.Column@@ -50,6 +51,7 @@ import app.nectarlink.android.Rimport app.nectarlink.android.core.CoreStateimport app.nectarlink.android.core.PairingStateimport app.nectarlink.android.ui.theme.LocalAppFonts+import app.nectarlink.android.ui.theme.LocalReducedMotionimport app.nectarlink.core.DiscoveredDeviceimport app.nectarlink.core.PairingFailureimport kotlinx.coroutines.delay@@ -78,6 +80,7 @@ fun PairingScreen() {var nearby by rememberSaveable { mutableStateOf(false) }val pairing = state.pairing+ val reducedMotion = LocalReducedMotion.currentDisposableEffect(Unit) {actions.visible(true)onDispose { actions.visible(false) }@@ -110,7 +113,13 @@ fun PairingScreen(AnimatedContent(targetState = pairing to nearby,- transitionSpec = { fadeIn() togetherWith fadeOut() },+ transitionSpec = {+ if (reducedMotion) {+ EnterTransition.None togetherWith ExitTransition.None+ } else {+ fadeIn() togetherWith fadeOut()+ }+ },modifier = Modifier.weight(1f),label = "pairing",) { (current, showNearby) ->@@ -176,6 +185,7 @@ private fun Scan(onLink: (String) -> Unit) {@Composableprivate fun NearbyList(devices: List<DiscoveredDevice>, onPair: (String) -> Unit) {+ val reducedMotion = LocalReducedMotion.currentColumn(verticalArrangement = Arrangement.spacedBy(10.dp)) {Text(stringResource(R.string.pair_nearby_hint),@@ -196,7 +206,15 @@ private fun NearbyList(devices: List<DiscoveredDevice>, onPair: (String) -> UnithorizontalArrangement = Arrangement.Center,verticalAlignment = Alignment.CenterVertically,) {- CircularProgressIndicator(Modifier.size(18.dp), strokeWidth = 2.dp)+ if (reducedMotion) {+ CircularProgressIndicator(+ progress = { 0.75f },+ modifier = Modifier.size(18.dp),+ strokeWidth = 2.dp,+ )+ } else {+ CircularProgressIndicator(Modifier.size(18.dp), strokeWidth = 2.dp)+ }Spacer(Modifier.width(12.dp))Text(stringResource(R.string.pair_looking),@@ -210,7 +228,7 @@ private fun NearbyList(devices: List<DiscoveredDevice>, onPair: (String) -> UnitSurface(shape = MaterialTheme.shapes.large,color = MaterialTheme.colorScheme.surfaceContainerHigh,- modifier = Modifier.fillMaxWidth().clickable { onPair(device.id) },+ modifier = Modifier.fillMaxWidth(),) {Row(Modifier.padding(16.dp), verticalAlignment = Alignment.CenterVertically) {Text(@@ -270,7 +288,15 @@ private fun CodeDigits(code: String) {@Composableprivate fun Working(text: String) {Row(verticalAlignment = Alignment.CenterVertically) {- CircularProgressIndicator(Modifier.size(20.dp), strokeWidth = 2.dp)+ if (LocalReducedMotion.current) {+ CircularProgressIndicator(+ progress = { 0.75f },+ modifier = Modifier.size(20.dp),+ strokeWidth = 2.dp,+ )+ } else {+ CircularProgressIndicator(Modifier.size(20.dp), strokeWidth = 2.dp)+ }Spacer(Modifier.width(12.dp))Text(text, style = MaterialTheme.typography.bodyLarge)}diff --git a/android/app/src/main/kotlin/app/nectarlink/android/ui/recorder/RecorderScreen.kt b/android/app/src/main/kotlin/app/nectarlink/android/ui/recorder/RecorderScreen.ktindex 5acac45..f0d791e 100644--- a/android/app/src/main/kotlin/app/nectarlink/android/ui/recorder/RecorderScreen.kt+++ b/android/app/src/main/kotlin/app/nectarlink/android/ui/recorder/RecorderScreen.kt@@ -7,6 +7,8 @@ import android.text.format.Formatterimport androidx.activity.compose.rememberLauncherForActivityResultimport androidx.activity.result.contract.ActivityResultContractsimport androidx.compose.animation.core.animateFloatAsState+import androidx.compose.animation.core.snap+import androidx.compose.animation.core.springimport androidx.compose.foundation.Canvasimport androidx.compose.foundation.layout.Arrangementimport androidx.compose.foundation.layout.Box@@ -58,6 +60,7 @@ import androidx.compose.ui.res.stringResourceimport androidx.compose.ui.semantics.contentDescriptionimport androidx.compose.ui.semantics.semanticsimport app.nectarlink.android.ui.theme.LocalAppFonts+import app.nectarlink.android.ui.theme.LocalReducedMotionimport androidx.compose.ui.text.input.ImeActionimport androidx.compose.ui.text.style.TextOverflowimport androidx.compose.ui.unit.dp@@ -139,8 +142,10 @@ fun RecorderScreen(onDispose { stopPlayback() }}+ val reducedMotion = LocalReducedMotion.currentval animatedLevel by animateFloatAsState(targetValue = if (session.active && !session.paused) session.level else 0f,+ animationSpec = if (reducedMotion) snap() else spring(),label = "micLevel",)@@ -339,6 +344,7 @@ fun RecorderScreen(Spacer(Modifier.height(16.dp))// Marker controls while recording+ val markerHint = stringResource(R.string.recorder_marker_hint)Row(modifier = Modifier.fillMaxWidth(),horizontalArrangement = Arrangement.spacedBy(8.dp),@@ -347,7 +353,7 @@ fun RecorderScreen(OutlinedTextField(value = markerText,onValueChange = { markerText = it },- placeholder = { Text(stringResource(R.string.recorder_marker_hint)) },+ placeholder = { Text(markerHint) },singleLine = true,keyboardOptions = KeyboardOptions(imeAction = ImeAction.Done),keyboardActions = KeyboardActions(@@ -356,7 +362,9 @@ fun RecorderScreen(markerText = ""},),- modifier = Modifier.weight(1f),+ modifier = Modifier+ .weight(1f)+ .semantics { contentDescription = markerHint },)val addMarkerDesc = stringResource(R.string.recorder_add_marker)FilledTonalButton(@@ -384,7 +392,7 @@ fun RecorderScreen(val label = m.label ?: stringResource(R.string.recorder_marker_default, idx + 1)AssistChip(onClick = {},- label = { Text("$ts · $label") },+ label = { Text(stringResource(R.string.recorder_marker_chip, ts, label)) },)}}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.ktindex eb9c671..720e765 100644--- 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@@ -76,6 +76,12 @@ import androidx.compose.ui.platform.LocalSoftwareKeyboardControllerimport androidx.compose.ui.platform.LocalViewimport androidx.compose.ui.res.painterResourceimport androidx.compose.ui.res.stringResource+import androidx.compose.ui.semantics.Role+import androidx.compose.ui.semantics.contentDescription+import androidx.compose.ui.semantics.onClick+import androidx.compose.ui.semantics.role+import androidx.compose.ui.semantics.selected+import androidx.compose.ui.semantics.semanticsimport androidx.compose.ui.text.input.ImeActionimport androidx.compose.ui.text.style.TextAlignimport androidx.compose.ui.text.style.TextOverflow@@ -85,6 +91,7 @@ import app.nectarlink.android.Rimport app.nectarlink.android.core.Coreimport app.nectarlink.android.core.Deviceimport app.nectarlink.android.core.WakeState+import app.nectarlink.android.ui.theme.LocalReducedMotionimport kotlinx.coroutines.delayimport kotlin.math.absimport kotlin.math.hypot@@ -278,7 +285,11 @@ private fun OfflineWakeBanner(device: Device, onWake: () -> Unit) {style = MaterialTheme.typography.titleSmall,)Spacer(Modifier.height(8.dp))- LinearProgressIndicator(modifier = Modifier.fillMaxWidth())+ if (LocalReducedMotion.current) {+ LinearProgressIndicator(progress = { 0.5f }, modifier = Modifier.fillMaxWidth())+ } else {+ LinearProgressIndicator(modifier = Modifier.fillMaxWidth())+ }}device.wakeState == WakeState.TimedOut -> {Text(@@ -368,6 +379,7 @@ private fun TouchpadView(// Big touchpad surfaceval primaryColor = MaterialTheme.colorScheme.primaryval outlineColor = MaterialTheme.colorScheme.outlineVariant+ val touchpadDesc = stringResource(R.string.remote_mode_touchpad)Surface(shape = MaterialTheme.shapes.extraLarge,color = MaterialTheme.colorScheme.surfaceContainerHigh,@@ -378,6 +390,7 @@ private fun TouchpadView(modifier = Modifier.weight(1f).fillMaxWidth()+ .semantics { contentDescription = touchpadDesc }.pointerInput(pcId, sensitivity) {val tapSlop = viewConfiguration.touchSlopval tapTimeoutMs = 240L@@ -584,6 +597,7 @@ private fun TouchpadView(// Soft keyboard input row when toggled openif (showKeyboard) {+ val typePlaceholder = stringResource(R.string.remote_type_placeholder, pcName)OutlinedTextField(value = textBuffer,onValueChange = { next ->@@ -601,7 +615,7 @@ private fun TouchpadView(}textBuffer = " "},- placeholder = { Text(stringResource(R.string.remote_type_placeholder, pcName)) },+ placeholder = { Text(typePlaceholder) },singleLine = true,keyboardOptions = KeyboardOptions(imeAction = ImeAction.Send),keyboardActions = KeyboardActions(@@ -612,7 +626,8 @@ private fun TouchpadView(),modifier = Modifier.fillMaxWidth()- .focusRequester(focusRequester),+ .focusRequester(focusRequester)+ .semantics { contentDescription = typePlaceholder },)}}@@ -692,6 +707,7 @@ private fun AirMouseView(val primaryColor = MaterialTheme.colorScheme.primaryval outlineColor = MaterialTheme.colorScheme.outlineVariant+ val airDesc = stringResource(R.string.remote_mode_air)Surface(shape = MaterialTheme.shapes.extraLarge,color = if (padHeld) MaterialTheme.colorScheme.primaryContainer else MaterialTheme.colorScheme.surfaceContainerHigh,@@ -703,6 +719,7 @@ private fun AirMouseView(modifier = Modifier.weight(1f).fillMaxWidth()+ .semantics { contentDescription = airDesc }.pointerInput(pcId, hasGyro) {val tapSlop = viewConfiguration.touchSlopval tapTimeoutMs = 240L@@ -1107,6 +1124,9 @@ private fun VoiceTypingBar(} else {MaterialTheme.colorScheme.onSecondaryContainer}+ val dictateLabel = stringResource(+ if (isListening) R.string.remote_dictate_stop else R.string.remote_dictate,+ )Surface(shape = CircleShape,@@ -1114,6 +1134,25 @@ private fun VoiceTypingBar(contentColor = buttonFg,modifier = Modifier.height(40.dp)+ .semantics(mergeDescendants = true) {+ role = Role.Button+ contentDescription = dictateLabel+ onClick(label = dictateLabel) {+ if (currentIsListening) {+ stopRecognition()+ } else if (+ ContextCompat.checkSelfPermission(+ context,+ Manifest.permission.RECORD_AUDIO,+ ) == PackageManager.PERMISSION_GRANTED+ ) {+ startRecognition()+ } else {+ permissionLauncher.launch(Manifest.permission.RECORD_AUDIO)+ }+ true+ }+ }.pointerInput(pcId) {val holdThresholdMs = 350LawaitEachGesture {@@ -1159,9 +1198,7 @@ private fun VoiceTypingBar(modifier = Modifier.padding(horizontal = 16.dp),) {Text(- text = stringResource(- if (isListening) R.string.remote_dictate_stop else R.string.remote_dictate,- ),+ text = dictateLabel,style = MaterialTheme.typography.labelLarge,maxLines = 1,)@@ -1183,7 +1220,12 @@ private fun SpecialKeysBar(verticalArrangement = Arrangement.spacedBy(6.dp),) {// Modifier keys row: 4 equal columns that fit at every font scale without overflowing- val mods = listOf("ctrl" to "Ctrl", "alt" to "Alt", "shift" to "Shift", "win" to "Win")+ val mods = listOf(+ "ctrl" to stringResource(R.string.remote_key_ctrl),+ "alt" to stringResource(R.string.remote_key_alt),+ "shift" to stringResource(R.string.remote_key_shift),+ "win" to stringResource(R.string.remote_key_win),+ )Row(modifier = Modifier.fillMaxWidth(),horizontalArrangement = Arrangement.spacedBy(6.dp),@@ -1214,6 +1256,11 @@ private fun SpecialKeysBar(modifier = Modifier.weight(1f).height(36.dp)+ .semantics(mergeDescendants = true) {+ role = Role.Switch+ this.selected = selected+ contentDescription = label+ }.clickable { onToggleMod(id) },) {Box(contentAlignment = Alignment.Center, modifier = Modifier.padding(horizontal = 4.dp)) {@@ -1230,19 +1277,19 @@ private fun SpecialKeysBar(// Navigation & special keys row: 6 equal columns across the full widthval keys = listOf(- "escape" to "Esc",- "tab" to "Tab",- "left" to "←",- "up" to "↑",- "down" to "↓",- "right" to "→",+ Triple("escape", stringResource(R.string.remote_key_esc), stringResource(R.string.remote_key_esc_desc)),+ Triple("tab", stringResource(R.string.remote_key_tab), stringResource(R.string.remote_key_tab)),+ Triple("left", "←", stringResource(R.string.remote_key_left_desc)),+ Triple("up", "↑", stringResource(R.string.remote_key_up_desc)),+ Triple("down", "↓", stringResource(R.string.remote_key_down_desc)),+ Triple("right", "→", stringResource(R.string.remote_key_right_desc)),)Row(modifier = Modifier.fillMaxWidth(),horizontalArrangement = Arrangement.spacedBy(6.dp),verticalAlignment = Alignment.CenterVertically,) {- for ((key, label) in keys) {+ for ((key, label, a11yLabel) in keys) {Surface(shape = MaterialTheme.shapes.small,color = MaterialTheme.colorScheme.surface,@@ -1251,7 +1298,11 @@ private fun SpecialKeysBar(modifier = Modifier.weight(1f).height(36.dp)- .clickable { onKey(key, null) },+ .semantics(mergeDescendants = true) {+ role = Role.Button+ contentDescription = a11yLabel+ }+ .clickable(role = Role.Button) { onKey(key, null) },) {Box(contentAlignment = Alignment.Center, modifier = Modifier.padding(horizontal = 2.dp)) {Text(@@ -1266,18 +1317,18 @@ private fun SpecialKeysBar(if (showExtraKeys) {val extra = listOf(- "home" to "Home",- "end" to "End",- "delete" to "Del",- "copy" to "Copy",- "paste" to "Paste",+ Triple("home", stringResource(R.string.remote_key_home), stringResource(R.string.remote_key_home)),+ Triple("end", stringResource(R.string.remote_key_end), stringResource(R.string.remote_key_end)),+ Triple("delete", stringResource(R.string.remote_key_del), stringResource(R.string.remote_key_del_desc)),+ Triple("copy", stringResource(R.string.remote_key_copy), stringResource(R.string.remote_key_copy)),+ Triple("paste", stringResource(R.string.remote_key_paste), stringResource(R.string.remote_key_paste)),)Row(modifier = Modifier.fillMaxWidth(),horizontalArrangement = Arrangement.spacedBy(6.dp),verticalAlignment = Alignment.CenterVertically,) {- for ((key, label) in extra) {+ for ((key, label, a11yLabel) in extra) {val isShortcut = key == "copy" || key == "paste"Surface(shape = MaterialTheme.shapes.small,@@ -1287,7 +1338,11 @@ private fun SpecialKeysBar(modifier = Modifier.weight(1f).height(36.dp)- .clickable { onKey(key, if (isShortcut) emptyList() else null) },+ .semantics(mergeDescendants = true) {+ role = Role.Button+ contentDescription = a11yLabel+ }+ .clickable(role = Role.Button) { onKey(key, if (isShortcut) emptyList() else null) },) {Box(contentAlignment = Alignment.Center, modifier = Modifier.padding(horizontal = 2.dp)) {Text(@@ -1450,6 +1505,10 @@ private fun PresentationView(// Hold for laser pointer pad (supports both gyroscope tilt and finger drag)val primaryColor = MaterialTheme.colorScheme.primary+ val laserDesc = stringResource(+ if (laserHeld) R.string.remote_laser_active else R.string.remote_laser_hold,+ pcName,+ )Surface(shape = MaterialTheme.shapes.extraLarge,color = if (laserHeld) MaterialTheme.colorScheme.primaryContainer else MaterialTheme.colorScheme.surfaceContainerHigh,@@ -1461,6 +1520,7 @@ private fun PresentationView(modifier = Modifier.weight(1f).fillMaxWidth()+ .semantics { contentDescription = laserDesc }.pointerInput(pcId) {awaitEachGesture {val down = awaitFirstDown(requireUnconsumed = false)diff --git a/android/app/src/main/kotlin/app/nectarlink/android/ui/settings/SettingsScreen.kt b/android/app/src/main/kotlin/app/nectarlink/android/ui/settings/SettingsScreen.ktindex bbf7e81..0a6fb71 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@@ -44,7 +44,10 @@ import androidx.compose.ui.Modifierimport androidx.compose.ui.platform.LocalContextimport androidx.compose.ui.res.pluralStringResourceimport androidx.compose.ui.res.stringResource+import androidx.compose.ui.semantics.Roleimport androidx.compose.ui.semantics.contentDescription+import androidx.compose.ui.semantics.role+import androidx.compose.ui.semantics.selectedimport androidx.compose.ui.semantics.semanticsimport androidx.compose.ui.unit.dpimport androidx.activity.compose.rememberLauncherForActivityResult@@ -113,9 +116,10 @@ fun SettingsScreen(}Section(stringResource(R.string.settings_clipboard_title)) {+ val suggestionsTitle = stringResource(R.string.settings_clipboard_suggestions)Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth()) {Column(Modifier.weight(1f).padding(end = 12.dp)) {- Text(stringResource(R.string.settings_clipboard_suggestions), style = MaterialTheme.typography.titleSmall)+ Text(suggestionsTitle, style = MaterialTheme.typography.titleSmall)Text(stringResource(R.string.settings_clipboard_suggestions_hint),style = MaterialTheme.typography.bodySmall,@@ -125,14 +129,16 @@ fun SettingsScreen(Switch(checked = suggestClipboardActions,onCheckedChange = onSetSuggestClipboardActions,+ modifier = Modifier.semantics { contentDescription = suggestionsTitle },)}}Section(stringResource(R.string.settings_localsend_title)) {+ val localsendTitle = stringResource(R.string.settings_localsend_title)Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth()) {Column(Modifier.weight(1f).padding(end = 12.dp)) {- Text(stringResource(R.string.settings_localsend_title), style = MaterialTheme.typography.titleSmall)+ Text(localsendTitle, style = MaterialTheme.typography.titleSmall)Text(stringResource(R.string.settings_localsend_subtitle),style = MaterialTheme.typography.bodySmall,@@ -142,6 +148,7 @@ fun SettingsScreen(Switch(checked = state.localsendEnabled,onCheckedChange = onToggleLocalSend,+ modifier = Modifier.semantics { contentDescription = localsendTitle },)}}@@ -159,9 +166,10 @@ fun SettingsScreen(SettingRowDivider()// 2. Clipboard history+ val clipboardHistoryTitle = stringResource(R.string.data_clipboard_title)Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth()) {Column(Modifier.weight(1f).padding(end = 12.dp)) {- Text(stringResource(R.string.data_clipboard_title), style = MaterialTheme.typography.titleSmall)+ Text(clipboardHistoryTitle, style = MaterialTheme.typography.titleSmall)Text(stringResource(R.string.data_clipboard_subtitle),style = MaterialTheme.typography.bodySmall,@@ -183,6 +191,7 @@ fun SettingsScreen(Switch(checked = state.clipboardHistoryEnabled,onCheckedChange = onSetClipboardHistoryEnabled,+ modifier = Modifier.semantics { contentDescription = clipboardHistoryTitle },)}if (state.clipboardHistory.isNotEmpty()) {@@ -335,9 +344,10 @@ fun SettingsScreen(}Section(stringResource(R.string.settings_remote)) {+ val sensitivityTitle = stringResource(R.string.settings_touchpad_sensitivity)Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth()) {Text(- stringResource(R.string.settings_touchpad_sensitivity),+ sensitivityTitle,style = MaterialTheme.typography.titleSmall,modifier = Modifier.weight(1f),)@@ -351,6 +361,7 @@ fun SettingsScreen(value = touchpadSensitivity,onValueChange = onTouchpadSensitivity,valueRange = 0.5f..2.5f,+ modifier = Modifier.semantics { contentDescription = sensitivityTitle },)}@@ -372,9 +383,10 @@ fun SettingsScreen(if (appearance.theme == "bloom") {SettingRowDivider()if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {+ val dynamicColorTitle = stringResource(R.string.settings_dynamic_color)Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth()) {Column(Modifier.weight(1f).padding(end = 12.dp)) {- Text(stringResource(R.string.settings_dynamic_color), style = MaterialTheme.typography.titleSmall)+ Text(dynamicColorTitle, style = MaterialTheme.typography.titleSmall)Text(stringResource(R.string.settings_dynamic_color_hint),style = MaterialTheme.typography.bodySmall,@@ -384,27 +396,41 @@ fun SettingsScreen(Switch(checked = appearance.dynamicColor,onCheckedChange = { on -> onAppearance { it.copy(dynamicColor = on) } },+ modifier = Modifier.semantics { contentDescription = dynamicColorTitle },)}}if (!appearance.dynamicColor || Build.VERSION.SDK_INT < Build.VERSION_CODES.S) {Row(horizontalArrangement = Arrangement.spacedBy(12.dp)) {Tokens.bloomSeeds.forEach { (name, seed) ->- val selected = appearance.seed == name+ val isSelected = appearance.seed == name+ val seedLabel = stringResource(+ when (name) {+ "honey" -> R.string.settings_seed_honey+ "lavender" -> R.string.settings_seed_lavender+ "ocean" -> R.string.settings_seed_ocean+ "sage" -> R.string.settings_seed_sage+ else -> R.string.settings_seed_honey+ },+ )Surface(shape = CircleShape,color = seed.color,modifier = Modifier.size(38.dp).then(- if (selected) {+ if (isSelected) {Modifier.border(2.5.dp, MaterialTheme.colorScheme.onSurface, CircleShape)} else {Modifier.border(1.dp, MaterialTheme.colorScheme.outlineVariant, CircleShape)},).clickable { onAppearance { it.copy(seed = name) } }- .semantics { contentDescription = name },+ .semantics {+ role = Role.RadioButton+ selected = isSelected+ contentDescription = seedLabel+ },) {}}}@@ -440,9 +466,10 @@ fun SettingsScreen(}OutlinedButton(onClick = { confirmUnpair = device }) { Text(stringResource(R.string.action_unpair)) }}+ val storageToggleTitle = stringResource(R.string.storage_pc_toggle)Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth()) {Column(Modifier.weight(1f).padding(end = 12.dp)) {- Text(stringResource(R.string.storage_pc_toggle), style = MaterialTheme.typography.bodyMedium)+ Text(storageToggleTitle, style = MaterialTheme.typography.bodyMedium)Text(stringResource(R.string.storage_pc_toggle_hint),style = MaterialTheme.typography.bodySmall,@@ -457,6 +484,7 @@ fun SettingsScreen(context.startActivity(PhoneStorage.allFilesAccessIntent(context))}},+ modifier = Modifier.semantics { contentDescription = storageToggleTitle },)}}diff --git a/android/app/src/main/kotlin/app/nectarlink/android/ui/theme/Theme.kt b/android/app/src/main/kotlin/app/nectarlink/android/ui/theme/Theme.ktindex 978de20..ffb330e 100644--- a/android/app/src/main/kotlin/app/nectarlink/android/ui/theme/Theme.kt+++ b/android/app/src/main/kotlin/app/nectarlink/android/ui/theme/Theme.kt@@ -1,6 +1,7 @@// SPDX-License-Identifier: GPL-3.0-or-laterpackage app.nectarlink.android.ui.theme+import android.animation.ValueAnimatorimport android.app.Activityimport android.os.Buildimport androidx.compose.foundation.isSystemInDarkTheme@@ -14,12 +15,39 @@ import androidx.compose.material3.dynamicLightColorSchemeimport androidx.compose.material3.lightColorSchemeimport androidx.compose.runtime.Composableimport androidx.compose.runtime.CompositionLocalProvider+import androidx.compose.runtime.DisposableEffectimport androidx.compose.runtime.SideEffect+import androidx.compose.runtime.compositionLocalOf+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOfimport androidx.compose.runtime.remember+import androidx.compose.runtime.setValueimport androidx.compose.ui.platform.LocalContextimport androidx.compose.ui.platform.LocalViewimport androidx.compose.ui.unit.dpimport androidx.core.view.WindowCompat+import androidx.lifecycle.Lifecycle+import androidx.lifecycle.LifecycleEventObserver+import androidx.lifecycle.compose.LocalLifecycleOwner++val LocalReducedMotion = compositionLocalOf { false }++/** True when Android's "Remove animations" (animator duration scale 0) is enabled. */+@Composable+fun rememberReducedMotion(): Boolean {+ var reduced by remember { mutableStateOf(!ValueAnimator.areAnimatorsEnabled()) }+ val lifecycleOwner = LocalLifecycleOwner.current+ DisposableEffect(lifecycleOwner) {+ val observer = LifecycleEventObserver { _, event ->+ if (event == Lifecycle.Event.ON_RESUME) {+ reduced = !ValueAnimator.areAnimatorsEnabled()+ }+ }+ lifecycleOwner.lifecycle.addObserver(observer)+ onDispose { lifecycleOwner.lifecycle.removeObserver(observer) }+ }+ return reduced+}/** The user's look choices (see Preferences). */data class Appearance(@@ -112,7 +140,11 @@ fun NectarlinkTheme(appearance: Appearance = Appearance(), content: @Composable}val assets = LocalContext.current.assetsval fonts = remember(assets) { AppFonts(assets) }- CompositionLocalProvider(LocalAppFonts provides fonts) {+ val reducedMotion = rememberReducedMotion()+ CompositionLocalProvider(+ LocalAppFonts provides fonts,+ LocalReducedMotion provides reducedMotion,+ ) {MaterialTheme(colorScheme = scheme,shapes = shapes(graphite),diff --git a/android/app/src/main/kotlin/app/nectarlink/android/ui/theme/Tokens.kt b/android/app/src/main/kotlin/app/nectarlink/android/ui/theme/Tokens.ktindex d037989..ae59131 100644--- a/android/app/src/main/kotlin/app/nectarlink/android/ui/theme/Tokens.kt+++ b/android/app/src/main/kotlin/app/nectarlink/android/ui/theme/Tokens.kt@@ -216,7 +216,7 @@ object Tokens {outlineVariant = Color(0xFF26272A),)- val warningLight = Color(0xFF9A6700)+ val warningLight = Color(0xFF7D5200)val warningDark = Color(0xFFF2C14E)val errorLight = Color(0xFFBA1A1A)val errorDark = Color(0xFFFFB4AB)diff --git a/android/app/src/main/kotlin/app/nectarlink/android/ui/webcam/WebcamScreen.kt b/android/app/src/main/kotlin/app/nectarlink/android/ui/webcam/WebcamScreen.ktindex d3bfdaf..69da5c4 100644--- a/android/app/src/main/kotlin/app/nectarlink/android/ui/webcam/WebcamScreen.kt+++ b/android/app/src/main/kotlin/app/nectarlink/android/ui/webcam/WebcamScreen.kt@@ -51,6 +51,8 @@ import androidx.compose.ui.platform.LocalContextimport androidx.compose.ui.platform.LocalViewimport androidx.compose.ui.res.painterResourceimport androidx.compose.ui.res.stringResource+import androidx.compose.ui.semantics.contentDescription+import androidx.compose.ui.semantics.semanticsimport androidx.compose.ui.unit.dpimport androidx.compose.ui.viewinterop.AndroidViewimport androidx.lifecycle.compose.collectAsStateWithLifecycle@@ -261,7 +263,7 @@ fun WebcamScreen()Spacer(Modifier.height(6.dp))Text(- text = "${session.width} × ${session.height} · ${session.fps} fps",+ text = stringResource(R.string.webcam_stream_spec, session.width, session.height, session.fps),style = MaterialTheme.typography.bodySmall,color = Color.White.copy(alpha = 0.72f),)@@ -282,10 +284,15 @@ fun WebcamScreen()Text(text = if (isStreamingHere && !session.connecting) {- stringResource(R.string.webcam_status_streaming, session.width, session.height, device.name) +- " · $camLabel"+ stringResource(+ R.string.webcam_status_streaming_camera,+ session.width,+ session.height,+ device.name,+ camLabel,+ )} else {- "${session.width} × ${session.height} · $camLabel"+ stringResource(R.string.webcam_stream_camera_spec, session.width, session.height, camLabel)},style = MaterialTheme.typography.labelMedium,modifier = Modifier.padding(horizontal = 10.dp, vertical = 6.dp),@@ -350,7 +357,7 @@ fun WebcamScreen(val currentLabel = stringResource(if (session.camera == "front") R.string.webcam_camera_front else R.string.webcam_camera_back,)- Text(stringResource(R.string.webcam_switch_camera) + " ($currentLabel)")+ Text(stringResource(R.string.webcam_switch_camera_current, currentLabel))}if (session.hasFlash) {@@ -376,10 +383,13 @@ fun WebcamScreen(style = MaterialTheme.typography.labelLarge,)Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {+ val res720p = stringResource(R.string.webcam_res_720p)+ val res1080p = stringResource(R.string.webcam_res_1080p)+ val res4k = stringResource(R.string.webcam_res_4k)val resolutions = buildList {- add(720 to "720p")- add(1080 to "1080p")- if (session.supports4k) add(2160 to "4K")+ add(720 to res720p)+ add(1080 to res1080p)+ if (session.supports4k) add(2160 to res4k)}for ((h, label) in resolutions) {FilterChip(@@ -393,29 +403,30 @@ fun WebcamScreen(// Zoom controls: presets + smooth high-contrast sliderColumn(verticalArrangement = Arrangement.spacedBy(8.dp)) {+ val zoomLabel = stringResource(+ R.string.webcam_zoom_label,+ String.format(Locale.US, "%.1f", session.zoomRatio).toFloat(),+ )Text(- stringResource(- R.string.webcam_zoom_label,- String.format(Locale.US, "%.1f", session.zoomRatio).toFloat(),- ),+ zoomLabel,style = MaterialTheme.typography.labelLarge,)Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {FilterChip(selected = kotlin.math.abs(session.zoomRatio - 1f) < 0.08f,onClick = { WebcamService.setZoomRatio(1f) },- label = { Text("1×") },+ label = { Text(stringResource(R.string.webcam_zoom_preset, 1)) },)FilterChip(selected = kotlin.math.abs(session.zoomRatio - 2f) < 0.08f,onClick = { WebcamService.setZoomRatio(2f.coerceAtMost(session.maxZoomRatio)) },- label = { Text("2×") },+ label = { Text(stringResource(R.string.webcam_zoom_preset, 2)) },)if (session.maxZoomRatio >= 4f) {FilterChip(selected = kotlin.math.abs(session.zoomRatio - 4f) < 0.08f,onClick = { WebcamService.setZoomRatio(4f.coerceAtMost(session.maxZoomRatio)) },- label = { Text("4×") },+ label = { Text(stringResource(R.string.webcam_zoom_preset, 4)) },)}}@@ -433,6 +444,7 @@ fun WebcamScreen(disabledActiveTrackColor = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.45f),disabledInactiveTrackColor = MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.7f),),+ modifier = Modifier.semantics { contentDescription = zoomLabel },)}}diff --git a/android/app/src/main/kotlin/app/nectarlink/android/update/UpdateCard.kt b/android/app/src/main/kotlin/app/nectarlink/android/update/UpdateCard.ktindex 7e96159..d34db21 100644--- a/android/app/src/main/kotlin/app/nectarlink/android/update/UpdateCard.kt+++ b/android/app/src/main/kotlin/app/nectarlink/android/update/UpdateCard.kt@@ -27,6 +27,7 @@ import androidx.compose.ui.unit.dpimport androidx.core.net.toUriimport androidx.lifecycle.compose.collectAsStateWithLifecycleimport app.nectarlink.android.R+import app.nectarlink.android.ui.theme.LocalReducedMotionimport kotlinx.coroutines.launch/** "Nectarlink 0.2.0 is available", while there's an update to talk about. */@@ -66,7 +67,11 @@ fun UpdateCard(updater: AppUpdater, modifier: Modifier = Modifier) {style = MaterialTheme.typography.bodyMedium,)if (state is AppUpdater.State.Downloading || state is AppUpdater.State.Installing) {- LinearProgressIndicator(Modifier.fillMaxWidth())+ if (LocalReducedMotion.current) {+ LinearProgressIndicator(progress = { 0.5f }, modifier = Modifier.fillMaxWidth())+ } else {+ LinearProgressIndicator(Modifier.fillMaxWidth())+ }}Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {if (failure == AppUpdater.Reason.NotAllowed && !updater.canInstall()) {diff --git a/android/app/src/main/kotlin/app/nectarlink/android/widget/PcWidgetProvider.kt b/android/app/src/main/kotlin/app/nectarlink/android/widget/PcWidgetProvider.ktnew file mode 100644index 0000000..bc463ee--- /dev/null+++ b/android/app/src/main/kotlin/app/nectarlink/android/widget/PcWidgetProvider.kt@@ -0,0 +1,220 @@+// SPDX-License-Identifier: GPL-3.0-or-later+package app.nectarlink.android.widget++import android.app.PendingIntent+import android.appwidget.AppWidgetManager+import android.appwidget.AppWidgetProvider+import android.content.ComponentName+import android.content.Context+import android.content.Intent+import android.graphics.Color+import android.view.View+import android.widget.RemoteViews+import android.widget.Toast+import app.nectarlink.android.NectarlinkApplication+import app.nectarlink.android.R+import app.nectarlink.android.clipboard.SendActivity+import app.nectarlink.android.core.CoreState+import app.nectarlink.android.core.Device+import app.nectarlink.android.core.WakeState+import app.nectarlink.android.ui.MainActivity++/**+ * Battery-free home-screen widget showing the primary paired PC's connection+ * status, Wake-on-LAN button when offline, and one-tap quick actions (Send+ * clipboard, Ring PC, Lock PC). Has `updatePeriodMillis="0"` so it never wakes+ * the device on a timer; [Core] refreshes it whenever state changes.+ */+class PcWidgetProvider : AppWidgetProvider() {++ override fun onUpdate(+ context: Context,+ appWidgetManager: AppWidgetManager,+ appWidgetIds: IntArray,+ ) {+ val core = (context.applicationContext as? NectarlinkApplication)?.core+ core?.start()+ updateWidgets(context, appWidgetManager, appWidgetIds, core?.state?.value)+ }++ override fun onReceive(context: Context, intent: Intent) {+ super.onReceive(context, intent)+ val action = intent.action ?: return+ if (action != ACTION_RING_PC && action != ACTION_LOCK_PC && action != ACTION_WAKE_PC) return++ val app = context.applicationContext as? NectarlinkApplication ?: return+ app.core.start()+ val state = app.core.state.value+ val pcId = intent.getStringExtra(EXTRA_PC_ID)?.takeIf { it.isNotBlank() }+ ?: primaryPc(state)?.id+ ?: return+ val pcName = state.nameOf(pcId)?.takeIf { it.isNotBlank() }+ ?: context.getString(R.string.your_pc)++ when (action) {+ ACTION_RING_PC -> {+ app.core.ring(pcId, true)+ Toast.makeText(+ context,+ context.getString(R.string.widget_pc_ringing_toast, pcName),+ Toast.LENGTH_SHORT,+ ).show()+ }+ ACTION_LOCK_PC -> {+ app.core.pcPower(pcId, sleep = false)+ Toast.makeText(+ context,+ context.getString(R.string.pc_locked, pcName),+ Toast.LENGTH_SHORT,+ ).show()+ }+ ACTION_WAKE_PC -> {+ app.core.wake(pcId)+ Toast.makeText(+ context,+ context.getString(R.string.widget_pc_waking_toast, pcName),+ Toast.LENGTH_SHORT,+ ).show()+ }+ }+ }++ companion object {+ const val ACTION_RING_PC = "app.nectarlink.widget.ACTION_RING_PC"+ const val ACTION_LOCK_PC = "app.nectarlink.widget.ACTION_LOCK_PC"+ const val ACTION_WAKE_PC = "app.nectarlink.widget.ACTION_WAKE_PC"+ const val EXTRA_PC_ID = "app.nectarlink.widget.EXTRA_PC_ID"++ private const val REQ_OPEN_APP = 100+ private const val REQ_SEND_CLIP = 101+ private const val REQ_RING = 102+ private const val REQ_LOCK = 103+ private const val REQ_WAKE = 104++ private val COLOR_ONLINE_TEXT = Color.parseColor("#9EF0B4")+ private val COLOR_OFFLINE_TEXT = Color.parseColor("#D5CFC2")++ private fun primaryPc(state: CoreState?): Device? =+ state?.devices?.firstOrNull { it.online } ?: state?.devices?.firstOrNull()++ fun refreshAll(context: Context, state: CoreState? = null) {+ val manager = AppWidgetManager.getInstance(context) ?: return+ val ids = runCatching {+ manager.getAppWidgetIds(ComponentName(context, PcWidgetProvider::class.java))+ }.getOrNull() ?: return+ if (ids.isEmpty()) return++ val effectiveState = state+ ?: (context.applicationContext as? NectarlinkApplication)?.core?.state?.value+ updateWidgets(context, manager, ids, effectiveState)+ }++ private fun updateWidgets(+ context: Context,+ appWidgetManager: AppWidgetManager,+ appWidgetIds: IntArray,+ state: CoreState?,+ ) {+ if (appWidgetIds.isEmpty()) return+ val pc = primaryPc(state)+ val views = RemoteViews(context.packageName, R.layout.widget_pc)++ val launchIntent = Intent(context, MainActivity::class.java).apply {+ flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP+ }+ val launchPending = PendingIntent.getActivity(+ context,+ REQ_OPEN_APP,+ launchIntent,+ PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,+ )+ views.setOnClickPendingIntent(R.id.widget_root, launchPending)++ if (pc == null) {+ views.setTextViewText(R.id.widget_pc_name, context.getString(R.string.widget_pc_no_pc))+ views.setTextViewText(R.id.widget_pc_status, context.getString(R.string.widget_pc_offline))+ views.setInt(R.id.widget_pc_status, "setBackgroundResource", R.drawable.bg_widget_pill_offline)+ views.setTextColor(R.id.widget_pc_status, COLOR_OFFLINE_TEXT)+ views.setViewVisibility(R.id.widget_pc_subtitle, View.VISIBLE)+ views.setTextViewText(R.id.widget_pc_subtitle, context.getString(R.string.widget_pc_tap_to_pair))+ views.setViewVisibility(R.id.widget_btn_wake, View.GONE)+ } else {+ val name = pc.name.ifBlank { context.getString(R.string.your_pc) }+ views.setTextViewText(R.id.widget_pc_name, name)+ views.setViewVisibility(R.id.widget_pc_subtitle, View.GONE)++ when {+ pc.online -> {+ views.setTextViewText(R.id.widget_pc_status, context.getString(R.string.widget_pc_connected))+ views.setInt(R.id.widget_pc_status, "setBackgroundResource", R.drawable.bg_widget_pill_online)+ views.setTextColor(R.id.widget_pc_status, COLOR_ONLINE_TEXT)+ }+ pc.wakeState == WakeState.Waking -> {+ views.setTextViewText(R.id.widget_pc_status, context.getString(R.string.widget_pc_waking))+ views.setInt(R.id.widget_pc_status, "setBackgroundResource", R.drawable.bg_widget_pill_offline)+ views.setTextColor(R.id.widget_pc_status, COLOR_OFFLINE_TEXT)+ }+ else -> {+ views.setTextViewText(R.id.widget_pc_status, context.getString(R.string.widget_pc_offline))+ views.setInt(R.id.widget_pc_status, "setBackgroundResource", R.drawable.bg_widget_pill_offline)+ views.setTextColor(R.id.widget_pc_status, COLOR_OFFLINE_TEXT)+ }+ }++ if (!pc.online && pc.canWake) {+ views.setViewVisibility(R.id.widget_btn_wake, View.VISIBLE)+ views.setOnClickPendingIntent(+ R.id.widget_btn_wake,+ actionBroadcast(context, REQ_WAKE, ACTION_WAKE_PC, pc.id),+ )+ } else {+ views.setViewVisibility(R.id.widget_btn_wake, View.GONE)+ }+ }++ val clipIntent = SendActivity.sendClipboardIntent(context, pc?.id)+ val clipPending = PendingIntent.getActivity(+ context,+ REQ_SEND_CLIP,+ clipIntent,+ PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,+ )+ views.setOnClickPendingIntent(R.id.widget_btn_send_clip, clipPending)++ views.setOnClickPendingIntent(+ R.id.widget_btn_ring,+ actionBroadcast(context, REQ_RING, ACTION_RING_PC, pc?.id),+ )+ views.setOnClickPendingIntent(+ R.id.widget_btn_lock,+ actionBroadcast(context, REQ_LOCK, ACTION_LOCK_PC, pc?.id),+ )++ for (id in appWidgetIds) {+ appWidgetManager.updateAppWidget(id, views)+ }+ }++ private fun actionBroadcast(+ context: Context,+ requestCode: Int,+ action: String,+ pcId: String?,+ ): PendingIntent {+ val intent = Intent(context, PcWidgetProvider::class.java).apply {+ this.action = action+ if (!pcId.isNullOrEmpty()) {+ putExtra(EXTRA_PC_ID, pcId)+ } else {+ removeExtra(EXTRA_PC_ID)+ }+ }+ return PendingIntent.getBroadcast(+ context,+ requestCode,+ intent,+ PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,+ )+ }+ }+}diff --git a/android/app/src/main/res/drawable/bg_widget_button.xml b/android/app/src/main/res/drawable/bg_widget_button.xmlnew file mode 100644index 0000000..c153556--- /dev/null+++ b/android/app/src/main/res/drawable/bg_widget_button.xml@@ -0,0 +1,10 @@+<?xml version="1.0" encoding="utf-8"?>+<!-- SPDX-License-Identifier: GPL-3.0-or-later -->+<shape xmlns:android="http://schemas.android.com/apk/res/android"+ android:shape="rectangle">+ <corners android:radius="12dp" />+ <solid android:color="#2B2923" />+ <stroke+ android:width="1dp"+ android:color="#3F3C34" />+</shape>diff --git a/android/app/src/main/res/drawable/bg_widget_card.xml b/android/app/src/main/res/drawable/bg_widget_card.xmlnew file mode 100644index 0000000..2ee6be6--- /dev/null+++ b/android/app/src/main/res/drawable/bg_widget_card.xml@@ -0,0 +1,10 @@+<?xml version="1.0" encoding="utf-8"?>+<!-- SPDX-License-Identifier: GPL-3.0-or-later -->+<shape xmlns:android="http://schemas.android.com/apk/res/android"+ android:shape="rectangle">+ <corners android:radius="18dp" />+ <solid android:color="#1C1B18" />+ <stroke+ android:width="1dp"+ android:color="#36342E" />+</shape>diff --git a/android/app/src/main/res/drawable/bg_widget_pill_offline.xml b/android/app/src/main/res/drawable/bg_widget_pill_offline.xmlnew file mode 100644index 0000000..ca03d6a--- /dev/null+++ b/android/app/src/main/res/drawable/bg_widget_pill_offline.xml@@ -0,0 +1,7 @@+<?xml version="1.0" encoding="utf-8"?>+<!-- SPDX-License-Identifier: GPL-3.0-or-later -->+<shape xmlns:android="http://schemas.android.com/apk/res/android"+ android:shape="rectangle">+ <corners android:radius="999dp" />+ <solid android:color="#332F29" />+</shape>diff --git a/android/app/src/main/res/drawable/bg_widget_pill_online.xml b/android/app/src/main/res/drawable/bg_widget_pill_online.xmlnew file mode 100644index 0000000..7784eb2--- /dev/null+++ b/android/app/src/main/res/drawable/bg_widget_pill_online.xml@@ -0,0 +1,7 @@+<?xml version="1.0" encoding="utf-8"?>+<!-- SPDX-License-Identifier: GPL-3.0-or-later -->+<shape xmlns:android="http://schemas.android.com/apk/res/android"+ android:shape="rectangle">+ <corners android:radius="999dp" />+ <solid android:color="#233B2B" />+</shape>diff --git a/android/app/src/main/res/layout/widget_pc.xml b/android/app/src/main/res/layout/widget_pc.xmlnew file mode 100644index 0000000..5e6749f--- /dev/null+++ b/android/app/src/main/res/layout/widget_pc.xml@@ -0,0 +1,130 @@+<?xml version="1.0" encoding="utf-8"?>+<!-- SPDX-License-Identifier: GPL-3.0-or-later -->+<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"+ android:id="@+id/widget_root"+ android:layout_width="match_parent"+ android:layout_height="match_parent"+ android:background="@drawable/bg_widget_card"+ android:orientation="vertical"+ android:padding="14dp">++ <LinearLayout+ android:layout_width="match_parent"+ android:layout_height="wrap_content"+ android:gravity="center_vertical"+ android:orientation="horizontal">++ <TextView+ android:id="@+id/widget_pc_name"+ android:layout_width="0dp"+ android:layout_height="wrap_content"+ android:layout_weight="1"+ android:ellipsize="end"+ android:singleLine="true"+ android:text="@string/widget_pc_no_pc"+ android:textColor="#F6F2EA"+ android:textSize="16sp"+ android:textStyle="bold" />++ <TextView+ android:id="@+id/widget_pc_status"+ android:layout_width="wrap_content"+ android:layout_height="wrap_content"+ android:background="@drawable/bg_widget_pill_offline"+ android:paddingStart="10dp"+ android:paddingTop="4dp"+ android:paddingEnd="10dp"+ android:paddingBottom="4dp"+ android:text="@string/widget_pc_offline"+ android:textColor="#D5CFC2"+ android:textSize="12sp"+ android:textStyle="bold" />++ <TextView+ android:id="@+id/widget_btn_wake"+ android:layout_width="wrap_content"+ android:layout_height="wrap_content"+ android:layout_marginStart="6dp"+ android:background="@drawable/bg_widget_button"+ android:paddingStart="12dp"+ android:paddingTop="4dp"+ android:paddingEnd="12dp"+ android:paddingBottom="4dp"+ android:text="@string/widget_pc_wake"+ android:textColor="#F4B841"+ android:textSize="12sp"+ android:textStyle="bold"+ android:visibility="gone" />+ </LinearLayout>++ <TextView+ android:id="@+id/widget_pc_subtitle"+ android:layout_width="match_parent"+ android:layout_height="wrap_content"+ android:layout_marginTop="4dp"+ android:ellipsize="end"+ android:singleLine="true"+ android:text="@string/widget_pc_tap_to_pair"+ android:textColor="#B8B1A3"+ android:textSize="12sp"+ android:visibility="visible" />++ <LinearLayout+ android:id="@+id/widget_actions_row"+ android:layout_width="match_parent"+ android:layout_height="wrap_content"+ android:layout_marginTop="10dp"+ android:baselineAligned="false"+ android:orientation="horizontal">++ <TextView+ android:id="@+id/widget_btn_send_clip"+ android:layout_width="0dp"+ android:layout_height="38dp"+ android:layout_weight="1"+ android:background="@drawable/bg_widget_button"+ android:ellipsize="end"+ android:gravity="center"+ android:paddingStart="6dp"+ android:paddingEnd="6dp"+ android:singleLine="true"+ android:text="@string/widget_pc_send_clip"+ android:textColor="#F6F2EA"+ android:textSize="12sp"+ android:textStyle="bold" />++ <TextView+ android:id="@+id/widget_btn_ring"+ android:layout_width="0dp"+ android:layout_height="38dp"+ android:layout_marginStart="4dp"+ android:layout_marginEnd="4dp"+ android:layout_weight="1"+ android:background="@drawable/bg_widget_button"+ android:ellipsize="end"+ android:gravity="center"+ android:paddingStart="6dp"+ android:paddingEnd="6dp"+ android:singleLine="true"+ android:text="@string/widget_pc_ring"+ android:textColor="#F6F2EA"+ android:textSize="12sp"+ android:textStyle="bold" />++ <TextView+ android:id="@+id/widget_btn_lock"+ android:layout_width="0dp"+ android:layout_height="38dp"+ android:layout_weight="1"+ android:background="@drawable/bg_widget_button"+ android:ellipsize="end"+ android:gravity="center"+ android:paddingStart="6dp"+ android:paddingEnd="6dp"+ android:singleLine="true"+ android:text="@string/widget_pc_lock"+ android:textColor="#F6F2EA"+ android:textSize="12sp"+ android:textStyle="bold" />+ </LinearLayout>+</LinearLayout>diff --git a/android/app/src/main/res/values/strings.xml b/android/app/src/main/res/values/strings.xmlindex 749be7e..07b45e6 100644--- a/android/app/src/main/res/values/strings.xml+++ b/android/app/src/main/res/values/strings.xml@@ -109,8 +109,8 @@<string name="mirror_sharing">Sharing your screen with %1$s</string><string name="action_stop">Stop</string><plurals name="app_windows_title">- <item quantity="one">An app is open in a window on a PC</item>- <item quantity="other">%d apps are open in windows on a PC</item>+ <item quantity="one">%1$d app is open in a window on a PC</item>+ <item quantity="other">%1$d apps are open in windows on a PC</item></plurals><string name="app_windows_text">Shown on %1$s. They run here, beside what\'s on your screen.</string><string name="action_close_all">Close all</string>@@ -251,6 +251,10 @@<string name="channel_ringing">Find my phone</string><string name="notification_connected_to">Connected to %1$s</string><string name="notification_connected_many">Connected to %1$d PCs</string>+ <plurals name="notification_connected_pcs">+ <item quantity="one">Connected to %1$d PC</item>+ <item quantity="other">Connected to %1$d PCs</item>+ </plurals><string name="notification_waiting">Waiting for your PC</string><string name="notification_not_paired">Not paired with a PC yet</string><plurals name="transfer_files">@@ -437,8 +441,8 @@<string name="data_clipboard_title">Clipboard history</string><string name="data_clipboard_subtitle">Encrypted on device (passwords and OTPs excluded) · kept for 7 days, up to 50 clips / 128 MB</string><plurals name="data_clipboard_count">- <item quantity="one">%d clip stored</item>- <item quantity="other">%d clips stored</item>+ <item quantity="one">%1$d clip stored</item>+ <item quantity="other">%1$d clips stored</item></plurals><string name="data_timeline_title">Timeline</string><string name="data_timeline_subtitle">Files, clips, links, photos, recordings and sessions · up to 5,000 items</string>@@ -464,5 +468,131 @@<string name="transfer_requested_from">%1$s wants to send files</string><string name="action_accept">Accept</string><string name="action_decline">Decline</string>+ <string name="action_dismiss">Dismiss</string>++ <!-- Continuity Camera -->+ <string name="channel_camera_requests">Camera capture requests</string>+ <string name="continuity_camera_request_scan_title">%1$s wants to scan a document</string>+ <string name="continuity_camera_request_photo_title">%1$s wants to take a photo</string>+ <string name="continuity_camera_request_scan_text">Tap to scan a document with your camera.</string>+ <string name="continuity_camera_request_photo_text">Tap to take a photo with your camera.</string>+ <string name="continuity_camera_scan_title">Scan document</string>+ <string name="continuity_camera_photo_title">Take photo</string>+ <string name="continuity_camera_for_pc">For %1$s</string>+ <string name="continuity_camera_mode_photo">Photo</string>+ <string name="continuity_camera_mode_scan">Scan</string>+ <string name="continuity_camera_enhance">Enhance document</string>+ <string name="continuity_camera_adjust_corners">Adjust corners</string>+ <string name="continuity_camera_preview_scan">Preview scan</string>+ <string name="continuity_camera_retake">Retake</string>+ <string name="continuity_camera_send_scan">Send scan</string>+ <string name="continuity_camera_use_photo">Use photo</string>+ <string name="continuity_camera_shutter_photo">Capture photo</string>+ <string name="continuity_camera_shutter_scan">Capture document</string>+ <string name="continuity_camera_preview_desc">Captured preview</string>+ <string name="continuity_camera_corners_desc">Drag corners to adjust document edges</string>+ <string name="continuity_camera_permission_denied">Camera permission denied on phone</string>+ <string name="continuity_camera_cancelled">Cancelled on phone</string>++ <!-- Task notifications -->+ <string name="task_default_label">Task</string>+ <string name="task_finished_title">%1$s finished</string>+ <string name="task_failed_title">%1$s failed (exit %2$d)</string>+ <string name="task_took_from">%1$s · %2$s</string>+ <string name="task_took_hm">Took %1$dh %2$02dm</string>+ <string name="task_took_ms">Took %1$dm %2$02ds</string>+ <string name="task_took_s">Took %1$ds</string>+ <string name="task_running_short">Running</string>++ <!-- Errors -->+ <string name="error_not_connected">The PC isn\'t connected right now.</string>+ <string name="error_not_paired">That PC isn\'t paired anymore.</string>+ <string name="error_timed_out">The PC didn\'t answer in time.</string>+ <string name="error_unsupported">The PC\'s app doesn\'t support that yet.</string>+ <string name="error_generic">Something went wrong.</string>++ <!-- Theme seed names -->+ <string name="settings_seed_honey">Honey</string>+ <string name="settings_seed_lavender">Lavender</string>+ <string name="settings_seed_ocean">Ocean</string>+ <string name="settings_seed_sage">Sage</string>++ <!-- Deck defaults & accessibility -->+ <string name="deck_tile_with_badge">%1$s, %2$s</string>+ <string name="deck_default_page_main">Main</string>+ <string name="deck_default_play_pause">Play / pause</string>+ <string name="deck_default_previous">Previous</string>+ <string name="deck_default_next">Next</string>+ <string name="deck_default_volume_down">Volume down</string>+ <string name="deck_default_volume_up">Volume up</string>+ <string name="deck_default_volume_mute">Mute audio</string>+ <string name="deck_default_mic_mute">Mic mute</string>+ <string name="deck_default_show_desktop">Show desktop</string>+ <string name="deck_default_switch_window">Switch window</string>+ <string name="deck_default_screenshot">Screenshot</string>+ <string name="deck_default_lock_pc">Lock PC</string>++ <!-- Remote special keys -->+ <string name="remote_key_ctrl">Ctrl</string>+ <string name="remote_key_alt">Alt</string>+ <string name="remote_key_shift">Shift</string>+ <string name="remote_key_win">Win</string>+ <string name="remote_key_esc">Esc</string>+ <string name="remote_key_esc_desc">Escape</string>+ <string name="remote_key_tab">Tab</string>+ <string name="remote_key_left_desc">Left arrow</string>+ <string name="remote_key_up_desc">Up arrow</string>+ <string name="remote_key_down_desc">Down arrow</string>+ <string name="remote_key_right_desc">Right arrow</string>+ <string name="remote_key_home">Home</string>+ <string name="remote_key_end">End</string>+ <string name="remote_key_del">Del</string>+ <string name="remote_key_del_desc">Delete</string>+ <string name="remote_key_copy">Copy</string>+ <string name="remote_key_paste">Paste</string>++ <!-- Webcam formatting -->+ <string name="webcam_stream_spec">%1$d × %2$d · %3$d fps</string>+ <string name="webcam_stream_camera_spec">%1$d × %2$d · %3$s</string>+ <string name="webcam_status_streaming_camera">Streaming %1$d × %2$d to %3$s · %4$s</string>+ <string name="webcam_switch_camera_current">Flip camera (%1$s)</string>+ <string name="webcam_res_720p">720p</string>+ <string name="webcam_res_1080p">1080p</string>+ <string name="webcam_res_4k">4K</string>+ <string name="webcam_zoom_preset">%1$d×</string>++ <!-- Formatted status & metadata phrases -->+ <string name="transfer_requested_from_size">%1$s wants to send files · %2$s</string>+ <string name="transfer_sending_progress">Sending to %1$s · %2$s / %3$s</string>+ <string name="transfer_receiving_progress">Receiving from %1$s · %2$s / %3$s</string>+ <string name="clipboard_history_meta">%1$s · %2$s</string>+ <string name="clipboard_history_meta_pinned">%1$s · %2$s · Pinned</string>+ <string name="timeline_latest_summary">%1$s · %2$s</string>+ <string name="recorder_marker_chip">%1$s · %2$s</string>++ <!-- Rich Handoff -->+ <string name="handoff_map_from">Map from %1$s</string>+ <string name="handoff_video_from">Video from %1$s</string>+ <string name="handoff_action_continue_video">Continue watching</string>+ <string name="handoff_doc_received_from">From %1$s · tap to open</string>++ <!-- Remote PC keyboard typing without mirroring -->+ <string name="keyboard_from_pc_banner">Typing from %1$s</string>+ <string name="keyboard_stop">Stop typing</string>++ <!-- Home-screen PC widget -->+ <string name="widget_pc_title">PC quick actions</string>+ <string name="widget_pc_description">Connection status, Send clipboard, Ring PC, Lock PC, and Wake for your paired PC.</string>+ <string name="widget_pc_no_pc">No PC paired</string>+ <string name="widget_pc_tap_to_pair">Tap to open Nectarlink and pair a PC</string>+ <string name="widget_pc_connected">Connected</string>+ <string name="widget_pc_offline">Offline</string>+ <string name="widget_pc_waking">Waking…</string>+ <string name="widget_pc_wake">Wake</string>+ <string name="widget_pc_send_clip">Send clip</string>+ <string name="widget_pc_ring">Ring PC</string>+ <string name="widget_pc_lock">Lock PC</string>+ <string name="widget_pc_ringing_toast">Ringing %1$s…</string>+ <string name="widget_pc_waking_toast">Waking %1$s…</string></resources>diff --git a/android/app/src/main/res/xml/input_service.xml b/android/app/src/main/res/xml/input_service.xmlindex e8cacf1..4d95b2a 100644--- a/android/app/src/main/res/xml/input_service.xml+++ b/android/app/src/main/res/xml/input_service.xml@@ -4,7 +4,7 @@<accessibility-service xmlns:android="http://schemas.android.com/apk/res/android"android:accessibilityEventTypes="typeWindowStateChanged"android:accessibilityFeedbackType="feedbackGeneric"- android:accessibilityFlags="flagDefault"+ android:accessibilityFlags="flagDefault|flagRetrieveInteractiveWindows"android:canPerformGestures="true"android:canRetrieveWindowContent="true"android:description="@string/input_service_description"diff --git a/android/app/src/main/res/xml/pc_widget_info.xml b/android/app/src/main/res/xml/pc_widget_info.xmlnew file mode 100644index 0000000..fb8ef32--- /dev/null+++ b/android/app/src/main/res/xml/pc_widget_info.xml@@ -0,0 +1,16 @@+<?xml version="1.0" encoding="utf-8"?>+<!-- SPDX-License-Identifier: GPL-3.0-or-later -->+<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"+ xmlns:tools="http://schemas.android.com/tools"+ android:description="@string/widget_pc_description"+ android:initialLayout="@layout/widget_pc"+ android:minHeight="110dp"+ android:minResizeHeight="90dp"+ android:minResizeWidth="180dp"+ android:minWidth="250dp"+ android:resizeMode="horizontal|vertical"+ android:targetCellHeight="2"+ android:targetCellWidth="4"+ android:updatePeriodMillis="0"+ android:widgetCategory="home_screen"+ tools:targetApi="s" />diff --git a/android/app/src/main/res/xml/shortcuts.xml b/android/app/src/main/res/xml/shortcuts.xmlnew file mode 100644index 0000000..eb98bc1--- /dev/null+++ b/android/app/src/main/res/xml/shortcuts.xml@@ -0,0 +1,8 @@+<?xml version="1.0" encoding="utf-8"?>+<!-- SPDX-License-Identifier: GPL-3.0-or-later -->+<shortcuts xmlns:android="http://schemas.android.com/apk/res/android">+ <share-target android:targetClass="app.nectarlink.android.clipboard.SendActivity">+ <data android:mimeType="*/*" />+ <category android:name="app.nectarlink.android.category.DIRECT_SHARE" />+ </share-target>+</shortcuts>diff --git a/core/nectarlink-cli/src/main.rs b/core/nectarlink-cli/src/main.rsindex a384bf8..a9b55a6 100644--- a/core/nectarlink-cli/src/main.rs+++ b/core/nectarlink-cli/src/main.rs@@ -147,6 +147,9 @@ enum Command {device: String,#[arg(required = true)]files: Vec<PathBuf>,+ /// Ask the receiving device to open the file with its default app once it arrives.+ #[arg(long)]+ open: bool,},/// Send a voice recording with optional markers to a paired PC (use with/// --as-phone) and wait until it has arrived.@@ -205,8 +208,14 @@ enum Command {},/// Wake a paired PC using its stored Wake-on-LAN addresses.Wake { device: String },- /// Open a web link on a paired device.- Open { device: String, url: String },+ /// Open a web, video, or map (`geo:`) link on a paired device.+ Open {+ device: String,+ url: String,+ /// Attach or update a playback timestamp in seconds for a video link.+ #[arg(long = "at-seconds")]+ at_seconds: Option<u32>,+ },/// Browse a paired phone's gallery (albums, photos, thumbnails, download),/// or with no arguments watch for new photos from paired phones until Ctrl+C.Photos {@@ -2592,12 +2601,12 @@ async fn run(cli: &Cli, node: &Node) -> Result<()> {node.ring(id, !off).await.context("ring failed")?;println!("{}", if *off { "Stopped ringing." } else { "Ringing…" });}- Command::Send { device, files } => {+ Command::Send { device, files, open } => {let (id, is_localsend) = resolve_send_target(node, device, cli.localsend_port).await?;if !is_localsend {wait_until_online(node, id).await?;}- send_files(node, id, files).await?;+ send_files(node, id, files, *open).await?;}Command::Record { device, duration, file, markers } => {if !cli.as_phone {@@ -3097,6 +3106,8 @@ async fn run(cli: &Cli, node: &Node) -> Result<()> {audio: sound.is_some() && app.is_none(),session,app: app.clone(),+ stay_awake: false,+ screen_off: false,};node.mirror_start(id, options).await.context("the phone didn't ask its user")?;println!(@@ -3196,8 +3207,40 @@ async fn run(cli: &Cli, node: &Node) -> Result<()> {if *apps {SCREEN_APPS.store(true, std::sync::atomic::Ordering::Relaxed);offers.push(nectarlink_core::MIRROR_VIRTUAL_DISPLAY.into());+ offers.push("notify.mirror".into());}node.update_power(node_power(cli), offers).await;+ if *apps {+ if let Ok(paired) = node.paired_devices()+ && let Some(first) = paired.first()+ {+ let _ =+ tokio::time::timeout(Duration::from_secs(3), wait_until_online(node, first.id)).await;+ }+ let now_ms = std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .map_or(0, |d| d.as_millis() as i64);+ node.notification_posted(Notification {+ key: "cli|screen|chat".into(),+ app: "com.example.chat".into(),+ app_name: "Chat".into(),+ title: Some("Alice".into()),+ text: Some("Tap to open Chat in an app window".into()),+ sub: None,+ when: now_ms,+ actions: vec![NotificationAction {+ id: "read".into(),+ title: "Mark as read".into(),+ reply: false,+ }],+ silent: true,+ icon: Some(sample_icon(2)),+ image: None,+ live: None,+ conversation: None,+ })+ .await;+ }println!("Sharing a {width}x{height} screen ({} frames) with PCs that ask.", units.len());let streamer = node.clone();let (width, height, fps) = (*width, *height, *fps);@@ -3699,10 +3742,16 @@ async fn run(cli: &Cli, node: &Node) -> Result<()> {bcasts,);}- Command::Open { device, url } => {+ Command::Open { device, url, at_seconds } => {let id = resolve(node, device)?;wait_until_online(node, id).await?;- node.open_link(id, url.clone()).await.context("the link didn't open")?;+ let resolved =+ nectarlink_core::extract_handoff_link(url).map(|h| h.url).unwrap_or_else(|| url.clone());+ let final_url = match at_seconds {+ Some(secs) => nectarlink_core::with_video_timestamp(&resolved, *secs),+ None => resolved,+ };+ node.open_link(id, final_url).await.context("the link didn't open")?;println!("Opened.");}Command::Media { device, action, player, position } => {@@ -3962,10 +4011,14 @@ async fn confirm_code(code: String) -> Result<bool> {}/// Sends files and shows progress until they've arrived.-async fn send_files(node: &Node, device: DeviceId, paths: &[PathBuf]) -> Result<()> {+async fn send_files(node: &Node, device: DeviceId, paths: &[PathBuf], open: bool) -> Result<()> {let mut events = node.events();let files = nectarlink_core::outgoing_paths(paths).context("can't read what to send")?;- let id = node.send_files(device, files).await.context("can't send")?;+ let id = if open {+ node.send_handoff_files(device, files).await.context("can't send")?+ } else {+ node.send_files(device, files).await.context("can't send")?+ };wait_for_outgoing_transfer(&mut events, &id).await}diff --git a/core/nectarlink-core/src/actions.rs b/core/nectarlink-core/src/actions.rsindex f97c921..3cda296 100644--- a/core/nectarlink-core/src/actions.rs+++ b/core/nectarlink-core/src/actions.rs@@ -194,13 +194,21 @@ impl Shared {}}-/// Checks a link the protocol allows: http or https, not too long.+/// Checks a link the protocol allows: `http://`, `https://`, or `geo:`, not too long.pub(crate) fn valid_link(url: &str) -> bool {+ if url.len() > nectarlink_protocol::messages::LINK_MAX_BYTES+ || url.chars().any(|c| c.is_control() || c.is_whitespace())+ {+ return false;+ }let lower = url.get(..8).map(str::to_ascii_lowercase).unwrap_or_default();- (lower.starts_with("http://") || lower.starts_with("https://"))- && url.len() <= nectarlink_protocol::messages::LINK_MAX_BYTES- && !url.chars().any(|c| c.is_control() || c.is_whitespace())- && url.split("://").nth(1).is_some_and(|rest| !rest.is_empty())+ if lower.starts_with("http://") || lower.starts_with("https://") {+ url.split("://").nth(1).is_some_and(|rest| !rest.is_empty())+ } else if url.get(..4).is_some_and(|p| p.eq_ignore_ascii_case("geo:")) {+ !url[4..].is_empty()+ } else {+ false+ }}pub(crate) async fn pc_power(shared: &Arc<Shared>, session: &Session, action: PowerAction) -> Result<()> {@@ -212,13 +220,16 @@ pub(crate) async fn pc_power(shared: &Arc<Shared>, session: &Session, action: PoOk(())}-fn link_host(url: &str) -> String {+fn link_detail(url: &str) -> String {+ if let Some(h) = crate::handoff::extract_handoff_link(url) {+ return h.label;+ }url.split("://").nth(1).unwrap_or(url).split(['/', '?', '#']).next().unwrap_or("").to_owned()}pub(crate) async fn open_link(shared: &Arc<Shared>, session: &Session, url: String) -> Result<()> {if !valid_link(&url) {- return Err(Error::Internal("not a web link".into()));+ return Err(Error::Internal("not a web or map link".into()));}if !shared.offers(&session.peer, LINKS)? {return Err(Error::Unsupported);@@ -232,7 +243,7 @@ pub(crate) async fn open_link(shared: &Arc<Shared>, session: &Session, url: Striincoming: false,timestamp: crate::now_unix(),title: url.clone(),- detail: link_host(&url),+ detail: link_detail(&url),target: url,size_bytes: 0,duration_secs: 0,@@ -359,7 +370,7 @@ pub(crate) async fn handle(shared: &Arc<Shared>, session: &Arc<Session>, env: &Eincoming: true,timestamp: crate::now_unix(),title: url.clone(),- detail: link_host(&url),+ detail: link_detail(&url),target: url,size_bytes: 0,duration_secs: 0,@@ -411,9 +422,16 @@ mod tests {fn only_web_links_go() {assert!(valid_link("https://example.com/a?b=c#d"));assert!(valid_link("HTTP://EXAMPLE.COM"));- for bad in- ["javascript:alert(1)", "file:///C:/x", "https://", "https://a b", "ms-settings:", "ftp://x"]- {+ assert!(valid_link("geo:48.8584,2.2945?q=Eiffel%20Tower"));+ for bad in [+ "javascript:alert(1)",+ "file:///C:/x",+ "https://",+ "geo:",+ "https://a b",+ "ms-settings:",+ "ftp://x",+ ] {assert!(!valid_link(bad), "{bad}");}assert!(!valid_link(&format!("https://a.com/{}", "x".repeat(8192))));diff --git a/core/nectarlink-core/src/config.rs b/core/nectarlink-core/src/config.rsindex de6e433..df09c70 100644--- a/core/nectarlink-core/src/config.rs+++ b/core/nectarlink-core/src/config.rs@@ -215,6 +215,16 @@ pub trait Platform: Send + Sync + 'static {) {}+ /// The PC changed `stay_awake` or `screen_off` while mirroring this phone's+ /// screen (`session == 0`).+ fn mirror_power_requested(+ &self,+ _peer: &nectarlink_protocol::DeviceId,+ _stay_awake: bool,+ _screen_off: bool,+ ) {+ }+/// The apps a PC may open in windows of their own (launchable ones),/// with small PNG icons (a PC asked).fn phone_apps(&self) -> Result<Vec<crate::PhoneApp>, String> {diff --git a/core/nectarlink-core/src/handoff.rs b/core/nectarlink-core/src/handoff.rsnew file mode 100644index 0000000..279ed40--- /dev/null+++ b/core/nectarlink-core/src/handoff.rs@@ -0,0 +1,593 @@+// SPDX-License-Identifier: MPL-2.0+//! Rich Handoff helpers (`docs/PLAN.md` §3.11):+//! - Map locations (`geo:` URIs and Google / Apple / Bing / OpenStreetMap links)+//! - YouTube and video links with playback timestamps (`t=`, `start=`, `#t=`)+//! - Safe document allowlist for `open_on_arrival` file transfers++use serde::{Deserialize, Serialize};++/// Classification of a link handed off between devices.+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]+pub enum HandoffKind {+ WebLink,+ VideoLink,+ MapLocation,+}++/// Parsed metadata for a link or `geo:` URI handed off between devices.+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+pub struct HandoffLink {+ pub kind: HandoffKind,+ /// Normalized URL or `geo:` URI ready to send over `link.open`.+ pub url: String,+ /// Short human-readable label (e.g. `"Map · Golden Gate Bridge"`, `"YouTube · 1:30"`).+ pub label: String,+ /// Playback position in seconds when `kind == HandoffKind::VideoLink`.+ pub timestamp_secs: Option<u32>,+ /// Place name or coordinates when `kind == HandoffKind::MapLocation`.+ pub map_query: Option<String>,+}++/// Safe non-executable document and media extensions allowed to open+/// automatically with the OS default application when `open_on_arrival` is set.+const SAFE_HANDOFF_EXTENSIONS: &[&str] = &[+ // Documents & text+ "pdf", "txt", "md", "rtf", "csv", "tsv", "json", "xml", "yaml", "yml", "doc", "docx", "xls", "xlsx",+ "ppt", "pptx", "odt", "ods", "odp", "epub", // Images+ "png", "jpg", "jpeg", "webp", "gif", "bmp", "svg", // Audio & video+ "mp3", "m4a", "wav", "flac", "ogg", "mp4", "mkv", "mov", "webm",+];++/// Returns `true` if `name` has a safe, non-executable document or media+/// extension that may be opened with the default application on arrival.+#[must_use]+pub fn is_safe_handoff_document(name: &str) -> bool {+ let trimmed = name.trim().trim_end_matches(['.', ' ']);+ let Some((_, ext)) = trimmed.rsplit_once('.') else {+ return false;+ };+ let lower = ext.to_ascii_lowercase();+ SAFE_HANDOFF_EXTENSIONS.contains(&lower.as_str())+}++/// Formats a video timestamp in seconds as `"M:SS"` or `"H:MM:SS"`.+#[must_use]+pub fn format_video_timestamp(secs: u32) -> String {+ let hours = secs / 3600;+ let mins = (secs % 3600) / 60;+ let rem = secs % 60;+ if hours > 0 { format!("{hours}:{mins:02}:{rem:02}") } else { format!("{mins}:{rem:02}") }+}++/// Parses a video timestamp token such as `"90"`, `"90s"`, `"1m30s"`, `"1h02m03s"`,+/// or `"01:30"` into seconds.+#[must_use]+pub fn parse_video_timestamp(raw: &str) -> Option<u32> {+ let s = raw.trim().trim_end_matches('s').trim();+ if s.is_empty() {+ return None;+ }+ if let Ok(n) = s.parse::<u32>() {+ return (n > 0 && n <= 86_400 * 7).then_some(n);+ }+ if s.contains(':') {+ let parts: Vec<&str> = s.split(':').collect();+ let secs = match parts.as_slice() {+ [m, sec] => m.parse::<u32>().ok()?.checked_mul(60)?.checked_add(sec.parse::<u32>().ok()?)?,+ [h, m, sec] => h+ .parse::<u32>()+ .ok()?+ .checked_mul(3600)?+ .checked_add(m.parse::<u32>().ok()?.checked_mul(60)?)?+ .checked_add(sec.parse::<u32>().ok()?)?,+ _ => return None,+ };+ return (secs > 0 && secs <= 86_400 * 7).then_some(secs);+ }++ // Parse HMS tokens like `1h2m3s` or `2m15` (after trailing `s` strip).+ let lower = raw.trim().to_ascii_lowercase();+ let mut total: u32 = 0;+ let mut cur: u32 = 0;+ let mut saw_unit = false;+ let mut saw_digit = false;+ for ch in lower.chars() {+ if let Some(d) = ch.to_digit(10) {+ cur = cur.checked_mul(10)?.checked_add(d)?;+ saw_digit = true;+ } else if ch == 'h' && saw_digit {+ total = total.checked_add(cur.checked_mul(3600)?)?;+ cur = 0;+ saw_digit = false;+ saw_unit = true;+ } else if ch == 'm' && saw_digit {+ total = total.checked_add(cur.checked_mul(60)?)?;+ cur = 0;+ saw_digit = false;+ saw_unit = true;+ } else if ch == 's' && saw_digit {+ total = total.checked_add(cur)?;+ cur = 0;+ saw_digit = false;+ saw_unit = true;+ } else {+ return None;+ }+ }+ if saw_digit {+ total = total.checked_add(cur)?;+ }+ (saw_unit && total > 0 && total <= 86_400 * 7).then_some(total)+}++/// Extracts the first `http://`, `https://`, or `geo:` link from `text` and+/// classifies it as a [`HandoffLink`].+#[must_use]+pub fn extract_handoff_link(text: &str) -> Option<HandoffLink> {+ let token = find_url_or_geo_token(text)?;+ classify_link_token(&token)+}++/// Attaches or updates a playback timestamp (`secs`) on a video URL.+#[must_use]+pub fn with_video_timestamp(url: &str, secs: u32) -> String {+ let trimmed = url.trim();+ if secs == 0 {+ return trimmed.to_owned();+ }+ let (before_frag, frag) = match trimmed.split_once('#') {+ Some((b, f)) => (b, Some(f)),+ None => (trimmed, None),+ };+ let lower_host = link_host(before_frag).to_ascii_lowercase();+ if lower_host == "vimeo.com" || lower_host.ends_with(".vimeo.com") {+ return format!("{before_frag}#t={secs}s");+ }+ let (base, query) = match before_frag.split_once('?') {+ Some((b, q)) => (b, Some(q)),+ None => (before_frag, None),+ };+ let mut kept: Vec<String> = Vec::new();+ if let Some(q) = query {+ for pair in q.split('&').filter(|p| !p.is_empty()) {+ let key = pair.split('=').next().unwrap_or("");+ if !key.eq_ignore_ascii_case("t")+ && !key.eq_ignore_ascii_case("start")+ && !key.eq_ignore_ascii_case("time_continue")+ {+ kept.push(pair.to_owned());+ }+ }+ }+ kept.push(format!("t={secs}"));+ let mut out = format!("{base}?{}", kept.join("&"));+ if let Some(f) = frag+ && !f.starts_with("t=")+ {+ out.push('#');+ out.push_str(f);+ }+ out+}++/// Converts a `geo:` URI into a universal Google Maps HTTPS URL so desktop+/// platforms without a registered `geo:` handler can open it in the browser.+#[must_use]+pub fn geo_to_maps_https(uri: &str) -> Option<String> {+ let rest = uri.trim().strip_prefix("geo:").or_else(|| uri.trim().strip_prefix("GEO:"))?;+ let (coords_part, query_part) = match rest.split_once('?') {+ Some((c, q)) => (c, Some(q)),+ None => (rest, None),+ };+ if let Some(q) = query_part {+ for pair in q.split('&') {+ if let Some((k, v)) = pair.split_once('=')+ && k.eq_ignore_ascii_case("q")+ && !v.trim().is_empty()+ {+ let decoded = percent_decode(v);+ return Some(format!(+ "https://www.google.com/maps/search/?api=1&query={}",+ percent_encode_query(decoded.trim())+ ));+ }+ }+ }+ let coords = coords_part.split(';').next().unwrap_or(coords_part).trim();+ if !coords.is_empty() && coords != "0,0" {+ return Some(format!(+ "https://www.google.com/maps/search/?api=1&query={}",+ percent_encode_query(coords)+ ));+ }+ None+}++/// Converts a street address or place query into a `geo:0,0?q=...` URI.+#[must_use]+pub fn address_to_geo_uri(address: &str) -> String {+ format!("geo:0,0?q={}", percent_encode_query(address.trim()))+}++fn find_url_or_geo_token(text: &str) -> Option<String> {+ let trimmed = text.trim();+ if trimmed.is_empty() {+ return None;+ }+ // Check if the whole string is a geo: URI (possibly with spaces in ?q= that we encode).+ if trimmed.len() > 4 && trimmed[..4].eq_ignore_ascii_case("geo:") {+ let first_line = trimmed.lines().next().unwrap_or(trimmed).trim();+ let normalized: String =+ first_line.chars().filter(|c| !c.is_control()).map(|c| if c == ' ' { '+' } else { c }).collect();+ if normalized.len() > 4 {+ return Some(normalized);+ }+ }+ for word in trimmed.split_whitespace() {+ let clean = word.trim_matches(|c: char| {+ matches!(c, '<' | '>' | '"' | '\'' | '(' | ')' | '[' | ']' | '{' | '}' | ',' | ';' | '!')+ });+ let lower_prefix: String = clean.chars().take(8).collect::<String>().to_ascii_lowercase();+ if lower_prefix.starts_with("https://")+ || lower_prefix.starts_with("http://")+ || lower_prefix.starts_with("geo:")+ {+ return Some(clean.to_owned());+ }+ }+ None+}++fn classify_link_token(url: &str) -> Option<HandoffLink> {+ if url.len() > nectarlink_protocol::messages::LINK_MAX_BYTES+ || url.chars().any(|c| c.is_control() || c.is_whitespace())+ {+ return None;+ }+ let lower_prefix: String = url.chars().take(8).collect::<String>().to_ascii_lowercase();+ if lower_prefix.starts_with("geo:") {+ let rest = &url[4..];+ if rest.is_empty() {+ return None;+ }+ let query = extract_geo_label(rest);+ let label = match &query {+ Some(q) => format!("Map · {q}"),+ None => "Map location".to_owned(),+ };+ return Some(HandoffLink {+ kind: HandoffKind::MapLocation,+ url: format!("geo:{rest}"),+ label,+ timestamp_secs: None,+ map_query: query,+ });+ }+ if !lower_prefix.starts_with("http://") && !lower_prefix.starts_with("https://") {+ return None;+ }+ let rest = url.split("://").nth(1)?;+ if rest.is_empty() {+ return None;+ }+ let host = link_host(url).to_ascii_lowercase();+ if host.is_empty() {+ return None;+ }++ if is_map_url(&host, rest) {+ let query = extract_http_map_query(url);+ let label = match &query {+ Some(q) => format!("Map · {q}"),+ None => "Map location".to_owned(),+ };+ return Some(HandoffLink {+ kind: HandoffKind::MapLocation,+ url: url.to_owned(),+ label,+ timestamp_secs: None,+ map_query: query,+ });+ }++ if let Some((provider, ts)) = classify_video_url(&host, url) {+ let label = match ts {+ Some(secs) => format!("{provider} · {}", format_video_timestamp(secs)),+ None => provider.to_owned(),+ };+ return Some(HandoffLink {+ kind: HandoffKind::VideoLink,+ url: url.to_owned(),+ label,+ timestamp_secs: ts,+ map_query: None,+ });+ }++ Some(HandoffLink {+ kind: HandoffKind::WebLink,+ url: url.to_owned(),+ label: host,+ timestamp_secs: None,+ map_query: None,+ })+}++fn link_host(url: &str) -> &str {+ url.split("://").nth(1).unwrap_or(url).split(['/', '?', '#']).next().unwrap_or("")+}++fn is_map_url(host: &str, rest_after_scheme: &str) -> bool {+ let h = host.strip_prefix("www.").unwrap_or(host);+ if h == "maps.app.goo.gl"+ || h == "maps.apple.com"+ || h == "openstreetmap.org"+ || h.starts_with("maps.google.")+ {+ return true;+ }+ let path = rest_after_scheme.find('/').map_or("", |i| &rest_after_scheme[i..]);+ let lower_path = path.to_ascii_lowercase();+ if (h.starts_with("google.") || h == "goo.gl" || h == "bing.com")+ && (lower_path.starts_with("/maps") || lower_path.contains("/maps/"))+ {+ return true;+ }+ false+}++fn extract_geo_label(rest: &str) -> Option<String> {+ let (coords_part, query_part) = match rest.split_once('?') {+ Some((c, q)) => (c, Some(q)),+ None => (rest, None),+ };+ if let Some(q) = query_part {+ for pair in q.split('&') {+ if let Some((k, v)) = pair.split_once('=')+ && k.eq_ignore_ascii_case("q")+ {+ let decoded = clean_map_label(&percent_decode(v));+ if !decoded.is_empty() {+ return Some(decoded);+ }+ }+ }+ }+ let coords = coords_part.split(';').next().unwrap_or(coords_part).trim();+ if !coords.is_empty() && coords != "0,0" {+ return Some(coords.to_owned());+ }+ None+}++fn extract_http_map_query(url: &str) -> Option<String> {+ let before_frag = url.split('#').next().unwrap_or(url);+ if let Some((_, query)) = before_frag.split_once('?') {+ for key_want in ["q", "query", "daddr", "where1", "address"] {+ for pair in query.split('&') {+ if let Some((k, v)) = pair.split_once('=')+ && k.eq_ignore_ascii_case(key_want)+ {+ let decoded = clean_map_label(&percent_decode(v));+ if !decoded.is_empty() {+ return Some(decoded);+ }+ }+ }+ }+ }+ // Check `/maps/place/<name>` or `/maps/search/<name>`+ let after_scheme = before_frag.split("://").nth(1)?;+ let path = after_scheme.find('/').map(|i| &after_scheme[i..])?;+ for marker in ["/maps/place/", "/maps/search/"] {+ if let Some(idx) = path.to_ascii_lowercase().find(marker) {+ let rest = &path[idx + marker.len()..];+ let seg = rest.split('/').next().unwrap_or("");+ if !seg.is_empty() && !seg.starts_with('@') {+ let decoded = clean_map_label(&percent_decode(seg));+ if !decoded.is_empty() {+ return Some(decoded);+ }+ }+ }+ }+ None+}++fn clean_map_label(raw: &str) -> String {+ // If geo query is `lat,lon(Label)`, prefer `Label`.+ let trimmed = raw.trim();+ if let Some(open) = trimmed.find('(')+ && let Some(close) = trimmed.rfind(')')+ && open + 1 < close+ {+ let inside = trimmed[open + 1..close].trim();+ if !inside.is_empty() {+ return truncate_label(inside, 60);+ }+ }+ truncate_label(trimmed, 60)+}++fn truncate_label(s: &str, max_chars: usize) -> String {+ let clean: String = s.chars().filter(|c| !c.is_control()).collect();+ let trimmed = clean.trim();+ if trimmed.chars().count() <= max_chars {+ trimmed.to_owned()+ } else {+ let mut out: String = trimmed.chars().take(max_chars).collect();+ out.push('…');+ out+ }+}++fn classify_video_url(host: &str, url: &str) -> Option<(&'static str, Option<u32>)> {+ let h = host.strip_prefix("www.").unwrap_or(host);+ let after_scheme = url.split("://").nth(1).unwrap_or("");+ let path_and_more = after_scheme.find('/').map_or("", |i| &after_scheme[i..]);+ let path = path_and_more.split(['?', '#']).next().unwrap_or("");+ let lower_path = path.to_ascii_lowercase();++ let provider = if h == "youtu.be" {+ (path.len() > 1).then_some("YouTube")+ } else if h == "youtube.com" || h == "m.youtube.com" || h == "music.youtube.com" {+ (lower_path == "/watch"+ || lower_path.starts_with("/shorts/")+ || lower_path.starts_with("/live/")+ || lower_path.starts_with("/embed/"))+ .then_some("YouTube")+ } else if h == "vimeo.com" || h == "player.vimeo.com" {+ (path.len() > 1).then_some("Vimeo")+ } else if h == "twitch.tv" || h == "m.twitch.tv" {+ lower_path.starts_with("/videos/").then_some("Twitch")+ } else {+ None+ }?;++ let ts = extract_video_timestamp(url);+ Some((provider, ts))+}++fn extract_video_timestamp(url: &str) -> Option<u32> {+ let (_, after_q) = url.split_once('?').unwrap_or((url, ""));+ let query = after_q.split('#').next().unwrap_or("");+ for pair in query.split('&').filter(|p| !p.is_empty()) {+ if let Some((k, v)) = pair.split_once('=')+ && (k.eq_ignore_ascii_case("t")+ || k.eq_ignore_ascii_case("start")+ || k.eq_ignore_ascii_case("time_continue"))+ && let Some(secs) = parse_video_timestamp(v)+ {+ return Some(secs);+ }+ }+ if let Some((_, frag)) = url.split_once('#') {+ for pair in frag.split('&').filter(|p| !p.is_empty()) {+ if let Some((k, v)) = pair.split_once('=')+ && (k.eq_ignore_ascii_case("t") || k.eq_ignore_ascii_case("start"))+ && let Some(secs) = parse_video_timestamp(v)+ {+ return Some(secs);+ }+ }+ }+ None+}++fn percent_decode(input: &str) -> String {+ let bytes = input.as_bytes();+ let mut out = Vec::with_capacity(bytes.len());+ let mut i = 0;+ while i < bytes.len() {+ if bytes[i] == b'+' {+ out.push(b' ');+ i += 1;+ } else if bytes[i] == b'%'+ && i + 2 < bytes.len()+ && let (Some(h), Some(l)) = (hex_val(bytes[i + 1]), hex_val(bytes[i + 2]))+ {+ out.push((h << 4) | l);+ i += 3;+ } else {+ out.push(bytes[i]);+ i += 1;+ }+ }+ String::from_utf8_lossy(&out).into_owned()+}++fn percent_encode_query(input: &str) -> String {+ let mut out = String::with_capacity(input.len() + 8);+ for &b in input.as_bytes() {+ if b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'.' | b',' | b':') {+ out.push(char::from(b));+ } else if b == b' ' {+ out.push('+');+ } else {+ out.push_str(&format!("%{b:02X}"));+ }+ }+ out+}++fn hex_val(b: u8) -> Option<u8> {+ match b {+ b'0'..=b'9' => Some(b - b'0'),+ b'a'..=b'f' => Some(b - b'a' + 10),+ b'A'..=b'F' => Some(b - b'A' + 10),+ _ => None,+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn extracts_and_formats_map_locations() {+ let geo = extract_handoff_link("geo:37.7749,-122.4194?q=Golden+Gate+Bridge").unwrap();+ assert_eq!(geo.kind, HandoffKind::MapLocation);+ assert_eq!(geo.map_query.as_deref(), Some("Golden Gate Bridge"));+ assert_eq!(geo.label, "Map · Golden Gate Bridge");+ assert_eq!(+ geo_to_maps_https(&geo.url).as_deref(),+ Some("https://www.google.com/maps/search/?api=1&query=Golden+Gate+Bridge")+ );++ let coords_only = extract_handoff_link("geo:48.8584,2.2945").unwrap();+ assert_eq!(coords_only.kind, HandoffKind::MapLocation);+ assert_eq!(coords_only.map_query.as_deref(), Some("48.8584,2.2945"));++ let gmaps = extract_handoff_link(+ "Meet me here: https://www.google.com/maps/place/Eiffel+Tower/@48.8583701,2.2922926,17z",+ )+ .unwrap();+ assert_eq!(gmaps.kind, HandoffKind::MapLocation);+ assert_eq!(gmaps.map_query.as_deref(), Some("Eiffel Tower"));+ assert_eq!(gmaps.label, "Map · Eiffel Tower");++ let apple = extract_handoff_link("https://maps.apple.com/?q= Cupertino+CA").unwrap();+ assert_eq!(apple.kind, HandoffKind::MapLocation);+ }++ #[test]+ fn extracts_and_updates_video_timestamps() {+ let yt =+ extract_handoff_link("Watch this https://www.youtube.com/watch?v=dQw4w9WgXcQ&t=1m30s").unwrap();+ assert_eq!(yt.kind, HandoffKind::VideoLink);+ assert_eq!(yt.timestamp_secs, Some(90));+ assert_eq!(yt.label, "YouTube · 1:30");++ let short = extract_handoff_link("https://youtu.be/dQw4w9WgXcQ?t=125").unwrap();+ assert_eq!(short.kind, HandoffKind::VideoLink);+ assert_eq!(short.timestamp_secs, Some(125));+ assert_eq!(short.label, "YouTube · 2:05");++ let vimeo = extract_handoff_link("https://vimeo.com/12345678#t=45s").unwrap();+ assert_eq!(vimeo.kind, HandoffKind::VideoLink);+ assert_eq!(vimeo.timestamp_secs, Some(45));+ assert_eq!(vimeo.label, "Vimeo · 0:45");++ let updated = with_video_timestamp("https://www.youtube.com/watch?v=dQw4w9WgXcQ&t=10", 245);+ assert_eq!(updated, "https://www.youtube.com/watch?v=dQw4w9WgXcQ&t=245");+ }++ #[test]+ fn allowlists_safe_handoff_documents_and_rejects_executables() {+ for safe in ["report.pdf", "notes.txt", "slides.pptx", "budget.xlsx", "photo.png", "clip.mp4"] {+ assert!(is_safe_handoff_document(safe), "{safe} should be allowed");+ }+ for unsafe_name in [+ "setup.exe",+ "installer.msi",+ "script.bat",+ "run.ps1",+ "archive.zip",+ "app.apk",+ "README",+ ".bashrc",+ ] {+ assert!(!is_safe_handoff_document(unsafe_name), "{unsafe_name} must be rejected");+ }+ }+}diff --git a/core/nectarlink-core/src/lib.rs b/core/nectarlink-core/src/lib.rsindex 561f24c..d4d8950 100644--- a/core/nectarlink-core/src/lib.rs+++ b/core/nectarlink-core/src/lib.rs@@ -18,6 +18,7 @@ pub mod deck;mod error;mod events;pub mod features;+pub mod handoff;mod identity;pub mod localsend;mod media;@@ -58,6 +59,10 @@ pub use events::{ConnectionPath, DiscoveredDevice, LinkState, NodeEvent, PairedDevice, PairingEvent, PairingFailure,};pub use features::{CapabilityMatrix, FeatureState};+pub use handoff::{+ HandoffKind, HandoffLink, address_to_geo_uri, extract_handoff_link, format_video_timestamp,+ geo_to_maps_https, is_safe_handoff_document, parse_video_timestamp, with_video_timestamp,+};pub use identity::{KeyProtector, PlainKeyProtector, default_protector};pub use localsend::{LOCALSEND_DEFAULT_PORT, LOCALSEND_MULTICAST_ADDR, LOCALSEND_PROTOCOL_VERSION, LocalSendPeer,@@ -74,13 +79,14 @@ pub use nectarlink_protocol::{AudioOutputDevice, Battery, CLIP_MAX_BYTES, CallControls, CallLogEntry, CallState,CameraCaptureCancel, CameraCaptureMode, CameraCaptureOk, CameraCaptureRequest,CameraCaptureResultMeta, Contact, ContactNumber, DeviceInfo, DeviceKind, LivePoint, LiveSegment,- MediaPlayer, MirrorAudioConfig, MirrorConfig, MirrorInput, MirrorResize, MirrorStart, Notification,- NotificationAction, NotificationChatMessage, NotificationConversation, NotificationLive, PcAudioSet,- PcWakeInfo, PhoneApp, PhoneToggleSet, PhoneToggleValue, PhoneToggles, PhotoAlbum, PhotoItem,- PhotoNew as Photo, PhotoThumb, PowerLevel, ScreenCorners, ScreenRect, ScreenShape, SmsAttachment,- SmsMessage, SmsPart, SmsThread, StorageChanged, StorageDelete, StorageEntries, StorageEntry,- StorageList, StorageMkdir, StorageRead, StorageReadMeta, StorageRename, StorageWriteAccept,- StorageWriteDone, StorageWriteOffer, TaskNotify, TouchAction, WebcamConfig, WebcamStart,+ MediaPlayer, MirrorAudioConfig, MirrorConfig, MirrorInput, MirrorPower, MirrorResize, MirrorStart,+ Notification, NotificationAction, NotificationChatMessage, NotificationConversation,+ NotificationLive, PcAudioSet, PcWakeInfo, PhoneApp, PhoneToggleSet, PhoneToggleValue, PhoneToggles,+ PhotoAlbum, PhotoItem, PhotoNew as Photo, PhotoThumb, PowerLevel, ScreenCorners, ScreenRect,+ ScreenShape, SmsAttachment, SmsMessage, SmsPart, SmsThread, StorageChanged, StorageDelete,+ StorageEntries, StorageEntry, StorageList, StorageMkdir, StorageRead, StorageReadMeta, StorageRename,+ StorageWriteAccept, StorageWriteDone, StorageWriteOffer, TaskNotify, TouchAction, WebcamConfig,+ WebcamStart,calls::{CONTROL as CALLS_CONTROL, DIAL as CALLS_DIAL, IN_CALL as CALLS_IN_CALL, LOG as CALLS_LOG,SHOW as CALLS_SHOW, STATE as CALLS_STATE,diff --git a/core/nectarlink-core/src/localsend.rs b/core/nectarlink-core/src/localsend.rsindex e9874ed..9f58b02 100644--- a/core/nectarlink-core/src/localsend.rs+++ b/core/nectarlink-core/src/localsend.rs@@ -960,6 +960,7 @@ async fn handle_prepare_upload(state: TransferState::Requested,recording: false,markers: Vec::new(),+ open_on_arrival: false,};let cancel = CancellationToken::new();@@ -1297,6 +1298,7 @@ pub(crate) async fn send_files(state: TransferState::Waiting,recording: false,markers: Vec::new(),+ open_on_arrival: false,};let cancel = CancellationToken::new();diff --git a/core/nectarlink-core/src/mirror.rs b/core/nectarlink-core/src/mirror.rsindex 0aecb03..540a84c 100644--- a/core/nectarlink-core/src/mirror.rs+++ b/core/nectarlink-core/src/mirror.rs@@ -23,8 +23,8 @@ use iroh::endpoint::{RecvStream, SendStream, VarInt};use nectarlink_protocol::{DeviceId, Envelope, ErrorCode, PacketKind,messages::{- MirrorAudioConfig, MirrorConfig, MirrorInput, MirrorResize, MirrorSession, MirrorStart, PhoneApp,- PhoneApps, StreamHeader, mirror, types,+ MirrorAudioConfig, MirrorConfig, MirrorInput, MirrorPower, MirrorResize, MirrorSession, MirrorStart,+ PhoneApp, PhoneApps, StreamHeader, mirror, types,},read_video_packet, video_packet_header, write_frame,};@@ -131,6 +131,20 @@ pub(crate) async fn resize(session.send(Envelope::new(types::MIRROR_RESIZE, &msg)?).await}+/// Update `stay_awake` and `screen_off` on a phone while mirroring its screen (`session == 0`).+pub(crate) async fn power(+ shared: &Shared,+ session: &Session,+ stay_awake: bool,+ screen_off: bool,+) -> Result<()> {+ if !shared.toggle_on(&session.peer, TOGGLE) {+ return Err(Error::Denied);+ }+ let msg = MirrorPower { stay_awake, screen_off };+ session.send(Envelope::new(types::MIRROR_POWER, &msg)?).await+}+/// The apps a phone can open in windows of their own, by name.pub(crate) async fn apps(shared: &Shared, session: &Session) -> Result<Vec<PhoneApp>> {if !shared.toggle_on(&session.peer, TOGGLE) {@@ -306,6 +320,7 @@ pub(crate) async fn handle(shared: &Arc<Shared>, session: &Arc<Session>, env: &Elet MirrorSession { session: mirroring } = env.body()?;// The PC's side: stop showing; the phone's: stop sharing.shared.stop_showing(&peer, mirroring);+ shared.emit(NodeEvent::Mirroring { device: peer, session: mirroring, on: false });tokio::task::spawn_blocking(move || platform.mirror_stop_requested(&peer, mirroring));session.send(Envelope::empty(types::OK).reply_to(env.id)).await?;}@@ -323,6 +338,16 @@ pub(crate) async fn handle(shared: &Arc<Shared>, session: &Arc<Session>, env: &E});}}+ types::MIRROR_POWER => {+ let power: MirrorPower = env.body()?;+ let allowed = shared.toggle_on(&peer, TOGGLE)+ && shared.local_capabilities().iter().any(|c| c == mirror::CAPTURE);+ if allowed {+ tokio::task::spawn_blocking(move || {+ platform.mirror_power_requested(&peer, power.stay_awake, power.screen_off);+ });+ }+ }types::MIRROR_INPUT => {let input: MirrorInput = env.body()?;let MirrorSession { session: mirroring } = env.body()?;diff --git a/core/nectarlink-core/src/node.rs b/core/nectarlink-core/src/node.rsindex bdf8cc5..b9b1b60 100644--- a/core/nectarlink-core/src/node.rs+++ b/core/nectarlink-core/src/node.rs@@ -1034,6 +1034,16 @@ impl Node {transfer::send(&self.shared, peer, files).await}+ /// Hands off a document to a paired device and asks the receiver to open it+ /// with the default application once it arrives (`docs/protocol/files.md`).+ pub async fn send_handoff_files(+ &self,+ peer: DeviceId,+ files: Vec<transfer::OutgoingFile>,+ ) -> Result<String> {+ transfer::send_handoff(&self.shared, peer, files).await+ }+/// Sends a voice recording and its markers to a paired PC; returns the/// transfer's ID. Progress and the outcome arrive as/// [`NodeEvent::Transfer`]; the transfer waits for the PC to connect and@@ -1316,6 +1326,12 @@ impl Node {crate::mirror::resize(&self.shared, &session, mirroring, width, height).await}+ /// Updates `stay_awake` and `screen_off` while mirroring a phone's screen (`session == 0`).+ pub async fn mirror_power(&self, peer: DeviceId, stay_awake: bool, screen_off: bool) -> Result<()> {+ let session = self.connected(&peer)?;+ crate::mirror::power(&self.shared, &session, stay_awake, screen_off).await+ }+/// The PC's mouse and keyboard on a phone's mirrored screen or app window.pub async fn mirror_input(&self,@@ -2067,6 +2083,36 @@ impl Node {Ok(entry)}+ /// Records a custom local timeline entry (e.g. a saved mirror screenshot or+ /// mirror video recording) and emits [`NodeEvent::TimelineChanged`].+ #[allow(clippy::too_many_arguments)]+ pub fn record_timeline(+ &self,+ kind: crate::TimelineKind,+ peer: DeviceId,+ incoming: bool,+ title: String,+ detail: String,+ target: String,+ size_bytes: u64,+ duration_secs: u64,+ ref_id: Option<String>,+ ) -> Option<i64> {+ self.shared.record_timeline(crate::timeline::NewTimelineEntry {+ kind,+ device_id: peer,+ device_name: self.shared.peer_name(&peer),+ incoming,+ timestamp: crate::now_unix(),+ title,+ detail,+ target,+ size_bytes,+ duration_secs,+ ref_id,+ })+ }+/// Updates a timeline entry matching `ref_id` (e.g. when a photo or voice/// recording finishes post-processing into its final destination).pub fn update_timeline_by_ref(diff --git a/core/nectarlink-core/src/transfer.rs b/core/nectarlink-core/src/transfer.rsindex 2cc6a1b..440a1b6 100644--- a/core/nectarlink-core/src/transfer.rs+++ b/core/nectarlink-core/src/transfer.rs@@ -112,6 +112,9 @@ pub struct Transfer {pub recording: bool,/// Timestamped markers placed during the recording.pub markers: Vec<RecordingMarker>,+ /// True when the sender handed off a single document that should open with+ /// the default app once it arrives (`docs/protocol/files.md`).+ pub open_on_arrival: bool,}/// Never prints file names (protocol v0 §11).@@ -127,6 +130,7 @@ impl std::fmt::Debug for Transfer {.field("state", &self.state).field("recording", &self.recording).field("markers", &self.markers.len())+ .field("open_on_arrival", &self.open_on_arrival).finish()}}@@ -354,7 +358,20 @@ fn transfer_timeline_detail(entries: &[FileEntry], recording: bool, markers: &[R/// Starts sending files; progress and the outcome arrive as/// [`NodeEvent::Transfer`]. Returns the transfer's ID.pub(crate) async fn send(shared: &Arc<Shared>, peer: DeviceId, files: Vec<OutgoingFile>) -> Result<String> {- send_inner(shared, peer, files, false, false, Vec::new()).await+ send_inner(shared, peer, files, false, false, Vec::new(), false).await+}++/// Starts sending a handed-off document that should open with the default app+/// on the receiving device once it arrives (`docs/protocol/files.md`).+pub(crate) async fn send_handoff(+ shared: &Arc<Shared>,+ peer: DeviceId,+ files: Vec<OutgoingFile>,+) -> Result<String> {+ let open_on_arrival = files.len() == 1+ && files[0].folder.is_none()+ && crate::handoff::is_safe_handoff_document(&files[0].name);+ send_inner(shared, peer, files, false, false, Vec::new(), open_on_arrival).await}/// Starts sending photos requested via `photos.get`.@@ -363,7 +380,7 @@ pub(crate) async fn send_photos_files(peer: DeviceId,files: Vec<OutgoingFile>,) -> Result<String> {- send_inner(shared, peer, files, false, true, Vec::new()).await+ send_inner(shared, peer, files, false, true, Vec::new(), false).await}/// Starts sending a voice recording and its markers (`docs/protocol/recorder.md`);@@ -376,7 +393,7 @@ pub(crate) async fn send_recording() -> Result<String> {file.folder = None;let clean_markers = sanitize_markers(markers);- send_inner(shared, peer, vec![file], true, false, clean_markers).await+ send_inner(shared, peer, vec![file], true, false, clean_markers, false).await}fn sanitize_markers(markers: Vec<RecordingMarker>) -> Vec<RecordingMarker> {@@ -424,6 +441,7 @@ async fn send_inner(recording: bool,is_photo: bool,markers: Vec<RecordingMarker>,+ open_on_arrival: bool,) -> Result<String> {if files.is_empty() || files.len() > files::MAX_FILES || (recording && files.len() != 1) {return Err(Error::Protocol("send between 1 and 5000 files".into()));@@ -463,10 +481,21 @@ async fn send_inner(}let entries: Vec<FileEntry> = opened.iter().map(|(entry, _)| entry.clone()).collect();let id = new_id();+ let open_on_arrival = open_on_arrival+ && !recording+ && entries.len() == 1+ && entries[0].folder.is_none()+ && crate::handoff::is_safe_handoff_document(&entries[0].name);// The whole offer has to fit in one frame.let offer = Envelope::new(files::OFFER,- &FilesOffer { id: id.clone(), files: entries.clone(), recording, markers: markers.clone() },+ &FilesOffer {+ id: id.clone(),+ files: entries.clone(),+ recording,+ markers: markers.clone(),+ open_on_arrival,+ },).map_err(|e| Error::Protocol(e.to_string()))?;if offer.to_cbor().len() > nectarlink_protocol::MAX_FRAME_LEN {@@ -483,9 +512,14 @@ async fn send_inner(state: TransferState::Waiting,recording,markers,+ open_on_arrival,};let id = transfer.id.clone();- let tl_detail = transfer_timeline_detail(&entries, recording, &transfer.markers);+ let tl_detail = if open_on_arrival {+ "Handoff document".into()+ } else {+ transfer_timeline_detail(&entries, recording, &transfer.markers)+ };let tl_target = source_targets.join("\n");let tl_kind = if recording {crate::TimelineKind::Recording@@ -590,6 +624,7 @@ async fn attempt(files: files.iter().map(|(entry, _)| entry.clone()).collect(),recording: reporter.transfer.recording,markers: reporter.transfer.markers.clone(),+ open_on_arrival: reporter.transfer.open_on_arrival,};let (Ok(header), Ok(offer)) =(Envelope::new(types::STREAM, &header), Envelope::new(files::OFFER, &offer))@@ -828,6 +863,11 @@ async fn receive(shared: Arc<Shared>, peer: DeviceId, mut send: SendStream, mutlet cancel = CancellationToken::new();shared.register_transfer(&offer.id, cancel.clone());+ let open_on_arrival = offer.open_on_arrival+ && !offer.recording+ && offer.files.len() == 1+ && offer.files[0].folder.is_none()+ && crate::handoff::is_safe_handoff_document(&offer.files[0].name);let transfer = Transfer {id: offer.id.clone(),device: peer,@@ -839,6 +879,7 @@ async fn receive(shared: Arc<Shared>, peer: DeviceId, mut send: SendStream, mutstate: TransferState::Running,recording: offer.recording,markers: offer.markers.clone(),+ open_on_arrival,};let mut reporter = Reporter::new(shared.clone(), transfer);reporter.set(TransferState::Running);@@ -862,6 +903,8 @@ async fn receive(shared: Arc<Shared>, peer: DeviceId, mut send: SendStream, mut1 => "Photo".into(),n => format!("{n} photos"),}+ } else if open_on_arrival {+ "Handoff document".into()} else {transfer_timeline_detail(&offer.files, offer.recording, &offer.markers)};diff --git a/core/nectarlink-core/tests/two_devices.rs b/core/nectarlink-core/tests/two_devices.rsindex ab33a93..e4119df 100644--- a/core/nectarlink-core/tests/two_devices.rs+++ b/core/nectarlink-core/tests/two_devices.rs@@ -134,6 +134,9 @@ impl Platform for RecordingPlatform {) {self.mirror_asks.lock().unwrap().push(format!("resize {session} {width}x{height}"));}+ fn mirror_power_requested(&self, _peer: &nectarlink_core::DeviceId, stay_awake: bool, screen_off: bool) {+ self.mirror_asks.lock().unwrap().push(format!("power awake={stay_awake} off={screen_off}"));+ }fn mirror_input(&self,_peer: &nectarlink_core::DeviceId,@@ -1578,6 +1581,8 @@ async fn the_phone_screen_streams_to_the_pc() {audio: true,session: 0,app: None,+ stay_awake: false,+ screen_off: false,};with_timeout("start", pc.node.mirror_start(phone_id, options)).await.unwrap();assert_eq!(*phone.platform.mirror_asks.lock().unwrap(), ["start 1920 with sound"]);@@ -1629,6 +1634,7 @@ async fn the_phone_screen_streams_to_the_pc() {assert_eq!(screen.got.lock().unwrap()[3..], ["sound 48000 Hz x2", "sound 10000 1920"]);pc.node.mirror_keyframe(phone_id, 0).await;+ pc.node.mirror_power(phone_id, true, true).await.unwrap();// The PC's mouse on the phone's screen; nonsense never leaves the PC.use nectarlink_core::{MirrorInput, TouchAction};pc.node@@ -1663,7 +1669,8 @@ async fn the_phone_screen_streams_to_the_pc() {}assert!(sound.is_closed(), "and its sound stream");let asks = phone.platform.mirror_asks.lock().unwrap().clone();- for wanted in ["keyframe 0", "Touch(Down) on 0", "Key(back) on 0", "stop 0"] {+ for wanted in ["keyframe 0", "power awake=true off=true", "Touch(Down) on 0", "Key(back) on 0", "stop 0"]+ {assert!(asks.iter().any(|a| a == wanted), "{wanted}: {asks:?}");}let shown = pc.platform.mirror_asks.lock().unwrap().clone();@@ -1684,6 +1691,8 @@ async fn phone_apps_open_in_windows_of_their_own() {audio: false,session,app: Some("com.example.chat".into()),+ stay_awake: false,+ screen_off: false,};// Not Elevated yet: no apps, no app windows.diff --git a/core/nectarlink-ffi/src/lib.rs b/core/nectarlink-ffi/src/lib.rsindex 5069f42..87cd3e3 100644--- a/core/nectarlink-ffi/src/lib.rs+++ b/core/nectarlink-ffi/src/lib.rs@@ -518,6 +518,9 @@ pub struct Transfer {pub recording: bool,/// Markers captured during the recording.pub markers: Vec<RecordingMarker>,+ /// True when the sender handed off a single document that should open with+ /// the default app once it arrives (`docs/protocol/files.md`).+ pub open_on_arrival: bool,}/// Never prints file names (protocol v0 §11).@@ -1044,6 +1047,10 @@ pub struct MirrorOptions {pub session: u32,/// The app (package name) to show in a window of its own.pub app: Option<String>,+ /// Keep the phone awake while mirroring (`session == 0`).+ pub stay_awake: bool,+ /// Turn the phone's physical screen off while mirroring (`session == 0`, Elevated).+ pub screen_off: bool,}/// An app a PC can open in a window (docs/protocol/mirror.md).@@ -2021,6 +2028,7 @@ impl From<core::Transfer> for Transfer {},recording: t.recording,markers: t.markers.into_iter().map(Into::into).collect(),+ open_on_arrival: t.open_on_arrival,}}}@@ -2345,6 +2353,8 @@ pub trait Platform: Send + Sync {fn mirror_keyframe_requested(&self, pc_id: String, session: u32);/// The PC resized an app window (`session` != 0) to `width × height`.fn mirror_resize_requested(&self, pc_id: String, session: u32, width: u32, height: u32);+ /// The PC updated `stay_awake` or `screen_off` while mirroring the screen (`session == 0`).+ fn mirror_power_requested(&self, pc_id: String, stay_awake: bool, screen_off: bool);/// The PC's mouse or keyboard on the mirrored screen (only while this/// phone offers `mirror.input`) or an app window. Return quickly.fn mirror_input(&self, pc_id: String, session: u32, input: MirrorInputEvent);@@ -2481,6 +2491,8 @@ impl core::Platform for PlatformAdapter {audio: options.audio,session: options.session,app: options.app.clone(),+ stay_awake: options.stay_awake,+ screen_off: options.screen_off,};if self.0.mirror_requested(peer.to_string(), options) {Ok(())@@ -2497,6 +2509,9 @@ impl core::Platform for PlatformAdapter {fn mirror_resize_requested(&self, peer: &DeviceId, session: u32, width: u32, height: u32) {self.0.mirror_resize_requested(peer.to_string(), session, width, height);}+ fn mirror_power_requested(&self, peer: &DeviceId, stay_awake: bool, screen_off: bool) {+ self.0.mirror_power_requested(peer.to_string(), stay_awake, screen_off);+ }fn mirror_input(&self, peer: &DeviceId, session: u32, input: core::MirrorInput) {self.0.mirror_input(peer.to_string(), session, input.into());}@@ -2948,6 +2963,15 @@ impl NectarlinkNode {self.run(async move { Ok(node.send_files(id, files).await?) }).await}+ /// Hands off a document to a paired PC and asks the PC to open it with the+ /// default application once it arrives (`docs/protocol/files.md`).+ pub async fn send_handoff_files(&self, id: String, files: Vec<FileToSend>) -> Result<String> {+ let id = parse_id(&id)?;+ let files = files.into_iter().map(file_to_send).collect::<Result<Vec<_>>>()?;+ let node = self.node.clone();+ self.run(async move { Ok(node.send_handoff_files(id, files).await?) }).await+ }+/// Sends a voice recording and its markers to a paired PC; returns the/// transfer's ID. Progress arrives as `Event::Transfer`.pub async fn send_recording(@@ -3413,6 +3437,17 @@ impl NectarlinkNode {self.run(async move { Ok(Arc::new(MirrorStream(node.mirror_open_audio(id).await?))) }).await}+ /// Tells a paired PC that mirroring or remote keyboard input on `session` has stopped (`mirror.stop`).+ pub async fn mirror_stop(&self, pc_id: String, session: u32) -> Result<()> {+ let id = parse_id(&pc_id)?;+ let node = self.node.clone();+ self.run(async move {+ node.mirror_stop(id, session).await;+ Ok(())+ })+ .await+ }+/// Opens this phone's camera stream to a paired PC (`docs/protocol/webcam.md`).pub async fn webcam_open(&self, pc_id: String) -> Result<Arc<MirrorStream>> {let id = parse_id(&pc_id)?;@@ -3613,6 +3648,73 @@ pub fn maps_web_url(address: String) -> String {core::maps_web_url(&address)}+/// Kind of rich Handoff link (`docs/protocol/actions.md`).+#[derive(Debug, Clone, Copy, PartialEq, Eq, uniffi::Enum)]+pub enum HandoffKind {+ WebLink,+ VideoLink,+ MapLocation,+}++impl From<core::HandoffKind> for HandoffKind {+ fn from(k: core::HandoffKind) -> Self {+ match k {+ core::HandoffKind::WebLink => HandoffKind::WebLink,+ core::HandoffKind::VideoLink => HandoffKind::VideoLink,+ core::HandoffKind::MapLocation => HandoffKind::MapLocation,+ }+ }+}++/// Rich Handoff link metadata extracted from a URL, `geo:` URI, or shared text.+#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)]+pub struct HandoffLink {+ pub kind: HandoffKind,+ pub url: String,+ pub label: String,+ pub timestamp_secs: Option<u32>,+ pub map_query: Option<String>,+}++impl From<core::HandoffLink> for HandoffLink {+ fn from(h: core::HandoffLink) -> Self {+ HandoffLink {+ kind: h.kind.into(),+ url: h.url,+ label: h.label,+ timestamp_secs: h.timestamp_secs,+ map_query: h.map_query,+ }+ }+}++/// Extracts and classifies a Handoff link (`http://`, `https://`, or `geo:`)+/// from a URL or shared text snippet.+#[uniffi::export]+pub fn extract_handoff_link(text: String) -> Option<HandoffLink> {+ core::extract_handoff_link(&text).map(Into::into)+}++/// Attaches or updates a playback timestamp (`?t=123` / `&t=123s`) on a+/// YouTube, Vimeo, or direct video link.+#[uniffi::export]+pub fn with_video_timestamp(url: String, seconds: u32) -> String {+ core::with_video_timestamp(&url, seconds)+}++/// Converts a `geo:` URI into a Google Maps `https://` URL.+#[uniffi::export]+pub fn geo_to_maps_https(uri: String) -> Option<String> {+ core::geo_to_maps_https(&uri)+}++/// Returns true when `name` is a safe document/media file (not an executable or+/// script) that may be opened automatically on arrival.+#[uniffi::export]+pub fn is_safe_handoff_document(name: String) -> bool {+ core::is_safe_handoff_document(&name)+}+/// Sends core logs to the platform log (logcat on Android). Call once,/// before starting the node. `filter` uses tracing's syntax, e.g. "info".#[uniffi::export]diff --git a/core/nectarlink-protocol/src/messages.rs b/core/nectarlink-protocol/src/messages.rsindex 3485bfd..3dfb0ea 100644--- a/core/nectarlink-protocol/src/messages.rs+++ b/core/nectarlink-protocol/src/messages.rs@@ -66,6 +66,7 @@ pub mod types {pub const SMS_CHANGED: &str = "sms.changed";pub const MIRROR_START: &str = "mirror.start";pub const MIRROR_STOP: &str = "mirror.stop";+ pub const MIRROR_POWER: &str = "mirror.power";pub const MIRROR_KEYFRAME: &str = "mirror.keyframe";pub const MIRROR_RESIZE: &str = "mirror.resize";pub const MIRROR_INPUT: &str = "mirror.input";@@ -1220,6 +1221,12 @@ pub struct MirrorStart {/// instead of the phone's screen (with a session other than SCREEN).#[serde(default, skip_serializing_if = "Option::is_none")]pub app: Option<String>,+ /// Keep the phone awake while mirroring its screen (`session == SCREEN`).+ #[serde(default, skip_serializing_if = "std::ops::Not::not")]+ pub stay_awake: bool,+ /// Turn the phone's physical screen off while mirroring (`session == SCREEN`, Elevated).+ #[serde(default, skip_serializing_if = "std::ops::Not::not")]+ pub screen_off: bool,}impl MirrorStart {@@ -1227,11 +1234,23 @@ impl MirrorStart {pub fn is_valid(&self) -> bool {match &self.app {None => self.session == mirror::SCREEN,- Some(app) => self.session != mirror::SCREEN && is_package_name(app),+ Some(app) => {+ self.session != mirror::SCREEN && is_package_name(app) && !self.stay_awake && !self.screen_off+ }}}}+/// Body of `mirror.power`: change `stay_awake` or `screen_off` while mirroring+/// the phone's screen (`session == SCREEN`).+#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]+pub struct MirrorPower {+ #[serde(default)]+ pub stay_awake: bool,+ #[serde(default)]+ pub screen_off: bool,+}+/// Which mirroring a `mirror.stop`, `mirror.keyframe` or `mirror.input` is/// about (its body, or part of it; missing means the screen).#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]@@ -1321,8 +1340,24 @@ pub mod mirror_keys {pub const DOWN: &str = "down";pub const TAB: &str = "tab";pub const NOTIFICATIONS: &str = "notifications";- pub const ALL: &[&str] =- &[BACK, HOME, RECENTS, ENTER, BACKSPACE, DELETE, LEFT, RIGHT, UP, DOWN, TAB, NOTIFICATIONS];+ pub const KEYBOARD_ON: &str = "keyboard_on";+ pub const KEYBOARD_OFF: &str = "keyboard_off";+ pub const ALL: &[&str] = &[+ BACK,+ HOME,+ RECENTS,+ ENTER,+ BACKSPACE,+ DELETE,+ LEFT,+ RIGHT,+ UP,+ DOWN,+ TAB,+ NOTIFICATIONS,+ KEYBOARD_ON,+ KEYBOARD_OFF,+ ];}/// `mirror.input`: the input's fields, and the session when it isn't the@@ -2563,6 +2598,10 @@ pub struct FilesOffer {/// Timestamped markers placed during the recording.#[serde(default, skip_serializing_if = "Vec::is_empty")]pub markers: Vec<RecordingMarker>,+ /// True when the sender asked the receiver to open this single safe document+ /// with the OS default application once it finishes arriving (Rich Handoff).+ #[serde(default, skip_serializing_if = "std::ops::Not::not")]+ pub open_on_arrival: bool,}/// Never prints file names (protocol v0 §11).@@ -2573,6 +2612,7 @@ impl std::fmt::Debug for FilesOffer {.field("files", &self.files.len()).field("recording", &self.recording).field("markers", &self.markers.len())+ .field("open_on_arrival", &self.open_on_arrival).finish()}}@@ -4064,6 +4104,7 @@ mod tests {files: names.iter().map(|n| FileEntry { name: (*n).into(), size: 1, folder: None }).collect(),recording: false,markers: Vec::new(),+ open_on_arrival: false,};assert!(offer("abcdefghijklmnop", &["photo.jpg", "Résumé (final).pdf"]).is_valid());for bad in ["", ".", "..", "a/b", "a\\b", "x\u{0}y", "tab\there"] {@@ -4082,6 +4123,7 @@ mod tests {files: vec![FileEntry { name: "a.jpg".into(), size: 1, folder: Some(folder.into()) }],recording: false,markers: Vec::new(),+ open_on_arrival: false,};for good in ["Trip", "Trip/Day 1", "Trip/Day 1/raw"] {assert!(offer(good).is_valid(), "{good:?}");@@ -4107,6 +4149,7 @@ mod tests {RecordingMarker { at_ms: 1200, label: None },RecordingMarker { at_ms: 5400, label: Some("Action item".into()) },],+ open_on_arrival: false,};assert!(rec.is_valid());assert!(!format!("{:?}", rec.markers[1]).contains("Action item"));diff --git a/desktop/app/build.rs b/desktop/app/build.rsindex 0264b7e..c6e6026 100644--- a/desktop/app/build.rs+++ b/desktop/app/build.rs@@ -20,6 +20,7 @@ const QML: &[&str] = &["qml/LaserOverlay.qml","qml/MainWindow.qml","qml/MirrorWindow.qml",+ "qml/ShelfWindow.qml","qml/components/AppsSheet.qml","qml/components/Avatar.qml","qml/components/Button.qml",diff --git a/desktop/app/cpp/app_helpers.cpp b/desktop/app/cpp/app_helpers.cppindex d352cc1..9e45d22 100644--- a/desktop/app/cpp/app_helpers.cpp+++ b/desktop/app/cpp/app_helpers.cpp@@ -3,8 +3,12 @@#include "video_view.h"#include <QtCore/QDir>+#include <QtCore/QFileInfo>+#include <QtCore/QMimeData>#include <QtCore/QPointer>+#include <QtCore/QUrl>#include <QtCore/QtEnvironmentVariables>+#include <QtGui/QDrag>#include <QtGui/QFontDatabase>#include <QtGui/QGuiApplication>#include <QtGui/QIcon>@@ -111,4 +115,34 @@ void trim_memory_caches()#endif}+bool start_external_drag(rust::Str file_path, rust::Str text_fallback)+{+ const QString path = QString::fromUtf8(file_path.data(), static_cast<qsizetype>(file_path.size())).trimmed();+ const QString text = QString::fromUtf8(text_fallback.data(), static_cast<qsizetype>(text_fallback.size()));+ if (path.isEmpty() && text.isEmpty())+ return false;++ auto *mime = new QMimeData();+ QPixmap dragPixmap;+ if (!path.isEmpty() && QFileInfo::exists(path)) {+ mime->setUrls({QUrl::fromLocalFile(path)});+ QImage img(path);+ if (!img.isNull()) {+ mime->setImageData(img);+ dragPixmap = QPixmap::fromImage(img.scaled(96, 96, Qt::KeepAspectRatio, Qt::SmoothTransformation));+ }+ } else if (!text.isEmpty()) {+ mime->setText(text);+ } else {+ delete mime;+ return false;+ }++ QDrag drag(QGuiApplication::instance());+ drag.setMimeData(mime);+ if (!dragPixmap.isNull())+ drag.setPixmap(dragPixmap);+ return drag.exec(Qt::CopyAction) != Qt::IgnoreAction;+}+diff --git a/desktop/app/cpp/app_helpers.h b/desktop/app/cpp/app_helpers.hindex c5ab391..6c279e4 100644--- a/desktop/app/cpp/app_helpers.h+++ b/desktop/app/cpp/app_helpers.h@@ -32,5 +32,9 @@ void trim_memory_caches();void register_qml_engine(QQmlEngine *engine);void register_qml_app_engine(QQmlApplicationEngine &engine);+// Starts an OS-level drag-and-drop operation for a local file or text fallback+// so items dragged out of the Shelf can be dropped into Explorer or any app.+bool start_external_drag(rust::Str file_path, rust::Str text_fallback);+diff --git a/desktop/app/qml/App.qml b/desktop/app/qml/App.qmlindex a7d1d0c..7a4f79b 100644--- a/desktop/app/qml/App.qml+++ b/desktop/app/qml/App.qml@@ -21,20 +21,37 @@ QtObject {active: AppController.laserActivesource: active ? "qrc:/qt/qml/app/nectarlink/qml/LaserOverlay.qml" : ""}- // 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.- readonly property ListModel mirrorWindows: ListModel {}- readonly property Instantiator mirrorInstantiator: Instantiator {- model: app.mirrorWindows- delegate: Loader {- required property string key- Component.onCompleted: setSource("qrc:/qt/qml/app/nectarlink/qml/MirrorWindow.qml", { mirrorKey: key })+ property var shelfWindow: null+ readonly property Component shelfWindowComponent: Component {+ ShelfWindow {}+ }++ function syncShelfWindow() {+ if (AppController.shelfOpen) {+ trayTrimTimer.stop()+ if (!app.shelfWindow) {+ const w = shelfWindowComponent.createObject(app)+ if (w) {+ app.shelfWindow = w+ } else {+ console.warn("ShelfWindow createObject failed:", shelfWindowComponent.errorString())+ }+ }+ } else {+ if (app.shelfWindow) {+ app.shelfWindow.destroy()+ app.shelfWindow = null+ }+ if (!app.mainWindow && Object.keys(app.openMirrors).length === 0)+ trayTrimTimer.restart()}}- readonly property Connections mirrorSync: Connections {- target: Mirror- function onWindowsChanged() { app.syncMirrorWindows() }++ // A window for each phone screen or app being mirrored. Keyed by+ // `mirrorKey`, so a window lives as long as its mirroring.+ property var openMirrors: ({})+ readonly property Component mirrorWindowComponent: Component {+ MirrorWindow {}}function syncMirrorWindows() {@@ -42,18 +59,25 @@ QtObject {try {keys = JSON.parse(Mirror.windows).map(w => w.key)} catch (e) {}- for (let i = mirrorWindows.count - 1; i >= 0; i--) {- if (keys.indexOf(mirrorWindows.get(i).key) < 0)- mirrorWindows.remove(i)+ const current = app.openMirrors+ for (const k of Object.keys(current)) {+ if (keys.indexOf(k) < 0) {+ if (current[k])+ current[k].destroy()+ delete current[k]+ }}for (const key of keys) {- let known = false- for (let i = 0; i < mirrorWindows.count; i++)- known = known || mirrorWindows.get(i).key === key- if (!known)- mirrorWindows.append({ key: key })+ if (!current[key]) {+ const w = mirrorWindowComponent.createObject(app, { mirrorKey: key })+ if (w) {+ current[key] = w+ } else {+ console.warn("MirrorWindow createObject failed:", mirrorWindowComponent.errorString())+ }+ }}- if (!app.mainWindow && mirrorWindows.count === 0)+ if (!app.mainWindow && Object.keys(current).length === 0 && !AppController.shelfOpen)trayTrimTimer.restart()}readonly property bool startMinimized: Qt.application.arguments.indexOf("--minimized") >= 0@@ -62,7 +86,7 @@ QtObject {readonly property Timer trayTrimTimer: Timer {interval: 350onTriggered: {- if (!app.mainWindow && app.mirrorWindows.count === 0) {+ if (!app.mainWindow && Object.keys(app.openMirrors).length === 0 && !AppController.shelfOpen) {gc()AppController.trimWorkingSet()}@@ -93,6 +117,10 @@ QtObject {}Component.onCompleted: {+ Mirror.windowsChanged.connect(app.syncMirrorWindows)+ AppController.shelfOpenChanged.connect(app.syncShelfWindow)+ app.syncMirrorWindows()+ app.syncShelfWindow()if (!startMinimized)showMain()else@@ -125,5 +153,8 @@ QtObject {app.mainWindow.flash()}}+ function onShelfOpenChanged() {+ app.syncShelfWindow()+ }}}diff --git a/desktop/app/qml/Icons.qml b/desktop/app/qml/Icons.qmlindex 32b752f..2a93018 100644--- a/desktop/app/qml/Icons.qml+++ b/desktop/app/qml/Icons.qml@@ -79,4 +79,8 @@ QtObject {readonly property string trash: "M4 7h16M10 11v6M14 11v6M6 7l1 12a2 2 0 0 0 2 2h6a2 2 0 0 0 2-2l1-12M9 7V4a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v3"readonly property string edit: "M16.5 3.5a2.1 2.1 0 0 1 3 3L7 19l-4 1 1-4L16.5 3.5z"readonly property string pin: "M12 17v5M9 10.76a2 2 0 0 1-1.11 1.79l-1.78.9A2 2 0 0 0 5 15.24V16h14v-.76a2 2 0 0 0-1.11-1.79l-1.78-.9A2 2 0 0 1 15 10.76V7a1 1 0 0 1 1-1 1 1 0 0 0 1-1V4a1 1 0 0 0-1-1H8a1 1 0 0 0-1 1v1a1 1 0 0 0 1 1 1 1 0 0 1 1 1z"+ readonly property string record: "M12 6a6 6 0 1 0 0 12 6 6 0 0 0 0-12z"+ readonly property string stopSquare: "M7 7h10v10H7z"+ readonly property string screenOff: "M8 2h8a2 2 0 0 1 2 2v8M18 16v4a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2V6a2 2 0 0 1 .6-1.4M11 18h2M3 3l18 18"+ readonly property string coffee: "M17 8h1a4 4 0 1 1 0 8h-1M3 8h14v7a4 4 0 0 1-4 4H7a4 4 0 0 1-4-4V8zM6 2v3M10 2v3M14 2v3"}diff --git a/desktop/app/qml/MainWindow.qml b/desktop/app/qml/MainWindow.qmlindex f7ead27..75f6a32 100644--- a/desktop/app/qml/MainWindow.qml+++ b/desktop/app/qml/MainWindow.qml@@ -54,18 +54,30 @@ NativeWindow {target: Preferencesfunction onBackdropChanged() { window.followBackdrop() }}- Component.onCompleted: followBackdrop()- darkFrame: Theme.dark- captionHeight: Theme.topBarHeight-Connections {target: window- // Back from Settings, maybe with Windows notifications turned on.function onActiveChanged() {- if (window.active)+ if (window.active) {AppController.refreshToastsEnabled()+ if (!window.activeFocusItem && window.contentItem)+ window.contentItem.forceActiveFocus()+ }}+ function onActiveFocusItemChanged() {+ if (!window.activeFocusItem && window.contentItem)+ Qt.callLater(() => {+ if (!window.activeFocusItem && window.contentItem)+ window.contentItem.forceActiveFocus()+ })+ }+ }+ Component.onCompleted: {+ followBackdrop()+ if (!window.activeFocusItem && window.contentItem)+ window.contentItem.forceActiveFocus()}+ darkFrame: Theme.dark+ captionHeight: Theme.topBarHeightfunction openPairing() { pairingSheet.open() }diff --git a/desktop/app/qml/MirrorWindow.qml b/desktop/app/qml/MirrorWindow.qmlindex c8688bc..2295b3d 100644--- a/desktop/app/qml/MirrorWindow.qml+++ b/desktop/app/qml/MirrorWindow.qml@@ -158,10 +158,27 @@ Window {}}- // The keyboard: text goes into the phone's text field; a few keys- // have phone meanings.+ // The keyboard: shortcuts for screenshots and recording work even+ // without remote control; text and navigation keys go to the phone.Keys.onPressed: (event) => {- if (!win.canControl || win.phase !== "showing")+ if (win.phase !== "showing")+ return+ if ((event.modifiers & Qt.ControlModifier) && (event.modifiers & Qt.ShiftModifier) && event.key === Qt.Key_C) {+ Mirror.screenshotClipboard(win.mirrorKey)+ event.accepted = true+ return+ }+ if ((event.modifiers & Qt.ControlModifier) && !(event.modifiers & Qt.ShiftModifier) && event.key === Qt.Key_S) {+ Mirror.screenshotFile(win.mirrorKey)+ event.accepted = true+ return+ }+ if ((event.modifiers & Qt.ControlModifier) && !(event.modifiers & Qt.ShiftModifier) && event.key === Qt.Key_R) {+ Mirror.toggleRecording(win.mirrorKey)+ event.accepted = true+ return+ }+ if (!win.canControl)returnconst keys = {}keys[Qt.Key_Escape] = "back"@@ -190,30 +207,148 @@ Window {}}- // The phone's sound on this PC: on or off, shown while the mouse is- // over the window (and while it's off).+ property int recordingElapsedSecs: 0+ function updateRecordingElapsed() {+ if (win.info.recording === true && (win.info.recordingStartedMs || 0) > 0) {+ win.recordingElapsedSecs = Math.max(0, Math.floor((Date.now() - win.info.recordingStartedMs) / 1000))+ } else {+ win.recordingElapsedSecs = 0+ }+ }+ onInfoChanged: updateRecordingElapsed()++ Timer {+ interval: 1000+ repeat: true+ running: win.info.recording === true+ onTriggered: win.updateRecordingElapsed()+ }++ function formatDuration(secs) {+ const m = Math.floor(secs / 60)+ const s = secs % 60+ return (m < 10 ? "0" + m : "" + m) + ":" + (s < 10 ? "0" + s : "" + s)+ }++ // Floating mirror toolbar: screenshots, MP4 recording, stay awake, screen off, and audio mute.HoverHandler { id: hovering }Rectangle {+ id: toolbaranchors.top: parent.topanchors.right: parent.rightanchors.margins: 12- width: 40; height: 40+ width: toolbarRow.implicitWidth + 8+ height: 40radius: 20- color: Qt.rgba(0, 0, 0, 0.6)- visible: win.info.sound === true && win.phase === "showing"- opacity: hovering.hovered || Mirror.muted ? 1 : 0- Behavior on opacity { NumberAnimation { duration: Theme.fadeFast } }- IconButton {+ color: Qt.rgba(0, 0, 0, 0.68)+ visible: win.phase === "showing" && video.frameSize.width > 0+ readonly property bool toolbarHasFocus: copyShotBtn.activeFocus || saveShotBtn.activeFocus+ || recordBtn.activeFocus || stayAwakeBtn.activeFocus || screenOffBtn.activeFocus || soundBtn.activeFocus+ opacity: hovering.hovered || toolbarHover.hovered || Mirror.muted+ || win.info.recording === true || win.info.screenOff === true+ || win.info.stayAwake === true || toolbarHasFocus ? 1 : 0+ Behavior on opacity { enabled: !Theme.reduceMotion; NumberAnimation { duration: Theme.fadeFast } }++ HoverHandler { id: toolbarHover }++ Row {+ id: toolbarRowanchors.centerIn: parent- iconPath: Mirror.muted ? Icons.soundOff : Icons.speaker- iconColor: "white"- label: Mirror.muted ? qsTr("Play the phone's sound here") : qsTr("Mute the phone's sound here")- onClicked: Mirror.toggleSound()+ spacing: 2++ IconButton {+ id: copyShotBtn+ iconPath: Icons.copy+ iconColor: "white"+ label: qsTr("Copy screenshot (Ctrl+Shift+C)")+ onClicked: Mirror.screenshotClipboard(win.mirrorKey)+ }+ IconButton {+ id: saveShotBtn+ iconPath: Icons.camera+ iconColor: "white"+ label: qsTr("Save screenshot (Ctrl+S)")+ onClicked: Mirror.screenshotFile(win.mirrorKey)+ }+ IconButton {+ id: recordBtn+ iconPath: win.info.recording === true ? Icons.stopSquare : Icons.record+ iconColor: win.info.recording === true ? Theme.error : "white"+ label: win.info.recording === true ? qsTr("Stop recording (Ctrl+R)") : qsTr("Record video (Ctrl+R)")+ onClicked: Mirror.toggleRecording(win.mirrorKey)+ }+ Txt {+ visible: win.info.recording === true+ anchors.verticalCenter: parent.verticalCenter+ leftPadding: 2+ rightPadding: 6+ role: "code"+ size: 12+ color: "white"+ text: win.formatDuration(win.recordingElapsedSecs)+ }+ IconButton {+ id: stayAwakeBtn+ visible: !win.info.app+ iconPath: Icons.coffee+ iconColor: win.info.stayAwake === true ? Theme.primary : "white"+ label: win.info.stayAwake === true+ ? qsTr("Phone stays awake while mirroring (turn off)")+ : qsTr("Keep phone awake while mirroring")+ onClicked: Mirror.setStayAwake(win.mirrorKey, !(win.info.stayAwake === true))+ }+ IconButton {+ id: screenOffBtn+ visible: !win.info.app && win.info.canScreenOff === true+ iconPath: Icons.screenOff+ iconColor: win.info.screenOff === true ? Theme.primary : "white"+ label: win.info.screenOff === true+ ? qsTr("Turn phone screen back on")+ : qsTr("Turn phone screen off while mirroring")+ onClicked: Mirror.setScreenOff(win.mirrorKey, !(win.info.screenOff === true))+ }+ IconButton {+ id: soundBtn+ visible: win.info.sound === true+ iconPath: Mirror.muted ? Icons.soundOff : Icons.speaker+ iconColor: "white"+ label: Mirror.muted ? qsTr("Play the phone's sound here") : qsTr("Mute the phone's sound here")+ onClicked: Mirror.toggleSound()+ }+ }+ }++ // Brief confirmation pill for screenshots, recordings, and power toggles.+ Rectangle {+ id: noticePill+ anchors.horizontalCenter: parent.horizontalCenter+ anchors.bottom: hintBanner.visible ? hintBanner.top : parent.bottom+ anchors.bottomMargin: hintBanner.visible ? 8 : 16+ width: Math.min(parent.width - 24, noticeTxt.implicitWidth + 24)+ height: noticeTxt.implicitHeight + 12+ radius: height / 2+ color: Qt.rgba(0, 0, 0, 0.78)+ visible: opacity > 0+ opacity: (win.info.notice || "").length > 0 ? 1 : 0+ Behavior on opacity { enabled: !Theme.reduceMotion; NumberAnimation { duration: Theme.fadeFast } }+ Txt {+ id: noticeTxt+ anchors.left: parent.left+ anchors.right: parent.right+ anchors. leftMargin: 12+ anchors.rightMargin: 12+ anchors.verticalCenter: parent.verticalCenter+ horizontalAlignment: Text.AlignHCenter+ elide: Text.ElideRight+ role: "caption"+ color: "white"+ text: win.info.notice || ""}}// How to control it, until the phone allows it.Rectangle {+ id: hintBanneranchors.left: parent.leftanchors.right: parent.rightanchors.bottom: parent.bottomdiff --git a/desktop/app/qml/ShelfWindow.qml b/desktop/app/qml/ShelfWindow.qmlnew file mode 100644index 0000000..865c043--- /dev/null+++ b/desktop/app/qml/ShelfWindow.qml@@ -0,0 +1,807 @@+// SPDX-License-Identifier: GPL-3.0-or-later+import QtQuick+import QtQuick.Window+import app.nectarlink++// Slide-out edge panel ("The Shelf") showing the latest photo, latest+// screenshot, current clipboard item, and recent received files. Dragging+// anything into the panel sends it to the connected phone; dragging any card+// out starts a native OS drag so it can be dropped into Explorer, browsers,+// or editors. Styled with WS_EX_NOACTIVATE so it never steals focus from the+// active application, and only instantiated while AppController.shelfOpen is+// true so nothing runs while hidden.+Window {+ id: shelfWin++ title: "Nectarlink Shelf"+ flags: Qt.Tool | Qt.FramelessWindowHint | Qt.WindowStaysOnTopHint | Qt.WindowDoesNotAcceptFocus+ color: "transparent"+ visible: true++ readonly property int availW: Screen.desktopAvailableWidth > 0 ? Screen.desktopAvailableWidth : 1920+ readonly property int availH: Screen.desktopAvailableHeight > 0 ? Screen.desktopAvailableHeight : 1080++ width: 348+ height: Math.min(620, Math.max(420, availH - 48))+ x: Screen.virtualX + availW - width - 12+ y: Screen.virtualY + Math.round((availH - height) / 2)++ property bool justDropped: false++ readonly property var shelfData: {+ if (!AppController.shelfItems || AppController.shelfItems === "") {+ return ({+ hasDevice: false,+ deviceName: "",+ latestPhoto: null,+ latestScreenshot: null,+ currentClip: null,+ recentFiles: []+ })+ }+ try {+ return JSON.parse(AppController.shelfItems)+ } catch (e) {+ return ({+ hasDevice: false,+ deviceName: "",+ latestPhoto: null,+ latestScreenshot: null,+ currentClip: null,+ recentFiles: []+ })+ }+ }++ function formatBytes(bytes) {+ const b = Number(bytes) || 0+ if (b < 1024)+ return qsTr("%1 B").arg(b)+ if (b < 1024 * 1024)+ return qsTr("%1 KB").arg((b / 1024).toFixed(1))+ if (b < 1024 * 1024 * 1024)+ return qsTr("%1 MB").arg((b / (1024 * 1024)).toFixed(1))+ return qsTr("%1 GB").arg((b / (1024 * 1024 * 1024)).toFixed(2))+ }++ Component.onCompleted: {+ Qt.callLater(() => AppController.styleShelfWindow())+ if (!Theme.reduceMotion) {+ slideAnim.restart()+ }+ }++ onVisibleChanged: {+ if (visible) {+ Qt.callLater(() => AppController.styleShelfWindow())+ }+ }++ Shortcut {+ sequence: "Escape"+ onActivated: AppController.closeShelf()+ }++ Timer {+ id: dropConfirmTimer+ interval: 1800+ onTriggered: shelfWin.justDropped = false+ }++ Item {+ id: rootItem+ anchors.fill: parent++ transform: Translate {+ id: slideTransform+ x: 0+ }++ NumberAnimation {+ id: slideAnim+ target: slideTransform+ property: "x"+ from: 24+ to: 0+ duration: Theme.reduceMotion ? 0 : 180+ easing.type: Easing.OutCubic+ }++ Rectangle {+ id: panel+ anchors.fill: parent+ radius: Theme.graphite ? Theme.radiusMd : Theme.radiusXl+ color: Theme.surface+ border.width: 1+ border.color: shelfDropArea.containsDrag ? Theme.primary : Theme.outlineVariant++ Behavior on border.color {+ enabled: !Theme.reduceMotion+ ColorAnimation { duration: Theme.fadeFast }+ }++ // Whole-window drop target so dropping anywhere on the Shelf sends to phone.+ DropArea {+ id: shelfDropArea+ anchors.fill: parent+ onDropped: (drop) => {+ const urls = []+ if (drop.urls) {+ for (let i = 0; i < drop.urls.length; i++) {+ urls.push(drop.urls[i].toString())+ }+ }+ const text = drop.text ? String(drop.text) : ""+ if (urls.length > 0 || text.trim().length > 0) {+ AppController.dropToShelf(urls, text)+ shelfWin.justDropped = true+ dropConfirmTimer.restart()+ }+ drop.acceptProposedAction()+ }+ }++ Column {+ id: mainColumn+ anchors.fill: parent+ anchors.margins: 14+ spacing: 10++ // ---- Header ----+ Item {+ width: parent.width+ height: 36++ Row {+ anchors.left: parent.left+ anchors.verticalCenter: parent.verticalCenter+ spacing: 8++ Rectangle {+ width: 28+ height: 28+ radius: Theme.pill(height)+ color: Theme.primaryContainer+ anchors.verticalCenter: parent.verticalCenter++ Icon {+ anchors.centerIn: parent+ width: 15+ height: 15+ path: Icons.sparkle+ color: Theme.primaryContainerContent+ }+ }++ Column {+ anchors.verticalCenter: parent.verticalCenter+ spacing: 0++ Txt {+ role: "title"+ size: 15+ weight: 650+ text: qsTr("Shelf")+ }++ Txt {+ role: "caption"+ size: 11+ muted: true+ text: shelfWin.shelfData.hasDevice+ ? shelfWin.shelfData.deviceName+ : qsTr("No phone connected")+ }+ }+ }++ Row {+ anchors.right: parent.right+ anchors.verticalCenter: parent.verticalCenter+ spacing: 2++ IconButton {+ iconPath: Icons.refresh+ label: qsTr("Refresh Shelf")+ onClicked: AppController.refreshShelf()+ }++ IconButton {+ iconPath: Icons.close+ label: qsTr("Close Shelf")+ onClicked: AppController.closeShelf()+ }+ }+ }++ // ---- Drop Zone Banner ----+ Rectangle {+ id: dropBanner+ width: parent.width+ height: 52+ radius: Theme.radiusMd+ color: shelfDropArea.containsDrag+ ? Theme.primaryContainer+ : (shelfWin.justDropped ? Theme.secondaryContainer : Theme.surfaceContainerLow)+ border.width: 1+ border.color: shelfDropArea.containsDrag ? Theme.primary : Theme.outlineVariant++ Accessible.role: Accessible.StaticText+ Accessible.name: dropLabel.text++ Behavior on color {+ enabled: !Theme.reduceMotion+ ColorAnimation { duration: Theme.fadeFast }+ }++ Row {+ anchors.centerIn: parent+ spacing: 8++ Icon {+ anchors.verticalCenter: parent.verticalCenter+ width: 16+ height: 16+ path: shelfWin.justDropped ? Icons.check : Icons.send+ color: shelfDropArea.containsDrag+ ? Theme.primaryContainerContent+ : (shelfWin.justDropped ? Theme.secondaryContainerContent : Theme.primary)+ }++ Txt {+ id: dropLabel+ anchors.verticalCenter: parent.verticalCenter+ role: "bodySmall"+ weight: 600+ color: shelfDropArea.containsDrag+ ? Theme.primaryContainerContent+ : (shelfWin.justDropped ? Theme.secondaryContainerContent : Theme.surfaceContent)+ text: shelfDropArea.containsDrag+ ? qsTr("Release to send to phone")+ : (shelfWin.justDropped+ ? qsTr("Sent to phone")+ : qsTr("Drop files, photos, or text here to send"))+ }+ }+ }++ // ---- Scrollable Shelf Content ----+ Flickable {+ id: contentFlick+ width: parent.width+ height: parent.height - 36 - 52 - 20+ contentWidth: width+ contentHeight: cardsColumn.implicitHeight+ clip: true+ boundsBehavior: Flickable.StopAtBounds++ Column {+ id: cardsColumn+ width: parent.width+ spacing: 10++ // ---- Camera Roll Row: Latest Photo & Latest Screenshot ----+ Row {+ width: parent.width+ spacing: 8++ Repeater {+ model: [+ {+ slotKind: "photo",+ title: qsTr("Latest photo"),+ emptyText: qsTr("No recent photo"),+ icon: Icons.photo,+ item: shelfWin.shelfData.latestPhoto+ },+ {+ slotKind: "screenshot",+ title: qsTr("Latest screenshot"),+ emptyText: qsTr("No recent screenshot"),+ icon: Icons.camera,+ item: shelfWin.shelfData.latestScreenshot+ }+ ]++ delegate: Rectangle {+ id: mediaCard+ readonly property var itemData: modelData.item+ readonly property bool hasItem: itemData !== null && itemData !== undefined+ readonly property string thumbSource: hasItem ? (itemData.thumbUrl || itemData.thumbnailDataUrl || "") : ""+ readonly property string targetRef: hasItem ? (itemData.localPath || itemData.id || "") : ""++ width: Math.floor((cardsColumn.width - 8) / 2)+ height: 152+ radius: Theme.radiusMd+ color: Theme.surfaceContainer+ border.width: Theme.graphite ? 1 : 0+ border.color: Theme.outlineVariant++ Column {+ anchors.fill: parent+ anchors.margins: 8+ spacing: 6++ // Card header+ Row {+ width: parent.width+ spacing: 5++ Icon {+ anchors.verticalCenter: parent.verticalCenter+ width: 13+ height: 13+ path: modelData.icon+ color: Theme.surfaceContentVariant+ }++ Txt {+ anchors.verticalCenter: parent.verticalCenter+ width: parent.width - 18+ role: "caption"+ weight: 600+ muted: true+ text: modelData.title+ }+ }++ // Thumbnail or empty state+ Item {+ width: parent.width+ height: 86++ Rectangle {+ anchors.fill: parent+ radius: Theme.radiusSm+ color: Theme.surfaceContainerHigh++ Txt {+ anchors.centerIn: parent+ width: parent.width - 12+ horizontalAlignment: Text.AlignHCenter+ wrapMode: Text.Wrap+ role: "caption"+ muted: true+ visible: !mediaCard.hasItem+ text: modelData.emptyText+ }+ }++ RoundedImage {+ anchors.fill: parent+ radius: Theme.radiusSm+ visible: mediaCard.hasItem && mediaCard.thumbSource !== ""+ source: mediaCard.thumbSource+ }++ MouseArea {+ id: mediaDragArea+ anchors.fill: parent+ enabled: mediaCard.hasItem+ hoverEnabled: true+ cursorShape: enabled ? Qt.OpenHandCursor : Qt.ArrowCursor++ property real pressX: 0+ property real pressY: 0+ property bool dragged: false++ Accessible.role: Accessible.Button+ Accessible.name: mediaCard.hasItem+ ? (modelData.title + ": " + mediaCard.itemData.name)+ : modelData.emptyText+ Accessible.onPressAction: {+ if (mediaCard.hasItem)+ AppController.activateShelfItem(modelData.slotKind, "open", mediaCard.targetRef)+ }++ onPressed: (mouse) => {+ pressX = mouse.x+ pressY = mouse.y+ dragged = false+ }++ onPositionChanged: (mouse) => {+ if (!pressed || dragged || !mediaCard.hasItem)+ return+ const dx = mouse.x - pressX+ const dy = mouse.y - pressY+ if (dx * dx + dy * dy > 36) {+ dragged = true+ AppController.startShelfDrag(+ modelData.slotKind,+ mediaCard.targetRef,+ mediaCard.itemData.name+ )+ }+ }++ onClicked: {+ if (!dragged && mediaCard.hasItem) {+ AppController.activateShelfItem(+ modelData.slotKind,+ "open",+ mediaCard.targetRef+ )+ }+ }+ }+ }++ // Bottom bar with filename + quick actions+ Item {+ width: parent.width+ height: 24++ Txt {+ anchors.left: parent.left+ anchors.right: mediaActions.left+ anchors.rightMargin: 4+ anchors.verticalCenter: parent.verticalCenter+ role: "caption"+ size: 11+ muted: !mediaCard.hasItem+ text: mediaCard.hasItem ? mediaCard.itemData.name : "—"+ }++ Row {+ id: mediaActions+ anchors.right: parent.right+ anchors.verticalCenter: parent.verticalCenter+ spacing: 2+ visible: mediaCard.hasItem++ IconButton {+ width: 24+ height: 24+ iconPath: Icons.copy+ label: qsTr("Copy")+ onClicked: AppController.activateShelfItem(+ modelData.slotKind,+ "copy",+ mediaCard.targetRef+ )+ }++ IconButton {+ width: 24+ height: 24+ iconPath: Icons.openExternal+ label: qsTr("Open")+ onClicked: AppController.activateShelfItem(+ modelData.slotKind,+ "open",+ mediaCard.targetRef+ )+ }+ }+ }+ }+ }+ }+ }++ // ---- Current Clip Card ----+ Rectangle {+ id: clipCard+ readonly property var clipData: shelfWin.shelfData.currentClip+ readonly property bool hasClip: clipData !== null && clipData !== undefined+ readonly property string clipId: hasClip ? (clipData.id || "") : ""++ width: parent.width+ implicitHeight: clipColumn.implicitHeight + 16+ radius: Theme.radiusMd+ color: Theme.surfaceContainer+ border.width: Theme.graphite ? 1 : 0+ border.color: Theme.outlineVariant++ Column {+ id: clipColumn+ anchors.left: parent.left+ anchors.right: parent.right+ anchors.top: parent.top+ anchors.margins: 8+ spacing: 6++ Item {+ width: parent.width+ height: 24++ Row {+ anchors.left: parent.left+ anchors.verticalCenter: parent.verticalCenter+ spacing: 6++ Icon {+ anchors.verticalCenter: parent.verticalCenter+ width: 14+ height: 14+ path: Icons.clipboard+ color: Theme.surfaceContentVariant+ }++ Txt {+ anchors.verticalCenter: parent.verticalCenter+ role: "caption"+ weight: 600+ muted: true+ text: qsTr("Current clip")+ }+ }++ IconButton {+ anchors.right: parent.right+ anchors.verticalCenter: parent.verticalCenter+ width: 24+ height: 24+ visible: clipCard.hasClip+ iconPath: Icons.copy+ label: qsTr("Copy clip")+ onClicked: AppController.activateShelfItem("clip", "copy", clipCard.clipId)+ }+ }++ Rectangle {+ width: parent.width+ height: clipCard.hasClip && clipCard.clipData.kind === "image" ? 76 : 54+ radius: Theme.radiusSm+ color: Theme.surfaceContainerHigh++ RoundedImage {+ anchors.fill: parent+ anchors.margins: 4+ radius: Theme.radiusXs+ fillMode: Image.PreserveAspectFit+ visible: clipCard.hasClip && clipCard.clipData.kind === "image"+ source: clipCard.hasClip && clipCard.clipData.imageDataUrl+ ? clipCard.clipData.imageDataUrl : ""+ }++ Txt {+ anchors.fill: parent+ anchors.margins: 8+ visible: !clipCard.hasClip || clipCard.clipData.kind !== "image"+ role: clipCard.hasClip ? "code" : "caption"+ size: 12+ muted: !clipCard.hasClip+ wrapMode: Text.Wrap+ maximumLineCount: 2+ elide: Text.ElideRight+ text: clipCard.hasClip+ ? clipCard.clipData.text+ : qsTr("Clipboard is empty")+ }++ MouseArea {+ anchors.fill: parent+ enabled: clipCard.hasClip+ hoverEnabled: true+ cursorShape: enabled ? Qt.OpenHandCursor : Qt.ArrowCursor++ property real pressX: 0+ property real pressY: 0+ property bool dragged: false++ Accessible.role: Accessible.Button+ Accessible.name: clipCard.hasClip+ ? qsTr("Current clip: %1").arg(clipCard.clipData.text)+ : qsTr("Clipboard is empty")+ Accessible.onPressAction: {+ if (clipCard.hasClip)+ AppController.activateShelfItem("clip", "copy", clipCard.clipId)+ }++ onPressed: (mouse) => {+ pressX = mouse.x+ pressY = mouse.y+ dragged = false+ }++ onPositionChanged: (mouse) => {+ if (!pressed || dragged || !clipCard.hasClip)+ return+ const dx = mouse.x - pressX+ const dy = mouse.y - pressY+ if (dx * dx + dy * dy > 36) {+ dragged = true+ AppController.startShelfDrag(+ "clip",+ clipCard.clipId,+ clipCard.clipData.text || ""+ )+ }+ }++ onClicked: {+ if (!dragged && clipCard.hasClip) {+ AppController.activateShelfItem("clip", "copy", clipCard.clipId)+ }+ }+ }+ }+ }+ }++ // ---- Recent Received Files Card ----+ Rectangle {+ id: filesCard+ readonly property var filesList: shelfWin.shelfData.recentFiles || []++ width: parent.width+ implicitHeight: filesColumn.implicitHeight + 16+ radius: Theme.radiusMd+ color: Theme.surfaceContainer+ border.width: Theme.graphite ? 1 : 0+ border.color: Theme.outlineVariant++ Column {+ id: filesColumn+ anchors.left: parent.left+ anchors.right: parent.right+ anchors.top: parent.top+ anchors.margins: 8+ spacing: 6++ Row {+ width: parent.width+ spacing: 6++ Icon {+ anchors.verticalCenter: parent.verticalCenter+ width: 14+ height: 14+ path: Icons.download+ color: Theme.surfaceContentVariant+ }++ Txt {+ anchors.verticalCenter: parent.verticalCenter+ role: "caption"+ weight: 600+ muted: true+ text: qsTr("Recent received files")+ }+ }++ Rectangle {+ width: parent.width+ height: 40+ radius: Theme.radiusSm+ color: Theme.surfaceContainerHigh+ visible: filesCard.filesList.length === 0++ Txt {+ anchors.centerIn: parent+ role: "caption"+ muted: true+ text: qsTr("No received files yet")+ }+ }++ Repeater {+ model: filesCard.filesList++ delegate: Rectangle {+ width: filesColumn.width+ height: 44+ radius: Theme.radiusSm+ color: Theme.surfaceContainerHigh++ MouseArea {+ id: fileRowDrag+ anchors.left: parent.left+ anchors.top: parent.top+ anchors.bottom: parent.bottom+ anchors.right: fileActions.left+ hoverEnabled: true+ cursorShape: Qt.OpenHandCursor++ property real pressX: 0+ property real pressY: 0+ property bool dragged: false++ Accessible.role: Accessible.Button+ Accessible.name: modelData.name+ Accessible.onPressAction: AppController.activateShelfItem("file", "open", modelData.path)++ onPressed: (mouse) => {+ pressX = mouse.x+ pressY = mouse.y+ dragged = false+ }++ onPositionChanged: (mouse) => {+ if (!pressed || dragged)+ return+ const dx = mouse.x - pressX+ const dy = mouse.y - pressY+ if (dx * dx + dy * dy > 36) {+ dragged = true+ AppController.startShelfDrag("file", modelData.path, modelData.name)+ }+ }++ onClicked: {+ if (!dragged)+ AppController.activateShelfItem("file", "open", modelData.path)+ }++ Row {+ anchors.fill: parent+ anchors.leftMargin: 8+ anchors.rightMargin: 4+ spacing: 8++ Icon {+ anchors.verticalCenter: parent.verticalCenter+ width: 16+ height: 16+ path: Icons.folder+ color: Theme.primary+ }++ Column {+ anchors.verticalCenter: parent.verticalCenter+ width: parent.width - 28+ spacing: 1++ Txt {+ width: parent.width+ role: "bodySmall"+ size: 12+ weight: 600+ text: modelData.name+ }++ Txt {+ width: parent.width+ role: "caption"+ size: 10+ muted: true+ text: shelfWin.formatBytes(modelData.size)+ }+ }+ }+ }++ Row {+ id: fileActions+ anchors.right: parent.right+ anchors.rightMargin: 4+ anchors.verticalCenter: parent.verticalCenter+ spacing: 2++ IconButton {+ width: 28+ height: 28+ iconPath: Icons.openExternal+ label: qsTr("Open file")+ onClicked: AppController.activateShelfItem("file", "open", modelData.path)+ }++ IconButton {+ width: 28+ height: 28+ iconPath: Icons.folder+ label: qsTr("Show in folder")+ onClicked: AppController.activateShelfItem("file", "reveal", modelData.path)+ }+ }+ }+ }+ }+ }++ Txt {+ width: parent.width+ horizontalAlignment: Text.AlignHCenter+ role: "caption"+ size: 11+ muted: true+ text: qsTr("Drag any card out to use, or drop files in to send")+ }+ }+ }+ }+ }+ }+}diff --git a/desktop/app/qml/Theme.qml b/desktop/app/qml/Theme.qmlindex e3bf264..2f937b3 100644--- a/desktop/app/qml/Theme.qml+++ b/desktop/app/qml/Theme.qml@@ -124,10 +124,13 @@ QtObject {readonly property int gutter: layout.gutterfunction space(step) { return Tokens.data.spacing.scale[step] }- // Focus rings show for keyboard focus only, not after a click (the- // web's :focus-visible).+ // Focus rings show for keyboard focus only, not after a click (TapHandler+ // doesn't take activeFocus on click; activeFocus on a control comes from Tab).function focusVisible(item) {- return item.activeFocus && (item.focusReason === Qt.TabFocusReason || item.focusReason === Qt.BacktabFocusReason)+ return item !== null && item !== undefined && item.activeFocus+ && (item.focusReason === undefined+ || item.focusReason === Qt.TabFocusReason+ || item.focusReason === Qt.BacktabFocusReason)}// ---- Motion ----diff --git a/desktop/app/qml/Tokens.qml b/desktop/app/qml/Tokens.qmlindex bed9106..e20d547 100644--- a/desktop/app/qml/Tokens.qml+++ b/desktop/app/qml/Tokens.qml@@ -270,7 +270,7 @@ QtObject {"error": "#BA1A1A","onError": "#FFFFFF","success": "{primary}",- "warning": "#9A6700"+ "warning": "#7D5200"}}},@@ -329,7 +329,7 @@ QtObject {"surfaceContainerHigh": "#EFEBE2","surfaceContainerHighest": "#E8E3D7","surfaceContainerLow": "#F1EDE4",- "warning": "#8A6A1F"+ "warning": "#705516"},"slate": {"buttonShadow": "3px 3px 0 #26272A",diff --git a/desktop/app/qml/components/AppsSheet.qml b/desktop/app/qml/components/AppsSheet.qmlindex 1888288..54ef99b 100644--- a/desktop/app/qml/components/AppsSheet.qml+++ b/desktop/app/qml/components/AppsSheet.qml@@ -183,7 +183,7 @@ Sheet {anchors.margins: 2radius: Theme.radiusMdcolor: "transparent"- border.width: recentCell.activeFocus ? 2 : 0+ border.width: Theme.focusVisible(recentCell) ? 2 : 0border.color: Theme.primary}Column {@@ -272,7 +272,7 @@ Sheet {anchors.margins: 4radius: Theme.radiusMdcolor: "transparent"- border.width: cell.activeFocus ? 2 : 0+ border.width: Theme.focusVisible(cell) ? 2 : 0border.color: Theme.primary}Column {diff --git a/desktop/app/qml/components/CallCard.qml b/desktop/app/qml/components/CallCard.qmlindex a5e5758..a8b812e 100644--- a/desktop/app/qml/components/CallCard.qml+++ b/desktop/app/qml/components/CallCard.qml@@ -169,7 +169,8 @@ Card {border.width: Theme.graphite ? 1 : 0border.color: Theme.outlineVariantscale: keyTap.pressed ? Theme.pressScale : 1- Behavior on scale { SpringAnimation { spring: Theme.springSnappy; damping: Theme.dampingSnappy } }+ Behavior on scale { enabled: !Theme.reduceMotion; SpringAnimation { spring: Theme.springSnappy; damping: Theme.dampingSnappy } }+ activeFocusOnTab: truefunction press() {PhoneCall.press(modelData)card.pressed = (card.pressed + modelData).slice(-24)@@ -177,6 +178,21 @@ Card {Accessible.role: Accessible.ButtonAccessible.name: modelDataAccessible.onPressAction: press()+ Keys.onPressed: (event) => {+ if (event.key === Qt.Key_Return || event.key === Qt.Key_Enter || event.key === Qt.Key_Space) {+ key.press()+ event.accepted = true+ }+ }+ Rectangle {+ anchors.fill: parent+ anchors.margins: -3+ radius: parent.radius + 3+ color: "transparent"+ border.width: 2+ border.color: Theme.primary+ visible: Theme.focusVisible(key)+ }Txt { anchors.centerIn: parent; role: "title"; text: key.modelData }HoverHandler { cursorShape: Qt.PointingHandCursor }TapHandler { id: keyTap; onTapped: key.press() }diff --git a/desktop/app/qml/components/Chip.qml b/desktop/app/qml/components/Chip.qmlindex b1ddd41..10a0df3 100644--- a/desktop/app/qml/components/Chip.qml+++ b/desktop/app/qml/components/Chip.qml@@ -8,6 +8,8 @@ Rectangle {property string textproperty string iconPathproperty bool selected: false+ property bool interactive: false+ signal clicked()implicitHeight: 30implicitWidth: row.implicitWidth + 24@@ -16,7 +18,28 @@ Rectangle {: (selected ? Theme.secondaryContainer : Theme.surfaceContainerHigh)border.width: Theme.graphite ? 1 : 0border.color: selected ? Theme.surfaceContent : Theme.outlineVariant- Behavior on color { ColorAnimation { duration: Theme.fadeFast } }+ Behavior on color { enabled: !Theme.reduceMotion; ColorAnimation { duration: Theme.fadeFast } }++ activeFocusOnTab: interactive && visible && enabled+ Accessible.role: interactive ? Accessible.Button : Accessible.StaticText+ Accessible.name: chip.text+ Accessible.onPressAction: if (chip.interactive) chip.clicked()+ Keys.onPressed: (event) => {+ if (chip.interactive && (event.key === Qt.Key_Return || event.key === Qt.Key_Enter || event.key === Qt.Key_Space)) {+ chip.clicked()+ event.accepted = true+ }+ }++ Rectangle {+ anchors.fill: parent+ anchors.margins: -3+ radius: chip.radius + 3+ color: "transparent"+ border.width: 2+ border.color: Theme.primary+ visible: chip.interactive && Theme.focusVisible(chip)+ }Row {id: row@@ -38,4 +61,7 @@ Rectangle {: (chip.selected ? Theme.secondaryContainerContent : Theme.surfaceContent)}}++ HoverHandler { enabled: chip.interactive; cursorShape: Qt.PointingHandCursor }+ TapHandler { enabled: chip.interactive; onTapped: chip.clicked() }}diff --git a/desktop/app/qml/components/CommandPalette.qml b/desktop/app/qml/components/CommandPalette.qmlindex 2655825..b6a8dac 100644--- a/desktop/app/qml/components/CommandPalette.qml+++ b/desktop/app/qml/components/CommandPalette.qml@@ -41,6 +41,12 @@ Item {Qt.callLater(() => AppController.noteCommandPaletteShown())}+ Shortcut {+ sequence: "Esc"+ enabled: palette.visible+ onActivated: AppController.closeCommandPalette()+ }+Rectangle {id: scrimanchors.fill: parent@@ -156,27 +162,49 @@ Item {color: Theme.surfaceContainerHighestborder.width: 1border.color: Theme.outlineVariant+ activeFocusOnTab: true++ function activate() {+ if (searchInput.text.length > 0) {+ searchInput.text = ""+ searchInput.forceActiveFocus()+ } else {+ AppController.closeCommandPalette()+ }+ }++ Accessible.role: Accessible.Button+ Accessible.name: searchInput.text.length > 0 ? qsTr("Clear search") : qsTr("Close command palette")+ Accessible.onPressAction: escBadge.activate()++ Keys.onPressed: (event) => {+ if (event.key === Qt.Key_Return || event.key === Qt.Key_Enter || event.key === Qt.Key_Space) {+ escBadge.activate()+ event.accepted = true+ }+ }++ Rectangle {+ anchors.fill: parent+ anchors.margins: -3+ radius: parent.radius + 3+ color: "transparent"+ border.width: 2+ border.color: Theme.primary+ visible: Theme.focusVisible(escBadge)+ }Txt {id: escLabelanchors.centerIn: parent- text: searchInput.text.length > 0 ? qsTr("Clear") : "Esc"+ text: searchInput.text.length > 0 ? qsTr("Clear") : qsTr("Esc")role: "caption"size: 11muted: true}HoverHandler { cursorShape: Qt.PointingHandCursor }- TapHandler {- onTapped: {- if (searchInput.text.length > 0) {- searchInput.text = ""- searchInput.forceActiveFocus()- } else {- AppController.closeCommandPalette()- }- }- }+ TapHandler { onTapped: escBadge.activate() }}}@@ -213,6 +241,13 @@ Item {? Theme.surfaceContainerHighest: "transparent"+ Accessible.role: Accessible.ListItem+ Accessible.name: (modelData.title || "") + (modelData.subtitle ? ", " + modelData.subtitle : "")+ Accessible.onPressAction: {+ palette.selectedIndex = row.index+ AppController.runCommandPalette(row.modelData.id)+ }+HoverHandler {id: rowHovercursorShape: Qt.PointingHandCursordiff --git a/desktop/app/qml/components/HistoryItem.qml b/desktop/app/qml/components/HistoryItem.qmlindex 4d8c476..c230785 100644--- a/desktop/app/qml/components/HistoryItem.qml+++ b/desktop/app/qml/components/HistoryItem.qml@@ -12,8 +12,21 @@ Item {required property string subrequired property real whenrequired property string iconUrl+ property bool canOpenApp: false+ signal openAppRequestedimplicitHeight: Math.max(icon.height, content.height) + 20+ activeFocusOnTab: item.canOpenApp+ Accessible.role: item.canOpenApp ? Accessible.Button : Accessible.Grouping+ Accessible.name: [item.appName, item.title, item.text].filter(s => s.length > 0).join(", ")+ Accessible.description: item.canOpenApp ? qsTr("Open %1 in an app window").arg(item.appName) : ""+ Accessible.onPressAction: if (item.canOpenApp) item.openAppRequested()+ Keys.onPressed: (event) => {+ if (item.canOpenApp && (event.key === Qt.Key_Return || event.key === Qt.Key_Enter || event.key === Qt.Key_Space)) {+ item.openAppRequested()+ event.accepted = true+ }+ }function timeText() {const date = new Date(when)@@ -22,6 +35,36 @@ Item {: qsTr("Yesterday %1").arg(date.toLocaleTimeString(Qt.locale(), Locale.ShortFormat))}+ Rectangle {+ anchors.fill: parent+ radius: Theme.radiusMd+ color: Theme.surfaceContent+ opacity: item.canOpenApp && historyHover.hovered ? 0.045 : 0+ Behavior on opacity {+ enabled: !Theme.reduceMotion+ NumberAnimation { duration: Theme.fadeFast }+ }+ }++ Rectangle {+ anchors.fill: parent+ radius: Theme.radiusMd+ color: "transparent"+ border.width: Theme.focusVisible(item) ? 2 : 0+ border.color: Theme.primary+ visible: Theme.focusVisible(item)+ }++ HoverHandler {+ id: historyHover+ cursorShape: item.canOpenApp ? Qt.PointingHandCursor : Qt.ArrowCursor+ }++ TapHandler {+ enabled: item.canOpenApp+ onTapped: item.openAppRequested()+ }+Item {id: iconx: 4; y: 10diff --git a/desktop/app/qml/components/NotificationItem.qml b/desktop/app/qml/components/NotificationItem.qmlindex b0be096..698fc0e 100644--- a/desktop/app/qml/components/NotificationItem.qml+++ b/desktop/app/qml/components/NotificationItem.qml@@ -61,9 +61,23 @@ Item {return ""}property bool replying: false+ property bool canOpenApp: falsesignal optionsRequested+ signal openAppRequestedimplicitHeight: content.height + 24+ activeFocusOnTab: item.canOpenApp && !item.replying+ Accessible.role: item.canOpenApp ? Accessible.Button : Accessible.Grouping+ Accessible.name: [item.appName, item.title, item.text].filter(s => s.length > 0).join(", ")+ Accessible.description: item.canOpenApp ? qsTr("Open %1 in an app window").arg(item.appName) : ""+ Accessible.onPressAction: if (item.canOpenApp && !item.replying) item.openAppRequested()+ Keys.onPressed: (event) => {+ if (item.canOpenApp && !item.replying+ && (event.key === Qt.Key_Return || event.key === Qt.Key_Enter || event.key === Qt.Key_Space)) {+ item.openAppRequested()+ event.accepted = true+ }+ }// Ticks once per second only for visible chronometer notifications while the window is shown.Timer {@@ -124,13 +138,15 @@ Item {item.replying = false}- // Hover tracking only: clicks go to the buttons inside.+ // Hover tracking; clicking the card body opens the app window when available.MouseArea {id: hoveranchors.fill: parenthoverEnabled: true- acceptedButtons: Qt.NoButton+ acceptedButtons: item.canOpenApp && !item.replying ? Qt.LeftButton : Qt.NoButton+ cursorShape: item.canOpenApp && !item.replying ? Qt.PointingHandCursor : Qt.ArrowCursorreadonly property bool hovered: containsMouse+ onClicked: if (item.canOpenApp && !item.replying) item.openAppRequested()}// A light wash of the text color, or a calm highlighted container for Live Updates.@@ -151,6 +167,15 @@ Item {Behavior on opacity { NumberAnimation { duration: Theme.fadeFast } }}+ Rectangle {+ anchors.fill: parent+ radius: Theme.radiusMd+ color: "transparent"+ border.width: Theme.focusVisible(item) ? 2 : 0+ border.color: Theme.primary+ visible: Theme.focusVisible(item)+ }+// App icon, or its initial when the phone didn't send one.Item {id: icondiff --git a/desktop/app/qml/components/NowPlaying.qml b/desktop/app/qml/components/NowPlaying.qmlindex 21f94d8..92817a3 100644--- a/desktop/app/qml/components/NowPlaying.qml+++ b/desktop/app/qml/components/NowPlaying.qml@@ -118,6 +118,19 @@ Card {id: barwidth: parent.widthheight: 16+ activeFocusOnTab: card.canSeek+ Accessible.role: Accessible.Slider+ Accessible.name: qsTr("Playback position")+ Keys.onPressed: (event) => {+ if (!card.canSeek || card.duration <= 0) return+ if (event.key === Qt.Key_Left) {+ card.send("seek", Math.round(Math.max(0, Math.min(card.duration, card.shown - 5000))))+ event.accepted = true+ } else if (event.key === Qt.Key_Right) {+ card.send("seek", Math.round(Math.max(0, Math.min(card.duration, card.shown + 5000))))+ event.accepted = true+ }+ }readonly property real fraction: card.duration > 0 ? Math.max(0, Math.min(1, card.shown / card.duration)) : 0Rectangle {id: track@@ -134,12 +147,21 @@ Card {}}Rectangle {- visible: card.canSeek && (seek.containsMouse || seek.pressed)+ visible: card.canSeek && (seek.containsMouse || seek.pressed || Theme.focusVisible(bar))x: bar.width * bar.fraction - width / 2anchors.verticalCenter: parent.verticalCenterwidth: 12; height: 12; radius: 6color: Theme.primary}+ Rectangle {+ anchors.fill: parent+ anchors.margins: -3+ radius: Theme.radiusXs + 3+ color: "transparent"+ border.width: 2+ border.color: Theme.primary+ visible: Theme.focusVisible(bar)+ }MouseArea {id: seekanchors.fill: parentdiff --git a/desktop/app/qml/components/Segmented.qml b/desktop/app/qml/components/Segmented.qmlindex 8bbbd3e..ffd5a30 100644--- a/desktop/app/qml/components/Segmented.qml+++ b/desktop/app/qml/components/Segmented.qml@@ -45,9 +45,16 @@ Rectangle {anchors.fill: parentradius: Theme.pill(height)color: option.selected ? (Theme.graphite ? Theme.surfaceContent : Theme.surface) : "transparent"- Behavior on color { ColorAnimation { duration: Theme.fadeFast } }- border.width: Theme.focusVisible(option) ? 2 : 0- border.color: Theme.primary+ Behavior on color { enabled: !Theme.reduceMotion; ColorAnimation { duration: Theme.fadeFast } }+ Rectangle {+ anchors.fill: parent+ anchors.margins: -3+ radius: parent.radius + 3+ color: "transparent"+ border.width: 2+ border.color: Theme.primary+ visible: Theme.focusVisible(option)+ }}Txt {id: labeldiff --git a/desktop/app/qml/components/Sheet.qml b/desktop/app/qml/components/Sheet.qmlindex 87608d0..4f660a2 100644--- a/desktop/app/qml/components/Sheet.qml+++ b/desktop/app/qml/components/Sheet.qml@@ -12,13 +12,26 @@ Item {default property alias content: body.datasignal dismissed- function open() { opened = true }+ function open() {+ opened = true+ if (!sheet.activeFocus)+ sheet.forceActiveFocus(Qt.OtherFocusReason)+ }function close() { opened = false }anchors.fill: parentvisible: opened || fade.runningz: 100+ Shortcut {+ sequence: "Esc"+ enabled: sheet.opened && sheet.dismissable+ onActivated: {+ sheet.close()+ sheet.dismissed()+ }+ }+Rectangle {id: scrimanchors.fill: parent@@ -48,7 +61,7 @@ Item {opacity: sheet.opened ? 1 : 0scale: sheet.opened || Theme.reduceMotion ? 1 : 0.96Behavior on opacity { NumberAnimation { duration: Theme.fadeNormal } }- Behavior on scale { SpringAnimation { spring: Theme.springStandard; damping: Theme.dampingStandard } }+ Behavior on scale { enabled: !Theme.reduceMotion; SpringAnimation { spring: Theme.springStandard; damping: Theme.dampingStandard } }clip: trueFlickable {diff --git a/desktop/app/qml/components/Toast.qml b/desktop/app/qml/components/Toast.qmlindex 8ca0d4a..53ffe7b 100644--- a/desktop/app/qml/components/Toast.qml+++ b/desktop/app/qml/components/Toast.qml@@ -28,10 +28,11 @@ Rectangle {}property bool shown: false+ visible: opacity > 0anchors.horizontalCenter: parent.horizontalCenteranchors.bottom: parent.bottom- anchors.bottomMargin: shown ? 24 : -height- Behavior on anchors.bottomMargin { SpringAnimation { spring: Theme.springStandard; damping: Theme.dampingStandard } }+ anchors.bottomMargin: shown || Theme.reduceMotion ? 24 : -height+ Behavior on anchors.bottomMargin { enabled: !Theme.reduceMotion; SpringAnimation { spring: Theme.springStandard; damping: Theme.dampingStandard } }opacity: shown ? 1 : 0Behavior on opacity { NumberAnimation { duration: Theme.fadeFast } }z: 200@@ -70,8 +71,6 @@ Rectangle {color: chipHover.hovered? Qt.rgba(Theme.primaryContainer.r, Theme.primaryContainer.g, Theme.primaryContainer.b, 0.92): Theme.primaryContainer- border.width: Theme.focusVisible(actionChip) ? 2 : 0- border.color: Theme.surfaceactiveFocusOnTab: toast.shown && toast.hasActionAccessible.role: Accessible.Button@@ -91,6 +90,16 @@ Rectangle {}}+ Rectangle {+ anchors.fill: parent+ anchors.margins: -3+ radius: parent.radius + 3+ color: "transparent"+ border.width: 2+ border.color: Theme.primary+ visible: Theme.focusVisible(actionChip)+ }+Txt {id: chipLabelanchors.centerIn: parentdiff --git a/desktop/app/qml/components/Toggle.qml b/desktop/app/qml/components/Toggle.qmlindex d748108..b2d4ed9 100644--- a/desktop/app/qml/components/Toggle.qml+++ b/desktop/app/qml/components/Toggle.qml@@ -45,9 +45,9 @@ FocusScope {x: toggle.checked ? parent.width - width - 4.5 : 6.5color: toggle.checked ? Theme.primaryContent : Theme.outline// Quick and settled, never springy: a switch must feel immediate.- Behavior on x { NumberAnimation { duration: Theme.reduceMotion ? 0 : 140; easing.type: Easing.OutCubic } }- Behavior on size { NumberAnimation { duration: Theme.reduceMotion ? 0 : 140; easing.type: Easing.OutCubic } }- Behavior on color { ColorAnimation { duration: Theme.fadeFast } }+ Behavior on x { enabled: !Theme.reduceMotion; NumberAnimation { duration: Theme.reduceMotion ? 0 : 140; easing.type: Easing.OutCubic } }+ Behavior on size { enabled: !Theme.reduceMotion; NumberAnimation { duration: Theme.reduceMotion ? 0 : 140; easing.type: Easing.OutCubic } }+ Behavior on color { enabled: !Theme.reduceMotion; ColorAnimation { duration: Theme.fadeFast } }}}Rectangle {diff --git a/desktop/app/qml/components/TransferItem.qml b/desktop/app/qml/components/TransferItem.qmlindex 3bcba37..5b5b78d 100644--- a/desktop/app/qml/components/TransferItem.qml+++ b/desktop/app/qml/components/TransferItem.qml@@ -25,11 +25,11 @@ Item {function size(bytes) {if (bytes < 1024) return qsTr("%1 B").arg(Math.round(bytes))- const units = ["KB", "MB", "GB", "TB"]+ const units = [qsTr("%1 KB"), qsTr("%1 MB"), qsTr("%1 GB"), qsTr("%1 TB")]let value = bytes / 1024let unit = 0while (value >= 1024 && unit < units.length - 1) { value /= 1024; unit++ }- return (value < 10 ? value.toFixed(1) : Math.round(value)) + " " + units[unit]+ return units[unit].arg(value < 10 ? value.toFixed(1) : Math.round(value))}function detail() {@@ -42,8 +42,9 @@ Item {return item.incoming ? qsTr("Paused; continues when %1 is back").arg(item.deviceName): qsTr("Waiting for %1").arg(item.deviceName)case "running":- return qsTr("%1 of %2").arg(size(done)).arg(size(total))- + (rate > 0 ? " · " + qsTr("%1/s").arg(size(rate)) : "")+ return rate > 0+ ? qsTr("%1 of %2 · %3/s").arg(size(done)).arg(size(total)).arg(size(rate))+ : qsTr("%1 of %2").arg(size(done)).arg(size(total))case "done":return item.incoming ? qsTr("From %1 · %2").arg(item.deviceName).arg(size(total)): qsTr("Sent to %1 · %2").arg(item.deviceName).arg(size(total))@@ -97,7 +98,7 @@ Item {width: parent.width * Math.max(0, Math.min(1, item.progress))color: Theme.primaryopacity: item.status === "waiting" ? 0.45 : 1- Behavior on width { NumberAnimation { duration: Theme.reduceMotion ? 0 : 180 } }+ Behavior on width { enabled: !Theme.reduceMotion; NumberAnimation { duration: Theme.reduceMotion ? 0 : 180 } }}}Txt {diff --git a/desktop/app/qml/pages/CallsPage.qml b/desktop/app/qml/pages/CallsPage.qmlindex 3063f36..3eb5523 100644--- a/desktop/app/qml/pages/CallsPage.qml+++ b/desktop/app/qml/pages/CallsPage.qml@@ -141,7 +141,7 @@ Item {Behavior on opacity { NumberAnimation { duration: Theme.fadeNormal } }transform: Translate {y: page.active || Theme.reduceMotion ? 0 : 12- Behavior on y { SpringAnimation { spring: Theme.springGentle; damping: Theme.dampingGentle } }+ Behavior on y { enabled: !Theme.reduceMotion; SpringAnimation { spring: Theme.springGentle; damping: Theme.dampingGentle } }}Shortcut {@@ -722,7 +722,7 @@ Item {border.width: Theme.focusVisible(padKey) ? 2 : (Theme.graphite ? 1 : 0)border.color: Theme.focusVisible(padKey) ? Theme.primary : Theme.outlineVariantscale: padTap.pressed ? Theme.pressScale : 1- Behavior on scale { SpringAnimation { spring: Theme.springSnappy; damping: Theme.dampingSnappy } }+ Behavior on scale { enabled: !Theme.reduceMotion; SpringAnimation { spring: Theme.springSnappy; damping: Theme.dampingSnappy } }function tapDigit(ch) {dialInput.text = dialInput.text + chdiff --git a/desktop/app/qml/pages/DeckPage.qml b/desktop/app/qml/pages/DeckPage.qmlindex ec24ea0..a790801 100644--- a/desktop/app/qml/pages/DeckPage.qml+++ b/desktop/app/qml/pages/DeckPage.qml@@ -17,19 +17,19 @@ Item {Behavior on opacity { NumberAnimation { duration: Theme.fadeNormal } }transform: Translate {y: page.active || Theme.reduceMotion ? 0 : 12- Behavior on y { SpringAnimation { spring: Theme.springGentle; damping: Theme.dampingGentle } }+ Behavior on y { enabled: !Theme.reduceMotion; SpringAnimation { spring: Theme.springGentle; damping: Theme.dampingGentle } }}readonly property var pagesList: {try {const parsed = JSON.parse(DeckController.pagesJson)- return Array.isArray(parsed) && parsed.length > 0 ? parsed : [{ id: "main", name: "Main", tiles: [] }]+ return Array.isArray(parsed) && parsed.length > 0 ? parsed : [{ id: "main", name: qsTr("Main"), tiles: [] }]} catch (e) {- return [{ id: "main", name: "Main", tiles: [] }]+ return [{ id: "main", name: qsTr("Main"), tiles: [] }]}}property int currentPageIndex: 0- readonly property var currentPage: pagesList[Math.min(currentPageIndex, Math.max(0, pagesList.length - 1))] || { id: "main", name: "Main", tiles: [] }+ readonly property var currentPage: pagesList[Math.min(currentPageIndex, Math.max(0, pagesList.length - 1))] || { id: "main", name: qsTr("Main"), tiles: [] }readonly property var currentTiles: currentPage.tiles || []property int draggedTileIndex: -1@@ -298,10 +298,10 @@ Item {delegate: Chip {required property var modelDatarequired property int index+ interactive: trueselected: index === page.currentPageIndextext: "%1 (%2)".arg(modelData.name).arg((modelData.tiles || []).length)- HoverHandler { cursorShape: Qt.PointingHandCursor }- TapHandler { onTapped: page.currentPageIndex = index }+ onClicked: page.currentPageIndex = index}}@@ -385,13 +385,13 @@ Item {color: Theme.graphite? (tileHover.hovered ? Theme.surfaceContainer : "transparent"): (tileHover.hovered ? Theme.surfaceContainerHigh : Theme.tileColor)- border.width: isBeingDragged || tileSlot.activeFocus ? 2 : (Theme.graphite ? 1 : 0)- border.color: isBeingDragged || tileSlot.activeFocus+ border.width: isBeingDragged || Theme.focusVisible(tileSlot) ? 2 : (Theme.graphite ? 1 : 0)+ border.color: isBeingDragged || Theme.focusVisible(tileSlot)? Theme.primary: (tileSlot.highlighted ? Theme.surfaceContent : Theme.outlineVariant)- scale: isBeingDragged ? 0.97 : 1.0- Behavior on scale { NumberAnimation { duration: Theme.fadeFast } }- Behavior on color { ColorAnimation { duration: Theme.fadeFast } }+ scale: isBeingDragged ? Theme.pressScale : 1.0+ Behavior on scale { enabled: !Theme.reduceMotion; NumberAnimation { duration: Theme.fadeFast } }+ Behavior on color { enabled: !Theme.reduceMotion; ColorAnimation { duration: Theme.fadeFast } }// Top row: Icon badge + live status pill + quick test buttonItem {@@ -445,11 +445,20 @@ Item {anchors.verticalCenter: parent.verticalCenterwidth: 28; height: 28radius: 14+ activeFocusOnTab: truecolor: testHover.hovered ? Theme.surfaceContainerHighest : "transparent"- opacity: tileHover.hovered || testHover.hovered ? 1 : 0.55+ border.width: Theme.focusVisible(testBtn) ? 2 : 0+ border.color: Theme.primary+ opacity: tileHover.hovered || testHover.hovered || testBtn.activeFocus ? 1 : 0.55Accessible.role: Accessible.ButtonAccessible.name: qsTr("Test %1").arg(tileSlot.modelData.label)Accessible.onPressAction: DeckController.testTile(tileSlot.modelData.id)+ Keys.onPressed: (event) => {+ if (event.key === Qt.Key_Return || event.key === Qt.Key_Enter || event.key === Qt.Key_Space) {+ DeckController.testTile(tileSlot.modelData.id)+ event.accepted = true+ }+ }Icon {anchors.centerIn: parent@@ -550,8 +559,8 @@ Item {height: 112radius: Theme.radiusMdcolor: addHover.hovered ? Theme.surfaceContainerHigh : "transparent"- border.width: addTileBtn.activeFocus ? 2 : 1- border.color: addTileBtn.activeFocus ? Theme.primary : Theme.outlineVariant+ border.width: Theme.focusVisible(addTileBtn) ? 2 : 1+ border.color: Theme.focusVisible(addTileBtn) ? Theme.primary : Theme.outlineVariantid: addTileBtnactiveFocusOnTab: trueAccessible.role: Accessible.Button@@ -697,10 +706,10 @@ Item {model: page.actionChoicesdelegate: Chip {required property var modelData+ interactive: trueselected: editorSheet.actionKind === modelData.idtext: modelData.label- HoverHandler { cursorShape: Qt.PointingHandCursor }- TapHandler { onTapped: editorSheet.selectKind(modelData.id) }+ onClicked: editorSheet.selectKind(modelData.id)}}}@@ -721,28 +730,28 @@ Item {visible: editorSheet.actionKind === "shortcut"spacing: 8Chip {+ interactive: trueselected: editorSheet.modCtrl- text: "Ctrl"- HoverHandler { cursorShape: Qt.PointingHandCursor }- TapHandler { onTapped: editorSheet.modCtrl = !editorSheet.modCtrl }+ text: qsTr("Ctrl")+ onClicked: editorSheet.modCtrl = !editorSheet.modCtrl}Chip {+ interactive: trueselected: editorSheet.modAlt- text: "Alt"- HoverHandler { cursorShape: Qt.PointingHandCursor }- TapHandler { onTapped: editorSheet.modAlt = !editorSheet.modAlt }+ text: qsTr("Alt")+ onClicked: editorSheet.modAlt = !editorSheet.modAlt}Chip {+ interactive: trueselected: editorSheet.modShift- text: "Shift"- HoverHandler { cursorShape: Qt.PointingHandCursor }- TapHandler { onTapped: editorSheet.modShift = !editorSheet.modShift }+ text: qsTr("Shift")+ onClicked: editorSheet.modShift = !editorSheet.modShift}Chip {+ interactive: trueselected: editorSheet.modWin- text: "Win"- HoverHandler { cursorShape: Qt.PointingHandCursor }- TapHandler { onTapped: editorSheet.modWin = !editorSheet.modWin }+ text: qsTr("Win")+ onClicked: editorSheet.modWin = !editorSheet.modWin}}@@ -783,6 +792,7 @@ Item {font.pixelSize: 13text: editorSheet.paramValueonTextEdited: editorSheet.paramValue = text+ Accessible.name: qsTr("Action parameter")}}@@ -837,6 +847,7 @@ Item {editorSheet.tileLabel = texteditorSheet.labelCustomized = true}+ Accessible.name: qsTr("Tile label")}}}@@ -852,13 +863,25 @@ Item {Repeater {model: page.iconChoicesdelegate: Rectangle {+ id: iconCellrequired property string modelDatareadonly property bool chosen: editorSheet.tileIcon === modelDatawidth: 27; height: 27radius: Theme.radiusSm+ activeFocusOnTab: truecolor: chosen ? Theme.secondaryContainer : Theme.surfaceContainerHigh- border.width: chosen ? 2 : 0+ border.width: chosen || Theme.focusVisible(iconCell) ? 2 : 0border.color: Theme.primary+ Accessible.role: Accessible.RadioButton+ Accessible.name: modelData+ Accessible.checked: chosen+ Accessible.onPressAction: editorSheet.tileIcon = modelData+ Keys.onPressed: (event) => {+ if (event.key === Qt.Key_Return || event.key === Qt.Key_Enter || event.key === Qt.Key_Space) {+ editorSheet.tileIcon = modelData+ event.accepted = true+ }+ }Icon {anchors.centerIn: parentwidth: 15; height: 15@@ -956,6 +979,18 @@ Item {property bool isNew: truecardWidth: 380+ function submitPageName() {+ const trimmed = pageNameInput.text.trim()+ if (trimmed.length === 0) return+ if (pageNameSheet.isNew) {+ DeckController.addPage(trimmed)+ page.currentPageIndex = page.pagesList.length - 1+ } else {+ DeckController.renamePage(page.currentPage.id, trimmed)+ }+ pageNameSheet.close()+ }+Column {width: parent.widthspacing: 14@@ -985,6 +1020,9 @@ Item {selectedTextColor: Theme.primaryContainerContentfont.family: Theme.fontUifont.pixelSize: 14+ Accessible.name: qsTr("Page name")+ Keys.onReturnPressed: pageNameSheet.submitPageName()+ Keys.onEnterPressed: pageNameSheet.submitPageName()}}@@ -995,17 +1033,7 @@ Item {Button {variant: "fill"text: pageNameSheet.isNew ? qsTr("Create") : qsTr("Save")- onClicked: {- const trimmed = pageNameInput.text.trim()- if (trimmed.length === 0) return- if (pageNameSheet.isNew) {- DeckController.addPage(trimmed)- page.currentPageIndex = page.pagesList.length - 1- } else {- DeckController.renamePage(page.currentPage.id, trimmed)- }- pageNameSheet.close()- }+ onClicked: pageNameSheet.submitPageName()}}}diff --git a/desktop/app/qml/pages/HomePage.qml b/desktop/app/qml/pages/HomePage.qmlindex 3410541..04d0c5f 100644--- a/desktop/app/qml/pages/HomePage.qml+++ b/desktop/app/qml/pages/HomePage.qml@@ -43,7 +43,7 @@ Item {Behavior on opacity { NumberAnimation { duration: Theme.fadeNormal } }transform: Translate {y: page.active || Theme.reduceMotion ? 0 : 12- Behavior on y { SpringAnimation { spring: Theme.springGentle; damping: Theme.dampingGentle } }+ Behavior on y { enabled: !Theme.reduceMotion; SpringAnimation { spring: Theme.springGentle; damping: Theme.dampingGentle } }}onCurrentChanged: {@@ -199,11 +199,11 @@ Item {required property int indexrequired property string namerequired property string kind+ interactive: truetext: nameiconPath: kind === "tablet" || kind === "phone" ? Icons.phone : Icons.laptopselected: index === page.current- TapHandler { onTapped: page.current = index }- HoverHandler { cursorShape: Qt.PointingHandCursor }+ onClicked: page.current = index}}}@@ -263,6 +263,8 @@ Item {}// Files dragged onto the page are sent to the device on screen.+ // Holding Shift while dropping a single document hands it off so it opens+ // with the default app upon arrival.DropArea {id: dropanchors.fill: parent@@ -270,7 +272,11 @@ Item {onEntered: (drag) => drag.accepted = drag.hasUrlsonDropped: (drag) => {if (drag.hasUrls) {- TransferList.send(page.currentDeviceId, drag.urls.map(url => url.toString()))+ const urls = drag.urls.map(url => url.toString())+ if ((drag.modifiers & Qt.ShiftModifier) && urls.length === 1)+ TransferList.sendHandoff(page.currentDeviceId, urls)+ else+ TransferList.send(page.currentDeviceId, urls)drag.accept(Qt.CopyAction)}}@@ -287,7 +293,7 @@ Item {border.color: Theme.primaryColumn {anchors.centerIn: parent- spacing: 12+ spacing: 8Icon {anchors.horizontalCenter: parent.horizontalCenterwidth: 40; height: 40@@ -301,6 +307,13 @@ Item {color: Theme.primaryContainerContenttext: qsTr("Drop to send to %1").arg(page.currentDeviceName)}+ Txt {+ anchors.horizontalCenter: parent.horizontalCenter+ role: "bodySmall"+ color: Theme.primaryContainerContent+ opacity: 0.85+ text: qsTr("Hold Shift while dropping a document to open it on arrival")+ }}}@@ -739,18 +752,33 @@ Item {readonly property real pillWidth: pillCount > 1 ? (width - spacing) / 2 : widthRectangle {+ id: smsPillvisible: heroCard.hasSmswidth: commRow.pillWidthheight: smsPillRow.height + 14radius: Theme.radiusMd+ activeFocusOnTab: truereadonly property int unread: home.summaryData.unreadMessages || 0color: smsHover.hovered? Qt.rgba(Theme.surface.r, Theme.surface.g, Theme.surface.b, Theme.dark ? 0.48 : 0.68): Qt.rgba(Theme.surface.r, Theme.surface.g, Theme.surface.b, Theme.dark ? 0.34 : 0.48)- border.width: 1- border.color: unread > 0- ? Qt.rgba(Theme.primary.r, Theme.primary.g, Theme.primary.b, 0.45)- : Qt.rgba(Theme.heroContent.r, Theme.heroContent.g, Theme.heroContent.b, 0.10)+ border.width: Theme.focusVisible(smsPill) ? 2 : 1+ border.color: Theme.focusVisible(smsPill)+ ? Theme.primary+ : (unread > 0+ ? Qt.rgba(Theme.primary.r, Theme.primary.g, Theme.primary.b, 0.45)+ : Qt.rgba(Theme.heroContent.r, Theme.heroContent.g, Theme.heroContent.b, 0.10))+ Accessible.role: Accessible.Button+ Accessible.name: unread > 0+ ? qsTr("%n unread", "", unread)+ : qsTr("Messages")+ Accessible.onPressAction: AppController.currentPage = "messages"+ Keys.onPressed: (event) => {+ if (event.key === Qt.Key_Return || event.key === Qt.Key_Enter || event.key === Qt.Key_Space) {+ AppController.currentPage = "messages"+ event.accepted = true+ }+ }Row {id: smsPillRow@@ -782,7 +810,7 @@ Item {width: parent.widthrole: "caption"color: Theme.heroContent- opacity: 0.74+ opacity: 0.80elide: Text.ElideRighttext: (home.summaryData.unreadMessages || 0) > 0 && home.summaryData.unreadSender? home.summaryData.unreadSender@@ -795,18 +823,33 @@ Item {}Rectangle {+ id: callsPillvisible: heroCard.hasCallswidth: commRow.pillWidthheight: callsPillRow.height + 14radius: Theme.radiusMd+ activeFocusOnTab: truereadonly property int missed: home.summaryData.missedCalls || 0color: callsHover.hovered? Qt.rgba(Theme.surface.r, Theme.surface.g, Theme.surface.b, Theme.dark ? 0.48 : 0.68): Qt.rgba(Theme.surface.r, Theme.surface.g, Theme.surface.b, Theme.dark ? 0.34 : 0.48)- border.width: 1- border.color: missed > 0- ? Qt.rgba(Theme.primary.r, Theme.primary.g, Theme.primary.b, 0.45)- : Qt.rgba(Theme.heroContent.r, Theme.heroContent.g, Theme.heroContent.b, 0.10)+ border.width: Theme.focusVisible(callsPill) ? 2 : 1+ border.color: Theme.focusVisible(callsPill)+ ? Theme.primary+ : (missed > 0+ ? Qt.rgba(Theme.primary.r, Theme.primary.g, Theme.primary.b, 0.45)+ : Qt.rgba(Theme.heroContent.r, Theme.heroContent.g, Theme.heroContent.b, 0.10))+ Accessible.role: Accessible.Button+ Accessible.name: missed > 0+ ? qsTr("%n missed", "", missed)+ : qsTr("Calls")+ Accessible.onPressAction: AppController.currentPage = "calls"+ Keys.onPressed: (event) => {+ if (event.key === Qt.Key_Return || event.key === Qt.Key_Enter || event.key === Qt.Key_Space) {+ AppController.currentPage = "calls"+ event.accepted = true+ }+ }Row {id: callsPillRow@@ -838,7 +881,7 @@ Item {width: parent.widthrole: "caption"color: Theme.heroContent- opacity: 0.74+ opacity: 0.80elide: Text.ElideRighttext: (home.summaryData.missedCalls || 0) > 0 && home.summaryData.missedCaller? home.summaryData.missedCaller@@ -853,15 +896,30 @@ Item {// 3. Latest photo or screenshot (rounded thumbnail + relative time; click opens Photos).Rectangle {+ id: photoPillwidth: parent.widthheight: 52visible: heroCard.hasPhotosradius: Theme.radiusMd+ activeFocusOnTab: truecolor: photoHover.hovered? Qt.rgba(Theme.surface.r, Theme.surface.g, Theme.surface.b, Theme.dark ? 0.48 : 0.68): Qt.rgba(Theme.surface.r, Theme.surface.g, Theme.surface.b, Theme.dark ? 0.34 : 0.48)- border.width: 1- border.color: Qt.rgba(Theme.heroContent.r, Theme.heroContent.g, Theme.heroContent.b, 0.10)+ border.width: Theme.focusVisible(photoPill) ? 2 : 1+ border.color: Theme.focusVisible(photoPill)+ ? Theme.primary+ : Qt.rgba(Theme.heroContent.r, Theme.heroContent.g, Theme.heroContent.b, 0.10)+ Accessible.role: Accessible.Button+ Accessible.name: home.summaryData.photoIsScreenshot+ ? qsTr("Latest screenshot")+ : (home.summaryData.photoIsVideo ? qsTr("Latest video") : qsTr("Latest photo"))+ Accessible.onPressAction: AppController.currentPage = "photos"+ Keys.onPressed: (event) => {+ if (event.key === Qt.Key_Return || event.key === Qt.Key_Enter || event.key === Qt.Key_Space) {+ AppController.currentPage = "photos"+ event.accepted = true+ }+ }Row {x: 8@@ -915,7 +973,7 @@ Item {width: parent.widthrole: "caption"color: Theme.heroContent- opacity: 0.74+ opacity: 0.80elide: Text.ElideRighttext: {const when = home.summaryData.photoDate@@ -1090,12 +1148,302 @@ Item {}}}++ // ---- Type on phone with PC keyboard (without mirroring) ----+ Card {+ id: typeOnPhoneCard+ width: parent.width+ readonly property var controlFeature: home.feature("mirroring.control")+ readonly property bool available: controlFeature.state === "available"+ readonly property bool typingActive: Mirror.keyboardDevice === home.deviceId+ visible: home.online && (available || controlFeature.state === "locked" || typingActive)+ onTypingActiveChanged: {+ if (typingActive) {+ liveKeyCapture.forceActiveFocus(Qt.OtherFocusReason)+ }+ }+ Column {+ width: parent.width+ spacing: 10+ Item {+ width: parent.width+ height: Math.max(typeLeftRow.height, typeRightRow.height)+ Row {+ id: typeLeftRow+ anchors.left: parent.left+ anchors.right: typeRightRow.left+ anchors.rightMargin: 12+ anchors.verticalCenter: parent.verticalCenter+ spacing: 10+ Icon {+ anchors.verticalCenter: parent.verticalCenter+ width: 18; height: 18+ path: Icons.keyboard+ color: Theme.primary+ }+ Column {+ width: parent.width - 28+ anchors.verticalCenter: parent.verticalCenter+ spacing: 1+ Txt {+ width: parent.width+ role: "label"+ elide: Text.ElideRight+ text: typeOnPhoneCard.typingActive+ ? qsTr("Typing on %1").arg(home.name)+ : qsTr("Type on phone")+ }+ Txt {+ width: parent.width+ role: "caption"+ muted: true+ elide: Text.ElideRight+ text: typeOnPhoneCard.typingActive+ ? qsTr("Press keys in the capture box below, or compose text to send (Esc to stop).")+ : qsTr("Use this PC's keyboard on %1 without mirroring its screen.").arg(home.name)+ }+ }+ }+ Row {+ id: typeRightRow+ anchors.right: parent.right+ anchors.verticalCenter: parent.verticalCenter+ spacing: 8+ Button {+ visible: !typeOnPhoneCard.typingActive+ enabled: typeOnPhoneCard.available+ variant: "tonal"+ size: "sm"+ iconPath: Icons.keyboard+ text: qsTr("Start typing")+ onClicked: Mirror.toggleKeyboard(home.deviceId)+ }+ Button {+ visible: typeOnPhoneCard.typingActive+ variant: "outline"+ size: "sm"+ iconPath: Icons.close+ text: qsTr("Stop typing")+ onClicked: Mirror.stopKeyboard()+ }+ }+ }++ Column {+ width: parent.width+ visible: typeOnPhoneCard.typingActive+ spacing: 8++ FocusScope {+ id: liveKeyCapture+ width: parent.width+ height: 40+ activeFocusOnTab: true+ property string lastKeyStatus: ""+ Accessible.role: Accessible.EditableText+ Accessible.name: qsTr("Live keyboard capture for %1").arg(home.name)+ Accessible.description: qsTr("Type directly to send keystrokes to the phone, or press Escape to stop.")++ Rectangle {+ anchors.fill: parent+ anchors.margins: -3+ radius: (Theme.graphite ? Theme.radiusSm : 20) + 3+ color: "transparent"+ border.width: 2+ border.color: Theme.primary+ visible: Theme.focusVisible(liveKeyCapture)+ }++ Rectangle {+ anchors.fill: parent+ radius: Theme.graphite ? Theme.radiusSm : height / 2+ color: Theme.graphite ? "transparent" : Theme.surfaceContainerHighest+ border.width: liveKeyCapture.activeFocus ? 2 : 1+ border.color: liveKeyCapture.activeFocus ? Theme.primary : Theme.outlineVariant++ Row {+ anchors.left: parent.left+ anchors.leftMargin: 14+ anchors.right: parent.right+ anchors.rightMargin: 14+ anchors.verticalCenter: parent.verticalCenter+ spacing: 10+ Icon {+ anchors.verticalCenter: parent.verticalCenter+ width: 16; height: 16+ path: Icons.keyboard+ color: liveKeyCapture.activeFocus ? Theme.primary : Theme.surfaceContentVariant+ }+ Txt {+ width: parent.width - 26+ anchors.verticalCenter: parent.verticalCenter+ role: "bodySmall"+ muted: !liveKeyCapture.activeFocus+ elide: Text.ElideRight+ text: liveKeyCapture.activeFocus+ ? (liveKeyCapture.lastKeyStatus.length > 0+ ? qsTr("Live keys active · Sent: %1").arg(liveKeyCapture.lastKeyStatus)+ : qsTr("Live keys active — type here, or press Ctrl+V to paste"))+ : qsTr("Click here to capture live keystrokes")+ }+ }+ TapHandler {+ onTapped: liveKeyCapture.forceActiveFocus(Qt.MouseFocusReason)+ }+ }++ Keys.onPressed: (event) => {+ if (event.key === Qt.Key_Escape) {+ Mirror.stopKeyboard()+ event.accepted = true+ return+ }+ if ((event.modifiers & Qt.ControlModifier) && event.key === Qt.Key_V) {+ Mirror.keyboardPaste(home.deviceId)+ liveKeyCapture.lastKeyStatus = qsTr("Clipboard")+ event.accepted = true+ return+ }+ const names = {}+ names[Qt.Key_Return] = "enter"+ names[Qt.Key_Enter] = "enter"+ names[Qt.Key_Backspace] = "backspace"+ names[Qt.Key_Delete] = "delete"+ names[Qt.Key_Left] = "left"+ names[Qt.Key_Right] = "right"+ names[Qt.Key_Up] = "up"+ names[Qt.Key_Down] = "down"+ names[Qt.Key_Tab] = "tab"+ if (names[event.key]) {+ Mirror.keyboardPress(home.deviceId, names[event.key])+ liveKeyCapture.lastKeyStatus = names[event.key]+ event.accepted = true+ } else if (event.text.length > 0+ && !(event.modifiers & (Qt.ControlModifier | Qt.AltModifier | Qt.MetaModifier))+ && event.text.charCodeAt(0) >= 32) {+ Mirror.keyboardText(home.deviceId, event.text)+ liveKeyCapture.lastKeyStatus = event.text+ event.accepted = true+ }+ }+ }++ Row {+ width: parent.width+ spacing: 8+ Rectangle {+ id: composeBox+ width: Math.max(120, parent.width - sendComposeBtn.width - pasteBtn.width - backspaceBtn.width - enterKeyBtn.width - 32)+ height: 36+ radius: Theme.graphite ? Theme.radiusSm : height / 2+ color: Theme.graphite ? "transparent" : Theme.surfaceContainerHighest+ border.width: composeInput.activeFocus ? 2 : 1+ border.color: composeInput.activeFocus ? Theme.primary : Theme.outlineVariant+ TextInput {+ id: composeInput+ anchors.fill: parent+ anchors.leftMargin: 14+ anchors.rightMargin: 14+ verticalAlignment: TextInput.AlignVCenter+ font.family: Theme.fontUi+ font.pixelSize: 13+ color: Theme.surfaceContent+ selectionColor: Theme.primaryContainer+ selectedTextColor: Theme.primaryContainerContent+ clip: true+ Accessible.name: qsTr("Type text to send to %1").arg(home.name)+ Keys.onReturnPressed: {+ if (composeInput.text.length > 0) {+ Mirror.keyboardText(home.deviceId, composeInput.text)+ composeInput.text = ""+ } else {+ Mirror.keyboardPress(home.deviceId, "enter")+ }+ }+ Keys.onEnterPressed: {+ if (composeInput.text.length > 0) {+ Mirror.keyboardText(home.deviceId, composeInput.text)+ composeInput.text = ""+ } else {+ Mirror.keyboardPress(home.deviceId, "enter")+ }+ }+ Keys.onEscapePressed: Mirror.stopKeyboard()+ Txt {+ anchors.verticalCenter: parent.verticalCenter+ visible: composeInput.text.length === 0+ role: "bodySmall"+ muted: true+ elide: Text.ElideRight+ width: parent.width+ text: qsTr("Or type a phrase and press Enter…")+ }+ }+ }+ Button {+ id: sendComposeBtn+ variant: "tonal"+ size: "sm"+ enabled: composeInput.text.length > 0+ text: qsTr("Send")+ onClicked: {+ if (composeInput.text.length > 0) {+ Mirror.keyboardText(home.deviceId, composeInput.text)+ composeInput.text = ""+ }+ }+ }+ Button {+ id: pasteBtn+ variant: "outline"+ size: "sm"+ iconPath: Icons.clipboard+ text: qsTr("Paste")+ onClicked: Mirror.keyboardPaste(home.deviceId)+ }+ Button {+ id: backspaceBtn+ variant: "outline"+ size: "sm"+ iconPath: Icons.backspace+ text: qsTr("Bksp")+ onClicked: Mirror.keyboardPress(home.deviceId, "backspace")+ }+ Button {+ id: enterKeyBtn+ variant: "outline"+ size: "sm"+ text: qsTr("Enter")+ onClicked: Mirror.keyboardPress(home.deviceId, "enter")+ }+ }+ }++ LockChip {+ visible: !typeOnPhoneCard.available && label.length > 0+ feature: typeOnPhoneCard.controlFeature+ }+ }+ }FileDialog {id: filePickertitle: qsTr("Send to %1").arg(home.name)fileMode: FileDialog.OpenFilesonAccepted: TransferList.send(home.deviceId, selectedFiles.map(url => url.toString()))}+ FileDialog {+ id: handoffFilePicker+ title: qsTr("Hand off & open on %1").arg(home.name)+ fileMode: FileDialog.OpenFile+ onAccepted: TransferList.sendHandoff(home.deviceId, [selectedFile.toString()])+ }+ Connections {+ target: AppController+ enabled: home.visible+ function onHandoffFilePickerRequested() {+ handoffFilePicker.open()+ }+ }FolderDialog {id: folderPickertitle: qsTr("Send a folder to %1").arg(home.name)@@ -1231,6 +1579,8 @@ Item {clock: feedClock.minutesvisible: deviceId === home.deviceIdheight: visible ? implicitHeight : 0+ canOpenApp: home.feature("mirroring.app_windows").state === "available" && app.length > 0+ onOpenAppRequested: Mirror.startApp(deviceId, app, appName.length > 0 ? appName : app)onOptionsRequested: appSheet.openFor(app, appName)}add: Transition {@@ -1416,6 +1766,12 @@ Item {}onVisibleChanged: if (!visible) confirmWifiOff = false+ Shortcut {+ sequence: "Esc"+ enabled: page.active && phoneControls.confirmWifiOff+ onActivated: phoneControls.confirmWifiOff = false+ }+Column {width: parent.widthspacing: 12@@ -1648,12 +2004,25 @@ Item {required property var modelDatawidth: parent.widthheight: 36+ activeFocusOnTab: true+ Accessible.role: Accessible.Button+ Accessible.name: previewRow.modelData.title || ""+ Accessible.description: previewRow.modelData.subtitle || ""+ Accessible.onPressAction: AppController.currentPage = "timeline"+ Keys.onPressed: (event) => {+ if (event.key === Qt.Key_Return || event.key === Qt.Key_Enter || event.key === Qt.Key_Space) {+ AppController.currentPage = "timeline"+ event.accepted = true+ }+ }Rectangle {anchors.fill: parentanchors.margins: -4radius: Theme.radiusSmcolor: previewHover.hovered ? Theme.surfaceContainerHigh : "transparent"+ border.width: Theme.focusVisible(previewRow) ? 2 : 0+ border.color: Theme.primary}Icon {@@ -1938,8 +2307,17 @@ Item {Repeater {model: NotificationHistorydelegate: HistoryItem {+ required property string deviceId+ required property string appwidth: historyColumn.widthvisible: historySearch.matches([appName, title, text, sub])+ canOpenApp: (AppController.capsRevision >= 0+ && AppController.featureState(deviceId, "mirroring.app_windows").state === "available")+ && app.length > 0+ onOpenAppRequested: {+ historySheet.close()+ Mirror.startApp(deviceId, app, appName.length > 0 ? appName : app)+ }}}}@@ -2143,6 +2521,18 @@ Item {anchors.right: parent.rightanchors.verticalCenter: parent.verticalCenterspacing: 4+ IconButton {+ visible: page.currentDeviceId.length > 0+ && clipRow.modelData.kind === "text"+ && Boolean(clipRow.modelData.text)+ && AppController.isHandoffText(clipRow.modelData.text)+ iconPath: Icons.globe+ label: qsTr("Open on phone")+ onClicked: {+ clipboardSheet.close()+ AppController.openLinkOnPhone(page.currentDeviceId, clipRow.modelData.text)+ }+ }IconButton {iconPath: Icons.copylabel: qsTr("Copy")@@ -2205,11 +2595,11 @@ Item {border.width: Theme.focusVisible(tile) ? 2 : (Theme.graphite ? 1 : 0)border.color: Theme.focusVisible(tile) ? Theme.primary : Theme.outlineVariantscale: tap.pressed && available ? Theme.pressScale : 1- Behavior on scale { SpringAnimation { spring: Theme.springSnappy; damping: Theme.dampingSnappy } }- Behavior on color { ColorAnimation { duration: Theme.fadeFast } }+ Behavior on scale { enabled: !Theme.reduceMotion; SpringAnimation { spring: Theme.springSnappy; damping: Theme.dampingSnappy } }+ Behavior on color { enabled: !Theme.reduceMotion; ColorAnimation { duration: Theme.fadeFast } }transform: Translate {y: hover.hovered && tile.available && !tap.pressed ? -Theme.hoverLift : 0- Behavior on y { SpringAnimation { spring: Theme.springSnappy; damping: Theme.dampingSnappy } }+ Behavior on y { enabled: !Theme.reduceMotion; SpringAnimation { spring: Theme.springSnappy; damping: Theme.dampingSnappy } }}Accessible.role: Accessible.Button@@ -2245,7 +2635,7 @@ Item {width: parent.widthspacing: 3Txt { width: parent.width; text: tile.title; role: "title"; size: 14; color: tile.ink; opacity: tile.available ? 1 : 0.6 }- Txt { width: parent.width; visible: tile.available; text: tile.subtitle; role: "bodySmall"; color: tile.ink; opacity: 0.75 }+ Txt { width: parent.width; visible: tile.available; text: tile.subtitle; role: "bodySmall"; color: tile.ink; opacity: tile.active ? 0.82 : 1.0 }// Not built yet, or capabilities unknown until the device has// connected once.Txt {@@ -2321,8 +2711,8 @@ Item {border.color: Theme.focusVisible(qbtn) ? Theme.primary : Theme.outlineVariantopacity: qbtn.available || qbtn.active ? 1 : 0.55scale: qtap.pressed && qbtn.available ? Theme.pressScale : 1- Behavior on scale { SpringAnimation { spring: Theme.springSnappy; damping: Theme.dampingSnappy } }- Behavior on color { ColorAnimation { duration: Theme.fadeFast } }+ Behavior on scale { enabled: !Theme.reduceMotion; SpringAnimation { spring: Theme.springSnappy; damping: Theme.dampingSnappy } }+ Behavior on color { enabled: !Theme.reduceMotion; ColorAnimation { duration: Theme.fadeFast } }Column {anchors.centerIn: parent@@ -2451,6 +2841,16 @@ Item {readonly property real fraction: slider.shownValue / 100.0+ Rectangle {+ anchors.fill: parent+ anchors.margins: -3+ radius: 6+ color: "transparent"+ border.width: 2+ border.color: Theme.primary+ visible: Theme.focusVisible(barScope)+ }+Rectangle {anchors.verticalCenter: parent.verticalCenterwidth: parent.widthdiff --git a/desktop/app/qml/pages/MessagesPage.qml b/desktop/app/qml/pages/MessagesPage.qmlindex 6c3c4cf..f94486e 100644--- a/desktop/app/qml/pages/MessagesPage.qml+++ b/desktop/app/qml/pages/MessagesPage.qml@@ -109,7 +109,7 @@ Item {Behavior on opacity { NumberAnimation { duration: Theme.fadeNormal } }transform: Translate {y: page.active || Theme.reduceMotion ? 0 : 12- Behavior on y { SpringAnimation { spring: Theme.springGentle; damping: Theme.dampingGentle } }+ Behavior on y { enabled: !Theme.reduceMotion; SpringAnimation { spring: Theme.springGentle; damping: Theme.dampingGentle } }}function applyComposeTarget() {@@ -363,8 +363,8 @@ Item {required property var modelDatatext: modelData.labelselected: Messages.appFilter === modelData.key- HoverHandler { cursorShape: Qt.PointingHandCursor }- TapHandler { onTapped: Messages.filterByApp(modelData.key) }+ interactive: true+ onClicked: Messages.filterByApp(modelData.key)}}}@@ -609,6 +609,7 @@ Item {required property var modelDatawidth: suggestionColumn.widthheight: 52+ activeFocusOnTab: trueAccessible.role: Accessible.ListItemAccessible.name: modelData.name + ", " + modelData.numberAccessible.onPressAction: choose()@@ -616,6 +617,12 @@ Item {toField.text = modelData.numbercomposer.focusText()}+ Keys.onPressed: (event) => {+ if (event.key === Qt.Key_Return || event.key === Qt.Key_Enter || event.key === Qt.Key_Space) {+ srow.choose()+ event.accepted = true+ }+ }Rectangle {anchors.fill: parentanchors.leftMargin: 6@@ -624,6 +631,8 @@ Item {color: sHover.hovered? Qt.rgba(Theme.surfaceContent.r, Theme.surfaceContent.g, Theme.surfaceContent.b, 0.08): "transparent"+ border.width: Theme.focusVisible(srow) ? 2 : 0+ border.color: Theme.primary}Item {id: sFace@@ -1188,11 +1197,22 @@ Item {Repeater {model: bubble.message.imagesdelegate: Item {+ id: picItemrequired property string modelDatawidth: pictures.widthheight: modelData.length > 0 && picture.status === Image.Ready? Math.min(320, width * picture.implicitImageHeight / Math.max(1, picture.implicitImageWidth)): 140+ activeFocusOnTab: modelData.length > 0+ Accessible.role: Accessible.Button+ Accessible.name: qsTr("Open image attachment")+ Accessible.onPressAction: if (picItem.modelData.length > 0) Qt.openUrlExternally(picItem.modelData)+ Keys.onPressed: (event) => {+ if (picItem.modelData.length > 0 && (event.key === Qt.Key_Return || event.key === Qt.Key_Enter || event.key === Qt.Key_Space)) {+ Qt.openUrlExternally(picItem.modelData)+ event.accepted = true+ }+ }RoundedImage {id: pictureanchors.fill: parent@@ -1201,6 +1221,14 @@ Item {fillMode: Image.PreserveAspectCropsourceSize.width: 520}+ Rectangle {+ anchors.fill: parent+ radius: 18+ color: "transparent"+ border.width: 2+ border.color: Theme.primary+ visible: Theme.focusVisible(picItem)+ }Spinner { anchors.centerIn: parent; visible: parent.modelData.length === 0 }TapHandler { onTapped: if (parent.modelData.length > 0) Qt.openUrlExternally(parent.modelData) }HoverHandler { cursorShape: parent.modelData.length > 0 ? Qt.PointingHandCursor : Qt.ArrowCursor }diff --git a/desktop/app/qml/pages/PhotosPage.qml b/desktop/app/qml/pages/PhotosPage.qmlindex 370db50..ab012ba 100644--- a/desktop/app/qml/pages/PhotosPage.qml+++ b/desktop/app/qml/pages/PhotosPage.qml@@ -102,9 +102,12 @@ Item {function formatBytes(bytes) {if (!bytes || bytes <= 0) return ""- if (bytes < 1024) return bytes + " B"- if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(0) + " KB"- return (bytes / (1024 * 1024)).toFixed(1) + " MB"+ if (bytes < 1024) return qsTr("%1 B").arg(Math.round(bytes))+ const units = [qsTr("%1 KB"), qsTr("%1 MB"), qsTr("%1 GB"), qsTr("%1 TB")]+ let value = bytes / 1024+ let unit = 0+ while (value >= 1024 && unit < units.length - 1) { value /= 1024; unit++ }+ return units[unit].arg(unit === 0 ? Math.round(value) : (value < 10 ? value.toFixed(1) : Math.round(value)))}function isSelected(id) {@@ -188,7 +191,7 @@ Item {Behavior on opacity { NumberAnimation { duration: Theme.fadeNormal } }transform: Translate {y: page.active || Theme.reduceMotion ? 0 : 12- Behavior on y { SpringAnimation { spring: Theme.springGentle; damping: Theme.dampingGentle } }+ Behavior on y { enabled: !Theme.reduceMotion; SpringAnimation { spring: Theme.springGentle; damping: Theme.dampingGentle } }}// Keyboard shortcuts for viewer navigation and selection.@@ -399,7 +402,9 @@ Item {visible: Photos.count > 0role: "caption"muted: true- text: Photos.more ? qsTr("%1+ items").arg(Photos.count) : qsTr("%1 items").arg(Photos.count)+ text: Photos.more+ ? qsTr("%1+ items").arg(Photos.count)+ : (Photos.count === 1 ? qsTr("1 item") : qsTr("%1 items").arg(Photos.count))}}@@ -453,6 +458,7 @@ Item {anchors.verticalCenter: parent.verticalCentervisible: Photos.count > 0iconPath: Icons.folder+ interactive: truetext: {const f = Photos.saveFolder || ""if (!gridPane.compactBar) return f@@ -460,8 +466,7 @@ Item {return parts.length > 0 && parts[parts.length - 1].length > 0? parts[parts.length - 1] : f}- TapHandler { onTapped: defaultFolderPicker.open() }- HoverHandler { cursorShape: Qt.PointingHandCursor }+ onClicked: defaultFolderPicker.open()}Button {@@ -908,6 +913,7 @@ Item {// Video play button overlay in viewer.Rectangle {+ id: playOverlayBtnanchors.centerIn: parentvisible: page.viewedItem !== null && !!page.viewedItem.isVideowidth: 76; height: 76@@ -916,7 +922,27 @@ Item {border.width: 2border.color: "#ffffff"scale: playTap.pressed ? Theme.pressScale : 1- Behavior on scale { SpringAnimation { spring: Theme.springSnappy; damping: Theme.dampingSnappy } }+ Behavior on scale { enabled: !Theme.reduceMotion; SpringAnimation { spring: Theme.springSnappy; damping: Theme.dampingSnappy } }+ activeFocusOnTab: true+ Accessible.role: Accessible.Button+ Accessible.name: qsTr("Play video")+ Accessible.onPressAction: if (page.viewedItem) Photos.openItem(page.viewedItem.id)+ Keys.onPressed: (event) => {+ if (event.key === Qt.Key_Return || event.key === Qt.Key_Enter || event.key === Qt.Key_Space) {+ if (page.viewedItem)+ Photos.openItem(page.viewedItem.id)+ event.accepted = true+ }+ }+ Rectangle {+ anchors.fill: parent+ anchors.margins: -3+ radius: parent.radius + 3+ color: "transparent"+ border.width: 2+ border.color: Theme.primary+ visible: Theme.focusVisible(playOverlayBtn)+ }Icon {anchors.centerIn: parentwidth: 30; height: 30@@ -989,8 +1015,8 @@ Item {: albumHover.hovered? Qt.rgba(Theme.surfaceContent.r, Theme.surfaceContent.g, Theme.surfaceContent.b, 0.06): "transparent"- border.width: albumRow.activeFocus ? 2 : (Theme.graphite && albumRow.selected ? 1 : 0)- border.color: albumRow.activeFocus ? Theme.primary : Theme.surfaceContent+ border.width: Theme.focusVisible(albumRow) ? 2 : (Theme.graphite && albumRow.selected ? 1 : 0)+ border.color: Theme.focusVisible(albumRow) ? Theme.primary : Theme.surfaceContentItem {id: coverBox@@ -1111,8 +1137,8 @@ Item {anchors.margins: 4radius: Theme.radiusSmcolor: Theme.surfaceContainerHigh- border.width: tile.selected ? 3 : (tile.activeFocus ? 2 : (Theme.graphite ? 1 : 0))- border.color: (tile.selected || tile.activeFocus) ? Theme.primary : Theme.outlineVariant+ border.width: tile.selected ? 3 : (Theme.focusVisible(tile) ? 2 : (Theme.graphite ? 1 : 0))+ border.color: (tile.selected || Theme.focusVisible(tile)) ? Theme.primary : Theme.outlineVariantclip: trueIcon {@@ -1220,6 +1246,12 @@ Item {color: tile.selected ? Theme.primary : Qt.rgba(0, 0, 0, 0.48)border.width: tile.selected ? 0 : 1.5border.color: "#ffffff"+ Accessible.role: Accessible.CheckBox+ Accessible.name: qsTr("Select photo")+ Accessible.checkable: true+ Accessible.checked: tile.selected+ Accessible.onPressAction: page.toggleSelect(tile.itemId, tile.index, false)+ Accessible.onToggleAction: page.toggleSelect(tile.itemId, tile.index, false)Icon {anchors.centerIn: parentvisible: tile.selecteddiff --git a/desktop/app/qml/pages/SettingsPage.qml b/desktop/app/qml/pages/SettingsPage.qmlindex 1387e6d..ecd87cf 100644--- a/desktop/app/qml/pages/SettingsPage.qml+++ b/desktop/app/qml/pages/SettingsPage.qml@@ -34,12 +34,16 @@ Item {function formatRetentionBytes(bytes) {const b = Number(bytes || 0)if (b <= 0)- return "0 B"+ return qsTr("%1 B").arg(0)if (b < 1024)- return b + " B"+ return qsTr("%1 B").arg(b)if (b < 1024 * 1024)- return Math.max(1, Math.round(b / 1024)) + " KB"- return (b / (1024 * 1024)).toFixed(1) + " MB"+ return qsTr("%1 KB").arg(Math.max(1, Math.round(b / 1024)))+ if (b < 1024 * 1024 * 1024)+ return qsTr("%1 MB").arg((b / (1024 * 1024)).toFixed(1))+ if (b < 1024 * 1024 * 1024 * 1024)+ return qsTr("%1 GB").arg((b / (1024 * 1024 * 1024)).toFixed(1))+ return qsTr("%1 TB").arg((b / (1024 * 1024 * 1024 * 1024)).toFixed(1))}opacity: active ? 1 : 0@@ -47,7 +51,7 @@ Item {Behavior on opacity { NumberAnimation { duration: Theme.fadeNormal } }transform: Translate {y: page.active || Theme.reduceMotion ? 0 : 12- Behavior on y { SpringAnimation { spring: Theme.springGentle; damping: Theme.dampingGentle } }+ Behavior on y { enabled: !Theme.reduceMotion; SpringAnimation { spring: Theme.springGentle; damping: Theme.dampingGentle } }}readonly property var toggleNames: ({@@ -428,6 +432,12 @@ Item {Accessible.name: modelData.labelAccessible.checked: selectedAccessible.onPressAction: Preferences.seed = modelData.key+ Keys.onPressed: (event) => {+ if (event.key === Qt.Key_Return || event.key === Qt.Key_Enter || event.key === Qt.Key_Space) {+ Preferences.seed = narrowPhoneSwatch.modelData.key+ event.accepted = true+ }+ }Row {id: narrowPhoneRowanchors.centerIn: parent@@ -635,6 +645,53 @@ Item {}}Divider { width: parent.width }+ ListRow {+ width: parent.width+ iconPath: Icons.folder+ title: qsTr("Shelf shortcut")+ description: qsTr("Global shortcut to slide out the Shelf at the screen edge without stealing focus.")+ Row {+ spacing: 8+ Button {+ anchors.verticalCenter: parent.verticalCenter+ visible: Preferences.shelfHotkey !== "Ctrl+Alt+S"+ variant: "text"+ size: "sm"+ text: qsTr("Reset")+ onClicked: {+ shelfHotkeyInput.text = "Ctrl+Alt+S"+ Preferences.shelfHotkey = "Ctrl+Alt+S"+ }+ }+ Rectangle {+ anchors.verticalCenter: parent.verticalCenter+ width: 132+ height: 32+ radius: Theme.radiusSm+ color: Theme.surfaceContainerHighest+ border.width: shelfHotkeyInput.activeFocus ? 2 : 1+ border.color: shelfHotkeyInput.activeFocus ? Theme.primary : Theme.outlineVariant+ TextInput {+ id: shelfHotkeyInput+ anchors.fill: parent+ anchors.leftMargin: 10+ anchors.rightMargin: 10+ verticalAlignment: TextInput.AlignVCenter+ horizontalAlignment: TextInput.AlignHCenter+ font.family: Theme.fontUi+ font.pixelSize: 13+ color: Theme.surfaceContent+ selectionColor: Theme.primaryContainer+ selectedTextColor: Theme.primaryContainerContent+ clip: true+ text: Preferences.shelfHotkey+ onEditingFinished: Preferences.shelfHotkey = text.trim()+ Accessible.name: qsTr("Shelf shortcut")+ }+ }+ }+ }+ Divider { width: parent.width }ListRow {width: parent.widthiconPath: Icons.camera@@ -837,10 +894,10 @@ Item {delegate: Chip {required property string deviceIdrequired property string name+ interactive: truetext: nameselected: Webcam.selectedPhone === deviceId- TapHandler { onTapped: Webcam.selectPhone(deviceId) }- HoverHandler { cursorShape: Qt.PointingHandCursor }+ onClicked: Webcam.selectPhone(deviceId)}}}@@ -965,8 +1022,9 @@ Item {? qsTr("%1 · Wake on Magic Packet is on. If this PC still won't wake from sleep or shutdown, check that Wake-on-LAN is enabled in BIOS/UEFI.").arg(adapter): qsTr("%1 · Wake on Magic Packet is on. Wi-Fi wake usually works from sleep, not full shutdown; use Ethernet for shutdown wake.").arg(adapter)}- const wifiNote = wired ? "" : qsTr(" Wi-Fi wake rarely works from shutdown.")- return qsTr("%1 · To wake this PC while it sleeps or is shut down, enable Wake on Magic Packet in Device Manager → Network adapters → %1 → Properties (Advanced tab → Wake on Magic Packet → Enabled; Power Management tab → Allow this device to wake the computer, Only allow a magic packet), and enable Wake-on-LAN in BIOS/UEFI.%2").arg(adapter).arg(wifiNote)+ return wired+ ? qsTr("%1 · To wake this PC while it sleeps or is shut down, enable Wake on Magic Packet in Device Manager → Network adapters → %1 → Properties (Advanced tab → Wake on Magic Packet → Enabled; Power Management tab → Allow this device to wake the computer, Only allow a magic packet), and enable Wake-on-LAN in BIOS/UEFI.").arg(adapter)+ : qsTr("%1 · To wake this PC while it sleeps or is shut down, enable Wake on Magic Packet in Device Manager → Network adapters → %1 → Properties (Advanced tab → Wake on Magic Packet → Enabled; Power Management tab → Allow this device to wake the computer, Only allow a magic packet), and enable Wake-on-LAN in BIOS/UEFI. Wi-Fi wake rarely works from shutdown.").arg(adapter)}Row {spacing: 6@@ -1124,8 +1182,10 @@ Item {title: qsTr("Cross-device timeline")description: {const count = Number(page.retentionSummary.timelineItems || 0)- return qsTr("Searchable local history of files, clips, links, photos, recordings and sessions (%1 items · up to 5,000).")- .arg(count)+ return count === 1+ ? qsTr("Searchable local history of files, clips, links, photos, recordings and sessions (1 item · up to 5,000).")+ : qsTr("Searchable local history of files, clips, links, photos, recordings and sessions (%1 items · up to 5,000).")+ .arg(count)}Row {spacing: 8@@ -1172,7 +1232,7 @@ Item {description: {const count = Number(page.retentionSummary.notificationHistory || 0)const size = page.formatRetentionBytes(page.retentionSummary.notificationImageBytes)- return qsTr("24 hours · up to 100 dismissed notifications (%1 stored · %2 of cached images).")+ return qsTr("24 hours · up to 300 dismissed notifications (%1 stored · %2 of cached images).").arg(count).arg(size)}@@ -1207,12 +1267,15 @@ Item {description: {const chatThreads = Number(page.retentionSummary.chatThreads || 0)const smsThreads = Number(page.retentionSummary.cachedSmsThreads || 0)+ const convs = chatThreads + smsThreadsconst totalMsgs = Number(page.retentionSummary.chatMessages || 0)+ Number(page.retentionSummary.cachedSmsMessages || 0)const size = page.formatRetentionBytes(page.retentionSummary.messageAttachmentBytes)- return qsTr("90 days · up to 500 messages per conversation (%1 conversations · %2 messages · %3 of attachments).")- .arg(chatThreads + smsThreads)- .arg(totalMsgs)+ const convPart = convs === 1 ? qsTr("1 conversation") : qsTr("%1 conversations").arg(convs)+ const msgPart = totalMsgs === 1 ? qsTr("1 message") : qsTr("%1 messages").arg(totalMsgs)+ return qsTr("90 days · up to 200 messages per conversation (%1 · %2 · %3 of attachments).")+ .arg(convPart)+ .arg(msgPart).arg(size)}Button {@@ -1236,9 +1299,11 @@ Item {description: {const files = Number(page.retentionSummary.photoThumbFiles || 0)const size = page.formatRetentionBytes(page.retentionSummary.photoThumbBytes)- return qsTr("30 days · up to 500 cached thumbnails (%1 files · %2). Original photos on your phone are never touched.")- .arg(files)- .arg(size)+ return files === 1+ ? qsTr("30 days · up to 500 cached thumbnails (1 file · %1). Original photos on your phone are never touched.").arg(size)+ : qsTr("30 days · up to 500 cached thumbnails (%1 files · %2). Original photos on your phone are never touched.")+ .arg(files)+ .arg(size)}Button {variant: "text"@@ -1256,8 +1321,10 @@ Item {title: qsTr("Received file transfer history")description: {const records = Number(page.retentionSummary.receivedFileRecords || 0)- return qsTr("Kept with timeline · %1 transfer records on this PC. Saved files in Downloads are kept.")- .arg(records)+ return records === 1+ ? qsTr("Kept with timeline · 1 transfer record on this PC. Saved files in Downloads are kept.")+ : qsTr("Kept with timeline · %1 transfer records on this PC. Saved files in Downloads are kept.")+ .arg(records)}Button {variant: "text"diff --git a/desktop/app/qml/pages/TimelinePage.qml b/desktop/app/qml/pages/TimelinePage.qmlindex d15e7fb..a6cd665 100644--- a/desktop/app/qml/pages/TimelinePage.qml+++ b/desktop/app/qml/pages/TimelinePage.qml@@ -18,7 +18,18 @@ Item {Behavior on opacity { NumberAnimation { duration: Theme.fadeNormal } }transform: Translate {y: page.active || Theme.reduceMotion ? 0 : 12- Behavior on y { SpringAnimation { spring: Theme.springGentle; damping: Theme.dampingGentle } }+ Behavior on y { enabled: !Theme.reduceMotion; SpringAnimation { spring: Theme.springGentle; damping: Theme.dampingGentle } }+ }++ Shortcut {+ sequence: "Esc"+ enabled: page.active && (page.deviceMenuOpen || page.confirmClearAll)+ onActivated: {+ if (page.deviceMenuOpen)+ page.deviceMenuOpen = false+ else if (page.confirmClearAll)+ page.confirmClearAll = false+ }}readonly property var kindOptions: [@@ -150,6 +161,12 @@ Item {clip: truetext: TimelineModel.searchQueryonTextEdited: TimelineModel.searchQuery = text+ Accessible.name: qsTr("Search timeline")+ Keys.onEscapePressed: (event) => {+ event.accepted = text.length > 0+ text = ""+ TimelineModel.searchQuery = ""+ }}Txt {anchors.left: searchInput.left@@ -207,16 +224,14 @@ Item {model: page.kindOptionsdelegate: Chip {required property var modelData+ interactive: truetext: modelData.labeliconPath: modelData.iconselected: TimelineModel.kindFilter === modelData.key- TapHandler {- onTapped: {- page.deviceMenuOpen = false- TimelineModel.kindFilter = modelData.key- }+ onClicked: {+ page.deviceMenuOpen = false+ TimelineModel.kindFilter = modelData.key}- HoverHandler { cursorShape: Qt.PointingHandCursor }}}}@@ -230,6 +245,7 @@ Item {readonly property real maxAllowedWidth: Math.max(110, filterBar.width - kindRow.width - 12)width: Math.min(maxAllowedWidth, deviceBtnRow.implicitWidth + 22)radius: Theme.pill(height)+ activeFocusOnTab: truereadonly property bool filtered: TimelineModel.deviceFilter.length > 0color: Theme.graphite? (filtered ? Theme.surfaceContent : "transparent")@@ -238,11 +254,27 @@ Item {border.color: page.deviceMenuOpen? Theme.primary: (filtered ? Theme.surfaceContent : Theme.outlineVariant)- Behavior on color { ColorAnimation { duration: Theme.fadeFast } }+ Behavior on color { enabled: !Theme.reduceMotion; ColorAnimation { duration: Theme.fadeFast } }Accessible.role: Accessible.ComboBoxAccessible.name: qsTr("Device filter: %1").arg(page.selectedDeviceName)Accessible.onPressAction: page.deviceMenuOpen = !page.deviceMenuOpen+ Keys.onPressed: (event) => {+ if (event.key === Qt.Key_Return || event.key === Qt.Key_Enter || event.key === Qt.Key_Space) {+ page.deviceMenuOpen = !page.deviceMenuOpen+ event.accepted = true+ }+ }++ Rectangle {+ anchors.fill: parent+ anchors.margins: -3+ radius: parent.radius + 3+ color: "transparent"+ border.width: 2+ border.color: Theme.primary+ visible: Theme.focusVisible(deviceDropdownBtn)+ }Row {id: deviceBtnRow@@ -605,10 +637,27 @@ Item {spacing: 2Rectangle {+ id: allDevItemwidth: parent.widthheight: 32radius: Theme.radiusSm+ activeFocusOnTab: truecolor: allDevHover.hovered ? Theme.surfaceContainerHigh : "transparent"+ border.width: Theme.focusVisible(allDevItem) ? 2 : 0+ border.color: Theme.primary+ Accessible.role: Accessible.MenuItem+ Accessible.name: qsTr("All devices")+ Accessible.onPressAction: {+ TimelineModel.deviceFilter = ""+ page.deviceMenuOpen = false+ }+ Keys.onPressed: (event) => {+ if (event.key === Qt.Key_Return || event.key === Qt.Key_Enter || event.key === Qt.Key_Space) {+ TimelineModel.deviceFilter = ""+ page.deviceMenuOpen = false+ event.accepted = true+ }+ }Row {x: 10@@ -650,6 +699,7 @@ Item {Repeater {model: DeviceList.count > 1 ? DeviceList : nulldelegate: Rectangle {+ id: devOptItemrequired property string deviceIdrequired property string namerequired property string kind@@ -657,7 +707,23 @@ Item {width: deviceMenuCol.widthheight: 32radius: Theme.radiusSm+ activeFocusOnTab: truecolor: devOptHover.hovered ? Theme.surfaceContainerHigh : "transparent"+ border.width: Theme.focusVisible(devOptItem) ? 2 : 0+ border.color: Theme.primary+ Accessible.role: Accessible.MenuItem+ Accessible.name: name+ Accessible.onPressAction: {+ TimelineModel.deviceFilter = deviceId+ page.deviceMenuOpen = false+ }+ Keys.onPressed: (event) => {+ if (event.key === Qt.Key_Return || event.key === Qt.Key_Enter || event.key === Qt.Key_Space) {+ TimelineModel.deviceFilter = deviceId+ page.deviceMenuOpen = false+ event.accepted = true+ }+ }Row {x: 10diff --git a/desktop/app/src/bridge/app.rs b/desktop/app/src/bridge/app.rsindex 9feeed2..4e43bec 100644--- a/desktop/app/src/bridge/app.rs+++ b/desktop/app/src/bridge/app.rs@@ -123,6 +123,9 @@ pub mod qobject {#[qproperty(bool, localsend_enabled)]#[qproperty(bool, localsend_receiving)]#[qproperty(QString, localsend_peers_json)]+ /// Slide-out edge Shelf state and JSON items (`""` while closed so nothing runs while hidden).+ #[qproperty(bool, shelf_open)]+ #[qproperty(QString, shelf_items)]type AppController = super::AppControllerRust;/// Enables or disables LocalSend LAN discovery and file sharing.@@ -132,6 +135,33 @@ pub mod qobject {#[qinvokable]fn refresh_localsend(self: Pin<&mut AppController>);+ /// Toggles the slide-out Shelf panel at the screen edge without stealing focus.+ #[qinvokable]+ fn toggle_shelf(self: Pin<&mut AppController>);+ /// Hides the Shelf panel and releases its cached items.+ #[qinvokable]+ fn close_shelf(self: Pin<&mut AppController>);+ /// Recomputes the Shelf items while the Shelf is open.+ #[qinvokable]+ fn refresh_shelf(self: Pin<&mut AppController>);+ /// Applies Win32 `WS_EX_NOACTIVATE | WS_EX_TOOLWINDOW | WS_EX_TOPMOST` to the Shelf window.+ #[qinvokable]+ fn style_shelf_window(self: &AppController);+ /// Starts a native OS drag-out operation for a Shelf item (photo, screenshot, clip, or file).+ #[qinvokable]+ fn start_shelf_drag(+ self: &AppController,+ kind: &QString,+ id_or_path: &QString,+ text: &QString,+ ) -> bool;+ /// Sends files, images, links, or text dropped onto the Shelf to the active phone.+ #[qinvokable]+ fn drop_to_shelf(self: &AppController, urls: &QList_QVariant, text: &QString);+ /// Opens, reveals, saves, or copies a Shelf item.+ #[qinvokable]+ fn activate_shelf_item(self: &AppController, kind: &QString, action: &QString, id_or_path: &QString);+/// Asks a paired device to ring (or stop).#[qinvokable]fn ring(self: Pin<&mut AppController>, device: &QString, on: bool);@@ -189,6 +219,12 @@ pub mod qobject {/// Runs the suggested action for the most recently received clipboard item.#[qinvokable]fn run_clip_suggestion(self: &AppController);+ /// Hands off a web link, video URL (with timestamp), `geo:` URI, or street address to a phone.+ #[qinvokable]+ fn open_link_on_phone(self: &AppController, device: &QString, text: &QString);+ /// Whether `text` is a web link, video URL, `geo:` URI, or street address that can be handed off.+ #[qinvokable]+ fn is_handoff_text(self: &AppController, text: &QString) -> bool;/// Starts a Continuity Camera capture (`"photo"` or `"scan"`) on the active phone.#[qinvokable]@@ -294,6 +330,9 @@ pub mod qobject {/// Show the Connection Doctor.#[qsignal]fn doctor_requested(self: Pin<&mut AppController>);+ /// Open the Handoff document picker on the Home page.+ #[qsignal]+ fn handoff_file_picker_requested(self: Pin<&mut AppController>);}impl cxx_qt::Threading for AppController {}@@ -350,12 +389,27 @@ pub struct AppControllerRust {localsend_enabled: bool,localsend_receiving: bool,localsend_peers_json: QString,+ shelf_open: bool,+ shelf_items: QString,tray: Option<tray::Tray>,}/// The controller's thread handle, so other threads (second launch) can/// reach it.static CONTROLLER: OnceLock<Mutex<Option<CxxQtThread<qobject::AppController>>>> = OnceLock::new();+static SHELF_OPEN: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);++/// Whether the slide-out Shelf panel is currently open.+pub fn is_shelf_open() -> bool {+ SHELF_OPEN.load(Ordering::Relaxed)+}++/// Toggles the slide-out Shelf panel from any thread (Command Palette, tray, or hotkey).+pub fn toggle_shelf_from_anywhere() {+ if let Some(qt) = controller() {+ let _ = qt.queue(|object| object.toggle_shelf());+ }+}/// Downloads and starts the update (from the app or its notification).pub fn install_update_in_background() {@@ -497,6 +551,7 @@ impl cxx_qt::Initialize for qobject::AppController {self.as_mut().set_command_palette_results(QString::from("[]"));self.as_mut().set_data_retention_summary(QString::from(&compute_data_retention_json()));self.as_mut().set_localsend_peers_json(QString::from("[]"));+ self.as_mut().set_shelf_items(QString::default());let initial_phone_colors = core_host::host().hub.read(|s| phone_colors_json(&s.devices));self.as_mut().set_phone_colors(QString::from(&initial_phone_colors));self.as_mut().refresh_appearance();@@ -521,11 +576,25 @@ impl cxx_qt::Initialize for qobject::AppController {let json = crate::clipboard::history_json();object.as_mut().set_clipboard_history(QString::from(&json));let preview = super::timeline::preview_json();- object.set_timeline_preview(QString::from(&preview));+ object.as_mut().set_timeline_preview(QString::from(&preview));+ if object.shelf_open {+ let shelf = compute_shelf_items_json(object.current_device);+ object.set_shelf_items(QString::from(&shelf));+ }});- super::subscribe(qt.clone(), Changes::TIMELINE | Changes::DEVICES | Changes::STATUS, |object| {+ super::subscribe(qt.clone(), Changes::TIMELINE | Changes::DEVICES | Changes::STATUS, |mut object| {let preview = super::timeline::preview_json();- object.set_timeline_preview(QString::from(&preview));+ object.as_mut().set_timeline_preview(QString::from(&preview));+ if object.shelf_open {+ let shelf = compute_shelf_items_json(object.current_device);+ object.set_shelf_items(QString::from(&shelf));+ }+ });+ super::subscribe(qt.clone(), Changes::TRANSFERS | Changes::PHOTOS, |mut object| {+ if object.shelf_open {+ let shelf = compute_shelf_items_json(object.current_device);+ object.as_mut().set_shelf_items(QString::from(&shelf));+ }});super::subscribe(qt.clone(), Changes::CONTINUITY, Self::refresh_continuity);super::subscribe(qt.clone(), Changes::PALETTE, Self::refresh_palette);@@ -548,6 +617,7 @@ impl cxx_qt::Initialize for qobject::AppController {let labels = tray::MenuLabels {open: "Open Nectarlink".into(),command_palette: "Command palette".into(),+ shelf: "Toggle Shelf".into(),take_photo: "Take photo with phone".into(),scan_document: "Scan document with phone".into(),find_phone: "Find my phone".into(),@@ -574,6 +644,9 @@ fn on_tray_event(qt: &CxxQtThread<qobject::AppController>, event: tray::TrayEvenobject.activate_requested();});}+ tray::TrayEvent::Shelf => {+ let _ = qt.queue(|object| object.toggle_shelf());+ }tray::TrayEvent::TakePhoto => crate::continuity_camera::start("photo"),tray::TrayEvent::ScanDocument => crate::continuity_camera::start("scan"),tray::TrayEvent::OpenLinkOnPhone => crate::links::open_copied_link_on_phone(),@@ -884,6 +957,16 @@ impl qobject::AppController {crate::clipboard::run_last_suggestion();}+ pub fn open_link_on_phone(&self, device: &QString, text: &QString) {+ if let Some(id) = super::parse_device(device) {+ crate::links::send_to(id, String::from(text));+ }+ }++ pub fn is_handoff_text(&self, text: &QString) -> bool {+ crate::links::is_handoff_text(&String::from(text))+ }+pub fn start_continuity_camera(&self, mode: &QString) {let idx = self.current_device.max(0) as usize;crate::continuity_camera::start_for_index(idx, &String::from(mode));@@ -954,6 +1037,14 @@ impl qobject::AppController {open_dialer(dev, &number);}}+ PaletteUiAction::OpenHandoffFilePicker { device_index } => {+ if let Some(idx) = device_index {+ self.as_mut().set_current_device(idx as i32);+ }+ self.as_mut().set_current_page(QString::from("home"));+ self.as_mut().activate_requested();+ self.handoff_file_picker_requested();+ }PaletteUiAction::OpenDoctor => {self.run_doctor();}@@ -1222,6 +1313,486 @@ impl qobject::AppController {self.as_mut().refresh_data_retention();self.toast(QString::from("Cleared all local history and caches"));}++ pub fn toggle_shelf(mut self: Pin<&mut Self>) {+ if self.shelf_open {+ self.close_shelf();+ } else {+ SHELF_OPEN.store(true, Ordering::Relaxed);+ let idx = self.current_device;+ let json = compute_shelf_items_json(idx);+ self.as_mut().set_shelf_items(QString::from(&json));+ self.as_mut().set_shelf_open(true);+ win::tray::apply_no_activate_style_by_title("Nectarlink Shelf");+ }+ }++ pub fn close_shelf(mut self: Pin<&mut Self>) {+ SHELF_OPEN.store(false, Ordering::Relaxed);+ self.as_mut().set_shelf_open(false);+ self.as_mut().set_shelf_items(QString::default());+ }++ pub fn refresh_shelf(mut self: Pin<&mut Self>) {+ if !self.shelf_open {+ return;+ }+ if let (Some(dev), _, true) = resolve_shelf_device(self.current_device) {+ refresh_shelf_photo_if_needed(dev, true);+ }+ let json = compute_shelf_items_json(self.current_device);+ self.as_mut().set_shelf_items(QString::from(&json));+ }++ pub fn style_shelf_window(&self) {+ win::tray::apply_no_activate_style_by_title("Nectarlink Shelf");+ }++ pub fn start_shelf_drag(&self, kind: &QString, id_or_path: &QString, text: &QString) -> bool {+ let kind_str = String::from(kind);+ let s = String::from(id_or_path).trim().to_owned();+ let t = String::from(text);++ if !s.is_empty() && std::path::Path::new(&s).exists() {+ return super::native::ffi::start_external_drag(&s, &t);+ }+ if (kind_str == "photo" || kind_str == "screenshot")+ && !s.is_empty()+ && let (Some(dev), _, _) = resolve_shelf_device(self.current_device)+ {+ let thumb = crate::photos::thumb_path(dev, &s);+ if let Some(dir) = thumb.parent() {+ let prefix = format!("full-{:016x}.", crate::photos::fingerprint(&s));+ if let Ok(entries) = std::fs::read_dir(dir) {+ for entry in entries.flatten() {+ let p = entry.path();+ if p.file_name().and_then(|n| n.to_str()).is_some_and(|n| n.starts_with(&prefix))+ && p.exists()+ {+ return super::native::ffi::start_external_drag(&p.to_string_lossy(), &t);+ }+ }+ }+ }+ if thumb.exists() {+ return super::native::ffi::start_external_drag(&thumb.to_string_lossy(), &t);+ }+ }+ if kind_str == "clip"+ && !s.is_empty()+ && t.is_empty()+ && let Some(node) = core_host::node()+ && let Some((_, bytes)) = node.clipboard_history_image(&s)+ {+ let tmp = core_host::host().data_dir.join("cache").join("shelf-clip.png");+ if let Some(parent) = tmp.parent() {+ let _ = std::fs::create_dir_all(parent);+ }+ if std::fs::write(&tmp, &bytes).is_ok() {+ return super::native::ffi::start_external_drag(&tmp.to_string_lossy(), "");+ }+ }+ super::native::ffi::start_external_drag("", &t)+ }++ pub fn drop_to_shelf(&self, urls: &QList<QVariant>, text: &QString) {+ let (Some(device), device_name, _) = resolve_shelf_device(self.current_device) else {+ show_message("No paired phone is connected.");+ return;+ };++ let mut paths: Vec<std::path::PathBuf> = Vec::new();+ let mut url_text_fallback = String::new();+ for v in urls.iter() {+ let raw = v+ .value::<QString>()+ .map(|qs| String::from(&qs))+ .or_else(|| v.value::<cxx_qt_lib::QUrl>().map(|qu| String::from(&qu.to_qstring())))+ .unwrap_or_default();+ let raw = raw.trim();+ if raw.is_empty() {+ continue;+ }+ let local = cxx_qt_lib::QUrl::from(&QString::from(raw))+ .to_local_file()+ .map(|p| String::from(&p))+ .filter(|p| !p.is_empty())+ .or_else(|| {+ raw.strip_prefix("file:///")+ .or_else(|| raw.strip_prefix("file://"))+ .map(|s| s.replace('/', "\\"))+ });+ if let Some(local_str) = local {+ let pb = std::path::PathBuf::from(&local_str);+ if pb.exists() {+ paths.push(pb);+ continue;+ }+ }+ let pb = std::path::PathBuf::from(raw);+ if pb.exists() {+ paths.push(pb);+ } else if url_text_fallback.is_empty() {+ url_text_fallback = raw.to_owned();+ }+ }++ if !paths.is_empty() {+ crate::transfers::send(device, paths);+ show_message(format!("Sending to {device_name}…"));+ return;+ }++ let dropped_text = {+ let t = String::from(text).trim().to_owned();+ if t.is_empty() { url_text_fallback } else { t }+ };+ if !dropped_text.is_empty() {+ if crate::links::is_handoff_text(&dropped_text) {+ crate::links::send_to(device, dropped_text);+ } else if let Some(node) = core_host::node() {+ let name = device_name.clone();+ core_host::spawn(async move {+ match node.send_clipboard(device, dropped_text).await {+ Ok(()) => show_message(format!("Sent text to {name}.")),+ Err(e) => show_message(describe(&e)),+ }+ });+ }+ }+ }++ pub fn activate_shelf_item(&self, kind: &QString, action: &QString, id_or_path: &QString) {+ let kind_str = String::from(kind);+ let action_str = String::from(action);+ let s = String::from(id_or_path).trim().to_owned();++ match kind_str.as_str() {+ "photo" | "screenshot" => {+ let p = std::path::Path::new(&s);+ if !s.is_empty() && p.exists() {+ match action_str.as_str() {+ "folder" | "reveal" | "save" => crate::transfers::show_in_folder(p),+ "copy" => {+ let mime = match p+ .extension()+ .and_then(|e| e.to_str())+ .map(str::to_ascii_lowercase)+ .as_deref()+ {+ Some("png") => "image/png",+ _ => "image/jpeg",+ };+ match std::fs::read(p)+ .map_err(|e| e.to_string())+ .and_then(|b| crate::win::clipboard::write_image(mime, &b))+ {+ Ok(()) => show_message("Copied to clipboard."),+ Err(_) => show_message("The photo couldn't be copied to the clipboard."),+ }+ }+ _ => crate::transfers::open(p),+ }+ } else if !s.is_empty()+ && let (Some(dev), _, _) = resolve_shelf_device(self.current_device)+ {+ let toast_action = match action_str.as_str() {+ "save" => Some(crate::photos::ACTION_SAVE),+ "copy" => Some(crate::photos::ACTION_COPY),+ _ => None,+ };+ crate::photos::on_toast(&format!("{dev} {s}"), toast_action);+ }+ }+ "clip" => {+ if !s.is_empty() {+ crate::clipboard::copy_history_item(&s);+ } else {+ show_message("Already on clipboard.");+ }+ }+ "file" => {+ let p = std::path::Path::new(&s);+ if !s.is_empty() && p.exists() {+ if action_str == "folder" || action_str == "reveal" {+ crate::transfers::show_in_folder(p);+ } else {+ crate::transfers::open(p);+ }+ } else {+ show_message("That file is no longer in its saved location.");+ }+ }+ _ => {}+ }+ }+}++fn resolve_shelf_device(current_device_idx: i32) -> (Option<DeviceId>, String, bool) {+ core_host::host().hub.read(|s| {+ let idx = current_device_idx.max(0) as usize;+ let chosen = s+ .devices+ .get(idx)+ .filter(|d| matches!(d.link, LinkState::Online { .. }))+ .or_else(|| s.devices.iter().find(|d| matches!(d.link, LinkState::Online { .. })))+ .or_else(|| s.devices.get(idx))+ .or_else(|| s.devices.first());+ match chosen {+ Some(d) => (Some(d.id), d.info.name.clone(), matches!(d.link, LinkState::Online { .. })),+ None => (None, String::new(), false),+ }+ })+}++fn compute_shelf_items_json(current_device_idx: i32) -> String {+ use nectarlink_core::{ClipboardItemKind, Direction, TimelineKind, TimelineQuery, TransferState};++ let (device_opt, device_name, online) = resolve_shelf_device(current_device_idx);+ let node = core_host::node();++ let mut latest_photo: Option<serde_json::Value> = None;+ let mut latest_photo_ts: i64 = -1;+ let mut latest_screenshot: Option<serde_json::Value> = None;+ let mut latest_screenshot_ts: i64 = -1;++ // 1. Check HOME_SUMMARY for the active phone (and trigger a one-shot fetch if needed while Shelf is open).+ if let Some(dev) = device_opt {+ let summary = home_store(|s| s.devices.get(&dev).cloned());+ match summary {+ Some(d) if d.photo_loaded => {+ if !d.photo_id.is_empty() {+ let thumb_p = crate::photos::thumb_path(dev, &d.photo_id);+ let thumb_url = if !d.photo_thumb.is_empty() {+ d.photo_thumb.clone()+ } else if thumb_p.exists() {+ crate::icons::file_url(&thumb_p)+ } else {+ String::new()+ };+ let obj = serde_json::json!({+ "id": d.photo_id,+ "name": d.photo_name,+ "date": d.photo_date,+ "thumbUrl": thumb_url,+ "localPath": "",+ });+ if d.photo_is_screenshot {+ latest_screenshot = Some(obj);+ latest_screenshot_ts = d.photo_date;+ } else {+ latest_photo = Some(obj);+ latest_photo_ts = d.photo_date;+ }+ }+ }+ _ if online => {+ refresh_shelf_photo_if_needed(dev, false);+ }+ _ => {}+ }+ }++ // 2. Check Timeline photo entries (saved photos / screenshots on disk).+ if let Some(ref n) = node+ && let Ok(page) = n.timeline_page(&TimelineQuery {+ kind: Some(TimelineKind::Photo),+ device: device_opt,+ limit: 25,+ ..Default::default()+ })+ {+ for entry in page.entries {+ let first_target = entry.target.lines().next().unwrap_or("").trim();+ if first_target.is_empty() {+ continue;+ }+ let path = std::path::PathBuf::from(first_target);+ if !path.exists() {+ continue;+ }+ let name = path.file_name().and_then(|f| f.to_str()).unwrap_or(&entry.title).to_owned();+ let lower_title = entry.title.to_ascii_lowercase();+ let lower_name = name.to_ascii_lowercase();+ let is_shot = lower_title.contains("screenshot")+ || lower_name.contains("screenshot")+ || entry.detail.to_ascii_lowercase().contains("screenshot");+ let obj = serde_json::json!({+ "id": path.to_string_lossy(),+ "name": name,+ "date": entry.timestamp,+ "thumbUrl": crate::icons::file_url(&path),+ "localPath": path.to_string_lossy(),+ });+ if is_shot {+ if entry.timestamp >= latest_screenshot_ts {+ latest_screenshot_ts = entry.timestamp;+ latest_screenshot = Some(obj);+ }+ } else if entry.timestamp >= latest_photo_ts {+ latest_photo_ts = entry.timestamp;+ latest_photo = Some(obj);+ }+ }+ }++ // 3. Scan Downloads\Nectarlink for mirror screenshots ("Screenshot ...") and saved photos.+ let dl_dir = core_host::downloads_dir();+ let mut dl_files: Vec<(i64, u64, std::path::PathBuf, String)> = Vec::new();+ if let Ok(entries) = std::fs::read_dir(&dl_dir) {+ for e in entries.flatten() {+ let p = e.path();+ let Ok(meta) = e.metadata() else { continue };+ if !meta.is_file() {+ continue;+ }+ let Some(name) = p.file_name().and_then(|n| n.to_str()).map(str::to_owned) else {+ continue;+ };+ let ts = meta+ .modified()+ .ok()+ .and_then(|m| m.duration_since(std::time::UNIX_EPOCH).ok())+ .map_or(0, |d| d.as_millis() as i64);+ dl_files.push((ts, meta.len(), p, name));+ }+ }+ dl_files.sort_by_key(|f| std::cmp::Reverse(f.0));++ for (ts, _, p, name) in &dl_files {+ let ext = p.extension().and_then(|e| e.to_str()).map(str::to_ascii_lowercase).unwrap_or_default();+ if !matches!(ext.as_str(), "png" | "jpg" | "jpeg" | "webp") {+ continue;+ }+ let is_shot = name.to_ascii_lowercase().contains("screenshot");+ if is_shot && *ts > latest_screenshot_ts {+ latest_screenshot_ts = *ts;+ latest_screenshot = Some(serde_json::json!({+ "id": p.to_string_lossy(),+ "name": name,+ "date": *ts,+ "thumbUrl": crate::icons::file_url(p),+ "localPath": p.to_string_lossy(),+ }));+ } else if !is_shot && latest_photo.is_none() {+ latest_photo = Some(serde_json::json!({+ "id": p.to_string_lossy(),+ "name": name,+ "date": *ts,+ "thumbUrl": crate::icons::file_url(p),+ "localPath": p.to_string_lossy(),+ }));+ }+ }++ // 4. Current clip (from encrypted local clipboard history, or live Windows clipboard fallback).+ let current_clip =+ if let Some(entry) = node.as_ref().and_then(|n| n.clipboard_history(None).into_iter().next()) {+ let (kind, image_data_url) = match entry.kind {+ ClipboardItemKind::Text => ("text", String::new()),+ ClipboardItemKind::Image => {+ ("image", crate::clipboard::thumb_for_clip(&entry.id).unwrap_or_default())+ }+ };+ serde_json::json!({+ "id": entry.id,+ "kind": kind,+ "text": entry.text,+ "imageDataUrl": image_data_url,+ "deviceName": entry.device_name,+ "localPath": "",+ })+ } else {+ match crate::win::clipboard::read() {+ crate::win::clipboard::Clip::Text(t) if !t.trim().is_empty() => serde_json::json!({+ "id": "",+ "kind": "text",+ "text": t,+ "imageDataUrl": "",+ "deviceName": "This PC",+ "localPath": "",+ }),+ _ => serde_json::Value::Null,+ }+ };++ // 5. Recent received files (up to 5 existing files on disk).+ let mut recent_files: Vec<serde_json::Value> = Vec::new();+ let mut seen_paths: std::collections::HashSet<String> = std::collections::HashSet::new();+ let mut add_file =+ |recent_files: &mut Vec<serde_json::Value>, path: &std::path::Path, dev_label: &str| {+ if recent_files.len() >= 5 || !path.exists() || !path.is_file() {+ return;+ }+ let path_str = path.to_string_lossy().into_owned();+ let key = path_str.to_ascii_lowercase();+ if !seen_paths.insert(key) {+ return;+ }+ let name = path.file_name().and_then(|n| n.to_str()).unwrap_or("File").to_owned();+ let size = std::fs::metadata(path).map_or(0, |m| m.len());+ recent_files.push(serde_json::json!({+ "name": name,+ "path": path_str,+ "size": size,+ "deviceName": dev_label,+ }));+ };++ let transfer_files: Vec<(std::path::PathBuf, String)> = core_host::host().hub.read(|s| {+ let mut out = Vec::new();+ for tv in &s.transfers {+ if tv.transfer.direction == Direction::Incoming+ && let TransferState::Done { ref saved } = tv.transfer.state+ {+ let dname = s.name_of(&tv.transfer.device).unwrap_or_else(|| "Phone".into());+ for p in saved {+ out.push((p.clone(), dname.clone()));+ }+ }+ }+ out+ });+ for (p, dname) in &transfer_files {+ add_file(&mut recent_files, p, dname);+ }++ if recent_files.len() < 5+ && let Some(ref n) = node+ && let Ok(page) = n.timeline_page(&TimelineQuery {+ kind: Some(TimelineKind::File),+ limit: 20,+ ..Default::default()+ })+ {+ for entry in page.entries {+ for line in entry.target.lines() {+ let trimmed = line.trim();+ if !trimmed.is_empty() {+ add_file(&mut recent_files, std::path::Path::new(trimmed), &entry.device_name);+ }+ }+ }+ }++ for (_, _, p, _) in &dl_files {+ if recent_files.len() >= 5 {+ break;+ }+ add_file(&mut recent_files, p, if device_name.is_empty() { "Phone" } else { &device_name });+ }++ serde_json::json!({+ "hasDevice": device_opt.is_some(),+ "deviceId": device_opt.map(|d| d.to_string()).unwrap_or_default(),+ "deviceName": device_name,+ "online": online,+ "latestPhoto": latest_photo.unwrap_or(serde_json::Value::Null),+ "latestScreenshot": latest_screenshot.unwrap_or(serde_json::Value::Null),+ "currentClip": current_clip,+ "recentFiles": recent_files,+ })+ .to_string()}fn compute_data_retention_json() -> String {@@ -1301,6 +1872,10 @@ fn bump_home_summary() {let _ = qt.queue(|mut object| {let rev = object.home_summary_revision.wrapping_add(1);object.as_mut().set_home_summary_revision(rev);+ if object.shelf_open {+ let shelf = compute_shelf_items_json(object.current_device);+ object.set_shelf_items(QString::from(&shelf));+ }});}}@@ -1384,6 +1959,7 @@ pub(crate) fn update_home_calls(device: DeviceId, entries: &[nectarlink_core::Capub(crate) fn on_home_event(event: &nectarlink_core::NodeEvent) {use nectarlink_core::NodeEvent;let watched = home_store(|s| s.watched);+ let shelf_active = is_shelf_open();match event {NodeEvent::LinkChanged { device, link: LinkState::Online { .. } } if watched == Some(*device) => {refresh_home_if_needed(*device, true, true, true);@@ -1413,7 +1989,7 @@ pub(crate) fn on_home_event(event: &nectarlink_core::NodeEvent) {refresh_home_if_needed(dev, false, true, false);});}- NodeEvent::PhotoAdded { device, photo } if watched == Some(*device) => {+ NodeEvent::PhotoAdded { device, photo } if watched == Some(*device) || shelf_active => {let thumb_url = crate::photos::write_thumb(*device, &photo.id, &photo.thumb).or_else(|| {let p = crate::photos::thumb_path(*device, &photo.id);@@ -1434,8 +2010,12 @@ pub(crate) fn on_home_event(event: &nectarlink_core::NodeEvent) {});bump_home_summary();}- NodeEvent::PhotosChanged { device } if watched == Some(*device) => {- refresh_home_if_needed(*device, false, false, true);+ NodeEvent::PhotosChanged { device } if watched == Some(*device) || shelf_active => {+ if watched == Some(*device) {+ refresh_home_if_needed(*device, false, false, true);+ } else {+ refresh_shelf_photo_if_needed(*device, true);+ }}NodeEvent::DeviceRemoved(device) => {home_store(|s| {@@ -1449,6 +2029,88 @@ pub(crate) fn on_home_event(event: &nectarlink_core::NodeEvent) {}}+fn refresh_shelf_photo_if_needed(device: DeviceId, force_photo: bool) {+ let (online, photos_avail) = core_host::host().hub.read(|s| {+ let online = s.devices.iter().any(|d| d.id == device && matches!(d.link, LinkState::Online { .. }));+ let avail = s.matrices.get(&device).and_then(|m| m.state("files.recent_photos"))+ == Some(FeatureState::Available);+ (online, avail)+ });+ if !online || !photos_avail {+ return;+ }+ let do_photo = home_store(|s| {+ let d = s.devices.entry(device).or_default();+ let should = !d.photo_busy && (force_photo || !d.photo_loaded);+ if should {+ d.photo_busy = true;+ }+ should+ });+ if do_photo {+ spawn_home_photo_fetch(device);+ }+}++fn spawn_home_photo_fetch(device: DeviceId) {+ let Some(node) = core_host::node() else {+ home_store(|s| {+ if let Some(d) = s.devices.get_mut(&device) {+ d.photo_busy = false;+ }+ });+ return;+ };+ core_host::spawn(async move {+ let Ok(items) = node.photo_list(device, None, None, 1).await else {+ home_store(|s| {+ if let Some(d) = s.devices.get_mut(&device) {+ d.photo_busy = false;+ }+ });+ return;+ };+ let Some(item) = items.into_iter().next() else {+ home_store(|s| {+ let d = s.devices.entry(device).or_default();+ d.photo_loaded = true;+ d.photo_busy = false;+ d.photo_id.clear();+ d.photo_name.clear();+ d.photo_date = 0;+ d.photo_thumb.clear();+ });+ bump_home_summary();+ return;+ };+ let mut disk_path = crate::photos::thumb_path(device, &item.id);+ if !disk_path.exists()+ && let Ok(thumbs) = node.photo_thumbs(device, vec![item.id.clone()]).await+ && let Some(first) = thumbs.into_iter().next()+ && let Some(saved) = crate::photos::write_thumb(device, &first.id, &first.data)+ {+ disk_path = saved;+ }+ let thumb_url = if disk_path.exists() { crate::icons::file_url(&disk_path) } else { String::new() };+ let lower_name = item.name.to_ascii_lowercase();+ let is_screenshot = lower_name.contains("screenshot")+ || item.album.as_deref().is_some_and(|a| a.to_ascii_lowercase().contains("screenshot"));+ let is_video = item.duration.is_some() || item.id.starts_with("video:");+ home_store(|s| {+ let d = s.devices.entry(device).or_default();+ d.photo_loaded = true;+ d.photo_busy = false;+ d.photo_id = item.id;+ d.photo_name = item.name;+ d.photo_date = item.date;+ d.photo_thumb = thumb_url;+ d.photo_is_video = is_video;+ d.photo_is_screenshot = is_screenshot;+ });+ bump_home_summary();+ });+}+fn refresh_home_if_needed(device: DeviceId, force_sms: bool, force_calls: bool, force_photo: bool) {let (online, sms_avail, calls_avail, photos_avail) = core_host::host().hub.read(|s| {let online = s.devices.iter().any(|d| d.id == device && matches!(d.link, LinkState::Online { .. }));@@ -1506,55 +2168,7 @@ fn refresh_home_if_needed(device: DeviceId, force_sms: bool, force_calls: bool,});}if do_photo {- core_host::spawn(async move {- let Ok(items) = node.photo_list(device, None, None, 1).await else {- home_store(|s| {- if let Some(d) = s.devices.get_mut(&device) {- d.photo_busy = false;- }- });- return;- };- let Some(item) = items.into_iter().next() else {- home_store(|s| {- let d = s.devices.entry(device).or_default();- d.photo_loaded = true;- d.photo_busy = false;- d.photo_id.clear();- d.photo_name.clear();- d.photo_date = 0;- d.photo_thumb.clear();- });- bump_home_summary();- return;- };- let mut disk_path = crate::photos::thumb_path(device, &item.id);- if !disk_path.exists()- && let Ok(thumbs) = node.photo_thumbs(device, vec![item.id.clone()]).await- && let Some(first) = thumbs.into_iter().next()- && let Some(saved) = crate::photos::write_thumb(device, &first.id, &first.data)- {- disk_path = saved;- }- let thumb_url =- if disk_path.exists() { crate::icons::file_url(&disk_path) } else { String::new() };- let lower_name = item.name.to_ascii_lowercase();- let is_screenshot = lower_name.contains("screenshot")- || item.album.as_deref().is_some_and(|a| a.to_ascii_lowercase().contains("screenshot"));- let is_video = item.duration.is_some() || item.id.starts_with("video:");- home_store(|s| {- let d = s.devices.entry(device).or_default();- d.photo_loaded = true;- d.photo_busy = false;- d.photo_id = item.id;- d.photo_name = item.name;- d.photo_date = item.date;- d.photo_thumb = thumb_url;- d.photo_is_video = is_video;- d.photo_is_screenshot = is_screenshot;- });- bump_home_summary();- });+ spawn_home_photo_fetch(device);}}diff --git a/desktop/app/src/bridge/mirror.rs b/desktop/app/src/bridge/mirror.rsindex bad2d0a..328d4a5 100644--- a/desktop/app/src/bridge/mirror.rs+++ b/desktop/app/src/bridge/mirror.rs@@ -42,6 +42,8 @@ pub mod qobject {#[qproperty(QString, apps_state, cxx_name = "appsState")]/// Why they couldn't be loaded.#[qproperty(QString, apps_error, cxx_name = "appsError")]+ /// Device ID currently receiving PC keyboard input without screen mirroring, or "".+ #[qproperty(QString, keyboard_device, cxx_name = "keyboardDevice")]type Mirror = super::MirrorRust;}@@ -93,6 +95,46 @@ pub mod qobject {#[qinvokable]#[cxx_name = "toggleSound"]fn toggle_sound(self: &Mirror);+ /// Copies a screenshot of a mirror window to the PC clipboard.+ #[qinvokable]+ #[cxx_name = "screenshotClipboard"]+ fn screenshot_clipboard(self: &Mirror, key: &QString);+ /// Saves a screenshot of a mirror window to Downloads\Nectarlink.+ #[qinvokable]+ #[cxx_name = "screenshotFile"]+ fn screenshot_file(self: &Mirror, key: &QString);+ /// Starts or stops MP4 video recording for a mirror window.+ #[qinvokable]+ #[cxx_name = "toggleRecording"]+ fn toggle_recording(self: &Mirror, key: &QString);+ /// Keeps the phone awake while mirroring its screen.+ #[qinvokable]+ #[cxx_name = "setStayAwake"]+ fn set_stay_awake(self: &Mirror, key: &QString, on: bool);+ /// Turns the phone's physical screen off while mirroring.+ #[qinvokable]+ #[cxx_name = "setScreenOff"]+ fn set_screen_off(self: &Mirror, key: &QString, on: bool);+ /// Starts or stops remote keyboard typing on `device` without screen mirroring.+ #[qinvokable]+ #[cxx_name = "toggleKeyboard"]+ fn toggle_keyboard(self: &Mirror, device: &QString);+ /// Stops remote keyboard typing without screen mirroring.+ #[qinvokable]+ #[cxx_name = "stopKeyboard"]+ fn stop_keyboard(self: &Mirror);+ /// Sends a key name to `device` while remote keyboard typing is active.+ #[qinvokable]+ #[cxx_name = "keyboardPress"]+ fn keyboard_press(self: &Mirror, device: &QString, name: &QString);+ /// Sends typed text to `device` while remote keyboard typing is active.+ #[qinvokable]+ #[cxx_name = "keyboardText"]+ fn keyboard_text(self: &Mirror, device: &QString, text: &QString);+ /// Pastes the PC's clipboard text onto `device` while remote keyboard typing is active.+ #[qinvokable]+ #[cxx_name = "keyboardPaste"]+ fn keyboard_paste(self: &Mirror, device: &QString);}}@@ -105,13 +147,18 @@ pub struct MirrorRust {recent_apps: QString,apps_state: QString,apps_error: QString,+ keyboard_device: QString,}impl cxx_qt::Initialize for qobject::Mirror {fn initialize(self: Pin<&mut Self>) {super::subscribe(self.qt_thread(),- Changes::MIRROR | Changes::CAPABILITIES | Changes::DEVICES,+ Changes::MIRROR+ | Changes::CAPABILITIES+ | Changes::DEVICES+ | Changes::NOTIFICATIONS+ | Changes::HISTORY,Self::refresh,);}@@ -125,16 +172,18 @@ impl qobject::Mirror {let windows: Vec<serde_json::Value> = mirror::windows().into_iter().map(|(window, shown)| {- let (control, name) = hub.read(|s| {+ let (control, can_screen_off, name) = hub.read(|s| {// The screen needs control turned on; app windows are Elevated already.let feature = if window.session == MIRROR_SCREEN {"mirroring.control"} else {"mirroring.app_windows"};- let control = s.matrices.get(&window.device).and_then(|m| m.state(feature))+ let matrix = s.matrices.get(&window.device);+ let control = matrix.and_then(|m| m.state(feature)) == Some(FeatureState::Available);+ let can_screen_off = matrix.and_then(|m| m.state("mirroring.app_windows"))== Some(FeatureState::Available);- (control, s.name_of(&window.device).unwrap_or_default())+ (control, can_screen_off, s.name_of(&window.device).unwrap_or_default())});let (phase, reason) = match shown.phase {Phase::Asking => ("asking", String::new()),@@ -162,6 +211,12 @@ impl qobject::Mirror {"reason": reason,"canControl": control,"sound": window.session == MIRROR_SCREEN && mirror::has_sound(&window.device),+ "recording": mirror::is_recording(&window),+ "recordingStartedMs": mirror::recording_started_ms(&window),+ "stayAwake": window.session == MIRROR_SCREEN && mirror::stay_awake(&window.device),+ "screenOff": window.session == MIRROR_SCREEN && mirror::screen_off(&window.device),+ "canScreenOff": window.session == MIRROR_SCREEN && can_screen_off,+ "notice": mirror::last_notice(&window),"savedX": geom.map(|g| g.x),"savedY": geom.map(|g| g.y),"savedWidth": geom.map(|g| g.width).unwrap_or(0),@@ -174,6 +229,10 @@ impl qobject::Mirror {self.as_mut().set_windows(QString::from(&json));}self.as_mut().set_muted(mirror::muted());+ let kb = mirror::keyboard_device().map(|d| d.to_string()).unwrap_or_default();+ if self.keyboard_device.to_string() != kb {+ self.as_mut().set_keyboard_device(QString::from(&kb));+ }let Some(device) = super::parse_device(&self.apps_device) else { return };let (state, apps, error) = match mirror::apps(&device) {@@ -315,6 +374,64 @@ impl qobject::Mirror {pub fn toggle_sound(&self) {mirror::set_muted(!mirror::muted());}++ pub fn screenshot_clipboard(&self, key: &QString) {+ if let Some(window) = Window::parse(&String::from(key)) {+ mirror::screenshot_clipboard(window);+ }+ }++ pub fn screenshot_file(&self, key: &QString) {+ if let Some(window) = Window::parse(&String::from(key)) {+ mirror::screenshot_file(window);+ }+ }++ pub fn toggle_recording(&self, key: &QString) {+ if let Some(window) = Window::parse(&String::from(key)) {+ mirror::toggle_recording(window);+ }+ }++ pub fn set_stay_awake(&self, key: &QString, on: bool) {+ if let Some(window) = Window::parse(&String::from(key)) {+ mirror::set_stay_awake(window, on);+ }+ }++ pub fn set_screen_off(&self, key: &QString, on: bool) {+ if let Some(window) = Window::parse(&String::from(key)) {+ mirror::set_screen_off(window, on);+ }+ }++ pub fn toggle_keyboard(&self, device: &QString) {+ if let Some(device) = super::parse_device(device) {+ mirror::toggle_remote_keyboard(device);+ }+ }++ pub fn stop_keyboard(&self) {+ mirror::set_remote_keyboard(None);+ }++ pub fn keyboard_press(&self, device: &QString, name: &QString) {+ if let Some(device) = super::parse_device(device) {+ mirror::keyboard_press(device, String::from(name));+ }+ }++ pub fn keyboard_text(&self, device: &QString, text: &QString) {+ if let Some(device) = super::parse_device(device) {+ mirror::keyboard_text(device, String::from(text));+ }+ }++ pub fn keyboard_paste(&self, device: &QString) {+ if let Some(device) = super::parse_device(device) {+ mirror::keyboard_paste(device);+ }+ }}/// A position on the screen, kept on it.diff --git a/desktop/app/src/bridge/native.rs b/desktop/app/src/bridge/native.rsindex bc97966..dff892f 100644--- a/desktop/app/src/bridge/native.rs+++ b/desktop/app/src/bridge/native.rs@@ -28,5 +28,7 @@ pub mod ffi {/// Records the active QML engine so `trim_memory_caches` can run GC and/// clear component caches.fn register_qml_app_engine(engine: Pin<&mut QQmlApplicationEngine>);+ /// Starts a native OS drag-and-drop operation for a local file or text.+ fn start_external_drag(file_path: &str, text_fallback: &str) -> bool;}}diff --git a/desktop/app/src/bridge/prefs.rs b/desktop/app/src/bridge/prefs.rsindex 9abc8be..3809694 100644--- a/desktop/app/src/bridge/prefs.rs+++ b/desktop/app/src/bridge/prefs.rs@@ -78,6 +78,8 @@ pub mod qobject {#[qproperty(QString, continuity_scan_hotkey)]/// Global hotkey for the Command Palette (e.g. `"Ctrl+Alt+Space"`).#[qproperty(QString, command_palette_hotkey)]+ /// Global hotkey for the Shelf panel (e.g. `"Ctrl+Alt+S"`).+ #[qproperty(QString, shelf_hotkey)]type Preferences = super::PreferencesRust;/// Sets the folder where voice recordings are saved (from a `file:` URL or path).@@ -168,6 +170,7 @@ pub struct PreferencesRust {continuity_photo_hotkey: QString,continuity_scan_hotkey: QString,command_palette_hotkey: QString,+ shelf_hotkey: QString,/// What the user chose (`start_with_windows` shows the default until then).start_choice: Option<bool>,/// Custom recordings folder if chosen (`None` means default).@@ -215,10 +218,12 @@ impl cxx_qt::Initialize for qobject::Preferences {self.as_mut().set_continuity_photo_hotkey(QString::from(&settings.continuity_photo_hotkey));self.as_mut().set_continuity_scan_hotkey(QString::from(&settings.continuity_scan_hotkey));self.as_mut().set_command_palette_hotkey(QString::from(&settings.command_palette_hotkey));+ self.as_mut().set_shelf_hotkey(QString::from(&settings.shelf_hotkey));crate::win::tray::update_hotkeys(&settings.continuity_photo_hotkey,&settings.continuity_scan_hotkey,&settings.command_palette_hotkey,+ &settings.shelf_hotkey,);crate::recordings::init(&settings);@@ -316,6 +321,7 @@ impl cxx_qt::Initialize for qobject::Preferences {&String::from(&p.continuity_photo_hotkey),&String::from(&p.continuity_scan_hotkey),&String::from(&p.command_palette_hotkey),+ &String::from(&p.shelf_hotkey),);p.save();})@@ -326,6 +332,7 @@ impl cxx_qt::Initialize for qobject::Preferences {&String::from(&p.continuity_photo_hotkey),&String::from(&p.continuity_scan_hotkey),&String::from(&p.command_palette_hotkey),+ &String::from(&p.shelf_hotkey),);p.save();})@@ -336,6 +343,18 @@ impl cxx_qt::Initialize for qobject::Preferences {&String::from(&p.continuity_photo_hotkey),&String::from(&p.continuity_scan_hotkey),&String::from(&p.command_palette_hotkey),+ &String::from(&p.shelf_hotkey),+ );+ p.save();+ })+ .release();+ self.as_mut()+ .on_shelf_hotkey_changed(|p| {+ crate::win::tray::update_hotkeys(+ &String::from(&p.continuity_photo_hotkey),+ &String::from(&p.continuity_scan_hotkey),+ &String::from(&p.command_palette_hotkey),+ &String::from(&p.shelf_hotkey),);p.save();})@@ -402,6 +421,7 @@ impl qobject::Preferences {continuity_photo_hotkey: String::from(&p.continuity_photo_hotkey),continuity_scan_hotkey: String::from(&p.continuity_scan_hotkey),command_palette_hotkey: String::from(&p.command_palette_hotkey),+ shelf_hotkey: String::from(&p.shelf_hotkey),};save_in_background(settings);}diff --git a/desktop/app/src/bridge/transfers.rs b/desktop/app/src/bridge/transfers.rsindex 895e498..8852af1 100644--- a/desktop/app/src/bridge/transfers.rs+++ b/desktop/app/src/bridge/transfers.rs@@ -102,6 +102,11 @@ pub mod qobject {/// Sends files (as `file:` URLs, from a picker or a drop) to a device.#[qinvokable]fn send(self: &TransferList, device: &QString, urls: &QStringList);+ /// Hands off a document (as `file:` URLs) to a device and asks the+ /// receiver to open it with its default app once it arrives.+ #[qinvokable]+ #[cxx_name = "sendHandoff"]+ fn send_handoff(self: &TransferList, device: &QString, urls: &QStringList);#[qinvokable]fn accept(self: &TransferList, id: &QString);#[qinvokable]@@ -296,6 +301,17 @@ impl qobject::TransferList {transfers::send(device, paths);}+ pub fn send_handoff(&self, device: &QString, urls: &QStringList) {+ let Some(device) = super::parse_device(device) else { return };+ let paths: Vec<PathBuf> = QList::<QString>::from(urls)+ .iter()+ .filter_map(|url| QUrl::from(url).to_local_file().map(|path| String::from(&path)))+ .filter(|path| !path.is_empty())+ .map(PathBuf::from)+ .collect();+ transfers::send_handoff(device, paths);+ }+pub fn accept(&self, id: &QString) {transfers::accept(&String::from(id));}@@ -349,6 +365,7 @@ mod tests {state: TransferState::Done { saved: vec![PathBuf::from(r"C:\Downloads\a.jpg")] },recording: false,markers: Vec::new(),+ open_on_arrival: false,},rate: 0.0,sampled: Instant::now(),diff --git a/desktop/app/src/command_palette.rs b/desktop/app/src/command_palette.rsindex 2240578..dacea0a 100644--- a/desktop/app/src/command_palette.rs+++ b/desktop/app/src/command_palette.rs@@ -31,6 +31,7 @@ pub enum PaletteUiAction {NavigatePage { page: String, device_index: Option<usize> },StartChat { device_id: String, number: String, name: String },OpenDialer { device_id: String, number: String },+ OpenHandoffFilePicker { device_index: Option<usize> },OpenDoctor,OpenPairing,}@@ -181,6 +182,10 @@ pub fn execute(id: &str) -> Option<PaletteUiAction> {return Some(PaletteUiAction::NavigatePage { page: "home".to_owned(), device_index: Some(idx) });}+ if id == "action:toggle_shelf" {+ crate::bridge::app::toggle_shelf_from_anywhere();+ return None;+ }if id == "action:continuity_photo" {crate::continuity_camera::start("photo");return None;@@ -251,6 +256,13 @@ pub fn execute(id: &str) -> Option<PaletteUiAction> {crate::mirror::start(dev);return None;}+ if let Some(dev_str) = id.strip_prefix("action:type_on_phone:")+ && let Ok(dev) = dev_str.parse::<DeviceId>()+ {+ crate::mirror::toggle_remote_keyboard(dev);+ let idx = device_index_of(dev);+ return Some(PaletteUiAction::NavigatePage { page: "home".to_owned(), device_index: idx });+ }if let Some(dev_str) = id.strip_prefix("action:webcam:")&& let Ok(dev) = dev_str.parse::<DeviceId>(){@@ -274,6 +286,12 @@ pub fn execute(id: &str) -> Option<PaletteUiAction> {}return None;}+ if let Some(dev_str) = id.strip_prefix("action:handoff_file:")+ && let Ok(dev) = dev_str.parse::<DeviceId>()+ {+ let idx = core_host::host().hub.read(|s| s.devices.iter().position(|d| d.id == dev));+ return Some(PaletteUiAction::OpenHandoffFilePicker { device_index: idx });+ }if let Some(rest) = id.strip_prefix("toggle:") {execute_phone_toggle(rest);@@ -523,7 +541,18 @@ fn build_candidates() -> Vec<PaletteCandidate> {});}- // Continuity Camera actions (global hotkeys shown as badges/shortcuts)+ // Shelf & Continuity Camera actions (global hotkeys shown as badges/shortcuts)+ out.push(PaletteCandidate {+ id: "action:toggle_shelf".into(),+ title: if crate::bridge::app::is_shelf_open() { "Hide Shelf".into() } else { "Open Shelf".into() },+ subtitle: "Slide-out edge panel with latest photo, screenshot, clipboard, and recent files".into(),+ category: "Actions".into(),+ icon: "folder".into(),+ badge: "Shelf".into(),+ shortcut: settings.shelf_hotkey.clone(),+ keywords: "shelf panel edge drop zone latest photo screenshot clipboard recent files drag".into(),+ base_boost: 91,+ });out.push(PaletteCandidate {id: "action:continuity_photo".into(),title: "Take photo with phone".into(),@@ -546,15 +575,44 @@ fn build_candidates() -> Vec<PaletteCandidate> {keywords: "scan document with phone continuity camera receipt paper pdf paste".into(),base_boost: 86,});+ let (link_title, link_sub, link_badge, link_keywords) = match crate::links::handoff_from_clipboard() {+ Some(h) => match h.kind {+ nectarlink_core::HandoffKind::MapLocation => (+ "Open copied location in Maps on phone".to_owned(),+ h.label,+ "Handoff · Map".to_owned(),+ "open copied link map location address directions geo handoff phone".to_owned(),+ ),+ nectarlink_core::HandoffKind::VideoLink => (+ "Continue copied video on phone".to_owned(),+ h.label,+ "Handoff · Video".to_owned(),+ "open copied link video youtube timestamp watch continue handoff phone".to_owned(),+ ),+ nectarlink_core::HandoffKind::WebLink => (+ "Open copied link on phone".to_owned(),+ h.label,+ "Handoff".to_owned(),+ "open copied link url browser web share handoff phone".to_owned(),+ ),+ },+ None => (+ "Open copied link on phone".to_owned(),+ "Send a web URL, video with timestamp, or map location on your clipboard to your phone"+ .to_owned(),+ "Handoff".to_owned(),+ "open copied link url browser web video youtube map address handoff phone".to_owned(),+ ),+ };out.push(PaletteCandidate {id: "action:open_link".into(),- title: "Open copied link on phone".into(),- subtitle: "Send the web URL on your clipboard to your phone's browser".into(),+ title: link_title,+ subtitle: link_sub,category: "Actions".into(),icon: "globe".into(),- badge: String::new(),+ badge: link_badge,shortcut: String::new(),- keywords: "open copied link url browser web share phone".into(),+ keywords: link_keywords,base_boost: 78,});@@ -570,6 +628,22 @@ fn build_candidates() -> Vec<PaletteCandidate> {keywords: format!("mirror phone screen cast display stream {dev_name}"),base_boost: 80,});+ let typing_active = crate::mirror::keyboard_device() == Some(dev_id);+ out.push(PaletteCandidate {+ id: format!("action:type_on_phone:{dev_id}"),+ title: if typing_active {+ "Stop typing on phone".into()+ } else {+ "Type on phone with PC keyboard".into()+ },+ subtitle: format!("Send live keystrokes and text to {dev_name} without screen mirroring"),+ category: "Actions".into(),+ icon: "keyboard".into(),+ badge: dev_name.clone(),+ shortcut: String::new(),+ keywords: format!("type on phone keyboard input text without mirroring {dev_name}"),+ base_boost: 79,+ });let webcam_streaming = matches!(crate::webcam::phase(),crate::webcam::Phase::Asking { .. } | crate::webcam::Phase::Streaming { .. }@@ -585,6 +659,17 @@ fn build_candidates() -> Vec<PaletteCandidate> {keywords: format!("webcam camera video stream call zoom teams {dev_name}"),base_boost: 76,});+ out.push(PaletteCandidate {+ id: format!("action:handoff_file:{dev_id}"),+ title: "Hand off document to phone".into(),+ subtitle: format!("Send a document to {dev_name} and open it automatically upon arrival"),+ category: "Actions".into(),+ icon: "send".into(),+ badge: "Handoff · Doc".into(),+ shortcut: String::new(),+ keywords: format!("hand off handoff document file open pdf doc txt send {dev_name}"),+ base_boost: 77,+ });out.push(PaletteCandidate {id: format!("action:phone_storage:{dev_id}"),title: "Browse phone storage in File Explorer".into(),@@ -1229,6 +1314,19 @@ mod tests {keywords: "open last photo latest picture screenshot Pixel 9".into(),base_boost: 90,},+ PaletteCandidate {+ id: "action:toggle_shelf".into(),+ title: "Open Shelf".into(),+ subtitle: "Slide-out edge panel with latest photo, screenshot, clipboard, and recent files"+ .into(),+ category: "Actions".into(),+ icon: "folder".into(),+ badge: "Shelf".into(),+ shortcut: "Ctrl+Alt+S".into(),+ keywords: "shelf panel edge drop zone latest photo screenshot clipboard recent files drag"+ .into(),+ base_boost: 91,+ },PaletteCandidate {id: "action:continuity_photo".into(),title: "Take photo with phone".into(),@@ -1320,6 +1418,7 @@ mod tests {assert_eq!(top("text alice"), "Text Alice Rivera");assert_eq!(top("call alice"), "Call Alice Rivera");assert_eq!(top("last photo"), "Open last photo");+ assert_eq!(top("shelf"), "Open Shelf");assert_eq!(top("mirror whatsapp"), "Mirror WhatsApp");assert_eq!(top("record voice"), "Record voice");assert_eq!(top("take photo"), "Take photo with phone");diff --git a/desktop/app/src/links.rs b/desktop/app/src/links.rsindex a865d6e..496057b 100644--- a/desktop/app/src/links.rs+++ b/desktop/app/src/links.rs@@ -1,10 +1,16 @@// SPDX-License-Identifier: GPL-3.0-or-later//! Links and power between this PC and paired phones-//! (docs/protocol/actions.md): links a phone shares open in the PC's-//! browser; a copied link can be opened on the phone from the tray; a phone-//! can lock this PC or put it to sleep.+//! (docs/protocol/actions.md): links a phone shares (web URLs, YouTube/video+//! links with playback timestamps, and `geo:` / map locations) open in the+//! PC's browser; a copied link, video, or address can be handed off to the+//! phone from the tray or Command Palette; a phone can lock this PC or put it+//! to sleep.-use nectarlink_core::{DeviceId, Error, FeatureState, LinkState, PowerAction};+use nectarlink_core::{+ ClipKind, DeviceId, Error, FeatureState, HandoffKind, HandoffLink, LinkState, PowerAction,+ address_to_geo_uri, classify_clip, extract_handoff_link, format_video_timestamp, geo_to_maps_https,+ with_video_timestamp,+};use crate::{bridge::app::describe,@@ -19,8 +25,11 @@ use crate::{/// The toast "device" for link notices.pub const TOAST_GROUP: &str = "links";-/// Opens a link a phone sent, in the default browser.+/// Opens a link a phone sent (`http://`, `https://`, or `geo:`), in the default browser.pub fn open_here(url: &str) -> Result<(), String> {+ if let Some(maps_url) = geo_to_maps_https(url) {+ return shell::open_url(&maps_url);+ }shell::open_url(url)}@@ -33,12 +42,58 @@ pub fn power(action: PowerAction) -> Result<(), String> {}}-/// Whether text is a single web link.+#[cfg(test)]fn as_link(text: &str) -> Option<&str> {let text = text.trim();+ if text.len() > 4096 || text.chars().any(char::is_whitespace) {+ return None;+ }let lower = text.get(..8).map(str::to_ascii_lowercase).unwrap_or_default();let web = lower.starts_with("http://") || lower.starts_with("https://");- (web && text.len() <= 4096 && !text.chars().any(char::is_whitespace)).then_some(text)+ let geo = text.get(..4).is_some_and(|p| p.eq_ignore_ascii_case("geo:")) && text.len() > 4;+ (web || geo).then_some(text)+}++/// Enriches a Handoff link with the PC's active media playback timestamp if it+/// is a video link without an explicit timestamp.+pub fn enrich_handoff_link(mut link: HandoffLink) -> HandoffLink {+ if link.kind == HandoffKind::VideoLink+ && link.timestamp_secs.is_none()+ && let Some(secs) = crate::media::local_playback_position_secs()+ {+ link.url = with_video_timestamp(&link.url, secs);+ link.timestamp_secs = Some(secs);+ link.label = format!("{} · {}", link.label, format_video_timestamp(secs));+ }+ link+}++/// Extracts a rich [`HandoffLink`] from arbitrary text (supporting `http://`/`https://`+/// links, YouTube/video links with timestamps, `geo:` URIs, map links, and street addresses).+pub fn handoff_from_text(text: &str) -> Option<HandoffLink> {+ if let Some(h) = extract_handoff_link(text) {+ return Some(enrich_handoff_link(h));+ }+ if let Some(s) = classify_clip(text)+ && s.kind == ClipKind::StreetAddress+ {+ let geo = address_to_geo_uri(text.trim());+ return extract_handoff_link(&geo);+ }+ None+}++/// Whether `text` can be handed off as a link, video with timestamp, or map location.+pub fn is_handoff_text(text: &str) -> bool {+ handoff_from_text(text).is_some()+}++/// Extracts a rich [`HandoffLink`] from the current Windows clipboard (supporting+/// `http://`/`https://` links, YouTube/video links with timestamps, `geo:` URIs,+/// map links, and copied street addresses).+pub fn handoff_from_clipboard() -> Option<HandoffLink> {+ let Clip::Text(text) = clipboard::read() else { return None };+ handoff_from_text(&text)}fn notice(title: &str, body: &str) {@@ -58,17 +113,20 @@ fn notice(title: &str, body: &str) {});}-/// "Open copied link on phone" (tray): opens the link on the clipboard on-/// a connected phone that takes links.+/// "Open copied link on phone" (tray / Command Palette): opens the link, video+/// with timestamp, or map location on the clipboard on a connected phone.pub fn open_copied_link_on_phone() {- let Clip::Text(text) = clipboard::read() else {+ let Clip::Text(_) = clipboard::read() else {return notice(- "Copy a link first",- "Copy a web link, then choose this again to open it on your phone.",+ "Copy a link or address first",+ "Copy a web link, video URL, or street address, then choose this again to open it on your phone.",);};- let Some(url) = as_link(&text).map(str::to_owned) else {- return notice("That's not a link", "Copy a web link (https://…), then choose this again.");+ let Some(handoff) = handoff_from_clipboard() else {+ return notice(+ "That's not a link or address",+ "Copy a web link (https://…), geo: URI, or street address, then choose this again.",+ );};let phone = core_host::host().hub.read(|s| {s.devices@@ -86,20 +144,36 @@ pub fn open_copied_link_on_phone() {"Your phone isn't connected right now, or its app needs an update.",);};- send(phone, name, url);+ send(phone, name, handoff);}-/// Opens `url` on `phone`, showing a Windows toast notification with the outcome.+/// Opens `url` (or a street address / link snippet) on `phone`, showing a Windows toast notification with the outcome.pub fn send_to(phone: DeviceId, url: String) {let name = core_host::host().hub.read(|s| s.name_of(&phone)).unwrap_or_else(|| "your phone".into());- send(phone, name, url);+ let handoff = handoff_from_text(&url).unwrap_or(HandoffLink {+ kind: HandoffKind::WebLink,+ label: url.clone(),+ url,+ timestamp_secs: None,+ map_query: None,+ });+ send(phone, name, handoff);}-fn send(phone: DeviceId, name: String, url: String) {+fn send(phone: DeviceId, name: String, handoff: HandoffLink) {let Some(node) = core_host::node() else { return };core_host::spawn(async move {- match node.open_link(phone, url).await {- Ok(()) => notice(&format!("Sent to {name}"), "Tap the notification on your phone to open it."),+ let body = match handoff.kind {+ HandoffKind::MapLocation => {+ format!("{} — tap the notification on your phone to open in Maps.", handoff.label)+ }+ HandoffKind::VideoLink if handoff.timestamp_secs.is_some() => {+ format!("{} — tap the notification on your phone to continue watching.", handoff.label)+ }+ _ => "Tap the notification on your phone to open it.".into(),+ };+ match node.open_link(phone, handoff.url).await {+ Ok(()) => notice(&format!("Sent to {name}"), &body),Err(Error::Unsupported) => notice("Couldn't send it", &format!("Update Nectarlink on {name}.")),Err(e) => notice("Couldn't send it", &describe(&e)),}@@ -114,6 +188,7 @@ mod tests {fn copied_links_are_recognized() {assert_eq!(as_link(" https://example.com/a?b \n"), Some("https://example.com/a?b"));assert_eq!(as_link("HTTP://X.ORG"), Some("HTTP://X.ORG"));+ assert_eq!(as_link("geo:37.7749,-122.4194?q=SF"), Some("geo:37.7749,-122.4194?q=SF"));assert_eq!(as_link("see https://example.com"), None);assert_eq!(as_link("javascript:alert(1)"), None);assert_eq!(as_link("https://a.com b"), None);diff --git a/desktop/app/src/main.rs b/desktop/app/src/main.rsindex 004a22f..680a0ef 100644--- a/desktop/app/src/main.rs+++ b/desktop/app/src/main.rs@@ -319,6 +319,7 @@ fn main() -> ExitCode {&settings.continuity_photo_hotkey,&settings.continuity_scan_hotkey,&settings.command_palette_hotkey,+ &settings.shelf_hotkey,);// A test instance (own data folder) leaves the user's menu and sign-in// alone.diff --git a/desktop/app/src/media.rs b/desktop/app/src/media.rsindex c2ce4aa..e2fd437 100644--- a/desktop/app/src/media.rs+++ b/desktop/app/src/media.rs@@ -146,8 +146,31 @@ pub fn on_event(event: &NodeEvent) {}}+/// Latest local media players on this PC and when they were sampled.+static LOCAL_PLAYERS: Mutex<Vec<(nectarlink_core::MediaPlayer, std::time::Instant)>> = Mutex::new(Vec::new());++/// Returns the current playback position in seconds of the active local media+/// player on this PC (if any player has a non-zero position).+pub fn local_playback_position_secs() -> Option<u32> {+ let guard = lock(&LOCAL_PLAYERS);+ let (player, sampled_at) = guard+ .iter()+ .find(|(p, _)| p.playing && p.position.is_some_and(|pos| pos > 0))+ .or_else(|| guard.iter().find(|(p, _)| p.position.is_some_and(|pos| pos > 0)))?;+ let base_ms = player.position?;+ let extra_ms = if player.playing { sampled_at.elapsed().as_millis() as u64 } else { 0 };+ let total_ms = match player.duration {+ Some(dur) if dur > 0 => base_ms.saturating_add(extra_ms).min(dur),+ _ => base_ms.saturating_add(extra_ms),+ };+ let secs = (total_ms / 1000) as u32;+ (secs > 0).then_some(secs)+}+/// What plays on this PC changed: tell the phones.pub fn local_changed(players: Vec<nectarlink_core::MediaPlayer>) {+ let now = std::time::Instant::now();+ *lock(&LOCAL_PLAYERS) = players.iter().cloned().map(|p| (p, now)).collect();crate::deck::on_local_media_changed(&players);core_host::spawn(async move {if let Some(node) = core_host::wait_for_node().await {diff --git a/desktop/app/src/mirror.rs b/desktop/app/src/mirror.rsindex 328d0c7..ba85f10 100644--- a/desktop/app/src/mirror.rs+++ b/desktop/app/src/mirror.rs@@ -8,10 +8,10 @@use std::{collections::{HashMap, HashSet},- path::PathBuf,+ path::{Path, PathBuf},sync::{Arc, Mutex, OnceLock,- atomic::{AtomicBool, AtomicU32, AtomicUsize, Ordering},+ atomic::{AtomicBool, AtomicU32, AtomicU64, AtomicUsize, Ordering},mpsc::{Receiver, SyncSender, TrySendError, sync_channel},},time::{Duration, Instant},@@ -22,12 +22,19 @@ use nectarlink_core::{};use crate::{- bridge::{app::describe, native::ffi},+ bridge::{+ app::{describe, show_message},+ native::ffi,+ },core_host,state::Changes,+ transfers::{ACTION_OPEN, ACTION_SHOW, TOAST_GROUP},win::{audio_out::Player,h264::{Decoder, to_bgrx},+ image::{Bitmap, encode_png},+ mp4::{MirrorRecorder, local_timestamp_filename, merge_sps_pps},+ toast::{self, Toast},},};@@ -39,11 +46,15 @@ const OPTIONS: MirrorStart = MirrorStart {audio: true,session: MIRROR_SCREEN,app: None,+ stay_awake: false,+ screen_off: false,};/// Packets waiting for the decoder, at most (about two seconds).const BACKLOG: usize = 120;/// How often decode times are logged.const STATS_EVERY: Duration = Duration::from_secs(10);+/// How long an in-window status notice stays visible.+const NOTICE_DURATION: Duration = Duration::from_secs(3);/// A mirroring on this PC: a phone and the session, 0 for its screen,/// others for its apps in windows of their own.@@ -152,6 +163,14 @@ struct State {windows: HashMap<Window, Shown>,/// Phones whose sound is coming in.sound: HashSet<DeviceId>,+ /// Phones kept awake while mirroring their screen.+ stay_awake: HashSet<DeviceId>,+ /// Phones whose physical screen is turned off while mirroring.+ screen_off: HashSet<DeviceId>,+ /// Phone currently receiving PC keyboard input without screen mirroring.+ keyboard_device: Option<DeviceId>,+ /// Short transient feedback notices per mirror window: `(text, shown_at, token)`.+ notices: HashMap<Window, (String, Instant, u64)>,apps: HashMap<DeviceId, Apps>,saved: SavedWindows,}@@ -161,6 +180,10 @@ impl Default for State {Self {windows: HashMap::new(),sound: HashSet::new(),+ stay_awake: HashSet::new(),+ screen_off: HashSet::new(),+ keyboard_device: None,+ notices: HashMap::new(),apps: HashMap::new(),saved: SavedWindows::load(),}@@ -171,6 +194,21 @@ impl Default for State {static MUTED: AtomicBool = AtomicBool::new(false);/// The next app window's session.static NEXT_SESSION: AtomicU32 = AtomicU32::new(1);+/// Monotonic token for auto-clearing window notices.+static NOTICE_SEQ: AtomicU64 = AtomicU64::new(1);++type FrameMap = HashMap<Window, (u32, u32, Arc<Vec<u8>>)>;++/// Latest displayed BGRX frame per window, for instant screenshots.+static FRAMES: Mutex<Option<FrameMap>> = Mutex::new(None);+/// Active MP4 recorders per window.+static RECORDERS: Mutex<Option<HashMap<Window, MirrorRecorder>>> = Mutex::new(None);+/// Latest video stream dimensions per window.+static LAST_CONFIG: Mutex<Option<HashMap<Window, (u32, u32)>>> = Mutex::new(None);+/// Latest audio stream format `(rate, channels)` per device.+static LAST_AUDIO_CONFIG: Mutex<Option<HashMap<DeviceId, (u32, u8)>>> = Mutex::new(None);+/// Latest Annex-B SPS/PPS bytes per window so mid-stream recordings have parameter sets immediately.+static LAST_SPS_PPS: Mutex<Option<HashMap<Window, Vec<u8>>>> = Mutex::new(None);pub fn muted() -> bool {MUTED.load(Ordering::Relaxed)@@ -191,6 +229,385 @@ fn set_sound(device: DeviceId, on: bool) {core_host::host().hub.changed(Changes::MIRROR);}+/// Whether `device` is set to stay awake while mirroring its screen.+pub fn stay_awake(device: &DeviceId) -> bool {+ state(|s| s.stay_awake.contains(device))+}++/// Whether `device`'s physical screen is turned off while mirroring.+pub fn screen_off(device: &DeviceId) -> bool {+ state(|s| s.screen_off.contains(device))+}++/// Toggles keeping the phone awake while mirroring (`session == 0`).+pub fn set_stay_awake(window: Window, on: bool) {+ if window.session != MIRROR_SCREEN {+ return;+ }+ let screen_off = state(|s| {+ if on {+ s.stay_awake.insert(window.device);+ } else {+ s.stay_awake.remove(&window.device);+ }+ s.screen_off.contains(&window.device)+ });+ set_notice(+ window,+ if on { "Keeping phone awake while mirroring" } else { "Phone sleep timeout restored" },+ );+ core_host::host().hub.changed(Changes::MIRROR);+ let Some(node) = core_host::node() else { return };+ core_host::spawn(async move {+ if let Err(e) = node.mirror_power(window.device, on, screen_off).await {+ tracing::debug!(error = %e, "mirror.power didn't reach the phone");+ }+ });+}++/// Toggles turning the phone's physical screen off while mirroring (`session == 0`).+pub fn set_screen_off(window: Window, on: bool) {+ if window.session != MIRROR_SCREEN {+ return;+ }+ let stay_awake = state(|s| {+ if on {+ s.screen_off.insert(window.device);+ } else {+ s.screen_off.remove(&window.device);+ }+ s.stay_awake.contains(&window.device)+ });+ set_notice(window, if on { "Phone screen turned off" } else { "Phone screen turned back on" });+ core_host::host().hub.changed(Changes::MIRROR);+ let Some(node) = core_host::node() else { return };+ core_host::spawn(async move {+ if let Err(e) = node.mirror_power(window.device, stay_awake, on).await {+ tracing::debug!(error = %e, "mirror.power didn't reach the phone");+ }+ });+}++/// Short status banner for `window` if shown within the last 3 seconds.+pub fn last_notice(window: &Window) -> String {+ state(|s| {+ s.notices+ .get(window)+ .filter(|(_, at, _)| at.elapsed() < NOTICE_DURATION)+ .map(|(text, _, _)| text.clone())+ .unwrap_or_default()+ })+}++fn set_notice(window: Window, text: impl Into<String>) {+ let token = NOTICE_SEQ.fetch_add(1, Ordering::Relaxed);+ state(|s| {+ s.notices.insert(window, (text.into(), Instant::now(), token));+ });+ core_host::host().hub.changed(Changes::MIRROR);+ core_host::spawn(async move {+ tokio::time::sleep(NOTICE_DURATION).await;+ let cleared = state(|s| {+ if s.notices.get(&window).is_some_and(|(_, _, t)| *t == token) {+ s.notices.remove(&window);+ true+ } else {+ false+ }+ });+ if cleared {+ core_host::host().hub.changed(Changes::MIRROR);+ }+ });+}++fn save_latest_frame(window: Window, width: u32, height: u32, bgrx: Vec<u8>) {+ FRAMES+ .lock()+ .unwrap_or_else(|e| e.into_inner())+ .get_or_insert_with(HashMap::new)+ .insert(window, (width, height, Arc::new(bgrx)));+}++fn clear_window_buffers(window: &Window) {+ if let Some(frames) = FRAMES.lock().unwrap_or_else(|e| e.into_inner()).as_mut() {+ frames.remove(window);+ }+ if let Some(cfg) = LAST_CONFIG.lock().unwrap_or_else(|e| e.into_inner()).as_mut() {+ cfg.remove(window);+ }+ if let Some(sps) = LAST_SPS_PPS.lock().unwrap_or_else(|e| e.into_inner()).as_mut() {+ sps.remove(window);+ }+}++fn latest_bitmap(window: &Window) -> Option<Bitmap> {+ let (width, height, raw) = FRAMES+ .lock()+ .unwrap_or_else(|e| e.into_inner())+ .as_ref()+ .and_then(|m| m.get(window))+ .map(|(w, h, b)| (*w, *h, b.clone()))?;+ if width == 0 || height == 0 {+ return None;+ }+ let mut bgra = (*raw).clone();+ for px in bgra.as_chunks_mut::<4>().0 {+ px[3] = 0xFF;+ }+ Some(Bitmap { width, height, bgra })+}++fn free_path(dir: &Path, name: &str) -> PathBuf {+ let first = dir.join(name);+ if !first.exists() {+ return first;+ }+ let path = Path::new(name);+ let stem = path.file_stem().and_then(|s| s.to_str()).unwrap_or(name);+ let ext = path.extension().and_then(|e| e.to_str());+ for n in 2..10_000u32 {+ let candidate = match ext {+ Some(ext) => dir.join(format!("{stem} ({n}).{ext}")),+ None => dir.join(format!("{stem} ({n})")),+ };+ if !candidate.exists() {+ return candidate;+ }+ }+ first+}++/// Copies the current mirror frame for `window` to the PC clipboard as PNG.+pub fn screenshot_clipboard(window: Window) {+ let Some(bitmap) = latest_bitmap(&window) else {+ set_notice(window, "Wait for the screen to appear first");+ show_message("Wait for the screen to appear first.");+ return;+ };+ let copied = encode_png(&bitmap)+ .map_err(|e| e.to_string())+ .and_then(|png| crate::win::clipboard::write_image("image/png", &png));+ match copied {+ Ok(()) => {+ set_notice(window, "Screenshot copied to clipboard");+ show_message("Screenshot copied to clipboard.");+ }+ Err(e) => {+ tracing::warn!(error = %e, "can't copy mirror screenshot");+ set_notice(window, "Couldn't copy screenshot");+ show_message("The screenshot couldn't be copied to the clipboard.");+ }+ }+}++/// Saves the current mirror frame for `window` to `Downloads\Nectarlink` as a PNG file.+pub fn screenshot_file(window: Window) {+ let Some(bitmap) = latest_bitmap(&window) else {+ set_notice(window, "Wait for the screen to appear first");+ show_message("Wait for the screen to appear first.");+ return;+ };+ let png = match encode_png(&bitmap) {+ Ok(png) => png,+ Err(e) => {+ tracing::warn!(error = %e, "can't encode mirror screenshot");+ set_notice(window, "Couldn't save screenshot");+ show_message("The screenshot couldn't be saved.");+ return;+ }+ };+ let base_name = local_timestamp_filename("Screenshot", "png");+ let dir = core_host::downloads_dir();+ if let Err(e) = std::fs::create_dir_all(&dir) {+ tracing::warn!(error = %e, "can't create Downloads\\Nectarlink");+ set_notice(window, "Couldn't save screenshot");+ show_message("The screenshot couldn't be saved.");+ return;+ }+ let path = free_path(&dir, &base_name);+ if let Err(e) = std::fs::write(&path, &png) {+ tracing::warn!(error = %e, "can't write mirror screenshot");+ set_notice(window, "Couldn't save screenshot");+ show_message("The screenshot couldn't be saved.");+ return;+ }+ let file_name = path.file_name().and_then(|n| n.to_str()).unwrap_or(&base_name).to_owned();+ if let Some(node) = core_host::node() {+ node.record_timeline(+ nectarlink_core::TimelineKind::Photo,+ window.device,+ true,+ file_name.clone(),+ "Mirror screenshot".into(),+ path.to_string_lossy().into_owned(),+ png.len() as u64,+ 0,+ None,+ );+ }+ let device_name =+ core_host::host().hub.read(|s| s.name_of(&window.device)).unwrap_or_else(|| "your phone".into());+ toast::show(Toast {+ device: TOAST_GROUP.into(),+ key: path.to_string_lossy().into_owned(),+ title: file_name.clone(),+ body: format!("Screenshot from {device_name}, saved in Downloads\\Nectarlink"),+ attribution: "Nectarlink".into(),+ icon: None,+ image: Some(path),+ actions: vec![(ACTION_OPEN.into(), "Open".into()), (ACTION_SHOW.into(), "Show in folder".into())],+ reply: None,+ silent: false,+ progress: None,+ call: false,+ });+ set_notice(window, format!("Saved {file_name}"));+ show_message(format!("Saved {file_name} to Downloads\\Nectarlink."));+}++/// Whether `window` is currently recording to an MP4 file.+pub fn is_recording(window: &Window) -> bool {+ RECORDERS.lock().unwrap_or_else(|e| e.into_inner()).as_ref().is_some_and(|m| m.contains_key(window))+}++/// Unix epoch milliseconds when the active recording for `window` started (`0` if not recording).+pub fn recording_started_ms(window: &Window) -> i64 {+ RECORDERS+ .lock()+ .unwrap_or_else(|e| e.into_inner())+ .as_ref()+ .and_then(|m| m.get(window))+ .map_or(0, MirrorRecorder::started_epoch_ms)+}++/// Starts or stops MP4 recording for `window`.+pub fn toggle_recording(window: Window) {+ if is_recording(&window) {+ stop_recording(window);+ return;+ }+ if !matches!(phase(&window), Some(Phase::Showing)) {+ set_notice(window, "Wait for the screen to appear first");+ show_message("Wait for the screen to appear first.");+ return;+ }+ let base_name = local_timestamp_filename("Mirror", "mp4");+ let dir = core_host::downloads_dir();+ if let Err(e) = std::fs::create_dir_all(&dir) {+ tracing::warn!(error = %e, "can't create Downloads\\Nectarlink");+ set_notice(window, "Couldn't start recording");+ show_message("Couldn't start recording.");+ return;+ }+ let path = free_path(&dir, &base_name);+ let (width, height) = LAST_CONFIG+ .lock()+ .unwrap_or_else(|e| e.into_inner())+ .as_ref()+ .and_then(|m| m.get(&window).copied())+ .or_else(|| {+ FRAMES+ .lock()+ .unwrap_or_else(|e| e.into_inner())+ .as_ref()+ .and_then(|m| m.get(&window).map(|(w, h, _)| (*w, *h)))+ })+ .unwrap_or((0, 0));++ let audio_cfg = if window.session == MIRROR_SCREEN && has_sound(&window.device) {+ LAST_AUDIO_CONFIG+ .lock()+ .unwrap_or_else(|e| e.into_inner())+ .as_ref()+ .and_then(|m| m.get(&window.device).copied())+ .or(Some((48_000, 2)))+ } else {+ None+ };++ let mut recorder = MirrorRecorder::new(path, width, height, OPTIONS.fps, audio_cfg);+ if let Some(sps_pps) =+ LAST_SPS_PPS.lock().unwrap_or_else(|e| e.into_inner()).as_ref().and_then(|m| m.get(&window))+ {+ recorder.set_sps_pps(sps_pps);+ }++ RECORDERS+ .lock()+ .unwrap_or_else(|e| e.into_inner())+ .get_or_insert_with(HashMap::new)+ .insert(window, recorder);++ set_notice(window, "Recording started");+ core_host::host().hub.changed(Changes::MIRROR);+ if let Some(node) = core_host::node() {+ core_host::spawn(async move { node.mirror_keyframe(window.device, window.session).await });+ }+}++/// Stops and finalizes any active MP4 recording for `window`.+pub fn stop_recording(window: Window) {+ let recorder =+ RECORDERS.lock().unwrap_or_else(|e| e.into_inner()).as_mut().and_then(|m| m.remove(&window));+ let Some(recorder) = recorder else { return };+ core_host::host().hub.changed(Changes::MIRROR);+ let duration_secs = recorder.started_at().elapsed().as_secs().max(1);++ core_host::spawn(async move {+ let res = tokio::task::spawn_blocking(move || recorder.finish()).await;+ match res {+ Ok(Ok(path)) => {+ let file_name = path.file_name().and_then(|n| n.to_str()).unwrap_or("Mirror.mp4").to_owned();+ let size_bytes = std::fs::metadata(&path).map_or(0, |m| m.len());+ if let Some(node) = core_host::node() {+ node.record_timeline(+ nectarlink_core::TimelineKind::Recording,+ window.device,+ true,+ file_name.clone(),+ "Mirror recording".into(),+ path.to_string_lossy().into_owned(),+ size_bytes,+ duration_secs,+ None,+ );+ }+ let device_name = core_host::host()+ .hub+ .read(|s| s.name_of(&window.device))+ .unwrap_or_else(|| "your phone".into());+ toast::show(Toast {+ device: TOAST_GROUP.into(),+ key: path.to_string_lossy().into_owned(),+ title: file_name.clone(),+ body: format!("Recording from {device_name}, saved in Downloads\\Nectarlink"),+ attribution: "Nectarlink".into(),+ icon: None,+ image: None,+ actions: vec![+ (ACTION_OPEN.into(), "Open".into()),+ (ACTION_SHOW.into(), "Show in folder".into()),+ ],+ reply: None,+ silent: false,+ progress: None,+ call: false,+ });+ set_notice(window, format!("Saved {file_name}"));+ show_message(format!("Saved {file_name} to Downloads\\Nectarlink."));+ }+ Ok(Err(msg)) => {+ set_notice(window, msg.clone());+ show_message(msg);+ }+ Err(e) => {+ tracing::warn!(error = %e, "mirror recording finalize panicked");+ }+ }+ });+}+static STATE: Mutex<Option<State>> = Mutex::new(None);fn state<T>(f: impl FnOnce(&mut State) -> T) -> T {@@ -238,9 +655,43 @@ pub fn save_geometry(window: Window, x: i32, y: i32, width: u32, height: u32) {});}-/// Package names of apps opened on `device` from this PC, most recent first.+/// Package names of recent apps on `device` (apps opened from this PC first,+/// followed by apps with active or recent notifications), most recent first.pub fn recent_apps(device: &DeviceId) -> Vec<String> {- state(|s| s.saved.recent.get(&device.to_string()).cloned().unwrap_or_default())+ let saved = state(|s| s.saved.recent.get(&device.to_string()).cloned().unwrap_or_default());+ let (notif_pkgs, hist_pkgs) = core_host::host().hub.read(|s| {+ let active: Vec<String> = s+ .notifications+ .iter()+ .filter(|n| &n.device == device && !n.notification.app.is_empty())+ .map(|n| n.notification.app.clone())+ .collect();+ let history: Vec<String> = s+ .history+ .iter()+ .filter(|h| &h.device == device && !h.notification.app.is_empty())+ .map(|h| h.notification.app.clone())+ .collect();+ (active, history)+ });+ merge_recent_apps(&saved, notif_pkgs, hist_pkgs)+}++pub(crate) fn merge_recent_apps(+ saved: &[String],+ active_notif_pkgs: impl IntoIterator<Item = String>,+ history_pkgs: impl IntoIterator<Item = String>,+) -> Vec<String> {+ let mut out = Vec::with_capacity(12);+ for pkg in saved.iter().cloned().chain(active_notif_pkgs).chain(history_pkgs) {+ if !pkg.is_empty() && !out.contains(&pkg) {+ out.push(pkg);+ if out.len() >= 12 {+ break;+ }+ }+ }+ out}fn record_recent(s: &mut State, device: &DeviceId, pkg: &str) {@@ -253,10 +704,86 @@ fn record_recent(s: &mut State, device: &DeviceId, pkg: &str) {/// Asks the phone for its screen.pub fn start(device: DeviceId) {+ if keyboard_device() == Some(device) {+ set_remote_keyboard(None);+ }let window = Window::screen(device);ffi::video_clear(&window.key());- state(|s| s.windows.insert(window, Shown { phase: Phase::Asking, app: None, pkg: None }));- request(window, OPTIONS);+ let (stay_awake, screen_off) = state(|s| {+ s.screen_off.remove(&device);+ s.windows.insert(window, Shown { phase: Phase::Asking, app: None, pkg: None });+ (s.stay_awake.contains(&device), false)+ });+ request(window, MirrorStart { stay_awake, screen_off, ..OPTIONS });+}++/// Phone currently receiving PC keyboard input without screen mirroring.+pub fn keyboard_device() -> Option<DeviceId> {+ state(|s| s.keyboard_device)+}++/// Starts or stops remote keyboard typing on `device` without screen mirroring.+pub fn set_remote_keyboard(device: Option<DeviceId>) {+ let prev = state(|s| {+ let prev = s.keyboard_device;+ s.keyboard_device = device;+ prev+ });+ if prev == device {+ return;+ }+ if let Some(old) = prev {+ input(Window::screen(old), nectarlink_core::MirrorInput::Key { key: "keyboard_off".into() });+ }+ if let Some(new) = device {+ input(Window::screen(new), nectarlink_core::MirrorInput::Key { key: "keyboard_on".into() });+ }+ core_host::host().hub.changed(Changes::MIRROR);+}++/// Toggles remote keyboard typing on `device` without screen mirroring.+pub fn toggle_remote_keyboard(device: DeviceId) {+ if keyboard_device() == Some(device) {+ set_remote_keyboard(None);+ } else {+ set_remote_keyboard(Some(device));+ }+}++/// Sends a special key (`"enter"`, `"backspace"`, `"delete"`, `"left"`, `"right"`, `"up"`, `"down"`, `"tab"`, `"back"`, `"home"`)+/// to `device` while remote keyboard mode is active.+pub fn keyboard_press(device: DeviceId, key_name: String) {+ if keyboard_device() == Some(device) {+ input(Window::screen(device), nectarlink_core::MirrorInput::Key { key: key_name });+ }+}++/// Sends typed text to `device` while remote keyboard mode is active, splitting into protocol-sized chunks.+pub fn keyboard_text(device: DeviceId, text: String) {+ if keyboard_device() != Some(device) || text.is_empty() {+ return;+ }+ let window = Window::screen(device);+ let mut piece = String::new();+ for c in text.chars() {+ if piece.len() + c.len_utf8() > nectarlink_core::MIRROR_MAX_TEXT_BYTES {+ input(window, nectarlink_core::MirrorInput::Text { text: std::mem::take(&mut piece) });+ }+ piece.push(c);+ }+ if !piece.is_empty() {+ input(window, nectarlink_core::MirrorInput::Text { text: piece });+ }+}++/// Pastes the PC's current clipboard text onto `device` while remote keyboard mode is active.+pub fn keyboard_paste(device: DeviceId) {+ if keyboard_device() != Some(device) {+ return;+ }+ if let crate::win::clipboard::Clip::Text(text) = crate::win::clipboard::read() {+ keyboard_text(device, text);+ }}/// Opens one of the phone's apps in a window of its own (or does nothing@@ -350,7 +877,15 @@ fn request(window: Window, options: MirrorStart) {/// Stops a mirroring (its window closed).pub fn stop(window: Window) {- state(|s| s.windows.remove(&window));+ stop_recording(window);+ clear_window_buffers(&window);+ state(|s| {+ s.windows.remove(&window);+ s.notices.remove(&window);+ if window.session == MIRROR_SCREEN {+ s.screen_off.remove(&window.device);+ }+ });ffi::video_clear(&window.key());core_host::host().hub.changed(Changes::MIRROR);let Some(node) = core_host::node() else { return };@@ -375,13 +910,56 @@ pub fn on_event(event: &NodeEvent) {// Closed here: nothing to say. Stopped on the phone: say so.NodeEvent::Mirroring { device, session, on: false } => {let window = Window { device: *device, session: *session };+ stop_recording(window);+ clear_window_buffers(&window);+ if *session == MIRROR_SCREEN {+ let cleared_kb = state(|s| {+ s.screen_off.remove(device);+ if s.keyboard_device == Some(*device) {+ s.keyboard_device = None;+ true+ } else {+ false+ }+ });+ if cleared_kb {+ core_host::host().hub.changed(Changes::MIRROR);+ }+ }if phase(&window).is_some() {set_phase(window, Phase::Ended(None));}}// A phone that went away takes its app list with it.NodeEvent::LinkChanged { device, link: nectarlink_core::LinkState::Offline { .. } } => {- state(|s| s.apps.remove(device));+ let cleared_kb = state(|s| {+ s.apps.remove(device);+ s.screen_off.remove(device);+ if s.keyboard_device == Some(*device) {+ s.keyboard_device = None;+ true+ } else {+ false+ }+ });+ if cleared_kb {+ core_host::host().hub.changed(Changes::MIRROR);+ }+ }+ NodeEvent::DeviceRemoved(id) => {+ let cleared_kb = state(|s| {+ s.apps.remove(id);+ s.screen_off.remove(id);+ if s.keyboard_device == Some(*id) {+ s.keyboard_device = None;+ true+ } else {+ false+ }+ });+ if cleared_kb {+ core_host::host().hub.changed(Changes::MIRROR);+ }}_ => {}}@@ -571,12 +1149,33 @@ impl Sink {impl MirrorSink for Sink {fn config(&self, config: MirrorConfig) {+ LAST_CONFIG+ .lock()+ .unwrap_or_else(|e| e.into_inner())+ .get_or_insert_with(HashMap::new)+ .insert(self.window, (config.width, config.height));+ if let Some(rec) =+ RECORDERS.lock().unwrap_or_else(|e| e.into_inner()).as_mut().and_then(|m| m.get_mut(&self.window))+ {+ rec.on_config(config.width, config.height);+ }let video = self.video.get_or_init(|| Video::start(self.window));// The format matters: wait for room rather than drop it.let _ = video.queue.send(Item::Config(config));}fn packet(&self, keyframe: bool, time_us: u64, data: Vec<u8>) {+ {+ let mut sps_map = LAST_SPS_PPS.lock().unwrap_or_else(|e| e.into_inner());+ let entry = sps_map.get_or_insert_with(HashMap::new).entry(self.window).or_default();+ merge_sps_pps(entry, &data);+ }+ if let Some(rec) =+ RECORDERS.lock().unwrap_or_else(|e| e.into_inner()).as_mut().and_then(|m| m.get_mut(&self.window))+ && let Err(e) = rec.on_packet(keyframe, time_us, &data)+ {+ tracing::warn!(error = %e, "mirror recording packet failed");+ }let Some(video) = self.video.get() else { return };match video.queue.try_send(Item::Packet { keyframe, time_us, data }) {Ok(()) => {@@ -589,12 +1188,27 @@ impl MirrorSink for Sink {}fn ended(&self) {+ stop_recording(self.window);if let Some(video) = self.video.get() {let _ = video.queue.send(Item::Ended);}}fn audio_config(&self, config: MirrorAudioConfig) {+ LAST_AUDIO_CONFIG+ .lock()+ .unwrap_or_else(|e| e.into_inner())+ .get_or_insert_with(HashMap::new)+ .insert(self.window.device, (config.rate, config.channels));+ if self.window.session == MIRROR_SCREEN+ && let Some(rec) = RECORDERS+ .lock()+ .unwrap_or_else(|e| e.into_inner())+ .as_mut()+ .and_then(|m| m.get_mut(&self.window))+ {+ rec.on_audio_config(config.rate, config.channels);+ }let mut sound = self.sound.lock().unwrap_or_else(|e| e.into_inner());// A new format: a new player (the old one ends when dropped).*sound = match Player::start(config.rate, u16::from(config.channels)) {@@ -607,7 +1221,17 @@ impl MirrorSink for Sink {set_sound(self.window.device, sound.is_some());}- fn audio(&self, _time_us: u64, data: Vec<u8>) {+ fn audio(&self, time_us: u64, data: Vec<u8>) {+ if self.window.session == MIRROR_SCREEN+ && let Some(rec) = RECORDERS+ .lock()+ .unwrap_or_else(|e| e.into_inner())+ .as_mut()+ .and_then(|m| m.get_mut(&self.window))+ && let Err(e) = rec.on_audio(time_us, &data)+ {+ tracing::debug!(error = %e, "mirror recording audio packet failed");+ }if muted() {return;}@@ -678,9 +1302,11 @@ fn decode(window: Window, items: &Receiver<Item>, waiting: &AtomicUsize) {let bgrx = to_bgrx(picture, w, h);if (src_w, src_h) == (w, h) || src_w == 0 || src_h == 0 {ffi::video_frame(&stream, src_w, src_h, &bgrx);+ save_latest_frame(window, src_w, src_h, bgrx);} else {let scaled = scale_bgrx(&bgrx, src_w, src_h, w, h);ffi::video_frame(&stream, w, h, &scaled);+ save_latest_frame(window, w, h, scaled);}stats.shown(decoded, converted.elapsed());} else {@@ -690,6 +1316,7 @@ fn decode(window: Window, items: &Receiver<Item>, waiting: &AtomicUsize) {Item::Ended => break,}}+ clear_window_buffers(&window);ffi::video_clear(&stream);}@@ -748,3 +1375,28 @@ impl Stats {*self = Stats::new();}}++#[cfg(test)]+mod tests {+ use super::merge_recent_apps;++ #[test]+ fn recent_apps_combines_saved_and_notification_packages_without_duplicates() {+ let saved = vec!["com.android.settings".to_owned(), "org.telegram.messenger".to_owned()];+ let active = vec![+ "org.telegram.messenger".to_owned(),+ "com.google.android.apps.messaging".to_owned(),+ String::new(),+ ];+ let history = vec!["com.google.android.apps.messaging".to_owned(), "com.spotify.music".to_owned()];+ assert_eq!(+ merge_recent_apps(&saved, active, history),+ vec![+ "com.android.settings".to_owned(),+ "org.telegram.messenger".to_owned(),+ "com.google.android.apps.messaging".to_owned(),+ "com.spotify.music".to_owned(),+ ]+ );+ }+}diff --git a/desktop/app/src/notifications.rs b/desktop/app/src/notifications.rsindex 90cb6c5..2df81e0 100644--- a/desktop/app/src/notifications.rs+++ b/desktop/app/src/notifications.rs@@ -472,7 +472,34 @@ pub fn on_toast(event: ToastEvent) {_ => {}}match event {- ToastEvent::Opened { .. } => crate::bridge::app::request_activation(),+ ToastEvent::Opened { device, key } => {+ if let Ok(dev) = device.parse::<DeviceId>() {+ let app_target = core_host::host().hub.read(|s| {+ let can_open = s.matrices.get(&dev).and_then(|m| m.state("mirroring.app_windows"))+ == Some(nectarlink_core::FeatureState::Available);+ if !can_open {+ return None;+ }+ s.notifications+ .iter()+ .find(|n| n.device == dev && n.notification.key == key)+ .map(|n| (n.notification.app.clone(), n.notification.app_name.clone()))+ .or_else(|| {+ s.history+ .iter()+ .find(|h| h.device == dev && h.notification.key == key)+ .map(|h| (h.notification.app.clone(), h.notification.app_name.clone()))+ })+ .filter(|(pkg, _)| !pkg.is_empty())+ });+ if let Some((pkg, app_name)) = app_target {+ let label = if app_name.is_empty() { pkg.clone() } else { app_name };+ crate::mirror::start_app(dev, pkg, label);+ return;+ }+ }+ crate::bridge::app::request_activation();+ }ToastEvent::Action { device, key, action } if action == ACTION_COPY_OTP => {if let Ok(dev) = device.parse::<DeviceId>() {let code = otp_codes(|c| c.get(&(dev, key.clone())).cloned()).or_else(|| {diff --git a/desktop/app/src/settings.rs b/desktop/app/src/settings.rsindex fe8d380..b13ad0f 100644--- a/desktop/app/src/settings.rs+++ b/desktop/app/src/settings.rs@@ -114,6 +114,8 @@ pub struct Settings {pub continuity_scan_hotkey: String,/// Global hotkey to open the Command Palette (e.g. `"Ctrl+Alt+Space"`, or `""` to disable).pub command_palette_hotkey: String,+ /// Global hotkey to slide out the Shelf panel at the screen edge (e.g. `"Ctrl+Alt+S"`, or `""` to disable).+ pub shelf_hotkey: String,}impl Default for Settings {@@ -143,6 +145,7 @@ impl Default for Settings {continuity_photo_hotkey: "Ctrl+Alt+C".into(),continuity_scan_hotkey: "Ctrl+Alt+D".into(),command_palette_hotkey: "Ctrl+Alt+Space".into(),+ shelf_hotkey: "Ctrl+Alt+S".into(),}}}@@ -197,6 +200,7 @@ mod tests {let def = Settings::load(dir.path());assert_eq!(def, Settings::default());assert_eq!(def.command_palette_hotkey, "Ctrl+Alt+Space");+ assert_eq!(def.shelf_hotkey, "Ctrl+Alt+S");let settings = Settings {theme: Theme::Graphite,@@ -223,6 +227,7 @@ mod tests {continuity_photo_hotkey: "Ctrl+Alt+P".into(),continuity_scan_hotkey: "Ctrl+Alt+S".into(),command_palette_hotkey: "Ctrl+Shift+Space".into(),+ shelf_hotkey: "Ctrl+Alt+E".into(),};settings.save(dir.path()).unwrap();assert_eq!(Settings::load(dir.path()), settings);diff --git a/desktop/app/src/state.rs b/desktop/app/src/state.rsindex 486f684..cc77a55 100644--- a/desktop/app/src/state.rs+++ b/desktop/app/src/state.rs@@ -1046,6 +1046,7 @@ mod tests {state,recording: false,markers: Vec::new(),+ open_on_arrival: false,}}diff --git a/desktop/app/src/transfers.rs b/desktop/app/src/transfers.rsindex 5959f5b..cf7cb22 100644--- a/desktop/app/src/transfers.rs+++ b/desktop/app/src/transfers.rs@@ -36,6 +36,16 @@ pub fn title(t: &Transfer) -> String {/// Sends files and folders to a device; the transfer list shows how it goes.pub fn send(device: DeviceId, paths: Vec<PathBuf>) {+ send_with_mode(device, paths, false);+}++/// Hands off a document to a device and asks the receiver to open it with its+/// default app once it arrives.+pub fn send_handoff(device: DeviceId, paths: Vec<PathBuf>) {+ send_with_mode(device, paths, true);+}++fn send_with_mode(device: DeviceId, paths: Vec<PathBuf>, handoff: bool) {let Some(node) = core_host::node() else { return };core_host::spawn(async move {let files = match tokio::task::spawn_blocking(move || nectarlink_core::outgoing_paths(&paths)).await {@@ -45,7 +55,12 @@ pub fn send(device: DeviceId, paths: Vec<PathBuf>) {Ok(Err(e)) => return show_message(describe(&e)),Err(_) => return,};- match node.send_files(device, files).await {+ let res = if handoff {+ node.send_handoff_files(device, files).await+ } else {+ node.send_files(device, files).await+ };+ match res {Ok(_) => {}Err(Error::Denied) => show_message("Files are turned off for that device."),Err(e) => show_message(describe(&e)),@@ -127,6 +142,13 @@ pub fn on_event(event: &NodeEvent) {return crate::recordings::on_done(t.clone());}let Some(first) = saved.first() else { return };+ let auto_open = t.open_on_arrival+ && saved.len() == 1+ && first.is_file()+ && first.file_name().and_then(|n| n.to_str()).is_some_and(nectarlink_core::is_safe_handoff_document);+ if auto_open {+ open(first);+ }let device = core_host::host().hub.read(|s| s.name_of(&t.device))@@ -140,11 +162,15 @@ pub fn on_event(event: &NodeEvent) {device: TOAST_GROUP.into(),key: first.to_string_lossy().into_owned(),title,- body: format!("From {device}, saved in Downloads\\Nectarlink"),+ body: if auto_open {+ format!("From {device}, opened from Downloads\\Nectarlink")+ } else {+ format!("From {device}, saved in Downloads\\Nectarlink")+ },attribution: "Nectarlink".into(),icon: None,image: None,- actions: vec![(ACTION_SHOW.into(), "Show in folder".into())],+ actions: vec![(ACTION_OPEN.into(), "Open".into()), (ACTION_SHOW.into(), "Show in folder".into())],reply: None,silent: false,progress: None,diff --git a/desktop/app/src/win/mod.rs b/desktop/app/src/win/mod.rsindex 64804ee..12ecedb 100644--- a/desktop/app/src/win/mod.rs+++ b/desktop/app/src/win/mod.rs@@ -16,6 +16,7 @@ pub mod icon;pub mod image;pub mod input;pub mod media_sessions;+pub mod mp4;pub mod net;pub mod shell;pub mod shortcut;diff --git a/desktop/app/src/win/mp4.rs b/desktop/app/src/win/mp4.rsnew file mode 100644index 0000000..a379539--- /dev/null+++ b/desktop/app/src/win/mp4.rs@@ -0,0 +1,527 @@+// SPDX-License-Identifier: GPL-3.0-or-later+//! MP4 recording for mirrored phone screens and app windows using Windows+//! Media Foundation's `IMFSinkWriter`.+//!+//! Video is muxed as H.264 passthrough (`MFVideoFormat_H264` on both input and+//! output streams of the sink writer) so zero video re-encoding occurs on the+//! PC. When phone audio (16-bit PCM) is present, it is encoded to AAC-LC+//! (`MFAudioFormat_AAC`) into the same `.mp4` container.++use std::{+ path::{Path, PathBuf},+ time::{Instant, SystemTime, UNIX_EPOCH},+};++use windows::{+ Win32::{+ Media::MediaFoundation::{+ IMFMediaBuffer, IMFMediaType, IMFSample, IMFSinkWriter, MF_MT_ALL_SAMPLES_INDEPENDENT,+ MF_MT_AUDIO_AVG_BYTES_PER_SECOND, MF_MT_AUDIO_BITS_PER_SAMPLE, MF_MT_AUDIO_BLOCK_ALIGNMENT,+ MF_MT_AUDIO_NUM_CHANNELS, MF_MT_AUDIO_SAMPLES_PER_SECOND, MF_MT_AVG_BITRATE, MF_MT_FRAME_RATE,+ MF_MT_FRAME_SIZE, MF_MT_INTERLACE_MODE, MF_MT_MAJOR_TYPE, MF_MT_MPEG_SEQUENCE_HEADER,+ MF_MT_PIXEL_ASPECT_RATIO, MF_MT_SUBTYPE, MFAudioFormat_AAC, MFAudioFormat_PCM, MFCreateMediaType,+ MFCreateMemoryBuffer, MFCreateSample, MFCreateSinkWriterFromURL, MFMediaType_Audio,+ MFMediaType_Video, MFSampleExtension_CleanPoint, MFVideoFormat_H264,+ MFVideoInterlace_Progressive,+ },+ System::SystemInformation::GetLocalTime,+ },+ core::HSTRING,+};++use super::h264::ensure_mf_started;++/// Formats `<prefix> YYYY-MM-DD HH.MM.SS.<ext>` using the PC's local clock.+pub fn local_timestamp_filename(prefix: &str, ext: &str) -> String {+ // SAFETY: GetLocalTime always succeeds and writes a SYSTEMTIME struct.+ let st = unsafe { GetLocalTime() };+ format!(+ "{prefix} {:04}-{:02}-{:02} {:02}.{:02}.{:02}.{ext}",+ st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond+ )+}++struct ActiveWriter {+ writer: IMFSinkWriter,+ video_stream: u32,+ audio_stream: Option<(u32, u32, u8)>,+ first_video_us: Option<u64>,+ last_video_hns: i64,+ video_frames_written: u64,+ first_audio_us: Option<u64>,+ last_audio_hns: i64,+ audio_samples_written: u64,+}++// SAFETY: Media Foundation runs in the multithreaded apartment (`COINIT_MULTITHREADED`+// via `ensure_mf_started`), and all access to `ActiveWriter` is serialized through `&mut self`.+unsafe impl Send for ActiveWriter {}++/// Records a mirrored H.264 stream (and optional PCM audio stream) into an `.mp4` file.+pub struct MirrorRecorder {+ path: PathBuf,+ width: u32,+ height: u32,+ fps: u32,+ audio_cfg: Option<(u32, u8)>,+ sps_pps: Vec<u8>,+ writer: Option<ActiveWriter>,+ started_at: Instant,+ started_epoch_ms: i64,+}++impl std::fmt::Debug for MirrorRecorder {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ f.debug_struct("MirrorRecorder")+ .field("path", &self.path)+ .field("width", &self.width)+ .field("height", &self.height)+ .field("active", &self.writer.is_some())+ .finish_non_exhaustive()+ }+}++impl MirrorRecorder {+ pub fn new(+ path: PathBuf,+ width: u32,+ height: u32,+ fps: u32,+ audio_cfg: Option<(u32, u8)>,+ ) -> MirrorRecorder {+ let started_epoch_ms =+ SystemTime::now().duration_since(UNIX_EPOCH).map_or(0, |d| d.as_millis() as i64);+ MirrorRecorder {+ path,+ width,+ height,+ fps: fps.max(1),+ audio_cfg,+ sps_pps: Vec::new(),+ writer: None,+ started_at: Instant::now(),+ started_epoch_ms,+ }+ }++ pub fn started_at(&self) -> Instant {+ self.started_at+ }++ pub fn started_epoch_ms(&self) -> i64 {+ self.started_epoch_ms+ }++ /// Seeds cached SPS/PPS NAL units collected before recording started.+ pub fn set_sps_pps(&mut self, sps_pps: &[u8]) {+ if !sps_pps.is_empty() {+ merge_sps_pps(&mut self.sps_pps, sps_pps);+ }+ }++ /// Updates stream dimensions before the first keyframe initializes the writer.+ pub fn on_config(&mut self, width: u32, height: u32) {+ if self.writer.is_none() && width > 0 && height > 0 {+ self.width = width;+ self.height = height;+ }+ }++ /// Updates audio configuration before the first keyframe initializes the writer.+ pub fn on_audio_config(&mut self, rate: u32, channels: u8) {+ if self.writer.is_none() && rate > 0 && channels > 0 {+ self.audio_cfg = Some((rate, channels));+ }+ }++ /// Processes an incoming Annex-B H.264 access unit.+ pub fn on_packet(&mut self, keyframe: bool, time_us: u64, data: &[u8]) -> Result<(), String> {+ if data.is_empty() {+ return Ok(());+ }+ merge_sps_pps(&mut self.sps_pps, data);++ // If this packet only carries parameter sets (SPS/PPS) without a coded frame,+ // keep them for the upcoming keyframe without writing an empty video sample.+ if is_parameter_only(data) {+ return Ok(());+ }++ let is_keyframe = keyframe || has_idr_slice(data);++ if self.writer.is_none() {+ if !is_keyframe || self.width == 0 || self.height == 0 {+ return Ok(());+ }+ let active = ActiveWriter::open(+ &self.path,+ self.width,+ self.height,+ self.fps,+ &self.sps_pps,+ self.audio_cfg,+ )+ .map_err(|e| e.to_string())?;+ self.writer = Some(active);+ }++ let Some(w) = self.writer.as_mut() else {+ return Ok(());+ };++ ensure_mf_started().map_err(|e| e.to_string())?;+ let first_us = *w.first_video_us.get_or_insert(time_us);+ let mut hns = (time_us.saturating_sub(first_us) * 10) as i64;+ if w.video_frames_written > 0 && hns <= w.last_video_hns {+ hns = w.last_video_hns + 10_000;+ }+ w.last_video_hns = hns;+ let dur_hns = (10_000_000 / u64::from(self.fps.max(1))) as i64;++ let mut combined = Vec::new();+ let payload: &[u8] = if is_keyframe && !data_has_sps_pps(data) && !self.sps_pps.is_empty() {+ combined.reserve(self.sps_pps.len() + data.len());+ combined.extend_from_slice(&self.sps_pps);+ combined.extend_from_slice(data);+ &combined+ } else {+ data+ };++ write_sample(&w.writer, w.video_stream, payload, hns, dur_hns, is_keyframe)+ .map_err(|e| e.to_string())?;+ w.video_frames_written += 1;+ Ok(())+ }++ /// Processes an incoming 16-bit interleaved PCM audio packet.+ pub fn on_audio(&mut self, time_us: u64, pcm: &[u8]) -> Result<(), String> {+ if pcm.is_empty() {+ return Ok(());+ }+ let Some(w) = self.writer.as_mut() else {+ // Wait until the first video keyframe initializes the writer so audio and video start at t=0.+ return Ok(());+ };+ let Some((stream_idx, rate, channels)) = w.audio_stream else {+ return Ok(());+ };++ ensure_mf_started().map_err(|e| e.to_string())?;+ let first_us = *w.first_audio_us.get_or_insert(time_us);+ let mut hns = (time_us.saturating_sub(first_us) * 10) as i64;+ if w.audio_samples_written > 0 && hns <= w.last_audio_hns {+ hns = w.last_audio_hns + 1;+ }+ let bytes_per_frame = (usize::from(channels.max(1)) * 2).max(2);+ let frames = pcm.len() / bytes_per_frame;+ if frames == 0 {+ return Ok(());+ }+ let dur_hns = ((frames as u64) * 10_000_000 / u64::from(rate.max(1))).max(1) as i64;+ w.last_audio_hns = hns + dur_hns;++ write_sample(&w.writer, stream_idx, pcm, hns, dur_hns, false).map_err(|e| e.to_string())?;+ w.audio_samples_written += 1;+ Ok(())+ }++ /// Finalizes the MP4 container and flushes it to disk.+ pub fn finish(mut self) -> Result<PathBuf, String> {+ if let Some(w) = self.writer.take()+ && w.video_frames_written > 0+ {+ ensure_mf_started().map_err(|e| e.to_string())?;+ if let Some((stream_idx, rate, channels)) = w.audio_stream+ && w.audio_samples_written == 0+ {+ // Media Foundation's MP4 sink rejects Finalize() with MF_E_SINK_NO_SAMPLES_PROCESSED+ // if a declared stream received 0 samples; write a single 20 ms silent frame.+ let silence_len = (rate as usize / 50).max(1) * usize::from(channels.max(1)) * 2;+ let silence = vec![0u8; silence_len];+ let _ = write_sample(&w.writer, stream_idx, &silence, 0, 200_000, false);+ }+ // SAFETY: Finalize flushes and closes the MP4 sink writer.+ unsafe { w.writer.Finalize() }.map_err(|e| e.to_string())?;+ drop(w);+ return Ok(self.path);+ }+ let _ = std::fs::remove_file(&self.path);+ Err("No video frames were recorded yet.".into())+ }+}++impl ActiveWriter {+ fn open(+ path: &Path,+ width: u32,+ height: u32,+ fps: u32,+ sps_pps: &[u8],+ audio_cfg: Option<(u32, u8)>,+ ) -> windows::core::Result<ActiveWriter> {+ ensure_mf_started()?;+ if let Some(parent) = path.parent() {+ let _ = std::fs::create_dir_all(parent);+ }+ let _ = std::fs::remove_file(path);++ // SAFETY: Media Foundation COM calls with owned parameters.+ unsafe {+ let writer: IMFSinkWriter =+ MFCreateSinkWriterFromURL(&HSTRING::from(path.as_os_str()), None, None)?;++ let video_out: IMFMediaType = MFCreateMediaType()?;+ video_out.SetGUID(&MF_MT_MAJOR_TYPE, &MFMediaType_Video)?;+ video_out.SetGUID(&MF_MT_SUBTYPE, &MFVideoFormat_H264)?;+ video_out.SetUINT32(&MF_MT_AVG_BITRATE, 8_000_000)?;+ video_out.SetUINT32(&MF_MT_INTERLACE_MODE, MFVideoInterlace_Progressive.0 as u32)?;+ video_out.SetUINT64(&MF_MT_FRAME_SIZE, (u64::from(width) << 32) | u64::from(height))?;+ video_out.SetUINT64(&MF_MT_FRAME_RATE, (u64::from(fps.max(1)) << 32) | 1u64)?;+ video_out.SetUINT64(&MF_MT_PIXEL_ASPECT_RATIO, (1u64 << 32) | 1u64)?;+ if !sps_pps.is_empty() {+ video_out.SetBlob(&MF_MT_MPEG_SEQUENCE_HEADER, sps_pps)?;+ }++ let video_stream = writer.AddStream(&video_out)?;+ writer.SetInputMediaType(video_stream, &video_out, None)?;++ let mut audio_stream = None;+ if let Some((rate, channels)) = audio_cfg+ && rate > 0+ && channels > 0+ {+ match add_aac_stream(&writer, rate, channels) {+ Ok(idx) => audio_stream = Some((idx, rate, channels)),+ Err(e) => {+ tracing::warn!(error = %e, "couldn't add AAC audio stream to MP4; recording video only");+ }+ }+ }++ writer.BeginWriting()?;++ Ok(ActiveWriter {+ writer,+ video_stream,+ audio_stream,+ first_video_us: None,+ last_video_hns: 0,+ video_frames_written: 0,+ first_audio_us: None,+ last_audio_hns: 0,+ audio_samples_written: 0,+ })+ }+ }+}++unsafe fn add_aac_stream(writer: &IMFSinkWriter, rate: u32, channels: u8) -> windows::core::Result<u32> {+ let ch = u32::from(channels);+ let block_align = ch * 2;+ // SAFETY: Media Foundation media type creation and stream setup.+ unsafe {+ let audio_out: IMFMediaType = MFCreateMediaType()?;+ audio_out.SetGUID(&MF_MT_MAJOR_TYPE, &MFMediaType_Audio)?;+ audio_out.SetGUID(&MF_MT_SUBTYPE, &MFAudioFormat_AAC)?;+ audio_out.SetUINT32(&MF_MT_AUDIO_SAMPLES_PER_SECOND, rate)?;+ audio_out.SetUINT32(&MF_MT_AUDIO_NUM_CHANNELS, ch)?;+ audio_out.SetUINT32(&MF_MT_AUDIO_BITS_PER_SAMPLE, 16)?;+ audio_out.SetUINT32(&MF_MT_AUDIO_AVG_BYTES_PER_SECOND, 20_000)?;++ let stream_idx = writer.AddStream(&audio_out)?;++ let audio_in: IMFMediaType = MFCreateMediaType()?;+ audio_in.SetGUID(&MF_MT_MAJOR_TYPE, &MFMediaType_Audio)?;+ audio_in.SetGUID(&MF_MT_SUBTYPE, &MFAudioFormat_PCM)?;+ audio_in.SetUINT32(&MF_MT_AUDIO_SAMPLES_PER_SECOND, rate)?;+ audio_in.SetUINT32(&MF_MT_AUDIO_NUM_CHANNELS, ch)?;+ audio_in.SetUINT32(&MF_MT_AUDIO_BITS_PER_SAMPLE, 16)?;+ audio_in.SetUINT32(&MF_MT_AUDIO_BLOCK_ALIGNMENT, block_align)?;+ audio_in.SetUINT32(&MF_MT_AUDIO_AVG_BYTES_PER_SECOND, rate * block_align)?;+ audio_in.SetUINT32(&MF_MT_ALL_SAMPLES_INDEPENDENT, 1)?;++ writer.SetInputMediaType(stream_idx, &audio_in, None)?;+ Ok(stream_idx)+ }+}++fn write_sample(+ writer: &IMFSinkWriter,+ stream_idx: u32,+ bytes: &[u8],+ hns: i64,+ dur_hns: i64,+ clean_point: bool,+) -> windows::core::Result<()> {+ // SAFETY: buffer is sized to `bytes.len()`, locked while copied, and unlocked before WriteSample.+ unsafe {+ let buf: IMFMediaBuffer = MFCreateMemoryBuffer(bytes.len() as u32)?;+ let mut dst = std::ptr::null_mut();+ buf.Lock(&mut dst, None, None)?;+ std::ptr::copy_nonoverlapping(bytes.as_ptr(), dst, bytes.len());+ buf.Unlock()?;+ buf.SetCurrentLength(bytes.len() as u32)?;++ let sample: IMFSample = MFCreateSample()?;+ sample.AddBuffer(&buf)?;+ sample.SetSampleTime(hns)?;+ sample.SetSampleDuration(dur_hns.max(1))?;+ if clean_point {+ sample.SetUINT32(&MFSampleExtension_CleanPoint, 1)?;+ }+ writer.WriteSample(stream_idx, &sample)+ }+}++/// Splits an Annex-B buffer into `(nal_type, nal_payload_without_start_code)` slices.+fn annex_b_nals(data: &[u8]) -> Vec<(u8, &[u8])> {+ let mut starts = Vec::new();+ let mut i = 0;+ while i + 3 <= data.len() {+ if i + 4 <= data.len() && data[i..i + 4] == [0, 0, 0, 1] {+ starts.push((i, i + 4));+ i += 4;+ } else if data[i..i + 3] == [0, 0, 1] {+ starts.push((i, i + 3));+ i += 3;+ } else {+ i += 1;+ }+ }+ let mut out = Vec::with_capacity(starts.len());+ for (idx, &(_, payload_start)) in starts.iter().enumerate() {+ let payload_end = starts.get(idx + 1).map_or(data.len(), |&(next_code, _)| next_code);+ if payload_start < payload_end {+ let payload = &data[payload_start..payload_end];+ out.push((payload[0] & 0x1F, payload));+ }+ }+ out+}++/// Extracts any SPS (NAL 7) and PPS (NAL 8) units from `data` and merges them+/// into `sps_pps` with 4-byte `00 00 00 01` Annex-B start codes.+pub fn merge_sps_pps(sps_pps: &mut Vec<u8>, data: &[u8]) {+ let nals = annex_b_nals(data);+ if !nals.iter().any(|&(t, _)| t == 7 || t == 8) {+ return;+ }+ let existing = annex_b_nals(sps_pps);+ let mut sps: Option<Vec<u8>> = existing.iter().find(|&&(t, _)| t == 7).map(|&(_, p)| p.to_vec());+ let mut pps: Option<Vec<u8>> = existing.iter().find(|&&(t, _)| t == 8).map(|&(_, p)| p.to_vec());+ for (t, payload) in nals {+ if t == 7 {+ sps = Some(payload.to_vec());+ } else if t == 8 {+ pps = Some(payload.to_vec());+ }+ }+ sps_pps.clear();+ if let Some(s) = sps {+ sps_pps.extend_from_slice(&[0, 0, 0, 1]);+ sps_pps.extend_from_slice(&s);+ }+ if let Some(p) = pps {+ sps_pps.extend_from_slice(&[0, 0, 0, 1]);+ sps_pps.extend_from_slice(&p);+ }+}++fn data_has_sps_pps(data: &[u8]) -> bool {+ let nals = annex_b_nals(data);+ nals.iter().any(|&(t, _)| t == 7) && nals.iter().any(|&(t, _)| t == 8)+}++fn has_idr_slice(data: &[u8]) -> bool {+ annex_b_nals(data).iter().any(|&(t, _)| t == 5)+}++fn is_parameter_only(data: &[u8]) -> bool {+ let nals = annex_b_nals(data);+ !nals.is_empty() && nals.iter().all(|&(t, _)| t == 7 || t == 8)+}++#[cfg(test)]+mod tests {+ use super::*;++ /// Splits an Annex-B stream into access units at its access unit delimiters (NAL type 9).+ fn access_units(stream: &[u8]) -> Vec<&[u8]> {+ let starts: Vec<usize> =+ (0..stream.len()).filter(|&i| stream[i..].starts_with(&[0, 0, 0, 1, 9])).collect();+ starts+ .iter()+ .enumerate()+ .map(|(n, &s)| &stream[s..*starts.get(n + 1).unwrap_or(&stream.len())])+ .collect()+ }++ fn contains_subslice(haystack: &[u8], needle: &[u8]) -> bool {+ haystack.windows(needle.len()).any(|w| w == needle)+ }++ #[test]+ fn muxes_h264_passthrough_to_mp4() {+ let dir = tempfile::tempdir().unwrap();+ let mp4_path = dir.path().join("passthrough.mp4");+ let units = access_units(include_bytes!("testdata/testsrc.h264"));+ assert!(!units.is_empty());++ let mut rec = MirrorRecorder::new(mp4_path.clone(), 320, 240, 30, None);+ for (i, unit) in units.iter().enumerate() {+ let keyframe = i % 5 == 0;+ rec.on_packet(keyframe, (i as u64) * 33_333, unit).unwrap();+ }+ let saved = rec.finish().unwrap();+ assert_eq!(saved, mp4_path);+ let bytes = std::fs::read(&saved).unwrap();+ assert!(bytes.len() > 200, "unexpectedly small MP4: {} B", bytes.len());+ assert_eq!(&bytes[4..8], b"ftyp");+ assert!(contains_subslice(&bytes, b"moov"), "missing moov box");+ assert!(contains_subslice(&bytes, b"mdat"), "missing mdat box");+ assert!(contains_subslice(&bytes, b"avc1"), "missing avc1 sample entry");+ let _ = std::fs::remove_file(&saved);+ }++ #[test]+ fn muxes_h264_and_pcm_audio_to_mp4() {+ let dir = tempfile::tempdir().unwrap();+ let units = access_units(include_bytes!("testdata/testsrc.h264"));++ // 1. Video + 48 kHz stereo PCM audio frames.+ let mp4_with_audio = dir.path().join("with_audio.mp4");+ let mut rec = MirrorRecorder::new(mp4_with_audio.clone(), 320, 240, 30, Some((48_000, 2)));+ let pcm_20ms = vec![0u8; (48_000 / 50) * 2 * 2];+ for (i, unit) in units.iter().enumerate() {+ let t_us = (i as u64) * 33_333;+ rec.on_packet(i % 5 == 0, t_us, unit).unwrap();+ rec.on_audio(t_us, &pcm_20ms).unwrap();+ }+ let saved = rec.finish().unwrap();+ let bytes = std::fs::read(&saved).unwrap();+ assert!(bytes.len() > 200);+ assert_eq!(&bytes[4..8], b"ftyp");+ assert!(contains_subslice(&bytes, b"moov"));+ assert!(contains_subslice(&bytes, b"mdat"));+ assert!(contains_subslice(&bytes, b"avc1"));+ assert!(contains_subslice(&bytes, b"mp4a"));+ let _ = std::fs::remove_file(&saved);++ // 2. Audio stream declared (`Some((48_000, 2))`), but 0 audio packets arrive:+ // the silent-frame safeguard must still allow Finalize() to succeed cleanly.+ let mp4_silent_safeguard = dir.path().join("silent_safeguard.mp4");+ let mut rec2 = MirrorRecorder::new(mp4_silent_safeguard.clone(), 320, 240, 30, Some((48_000, 2)));+ for (i, unit) in units.iter().enumerate() {+ rec2.on_packet(i % 5 == 0, (i as u64) * 33_333, unit).unwrap();+ }+ let saved2 = rec2.finish().unwrap();+ let bytes2 = std::fs::read(&saved2).unwrap();+ assert!(bytes2.len() > 200);+ assert_eq!(&bytes2[4..8], b"ftyp");+ assert!(contains_subslice(&bytes2, b"moov"));+ assert!(contains_subslice(&bytes2, b"avc1"));+ assert!(contains_subslice(&bytes2, b"mp4a"));+ let _ = std::fs::remove_file(&saved2);+ }+}diff --git a/desktop/app/src/win/tray.rs b/desktop/app/src/win/tray.rsindex 7825c3d..0ba8f71 100644--- a/desktop/app/src/win/tray.rs+++ b/desktop/app/src/win/tray.rs@@ -57,6 +57,7 @@ use windows::{pub enum TrayEvent {Open,CommandPalette,+ Shelf,TakePhoto,ScanDocument,FindPhone,@@ -75,6 +76,7 @@ pub enum TrayEvent {pub struct MenuLabels {pub open: String,pub command_palette: String,+ pub shelf: String,pub take_photo: String,pub scan_document: String,pub find_phone: String,@@ -89,6 +91,7 @@ const TIMER_TRACK_FG: usize = 1;const HOTKEY_PHOTO_ID: i32 = 101;const HOTKEY_SCAN_ID: i32 = 102;const HOTKEY_PALETTE_ID: i32 = 103;+const HOTKEY_SHELF_ID: i32 = 104;const ICON_ID: u32 = 1;const CMD_OPEN: u32 = 1;const CMD_FIND_PHONE: u32 = 2;@@ -97,6 +100,7 @@ const CMD_OPEN_LINK: u32 = 4;const CMD_TAKE_PHOTO: u32 = 5;const CMD_SCAN_DOCUMENT: u32 = 6;const CMD_COMMAND_PALETTE: u32 = 7;+const CMD_SHELF: u32 = 8;const PBT_APMRESUMEAUTOMATIC: usize = 0x12;/// NIN_SELECT | NINF_KEY (shellapi.h): the icon was activated with the keyboard.const NIN_KEYSELECT: u32 = NIN_SELECT | 0x1;@@ -107,8 +111,8 @@ type Handler = Box<dyn Fn(TrayEvent)>;static TRAY_HWND: AtomicIsize = AtomicIsize::new(0);static LAST_EXTERNAL_FOREGROUND: Mutex<Option<(isize, String)>> = Mutex::new(None);-static HOTKEY_SPECS: Mutex<(String, String, String)> =- Mutex::new((String::new(), String::new(), String::new()));+static HOTKEY_SPECS: Mutex<(String, String, String, String)> =+ Mutex::new((String::new(), String::new(), String::new(), String::new()));thread_local! {static HANDLER: RefCell<Option<Handler>> = RefCell::new(None);@@ -308,6 +312,35 @@ pub fn send_paste_fallback_if_not_foreground(hwnd: isize) {}}+/// Applies `WS_EX_NOACTIVATE | WS_EX_TOOLWINDOW | WS_EX_TOPMOST` to a top-level+/// window owned by this process matching `title`, so clicking or dragging inside+/// the Shelf never steals keyboard focus from the user's active window.+pub fn apply_no_activate_style_by_title(title: &str) {+ // SAFETY: Enumerates top-level windows in Z-order and updates GWL_EXSTYLE on a window owned by this process.+ unsafe {+ let self_pid = GetCurrentProcessId();+ let mut cur = match GetTopWindow(None) {+ Ok(h) => h,+ Err(_) => return,+ };+ for _ in 0..256 {+ let mut pid: u32 = 0;+ GetWindowThreadProcessId(cur, Some(&mut pid));+ if pid == self_pid && window_title(cur) == title {+ let ex = GetWindowLongW(cur, GWL_EXSTYLE) as u32;+ let wanted = ex | WS_EX_NOACTIVATE.0 | WS_EX_TOOLWINDOW.0 | WS_EX_TOPMOST.0;+ let _ =+ windows::Win32::UI::WindowsAndMessaging::SetWindowLongW(cur, GWL_EXSTYLE, wanted as i32);+ break;+ }+ match GetWindow(cur, GW_HWNDNEXT) {+ Ok(next) if !next.0.is_null() => cur = next,+ _ => break,+ }+ }+ }+}+/// Parses a hotkey string such as `"Ctrl+Alt+C"`, `"Ctrl+Alt+Space"` or `"Ctrl+Shift+F9"` into/// `(HOT_KEY_MODIFIERS bits including MOD_NOREPEAT, virtual_key_code)`.pub fn parse_hotkey(spec: &str) -> Option<(u32, u32)> {@@ -367,11 +400,16 @@ pub fn parse_hotkey(spec: &str) -> Option<(u32, u32)> {Some((mods | MOD_NOREPEAT.0, vk))}-/// Updates the Continuity Camera and Command Palette global hotkeys (`photo_spec`, `scan_spec`, and `palette_spec`).-pub fn update_hotkeys(photo_spec: &str, scan_spec: &str, palette_spec: &str) {+/// Updates the Continuity Camera, Command Palette, and Shelf global hotkeys (`photo_spec`, `scan_spec`, `palette_spec`, and `shelf_spec`).+pub fn update_hotkeys(photo_spec: &str, scan_spec: &str, palette_spec: &str, shelf_spec: &str) {{let mut specs = HOTKEY_SPECS.lock().unwrap_or_else(|e| e.into_inner());- *specs = (photo_spec.trim().to_owned(), scan_spec.trim().to_owned(), palette_spec.trim().to_owned());+ *specs = (+ photo_spec.trim().to_owned(),+ scan_spec.trim().to_owned(),+ palette_spec.trim().to_owned(),+ shelf_spec.trim().to_owned(),+ );}let raw = TRAY_HWND.load(Ordering::Acquire);if raw != 0 {@@ -383,13 +421,14 @@ pub fn update_hotkeys(photo_spec: &str, scan_spec: &str, palette_spec: &str) {}unsafe fn apply_hotkeys_on_window(hwnd: HWND) {- let (photo_spec, scan_spec, palette_spec) =+ let (photo_spec, scan_spec, palette_spec, shelf_spec) =HOTKEY_SPECS.lock().unwrap_or_else(|e| e.into_inner()).clone();// SAFETY: Unregistering and registering hotkeys on the thread that owns `hwnd`.unsafe {let _ = UnregisterHotKey(Some(hwnd), HOTKEY_PHOTO_ID);let _ = UnregisterHotKey(Some(hwnd), HOTKEY_SCAN_ID);let _ = UnregisterHotKey(Some(hwnd), HOTKEY_PALETTE_ID);+ let _ = UnregisterHotKey(Some(hwnd), HOTKEY_SHELF_ID);if let Some((mods, vk)) = parse_hotkey(&photo_spec)&& let Err(e) = RegisterHotKey(Some(hwnd), HOTKEY_PHOTO_ID, HOT_KEY_MODIFIERS(mods), vk){@@ -405,6 +444,11 @@ unsafe fn apply_hotkeys_on_window(hwnd: HWND) {{tracing::debug!(hotkey = %palette_spec, error = %e, "could not register Command Palette hotkey");}+ if let Some((mods, vk)) = parse_hotkey(&shelf_spec)+ && let Err(e) = RegisterHotKey(Some(hwnd), HOTKEY_SHELF_ID, HOT_KEY_MODIFIERS(mods), vk)+ {+ tracing::debug!(hotkey = %shelf_spec, error = %e, "could not register Shelf hotkey");+ }}}@@ -489,6 +533,7 @@ impl Drop for Tray {let _ = UnregisterHotKey(Some(self.hwnd), HOTKEY_PHOTO_ID);let _ = UnregisterHotKey(Some(self.hwnd), HOTKEY_SCAN_ID);let _ = UnregisterHotKey(Some(self.hwnd), HOTKEY_PALETTE_ID);+ let _ = UnregisterHotKey(Some(self.hwnd), HOTKEY_SHELF_ID);let _ = KillTimer(Some(self.hwnd), TIMER_TRACK_FG);let _ = Shell_NotifyIconW(NIM_DELETE, &data);let _ = DestroyWindow(self.hwnd);@@ -584,6 +629,7 @@ fn show_menu(hwnd: HWND, x: i32, y: i32) {let to_wide = |s: &str| s.encode_utf16().chain(Some(0)).collect::<Vec<u16>>();let (open, find, quit) = (to_wide(&labels.open), to_wide(&labels.find_phone), to_wide(&labels.quit));let palette = to_wide(&labels.command_palette);+ let shelf = to_wide(&labels.shelf);let take_photo = to_wide(&labels.take_photo);let scan_doc = to_wide(&labels.scan_document);let link = to_wide(&labels.open_link);@@ -598,6 +644,7 @@ fn show_menu(hwnd: HWND, x: i32, y: i32) {let _ = AppendMenuW(menu, MF_SEPARATOR, 0, PCWSTR::null());let _ = AppendMenuW(menu, MF_STRING, CMD_OPEN as usize, PCWSTR(open.as_ptr()));let _ = AppendMenuW(menu, MF_STRING, CMD_COMMAND_PALETTE as usize, PCWSTR(palette.as_ptr()));+ let _ = AppendMenuW(menu, MF_STRING, CMD_SHELF as usize, PCWSTR(shelf.as_ptr()));let _ = AppendMenuW(menu, find_flags, CMD_FIND_PHONE as usize, PCWSTR(find.as_ptr()));let _ = AppendMenuW(menu, find_flags, CMD_OPEN_LINK as usize, PCWSTR(link.as_ptr()));let _ = AppendMenuW(menu, MF_SEPARATOR, 0, PCWSTR::null());@@ -614,6 +661,7 @@ fn show_menu(hwnd: HWND, x: i32, y: i32) {CMD_SCAN_DOCUMENT => emit(TrayEvent::ScanDocument),CMD_OPEN => emit(TrayEvent::Open),CMD_COMMAND_PALETTE => emit(TrayEvent::CommandPalette),+ CMD_SHELF => emit(TrayEvent::Shelf),CMD_FIND_PHONE => emit(TrayEvent::FindPhone),CMD_OPEN_LINK => emit(TrayEvent::OpenLinkOnPhone),CMD_QUIT => emit(TrayEvent::Quit),@@ -655,6 +703,7 @@ unsafe extern "system" fn window_proc(hwnd: HWND, msg: u32, wparam: WPARAM, lparHOTKEY_PHOTO_ID => emit(TrayEvent::TakePhoto),HOTKEY_SCAN_ID => emit(TrayEvent::ScanDocument),HOTKEY_PALETTE_ID => emit(TrayEvent::CommandPalette),+ HOTKEY_SHELF_ID => emit(TrayEvent::Shelf),_ => {}}LRESULT(0)diff --git a/docs/PLAN.md b/docs/PLAN.mdindex 8b20f4a..30b678f 100644--- a/docs/PLAN.md+++ b/docs/PLAN.md@@ -2,7 +2,7 @@> **Nectarlink** connects Android phones and Windows PCs. It's one open-source app that replaces Phone Link, KDE Connect, scrcpy, LocalSend and Intel Unison.> *Bees carry nectar back to the hive. Nectarlink carries everything between your phone and your PC.*-> Status: **planning complete, stack locked (Qt Quick + Rust), name final (Nectarlink), repo initialized locally. No product code yet.** Next steps in §12. Last updated 2026-10-04.+> Status: **in active development (Qt Quick + Rust on Windows 11, Kotlin + Jetpack Compose on Android, shared Rust core).** Phase 1 and most of Phases 2–3 work end to end; see §3 for per-feature status. Last updated 2026-10-09.---@@ -106,21 +106,21 @@ Power: 🟢 Basic · 🔵 Assist · 🟣 Elevated (see §4.6).### 3.1 Connection & setup| Feature | Tier ||---|---|-| Pair by **QR code** (PC shows QR → phone scans), by **tap a nearby device + 6-digit code match**, or **plug in USB** (auto-pair) | P0 |-| Auto-reconnect everywhere: PC wake from sleep, Wi-Fi changes, phone reboot, app updates | P0 |-| Works over **Wi-Fi, Ethernet-to-Wi-Fi, USB**, and **away from home** (hole punching + relay, opt-in, self-hostable) | P0 (LAN/USB), P1 (away) |-| **Connection Doctor**: detects firewall, Public network profile, AP isolation, VPN, battery optimization, OEM killers. One-click fixes plus per-OEM guides | P0 |-| Companion Device Manager association + PC BLE beacon, so the phone app is woken when the PC is nearby | P1 |+| Pair by **QR code** (PC shows QR → phone scans), by **tap a nearby device + 6-digit code match**, or **plug in USB** (auto-pair) — partial (QR code and nearby 6-digit code work; USB auto-pair not started) | P0 |+| Auto-reconnect everywhere: PC wake from sleep, Wi-Fi changes, phone reboot, app updates ✅ | P0 |+| Works over **Wi-Fi, Ethernet-to-Wi-Fi, USB**, and **away from home** (hole punching + relay, opt-in, self-hostable) — partial (Wi-Fi and Ethernet-to-Wi-Fi work; USB transport and away-from-home UI/self-hosted relay config not started) | P0 (LAN/USB), P1 (away) |+| **Connection Doctor**: detects firewall, Public network profile, AP isolation, VPN, battery optimization, OEM killers. One-click fixes plus per-OEM guides — partial (firewall, Public network profile, VPN, and Android battery optimization / local network checks with one-click fixes work; AP isolation probe and per-OEM guides missing) | P0 |+| Companion Device Manager association + PC BLE beacon, so the phone app is woken when the PC is nearby — not started | P1 || Bluetooth fallback link for low-bandwidth features (notifications, SMS, calls) when there's no shared network | P2 |-| Multiple phones per PC, multiple PCs per phone, per-device feature permissions | P0 (model), P1 (UI) |+| Multiple phones per PC, multiple PCs per phone, per-device feature permissions ✅ | P0 (model), P1 (UI) |### 3.2 Notifications| Feature | Tier ||---|---|-| Mirror notifications as native Windows toasts with **app icon, big images, actions, inline reply** | P0 🟢 |-| Dismiss sync (clear on one side → cleared on the other), per-app allow/block, quiet hours | P0 🟢 |-| Notification feed in the app: history, search, grouping by app/conversation | P0 🟢 |-| **Sensitive notifications / OTPs** | P0 🟣 |+| Mirror notifications as native Windows toasts with **app icon, big images, actions, inline reply** ✅ | P0 🟢 |+| Dismiss sync (clear on one side → cleared on the other), per-app allow/block, quiet hours ✅ | P0 🟢 |+| Notification feed in the app: history, search, grouping by app/conversation — partial (live feed and searchable 24-hour dismissed history work; collapsible grouping by app in the feed is missing, while conversation notifications group in Messages) | P0 🟢 |+| **Sensitive notifications / OTPs** — not started (Android 15+ `RECEIVE_SENSITIVE_NOTIFICATIONS` appop grant in Elevated mode not wired) | P0 🟣 || **Smart OTP**: detect codes and offer a "Copy code" toast; auto-copy optional ✅ | P1 || **Live Updates** (Android 16 progress notifications: rides, deliveries, timers) shown live on PC ✅ | P1 || DND sync: quiet PC notifications when phone is in DND, plus toggle phone DND from PC (Windows has no public API to read or set Focus/DND) ✅ | P1 🟢/🟣 |@@ -137,10 +137,10 @@ Power: 🟢 Basic · 🔵 Assist · 🟣 Elevated (see §4.6).### 3.4 Calls| Feature | Tier ||---|---|-| Incoming call alert on PC with caller photo; answer / decline / silence (audio stays on phone) | P0 🟢 |-| Call in progress on PC: timer, hang up, volume; with Elevated (Android 12+), mute, speaker, hold and keypad through a calling-companion `InCallService` | P0 🟢 |-| Call log, dialer, call from contacts | P1 🟢 |-| **Call audio on PC via Bluetooth HFP** (PC mic/speakers) | P1 (after spike) |+| Incoming call alert on PC with caller photo; answer / decline / silence (audio stays on phone) ✅ | P0 🟢 |+| Call in progress on PC: timer, hang up, volume; with Elevated (Android 12+), mute, speaker, hold and keypad through a calling-companion `InCallService` ✅ | P0 🟢 |+| Call log, dialer, call from contacts ✅ | P1 🟢 |+| **Call audio on PC via Bluetooth HFP** (PC mic/speakers) — not started | P1 (after spike) || Auto-pause PC media during calls ✅ | P1 |Not planned: **recording calls.** Android keeps call audio (`VOICE_CALL`@@ -150,51 +150,51 @@ current Android. Talking through the PC comes with the HFP item above.### 3.5 Clipboard| Feature | Tier ||---|---|-| Text + images + rich text, bidirectional, auto | P0 (PC→phone 🟢, phone→PC auto 🟣) |-| Fallbacks without Elevated: "Send clipboard" QS tile, share target, notification button | P0 🟢 |+| Text + images + rich text, bidirectional, auto — partial (plain text and images work with PC→phone auto and manual phone→PC; rich text HTML/RTF and Elevated background phone→PC auto sync are missing) | P0 (PC→phone 🟢, phone→PC auto 🟣) |+| Fallbacks without Elevated: "Send clipboard" QS tile, share target, notification button ✅ | P0 🟢 || Clipboard history (both devices, local, encrypted), pin items ✅ | P1 |-| **Smart clipboard (context chips)**: copy an address → "Open in Maps"; a phone number → "Call"; a tracking code → "Track"; a link → "Open on phone"; an OTP → "Paste on PC" | P1 |-| Respect password managers' "exclude from clipboard history" flags on both sides; never sync sensitive clips | P0 |+| **Smart clipboard (context chips)**: copy an address → "Open in Maps"; a phone number → "Call"; a tracking code → "Track"; a link → "Open on phone"; an email → "Email" (OTPs have "Copy code" on notifications and texts) ✅ | P1 |+| Respect password managers' "exclude from clipboard history" flags on both sides; never sync sensitive clips ✅ | P0 || Copy files on PC → paste on phone (and the reverse) | P2 |### 3.6 Files & photos| Feature | Tier ||---|---|-| Send files/folders both ways: drag-drop, share sheet, Explorer **"Send to phone"** context menu, Windows share sheet | P0 |-| Fast, resumable, multi-stream transfers with progress, pause/resume, and integrity hashing | P0 |-| **Flick to send**: flick a photo/file upward on the phone and it lands on the PC. Drag a file to the screen edge on the PC and it flies to the phone. Physics-based animation on both ends | P1 |+| Send files/folders both ways: drag-drop, share sheet, Explorer **"Send to phone"** context menu, Windows share sheet — partial (drag-drop, file/folder pickers, Android share sheet, and Explorer "Send to" context menu work; Windows share sheet target is missing) | P0 |+| Fast, resumable, multi-stream transfers with progress, pause/resume, and integrity hashing — partial (pipelined transfers with live progress, cancel, and automatic byte-offset resume after a dropped connection work; manual pause/resume, multi-stream striping, and integrity hashing are missing) | P0 |+| **Flick to send**: flick a photo/file upward on the phone and it lands on the PC. Drag a file to the screen edge on the PC and it flies to the phone. Physics-based animation on both ends — not started | P1 || **LocalSend protocol interop**: send to and receive from any LocalSend device (iOS, Mac, Linux). We implement its open protocol in Rust; we don't reuse its (Dart) code ✅ | P1 || **Coexistence**: runs side by side with KDE Connect (ports 1714–1764) and LocalSend (53317) on the same PC without conflicts. If LocalSend's port is taken, Nectarlink still sends but leaves receiving to the LocalSend app ✅ | P0 || **Phone storage in Explorer** (Cloud Files API: placeholders, on-demand download, native sync icons) ✅ | P1 |-| **Photos**: gallery with thumbnails, recent screenshots/photos pop up on PC, drag out to the desktop | P0 (recent), P1 (gallery) |+| **Photos**: gallery with thumbnails, recent screenshots/photos pop up on PC, drag out to the desktop — partial (recent photo/screenshot popups and the full gallery with albums, thumbnails, viewer, copy, and save work; dragging a photo tile directly out to the desktop is missing) | P0 (recent), P1 (gallery) || Folder sync (Syncthing-style two-way folders, e.g. Camera → PC) | P2 |### 3.7 Screen mirroring & phone apps on PC| Feature | Tier ||---|---|-| Mirror and control the full phone screen. **Hardware decode**, ≤50 ms on LAN, 1080p60+, H.264/H.265/AV1 | P0 (Standard 🟢 view / 🔵 control, Elevated 🟣) |-| **Built-in**. Nothing to download and no scrcpy path to configure | P0 |-| **Audio forwarding** (phone audio plays on PC) | P1 🟣 (or 🟢 via playback capture) |-| **App windows**: launch a phone app as its own resizable PC window with taskbar icon (virtual display, flex resize). App list and pinning | P1 🟣 |-| Keyboard (physical layout via UHID), mouse, scroll, gamepad, IME text, copy/paste inside the mirror, drag files in to send | P1 |-| Screen off while mirroring, keep awake, record, screenshot | P1 |-| Recent apps / notifications open directly into an app window | P1 |+| Mirror and control the full phone screen. **Hardware decode**, ≤50 ms on LAN, 1080p60+, H.264/H.265/AV1 — partial (1080p60 H.264 hardware encode/decode, Standard 🟢 view, Assist 🔵 control, and Elevated 🟣 input work; H.265/AV1 codecs and prompt-free Elevated full-screen capture without MediaProjection are missing) | P0 (Standard 🟢 view / 🔵 control, Elevated 🟣) |+| **Built-in**. Nothing to download and no scrcpy path to configure ✅ | P0 |+| **Audio forwarding** (phone audio plays on PC) — partial (🟢 playback capture on Android 10+ works with mute on the mirror window; 🟣 Elevated capture of apps that block playback capture is missing) | P1 🟣 (or 🟢 via playback capture) |+| **App windows**: launch a phone app as its own resizable PC window with taskbar icon (virtual display, flex resize). App list and pinning ✅ | P1 🟣 |+| Keyboard (physical layout via UHID), mouse, scroll, gamepad, IME text, copy/paste inside the mirror, drag files in to send — partial (mouse, scroll, navigation/edit keys, text input, and Ctrl+V paste work; UHID physical layout, gamepad, Ctrl+C inside the mirror, and drag-files-in-to-send are missing) | P1 |+| Screen off while mirroring, keep awake, record, screenshot ✅ | P1 |+| Recent apps / notifications open directly into an app window ✅ | P1 |### 3.8 Media & audio| Feature | Tier ||---|---|-| Control phone media from PC. Phone media appears **in Windows' own media flyout** with artwork | P0 🟢 |-| Control PC media from phone (media notification with artwork, seek, volume) | P0 🟢 |-| PC volume and output device switch from phone | P1 |-| **Voice Recorder → PC**: record with the phone's (better) mic, hit send, and the file lands on the PC in your chosen format (Opus/M4A/MP3/WAV/FLAC) and folder. Optional: record *straight into* the PC (live stream, appears when you stop), noise suppression, markers ✅ | P1 🟢 |+| Control phone media from PC. Phone media appears **in Windows' own media flyout** with artwork ✅ | P0 🟢 |+| Control PC media from phone (media notification with artwork, seek, volume) ✅ | P0 🟢 |+| PC volume and active output device indicator from phone ✅ (Windows has no public API to switch the default audio output device) | P1 |+| **Voice Recorder → PC**: record with the phone's (better) mic, hit send, and the file lands on the PC in your chosen format (M4A/MP3/WAV/FLAC) and folder, with timestamped markers ✅ (optional live stream while recording, Opus, and noise suppression not started) | P1 🟢 || Phone as speaker / headphones for PC audio | P2 || Phone as live microphone for PC apps | P2 (needs a virtual audio driver, evaluate) |### 3.9 Camera| Feature | Tier ||---|---|-| **Phone as webcam** (Windows 11 virtual camera, shows up in Teams/Zoom/OBS/Camera app). Front/back, zoom, torch, HDR, 1080p/4K ✅ | P1 🟢 (Camera2) |-| **Continuity Camera**: right-click in any PC app → "Take photo / Scan document with phone" → the phone opens the camera (with document edge detection) → the result is pasted at the cursor | P1 🟢 |+| **Phone as webcam** (Windows 11 virtual camera, shows up in Teams/Zoom/OBS/Camera app). Front/back, zoom, torch, mirror, 720p/1080p ✅ (4K virtual-camera output and HDR not started) | P1 🟢 (Camera2) |+| **Continuity Camera**: from the PC (Home, tray, Command Palette, or global hotkey) → "Take photo / Scan document with phone" → the phone opens the camera (with document edge detection and perspective correction) → the result is placed on the clipboard and pasted at the cursor ✅ | P1 🟢 |### 3.10 Remote input & control| Feature | Tier |@@ -202,11 +202,11 @@ current Android. Talking through the PC comes with the HFP item above.| 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 🟣 |-| **Deck**: the phone becomes a Stream-Deck-style macro pad for the PC with live tiles: mic mute, media, app launchers, scripts, OBS scenes, window switching, multiple pages, haptic feedback ✅ | P1 🟢 |+| Type on the phone with the PC keyboard (without mirroring) ✅ | P1 🟣 |+| **Deck**: the phone becomes a Stream-Deck-style macro pad for the PC with live tiles: mic mute, speaker volume/mute, media, app launchers, shortcuts, scripts/commands, window switching, multiple pages, haptic feedback ✅ (dedicated OBS WebSocket tile not started) | P1 🟢 || **Flow**: move the PC mouse off the screen edge onto the phone/tablet and back, with clipboard following | P2 🟣 || Phone toggles from PC: Wi-Fi, BT, DND, ringer, flashlight, volume, brightness ✅ (the hotspot has no shell command to switch it; see Instant Hotspot) | P1 (partly 🟣) |-| PC actions from phone: lock, sleep, shutdown, mute, custom commands/scripts ✅ | P0 (lock/sleep), P1 (custom, off by default) |+| PC actions from phone: lock, sleep, mute, custom commands/scripts ✅ (shutdown intentionally omitted) | P0 (lock/sleep), P1 (custom, off by default) || Wake-on-LAN ✅ | P1 || **Unlock PC with phone fingerprint**: the PC lock screen offers "Unlock with phone" → the phone shows a biometric prompt → a signed challenge unlocks Windows. Built as a Windows credential provider. Keys live in Android Keystore (StrongBox where available) and are bound to biometrics. Works only when paired and nearby (BLE proximity + LAN). Rate-limited, revocable, and **external security review before release** | P2 (dedicated workstream) |@@ -214,27 +214,27 @@ current Android. Talking through the PC comes with the HFP item above.| Feature | Tier ||---|---|| **Nectar Island** (optional extra, off by default): a small, animated pill at the top of the PC screen showing live phone activity (call, timer, music, transfer, Live Update, OTP, voice recording). Expands on hover. A nice touch, not a pillar | P2 |-| **Shelf**: slide-out edge panel with the latest photo, screenshot, clipboard and recent files. Drag anything in to send | P1 |-| **Command Palette** (global hotkey): "send clipboard", "find my phone", "text Mom", "open last photo", "mirror Spotify", "record voice" | P1 |+| **Shelf**: slide-out edge panel with the latest photo, screenshot, clipboard and recent files. Drag anything in to send ✅ | P1 |+| **Command Palette** (global hotkey): "send clipboard", "find my phone", "text Mom", "open last photo", "mirror Spotify", "record voice" ✅ | P1 || **Material You sync**: the PC app takes its accent and theme from the phone's wallpaper colors, so both apps look like one ✅ | P1 |-| **Handoff**: send a link, map location, document or YouTube timestamp to open on the other device | P0 (links), P1 (rich) |+| **Handoff**: send a link, map location, document or YouTube timestamp to open on the other device ✅ | P0 (links), P1 (rich) || **"Ping me when it's done"**: `nectarlink notify-when <pid \| -- command...>` watches a running process or command on the PC, shows a live chronometer notification on the phone while it runs, and alerts the phone when it finishes or fails ✅ | P1 || **Timeline**: one searchable history of everything that moved between devices (files, clips, links, photos, recordings), with "send again" ✅ | P1 || **Your PC in your pocket**: from anywhere (Away mode), browse and grab PC files, see what the PC is doing (Ping-me tasks, downloads), wake it (relayed Wake-on-LAN through another Nectarlink device left at home), and later view/control the PC screen (reverse mirroring) | P2 (files/status in P1 if Away mode lands early) || **Proximity lock**: lock the PC when the phone walks away (BLE RSSI) | P2 || **Automations**: triggers (connected, battery low, call started) → actions | P2 |-| Find my phone (ring even on silent), battery & signal in tray, low-battery alerts, measured phone screen preview & Home summary ✅ | P0 |+| Find my phone (ring even on silent), battery & signal in tray, low-battery alerts, measured phone screen preview & Home summary — partial (Find my phone/PC, battery in tray, low-battery and full-charge alerts, and measured phone screen preview with Home summary work; phone signal strength is not reported) | P0 |### 3.12 Platform & ecosystem| Feature | Tier ||---|---|-| Tray app, start on login, jump list, global hotkeys, Windows Widgets board widget | P0/P1 |-| Android Quick Settings tiles, home-screen widgets (Glance), share target, Direct Share to PC | P0/P1 |-| **CLI** (`nectarlink send file.pdf`, `nectarlink clip`, `nectarlink notify`, `nectarlink notify-when`) and local authenticated API for scripts and PowerToys Command Palette ✅ | P1 |+| Tray app, start on login, jump list, global hotkeys, Windows Widgets board widget — partial (tray app, start on login, and global hotkeys work; taskbar jump list and Windows Widgets board widget not started) | P0/P1 |+| Android Quick Settings tiles, home-screen widgets (Glance), share target, Direct Share to PC ✅ | P0/P1 |+| **CLI** (`nectarlink send file.pdf`, `nectarlink clip`, `nectarlink notify`, `nectarlink notify-when`) and local authenticated API for scripts and PowerToys Command Palette — partial (full `nectarlink` CLI and single-instance IPC forwarding work; general local API server and PowerToys extension not started) | P1 || Tablet as second screen (IddCx virtual monitor) | P2 || macOS desktop build | P2 (future scope) || Plugin/extension API over the open protocol | P2 |-| Full i18n, accessibility (screen readers, keyboard nav, contrast), reduced motion | P1 |+| Full i18n, accessibility (screen readers, keyboard nav, contrast), reduced motion ✅ | P1 |### 3.13 Rejected for now (parked, can be revived later)| Idea | Why parked |@@ -313,7 +313,7 @@ nectarlink/- **Encryption:** QUIC + TLS 1.3 (raw public keys), always. Relays only forward ciphertext.- **Per-device permissions:** each paired device has feature toggles. Dangerous ones (run commands, remote input into PC, file browse, PC unlock) are **off by default**.- **Local API/CLI:** a named pipe with a per-user token. No open localhost TCP port.-- **At-rest & data retention ✅:** clipboard history is sealed on disk with `KeyProtector` (DPAPI on Windows, Keystore AES-GCM on Android), capped at 50 items, and auto-purges unpinned clips older than 7 days (pinned clips stay; OTPs are never stored). Timeline defaults to 90 days (configurable: 30 / 90 / 365 days or Forever) and 5,000 entries. Notification history on PC is capped at 200 items and 24 hours. `MessagingStyle` conversation cache retains up to 200 threads per peer (100 messages/thread) for 30 days. Both apps expose per-category clear buttons and a single **"Clear everything"** action in *Settings → Privacy & Data* that wipes all local history and caches while keeping device identity, paired devices, and feature toggles intact.+- **At-rest & data retention ✅:** clipboard history is sealed on disk with `KeyProtector` (DPAPI on Windows, Keystore AES-GCM on Android), capped at 50 items, and auto-purges unpinned clips older than 7 days (pinned clips stay; OTPs are never stored). Timeline defaults to 90 days (configurable: 30 / 90 / 365 days or Forever) and 5,000 entries. Notification history on PC is capped at 300 dismissed items and 24 hours. `MessagingStyle` conversation cache retains up to 200 threads per peer (200 messages/thread) for 90 days. Photo thumbnail cache on PC keeps up to 500 thumbnails for 30 days. Both apps expose per-category clear buttons and a single **"Clear everything"** action in *Settings → Data & storage* that wipes all local history and caches while keeping device identity, paired devices, and feature toggles intact.- Security audit before 1.0. Fuzz the protocol decoder and pairing handshake. The credential provider gets its own threat model and review.### 4.4 Connectivity: "it just works"@@ -731,7 +731,7 @@ Each phase ends with a usable, releasable product. Phase sizes are relative; act- Battery soak tests on testers' phones.- An opt-in diagnostics bundle, since there's no telemetry.10. **Island etiquette.** Auto-hide during fullscreen games, videos and presentations and when Windows is in Do Not Disturb. Handle multiple monitors.-11. **Data retention defaults ✅:** Timeline (90 days default — configurable 30 / 90 / 365 days or Forever — and 5,000 entries cap, auto-purged + Clear all ✅), clipboard history (50 entries, 7-day auto-purge for unpinned items while pinned stay, encrypted at rest with `KeyProtector`, OTPs excluded + Clear history ✅), notification history (24 hours, 200 items cap + Clear notifications ✅), `MessagingStyle` message cache (30 days, 200 threads/peer, 100 messages/thread + Clear message cache ✅), received file transfer records (Clear transfer history without deleting files on disk ✅), and one **"Clear everything"** button (`clear_all_local_data`) in *Settings → Privacy & Data* on both PC and Android that wipes all local history and caches while preserving device identity, paired devices, and per-device feature toggles ✅.+11. **Data retention defaults ✅:** Timeline (90 days default — configurable 30 / 90 / 365 days or Forever — and 5,000 entries cap, auto-purged + Clear ✅), clipboard history (50 entries, 7-day auto-purge for unpinned items while pinned stay, encrypted at rest with `KeyProtector`, OTPs excluded + Clear ✅), notification history (24 hours, 300 dismissed items cap + Clear ✅), `MessagingStyle` message cache (90 days, 200 threads/peer, 200 messages/thread + Clear ✅), photo thumbnail cache (30 days, 500 thumbnails cap + Clear ✅), received file transfer records (Clear transfer history without deleting files on disk ✅), and one **"Clear everything"** button (`clear_all_local_data`) in *Settings → Data & storage* on both PC and Android that wipes all local history and caches while preserving device identity, paired devices, and per-device feature toggles ✅.12. **Accessibility and translations from day one.** All strings translatable (`qsTr`, Android resources), RTL layouts, screen-reader labels, keyboard focus order. Retrofitting is expensive.13. **Asset licenses.** The display font under OFL, an icon set under a permissive license (e.g. Material Symbols, Apache-2.0). No Microsoft or Google logos; competitor names only in plain comparison wording.14. **Realistic pacing.** Claude writes most of the code, but every phase needs maintainer review and tester feedback. Estimate phase durations after Phase 0 from real velocity, not before.diff --git a/docs/design/tokens.json b/docs/design/tokens.jsonindex b5b9d9a..735171c 100644--- a/docs/design/tokens.json+++ b/docs/design/tokens.json@@ -160,7 +160,7 @@"$note": "No green. Success / done / connected states use the theme's own color roles: primary (dot, 'On' chips) and primaryContainer/onPrimaryContainer (completed checks). Only warning and error have dedicated colors.","light": {"success": "{primary}",- "warning": "#9A6700",+ "warning": "#7D5200","error": "#BA1A1A","onError": "#FFFFFF"},@@ -213,7 +213,7 @@"outline": "#4A4743","outlineVariant": "#D5CFC2","success": "#1A1918",- "warning": "#8A6A1F",+ "warning": "#705516","error": "#9E2B25","onError": "#F5F2EB","buttonShadow": "3px 3px 0 #D5CFC2",diff --git a/docs/protocol/actions.md b/docs/protocol/actions.mdindex 5e621d0..51f5a98 100644--- a/docs/protocol/actions.md+++ b/docs/protocol/actions.md@@ -48,15 +48,22 @@ they're too easy to set off by accident, and lose unsaved work.### 2.2 `link.open`-Asks the receiver to open `url`, which **MUST** be an `http` or `https`-link of at most 4,096 bytes with no whitespace or control characters.+Asks the receiver to open `url`, which **MUST** be an `http`, `https` or+`geo:` link of at most 4,096 bytes with no whitespace or control characters.Receivers **MUST** check this themselves and answer `BAD_MESSAGE` toanything else; no other kind of link is ever opened.-A PC opens the link in its default browser. A phone shows it in a-notification the user taps to open it, since Android doesn't let apps in-the background open screens. `INTERNAL` means it couldn't be opened or-shown.+Map handoff uses either `geo:<lat>,<lon>?q=...` URIs or web map URLs (Google+Maps, Apple Maps, Bing Maps, OpenStreetMap). Video handoff preserves or+attaches the playback timestamp in the URL (`?t=<seconds>` / `&t=<seconds>s` on+YouTube, `#t=<seconds>s` on Vimeo, `?t=<seconds>` on Twitch).++A PC opens `http`/`https` links in its default browser and converts `geo:`+URIs to an HTTPS map search URL. When the Android app is in the foreground, it+opens the link or map intent immediately (`ACTION_VIEW`, falling back to an+HTTPS map URL if no Maps app handles `geo:`); when in the background, it posts+a high-priority notification (`Open`, `Open in Maps`, or `Continue watching`)+the user taps to open it. `INTERNAL` means it couldn't be opened or shown.### 2.3 `pc.wake_info` (Wake-on-LAN)diff --git a/docs/protocol/files.md b/docs/protocol/files.mdindex 773abe2..c166219 100644--- a/docs/protocol/files.md+++ b/docs/protocol/files.md@@ -27,6 +27,7 @@ t = "files.offer" b = {size: uint,? folder: text, // Only for files in a sent folder (see below)} ], // 1–5,000 files, in order+ ? open_on_arrival: bool, // True when handing off a single document to open on arrival}```@@ -44,6 +45,13 @@ Empty folders aren't sent.single-file offer (without `folder`) and may include `"markers"`: up to 256entries `{ at_ms: uint, label?: text }`.+**Handoff documents.** When a sender hands off a single safe document (`pdf`,+`txt`, `md`, `rtf`, `csv`, `json`, `html`, `epub`, or Office/OpenDocument files)+to open immediately on the other device, `files.offer` sets+`"open_on_arrival": true` on a single-file offer (without `folder` or+`recording`). Receivers **MUST** check the received file's extension against a+safe document allowlist and never automatically execute binaries or scripts.+Receivers **MUST** reject an offer that breaks these rules with`BAD_MESSAGE`, and still pick their own safe names for writing (see §4). Thewhole offer is one frame (v0 §3), which limits how many files with longdiff --git a/docs/protocol/mirror.md b/docs/protocol/mirror.mdindex 6eee04a..eb298ba 100644--- a/docs/protocol/mirror.md+++ b/docs/protocol/mirror.md@@ -30,8 +30,10 @@ On the control stream.```t = "mirror.start" id = n b = { max_size: uint, fps: uint, bitrate: uint, ? audio: bool,- ? session: uint, ? app: text }+ ? session: uint, ? app: text,+ ? stay_awake: bool, ? screen_off: bool }t = "mirror.stop" id = n b = { ? session: uint }+t = "mirror.power" b = { ? stay_awake: bool, ? screen_off: bool }t = "mirror.keyframe" b = { ? session: uint }t = "mirror.resize" b = { session: uint, width: uint, height: uint }t = "mirror.apps" id = n@@ -45,13 +47,18 @@ means 0, so PCs and phones that predate sessions work as before.- `mirror.start` (PC → phone): show me your screen, its longer side at most`max_size` pixels, at most `fps` frames a second, aiming for `bitrate`- bits a second, and with `audio` (default false), its sound too. The+ bits a second, and with `audio` (default false), its sound too. For the+ phone's screen (`session` 0), `stay_awake` keeps the phone's screen from+ timing out while mirrored, and `screen_off` (Elevated) turns the phone's+ physical display panel off while the mirror keeps running. Thephone answers `ok` once it has asked its user; video follows only if theuser agrees, and sound only if the phone can (it may share the screenwithout it). Errors: `DENIED` (mirroring is off for the PC),`UNSUPPORTED` (no `mirror.capture`).- `mirror.stop` (either way): stop. The PC stops reading the video stream;- the phone stops sharing and finishes it.+ the phone stops sharing, restores normal display power, and finishes it.+- `mirror.power` (PC → phone): update `stay_awake` and `screen_off` while+ mirroring the phone's screen (`session` 0). Not answered.- `mirror.keyframe` (PC → phone): the decoder lost its place; send akeyframe next. Not answered.- `mirror.resize` (PC → phone): resize an app window's display (`session != 0`)@@ -104,13 +111,21 @@ bottom), so they hold at any size and rotation.- `scroll`: the mouse wheel at a point, in notches (positive: down orright); the phone swipes the other way.- `key`: `back`, `home`, `recents`, `notifications`, `enter`, `backspace`,- `delete`, `left`, `right`, `up`, `down` or `tab`. Others are dropped.-- `text`: typed text (at most 4 KiB), into the focused text field. At- Elevated it's typed as key events, so only what the keyboard map can type- (most Latin text) arrives.+ `delete`, `left`, `right`, `up`, `down`, `tab`, `keyboard_on` or+ `keyboard_off`. Others are dropped. `keyboard_on` and `keyboard_off` mark+ when a PC starts or stops typing on the phone (`session` 0) without+ opening a video stream; the phone shows a banner with a button to stop it+ (which sends `mirror.stop` for `session` 0 back to the PC).+- `text`: typed text (at most 4 KiB), into the focused text field. When the+ accessibility service (`InputService`) is running, non-ASCII / Unicode+ text is inserted directly into the focused editable node; at Elevated+ without the accessibility service, ASCII/Latin text is typed as key events+ and non-ASCII text is pasted via the phone's clipboard (`KEYCODE_PASTE`).The Windows app maps the left button to a finger, right-click to Back,-middle-click to Home and Ctrl+V to typing the PC's clipboard.+middle-click to Home and Ctrl+V to typing the PC's clipboard, and also+offers a **Type on phone** bar on Home (and in the Command Palette) to type+on the phone with the PC keyboard without mirroring its screen.## 5. Sounddiff --git a/tools/xtask/src/main.rs b/tools/xtask/src/main.rsindex cf03dfe..e446055 100644--- a/tools/xtask/src/main.rs+++ b/tools/xtask/src/main.rs@@ -100,10 +100,13 @@ const ROLES: &[&str] = &[/// Catches mistakes in the token file before they reach a theme.fn validate(tokens: &Value) -> Result<()> {let themes = tokens.get("themes").context("missing \"themes\"")?;+ let status = themes.pointer("/bloom/status").context("missing bloom status")?;let seeds = themes.pointer("/bloom/seeds").and_then(Value::as_object).context("missing bloom seeds")?;for (seed, def) in seeds {for mode in ["light", "dark"] {- check_palette(def.get(mode), &format!("bloom.{seed}.{mode}"))?;+ let name = format!("bloom.{seed}.{mode}");+ check_palette(def.get(mode), &name)?;+ check_contrast(def.get(mode), status.get(mode), &name)?;}}let variants = themes@@ -111,7 +114,9 @@ fn validate(tokens: &Value) -> Result<()> {.and_then(Value::as_object).context("missing graphite variants")?;for (variant, palette) in variants {- check_palette(Some(palette), &format!("graphite.{variant}"))?;+ let name = format!("graphite.{variant}");+ check_palette(Some(palette), &name)?;+ check_contrast(Some(palette), Some(palette), &name)?;}Ok(())}@@ -128,6 +133,83 @@ fn check_palette(palette: Option<&Value>, name: &str) -> Result<()> {Ok(())}+fn parse_rgb(hex: &str) -> Result<(u8, u8, u8)> {+ if !is_hex_color(hex) {+ bail!("{hex:?} is not a #RRGGBB color");+ }+ let r = u8::from_str_radix(&hex[1..3], 16)?;+ let g = u8::from_str_radix(&hex[3..5], 16)?;+ let b = u8::from_str_radix(&hex[5..7], 16)?;+ Ok((r, g, b))+}++fn relative_luminance((r, g, b): (u8, u8, u8)) -> f64 {+ let chan = |c: u8| {+ let s = f64::from(c) / 255.0;+ if s <= 0.03928 { s / 12.92 } else { ((s + 0.055) / 1.055).powf(2.4) }+ };+ 0.2126 * chan(r) + 0.7152 * chan(g) + 0.0722 * chan(b)+}++fn contrast_ratio(fg: &str, bg: &str) -> Result<f64> {+ let l1 = relative_luminance(parse_rgb(fg)?);+ let l2 = relative_luminance(parse_rgb(bg)?);+ let (bright, dark) = if l1 >= l2 { (l1, l2) } else { (l2, l1) };+ Ok((bright + 0.05) / (dark + 0.05))+}++/// Enforces WCAG 2.1 AA (>= 4.5:1) contrast for all text and status pairs.+fn check_contrast(palette: Option<&Value>, status: Option<&Value>, name: &str) -> Result<()> {+ let p = palette.and_then(Value::as_object).with_context(|| format!("{name}: missing palette"))?;+ let s = status.and_then(Value::as_object).with_context(|| format!("{name}: missing status"))?;+ let get_p = |k: &str| p.get(k).and_then(Value::as_str).with_context(|| format!("{name}: missing {k}"));+ let get_s = |k: &str| s.get(k).and_then(Value::as_str).with_context(|| format!("{name}: missing {k}"));++ let surfaces = [+ "surface",+ "surfaceContainerLow",+ "surfaceContainer",+ "surfaceContainerHigh",+ "surfaceContainerHighest",+ ];+ for bg_key in surfaces {+ let bg = get_p(bg_key)?;+ for fg_key in ["onSurface", "onSurfaceVariant", "primary"] {+ let fg = get_p(fg_key)?;+ let ratio = contrast_ratio(fg, bg)?;+ if ratio < 4.5 {+ bail!("{name}: {fg_key} ({fg}) on {bg_key} ({bg}) has contrast {ratio:.2}:1 (< 4.5:1)");+ }+ }+ for st_key in ["warning", "error"] {+ let fg = get_s(st_key)?;+ let ratio = contrast_ratio(fg, bg)?;+ if ratio < 4.5 {+ bail!("{name}: {st_key} ({fg}) on {bg_key} ({bg}) has contrast {ratio:.2}:1 (< 4.5:1)");+ }+ }+ }+ for (fg_key, bg_key) in [+ ("onPrimary", "primary"),+ ("onPrimaryContainer", "primaryContainer"),+ ("onSecondaryContainer", "secondaryContainer"),+ ] {+ let fg = get_p(fg_key)?;+ let bg = get_p(bg_key)?;+ let ratio = contrast_ratio(fg, bg)?;+ if ratio < 4.5 {+ bail!("{name}: {fg_key} ({fg}) on {bg_key} ({bg}) has contrast {ratio:.2}:1 (< 4.5:1)");+ }+ }+ let on_err = get_s("onError")?;+ let err = get_s("error")?;+ let err_ratio = contrast_ratio(on_err, err)?;+ if err_ratio < 4.5 {+ bail!("{name}: onError ({on_err}) on error ({err}) has contrast {err_ratio:.2}:1 (< 4.5:1)");+ }+ Ok(())+}+fn is_hex_color(s: &str) -> bool {s.len() == 7 && s.starts_with('#') && s[1..].bytes().all(|b| b.is_ascii_hexdigit())}@@ -279,4 +361,13 @@ mod tests {let v: Value = serde_json::json!({"$note": 1, "a": {"$x": 2, "b": [ {"$y": 3, "c": 4} ]}});assert_eq!(strip_docs(&v), serde_json::json!({"a": {"b": [{"c": 4}]}}));}++ #[test]+ fn rejects_low_contrast_palette() {+ let source = fs::read_to_string(repo_root().join(TOKENS)).unwrap();+ let mut tokens: Value = serde_json::from_str(&source).unwrap();+ tokens.pointer_mut("/themes/bloom/status/light").unwrap()["warning"] = "#9A6700".into();+ let err = validate(&tokens).unwrap_err().to_string();+ assert!(err.contains("warning"), "{err}");+ }}