Your Android phone and your Windows PC, working as one. Local-first, end-to-end encrypted, no account.
Polish: calmer Home on both apps, a quieter Deck, upright webcam
Bee8f067922c9e7
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 47c6983..a260f16 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@@ -32,6 +32,8 @@ import androidx.compose.foundation.pager.rememberPagerStateimport androidx.compose.foundation.rememberScrollStateimport androidx.compose.foundation.shape.CircleShapeimport androidx.compose.material3.FilterChip+import androidx.compose.material3.Icon+import androidx.compose.material3.IconButtonimport androidx.compose.material3.MaterialThemeimport androidx.compose.material3.OutlinedButtonimport androidx.compose.material3.Surface@@ -58,11 +60,11 @@ import androidx.compose.ui.graphics.StrokeJoinimport androidx.compose.ui.graphics.drawscope.DrawScopeimport androidx.compose.ui.graphics.drawscope.Strokeimport androidx.compose.ui.graphics.graphicsLayer-import androidx.compose.ui.graphics.luminanceimport androidx.compose.ui.input.pointer.pointerInputimport androidx.compose.ui.platform.LocalConfigurationimport androidx.compose.ui.platform.LocalContextimport androidx.compose.ui.platform.LocalView+import androidx.compose.ui.res.painterResourceimport androidx.compose.ui.res.stringResourceimport androidx.compose.ui.semantics.Roleimport androidx.compose.ui.semantics.contentDescription@@ -96,7 +98,6 @@ fun DeckScreen(val context = LocalContext.currentval configuration = LocalConfiguration.currentval isLandscape = configuration.orientation == Configuration.ORIENTATION_LANDSCAPE- val isDark = MaterialTheme.colorScheme.background.luminance() < 0.5fval scope = rememberCoroutineScope()var fullScreen by rememberSaveable { mutableStateOf(false) }@@ -159,7 +160,7 @@ fun DeckScreen(modifier = modifier.fillMaxSize().padding(- horizontal = if (isLandscape) 16.dp else 16.dp,+ horizontal = 16.dp,vertical = if (fullScreen || isLandscape) 8.dp else 12.dp,),verticalArrangement = Arrangement.spacedBy(if (isLandscape) 8.dp else 12.dp),@@ -169,11 +170,11 @@ fun DeckScreen(modifier = Modifier.fillMaxWidth(),verticalAlignment = Alignment.CenterVertically,) {- TextButton(- onClick = onBack,- contentPadding = PaddingValues(horizontal = 12.dp, vertical = 6.dp),- ) {- Text("← " + stringResource(R.string.action_back), style = MaterialTheme.typography.labelLarge)+ IconButton(onClick = onBack) {+ Icon(+ painter = painterResource(R.drawable.ic_back),+ contentDescription = stringResource(R.string.action_back),+ )}Spacer(Modifier.width(4.dp))Column(modifier = Modifier.weight(1f)) {@@ -271,7 +272,7 @@ fun DeckScreen(Text(stringResource(R.string.deck_empty_page, device.name),style = MaterialTheme.typography.bodyMedium,- color = MaterialTheme.colorScheme.onSurfaceVariant,+ color = MaterialResource.onSurfaceVariant(),textAlign = TextAlign.Center,modifier = Modifier.padding(24.dp),)@@ -289,7 +290,6 @@ fun DeckScreen(DeckTileButton(tile = tile,liveState = liveState,- isDark = isDark,compact = isLandscape,enabled = device.online,onPress = {@@ -322,6 +322,11 @@ fun DeckScreen(}}+private object MaterialResource {+ @Composable+ fun onSurfaceVariant(): Color = MaterialTheme.colorScheme.onSurfaceVariant+}+@Composableprivate fun DeckBanner(title: String,@@ -360,57 +365,41 @@ private data class TilePalette(val border: Color,val accent: Color,val fg: Color,+ val iconWell: Color,)-private fun tilePalette(colorName: String, isDark: Boolean): TilePalette = when (colorName) {- "amber" -> if (isDark) {- TilePalette(Color(0xFF33240C), Color(0xFF6B4C1B), Color(0xFFF59E0B), Color(0xFFFDE68A))- } else {- TilePalette(Color(0xFFFEF3C7), Color(0xFFF59E0B), Color(0xFFD97706), Color(0xFF78350F))- }- "coral" -> if (isDark) {- TilePalette(Color(0xFF361B12), Color(0xFF7A3720), Color(0xFFF97316), Color(0xFFFED7AA))- } else {- TilePalette(Color(0xFFFFEDD5), Color(0xFFF97316), Color(0xFFEA580C), Color(0xFF7C2D12))- }- "red", "rose" -> if (isDark) {- TilePalette(Color(0xFF371520), Color(0xFF7F2642), Color(0xFFF43F5E), Color(0xFFFECDD3))- } else {- TilePalette(Color(0xFFFFE4E6), Color(0xFFF43F5E), Color(0xFFE11D48), Color(0xFF881337))- }- "violet" -> if (isDark) {- TilePalette(Color(0xFF25173D), Color(0xFF56348E), Color(0xFF8B5CF6), Color(0xFFDDD6FE))- } else {- TilePalette(Color(0xFFEDE9FE), Color(0xFF8B5CF6), Color(0xFF7C3AED), Color(0xFF4C1D95))- }- "blue", "indigo" -> if (isDark) {- TilePalette(Color(0xFF14263D), Color(0xFF285185), Color(0xFF3B82F6), Color(0xFFBFDBFE))- } else {- TilePalette(Color(0xFFDBEAFE), Color(0xFF3B82F6), Color(0xFF2563EB), Color(0xFF1E3A8A))- }- "teal" -> if (isDark) {- TilePalette(Color(0xFF102E2C), Color(0xFF21645F), Color(0xFF14B8A6), Color(0xFF99F6E4))- } else {- TilePalette(Color(0xFFCCFBF1), Color(0xFF14B8A6), Color(0xFF0D9488), Color(0xFF134E4A))- }- "green", "emerald" -> if (isDark) {- TilePalette(Color(0xFF112E20), Color(0xFF226444), Color(0xFF10B981), Color(0xFFA7F3D0))- } else {- TilePalette(Color(0xFFD1FAE5), Color(0xFF10B981), Color(0xFF059669), Color(0xFF064E3B))- }- else -> if (isDark) {- TilePalette(Color(0xFF1E2530), Color(0xFF3D4B5F), Color(0xFF94A3B8), Color(0xFFE2E8F0))+@Composable+private fun tilePalette(+ @Suppress("UNUSED_PARAMETER") colorName: String,+ highlighted: Boolean,+): TilePalette {+ val scheme = MaterialTheme.colorScheme+ return if (highlighted) {+ TilePalette(+ bg = scheme.primaryContainer,+ border = scheme.primary,+ accent = scheme.primary,+ fg = scheme.onPrimaryContainer,+ iconWell = scheme.surfaceContainerHigh,+ )} else {- TilePalette(Color(0xFFF1F5F9), Color(0xFF94A3B8), Color(0xFF475569), Color(0xFF1E293B))+ TilePalette(+ bg = scheme.surfaceContainerHigh,+ border = scheme.outlineVariant,+ accent = scheme.primary,+ fg = scheme.onSurface,+ iconWell = scheme.secondaryContainer,+ )}}@Composableprivate fun liveBadgeText(kind: String, state: DeckState): String? = when (kind) {"media_play_pause" -> stringResource(if (state.playing) R.string.deck_playing else R.string.deck_paused)- "volume_up", "volume_down", "volume_mute" ->+ "volume_mute" ->if (state.muted) stringResource(R.string.deck_muted)- else stringResource(R.string.deck_volume_percent, state.volume.toInt())+ else if (state.volume > 0u) stringResource(R.string.deck_volume_percent, state.volume.toInt())+ else null"mic_mute" -> when (state.micMuted) {true -> stringResource(R.string.deck_muted)false -> stringResource(R.string.deck_live)@@ -437,19 +426,18 @@ private fun effectiveIcon(tile: DeckTile, state: DeckState): String = when {private fun DeckTileButton(tile: DeckTile,liveState: DeckState,- isDark: Boolean,compact: Boolean,enabled: Boolean,onPress: () -> Unit,) {- val palette = tilePalette(tile.color, isDark)val badge = liveBadgeText(tile.kind, liveState)val highlighted = isLiveHighlighted(tile.kind, liveState)+ val palette = tilePalette(tile.color, highlighted)val iconName = effectiveIcon(tile, liveState)var pressed by remember { mutableStateOf(false) }val scale by animateFloatAsState(- targetValue = if (pressed) 0.94f else 1f,+ targetValue = if (pressed) 0.96f else 1f,animationSpec = spring(stiffness = Spring.StiffnessHigh),label = "tileScale",)@@ -462,7 +450,7 @@ private fun DeckTileButton(contentColor = palette.fg,border = BorderStroke(width = if (highlighted) 2.dp else 1.dp,- color = if (highlighted) palette.accent else palette.border.copy(alpha = 0.65f),+ color = if (highlighted) palette.accent else palette.border,),modifier = Modifier.fillMaxWidth()@@ -504,7 +492,7 @@ private fun DeckTileButton() {Surface(shape = MaterialTheme.shapes.medium,- color = palette.accent.copy(alpha = if (isDark) 0.24f else 0.16f),+ color = palette.iconWell,modifier = Modifier.size(if (compact) 34.dp else 36.dp),) {Box(contentAlignment = Alignment.Center) {@@ -519,8 +507,8 @@ private fun DeckTileButton(if (badge != null) {Surface(shape = CircleShape,- color = if (highlighted) palette.accent else palette.accent.copy(alpha = if (isDark) 0.24f else 0.16f),- contentColor = if (highlighted) Color.White else palette.fg,+ color = if (highlighted) palette.accent else palette.iconWell,+ contentColor = if (highlighted) MaterialTheme.colorScheme.onPrimary else palette.fg,) {Text(text = badge,@@ -894,15 +882,15 @@ private fun fallbackDefaultLayout(): DeckLayout = DeckLayout(id = "main",name = "Main",tiles = listOf(- DeckTile("play_pause", "Play / Pause", "play", "amber", "media_play_pause"),+ 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("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"),),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 ae85153..5deea31 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@@ -6,7 +6,6 @@ import android.text.format.DateUtilsimport android.text.format.Formatterimport androidx.activity.compose.rememberLauncherForActivityResultimport androidx.activity.result.contract.ActivityResultContracts-import androidx.compose.foundation.layout.FlowRowimport androidx.compose.material3.LinearProgressIndicatorimport androidx.compose.material3.TextButtonimport androidx.compose.ui.text.style.TextOverflow@@ -328,6 +327,7 @@ private fun PcCard(if (tree != null) onSendFolder(device.id, tree)}var ringing by remember(device.id) { mutableStateOf(false) }+ var showMoreActions by remember(device.id) { mutableStateOf(false) }Surface(shape = MaterialTheme.shapes.extraLarge,color = MaterialTheme.colorScheme.primaryContainer,@@ -385,11 +385,12 @@ private fun PcCard()val outlined = ButtonDefaults.outlinedButtonColors(contentColor = ink, disabledContentColor = ink.copy(alpha = 0.38f))val outline = BorderStroke(1.dp, ink.copy(alpha = if (device.online) 0.45f else 0.15f))- FlowRow(horizontalArrangement = Arrangement.spacedBy(8.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {+ Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {if (!device.online && device.canWake) {Button(enabled = device.wakeState != WakeState.Waking,onClick = { onWake(device.id) },+ modifier = Modifier.fillMaxWidth(),) {Text(if (device.wakeState == WakeState.Waking) stringResource(R.string.wake_waking, device.name)@@ -397,58 +398,158 @@ private fun PcCard()}}- Button(- enabled = device.online,- onClick = {- ringing = !ringing- onRing(device.id, ringing)- },- ) {- Text(stringResource(if (ringing) R.string.action_stop_ringing else R.string.action_ring_pc))- }- FilledTonalButton(- colors = tonal,- onClick = { onRemote(device.id) },- ) {- Text(stringResource(R.string.action_remote_pc))- }- FilledTonalButton(- colors = tonal,- onClick = { onDeck(device.id) },+ // Primary 2x2 grid: Control PC, Deck, Webcam, Send files+ Row(+ modifier = Modifier.fillMaxWidth(),+ horizontalArrangement = Arrangement.spacedBy(8.dp),) {- Text(stringResource(R.string.action_deck_pc))- }- FilledTonalButton(- colors = tonal,- onClick = { onRecord(device.id) },- ) {- Text(stringResource(R.string.action_record_pc))+ Button(+ onClick = { onRemote(device.id) },+ modifier = Modifier.weight(1f),+ ) {+ Text(stringResource(R.string.action_remote_pc), maxLines = 1, overflow = TextOverflow.Ellipsis)+ }+ FilledTonalButton(+ colors = tonal,+ onClick = { onDeck(device.id) },+ modifier = Modifier.weight(1f),+ ) {+ Text(stringResource(R.string.action_deck_pc), maxLines = 1, overflow = TextOverflow.Ellipsis)+ }}- FilledTonalButton(- colors = tonal,- onClick = { onWebcam(device.id) },+ Row(+ modifier = Modifier.fillMaxWidth(),+ horizontalArrangement = Arrangement.spacedBy(8.dp),) {- Text(stringResource(R.string.action_webcam_pc))+ FilledTonalButton(+ colors = tonal,+ onClick = { onWebcam(device.id) },+ modifier = Modifier.weight(1f),+ ) {+ Text(stringResource(R.string.action_webcam_pc), maxLines = 1, overflow = TextOverflow.Ellipsis)+ }+ FilledTonalButton(+ enabled = device.online,+ colors = tonal,+ onClick = { pickFiles.launch(arrayOf("*/*")) },+ modifier = Modifier.weight(1f),+ ) {+ Text(stringResource(R.string.action_send_files), maxLines = 1, overflow = TextOverflow.Ellipsis)+ }}- FilledTonalButton(- enabled = device.online,- colors = tonal,- onClick = { context.startActivity(SendActivity.sendClipboardIntent(context)) },++ val expanded = showMoreActions || ringing+ Row(+ modifier = Modifier.fillMaxWidth(),+ horizontalArrangement = Arrangement.SpaceBetween,+ verticalAlignment = Alignment.CenterVertically,) {- Text(stringResource(R.string.action_send_clipboard))- }- FilledTonalButton(enabled = device.online, colors = tonal, onClick = { pickFiles.launch(arrayOf("*/*")) }) {- Text(stringResource(R.string.action_send_files))- }- FilledTonalButton(enabled = device.online, colors = tonal, onClick = { pickFolder.launch(null) }) {- Text(stringResource(R.string.action_send_folder))- }- if (device.has("device.pc_actions")) {- OutlinedButton(enabled = device.online, colors = outlined, border = outline, onClick = { onPower(device.id, false) }) {- Text(stringResource(R.string.action_lock_pc))+ TextButton(+ onClick = { showMoreActions = !expanded },+ colors = ButtonDefaults.textButtonColors(contentColor = ink.copy(alpha = 0.85f)),+ ) {+ Text(+ text = stringResource(if (expanded) R.string.action_less else R.string.action_more),+ style = MaterialTheme.typography.labelLarge,+ )+ }+ if (ringing && !showMoreActions) {+ FilledTonalButton(+ colors = tonal,+ onClick = {+ ringing = false+ onRing(device.id, false)+ },+ ) {+ Text(stringResource(R.string.action_stop_ringing))+ }}- OutlinedButton(enabled = device.online, colors = outlined, border = outline, onClick = { onPower(device.id, true) }) {- Text(stringResource(R.string.action_sleep_pc))+ }++ if (expanded) {+ Surface(+ shape = MaterialTheme.shapes.large,+ color = ink.copy(alpha = 0.06f),+ contentColor = ink,+ ) {+ Column(+ modifier = Modifier.fillMaxWidth().padding(12.dp),+ verticalArrangement = Arrangement.spacedBy(8.dp),+ ) {+ Row(+ modifier = Modifier.fillMaxWidth(),+ horizontalArrangement = Arrangement.spacedBy(8.dp),+ ) {+ FilledTonalButton(+ enabled = device.online,+ colors = tonal,+ onClick = { pickFolder.launch(null) },+ modifier = Modifier.weight(1f),+ ) {+ Text(stringResource(R.string.action_send_folder), maxLines = 1, overflow = TextOverflow.Ellipsis)+ }+ FilledTonalButton(+ enabled = device.online,+ colors = tonal,+ onClick = { context.startActivity(SendActivity.sendClipboardIntent(context)) },+ modifier = Modifier.weight(1f),+ ) {+ Text(stringResource(R.string.action_send_clipboard), maxLines = 1, overflow = TextOverflow.Ellipsis)+ }+ }+ Row(+ modifier = Modifier.fillMaxWidth(),+ horizontalArrangement = Arrangement.spacedBy(8.dp),+ ) {+ FilledTonalButton(+ colors = tonal,+ onClick = { onRecord(device.id) },+ modifier = Modifier.weight(1f),+ ) {+ Text(stringResource(R.string.action_record_pc), maxLines = 1, overflow = TextOverflow.Ellipsis)+ }+ FilledTonalButton(+ enabled = device.online,+ colors = tonal,+ onClick = {+ ringing = !ringing+ onRing(device.id, ringing)+ },+ modifier = Modifier.weight(1f),+ ) {+ Text(+ stringResource(if (ringing) R.string.action_stop_ringing else R.string.action_ring_pc),+ maxLines = 1,+ overflow = TextOverflow.Ellipsis,+ )+ }+ }+ if (device.has("device.pc_actions")) {+ Row(+ modifier = Modifier.fillMaxWidth(),+ horizontalArrangement = Arrangement.spacedBy(8.dp),+ ) {+ OutlinedButton(+ enabled = device.online,+ colors = outlined,+ border = outline,+ onClick = { onPower(device.id, false) },+ modifier = Modifier.weight(1f),+ ) {+ Text(stringResource(R.string.action_lock_pc), maxLines = 1, overflow = TextOverflow.Ellipsis)+ }+ OutlinedButton(+ enabled = device.online,+ colors = outlined,+ border = outline,+ onClick = { onPower(device.id, true) },+ modifier = Modifier.weight(1f),+ ) {+ Text(stringResource(R.string.action_sleep_pc), maxLines = 1, overflow = TextOverflow.Ellipsis)+ }+ }+ }+ }}}}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 9d879cd..95b6896 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@@ -196,7 +196,7 @@ private fun NearbyList(devices: List<DiscoveredDevice>, onPair: (String) -> Unit) {Row(Modifier.padding(16.dp), verticalAlignment = Alignment.CenterVertically) {Text(- device.name ?: device.id.take(8),+ device.name ?: stringResource(R.string.your_pc),style = MaterialTheme.typography.titleMedium,modifier = Modifier.weight(1f),)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 433a012..ff8836d 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@@ -31,6 +31,8 @@ import androidx.compose.material3.AssistChipimport androidx.compose.material3.Buttonimport androidx.compose.material3.ButtonDefaultsimport androidx.compose.material3.FilledTonalButton+import androidx.compose.material3.Icon+import androidx.compose.material3.IconButtonimport androidx.compose.material3.MaterialThemeimport androidx.compose.material3.OutlinedButtonimport androidx.compose.material3.OutlinedTextField@@ -50,6 +52,7 @@ import androidx.compose.ui.geometry.CornerRadiusimport androidx.compose.ui.geometry.Offsetimport androidx.compose.ui.geometry.Sizeimport androidx.compose.ui.platform.LocalContext+import androidx.compose.ui.res.painterResourceimport androidx.compose.ui.res.pluralStringResourceimport androidx.compose.ui.res.stringResourceimport androidx.compose.ui.semantics.contentDescription@@ -152,11 +155,11 @@ fun RecorderScreen(modifier = Modifier.fillMaxWidth(),verticalAlignment = Alignment.CenterVertically,) {- TextButton(- onClick = onBack,- contentPadding = PaddingValues(horizontal = 12.dp, vertical = 8.dp),- ) {- Text("← " + stringResource(R.string.action_back), style = MaterialTheme.typography.labelLarge)+ IconButton(onClick = onBack) {+ Icon(+ painter = painterResource(R.drawable.ic_back),+ contentDescription = stringResource(R.string.action_back),+ )}Spacer(Modifier.width(4.dp))Text(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 aa551ec..0c6dc55 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@@ -43,6 +43,8 @@ import androidx.compose.material3.Buttonimport androidx.compose.material3.ButtonDefaultsimport androidx.compose.material3.FilledTonalButtonimport androidx.compose.material3.FilterChip+import androidx.compose.material3.Icon+import androidx.compose.material3.IconButtonimport androidx.compose.material3.LinearProgressIndicatorimport androidx.compose.material3.MaterialThemeimport androidx.compose.material3.OutlinedButton@@ -52,7 +54,6 @@ import androidx.compose.material3.SegmentedButtonDefaultsimport androidx.compose.material3.SingleChoiceSegmentedButtonRowimport androidx.compose.material3.Surfaceimport androidx.compose.material3.Text-import androidx.compose.material3.TextButtonimport androidx.compose.runtime.Composableimport androidx.compose.runtime.DisposableEffectimport androidx.compose.runtime.LaunchedEffect@@ -74,6 +75,7 @@ import androidx.compose.ui.input.pointer.positionChangeimport androidx.compose.ui.platform.LocalContextimport androidx.compose.ui.platform.LocalSoftwareKeyboardControllerimport androidx.compose.ui.platform.LocalView+import androidx.compose.ui.res.painterResourceimport androidx.compose.ui.res.stringResourceimport androidx.compose.ui.text.input.ImeActionimport androidx.compose.ui.text.style.TextAlign@@ -147,11 +149,11 @@ fun RemoteScreen(modifier = Modifier.fillMaxWidth(),verticalAlignment = Alignment.CenterVertically,) {- TextButton(- onClick = onBack,- contentPadding = PaddingValues(horizontal = 12.dp, vertical = 8.dp),- ) {- Text("← " + stringResource(R.string.action_back), style = MaterialTheme.typography.labelLarge)+ IconButton(onClick = onBack) {+ Icon(+ painter = painterResource(R.drawable.ic_back),+ contentDescription = stringResource(R.string.action_back),+ )}Spacer(Modifier.width(4.dp))Text(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 f60f672..aca710a 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@@ -20,6 +20,7 @@ import androidx.compose.foundation.verticalScrollimport androidx.compose.material3.AlertDialogimport androidx.compose.material3.Buttonimport androidx.compose.material3.FilledTonalButton+import androidx.compose.material3.HorizontalDividerimport androidx.compose.material3.MaterialThemeimport androidx.compose.material3.OutlinedButtonimport androidx.compose.material3.SegmentedButton@@ -61,11 +62,9 @@ import app.nectarlink.android.toggles.PhoneTogglesimport app.nectarlink.android.update.AppUpdaterimport app.nectarlink.android.update.CheckForUpdatesimport app.nectarlink.android.core.CoreState-import app.nectarlink.android.core.CoreStatusimport app.nectarlink.android.core.Deviceimport app.nectarlink.android.notifications.NotificationListenerimport app.nectarlink.android.ui.theme.Appearance-import app.nectarlink.android.ui.theme.LocalAppFontsimport app.nectarlink.android.ui.theme.Tokens@Composable@@ -224,7 +223,10 @@ fun SettingsScreen(Section(stringResource(R.string.settings_devices)) {val context = LocalContext.current- state.devices.forEach { device ->+ state.devices.forEachIndexed { index, device ->+ if (index > 0) {+ HorizontalDivider(color = MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.5f))+ }Column(verticalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.fillMaxWidth()) {Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth()) {Column(Modifier.weight(1f)) {@@ -264,14 +266,6 @@ fun SettingsScreen(Section(stringResource(R.string.settings_about)) {Text(stringResource(R.string.about_version, BuildConfig.VERSION_NAME), style = MaterialTheme.typography.bodyMedium)CheckForUpdates(updater)- (state.status as? CoreStatus.Ready)?.let {- Text(- it.deviceId,- style = MaterialTheme.typography.bodySmall,- fontFamily = LocalAppFonts.current.mono,- color = MaterialTheme.colorScheme.onSurfaceVariant,- )- }}}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 0071735..d3bfdaf 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@@ -27,12 +27,15 @@ import androidx.compose.material3.Buttonimport androidx.compose.material3.ButtonDefaultsimport androidx.compose.material3.FilledTonalButtonimport androidx.compose.material3.FilterChip+import androidx.compose.material3.HorizontalDivider+import androidx.compose.material3.Icon+import androidx.compose.material3.IconButtonimport androidx.compose.material3.MaterialThemeimport androidx.compose.material3.OutlinedButtonimport androidx.compose.material3.Slider+import androidx.compose.material3.SliderDefaultsimport androidx.compose.material3.Surfaceimport androidx.compose.material3.Text-import androidx.compose.material3.TextButtonimport androidx.compose.runtime.Composableimport androidx.compose.runtime.DisposableEffectimport androidx.compose.runtime.LaunchedEffect@@ -46,6 +49,7 @@ import androidx.compose.ui.draw.clipimport androidx.compose.ui.graphics.Colorimport androidx.compose.ui.platform.LocalContextimport androidx.compose.ui.platform.LocalView+import androidx.compose.ui.res.painterResourceimport androidx.compose.ui.res.stringResourceimport androidx.compose.ui.unit.dpimport androidx.compose.ui.viewinterop.AndroidView@@ -82,6 +86,7 @@ fun WebcamScreen(var startAfterGrant by remember { mutableStateOf(false) }val askCamera = rememberLauncherForActivityResult(ActivityResultContracts.RequestPermission()) { granted ->hasCameraPermission = WebcamService.hasPermission(context)+ WebcamService.refreshCapabilities(context)onAccessChanged()if (granted && startAfterGrant) {startAfterGrant = false@@ -96,9 +101,13 @@ fun WebcamScreen(}}+ LaunchedEffect(Unit) {+ WebcamService.refreshCapabilities(context)+ }+LaunchedEffect(initialHeight, initialCamera) {if (initialHeight != null) WebcamService.setResolutionHeight(initialHeight)- if (initialCamera != null) WebcamService.setCamera(initialCamera)+ if (initialCamera != null) WebcamService.setCamera(initialCamera, context)}LaunchedEffect(autoStart, hasCameraPermission, device.online) {@@ -120,7 +129,7 @@ fun WebcamScreen(val previewView = remember {PreviewView(context).apply {- scaleType = PreviewView.ScaleType.FIT_CENTER+ scaleType = PreviewView.ScaleType.FILL_CENTERimplementationMode = PreviewView.ImplementationMode.COMPATIBLE}}@@ -139,17 +148,17 @@ fun WebcamScreen(contentPadding = PaddingValues(horizontal = 16.dp, vertical = 12.dp),verticalArrangement = Arrangement.spacedBy(16.dp),) {- // Header: Back, PC name, online dot+ // Header: Back icon button, PC name, online dotitem {Row(modifier = Modifier.fillMaxWidth(),verticalAlignment = Alignment.CenterVertically,) {- TextButton(- onClick = onBack,- contentPadding = PaddingValues(horizontal = 12.dp, vertical = 8.dp),- ) {- Text("← " + stringResource(R.string.action_back), style = MaterialTheme.typography.labelLarge)+ IconButton(onClick = onBack) {+ Icon(+ painter = painterResource(R.drawable.ic_back),+ contentDescription = stringResource(R.string.action_back),+ )}Spacer(Modifier.width(4.dp))Text(@@ -285,18 +294,18 @@ fun WebcamScreen(}}- // Controls Card: Start/Stop, Front/Back switch, Torch, Resolution, Zoom+ // Controls Card: Start/Stop, Front/Back switch, Torch (when camera has flash), Resolution, Zoomitem {Surface(shape = MaterialTheme.shapes.extraLarge,- color = MaterialTheme.colorScheme.primaryContainer,- contentColor = MaterialTheme.colorScheme.onPrimaryContainer,+ color = MaterialTheme.colorScheme.surfaceContainer,+ contentColor = MaterialTheme.colorScheme.onSurface,) {Column(modifier = Modifier.fillMaxWidth().padding(20.dp),verticalArrangement = Arrangement.spacedBy(16.dp),) {- // Primary Start/Stop + Flip camera + Torch+ // Primary Start/Stop + Flip camera + Torch (only shown when camera has flash)FlowRow(horizontalArrangement = Arrangement.spacedBy(8.dp),verticalArrangement = Arrangement.spacedBy(8.dp),@@ -335,7 +344,7 @@ fun WebcamScreen(FilledTonalButton(onClick = {val next = if (session.camera == "front") "back" else "front"- WebcamService.setCamera(next)+ WebcamService.setCamera(next, context)},) {val currentLabel = stringResource(@@ -344,9 +353,9 @@ fun WebcamScreen(Text(stringResource(R.string.webcam_switch_camera) + " ($currentLabel)")}- if (session.camera == "back" && (!isStreamingHere || session.hasFlash)) {+ if (session.hasFlash) {OutlinedButton(- enabled = isStreamingHere && session.hasFlash,+ enabled = isStreamingHere,onClick = { WebcamService.setTorch(!session.torchOn) },) {Text(@@ -358,6 +367,8 @@ fun WebcamScreen(}}+ HorizontalDivider(color = MaterialTheme.colorScheme.outlineVariant)+// Resolution picker: 720p, 1080p, and 4K (when supported)Column(verticalArrangement = Arrangement.spacedBy(6.dp)) {Text(@@ -380,31 +391,33 @@ fun WebcamScreen(}}- // Zoom controls: 1x / 2x presets + smooth slider- Column(verticalArrangement = Arrangement.spacedBy(6.dp)) {- Row(- modifier = Modifier.fillMaxWidth(),- verticalAlignment = Alignment.CenterVertically,- ) {- Text(- stringResource(- R.string.webcam_zoom_label,- String.format(Locale.US, "%.1f", session.zoomRatio).toFloat(),- ),- style = MaterialTheme.typography.labelLarge,- modifier = Modifier.weight(1f),- )+ // Zoom controls: presets + smooth high-contrast slider+ Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {+ Text(+ stringResource(+ R.string.webcam_zoom_label,+ String.format(Locale.US, "%.1f", session.zoomRatio).toFloat(),+ ),+ 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×") },)- Spacer(Modifier.width(8.dp))FilterChip(selected = kotlin.math.abs(session.zoomRatio - 2f) < 0.08f,onClick = { WebcamService.setZoomRatio(2f.coerceAtMost(session.maxZoomRatio)) },label = { Text("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×") },+ )+ }}val minZ = session.minZoomRatioval maxZ = session.maxZoomRatio.coerceAtLeast(minZ + 0.1f)@@ -412,7 +425,14 @@ fun WebcamScreen(value = session.zoomRatio.coerceIn(minZ, maxZ),onValueChange = { WebcamService.setZoomRatio(it) },valueRange = minZ..maxZ,- enabled = isStreamingHere,+ colors = SliderDefaults.colors(+ thumbColor = MaterialTheme.colorScheme.primary,+ activeTrackColor = MaterialTheme.colorScheme.primary,+ inactiveTrackColor = MaterialTheme.colorScheme.secondaryContainer,+ disabledThumbColor = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.6f),+ disabledActiveTrackColor = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.45f),+ disabledInactiveTrackColor = MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.7f),+ ),)}}diff --git a/android/app/src/main/kotlin/app/nectarlink/android/webcam/CameraEncoder.kt b/android/app/src/main/kotlin/app/nectarlink/android/webcam/CameraEncoder.ktindex bc4810c..dd20d10 100644--- a/android/app/src/main/kotlin/app/nectarlink/android/webcam/CameraEncoder.kt+++ b/android/app/src/main/kotlin/app/nectarlink/android/webcam/CameraEncoder.kt@@ -2,6 +2,9 @@package app.nectarlink.android.webcamimport android.content.Context+import android.hardware.camera2.CameraCharacteristics+import android.hardware.camera2.CameraManager+import android.hardware.display.DisplayManagerimport android.media.MediaCodecimport android.media.MediaCodecInfoimport android.media.MediaCodecList@@ -12,6 +15,8 @@ import android.os.Handlerimport android.os.Looperimport android.util.Logimport android.util.Size+import android.view.Display+import android.view.OrientationEventListenerimport android.view.Surfaceimport androidx.camera.core.Cameraimport androidx.camera.core.CameraSelector@@ -59,6 +64,7 @@ internal class CameraEncoder(initialHeight: Int,private val fps: Int,initialCamera: String,+ initialZoomRatio: Float = 1f,private val onStateChanged: (CameraLiveState) -> Unit,private val onEnded: () -> Unit,) {@@ -66,6 +72,7 @@ internal class CameraEncoder(private val main = Handler(Looper.getMainLooper())private val mainExecutor = ContextCompat.getMainExecutor(this.context)private val surfaceExecutor = Executors.newSingleThreadExecutor()+ private val displayManager = this.context.getSystemService(DisplayManager::class.java)val supports4k: Boolean = supports4kEncoder()@@ -74,9 +81,11 @@ internal class CameraEncoder(@Volatile private var targetHeight: Int = normalizeHeight(initialHeight, supports4k)@Volatile private var cameraFacing: String = if (initialCamera == "front") "front" else "back"@Volatile private var activeCodec: ActiveCodec? = null+ @Volatile private var currentSurfaceRotation: Int = readDisplayRotation()private var cameraProvider: ProcessCameraProvider? = nullprivate var boundCamera: Camera? = null+ private var encoderPreview: Preview? = nullprivate var uiPreview: Preview? = nullprivate var pendingUiSurfaceProvider: Preview.SurfaceProvider? = nullprivate var liveState = CameraLiveState(@@ -84,12 +93,46 @@ internal class CameraEncoder(height = targetHeight,fps = fps,camera = cameraFacing,+ zoomRatio = initialZoomRatio.coerceAtLeast(1f),+ maxZoomRatio = cameraMaxZoom(this.context, cameraFacing),+ hasFlash = cameraHasFlash(this.context, cameraFacing),supports4k = supports4k,)+ private val displayListener = object : DisplayManager.DisplayListener {+ override fun onDisplayAdded(displayId: Int) {}+ override fun onDisplayRemoved(displayId: Int) {}+ override fun onDisplayChanged(displayId: Int) {+ if (displayId != Display.DEFAULT_DISPLAY || !running) return+ applySurfaceRotation(readDisplayRotation())+ }+ }++ private val orientationListener = object : OrientationEventListener(this.context) {+ override fun onOrientationChanged(orientation: Int) {+ if (orientation == ORIENTATION_UNKNOWN || !running) return+ val snapped = snapOrientationToSurfaceRotation(orientation, currentSurfaceRotation)+ applySurfaceRotation(snapped)+ }+ }++ private fun readDisplayRotation(): Int =+ displayManager?.getDisplay(Display.DEFAULT_DISPLAY)?.rotation ?: Surface.ROTATION_0++ private fun applySurfaceRotation(rotation: Int) {+ if (rotation == currentSurfaceRotation) return+ currentSurfaceRotation = rotation+ encoderPreview?.targetRotation = rotation+ uiPreview?.targetRotation = rotation+ requestKeyframe()+ }+fun start() {main.post {if (!running) return@post+ currentSurfaceRotation = readDisplayRotation()+ runCatching { displayManager?.registerDisplayListener(displayListener, main) }+ runCatching { if (orientationListener.canDetectOrientation()) orientationListener.enable() }val future = ProcessCameraProvider.getInstance(context)future.addListener({if (!running) return@addListener@@ -108,8 +151,11 @@ internal class CameraEncoder(if (!running) returnrunning = falsemain.post {+ runCatching { displayManager?.unregisterDisplayListener(displayListener) }+ runCatching { orientationListener.disable() }runCatching { cameraProvider?.unbindAll() }boundCamera = null+ encoderPreview = nulluiPreview = null}surfaceExecutor.execute {@@ -179,7 +225,9 @@ internal class CameraEncoder(val provider = cameraProvider ?: returnif (!running) return- val desiredSize = Size(widthForHeight(targetHeight), targetHeight)+ val desiredHeight = targetHeight+ val desiredWidth = widthForHeight(desiredHeight)+ val desiredSize = Size(desiredWidth, desiredHeight)val resSelector = ResolutionSelector.Builder().setAspectRatioStrategy(AspectRatioStrategy.RATIO_16_9_FALLBACK_AUTO_STRATEGY).setResolutionStrategy(@@ -190,12 +238,15 @@ internal class CameraEncoder().build()- val encoderPreview = Preview.Builder()+ val rotation = currentSurfaceRotation+ val encPreview = Preview.Builder().setResolutionSelector(resSelector)+ .setTargetRotation(rotation).build()+ encoderPreview = encPreviewval facingForRequest = cameraFacing- encoderPreview.setSurfaceProvider(surfaceExecutor) { request ->+ encPreview.setSurfaceProvider(surfaceExecutor) { request ->if (!running) {request.willNotProvideSurface()return@setSurfaceProvider@@ -203,10 +254,14 @@ internal class CameraEncoder(activeCodec?.stop()activeCodec = null- val w = request.resolution.width- val h = request.resolution.height- val started = startCodecForResolution(w, h, facingForRequest)- if (started == null) {+ val srcW = request.resolution.width+ val srcH = request.resolution.height+ val outH = desiredHeight+ val outW = widthForHeight(outH)+ val started = startCodecForResolution(srcW, srcH, outW, outH, facingForRequest)+ val inputSurface = started?.pipe?.inputSurface+ if (started == null || inputSurface == null) {+ started?.stop()request.willNotProvideSurface()if (targetHeight > 1080) {// Fall back from 4K to 1080p if the codec rejected 4K.@@ -217,10 +272,14 @@ internal class CameraEncoder(return@setSurfaceProvider}activeCodec = started+ request.setTransformationInfoListener(surfaceExecutor) { info ->+ started.pipe.updateTransform(info.rotationDegrees, info.isMirroring)+ }main.post {updateState { it.copy(width = started.width, height = started.height, camera = facingForRequest) }}- request.provideSurface(started.surface, surfaceExecutor) {+ request.provideSurface(inputSurface, surfaceExecutor) {+ request.clearTransformationInfoListener()if (activeCodec === started) {activeCodec = null}@@ -234,6 +293,7 @@ internal class CameraEncoder(.setAspectRatioStrategy(AspectRatioStrategy.RATIO_16_9_FALLBACK_AUTO_STRATEGY).build(),)+ .setTargetRotation(rotation).build().also { it.setSurfaceProvider(pendingUiSurfaceProvider) }uiPreview = previewForUi@@ -255,11 +315,11 @@ internal class CameraEncoder(provider.unbindAll()val camera = runCatching {- provider.bindToLifecycle(lifecycleOwner, selector, encoderPreview, previewForUi)+ provider.bindToLifecycle(lifecycleOwner, selector, encPreview, previewForUi)}.getOrElse {- // Fallback for single-stream legacy cameras: bind encoderPreview alone.+ // Fallback for single-stream legacy cameras: bind encPreview alone.runCatching {- provider.bindToLifecycle(lifecycleOwner, selector, encoderPreview)+ provider.bindToLifecycle(lifecycleOwner, selector, encPreview)}.getOrNull()}@@ -270,23 +330,35 @@ internal class CameraEncoder(}boundCamera = cameraval zoomState = camera.cameraInfo.zoomState.value- val hasFlash = camera.cameraInfo.hasFlashUnit()+ val minZ = zoomState?.minZoomRatio ?: 1f+ val maxZ = (zoomState?.maxZoomRatio ?: cameraMaxZoom(context, cameraFacing)).coerceAtLeast(2f)+ val initialZ = liveState.zoomRatio.coerceIn(minZ, maxZ)+ if (initialZ > minZ) {+ camera.cameraControl.setZoomRatio(initialZ)+ }+ val hasFlash = camera.cameraInfo.hasFlashUnit() && cameraHasFlash(context, cameraFacing)updateState {it.copy(camera = cameraFacing,- zoomRatio = zoomState?.zoomRatio ?: 1f,- minZoomRatio = zoomState?.minZoomRatio ?: 1f,- maxZoomRatio = (zoomState?.maxZoomRatio ?: 4f).coerceAtLeast(2f),+ zoomRatio = initialZ,+ minZoomRatio = minZ,+ maxZoomRatio = maxZ,hasFlash = hasFlash,torchOn = false,)}}- private fun startCodecForResolution(width: Int, height: Int, camera: String): ActiveCodec? {- val bitrate = bitrateForHeight(height)+ private fun startCodecForResolution(+ srcWidth: Int,+ srcHeight: Int,+ outWidth: Int,+ outHeight: Int,+ camera: String,+ ): ActiveCodec? {+ val bitrate = bitrateForHeight(outHeight)return runCatching {- val format = MediaFormat.createVideoFormat(MediaFormat.MIMETYPE_VIDEO_AVC, width, height).apply {+ val format = MediaFormat.createVideoFormat(MediaFormat.MIMETYPE_VIDEO_AVC, outWidth, outHeight).apply {setInteger(MediaFormat.KEY_COLOR_FORMAT, MediaCodecInfo.CodecCapabilities.COLOR_FormatSurface)setInteger(MediaFormat.KEY_BIT_RATE, bitrate)setInteger(MediaFormat.KEY_FRAME_RATE, fps)@@ -306,17 +378,27 @@ internal class CameraEncoder(}val codec = MediaCodec.createEncoderByType(MediaFormat.MIMETYPE_VIDEO_AVC)codec.configure(format, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE)- val surface = codec.createInputSurface()+ val codecSurface = codec.createInputSurface()codec.start()- ActiveCodec(codec, surface, width, height, camera).also { it.startDrain() }+ val pipe = GlSurfacePipe(+ srcWidth = srcWidth,+ srcHeight = srcHeight,+ dstWidth = outWidth,+ dstHeight = outHeight,+ encoderInputSurface = codecSurface,+ initialRotationDegrees = 0,+ initialMirror = false,+ )+ ActiveCodec(codec, codecSurface, pipe, outWidth, outHeight, camera).also { it.startDrain() }}.onFailure { e ->- Log.w(TAG, "can't start H.264 encoder for ${width}x${height}", e)+ Log.w(TAG, "can't start H.264 encoder for ${outWidth}x${outHeight}", e)}.getOrNull()}private inner class ActiveCodec(val codec: MediaCodec,- val surface: Surface,+ val codecSurface: Surface,+ val pipe: GlSurfacePipe,val width: Int,val height: Int,val camera: String,@@ -330,10 +412,11 @@ internal class CameraEncoder(fun stop() {if (!active.compareAndSet(true, false)) return+ runCatching { pipe.release() }drainThread?.let { runCatching { it.join(500) } }runCatching { codec.stop() }runCatching { codec.release() }- runCatching { surface.release() }+ runCatching { codecSurface.release() }}private fun drainLoop() {@@ -418,6 +501,69 @@ internal class CameraEncoder(else -> 720}+ /** Maps physical tilt degrees (0..359) to [Surface] rotation with hysteresis. */+ internal fun snapOrientationToSurfaceRotation(orientation: Int, currentRotation: Int): Int {+ val currentDeg = when (currentRotation) {+ Surface.ROTATION_0 -> 0+ Surface.ROTATION_270 -> 90+ Surface.ROTATION_180 -> 180+ Surface.ROTATION_90 -> 270+ else -> 0+ }+ val diff = kotlin.math.min(+ kotlin.math.abs(orientation - currentDeg),+ 360 - kotlin.math.abs(orientation - currentDeg),+ )+ // 55-degree hysteresis band avoids flipping near diagonal angles.+ if (diff < 55) return currentRotation+ return when {+ orientation >= 315 || orientation < 45 -> Surface.ROTATION_0+ orientation in 45..134 -> Surface.ROTATION_270+ orientation in 135..224 -> Surface.ROTATION_180+ else -> Surface.ROTATION_90+ }+ }++ /** Checks whether the requested camera (`front` or `back`) has a flash unit. */+ fun cameraHasFlash(context: Context, camera: String): Boolean = runCatching {+ val cm = context.getSystemService(CameraManager::class.java) ?: return false+ val wantedFacing = if (camera == "front") {+ CameraCharacteristics.LENS_FACING_FRONT+ } else {+ CameraCharacteristics.LENS_FACING_BACK+ }+ cm.cameraIdList.any { id ->+ val chars = cm.getCameraCharacteristics(id)+ chars.get(CameraCharacteristics.LENS_FACING) == wantedFacing &&+ chars.get(CameraCharacteristics.FLASH_INFO_AVAILABLE) == true+ }+ }.getOrDefault(false)++ /** Queries the maximum digital zoom ratio supported by the requested camera (`front` or `back`). */+ fun cameraMaxZoom(context: Context, camera: String): Float = runCatching {+ val cm = context.getSystemService(CameraManager::class.java) ?: return 4f+ val wantedFacing = if (camera == "front") {+ CameraCharacteristics.LENS_FACING_FRONT+ } else {+ CameraCharacteristics.LENS_FACING_BACK+ }+ for (id in cm.cameraIdList) {+ val chars = cm.getCameraCharacteristics(id)+ if (chars.get(CameraCharacteristics.LENS_FACING) == wantedFacing) {+ val rangeMax = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {+ chars.get(CameraCharacteristics.CONTROL_ZOOM_RATIO_RANGE)?.upper+ } else {+ null+ }+ val maxZ = rangeMax+ ?: chars.get(CameraCharacteristics.SCALER_AVAILABLE_MAX_DIGITAL_ZOOM)+ ?: 4f+ return maxZ.coerceIn(2f, 8f)+ }+ }+ 4f+ }.getOrDefault(4f)+/** Checks whether any hardware AVC encoder on this device supports 3840×2160. */fun supports4kEncoder(): Boolean = runCatching {val list = MediaCodecList(MediaCodecList.REGULAR_CODECS)diff --git a/android/app/src/main/kotlin/app/nectarlink/android/webcam/GlSurfacePipe.kt b/android/app/src/main/kotlin/app/nectarlink/android/webcam/GlSurfacePipe.ktnew file mode 100644index 0000000..c22fd0a--- /dev/null+++ b/android/app/src/main/kotlin/app/nectarlink/android/webcam/GlSurfacePipe.kt@@ -0,0 +1,317 @@+// SPDX-License-Identifier: GPL-3.0-or-later+package app.nectarlink.android.webcam++import android.graphics.SurfaceTexture+import android.opengl.EGL14+import android.opengl.EGLConfig+import android.opengl.EGLContext+import android.opengl.EGLDisplay+import android.opengl.EGLExt+import android.opengl.EGLSurface+import android.opengl.GLES11Ext+import android.opengl.GLES20+import android.os.Handler+import android.os.HandlerThread+import android.view.Surface+import java.nio.ByteBuffer+import java.nio.ByteOrder+import java.nio.FloatBuffer+import java.util.concurrent.CountDownLatch+import java.util.concurrent.TimeUnit++/**+ * Renders CameraX frames from an input [SurfaceTexture] into a [MediaCodec]+ * encoder input [Surface], applying sensor-to-display rotation and a 16:9+ * center-crop (`FILL_CENTER`) so the encoded H.264 stream is always upright+ * and fills the frame in both portrait and landscape phone orientations.+ */+internal class GlSurfacePipe(+ private val srcWidth: Int,+ private val srcHeight: Int,+ private val dstWidth: Int,+ private val dstHeight: Int,+ private val encoderInputSurface: Surface,+ initialRotationDegrees: Int,+ initialMirror: Boolean,+) : SurfaceTexture.OnFrameAvailableListener {++ private val thread = HandlerThread("webcam-gl-${dstWidth}x${dstHeight}").apply { start() }+ private val handler = Handler(thread.looper)++ @Volatile private var rotationDegrees: Int = ((initialRotationDegrees % 360) + 360) % 360+ @Volatile private var mirrorHorizontally: Boolean = initialMirror+ @Volatile private var released = false++ private var eglDisplay: EGLDisplay = EGL14.EGL_NO_DISPLAY+ private var eglContext: EGLContext = EGL14.EGL_NO_CONTEXT+ private var eglSurface: EGLSurface = EGL14.EGL_NO_SURFACE+ private var oesTexId: Int = 0+ private var program: Int = 0+ private var aPositionLoc: Int = 0+ private var aTexCoordLoc: Int = 0+ private var uStMatrixLoc: Int = 0++ private var surfaceTexture: SurfaceTexture? = null+ var inputSurface: Surface? = null+ private set++ private val stMatrix = FloatArray(16)+ private val quadBuffer: FloatBuffer = ByteBuffer+ .allocateDirect(4 * 4 * 4)+ .order(ByteOrder.nativeOrder())+ .asFloatBuffer()++ init {+ val ready = CountDownLatch(1)+ handler.post {+ try {+ initGl()+ } finally {+ ready.countDown()+ }+ }+ ready.await(3, TimeUnit.SECONDS)+ }++ fun updateTransform(rotationDeg: Int, mirror: Boolean) {+ rotationDegrees = ((rotationDeg % 360) + 360) % 360+ mirrorHorizontally = mirror+ }++ override fun onFrameAvailable(st: SurfaceTexture?) {+ if (released) return+ handler.post { drawFrame() }+ }++ fun release() {+ if (released) return+ released = true+ val done = CountDownLatch(1)+ handler.post {+ try {+ releaseGl()+ } finally {+ done.countDown()+ }+ }+ done.await(1, TimeUnit.SECONDS)+ thread.quitSafely()+ }++ private fun initGl() {+ eglDisplay = EGL14.eglGetDisplay(EGL14.EGL_DEFAULT_DISPLAY)+ val version = IntArray(2)+ EGL14.eglInitialize(eglDisplay, version, 0, version, 1)++ val attribList = intArrayOf(+ EGL14.EGL_RED_SIZE, 8,+ EGL14.EGL_GREEN_SIZE, 8,+ EGL14.EGL_BLUE_SIZE, 8,+ EGL14.EGL_ALPHA_SIZE, 8,+ EGL14.EGL_RENDERABLE_TYPE, EGL14.EGL_OPENGL_ES2_BIT,+ EGLExt.EGL_RECORDABLE_ANDROID, 1,+ EGL14.EGL_NONE,+ )+ val configs = arrayOfNulls<EGLConfig>(1)+ val numConfigs = IntArray(1)+ EGL14.eglChooseConfig(eglDisplay, attribList, 0, configs, 0, 1, numConfigs, 0)+ val config = configs[0] ?: return++ val ctxAttribs = intArrayOf(EGL14.EGL_CONTEXT_CLIENT_VERSION, 2, EGL14.EGL_NONE)+ eglContext = EGL14.eglCreateContext(eglDisplay, config, EGL14.EGL_NO_CONTEXT, ctxAttribs, 0)++ val surfaceAttribs = intArrayOf(EGL14.EGL_NONE)+ eglSurface = EGL14.eglCreateWindowSurface(eglDisplay, config, encoderInputSurface, surfaceAttribs, 0)+ EGL14.eglMakeCurrent(eglDisplay, eglSurface, eglSurface, eglContext)++ program = createProgram(VERTEX_SHADER, FRAGMENT_SHADER)+ aPositionLoc = GLES20.glGetAttribLocation(program, "aPosition")+ aTexCoordLoc = GLES20.glGetAttribLocation(program, "aTexCoord")+ uStMatrixLoc = GLES20.glGetUniformLocation(program, "uStMatrix")++ val texIds = IntArray(1)+ GLES20.glGenTextures(1, texIds, 0)+ oesTexId = texIds[0]+ GLES20.glBindTexture(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, oesTexId)+ GLES20.glTexParameteri(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_LINEAR)+ GLES20.glTexParameteri(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_LINEAR)+ GLES20.glTexParameteri(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, GLES20.GL_TEXTURE_WRAP_S, GLES20.GL_CLAMP_TO_EDGE)+ GLES20.glTexParameteri(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, GLES20.GL_TEXTURE_WRAP_T, GLES20.GL_CLAMP_TO_EDGE)++ val st = SurfaceTexture(oesTexId)+ st.setDefaultBufferSize(srcWidth, srcHeight)+ st.setOnFrameAvailableListener(this, handler)+ surfaceTexture = st+ inputSurface = Surface(st)+ }++ private fun drawFrame() {+ val st = surfaceTexture ?: return+ if (eglDisplay === EGL14.EGL_NO_DISPLAY || eglSurface === EGL14.EGL_NO_SURFACE) return++ runCatching {+ st.updateTexImage()+ st.getTransformMatrix(stMatrix)+ }.onFailure { return }++ val rot = rotationDegrees+ val mirror = mirrorHorizontally++ // After rotating the source buffer by `rot`, its upright dimensions are:+ val uprightW = if (rot % 180 != 0) srcHeight.toFloat() else srcWidth.toFloat()+ val uprightH = if (rot % 180 != 0) srcWidth.toFloat() else srcHeight.toFloat()+ val srcAspect = (uprightW / uprightH.coerceAtLeast(1f)).coerceAtLeast(0.01f)+ val dstAspect = (dstWidth.toFloat() / dstHeight.coerceAtLeast(1).toFloat()).coerceAtLeast(0.01f)++ // FILL_CENTER crop factors in upright output space:+ val scaleX: Float+ val scaleY: Float+ if (srcAspect > dstAspect) {+ scaleX = dstAspect / srcAspect+ scaleY = 1f+ } else {+ scaleX = 1f+ scaleY = srcAspect / dstAspect+ }++ updateQuadVertices(rot, scaleX, scaleY, mirror)++ GLES20.glViewport(0, 0, dstWidth, dstHeight)+ GLES20.glClearColor(0f, 0f, 0f, 1f)+ GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT)++ GLES20.glUseProgram(program)+ GLES20.glActiveTexture(GLES20.GL_TEXTURE0)+ GLES20.glBindTexture(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, oesTexId)+ GLES20.glUniformMatrix4fv(uStMatrixLoc, 1, false, stMatrix, 0)++ quadBuffer.position(0)+ GLES20.glVertexAttribPointer(aPositionLoc, 2, GLES20.GL_FLOAT, false, 16, quadBuffer)+ GLES20.glEnableVertexAttribArray(aPositionLoc)++ quadBuffer.position(2)+ GLES20.glVertexAttribPointer(aTexCoordLoc, 2, GLES20.GL_FLOAT, false, 16, quadBuffer)+ GLES20.glEnableVertexAttribArray(aTexCoordLoc)++ GLES20.glDrawArrays(GLES20.GL_TRIANGLE_STRIP, 0, 4)++ val tsNs = st.timestamp+ if (tsNs > 0L) {+ EGLExt.eglPresentationTimeANDROID(eglDisplay, eglSurface, tsNs)+ }+ EGL14.eglSwapBuffers(eglDisplay, eglSurface)+ }++ private fun updateQuadVertices(rot: Int, scaleX: Float, scaleY: Float, mirror: Boolean) {+ // 4 corners of clip space: (-1,-1), (1,-1), (-1,1), (1,1)+ val clipX = floatArrayOf(-1f, 1f, -1f, 1f)+ val clipY = floatArrayOf(-1f, -1f, 1f, 1f)+ quadBuffer.position(0)+ for (i in 0 until 4) {+ val vx = clipX[i]+ val vy = clipY[i]+ // Centered upright coordinates in [-0.5, +0.5], scaled for aspect-fill crop:+ val sx = (if (mirror) -vx else vx) * 0.5f * scaleX+ val sy = vy * 0.5f * scaleY+ // Map upright output point (sx, sy) back to unrotated buffer coordinates (bx, by)+ // for a clockwise image rotation of `rot` degrees:+ val bx: Float+ val by: Float+ when (rot) {+ 90 -> {+ bx = -sy+ by = sx+ }+ 180 -> {+ bx = -sx+ by = -sy+ }+ 270 -> {+ bx = sy+ by = -sx+ }+ else -> {+ bx = sx+ by = sy+ }+ }+ quadBuffer.put(vx)+ quadBuffer.put(vy)+ quadBuffer.put(bx + 0.5f)+ quadBuffer.put(by + 0.5f)+ }+ quadBuffer.position(0)+ }++ private fun releaseGl() {+ runCatching { inputSurface?.release() }+ inputSurface = null+ runCatching {+ surfaceTexture?.setOnFrameAvailableListener(null)+ surfaceTexture?.release()+ }+ surfaceTexture = null++ if (eglDisplay !== EGL14.EGL_NO_DISPLAY) {+ EGL14.eglMakeCurrent(eglDisplay, EGL14.EGL_NO_SURFACE, EGL14.EGL_NO_SURFACE, EGL14.EGL_NO_CONTEXT)+ if (oesTexId != 0) {+ GLES20.glDeleteTextures(1, intArrayOf(oesTexId), 0)+ oesTexId = 0+ }+ if (program != 0) {+ GLES20.glDeleteProgram(program)+ program = 0+ }+ if (eglSurface !== EGL14.EGL_NO_SURFACE) {+ EGL14.eglDestroySurface(eglDisplay, eglSurface)+ eglSurface = EGL14.EGL_NO_SURFACE+ }+ if (eglContext !== EGL14.EGL_NO_CONTEXT) {+ EGL14.eglDestroyContext(eglDisplay, eglContext)+ eglContext = EGL14.EGL_NO_CONTEXT+ }+ EGL14.eglTerminate(eglDisplay)+ eglDisplay = EGL14.EGL_NO_DISPLAY+ }+ }++ companion object {+ private const val VERTEX_SHADER = """+ uniform mat4 uStMatrix;+ attribute vec4 aPosition;+ attribute vec4 aTexCoord;+ varying vec2 vTexCoord;+ void main() {+ gl_Position = aPosition;+ vTexCoord = (uStMatrix * aTexCoord).xy;+ }+ """++ private const val FRAGMENT_SHADER = """+ #extension GL_OES_EGL_image_external : require+ precision mediump float;+ varying vec2 vTexCoord;+ uniform samplerExternalOES sTexture;+ void main() {+ gl_FragColor = texture2D(sTexture, vTexCoord);+ }+ """++ private fun compileShader(type: Int, src: String): Int {+ val shader = GLES20.glCreateShader(type)+ GLES20.glShaderSource(shader, src)+ GLES20.glCompileShader(shader)+ return shader+ }++ private fun createProgram(vsSource: String, fsSource: String): Int {+ val vs = compileShader(GLES20.GL_VERTEX_SHADER, vsSource)+ val fs = compileShader(GLES20.GL_FRAGMENT_SHADER, fsSource)+ val prog = GLES20.glCreateProgram()+ GLES20.glAttachShader(prog, vs)+ GLES20.glAttachShader(prog, fs)+ GLES20.glLinkProgram(prog)+ return prog+ }+ }+}diff --git a/android/app/src/main/kotlin/app/nectarlink/android/webcam/WebcamService.kt b/android/app/src/main/kotlin/app/nectarlink/android/webcam/WebcamService.ktindex 7c2d909..81c8330 100644--- a/android/app/src/main/kotlin/app/nectarlink/android/webcam/WebcamService.kt+++ b/android/app/src/main/kotlin/app/nectarlink/android/webcam/WebcamService.kt@@ -95,6 +95,9 @@ class WebcamService : LifecycleService() {val normHeight = CameraEncoder.normalizeHeight(height, supports4k)val normWidth = CameraEncoder.widthForHeight(normHeight)val normCamera = if (camera == "front") "front" else "back"+ val hasFlash = CameraEncoder.cameraHasFlash(this, normCamera)+ val maxZoom = CameraEncoder.cameraMaxZoom(this, normCamera)+ val initialZoom = _session.value.zoomRatio.coerceIn(1f, maxZoom)_session.value = WebcamSession(active = true,@@ -104,6 +107,9 @@ class WebcamService : LifecycleService() {height = normHeight,fps = fps,camera = normCamera,+ zoomRatio = initialZoom,+ maxZoomRatio = maxZoom,+ hasFlash = hasFlash,supports4k = supports4k,)@@ -149,6 +155,7 @@ class WebcamService : LifecycleService() {initialHeight = normHeight,fps = fps,initialCamera = normCamera,+ initialZoomRatio = _session.value.zoomRatio,onStateChanged = { live ->_session.update { s ->s.copy(@@ -307,9 +314,33 @@ class WebcamService : LifecycleService() {current?.takeIf { it.pcId == pcId }?.encoder?.requestKeyframe()}- fun setCamera(camera: String) {+ fun refreshCapabilities(context: Context) {+ val cam = _session.value.camera+ val flash = CameraEncoder.cameraHasFlash(context, cam)+ val maxZoom = CameraEncoder.cameraMaxZoom(context, cam)+ _session.update {+ it.copy(+ hasFlash = flash,+ maxZoomRatio = maxZoom,+ zoomRatio = it.zoomRatio.coerceIn(1f, maxZoom),+ )+ }+ }++ fun setCamera(camera: String, context: Context? = null) {val norm = if (camera == "front") "front" else "back"- _session.update { it.copy(camera = norm, torchOn = false) }+ val ctx = context ?: current+ val flash = ctx?.let { CameraEncoder.cameraHasFlash(it, norm) } ?: false+ val maxZoom = ctx?.let { CameraEncoder.cameraMaxZoom(it, norm) } ?: 4f+ _session.update {+ it.copy(+ camera = norm,+ hasFlash = flash,+ maxZoomRatio = maxZoom,+ zoomRatio = it.zoomRatio.coerceIn(1f, maxZoom),+ torchOn = false,+ )+ }current?.encoder?.setCamera(norm)}diff --git a/android/app/src/main/res/drawable/ic_back.xml b/android/app/src/main/res/drawable/ic_back.xmlnew file mode 100644index 0000000..f251e13--- /dev/null+++ b/android/app/src/main/res/drawable/ic_back.xml@@ -0,0 +1,17 @@+<?xml version="1.0" encoding="utf-8"?>+<!-- SPDX-License-Identifier: GPL-3.0-or-later -->+<!-- Back arrow (same stroke style as the rest of the icon set). -->+<vector xmlns:android="http://schemas.android.com/apk/res/android"+ android:width="24dp"+ android:height="24dp"+ android:viewportWidth="24"+ android:viewportHeight="24"+ android:autoMirrored="true">+ <path+ android:pathData="M19 12H5M12 19l-7-7 7-7"+ android:strokeColor="#FF000000"+ android:strokeWidth="1.8"+ android:strokeLineCap="round"+ android:strokeLineJoin="round"+ android:fillColor="#00000000" />+</vector>diff --git a/android/app/src/main/res/values/strings.xml b/android/app/src/main/res/values/strings.xmlindex a4f0ba4..ae1f564 100644--- a/android/app/src/main/res/values/strings.xml+++ b/android/app/src/main/res/values/strings.xml@@ -201,6 +201,8 @@<string name="action_lock_pc">Lock PC</string><string name="action_sleep_pc">Sleep</string><string name="action_wake_pc">Wake</string>+ <string name="action_more">More actions</string>+ <string name="action_less">Fewer actions</string><string name="wake_waking">Waking %1$s…</string><string name="wake_timeout_title">%1$s hasn\'t woken up yet</string><string name="wake_timeout_text">Check that:\n• Wake-on-LAN is enabled in BIOS/UEFI and in the network adapter\'s settings in Windows (Power Management and Wake on Magic Packet).\n• %1$s is on Ethernet if it was shut down (Wi-Fi wake rarely works from shutdown).\n• This phone is on the same network as %1$s.</string>@@ -314,7 +316,7 @@<string name="deck_empty_page">No tiles on this page yet. Add tiles in Nectarlink on %1$s.</string><string name="deck_commands_denied_title">Allow commands on %1$s</string><string name="deck_commands_denied_text">To run shell commands from this phone, turn on “Run Deck commands” for this phone in Nectarlink › Settings › Devices on %1$s.</string>- <string name="deck_hint">Configure pages and tiles in Nectarlink › Deck on %1$s.</string>+ <string name="deck_hint">Customize tiles in Deck on %1$s</string><!-- Phone storage in File Explorer --><string name="settings_storage">Storage in File Explorer</string>diff --git a/core/nectarlink-protocol/src/messages.rs b/core/nectarlink-protocol/src/messages.rsindex 94fb4ae..e3d9c16 100644--- a/core/nectarlink-protocol/src/messages.rs+++ b/core/nectarlink-protocol/src/messages.rs@@ -2436,22 +2436,22 @@ pub mod deck_kinds {/// Default label for an action kind.pub fn default_label(kind: &str) -> &'static str {match kind {- MEDIA_PLAY_PAUSE => "Play / Pause",+ MEDIA_PLAY_PAUSE => "Play / pause",MEDIA_NEXT => "Next",MEDIA_PREVIOUS => "Previous",- VOLUME_UP => "Volume Up",- VOLUME_DOWN => "Volume Down",- VOLUME_MUTE => "Mute Audio",- MIC_MUTE => "Mic Mute",+ VOLUME_UP => "Volume up",+ VOLUME_DOWN => "Volume down",+ VOLUME_MUTE => "Mute audio",+ MIC_MUTE => "Mic mute",LOCK_PC => "Lock PC",- SHOW_DESKTOP => "Show Desktop",- SWITCH_WINDOW => "Switch Window",+ SHOW_DESKTOP => "Show desktop",+ SWITCH_WINDOW => "Switch window",SCREENSHOT => "Screenshot",SHORTCUT => "Shortcut",- OPEN_URL => "Open Website",- TYPE_TEXT => "Type Text",- LAUNCH_APP => "Launch App",- RUN_COMMAND => "Run Command",+ OPEN_URL => "Open website",+ TYPE_TEXT => "Type text",+ LAUNCH_APP => "Launch app",+ RUN_COMMAND => "Run command",_ => "Action",}}@@ -2578,7 +2578,21 @@ impl DeckTile {if !is_valid_deck_id(&self.id) || !deck_kinds::ALL.contains(&self.kind.as_str()) {return None;}- let label = sanitize_deck_label(&self.label)?;+ let raw_label = sanitize_deck_label(&self.label)?;+ let label = match (self.kind.as_str(), raw_label.as_str()) {+ (deck_kinds::MEDIA_PLAY_PAUSE, "Play / Pause") => "Play / pause".into(),+ (deck_kinds::VOLUME_UP, "Volume Up") => "Volume up".into(),+ (deck_kinds::VOLUME_DOWN, "Volume Down") => "Volume down".into(),+ (deck_kinds::VOLUME_MUTE, "Mute Audio") => "Mute audio".into(),+ (deck_kinds::MIC_MUTE, "Mic Mute") => "Mic mute".into(),+ (deck_kinds::SHOW_DESKTOP, "Show Desktop") => "Show desktop".into(),+ (deck_kinds::SWITCH_WINDOW, "Switch Window") => "Switch window".into(),+ (deck_kinds::OPEN_URL, "Open Website") => "Open website".into(),+ (deck_kinds::TYPE_TEXT, "Type Text") => "Type text".into(),+ (deck_kinds::LAUNCH_APP, "Launch App") => "Launch app".into(),+ (deck_kinds::RUN_COMMAND, "Run Command") => "Run command".into(),+ _ => raw_label,+ };let icon = if deck_icons::ALL.contains(&self.icon.as_str()) {self.icon} else {@@ -3629,7 +3643,7 @@ mod tests {// Debug output hides user labels and page names.let dbg = format!("{layout:?}");- assert!(!dbg.contains("Play / Pause") && !dbg.contains("Main"), "{dbg}");+ assert!(!dbg.contains("Play / pause") && !dbg.contains("Main"), "{dbg}");let env = Envelope::new(types::DECK_LAYOUT, &layout).unwrap();let back: DeckLayout = Envelope::from_cbor(&env.to_cbor()).unwrap().body().unwrap();diff --git a/desktop/app/cpp/app_helpers.cpp b/desktop/app/cpp/app_helpers.cppindex 5b9d2f5..aa829c6 100644--- a/desktop/app/cpp/app_helpers.cpp+++ b/desktop/app/cpp/app_helpers.cpp@@ -8,8 +8,14 @@#include <QtGui/QIcon>#include <QtGui/QImage>#include <QtGui/QPixmap>+#include <QtGui/QPixmapCache>#include <QtQuick/QQuickWindow>+#ifdef _WIN32+#define WIN32_LEAN_AND_MEAN+#include <windows.h>+#endif+namespace {QIcon &appIcon(){@@ -57,3 +63,12 @@ int32_t load_bundled_fonts()}return loaded;}++void trim_memory_caches()+{+ QPixmapCache::clear();+#ifdef _WIN32+ SetProcessWorkingSetSize(GetCurrentProcess(), static_cast<SIZE_T>(-1), static_cast<SIZE_T>(-1));+#endif+}+diff --git a/desktop/app/cpp/app_helpers.h b/desktop/app/cpp/app_helpers.hindex 1e05109..a30091d 100644--- a/desktop/app/cpp/app_helpers.h+++ b/desktop/app/cpp/app_helpers.h@@ -19,3 +19,8 @@ void keep_running_without_windows();// Registers every font compiled in under :/fonts/ and returns how many// loaded. Call after QGuiApplication is created.int32_t load_bundled_fonts();++// Clears Qt pixmap caches and asks Windows to trim unused pages from the+// process working set after windows are destroyed (tray mode).+void trim_memory_caches();+diff --git a/desktop/app/qml/App.qml b/desktop/app/qml/App.qmlindex 95183e9..afd5774 100644--- a/desktop/app/qml/App.qml+++ b/desktop/app/qml/App.qml@@ -11,7 +11,8 @@ QtObject {id: appproperty MainWindow mainWindow: null- readonly property LaserOverlay laserOverlay: LaserOverlay {}+ property LaserOverlay laserOverlay: null+ readonly property Component laserComponent: Component { LaserOverlay {} }// A window for each phone screen or app being mirrored. The model// keeps a row per window (by key), so a window lives as long as its// mirroring, whatever else changes.@@ -44,12 +45,25 @@ QtObject {if (!known)mirrorWindows.append({ key: key })}+ if (!app.mainWindow && mirrorWindows.count === 0)+ trayTrimTimer.restart()}readonly property Component mainComponent: Component { MainWindow {} }readonly property bool startMinimized: Qt.application.arguments.indexOf("--minimized") >= 0|| Qt.application.arguments.indexOf("--send-to") >= 0+ readonly property Timer trayTrimTimer: Timer {+ interval: 350+ onTriggered: {+ if (!app.mainWindow && app.mirrorWindows.count === 0) {+ gc()+ AppController.trimWorkingSet()+ }+ }+ }+function showMain() {+ trayTrimTimer.stop()if (!mainWindow) {mainWindow = mainComponent.createObject(null)mainWindow.closeRequested.connect(app.onMainClosed)@@ -65,10 +79,18 @@ QtObject {// Destroy after the close event has finished.const window = mainWindowmainWindow = null- Qt.callLater(() => window.destroy())+ Qt.callLater(() => {+ window.destroy()+ trayTrimTimer.restart()+ })}- Component.onCompleted: if (!startMinimized) showMain()+ Component.onCompleted: {+ if (!startMinimized)+ showMain()+ else+ trayTrimTimer.restart()+ }// Qt follows the system color scheme unless told otherwise; the window// frame and Mica tint must follow the app's theme instead.@@ -82,6 +104,15 @@ QtObject {target: AppControllerfunction onActivateRequested() { app.showMain() }function onQuitRequested() { Qt.quit() }+ function onLaserActiveChanged() {+ if (AppController.laserActive && !app.laserOverlay) {+ app.laserOverlay = app.laserComponent.createObject(null)+ } else if (!AppController.laserActive && app.laserOverlay) {+ const overlay = app.laserOverlay+ app.laserOverlay = null+ Qt.callLater(() => overlay.destroy())+ }+ }function onRingingFromChanged() {if (AppController.ringingFrom.length > 0) {app.showMain()diff --git a/desktop/app/qml/pages/DeckPage.qml b/desktop/app/qml/pages/DeckPage.qmlindex 765ea8c..ec24ea0 100644--- a/desktop/app/qml/pages/DeckPage.qml+++ b/desktop/app/qml/pages/DeckPage.qml@@ -8,6 +8,9 @@ import app.nectarlinkItem {id: pageproperty bool active: false+ onActiveChanged: DeckController.setPageActive(active)+ Component.onCompleted: if (active) DeckController.setPageActive(true)+ Component.onDestruction: DeckController.setPageActive(false)opacity: active ? 1 : 0visible: opacity > 0@@ -78,41 +81,13 @@ Item {}}- // Curated tile color palette for Light and Dark modes (matches deck_colors::ALL).- function tilePalette(colorName) {- const dark = Theme.dark- const map = {- amber: dark ? { bg: "#3B2A14", fg: "#FFDDB3", accent: "#F5A623", border: "#6A4B24" }- : { bg: "#FFF0D6", fg: "#4A2E00", accent: "#C97A00", border: "#F0D199" },- coral: dark ? { bg: "#3E221D", fg: "#FFDAD3", accent: "#FF7E67", border: "#6E3D34" }- : { bg: "#FFE6E0", fg: "#521A10", accent: "#C84B31", border: "#F4BFB3" },- red: dark ? { bg: "#3D1F24", fg: "#FFD9DE", accent: "#F45B69", border: "#6D353E" }- : { bg: "#FFE4E8", fg: "#51121B", accent: "#C92A37", border: "#F2B6BE" },- teal: dark ? { bg: "#153230", fg: "#C4F3EE", accent: "#38CFC3", border: "#285B57" }- : { bg: "#DCF7F4", fg: "#083B37", accent: "#0D9488", border: "#A3E5DF" },- green: dark ? { bg: "#183324", fg: "#C9F5DA", accent: "#4ADE80", border: "#2C5C41" }- : { bg: "#E0F8EA", fg: "#0C3B22", accent: "#16A34A", border: "#A9E8C2" },- blue: dark ? { bg: "#172E3D", fg: "#CEE7FF", accent: "#56B4F9", border: "#2B536E" }- : { bg: "#E0F2FE", fg: "#0B324D", accent: "#0284C7", border: "#AEDBFA" },- violet: dark ? { bg: "#2E2340", fg: "#E9DDFF", accent: "#A985FF", border: "#523F73" }- : { bg: "#EFE7FF", fg: "#2E1557", accent: "#6B46C1", border: "#D3C0FA" },- slate: dark ? { bg: "#222934", fg: "#DCE4F0", accent: "#8FA3BF", border: "#3E4B5E" }- : { bg: "#EAEEF4", fg: "#1E293B", accent: "#475569", border: "#CBD5E1" }- }- return map[colorName] || map.amber+ function isTileHighlighted(kind) {+ if (kind === "media_play_pause") return DeckController.playing+ if (kind === "volume_mute") return DeckController.muted+ if (kind === "mic_mute") return DeckController.micState === 1+ return false}- readonly property var colorChoices: [- { id: "amber", label: qsTr("Amber") },- { id: "coral", label: qsTr("Coral") },- { id: "red", label: qsTr("Red") },- { id: "teal", label: qsTr("Teal") },- { id: "green", label: qsTr("Green") },- { id: "blue", label: qsTr("Blue") },- { id: "violet", label: qsTr("Violet") },- { id: "slate", label: qsTr("Slate") }- ]-readonly property var iconChoices: ["play", "pause", "skip_next", "skip_previous","volume_up", "volume_down", "volume_off", "mic",@@ -122,7 +97,7 @@ Item {]readonly property var actionChoices: [- { id: "media_play_pause", group: qsTr("Media"), label: qsTr("Play / Pause") },+ { id: "media_play_pause", group: qsTr("Media"), label: qsTr("Play / pause") },{ id: "media_previous", group: qsTr("Media"), label: qsTr("Previous track") },{ id: "media_next", group: qsTr("Media"), label: qsTr("Next track") },{ id: "volume_down", group: qsTr("Audio"), label: qsTr("Volume down") },@@ -180,7 +155,7 @@ Item {const localPath = DeckController.urlToLocalPath(selectedFile.toString())if (localPath.length > 0) {editorSheet.paramValue = localPath- if (!editorSheet.labelCustomized || editorSheet.tileLabel.length === 0 || editorSheet.tileLabel === qsTr("Launch App")) {+ if (!editorSheet.labelCustomized || editorSheet.tileLabel.length === 0 || editorSheet.tileLabel === qsTr("Launch app")) {const parts = localPath.split(/[\\/]/)const file = parts[parts.length - 1] || ""const stem = file.replace(/\.(exe|lnk)$/i, "")@@ -223,7 +198,7 @@ Item {wrapMode: Text.WordWraprole: "bodySmall"muted: true- text: qsTr("Big, one-tap buttons on your phone for media, volume, mic mute, window management, shortcuts, and apps. Drag tiles to reorder them or click any tile to customize it.")+ text: qsTr("One-tap buttons on your phone for media, volume, mic mute, window management, shortcuts, and apps. Drag tiles to reorder them or click any tile to customize it.")}}Row {@@ -249,29 +224,59 @@ Item {Divider { width: parent.width }- // Live status pills showing what phones see right now+ // Live status summary showing what phones see right nowFlow {width: parent.width- spacing: 10-- Chip {- iconPath: DeckController.muted ? Icons.soundOff : Icons.speaker- selected: !DeckController.muted- text: DeckController.muted- ? qsTr("Speaker: Muted (%1%)").arg(DeckController.volume)- : qsTr("Speaker: %1%").arg(DeckController.volume)+ spacing: 16++ Row {+ spacing: 6+ Icon {+ anchors.verticalCenter: parent.verticalCenter+ width: 15; height: 15+ path: DeckController.muted ? Icons.soundOff : Icons.speaker+ color: Theme.surfaceContentVariant+ }+ Txt {+ anchors.verticalCenter: parent.verticalCenter+ role: "bodySmall"+ muted: true+ text: DeckController.muted+ ? qsTr("Speaker muted (%1%)").arg(DeckController.volume)+ : qsTr("Speaker %1%").arg(DeckController.volume)+ }}- Chip {- iconPath: DeckController.micState === 1 ? Icons.micOff : Icons.mic- selected: DeckController.micState === 0- text: DeckController.micState === 1 ? qsTr("Mic: Muted")- : DeckController.micState === 0 ? qsTr("Mic: Live")- : qsTr("Mic: None")+ Row {+ spacing: 6+ Icon {+ anchors.verticalCenter: parent.verticalCenter+ width: 15; height: 15+ path: DeckController.micState === 1 ? Icons.micOff : Icons.mic+ color: Theme.surfaceContentVariant+ }+ Txt {+ anchors.verticalCenter: parent.verticalCenter+ role: "bodySmall"+ muted: true+ text: DeckController.micState === 1 ? qsTr("Mic muted")+ : DeckController.micState === 0 ? qsTr("Mic live")+ : qsTr("No mic")+ }}- Chip {- iconPath: DeckController.playing ? Icons.play : Icons.pause- selected: DeckController.playing- text: DeckController.playing ? qsTr("Media: Playing") : qsTr("Media: Paused")+ Row {+ spacing: 6+ Icon {+ anchors.verticalCenter: parent.verticalCenter+ width: 15; height: 15+ path: DeckController.playing ? Icons.play : Icons.pause+ color: Theme.surfaceContentVariant+ }+ Txt {+ anchors.verticalCenter: parent.verticalCenter+ role: "bodySmall"+ muted: true+ text: DeckController.playing ? qsTr("Media playing") : qsTr("Media paused")+ }}}}@@ -346,7 +351,7 @@ Item {id: tileGridwidth: parent.widthcolumns: width >= 760 ? 4 : 3- spacing: 14+ spacing: 12readonly property real cellWidth: (width - spacing * (columns - 1)) / columns@@ -358,32 +363,35 @@ Item {required property int indexwidth: tileGrid.cellWidth- height: 118+ height: 112+ activeFocusOnTab: true+ Accessible.role: Accessible.Button+ Accessible.name: modelData.label+ Accessible.onPressAction: page.openEditTile(modelData)+ Keys.onPressed: (event) => {+ if (event.key === Qt.Key_Return || event.key === Qt.Key_Enter || event.key === Qt.Key_Space) {+ page.openEditTile(modelData)+ event.accepted = true+ }+ }- readonly property var pal: page.tilePalette(modelData.color)readonly property bool isBeingDragged: page.draggedTileIndex === index+ readonly property bool highlighted: page.isTileHighlighted(modelData.kind)Rectangle {id: tileCardanchors.fill: parentradius: Theme.radiusMd- color: Theme.graphite ? Theme.surfaceContainer : tileSlot.pal.bg- border.width: isBeingDragged ? 2 : (Theme.graphite ? 1 : 1)- border.color: isBeingDragged ? Theme.primary- : Theme.graphite ? tileSlot.pal.accent : tileSlot.pal.border- scale: isBeingDragged ? 0.96 : (tileHover.hovered ? 1.01 : 1.0)+ 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+ ? Theme.primary+ : (tileSlot.highlighted ? Theme.surfaceContent : Theme.outlineVariant)+ scale: isBeingDragged ? 0.97 : 1.0Behavior on scale { NumberAnimation { duration: Theme.fadeFast } }-- // Left accent bar in Graphite so tile color is clear without heavy fill- Rectangle {- visible: Theme.graphite- width: 4- height: parent.height - 24- x: 8- anchors.verticalCenter: parent.verticalCenter- radius: 2- color: tileSlot.pal.accent- }+ Behavior on color { ColorAnimation { duration: Theme.fadeFast } }// Top row: Icon badge + live status pill + quick test buttonItem {@@ -391,20 +399,22 @@ Item {anchors.right: parent.rightanchors.top: parent.topanchors.margins: 14- anchors.leftMargin: Theme.graphite ? 18 : 14height: 34Rectangle {id: iconBadgewidth: 34; height: 34radius: Theme.radiusSm- color: Theme.graphite ? Theme.surfaceContainerHigh- : Qt.rgba(tileSlot.pal.accent.r, tileSlot.pal.accent.g, tileSlot.pal.accent.b, 0.18)+ color: tileSlot.highlighted+ ? Theme.primaryContainer+ : (Theme.graphite ? Theme.surfaceContainerHigh : Theme.secondaryContainer)Icon {anchors.centerIn: parentwidth: 18; height: 18path: page.iconPathFor(tileSlot.modelData.icon, tileSlot.modelData.kind)- color: Theme.graphite ? tileSlot.pal.accent : tileSlot.pal.fg+ color: tileSlot.highlighted+ ? Theme.primaryContainerContent+ : (Theme.graphite ? Theme.surfaceContent : Theme.secondaryContainerContent)}}@@ -415,17 +425,16 @@ Item {anchors.leftMargin: 8anchors.verticalCenter: parent.verticalCenterheight: 22- width: statusLabel.implicitWidth + 14+ width: statusLabel.implicitWidth + 12radius: 11- color: Theme.graphite ? Theme.surfaceContainerHigh- : Qt.rgba(0, 0, 0, Theme.dark ? 0.28 : 0.08)+ color: tileSlot.highlighted ? Theme.primaryContainer : Theme.surfaceContainerHighTxt {id: statusLabelanchors.centerIn: parenttext: tileSlot.modelData.status || ""role: "mono"size: 11- color: Theme.graphite ? Theme.surfaceContent : tileSlot.pal.fg+ color: tileSlot.highlighted ? Theme.primaryContainerContent : Theme.surfaceContentVariant}}@@ -436,10 +445,8 @@ Item {anchors.verticalCenter: parent.verticalCenterwidth: 28; height: 28radius: 14- color: testHover.hovered- ? (Theme.graphite ? Theme.surfaceContainerHighest : Qt.rgba(0, 0, 0, Theme.dark ? 0.35 : 0.14))- : "transparent"- opacity: tileHover.hovered || testHover.hovered ? 1 : 0.65+ color: testHover.hovered ? Theme.surfaceContainerHighest : "transparent"+ opacity: tileHover.hovered || testHover.hovered ? 1 : 0.55Accessible.role: Accessible.ButtonAccessible.name: qsTr("Test %1").arg(tileSlot.modelData.label)Accessible.onPressAction: DeckController.testTile(tileSlot.modelData.id)@@ -447,8 +454,8 @@ Item {Icon {anchors.centerIn: parentwidth: 14; height: 14- path: Icons.bolt- color: Theme.graphite ? Theme.surfaceContentVariant : tileSlot.pal.fg+ path: Icons.play+ color: Theme.surfaceContentVariant}HoverHandler { id: testHover; cursorShape: Qt.PointingHandCursor }TapHandler {@@ -463,25 +470,24 @@ Item {anchors.right: parent.rightanchors.bottom: parent.bottomanchors.margins: 14- anchors.leftMargin: Theme.graphite ? 18 : 14spacing: 2Txt {width: parent.widthtext: tileSlot.modelData.label- role: "title"- size: 15+ role: "body"+ weight: Font.DemiBoldelide: Text.ElideRight- color: Theme.graphite ? Theme.surfaceContent : tileSlot.pal.fg+ color: Theme.surfaceContent}Txt {+ visible: (tileSlot.modelData.subtitle || "").length > 0width: parent.widthtext: tileSlot.modelData.subtitle || ""role: "bodySmall"size: 11elide: Text.ElideRight- color: Theme.graphite ? Theme.surfaceContentVariant : tileSlot.pal.fg- opacity: Theme.graphite ? 1.0 : 0.76+ muted: true}}@@ -541,11 +547,22 @@ Item {Rectangle {visible: page.currentTiles.length < 24width: tileGrid.cellWidth- height: 118+ height: 112radius: Theme.radiusMdcolor: addHover.hovered ? Theme.surfaceContainerHigh : "transparent"- border.width: 1- border.color: Theme.outlineVariant+ border.width: addTileBtn.activeFocus ? 2 : 1+ border.color: addTileBtn.activeFocus ? Theme.primary : Theme.outlineVariant+ id: addTileBtn+ activeFocusOnTab: true+ Accessible.role: Accessible.Button+ Accessible.name: qsTr("Add tile")+ Accessible.onPressAction: page.openAddTile()+ Keys.onPressed: (event) => {+ if (event.key === Qt.Key_Return || event.key === Qt.Key_Enter || event.key === Qt.Key_Space) {+ page.openAddTile()+ event.accepted = true+ }+ }Column {anchors.centerIn: parent@@ -587,8 +604,6 @@ Item {property bool modWin: falseproperty string errorText: ""- readonly property var previewPal: page.tilePalette(tileColor)-function selectKind(kind) {actionKind = kindif (!labelCustomized || tileLabel.trim().length === 0) {@@ -627,24 +642,30 @@ Item {wrapMode: Text.WordWraprole: "bodySmall"muted: true- text: qsTr("Phones only receive the tile's label, icon, color, and action kind. File paths and commands stay on this PC.")+ text: qsTr("Phones only receive the tile's label, icon, and action kind. File paths and commands stay on this PC.")}}// Live miniature tile previewRectangle {id: previewBox- width: 148; height: 64+ width: 148; height: 68radius: Theme.radiusMd- color: Theme.graphite ? Theme.surfaceContainer : editorSheet.previewPal.bg- border.width: 1- border.color: Theme.graphite ? editorSheet.previewPal.accent : editorSheet.previewPal.border-- Icon {- x: 12; y: 10- width: 16; height: 16- path: page.iconPathFor(editorSheet.tileIcon, editorSheet.actionKind)- color: Theme.graphite ? editorSheet.previewPal.accent : editorSheet.previewPal.fg+ color: Theme.graphite ? "transparent" : Theme.tileColor+ border.width: Theme.graphite ? 1 : 0+ border.color: Theme.outlineVariant++ Rectangle {+ x: 10; y: 10+ width: 24; height: 24+ radius: Theme.radiusSm+ color: Theme.graphite ? Theme.surfaceContainerHigh : Theme.secondaryContainer+ Icon {+ anchors.centerIn: parent+ width: 14; height: 14+ path: page.iconPathFor(editorSheet.tileIcon, editorSheet.actionKind)+ color: Theme.graphite ? Theme.surfaceContent : Theme.secondaryContainerContent+ }}Txt {anchors.left: parent.left@@ -652,10 +673,10 @@ Item {anchors.bottom: parent.bottomanchors.margins: 10text: editorSheet.tileLabel.length > 0 ? editorSheet.tileLabel : DeckController.defaultLabelFor(editorSheet.actionKind)- role: "title"- size: 13+ role: "bodySmall"+ weight: Font.DemiBoldelide: Text.ElideRight- color: Theme.graphite ? Theme.surfaceContent : editorSheet.previewPal.fg+ color: Theme.surfaceContent}}}@@ -786,69 +807,35 @@ Item {}}- // Tile Label Input + Color Swatches side-by-side- Row {+ // Tile Label Input+ Column {width: parent.width- spacing: 16-- Column {- width: parent.width - colorCol.width - 16- spacing: 6- Txt { text: qsTr("Label"); role: "label"; muted: true }- Rectangle {- width: parent.width- height: 36- radius: Theme.radiusSm- color: Theme.surfaceContainerHigh- border.width: labelInput.activeFocus ? 2 : 1- border.color: labelInput.activeFocus ? Theme.primary : Theme.outlineVariant-- TextInput {- id: labelInput- anchors.fill: parent- anchors.leftMargin: 12- anchors.rightMargin: 12- verticalAlignment: TextInput.AlignVCenter- clip: true- color: Theme.surfaceContent- selectionColor: Theme.primaryContainer- selectedTextColor: Theme.primaryContainerContent- font.family: Theme.fontUi- font.pixelSize: 14- text: editorSheet.tileLabel- onTextEdited: {- editorSheet.tileLabel = text- editorSheet.labelCustomized = true- }- }- }- }-- Column {- id: colorCol- spacing: 6- Txt { text: qsTr("Color"); role: "label"; muted: true }- Row {- height: 36- spacing: 8- Repeater {- model: page.colorChoices- delegate: Rectangle {- required property var modelData- readonly property var pal: page.tilePalette(modelData.id)- readonly property bool chosen: editorSheet.tileColor === modelData.id- anchors.verticalCenter: parent.verticalCenter- width: 26; height: 26; radius: 13- color: pal.accent- border.width: chosen ? 3 : 1- border.color: chosen ? Theme.surfaceContent : pal.border- Accessible.role: Accessible.RadioButton- Accessible.name: modelData.label- Accessible.checked: chosen- Accessible.onPressAction: editorSheet.tileColor = modelData.id- HoverHandler { cursorShape: Qt.PointingHandCursor }- TapHandler { onTapped: editorSheet.tileColor = modelData.id }- }+ spacing: 6+ Txt { text: qsTr("Label"); role: "label"; muted: true }+ Rectangle {+ width: parent.width+ height: 36+ radius: Theme.radiusSm+ color: Theme.surfaceContainerHigh+ border.width: labelInput.activeFocus ? 2 : 1+ border.color: labelInput.activeFocus ? Theme.primary : Theme.outlineVariant++ TextInput {+ id: labelInput+ anchors.fill: parent+ anchors.leftMargin: 12+ anchors.rightMargin: 12+ verticalAlignment: TextInput.AlignVCenter+ clip: true+ color: Theme.surfaceContent+ selectionColor: Theme.primaryContainer+ selectedTextColor: Theme.primaryContainerContent+ font.family: Theme.fontUi+ font.pixelSize: 14+ text: editorSheet.tileLabel+ onTextEdited: {+ editorSheet.tileLabel = text+ editorSheet.labelCustomized = true}}}diff --git a/desktop/app/qml/pages/HomePage.qml b/desktop/app/qml/pages/HomePage.qmlindex 9205543..12913c5 100644--- a/desktop/app/qml/pages/HomePage.qml+++ b/desktop/app/qml/pages/HomePage.qml@@ -534,52 +534,55 @@ Item {}}+ // Active webcam session on this phone.Card {+ id: webcamHomeCardwidth: parent.width+ readonly property var webcamFeature: home.feature("camera.webcam")+ readonly property bool isThisPhone: (Webcam.phase === "streaming" || Webcam.phase === "asking")+ && Webcam.activeDevice === home.deviceId+ visible: isThisPhoneColumn {width: parent.width- spacing: 12- Txt { text: qsTr("Connection"); role: "label"; muted: true }+ spacing: 10Row {- spacing: 10- StatusDot { anchors.verticalCenter: parent.verticalCenter; online: home.online }+ spacing: 8+ Icon {+ anchors.verticalCenter: parent.verticalCenter+ path: Icons.video+ color: Theme.primary+ }Txt {anchors.verticalCenter: parent.verticalCenter- role: "body"- text: home.online- ? (home.path === "relay" ? qsTr("Connected while away") : qsTr("Connected on this network"))- : qsTr("Not connected")+ text: qsTr("Webcam")+ role: "label"}}Txt {width: parent.width- wrapMode: Text.WordWraprole: "bodySmall"muted: true- text: home.online- ? (home.rttMs >= 1 ? qsTr("Round trip %1 ms. End-to-end encrypted.").arg(home.rttMs)- : qsTr("Round trip under 1 ms. End-to-end encrypted."))- : home.lastSeen > 0- ? qsTr("Last seen %1. They reconnect on their own when both are on the same network.")- .arg(page.relativeTime(home.lastSeen))- : qsTr("Open Nectarlink on %1. They connect on their own when both are on the same network.")- .arg(home.name)+ wrapMode: Text.WordWrap+ text: Webcam.statusText.length > 0+ ? Webcam.statusText+ : qsTr("Using %1's camera on this PC.").arg(home.name)}Button {- visible: !home.onlinevariant: "tonal"size: "sm"- text: qsTr("Check the connection")- onClicked: AppController.runDoctor()+ iconPath: Icons.close+ text: qsTr("Stop webcam")+ onClicked: Webcam.stop()}}}- // Quick settings on the phone (toggles, ringer, volume, brightness).+ // Quick settings on the phone (toggles, plus expandable ringer/volume/brightness).Card {id: phoneControlswidth: parent.widthvisible: home.online && state !== null+ property bool expanded: falseproperty bool confirmWifiOff: falseproperty var hoveredLockedFeature: nullreadonly property var state: {@@ -603,13 +606,10 @@ Item {readonly property var brightnessFeature: home.feature("toggles.brightness")readonly property var wifiFeature: home.feature("toggles.wifi")readonly property var bluetoothFeature: home.feature("toggles.bluetooth")+ readonly property var webcamFeature: home.feature("camera.webcam")readonly property var activeLockFeature: {if (hoveredLockedFeature && hoveredLockedFeature.state === "locked")return hoveredLockedFeature- if (wifiFeature.state === "locked")- return wifiFeature- if (dndFeature.state === "locked")- return dndFeaturereturn ({})}onVisibleChanged: if (!visible) confirmWifiOff = false@@ -618,13 +618,31 @@ Item {width: parent.widthspacing: 12- Txt { text: qsTr("Phone controls"); role: "label"; muted: true }+ Item {+ width: parent.width+ height: 24+ Txt {+ anchors.left: parent.left+ anchors.verticalCenter: parent.verticalCenter+ text: qsTr("Phone controls")+ role: "label"+ muted: true+ }+ Button {+ anchors.right: parent.right+ anchors.verticalCenter: parent.verticalCenter+ variant: "text"+ size: "sm"+ text: phoneControls.expanded ? qsTr("Less") : qsTr("Sound & display")+ onClicked: phoneControls.expanded = !phoneControls.expanded+ }+ }Row {id: toggleRowwidth: parent.widthspacing: 6- readonly property int buttonCount: phoneControls.hasFlashlight ? 5 : 4+ readonly property int buttonCount: phoneControls.hasFlashlight ? 4 : 3readonly property real buttonWidth: (width - spacing * (buttonCount - 1)) / buttonCountQuickToggleButton {@@ -725,134 +743,145 @@ Item {}}- // Ringer mode segmented control.Column {width: parent.width- spacing: 6- Segmented {+ spacing: 12+ visible: phoneControls.expanded++ // Ringer mode segmented control.+ Column {width: parent.width- enabled: phoneControls.ringerFeature.state === "available"- || phoneControls.ringerFeature.state === "partial"- opacity: enabled ? 1 : 0.5- options: [- { value: "ring", label: qsTr("Ring") },- { value: "vibrate", label: qsTr("Vibrate") },- { value: "silent", label: qsTr("Silent") }- ]- value: phoneControls.state ? phoneControls.state.ringer : "ring"- onPicked: (mode) => AppController.setPhoneToggle(home.deviceId, "ringer", mode)- }- LockChip {- visible: phoneControls.ringerFeature.state === "locked" && label.length > 0- feature: phoneControls.ringerFeature- maxWidth: parent.width+ spacing: 6+ Segmented {+ width: parent.width+ enabled: phoneControls.ringerFeature.state === "available"+ || phoneControls.ringerFeature.state === "partial"+ opacity: enabled ? 1 : 0.5+ options: [+ { value: "ring", label: qsTr("Ring") },+ { value: "vibrate", label: qsTr("Vibrate") },+ { value: "silent", label: qsTr("Silent") }+ ]+ value: phoneControls.state ? phoneControls.state.ringer : "ring"+ onPicked: (mode) => AppController.setPhoneToggle(home.deviceId, "ringer", mode)+ }+ LockChip {+ visible: phoneControls.ringerFeature.state === "locked" && label.length > 0+ feature: phoneControls.ringerFeature+ maxWidth: parent.width+ }}- }- // Media volume slider.- ToggleSlider {- width: parent.width- deviceId: home.deviceId- toggleId: "volume"- title: qsTr("Volume")- iconPath: shownValue === 0 ? Icons.soundOff : Icons.speaker- phoneValue: phoneControls.state ? phoneControls.state.volume : 0- feature: phoneControls.volumeFeature- }+ // Media volume slider.+ ToggleSlider {+ width: parent.width+ deviceId: home.deviceId+ toggleId: "volume"+ title: qsTr("Volume")+ iconPath: shownValue === 0 ? Icons.soundOff : Icons.speaker+ phoneValue: phoneControls.state ? phoneControls.state.volume : 0+ feature: phoneControls.volumeFeature+ }- // Screen brightness slider.- ToggleSlider {- width: parent.width- deviceId: home.deviceId- toggleId: "brightness"- title: qsTr("Brightness")- iconPath: Icons.brightness- phoneValue: phoneControls.state ? phoneControls.state.brightness : 0- feature: phoneControls.brightnessFeature+ // Screen brightness slider.+ ToggleSlider {+ width: parent.width+ deviceId: home.deviceId+ toggleId: "brightness"+ title: qsTr("Brightness")+ iconPath: Icons.brightness+ phoneValue: phoneControls.state ? phoneControls.state.brightness : 0+ feature: phoneControls.brightnessFeature+ }}}}- // Phone as a webcam on this PC.Card {- id: webcamHomeCardwidth: parent.width- visible: home.online || webcamFeature.state === "locked"- readonly property var webcamFeature: home.feature("camera.webcam")- readonly property bool isThisPhone: (Webcam.phase === "streaming" || Webcam.phase === "asking")- && Webcam.activeDevice === home.deviceIdColumn {width: parent.widthspacing: 10+ Txt { text: qsTr("Connection"); role: "label"; muted: true }Row {- spacing: 8- Icon {- anchors.verticalCenter: parent.verticalCenter- path: Icons.video- color: webcamHomeCard.isThisPhone ? Theme.primary : Theme.surfaceContentVariant- }+ spacing: 10+ StatusDot { anchors.verticalCenter: parent.verticalCenter; online: home.online }Txt {anchors.verticalCenter: parent.verticalCenter- text: qsTr("Webcam")- role: "label"- muted: !webcamHomeCard.isThisPhone+ role: "body"+ text: home.online+ ? (home.path === "relay" ? qsTr("Connected while away") : qsTr("Connected on this network"))+ : qsTr("Not connected")}}Txt {width: parent.width+ wrapMode: Text.WordWraprole: "bodySmall"muted: true- wrapMode: Text.WordWrap- text: webcamHomeCard.isThisPhone && Webcam.statusText.length > 0- ? Webcam.statusText- : qsTr("Use %1's camera in video calls on this PC.").arg(home.name)- }- LockChip {- visible: webcamHomeCard.webcamFeature.state === "locked" && label.length > 0- feature: webcamHomeCard.webcamFeature- maxWidth: parent.width+ text: home.online+ ? (home.rttMs >= 1 ? qsTr("Round trip %1 ms · End-to-end encrypted").arg(home.rttMs)+ : qsTr("Round trip under 1 ms · End-to-end encrypted"))+ : home.lastSeen > 0+ ? qsTr("Last seen %1. Reconnects automatically on the same network.")+ .arg(page.relativeTime(home.lastSeen))+ : qsTr("Open Nectarlink on %1 to connect on this network.")+ .arg(home.name)}Button {- visible: webcamHomeCard.isThisPhone- || (home.online && (webcamHomeCard.webcamFeature.state === "available"- || webcamHomeCard.webcamFeature.action === "enableAddon"))- variant: webcamHomeCard.isThisPhone ? "tonal" : "fill"+ visible: !home.online+ variant: "tonal"size: "sm"- iconPath: webcamHomeCard.isThisPhone ? Icons.close : Icons.video- text: webcamHomeCard.isThisPhone ? qsTr("Stop webcam") : qsTr("Start webcam")- onClicked: {- if (webcamHomeCard.isThisPhone)- Webcam.stop()- else- Webcam.start(home.deviceId)+ text: qsTr("Check the connection")+ onClicked: AppController.runDoctor()+ }+ Divider {+ width: parent.width+ visible: home.online && !webcamHomeCard.isThisPhone+ && (webcamHomeCard.webcamFeature.state === "available"+ || webcamHomeCard.webcamFeature.action === "enableAddon")+ }+ Item {+ width: parent.width+ height: 32+ visible: home.online && !webcamHomeCard.isThisPhone+ && (webcamHomeCard.webcamFeature.state === "available"+ || webcamHomeCard.webcamFeature.action === "enableAddon")+ Row {+ anchors.left: parent.left+ anchors.verticalCenter: parent.verticalCenter+ spacing: 8+ Icon {+ anchors.verticalCenter: parent.verticalCenter+ width: 16; height: 16+ path: Icons.video+ color: Theme.surfaceContentVariant+ }+ Txt {+ anchors.verticalCenter: parent.verticalCenter+ role: "bodySmall"+ text: qsTr("Phone as webcam")+ }+ }+ Button {+ anchors.right: parent.right+ anchors.verticalCenter: parent.verticalCenter+ variant: "tonal"+ size: "sm"+ text: qsTr("Start")+ onClicked: Webcam.start(home.deviceId)}}- }- }-- Card {- width: parent.width- Column {- width: parent.width- spacing: 12- Txt { text: qsTr("This PC"); role: "label"; muted: true }- Txt { width: parent.width; text: AppController.deviceName; role: "title" }+ Divider { width: parent.width }Txt {width: parent.widthrole: "bodySmall"muted: true- text: qsTr("Paired with %1 since %2")- .arg(home.name)+ text: qsTr("This PC (%1) · Paired %2")+ .arg(AppController.deviceName).arg(new Date(home.pairedAt * 1000).toLocaleDateString(Qt.locale(), Locale.ShortFormat))wrapMode: Text.WordWrap}- Button {- variant: "tonal"- size: "sm"- iconPath: Icons.plus- text: qsTr("Pair another device")- onClicked: page.pairRequested()- }}}}@@ -1049,10 +1078,11 @@ Item {readonly property bool available: feature.state === "available" && readyheight: 108+ activeFocusOnTab: availableradius: Theme.radiusLgcolor: tile.active ? Theme.primary : Theme.tileColor- border.width: Theme.graphite ? 1 : 0- border.color: Theme.outlineVariant+ border.width: Theme.focusVisible(tile) ? 2 : (Theme.graphite ? 1 : 0)+ border.color: Theme.focusVisible(tile) ? Theme.primary : Theme.outlineVariantscale: tap.pressed && available ? Theme.pressScale : 1Behavior on scale { SpringAnimation { spring: Theme.springSnappy; damping: Theme.dampingSnappy } }Behavior on color { ColorAnimation { duration: Theme.fadeFast } }@@ -1065,6 +1095,12 @@ Item {Accessible.name: titleAccessible.description: available ? subtitle : lock.labelAccessible.onPressAction: if (tile.available) tile.clicked()+ Keys.onPressed: (event) => {+ if (tile.available && (event.key === Qt.Key_Return || event.key === Qt.Key_Enter || event.key === Qt.Key_Space)) {+ tile.clicked()+ event.accepted = true+ }+ }readonly property color ink: tile.active ? Theme.primaryContent : Theme.surfaceContentColumn {diff --git a/desktop/app/qml/pages/SettingsPage.qml b/desktop/app/qml/pages/SettingsPage.qmlindex 1f2aa8b..033f583 100644--- a/desktop/app/qml/pages/SettingsPage.qml+++ b/desktop/app/qml/pages/SettingsPage.qml@@ -10,6 +10,10 @@ Item {property bool active: falsesignal pairRequested+ onActiveChanged: Webcam.setPreviewActive(active)+ Component.onCompleted: if (active) Webcam.setPreviewActive(true)+ Component.onDestruction: Webcam.setPreviewActive(false)+opacity: active ? 1 : 0visible: opacity > 0Behavior on opacity { NumberAnimation { duration: Theme.fadeNormal } }@@ -118,15 +122,22 @@ Item {readonly property var wallpaperPalette: Theme.wallpaperSeed? Theme.wallpaperSeed[Theme.dark ? "dark" : "light"] : nullwidth: 26; height: 26; radius: 13+ activeFocusOnTab: truecolor: !wallpaper ? Tokens.data.themes.bloom.seeds[modelData].seed: wallpaperPalette ? wallpaperPalette.primary : Theme.surfaceContainerHighest- border.width: selected ? 2 : 0- border.color: Theme.surfaceContent+ border.width: selected || Theme.focusVisible(swatch) ? 2 : 0+ border.color: Theme.focusVisible(swatch) ? Theme.primary : Theme.surfaceContentAccessible.role: Accessible.RadioButtonAccessible.name: wallpaper ? qsTr("Wallpaper"): modelData.charAt(0).toUpperCase() + modelData.slice(1)Accessible.checked: selectedAccessible.onPressAction: Preferences.seed = modelData+ Keys.onPressed: (event) => {+ if (event.key === Qt.Key_Return || event.key === Qt.Key_Enter || event.key === Qt.Key_Space) {+ Preferences.seed = swatch.modelData+ event.accepted = true+ }+ }Icon {visible: swatch.wallpaperanchors.centerIn: parent@@ -286,16 +297,25 @@ Item {? qsTr("\"Nectarlink Webcam\" is registered for Zoom, Teams, Meet and other apps."): qsTr("Set up once (needs administrator approval) so Zoom, Teams, Meet and other apps see \"Nectarlink Webcam\".")Row {- spacing: 8+ spacing: 12Spinner {anchors.verticalCenter: parent.verticalCentervisible: Webcam.addonBusy}- Chip {+ Row {anchors.verticalCenter: parent.verticalCentervisible: Webcam.addonRegistered- selected: true- text: qsTr("Ready")+ spacing: 6+ StatusDot {+ anchors.verticalCenter: parent.verticalCenter+ online: true+ }+ Txt {+ anchors.verticalCenter: parent.verticalCenter+ role: "bodySmall"+ muted: true+ text: qsTr("Ready")+ }}Button {anchors.verticalCenter: parent.verticalCenter@@ -455,12 +475,21 @@ Item {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)}- Chip {- selected: AppController.wakeState === "enabled"- text: AppController.wakeState === "enabled" ? qsTr("Ready")- : AppController.wakeState === "disabled" ? qsTr("Off in Windows")- : AppController.wakeState === "unknown" ? qsTr("Check settings")- : qsTr("No adapter")+ Row {+ spacing: 6+ StatusDot {+ anchors.verticalCenter: parent.verticalCenter+ online: AppController.wakeState === "enabled"+ }+ Txt {+ anchors.verticalCenter: parent.verticalCenter+ role: "bodySmall"+ muted: true+ text: AppController.wakeState === "enabled" ? qsTr("Ready")+ : AppController.wakeState === "disabled" ? qsTr("Off in Windows")+ : AppController.wakeState === "unknown" ? qsTr("Check settings")+ : qsTr("No adapter")+ }}}}@@ -647,19 +676,6 @@ Item {spacing: 8Txt { text: qsTr("Nectarlink %1").arg(AppController.version); role: "title" }Txt { text: qsTr("This PC: %1").arg(AppController.deviceName); role: "bodySmall"; muted: true }- TextEdit {- width: parent.width- readOnly: true- selectByMouse: true- wrapMode: TextEdit.WrapAnywhere- text: AppController.deviceId- color: Theme.surfaceContentVariant- selectionColor: Theme.primaryContainer- selectedTextColor: Theme.primaryContainerContent- font.family: Theme.fontMono- font.pixelSize: 12- Accessible.name: qsTr("Device ID")- }// Updates (installed copies only).Row {visible: AppController.canUpdatediff --git a/desktop/app/src/bridge/app.rs b/desktop/app/src/bridge/app.rsindex 499aebd..ddd2fa2 100644--- a/desktop/app/src/bridge/app.rs+++ b/desktop/app/src/bridge/app.rs@@ -164,6 +164,9 @@ pub mod qobject {/// The local sync root folder path for a paired phone.#[qinvokable]fn phone_storage_path(self: &AppController, device: &QString) -> QString;+ /// Releases idle UI caches and trims the working set when closed to tray.+ #[qinvokable]+ fn trim_working_set(self: &AppController);/// A short message for the user (e.g. a command failed).#[qsignal]@@ -709,6 +712,11 @@ impl qobject::AppController {crate::storage::sync_root_path_for(id).map(|p| p.display().to_string()).unwrap_or_default();QString::from(&path)}++ pub fn trim_working_set(&self) {+ crate::webcam::release_idle_resources();+ super::native::ffi::trim_memory_caches();+ }}impl Drop for AppControllerRust {diff --git a/desktop/app/src/bridge/deck.rs b/desktop/app/src/bridge/deck.rsindex 28ce522..e638e17 100644--- a/desktop/app/src/bridge/deck.rs+++ b/desktop/app/src/bridge/deck.rs@@ -48,13 +48,13 @@ struct UiPage {fn action_fields(action: &DeckAction) -> (String, bool, bool, bool, bool, String) {match action {DeckAction::MediaPlayPause => (String::new(), false, false, false, false, "Media key".into()),- DeckAction::MediaNext => (String::new(), false, false, false, false, "Next track".into()),- DeckAction::MediaPrevious => (String::new(), false, false, false, false, "Previous track".into()),- DeckAction::VolumeUp => (String::new(), false, false, false, false, "Volume +2%".into()),- DeckAction::VolumeDown => (String::new(), false, false, false, false, "Volume -2%".into()),- DeckAction::VolumeMute => (String::new(), false, false, false, false, "Toggle speaker mute".into()),- DeckAction::MicMute => (String::new(), false, false, false, false, "Toggle mic mute".into()),- DeckAction::LockPc => (String::new(), false, false, false, false, "Lock workstation".into()),+ DeckAction::MediaNext => (String::new(), false, false, false, false, "Media key".into()),+ DeckAction::MediaPrevious => (String::new(), false, false, false, false, "Media key".into()),+ DeckAction::VolumeUp => (String::new(), false, false, false, false, "+2%".into()),+ DeckAction::VolumeDown => (String::new(), false, false, false, false, "−2%".into()),+ DeckAction::VolumeMute => (String::new(), false, false, false, false, "Speaker".into()),+ DeckAction::MicMute => (String::new(), false, false, false, false, "Microphone".into()),+ DeckAction::LockPc => (String::new(), false, false, false, false, "Win + L".into()),DeckAction::ShowDesktop => (String::new(), false, false, false, false, "Win + D".into()),DeckAction::SwitchWindow => (String::new(), false, false, false, false, "Alt + Tab".into()),DeckAction::Screenshot => (String::new(), false, false, false, false, "Win + Shift + S".into()),@@ -251,4 +251,8 @@ impl qobject::DeckController {.unwrap_or_else(|| String::from(url));QString::from(raw.trim())}++ pub fn set_page_active(&self, active: bool) {+ deck::set_page_active(active);+ }}diff --git a/desktop/app/src/bridge/native.rs b/desktop/app/src/bridge/native.rsindex 8c33630..ea1d8a5 100644--- a/desktop/app/src/bridge/native.rs+++ b/desktop/app/src/bridge/native.rs@@ -21,5 +21,7 @@ pub mod ffi {/// Registers the fonts compiled in under `:/fonts/`; returns how/// many loaded.fn load_bundled_fonts() -> i32;+ /// Clears Qt pixmap caches and trims the process working set.+ fn trim_memory_caches();}}diff --git a/desktop/app/src/bridge/prefs.rs b/desktop/app/src/bridge/prefs.rsindex 240a055..fe58eb2 100644--- a/desktop/app/src/bridge/prefs.rs+++ b/desktop/app/src/bridge/prefs.rs@@ -117,6 +117,8 @@ pub mod qobject {fn test_tile(self: Pin<&mut DeckController>, tile_id: &QString);#[qinvokable]fn url_to_local_path(self: &DeckController, url: &QString) -> QString;+ #[qinvokable]+ fn set_page_active(self: &DeckController, active: bool);}impl cxx_qt::Initialize for Preferences {}diff --git a/desktop/app/src/bridge/webcam.rs b/desktop/app/src/bridge/webcam.rsindex af28818..15d18b2 100644--- a/desktop/app/src/bridge/webcam.rs+++ b/desktop/app/src/bridge/webcam.rs@@ -58,6 +58,9 @@ pub mod qobject {fn start(self: &Webcam, device: &QString);#[qinvokable]fn stop(self: &Webcam);+ #[qinvokable]+ #[cxx_name = "setPreviewActive"]+ fn set_preview_active(self: &Webcam, active: bool);}}@@ -148,4 +151,8 @@ impl qobject::Webcam {pub fn stop(&self) {webcam::stop();}++ pub fn set_preview_active(&self, active: bool) {+ webcam::set_preview_active(active);+ }}diff --git a/desktop/app/src/deck.rs b/desktop/app/src/deck.rsindex 1e2c31b..9153124 100644--- a/desktop/app/src/deck.rs+++ b/desktop/app/src/deck.rs@@ -30,6 +30,7 @@ struct RuntimeState {static DECK: Mutex<Option<RuntimeState>> = Mutex::new(None);static MEDIA_PLAYING: AtomicBool = AtomicBool::new(false);static HAS_MEDIA_SESSION: AtomicBool = AtomicBool::new(false);+static PAGE_ACTIVE: AtomicBool = AtomicBool::new(false);fn lock<T>(m: &Mutex<T>) -> MutexGuard<'_, T> {m.lock().unwrap_or_else(|e| e.into_inner())@@ -46,6 +47,18 @@ fn sample_live_state() -> DeckState {DeckState { volume, muted, mic_muted, playing }}+/// Marks whether the desktop Deck page is currently visible so idle background+/// polling can pause when no paired device is online.+pub fn set_page_active(active: bool) {+ let prev = PAGE_ACTIVE.swap(active, Ordering::Relaxed);+ if active && !prev {+ core_host::spawn(async {+ reload_from_disk_if_modified();+ refresh_live_state().await;+ });+ }+}+/// Loads `deck.json` from `data_dir` and starts the background poller that/// keeps speaker volume, microphone mute, and external `deck.json` edits in sync.pub fn init(data_dir: &Path) {@@ -56,23 +69,38 @@ pub fn init(data_dir: &Path) {}let config = DeckConfig::load(&path);let mtime = file_mtime(&path);- let initial_state = sample_live_state();+ let initial_state = DeckState { volume: 50, muted: false, mic_muted: Some(false), playing: false };let wire_layout = config.to_wire_layout();{let mut guard = lock(&DECK);- *guard =- Some(RuntimeState { config, state: initial_state.clone(), path: Some(path), last_mtime: mtime });+ *guard = Some(RuntimeState { config, state: initial_state, path: Some(path), last_mtime: mtime });}core_host::host().hub.update(|_| Changes::DECK);core_host::spawn(async move {+ let sampled = tokio::task::spawn_blocking(sample_live_state).await.unwrap_or(DeckState {+ volume: 50,+ muted: false,+ mic_muted: Some(false),+ playing: false,+ });+ {+ let mut guard = lock(&DECK);+ if let Some(rt) = guard.as_mut() {+ rt.state = sampled.clone();+ }+ }+ core_host::host().hub.update(|_| Changes::DECK);if let Some(node) = core_host::wait_for_node().await {let _ = node.set_deck_layout(wire_layout).await;- let _ = node.set_deck_state(initial_state).await;+ let _ = node.set_deck_state(sampled).await;}- let mut interval = tokio::time::interval(Duration::from_millis(1200));+ let mut interval = tokio::time::interval(Duration::from_millis(1500));loop {interval.tick().await;+ if !PAGE_ACTIVE.load(Ordering::Relaxed) {+ continue;+ }reload_from_disk_if_modified();refresh_live_state().await;}@@ -108,7 +136,9 @@ fn reload_from_disk_if_modified() {/// Re-reads the PC's speaker and mic states and broadcasts `deck.state` if changed.pub async fn refresh_live_state() {- let next = sample_live_state();+ let Ok(next) = tokio::task::spawn_blocking(sample_live_state).await else {+ return;+ };let changed = {let mut guard = lock(&DECK);match guard.as_mut() {@@ -184,6 +214,7 @@ pub fn handle_press(_peer: &DeviceId, tile_id: &str) -> Result<(), String> {/// Executes a tile's action by ID (used both for remote `deck.press` and the/// desktop Deck editor's "Test" button).pub fn execute_tile(tile_id: &str) -> Result<(), String> {+ reload_from_disk_if_modified();let action = {let guard = lock(&DECK);let rt = guard.as_ref().ok_or_else(|| "deck not initialized".to_owned())?;diff --git a/desktop/app/src/webcam.rs b/desktop/app/src/webcam.rsindex cbe81da..ae07913 100644--- a/desktop/app/src/webcam.rs+++ b/desktop/app/src/webcam.rs@@ -69,13 +69,14 @@ struct State {static STATE: Mutex<Option<State>> = Mutex::new(None);static MIRROR: AtomicBool = AtomicBool::new(false);static HEIGHT: AtomicU32 = AtomicU32::new(720);+static PREVIEW_ACTIVE: AtomicBool = AtomicBool::new(false);fn state<T>(f: impl FnOnce(&mut State) -> T) -> T {f(STATE.lock().unwrap_or_else(|e| e.into_inner()).get_or_insert_default())}-/// Initializes shared memory, placeholder preview, and (if registered) the-/// Windows virtual camera session.+/// Initializes webcam preferences and (if registered) the Windows virtual+/// camera session.pub fn init(settings: &Settings) {MIRROR.store(settings.webcam_mirror, Ordering::Relaxed);let h = if settings.webcam_height == 1080 { 1080 } else { 720 };@@ -98,7 +99,9 @@ pub fn init(settings: &Settings) {s.addon_registered = registered;s.vcam_handle = vcam_handle;});- refresh_idle_frame();+ if registered {+ refresh_idle_frame();+ }}/// Stops the virtual camera session on app exit.@@ -107,6 +110,7 @@ pub fn shutdown() {if let Some(mapping) = &s.mapping {mapping.set_idle("");}+ s.mapping = None;s.vcam_handle = None;});}@@ -251,8 +255,25 @@ fn mapping() -> Option<Arc<SharedFrameMapping>> {})}-/// Updates the shared-memory header and the QML preview `VideoView` with the-/// idle placeholder frame when no stream is active.+/// Updates the camera's global mapping (if a camera client has opened it)+/// without allocating the 8 MB local fallback mapping while idle.+fn idle_mapping() -> Option<Arc<SharedFrameMapping>> {+ state(|s| {+ let due = s.global_tried.is_none_or(|at| at.elapsed() >= std::time::Duration::from_secs(1));+ if !s.mapping_global && due {+ s.global_tried = Some(std::time::Instant::now());+ if let Ok(global) = SharedFrameMapping::open_existing(DEFAULT_MAPPING_NAME) {+ tracing::debug!("joined the virtual camera's frame mapping");+ s.mapping = Some(Arc::new(global));+ s.mapping_global = true;+ }+ }+ s.mapping.clone()+ })+}++/// Updates the shared-memory header and (when Settings is visible) the QML+/// preview `VideoView` with the idle placeholder frame when no stream is active.fn refresh_idle_frame() {let is_streaming = state(|s| matches!(s.phase, Phase::Streaming { .. }));if is_streaming {@@ -260,13 +281,45 @@ fn refresh_idle_frame() {}let phone = selected_phone();let name = phone_name_for(phone);- if let Some(mapping) = mapping() {+ if let Some(mapping) = idle_mapping() {mapping.set_idle(&name);}- let (w, h) = (640u32, 360u32);- let mut bgrx = vec![0u8; (w * h * 4) as usize];- render_placeholder_bgrx(&mut bgrx, w, h, &name);- ffi::video_frame(PREVIEW_STREAM, w, h, &bgrx);+ if PREVIEW_ACTIVE.load(Ordering::Relaxed) {+ let (w, h) = (640u32, 360u32);+ let mut bgrx = vec![0u8; (w * h * 4) as usize];+ render_placeholder_bgrx(&mut bgrx, w, h, &name);+ ffi::video_frame(PREVIEW_STREAM, w, h, &bgrx);+ }+}++/// Marks whether the Settings webcam preview is on screen so the idle+/// placeholder image is only held while needed.+pub fn set_preview_active(active: bool) {+ let prev = PREVIEW_ACTIVE.swap(active, Ordering::AcqRel);+ if active && !prev {+ refresh_idle_frame();+ } else if !active {+ let is_streaming = state(|s| matches!(s.phase, Phase::Streaming { .. }));+ if !is_streaming {+ ffi::video_clear(PREVIEW_STREAM);+ }+ }+}++/// Releases the idle preview image and any local-only shared mapping when the+/// main window closes to the tray.+pub fn release_idle_resources() {+ PREVIEW_ACTIVE.store(false, Ordering::Release);+ let is_streaming = state(|s| {+ let streaming = matches!(s.phase, Phase::Streaming { .. });+ if !streaming && !s.mapping_global {+ s.mapping = None;+ }+ streaming+ });+ if !is_streaming {+ ffi::video_clear(PREVIEW_STREAM);+ }}/// Requests a webcam stream from `device` (or the selected phone).