Your Android phone and your Windows PC, working as one. Local-first, end-to-end encrypted, no account.
Polish 2: light in the background, a clean webcam placeholder, tidier pages
Bee97faa806b666
diff --git a/Cargo.lock b/Cargo.lockindex 707c3c4..dc81a07 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -2,6 +2,22 @@# It is not intended for manual editing.version = 4+[[package]]+name = "ab_glyph"+version = "0.2.32"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "01c0457472c38ea5bd1c3b5ada5e368271cb550be7a4ca4a0b4634e9913f6cc2"+dependencies = [+ "ab_glyph_rasterizer",+ "owned_ttf_parser",+]++[[package]]+name = "ab_glyph_rasterizer"+version = "0.1.10"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "366ffbaa4442f4684d91e2cd7c5ea7c4ed8add41959a31447066e279e432b618"+[[package]]name = "acto"version = "0.8.2"@@ -2395,6 +2411,7 @@ dependencies = [name = "nectarlink-vcam"version = "0.0.1"dependencies = [+ "ab_glyph","windows","windows-core",]@@ -2809,6 +2826,15 @@ version = "0.2.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d"+[[package]]+name = "owned_ttf_parser"+version = "0.25.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "36820e9051aca1014ddc75770aab4d68bc1e9e632f0f5627c4086bc216fb583b"+dependencies = [+ "ttf-parser",+]+[[package]]name = "papaya"version = "0.2.5"@@ -4211,6 +4237,12 @@ version = "0.2.5"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b"+[[package]]+name = "ttf-parser"+version = "0.25.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d2df906b07856748fa3f6e0ad0cbaa047052d4a7dd609e231c4f72cee8c36f31"+[[package]]name = "typenum"version = "1.20.1"diff --git a/README.md b/README.mdindex cc7d819..b7d7fc0 100644--- a/README.md+++ b/README.md@@ -200,7 +200,8 @@ tests; there are no releases yet.- **Windows app**: home, messages, calls, photos, deck and settings, two themes in light and dark (Bloom,which takes its colors from the desktop wallpaper, and Graphite), Mica, acustom title bar with Snap Layouts, and a tray icon. In the background it- uses about 10 MB of memory (as shown in Task Manager).+ unloads its window and caches (~27 MB private commit when started in the tray+ or ~60 MB after closing the window, with a ~5–10 MB active working set).- **Android app**: pairing, home and settings, Material You colors, a backgroundconnection service, and an identity key protected by the Android Keystore.- **Connection Doctor** on the PC: finds what keeps the phone fromdiff --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 a260f16..a331cd8 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@@ -197,7 +197,7 @@ fun DeckScreen(stringResource(R.string.deck_hint, device.name),style = MaterialTheme.typography.bodySmall,color = MaterialTheme.colorScheme.onSurfaceVariant,- maxLines = 1,+ maxLines = 2,overflow = TextOverflow.Ellipsis,)}@@ -278,7 +278,12 @@ fun DeckScreen()}} else {- val columns = if (isLandscape) 4 else 3+ val largeFont = LocalConfiguration.current.fontScale >= 1.2f+ val columns = when {+ isLandscape -> if (largeFont) 3 else 4+ largeFont -> 2+ else -> 3+ }LazyVerticalGrid(columns = GridCells.Fixed(columns),modifier = Modifier.fillMaxSize(),@@ -443,6 +448,8 @@ private fun DeckTileButton()val a11yDescription = if (badge != null) "${tile.label}, $badge" else tile.label+ val fontScale = LocalConfiguration.current.fontScale.coerceIn(1f, 1.35f)+ val tileHeight = ((if (compact) 98 else 118) * fontScale).dpSurface(shape = MaterialTheme.shapes.large,@@ -454,7 +461,7 @@ private fun DeckTileButton(),modifier = Modifier.fillMaxWidth()- .height(if (compact) 98.dp else 118.dp)+ .height(tileHeight).graphicsLayer {scaleX = scalescaleY = scale@@ -505,6 +512,7 @@ private fun DeckTileButton(}if (badge != null) {+ Spacer(Modifier.width(6.dp))Surface(shape = CircleShape,color = if (highlighted) palette.accent else palette.iconWell,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 95b6896..d006d03 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@@ -151,17 +151,21 @@ fun PairingScreen(@Composableprivate fun Scan(onLink: (String) -> Unit) {- Column(horizontalAlignment = Alignment.CenterHorizontally) {+ Column(+ modifier = Modifier.fillMaxSize(),+ horizontalAlignment = Alignment.CenterHorizontally,+ ) {Text(stringResource(R.string.pair_scan_hint),style = MaterialTheme.typography.bodyMedium,color = MaterialTheme.colorScheme.onSurfaceVariant,textAlign = TextAlign.Center,)- Spacer(Modifier.height(20.dp))+ Spacer(Modifier.height(16.dp))QrScanner(onLink = onLink,modifier = Modifier+ .weight(1f, fill = false).fillMaxWidth().aspectRatio(1f).clip(MaterialTheme.shapes.extraLarge)@@ -182,10 +186,24 @@ private fun NearbyList(devices: List<DiscoveredDevice>, onPair: (String) -> Unit)Spacer(Modifier.height(6.dp))if (devices.isEmpty()) {- Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.Center, verticalAlignment = Alignment.CenterVertically) {- CircularProgressIndicator(Modifier.size(18.dp), strokeWidth = 2.dp)- Spacer(Modifier.width(10.dp))- Text(stringResource(R.string.pair_looking), style = MaterialTheme.typography.bodySmall)+ Surface(+ shape = MaterialTheme.shapes.large,+ color = MaterialTheme.colorScheme.surfaceContainer,+ modifier = Modifier.fillMaxWidth(),+ ) {+ Row(+ Modifier.fillMaxWidth().padding(20.dp),+ horizontalArrangement = Arrangement.Center,+ verticalAlignment = Alignment.CenterVertically,+ ) {+ CircularProgressIndicator(Modifier.size(18.dp), strokeWidth = 2.dp)+ Spacer(Modifier.width(12.dp))+ Text(+ stringResource(R.string.pair_looking),+ style = MaterialTheme.typography.bodyMedium,+ color = MaterialTheme.colorScheme.onSurfaceVariant,+ )+ }}}devices.forEach { device ->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 ff8836d..5acac45 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@@ -57,7 +57,7 @@ import androidx.compose.ui.res.pluralStringResourceimport androidx.compose.ui.res.stringResourceimport androidx.compose.ui.semantics.contentDescriptionimport androidx.compose.ui.semantics.semantics-import androidx.compose.ui.text.font.FontFamily+import app.nectarlink.android.ui.theme.LocalAppFontsimport androidx.compose.ui.text.input.ImeActionimport androidx.compose.ui.text.style.TextOverflowimport androidx.compose.ui.unit.dp@@ -253,7 +253,11 @@ fun RecorderScreen(Spacer(Modifier.height(12.dp))Text(text = RecorderService.formatDuration(session.elapsedMs),- style = MaterialTheme.typography.displayLarge.copy(fontFamily = FontFamily.Monospace),+ style = MaterialTheme.typography.displayMedium.copy(+ fontFamily = LocalAppFonts.current.mono,+ ),+ maxLines = 1,+ softWrap = false,)Spacer(Modifier.height(16.dp))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 0c6dc55..250f664 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@@ -72,6 +72,7 @@ import androidx.compose.ui.focus.focusRequesterimport androidx.compose.ui.geometry.Offsetimport androidx.compose.ui.input.pointer.pointerInputimport androidx.compose.ui.input.pointer.positionChange+import androidx.compose.ui.platform.LocalConfigurationimport androidx.compose.ui.platform.LocalContextimport androidx.compose.ui.platform.LocalSoftwareKeyboardControllerimport androidx.compose.ui.platform.LocalView@@ -169,27 +170,46 @@ fun RemoteScreen(}// Mode switcher: Touchpad | Air mouse | Presentation+ val largeFont = LocalConfiguration.current.fontScale >= 1.15fSingleChoiceSegmentedButtonRow(Modifier.fillMaxWidth()) {SegmentedButton(selected = mode == RemoteMode.Touchpad,onClick = { mode = RemoteMode.Touchpad },shape = SegmentedButtonDefaults.itemShape(0, 3),+ icon = { if (!largeFont) SegmentedButtonDefaults.Icon(mode == RemoteMode.Touchpad) },+ modifier = Modifier.weight(0.95f),) {- Text(stringResource(R.string.remote_mode_touchpad), maxLines = 1)+ Text(+ stringResource(R.string.remote_mode_touchpad),+ maxLines = 1,+ overflow = TextOverflow.Ellipsis,+ )}SegmentedButton(selected = mode == RemoteMode.AirMouse,onClick = { mode = RemoteMode.AirMouse },shape = SegmentedButtonDefaults.itemShape(1, 3),+ icon = { if (!largeFont) SegmentedButtonDefaults.Icon(mode == RemoteMode.AirMouse) },+ modifier = Modifier.weight(0.95f),) {- Text(stringResource(R.string.remote_mode_air), maxLines = 1)+ Text(+ stringResource(R.string.remote_mode_air),+ maxLines = 1,+ overflow = TextOverflow.Ellipsis,+ )}SegmentedButton(selected = mode == RemoteMode.Presentation,onClick = { mode = RemoteMode.Presentation },shape = SegmentedButtonDefaults.itemShape(2, 3),+ icon = { if (!largeFont) SegmentedButtonDefaults.Icon(mode == RemoteMode.Presentation) },+ modifier = Modifier.weight(1.2f),) {- Text(stringResource(R.string.remote_mode_presentation), maxLines = 1)+ Text(+ stringResource(R.string.remote_mode_presentation),+ maxLines = 1,+ overflow = TextOverflow.Ellipsis,+ )}}@@ -493,31 +513,47 @@ private fun TouchpadView() {FilledTonalButton(onClick = { core.remoteButton(pcId, "left", "click", onStatus) },- contentPadding = PaddingValues(horizontal = 10.dp, vertical = 8.dp),+ contentPadding = PaddingValues(horizontal = 8.dp, vertical = 8.dp),modifier = Modifier.weight(1f).height(48.dp),) {- Text(stringResource(R.string.remote_left_click), maxLines = 1)+ Text(+ stringResource(R.string.remote_left_click),+ maxLines = 1,+ overflow = TextOverflow.Ellipsis,+ )}OutlinedButton(onClick = { core.remoteButton(pcId, "middle", "click", onStatus) },- contentPadding = PaddingValues(horizontal = 10.dp, vertical = 8.dp),+ contentPadding = PaddingValues(horizontal = 8.dp, vertical = 8.dp),modifier = Modifier.weight(1f).height(48.dp),) {- Text(stringResource(R.string.remote_middle_click), maxLines = 1)+ Text(+ stringResource(R.string.remote_middle_click),+ maxLines = 1,+ overflow = TextOverflow.Ellipsis,+ )}FilledTonalButton(onClick = { core.remoteButton(pcId, "right", "click", onStatus) },- contentPadding = PaddingValues(horizontal = 10.dp, vertical = 8.dp),+ contentPadding = PaddingValues(horizontal = 8.dp, vertical = 8.dp),modifier = Modifier.weight(1f).height(48.dp),) {- Text(stringResource(R.string.remote_right_click), maxLines = 1)+ Text(+ stringResource(R.string.remote_right_click),+ maxLines = 1,+ overflow = TextOverflow.Ellipsis,+ )}Button(onClick = { showKeyboard = !showKeyboard },- contentPadding = PaddingValues(horizontal = 14.dp, vertical = 8.dp),+ contentPadding = PaddingValues(horizontal = 12.dp, vertical = 8.dp),modifier = Modifier.height(48.dp),) {- Text(stringResource(R.string.remote_keyboard), maxLines = 1)+ Text(+ stringResource(R.string.remote_keyboard),+ maxLines = 1,+ overflow = TextOverflow.Ellipsis,+ )}}@@ -1265,7 +1301,7 @@ private fun PresentationView(Column(modifier = modifier.fillMaxWidth(),- verticalArrangement = Arrangement.spacedBy(12.dp),+ verticalArrangement = Arrangement.spacedBy(10.dp),) {// Huge Next Slide button (easy to hit without looking)Button(@@ -1273,11 +1309,13 @@ private fun PresentationView(shape = MaterialTheme.shapes.extraLarge,modifier = Modifier.fillMaxWidth()- .height(116.dp),+ .height(96.dp),) {Text(stringResource(R.string.remote_slide_next),- style = MaterialTheme.typography.headlineMedium,+ style = MaterialTheme.typography.headlineSmall,+ maxLines = 1,+ overflow = TextOverflow.Ellipsis,)}@@ -1287,11 +1325,13 @@ private fun PresentationView(shape = MaterialTheme.shapes.extraLarge,modifier = Modifier.fillMaxWidth()- .height(72.dp),+ .height(64.dp),) {Text(stringResource(R.string.remote_slide_prev),style = MaterialTheme.typography.titleLarge,+ maxLines = 1,+ overflow = TextOverflow.Ellipsis,)}@@ -1302,24 +1342,36 @@ private fun PresentationView() {OutlinedButton(onClick = { core.remoteSlide(pcId, "start", onStatus) },- contentPadding = PaddingValues(horizontal = 8.dp, vertical = 8.dp),- modifier = Modifier.weight(1f).height(48.dp),+ contentPadding = PaddingValues(horizontal = 6.dp, vertical = 8.dp),+ modifier = Modifier.weight(0.98f).height(48.dp),) {- Text(stringResource(R.string.remote_slide_start), maxLines = 1)+ Text(+ stringResource(R.string.remote_slide_start),+ maxLines = 1,+ overflow = TextOverflow.Ellipsis,+ )}OutlinedButton(onClick = { core.remoteSlide(pcId, "stop", onStatus) },- contentPadding = PaddingValues(horizontal = 8.dp, vertical = 8.dp),- modifier = Modifier.weight(1f).height(48.dp),+ contentPadding = PaddingValues(horizontal = 6.dp, vertical = 8.dp),+ modifier = Modifier.weight(0.88f).height(48.dp),) {- Text(stringResource(R.string.remote_slide_stop), maxLines = 1)+ Text(+ stringResource(R.string.remote_slide_stop),+ maxLines = 1,+ overflow = TextOverflow.Ellipsis,+ )}OutlinedButton(onClick = { core.remoteSlide(pcId, "black", onStatus) },- contentPadding = PaddingValues(horizontal = 8.dp, vertical = 8.dp),- modifier = Modifier.weight(1f).height(48.dp),+ contentPadding = PaddingValues(horizontal = 6.dp, vertical = 8.dp),+ modifier = Modifier.weight(1.22f).height(48.dp),) {- Text(stringResource(R.string.remote_slide_black), maxLines = 1)+ Text(+ stringResource(R.string.remote_slide_black),+ maxLines = 1,+ overflow = TextOverflow.Ellipsis,+ )}}@@ -1395,7 +1447,11 @@ private fun PresentationView(Text(stringResource(R.string.remote_volume_hint),style = MaterialTheme.typography.bodySmall,- color = MaterialTheme.colorScheme.onSurfaceVariant,+ color = if (laserHeld) {+ MaterialTheme.colorScheme.onPrimaryContainer.copy(alpha = 0.8f)+ } else {+ MaterialTheme.colorScheme.onSurfaceVariant+ },textAlign = TextAlign.Center,)}diff --git a/android/app/src/main/kotlin/app/nectarlink/android/ui/settings/SettingsScreen.kt b/android/app/src/main/kotlin/app/nectarlink/android/ui/settings/SettingsScreen.ktindex aca710a..e0a234d 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@@ -87,12 +87,12 @@ fun SettingsScreen(Column(modifier.verticalScroll(rememberScrollState()).padding(16.dp),- verticalArrangement = Arrangement.spacedBy(12.dp),+ verticalArrangement = Arrangement.spacedBy(16.dp),) {Text(stringResource(R.string.settings_title),style = MaterialTheme.typography.headlineMedium,- modifier = Modifier.padding(top = 8.dp, bottom = 4.dp),+ modifier = Modifier.padding(top = 8.dp),)Section(stringResource(R.string.settings_notifications)) {@@ -108,6 +108,7 @@ fun SettingsScreen(permissions = PhoneCalls.permissions,onAccessChanged = onAccessChanged,)+ SettingRowDivider()RuntimePermissionAccess(title = stringResource(R.string.contacts_title),textOn = stringResource(R.string.contacts_on),@@ -116,6 +117,7 @@ fun SettingsScreen(permissions = PhoneContacts.permissions,onAccessChanged = onAccessChanged,)+ SettingRowDivider()RuntimePermissionAccess(title = stringResource(R.string.sms_title),textOn = stringResource(R.string.sms_on),@@ -132,9 +134,7 @@ fun SettingsScreen(partial = state.photoPartialAccess,onAccessChanged = onAccessChanged,)- }-- Section(stringResource(R.string.settings_storage)) {+ SettingRowDivider()StorageAccess(allFiles = state.storageAllFilesAccess,safFolders = state.storageSafFolders,@@ -145,8 +145,11 @@ fun SettingsScreen(Section(stringResource(R.string.settings_control)) {DndAccess(state.dndAccess)+ SettingRowDivider()WriteSettingsAccess(state.writeSettingsAccess || state.elevated)+ SettingRowDivider()ControlAccess(state.inputAccess)+ SettingRowDivider()ElevatedAccess()}@@ -186,9 +189,10 @@ fun SettingsScreen(appearance.mode,) { value -> onAppearance { it.copy(mode = value) } }if (appearance.theme == "bloom") {+ SettingRowDivider()if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth()) {- Column(Modifier.weight(1f)) {+ Column(Modifier.weight(1f).padding(end = 12.dp)) {Text(stringResource(R.string.settings_dynamic_color), style = MaterialTheme.typography.titleSmall)Text(stringResource(R.string.settings_dynamic_color_hint),@@ -210,8 +214,14 @@ fun SettingsScreen(shape = CircleShape,color = seed.color,modifier = Modifier- .size(32.dp)- .then(if (selected) Modifier.border(2.dp, MaterialTheme.colorScheme.onSurface, CircleShape) else Modifier)+ .size(38.dp)+ .then(+ if (selected) {+ Modifier.border(2.5.dp, MaterialTheme.colorScheme.onSurface, CircleShape)+ } else {+ Modifier.border(1.dp, MaterialTheme.colorScheme.outlineVariant, CircleShape)+ },+ ).clickable { onAppearance { it.copy(seed = name) } }.semantics { contentDescription = name },) {}@@ -225,17 +235,27 @@ fun SettingsScreen(val context = LocalContext.currentstate.devices.forEachIndexed { index, device ->if (index > 0) {- HorizontalDivider(color = MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.5f))+ SettingRowDivider()}- Column(verticalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.fillMaxWidth()) {+ Column(verticalArrangement = Arrangement.spacedBy(10.dp), modifier = Modifier.fillMaxWidth()) {Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth()) {- Column(Modifier.weight(1f)) {+ Column(Modifier.weight(1f).padding(end = 12.dp)) {Text(device.name, style = MaterialTheme.typography.titleSmall)- Text(- stringResource(if (device.online) R.string.connected else R.string.not_connected),- style = MaterialTheme.typography.bodySmall,- color = MaterialTheme.colorScheme.onSurfaceVariant,- )+ Row(+ verticalAlignment = Alignment.CenterVertically,+ horizontalArrangement = Arrangement.spacedBy(6.dp),+ ) {+ Surface(+ shape = CircleShape,+ color = if (device.online) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.outline,+ modifier = Modifier.size(8.dp),+ ) {}+ Text(+ stringResource(if (device.online) R.string.connected else R.string.not_connected),+ style = MaterialTheme.typography.bodySmall,+ color = MaterialTheme.colorScheme.onSurfaceVariant,+ )+ }}OutlinedButton(onClick = { confirmUnpair = device }) { Text(stringResource(R.string.action_unpair)) }}@@ -583,16 +603,23 @@ private fun StorageAccess(}}+@Composable+private fun SettingRowDivider() {+ HorizontalDivider(color = MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.45f))+}+@Composableprivate fun Section(title: String, content: @Composable () -> Unit) {- Text(- title,- style = MaterialTheme.typography.labelLarge,- color = MaterialTheme.colorScheme.onSurfaceVariant,- modifier = Modifier.padding(top = 8.dp),- )- Surface(shape = MaterialTheme.shapes.large, color = MaterialTheme.colorScheme.surfaceContainer) {- Column(Modifier.fillMaxWidth().padding(16.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) { content() }+ Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {+ Text(+ title,+ style = MaterialTheme.typography.labelLarge,+ color = MaterialTheme.colorScheme.onSurfaceVariant,+ modifier = Modifier.padding(start = 4.dp),+ )+ Surface(shape = MaterialTheme.shapes.large, color = MaterialTheme.colorScheme.surfaceContainer) {+ Column(Modifier.fillMaxWidth().padding(16.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) { content() }+ }}}diff --git a/core/nectarlink-cli/src/main.rs b/core/nectarlink-cli/src/main.rsindex 084dcf3..2286cc6 100644--- a/core/nectarlink-cli/src/main.rs+++ b/core/nectarlink-cli/src/main.rs@@ -315,6 +315,12 @@ enum Command {/// Artwork for the song (JPEG or PNG).#[arg(long)]art: Option<PathBuf>,+ /// Number of sample gallery items to generate.+ #[arg(long, default_value_t = 12)]+ photos: usize,+ /// Number of sample messages in the main conversation.+ #[arg(long, default_value_t = 3)]+ messages: usize,},/// Act as a phone with an incoming call (use with --as-phone): PCs can/// answer it, then mute, use the speaker, hold, press keys or hang up,@@ -888,11 +894,31 @@ static TEXTS: std::sync::Mutex<Vec<SampleText>> = std::sync::Mutex::new(Vec::new/// Set by `texts`, to tell PCs when the samples changed.static TEXTS_NODE: std::sync::OnceLock<Node> = std::sync::OnceLock::new();-fn sample_texts() {+fn sample_texts(main_thread_count: usize) {let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.as_millis() as i64);let min = 60_000;+ let mut rows: Vec<SampleText> = Vec::with_capacity(main_thread_count + 8);+ if main_thread_count > 3 {+ let extra = main_thread_count - 3;+ let phrases = [+ "Here are the notes from the design sync earlier today.",+ "Looks good! Did you check the layout at 760x540 too?",+ "Yes, everything fits cleanly without clipping.",+ "Nice, how about dark mode and Bloom theme?",+ "Tested both — contrast on the cards and headers is solid.",+ "Can we also test scrolling through a long thread?",+ "On it right now, generating 500 messages to check frame pacing.",+ "Awesome, let me know when you're ready for dinner.",+ ];+ for i in 0..extra {+ let incoming = i % 2 == 0;+ let body = format!("{} (#{})", phrases[i % phrases.len()], i + 1);+ let date = now - (55 + ((extra - i) as i64) * 12) * min;+ rows.push((1, "+15550100".into(), "Sam Rivera".into(), incoming, body, date));+ }+ }let samples = [(1, "+15550100", "Sam Rivera", true, "Are we still on for dinner tonight?", now - 50 * min),(1, "+15550100", "Sam Rivera", false, "Yes! 7:30 at the usual place", now - 48 * min),@@ -910,10 +936,12 @@ fn sample_texts() {(3, "+15550188", "Alex", false, "Can you send me the photos from Saturday?", now - 3 * 24 * 60 * min),(3, "+15550188", "Alex", true, "Sure, uploading them now", now - 3 * 24 * 60 * min + 5 * min),];- *TEXTS.lock().unwrap() = samples- .into_iter()- .map(|(t, n, name, incoming, body, date)| (t, n.into(), name.into(), incoming, body.into(), date))- .collect();+ rows.extend(+ samples.into_iter().map(|(t, n, name, incoming, body, date)| {+ (t, n.into(), name.into(), incoming, body.into(), date)+ }),+ );+ *TEXTS.lock().unwrap() = rows;}static CONTACTS: std::sync::Mutex<Vec<nectarlink_core::Contact>> = std::sync::Mutex::new(Vec::new());@@ -1186,7 +1214,7 @@ fn sample_jpeg(out}-fn sample_photos() {+fn sample_photos(total_count: usize) {use nectarlink_core::{PhotoAlbum, PhotoItem};let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH)@@ -1343,14 +1371,14 @@ fn sample_photos() {let temp_dir = std::env::temp_dir().join("nectarlink-demo-photos");let _ = std::fs::create_dir_all(&temp_dir);- let mut items = Vec::with_capacity(specs.len());+ let mut base_items = Vec::with_capacity(specs.len());for (id, name, date, w, h, duration, album, top, bottom, sun) in specs {let thumb_jpeg = sample_jpeg(240, 180, top, bottom, sun);let full_bytes = sample_jpeg(640, 480, top, bottom, sun);let size = full_bytes.len() as u64;let full_path = temp_dir.join(name);let _ = std::fs::write(&full_path, &full_bytes);- items.push(SampleGalleryItem {+ base_items.push(SampleGalleryItem {item: PhotoItem {id: id.into(),name: name.into(),@@ -1365,24 +1393,62 @@ fn sample_photos() {full_path,});}++ let mut items = Vec::with_capacity(total_count);+ for idx in 0..total_count {+ if idx < base_items.len() {+ let b = &base_items[idx];+ items.push(SampleGalleryItem {+ item: b.item.clone(),+ thumb_jpeg: b.thumb_jpeg.clone(),+ full_path: b.full_path.clone(),+ });+ } else {+ let b = &base_items[idx % base_items.len()];+ let id = format!("media:demo-{}", idx + 1);+ let name = format!("IMG_202603{:02}_{:06}.jpg", 31 - ((idx / 70) % 28), idx + 1);+ let date = now - (84 + (idx as i64) * 2) * hour;+ items.push(SampleGalleryItem {+ item: PhotoItem {+ id,+ name,+ date,+ size: b.item.size,+ width: b.item.width,+ height: b.item.height,+ duration: b.item.duration,+ album: b.item.album.clone(),+ },+ thumb_jpeg: b.thumb_jpeg.clone(),+ full_path: b.full_path.clone(),+ });+ }+ }++ let count_album =+ |alb: &str| items.iter().filter(|e| e.item.album.as_deref() == Some(alb)).count() as u32;+ let cam_cnt = count_album("bucket:camera");+ let scr_cnt = count_album("bucket:screenshots");+ let trp_cnt = count_album("bucket:trips");+*GALLERY_ITEMS.lock().unwrap() = items;*GALLERY_ALBUMS.lock().unwrap() = vec![PhotoAlbum {id: "bucket:camera".into(),name: "Camera".into(),- count: 6,+ count: cam_cnt,cover: Some("media:demo-1".into()),},PhotoAlbum {id: "bucket:screenshots".into(),name: "Screenshots".into(),- count: 2,+ count: scr_cnt,cover: Some("media:demo-5".into()),},PhotoAlbum {id: "bucket:trips".into(),name: "Weekend Trip".into(),- count: 4,+ count: trp_cnt,cover: Some("media:demo-7".into()),},];@@ -2805,7 +2871,7 @@ async fn run(cli: &Cli, node: &Node) -> Result<()> {if !cli.as_phone {bail!("texts are on phones: add --as-phone");}- sample_texts();+ sample_texts(3);sample_contacts();sample_call_log();let _ = TEXTS_NODE.set(node.clone());@@ -2860,14 +2926,14 @@ async fn run(cli: &Cli, node: &Node) -> Result<()> {println!("Ringing on connected PCs (and on others when they connect).");watch(node, false).await?;}- Command::Demo { call, art } => {+ Command::Demo { call, art, photos, messages } => {if !cli.as_phone {bail!("the demo is a phone: add --as-phone");}- sample_texts();+ sample_texts(*messages);sample_contacts();sample_call_log();- sample_photos();+ sample_photos(*photos);let _ = TEXTS_NODE.set(node.clone());let _ = CALL_NODE.set(node.clone());let _ = TOGGLES_NODE.set(node.clone());diff --git a/desktop/app/cpp/app_helpers.cpp b/desktop/app/cpp/app_helpers.cppindex aa829c6..d352cc1 100644--- a/desktop/app/cpp/app_helpers.cpp+++ b/desktop/app/cpp/app_helpers.cpp@@ -1,7 +1,9 @@// SPDX-License-Identifier: GPL-3.0-or-later#include "app_helpers.h"+#include "video_view.h"#include <QtCore/QDir>+#include <QtCore/QPointer>#include <QtCore/QtEnvironmentVariables>#include <QtGui/QFontDatabase>#include <QtGui/QGuiApplication>@@ -9,11 +11,14 @@#include <QtGui/QImage>#include <QtGui/QPixmap>#include <QtGui/QPixmapCache>+#include <QtQml/QQmlApplicationEngine>+#include <QtQml/QQmlEngine>#include <QtQuick/QQuickWindow>#ifdef _WIN32#define WIN32_LEAN_AND_MEAN#include <windows.h>+#include <malloc.h>#endifnamespace {@@ -22,8 +27,25 @@ QIcon &appIcon()static QIcon icon;return icon;}++QPointer<QQmlEngine> &qmlEngineRef()+{+ static QPointer<QQmlEngine> engine;+ return engine;+}} // namespace+void register_qml_engine(QQmlEngine *engine)+{+ if (engine)+ qmlEngineRef() = engine;+}++void register_qml_app_engine(QQmlApplicationEngine &engine)+{+ qmlEngineRef() = &engine;+}+void prepare_qt(){// Windows get an alpha channel so the Mica backdrop can show through, and@@ -31,6 +53,11 @@ void prepare_qt()// transparent pixels render white (see spikes/s1-qt-rust, lesson 7).QQuickWindow::setDefaultAlphaBuffer(true);qputenv("QT_QPA_DISABLE_REDIRECTION_SURFACE", "1");+ qputenv("QSG_RENDER_LOOP", "basic");+ // Qt's V4 JS engine reserves 2 x QV4_JS_MAX_STACK_SIZE of committed RW+ // memory (8 MB by default). 512 KB per stack (1 MB total) is plenty for+ // UI bindings and saves 7 MB of private commit in the tray.+ qputenv("QV4_JS_MAX_STACK_SIZE", "524288");}void add_app_icon_image(int32_t size, rust::Slice<const uint8_t> rgba)@@ -66,9 +93,22 @@ int32_t load_bundled_fonts()void trim_memory_caches(){+ clear_idle_video_frames();QPixmapCache::clear();+ if (QQmlEngine *engine = qmlEngineRef().data()) {+ engine->collectGarbage();+ engine->trimComponentCache();+ engine->collectGarbage();+ }#ifdef _WIN32+ _heapmin();+ HANDLE heaps[64];+ const DWORD count = GetProcessHeaps(64, heaps);+ for (DWORD i = 0; i < count && i < 64; ++i) {+ HeapCompact(heaps[i], 0);+ }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 a30091d..c5ab391 100644--- a/desktop/app/cpp/app_helpers.h+++ b/desktop/app/cpp/app_helpers.h@@ -20,7 +20,17 @@ void keep_running_without_windows();// 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).+class QQmlEngine;+class QQmlApplicationEngine;++// Clears Qt pixmap/QML caches, compacts heaps, and asks Windows to trim unused+// pages from the process working set after windows are destroyed (tray mode).void trim_memory_caches();+// Records the active QML engine so trim_memory_caches can run GC and clear+// component caches when windows are unloaded.+void register_qml_engine(QQmlEngine *engine);+void register_qml_app_engine(QQmlApplicationEngine &engine);+++diff --git a/desktop/app/cpp/native_window.cpp b/desktop/app/cpp/native_window.cppindex 1f6ee78..676f594 100644--- a/desktop/app/cpp/native_window.cpp+++ b/desktop/app/cpp/native_window.cpp@@ -1,13 +1,18 @@// SPDX-License-Identifier: GPL-3.0-or-later#include "native_window.h"+#include "app_helpers.h"#include <QtGui/QPlatformSurfaceEvent>+#include <QtQml/QtQml>+#include <QtQuick/QSGRendererInterface>#include <algorithm>#define WIN32_LEAN_AND_MEAN#include <windows.h>+#include <d3d11.h>#include <dwmapi.h>+#include <dxgi1_3.h>#include <windowsx.h>namespace {@@ -25,6 +30,31 @@ HWND hwndOf(const QWindow *window)return reinterpret_cast<HWND>(window->winId());}+void trimD3DResources(QQuickWindow *window)+{+ if (!window)+ return;+ QSGRendererInterface *rif = window->rendererInterface();+ if (!rif)+ return;+ auto *device = static_cast<ID3D11Device *>(+ rif->getResource(window, QSGRendererInterface::DeviceResource));+ if (!device)+ return;+ ID3D11DeviceContext *ctx = nullptr;+ device->GetImmediateContext(&ctx);+ if (ctx) {+ ctx->ClearState();+ ctx->Flush();+ ctx->Release();+ }+ IDXGIDevice3 *dxgi3 = nullptr;+ if (SUCCEEDED(device->QueryInterface(__uuidof(IDXGIDevice3), reinterpret_cast<void **>(&dxgi3))) && dxgi3) {+ dxgi3->Trim();+ dxgi3->Release();+ }+}+} // namespaceNativeWindow::NativeWindow(QWindow *parent)@@ -33,6 +63,10 @@ NativeWindow::NativeWindow(QWindow *parent)// Qt removes the system title bar and lets content fill the window.setFlags(flags() | Qt::ExpandedClientAreaHint);setColor(Qt::transparent);+ // Drop the scene graph and D3D/RHI resources when the window is hidden or+ // closed to the tray instead of keeping GPU buffers in private commit.+ setPersistentSceneGraph(false);+ setPersistentGraphics(false);}void NativeWindow::setBackdrop(bool on)@@ -117,8 +151,32 @@ void NativeWindow::flash()FlashWindowEx(&info);}+void NativeWindow::releaseAndTeardown()+{+ if (QQmlEngine *engine = qmlEngine(this))+ register_qml_engine(engine);+ m_holes.clear();+ m_maximizeButton = nullptr;+ trimD3DResources(this);+ releaseResources();+ hide();+ trimD3DResources(this);+ destroy();+}+bool NativeWindow::event(QEvent *event){+ if (QQmlEngine *engine = qmlEngine(this))+ register_qml_engine(engine);+ if (event->type() == QEvent::Close) {+ trimD3DResources(this);+ event->accept();+ emit closeRequested();+ return true;+ }+ if (event->type() == QEvent::Hide) {+ trimD3DResources(this);+ }if (event->type() == QEvent::PlatformSurface&& static_cast<QPlatformSurfaceEvent *>(event)->surfaceEventType()== QPlatformSurfaceEvent::SurfaceCreated) {diff --git a/desktop/app/cpp/native_window.h b/desktop/app/cpp/native_window.hindex c9d1bc9..41a15ba 100644--- a/desktop/app/cpp/native_window.h+++ b/desktop/app/cpp/native_window.h@@ -56,6 +56,10 @@ public:Q_INVOKABLE void bringToFront();// Flashes the taskbar button until the window is activated.Q_INVOKABLE void flash();+ // Releases scene-graph/D3D resources, destroys the native HWND, and+ // schedules deletion when closing to the tray.+ Q_INVOKABLE void releaseAndTeardown();+signals:void backdropChanged();@@ -63,6 +67,7 @@ signals:void captionHeightChanged();void maximizeButtonChanged();void maximizeStateChanged();+ void closeRequested();protected:bool event(QEvent *event) override;diff --git a/desktop/app/cpp/video_view.cpp b/desktop/app/cpp/video_view.cppindex 217da22..48948eb 100644--- a/desktop/app/cpp/video_view.cpp+++ b/desktop/app/cpp/video_view.cpp@@ -219,3 +219,13 @@ void video_clear(rust::Str stream)latest.remove(key);wakeViews(key);}++void clear_idle_video_frames()+{+ std::lock_guard guard(lock);+ if (views.empty()) {+ latest.clear();+ latest.squeeze();+ }+}+diff --git a/desktop/app/cpp/video_view.h b/desktop/app/cpp/video_view.hindex 1bd6c6a..e93f83c 100644--- a/desktop/app/cpp/video_view.h+++ b/desktop/app/cpp/video_view.h@@ -75,3 +75,7 @@ void video_frame(rust::Str stream, uint32_t width, uint32_t height, rust::Slice<// The stream ended: views of it go blank. Any thread.void video_clear(rust::Str stream);++// Drops cached video frames for streams that have no live VideoView.+void clear_idle_video_frames();+diff --git a/desktop/app/qml/App.qml b/desktop/app/qml/App.qmlindex afd5774..a7d1d0c 100644--- a/desktop/app/qml/App.qml+++ b/desktop/app/qml/App.qml@@ -10,18 +10,26 @@ import app.nectarlinkQtObject {id: app- property MainWindow mainWindow: null- property LaserOverlay laserOverlay: null- readonly property Component laserComponent: Component { LaserOverlay {} }+ readonly property var mainWindow: mainLoader.item+ readonly property Loader mainLoader: Loader {+ onLoaded: {+ item.closeRequested.connect(app.onMainClosed)+ item.bringToFront()+ }+ }+ readonly property Loader laserLoader: Loader {+ active: AppController.laserActive+ source: active ? "qrc:/qt/qml/app/nectarlink/qml/LaserOverlay.qml" : ""+ }// A window for each phone screen or app being mirrored. The model// keeps a row per window (by key), so a window lives as long as its// mirroring, whatever else changes.readonly property ListModel mirrorWindows: ListModel {}readonly property Instantiator mirrorInstantiator: Instantiator {model: app.mirrorWindows- delegate: MirrorWindow {+ delegate: Loader {required property string key- mirrorKey: key+ Component.onCompleted: setSource("qrc:/qt/qml/app/nectarlink/qml/MirrorWindow.qml", { mirrorKey: key })}}readonly property Connections mirrorSync: Connections {@@ -48,7 +56,6 @@ QtObject {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@@ -64,11 +71,11 @@ QtObject {function showMain() {trayTrimTimer.stop()- if (!mainWindow) {- mainWindow = mainComponent.createObject(null)- mainWindow.closeRequested.connect(app.onMainClosed)+ if (!mainLoader.item) {+ mainLoader.setSource("qrc:/qt/qml/app/nectarlink/qml/MainWindow.qml")+ } else {+ mainLoader.item.bringToFront()}- mainWindow.bringToFront()}function onMainClosed() {@@ -76,11 +83,11 @@ QtObject {Qt.quit()return}- // Destroy after the close event has finished.- const window = mainWindow- mainWindow = null+ // Unload after the close event has finished.Qt.callLater(() => {- window.destroy()+ if (mainLoader.item)+ mainLoader.item.releaseAndTeardown()+ mainLoader.setSource("")trayTrimTimer.restart()})}@@ -104,25 +111,18 @@ 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()- app.mainWindow.flash()+ if (app.mainWindow)+ app.mainWindow.flash()}}function onRemotePromptDeviceIdChanged() {if (AppController.remotePromptDeviceId.length > 0) {app.showMain()- app.mainWindow.flash()+ if (app.mainWindow)+ app.mainWindow.flash()}}}diff --git a/desktop/app/qml/MainWindow.qml b/desktop/app/qml/MainWindow.qmlindex 175ddc7..349b0e4 100644--- a/desktop/app/qml/MainWindow.qml+++ b/desktop/app/qml/MainWindow.qml@@ -6,10 +6,16 @@ import app.nectarlink// is paired it shows the welcome (pairing) screen instead.NativeWindow {id: window- signal closeRequestedreadonly property bool welcome: AppController.status === "ready" && !AppController.hasDevices- property string page: "home"+ property string page: AppController.currentPage.length > 0 ? AppController.currentPage : "home"+ onPageChanged: if (AppController.currentPage !== page) AppController.currentPage = page+ readonly property int currentDeviceIndex: DeviceList.count > 0+ ? Math.min(Math.max(0, AppController.currentDevice), DeviceList.count - 1) : 0+ readonly property string currentDeviceId: DeviceList.count > 0+ ? DeviceList.deviceIdAt(currentDeviceIndex) : ""+ readonly property string currentDeviceName: DeviceList.count > 0+ ? DeviceList.deviceNameAt(currentDeviceIndex) : ""width: 1100height: 720@@ -52,14 +58,8 @@ NativeWindow {darkFrame: Theme.darkcaptionHeight: Theme.topBarHeight- // QQuickWindow's `closing` is a revisioned member, hidden on subclasses- // in a 1.0 module; Connections reaches it through the meta-object.Connections {target: window- function onClosing(close) {- close.accepted = true- window.closeRequested()- }// Back from Settings, maybe with Windows notifications turned on.function onActiveChanged() {if (window.active)@@ -212,50 +212,45 @@ NativeWindow {width: parent.widthclip: true- HomePage {- id: homePage- anchors.fill: parent- active: window.page === "home"- onPairRequested: window.openPairing()- }- MessagesPage {- anchors.fill: parent- active: window.page === "messages"- deviceId: homePage.currentDeviceId- deviceName: homePage.currentDeviceName- }- CallsPage {+ Loader {+ id: pageLoaderanchors.fill: parent- active: window.page === "calls"- deviceId: homePage.currentDeviceId- deviceName: homePage.currentDeviceName- onTextRequested: (number, name) => {- Messages.startChat(homePage.currentDeviceId, number, name)- window.page = "messages"+ active: !window.welcome && AppController.status === "ready"+ source: {+ if (!active) return ""+ switch (window.page) {+ case "messages": return "qrc:/qt/qml/app/nectarlink/qml/pages/MessagesPage.qml"+ case "calls": return "qrc:/qt/qml/app/nectarlink/qml/pages/CallsPage.qml"+ case "photos": return "qrc:/qt/qml/app/nectarlink/qml/pages/PhotosPage.qml"+ case "deck": return "qrc:/qt/qml/app/nectarlink/qml/pages/DeckPage.qml"+ case "settings": return "qrc:/qt/qml/app/nectarlink/qml/pages/SettingsPage.qml"+ default: return "qrc:/qt/qml/app/nectarlink/qml/pages/HomePage.qml"+ }+ }+ onLoaded: {+ if ("deviceId" in item)+ item.deviceId = Qt.binding(() => window.currentDeviceId)+ if ("deviceName" in item)+ item.deviceName = Qt.binding(() => window.currentDeviceName)+ item.active = true+ if (item.pairRequested)+ item.pairRequested.connect(window.openPairing)+ if (item.textRequested) {+ item.textRequested.connect((number, name) => {+ Messages.startChat(window.currentDeviceId, number, name)+ window.page = "messages"+ })+ }}- }- PhotosPage {- anchors.fill: parent- active: window.page === "photos"- deviceId: homePage.currentDeviceId- deviceName: homePage.currentDeviceName- }- DeckPage {- anchors.fill: parent- active: window.page === "deck"- }- SettingsPage {- anchors.fill: parent- active: window.page === "settings"- onPairRequested: window.openPairing()}}}// ---- First run ----- WelcomePage {+ Loader {anchors.fill: parent- visible: window.welcome || AppController.status !== "ready"+ active: window.welcome || AppController.status !== "ready"+ source: active ? "qrc:/qt/qml/app/nectarlink/qml/pages/WelcomePage.qml" : ""}// ---- Overlays ----@@ -263,11 +258,17 @@ NativeWindow {id: pairingSheetcardWidth: 480onOpenedChanged: if (!opened) Pairing.cancel()- PairingPanel {+ Loader {+ id: pairingLoaderwidth: parent.width- running: pairingSheet.opened- onFinished: pairingSheet.close()- onCancelled: pairingSheet.close()+ active: pairingSheet.opened+ source: active ? "qrc:/qt/qml/app/nectarlink/qml/pages/PairingPanel.qml" : ""+ onLoaded: {+ item.width = Qt.binding(() => pairingLoader.width)+ item.running = Qt.binding(() => pairingSheet.opened)+ item.finished.connect(() => pairingSheet.close())+ item.cancelled.connect(() => pairingSheet.close())+ }}}@@ -350,10 +351,21 @@ NativeWindow {anchors.right: parent.right}- DoctorSheet { id: doctorSheet }+ Loader {+ id: doctorLoader+ anchors.fill: parent+ active: false+ source: active ? "qrc:/qt/qml/app/nectarlink/qml/components/DoctorSheet.qml" : ""+ onLoaded: item.open()+ }Connections {target: AppController- function onDoctorRequested() { doctorSheet.open() }+ function onDoctorRequested() {+ if (doctorLoader.active && doctorLoader.item)+ doctorLoader.item.open()+ else+ doctorLoader.active = true+ }}Toast { id: toast }diff --git a/desktop/app/qml/components/AppsSheet.qml b/desktop/app/qml/components/AppsSheet.qmlindex 055d8c9..1888288 100644--- a/desktop/app/qml/components/AppsSheet.qml+++ b/desktop/app/qml/components/AppsSheet.qml@@ -163,9 +163,13 @@ Sheet {required property var modelDatawidth: Math.min(96, Math.floor((recentSection.width - 20) / Math.max(1, sheet.recent.length)))height: 82+ activeFocusOnTab: trueAccessible.role: Accessible.ButtonAccessible.name: modelData.labelAccessible.onPressAction: sheet.launch(modelData)+ Keys.onReturnPressed: sheet.launch(modelData)+ Keys.onEnterPressed: sheet.launch(modelData)+ Keys.onSpacePressed: sheet.launch(modelData)Rectangle {anchors.fill: parent@@ -174,6 +178,14 @@ Sheet {color: Theme.surfaceContentopacity: recentTap.pressed ? 0.12 : (recentHover.hovered ? 0.06 : 0)}+ Rectangle {+ anchors.fill: parent+ anchors.margins: 2+ radius: Theme.radiusMd+ color: "transparent"+ border.width: recentCell.activeFocus ? 2 : 0+ border.color: Theme.primary+ }Column {anchors.centerIn: parentwidth: parent.width - 8@@ -223,7 +235,12 @@ Sheet {GridView {id: gridwidth: parent.width- height: Math.min(contentHeight, recentSection.visible ? 300 : 420)+ height: Math.min(+ contentHeight,+ recentSection.visible+ ? Math.max(160, Math.min(300, sheet.height - 340))+ : Math.max(200, Math.min(420, sheet.height - 210))+ )visible: sheet.loadState === "ready" && sheet.shown.length > 0clip: truemodel: sheet.shown@@ -235,9 +252,13 @@ Sheet {required property var modelDatawidth: grid.cellWidthheight: grid.cellHeight+ activeFocusOnTab: trueAccessible.role: Accessible.ButtonAccessible.name: modelData.labelAccessible.onPressAction: sheet.launch(modelData)+ Keys.onReturnPressed: sheet.launch(modelData)+ Keys.onEnterPressed: sheet.launch(modelData)+ Keys.onSpacePressed: sheet.launch(modelData)Rectangle {anchors.fill: parent@@ -246,6 +267,14 @@ Sheet {color: Theme.surfaceContentopacity: tap.pressed ? 0.12 : (hover.hovered ? 0.06 : 0)}+ Rectangle {+ anchors.fill: parent+ anchors.margins: 4+ radius: Theme.radiusMd+ color: "transparent"+ border.width: cell.activeFocus ? 2 : 0+ border.color: Theme.primary+ }Column {anchors.centerIn: parentwidth: parent.width - 12diff --git a/desktop/app/qml/components/Sheet.qml b/desktop/app/qml/components/Sheet.qmlindex acd0baa..64c9eea 100644--- a/desktop/app/qml/components/Sheet.qml+++ b/desktop/app/qml/components/Sheet.qml@@ -47,10 +47,19 @@ Item {// Swallow clicks so they don't reach the scrim.TapHandler {}- Item {- id: body+ Flickable {anchors.fill: parentanchors.margins: 24+ contentWidth: width+ contentHeight: body.childrenRect.height+ interactive: contentHeight > height+ boundsBehavior: Flickable.StopAtBounds+ clip: true+ Item {+ id: body+ width: parent.width+ height: childrenRect.height+ }}}diff --git a/desktop/app/qml/pages/CallsPage.qml b/desktop/app/qml/pages/CallsPage.qmlindex 407b63e..9336284 100644--- a/desktop/app/qml/pages/CallsPage.qml+++ b/desktop/app/qml/pages/CallsPage.qml@@ -117,6 +117,7 @@ Item {}onActiveChanged: if (active) load()+ Component.onCompleted: load()onDeviceIdChanged: {selectedContact = nullload()@@ -699,13 +700,14 @@ Item {required property var modelDatawidth: 84; height: 50radius: Theme.pill(height)+ activeFocusOnTab: truecolor: padTap.pressed? Theme.secondaryContainer: padHover.hovered? Qt.rgba(Theme.surfaceContent.r, Theme.surfaceContent.g, Theme.surfaceContent.b, 0.08): (Theme.graphite ? "transparent" : Theme.surfaceContainerHigh)- border.width: Theme.graphite ? 1 : 0- border.color: Theme.outlineVariant+ border.width: Theme.focusVisible(padKey) ? 2 : (Theme.graphite ? 1 : 0)+ border.color: Theme.focusVisible(padKey) ? Theme.primary : Theme.outlineVariantscale: padTap.pressed ? Theme.pressScale : 1Behavior on scale { SpringAnimation { spring: Theme.springSnappy; damping: Theme.dampingSnappy } }@@ -715,6 +717,13 @@ Item {PhoneCall.press(ch)}+ Keys.onPressed: (event) => {+ if (event.key === Qt.Key_Return || event.key === Qt.Key_Enter || event.key === Qt.Key_Space) {+ tapDigit(modelData.digit)+ event.accepted = true+ }+ }+Accessible.role: Accessible.ButtonAccessible.name: modelData.sub.length > 0 ? modelData.digit + " " + modelData.sub : modelData.digitAccessible.onPressAction: tapDigit(modelData.digit)@@ -811,6 +820,7 @@ Item {: qsTr("Incoming")height: dayHeader.height + 68+ activeFocusOnTab: trueAccessible.role: Accessible.ListItemAccessible.name: displayName + ", " + dirLabel + ", " + page.shortTime(entry.date)Accessible.onPressAction: selectCall()@@ -819,6 +829,13 @@ Item {dialInput.text = entry.number}+ Keys.onPressed: (event) => {+ if (event.key === Qt.Key_Return || event.key === Qt.Key_Enter || event.key === Qt.Key_Space) {+ selectCall()+ event.accepted = true+ }+ }+// Day separator ("Today", "Yesterday", date).Txt {id: dayHeader@@ -829,7 +846,7 @@ Item {leftPadding: 20role: "label"muted: true- text: page.dayLabel(row.entry.date)+ text: row.newDay ? page.dayLabel(row.entry.date) : ""}Item {@@ -845,6 +862,8 @@ Item {color: callHover.hovered? Qt.rgba(Theme.surfaceContent.r, Theme.surfaceContent.g, Theme.surfaceContent.b, 0.06): "transparent"+ border.width: Theme.focusVisible(row) ? 2 : 0+ border.color: Theme.primaryBehavior on color { ColorAnimation { duration: Theme.fadeFast } }}@@ -960,6 +979,7 @@ Item {&& (!previous || previous.starred !== contact.starred)height: sectionLabel.height + 68+ activeFocusOnTab: trueAccessible.role: Accessible.ListItemAccessible.name: contact.name + (primaryNumber.length > 0 ? ", " + primaryNumber : "")Accessible.onPressAction: pickContact()@@ -970,6 +990,13 @@ Item {dialInput.text = primaryNumber}+ Keys.onPressed: (event) => {+ if (event.key === Qt.Key_Return || event.key === Qt.Key_Enter || event.key === Qt.Key_Space) {+ pickContact()+ event.accepted = true+ }+ }+Row {id: sectionLabelx: 20@@ -1004,6 +1031,8 @@ Item {color: crow.selected ? Theme.secondaryContainer: contactHover.hovered ? Qt.rgba(Theme.surfaceContent.r, Theme.surfaceContent.g, Theme.surfaceContent.b, 0.06): "transparent"+ border.width: Theme.focusVisible(crow) ? 2 : 0+ border.color: Theme.primaryBehavior on color { ColorAnimation { duration: Theme.fadeFast } }}diff --git a/desktop/app/qml/pages/HomePage.qml b/desktop/app/qml/pages/HomePage.qmlindex 12913c5..523a753 100644--- a/desktop/app/qml/pages/HomePage.qml+++ b/desktop/app/qml/pages/HomePage.qml@@ -9,7 +9,7 @@ import app.nectarlinkItem {id: pageproperty bool active: true- property int current: 0+ property int current: AppController.currentDevice// The device shown, for dropped files.property string currentDeviceIdproperty string currentDeviceName@@ -24,10 +24,17 @@ Item {Behavior on y { SpringAnimation { spring: Theme.springGentle; damping: Theme.dampingGentle } }}- onCurrentChanged: if (current >= DeviceList.count) current = 0+ onCurrentChanged: {+ if (current >= DeviceList.count) current = 0+ if (AppController.currentDevice !== current)+ AppController.currentDevice = current+ }Connections {target: DeviceList- function onCountChanged() { if (page.current >= DeviceList.count) page.current = Math.max(0, DeviceList.count - 1) }+ function onCountChanged() {+ if (page.current >= DeviceList.count)+ page.current = Math.max(0, DeviceList.count - 1)+ }}function relativeTime(unixSeconds) {diff --git a/desktop/app/qml/pages/MessagesPage.qml b/desktop/app/qml/pages/MessagesPage.qmlindex 3336f29..5ee862c 100644--- a/desktop/app/qml/pages/MessagesPage.qml+++ b/desktop/app/qml/pages/MessagesPage.qml@@ -122,6 +122,8 @@ Item {}// Leaving the page closes the open conversation.onActiveChanged: active ? load() : closeChat()+ Component.onCompleted: load()+ Component.onDestruction: Messages.closeThread()Shortcut {sequence: "Esc"@@ -539,6 +541,7 @@ Item {visible: !!page.openThreadclip: truespacing: 6+ cacheBuffer: 960// A short conversation sits at the bottom, by the box.topMargin: Math.max(16, height - contentHeight - bottomMargin)bottomMargin: 8@@ -546,13 +549,31 @@ Item {model: page.messages// The latest at the bottom; scrolling up loads older ones.property int lastCount: 0+ property string lastThreadId: ""+ property real savedBottomOffset: -1onCountChanged: {- const grewAtTop = count > lastCount && lastCount > 0 && Messages.loadingOlder === false && atYBeginning- if (!grewAtTop)+ const threadSwitched = Messages.thread !== lastThreadId+ lastThreadId = Messages.thread+ if (threadSwitched || lastCount === 0) {+ savedBottomOffset = -1Qt.callLater(positionViewAtEnd)+ } else if (savedBottomOffset >= 0 && count > lastCount) {+ const off = savedBottomOffset+ savedBottomOffset = -1+ Qt.callLater(() => {+ contentY = Math.max(originY, contentHeight - off)+ })+ } else if (count > lastCount) {+ Qt.callLater(positionViewAtEnd)+ }lastCount = count}- onAtYBeginningChanged: if (atYBeginning && Messages.more && count > 0) Messages.loadOlder()+ onAtYBeginningChanged: {+ if (atYBeginning && Messages.more && count > 0 && !Messages.loadingOlder) {+ savedBottomOffset = contentHeight - contentY+ Messages.loadOlder()+ }+ }header: Item {width: messageList.widthheight: Messages.loadingOlder ? 40 : 0@@ -686,6 +707,7 @@ Item {property var threadreadonly property bool selected: thread.id === Messages.threadheight: 72+ activeFocusOnTab: trueAccessible.role: Accessible.ListItemAccessible.name: thread.title + ". " + thread.snippetAccessible.onPressAction: open()@@ -693,6 +715,12 @@ Item {page.composing = falseMessages.openThread(thread.id)}+ Keys.onPressed: (event) => {+ if (event.key === Qt.Key_Return || event.key === Qt.Key_Enter || event.key === Qt.Key_Space) {+ open()+ event.accepted = true+ }+ }Rectangle {anchors.fill: parent@@ -702,6 +730,8 @@ Item {color: row.selected ? Theme.secondaryContainer: rowHover.hovered ? Qt.rgba(Theme.surfaceContent.r, Theme.surfaceContent.g, Theme.surfaceContent.b, 0.06): "transparent"+ border.width: Theme.focusVisible(row) ? 2 : 0+ border.color: Theme.primaryBehavior on color { ColorAnimation { duration: Theme.fadeFast } }}Item {@@ -802,7 +832,16 @@ Item {property var previous: nullreadonly property bool mine: message.outgoingreadonly property real maxWidth: Math.min(width * 0.72, 520)- readonly property bool newDay: !previous || new Date(previous.date).toDateString() !== new Date(message.date).toDateString()+ readonly property bool hasUrl: message.body.indexOf("http://") >= 0 || message.body.indexOf("https://") >= 0+ readonly property bool newDay: {+ if (!previous)+ return true+ if (Math.abs(message.date - previous.date) < 600000)+ return false+ const d1 = new Date(previous.date)+ const d2 = new Date(message.date)+ return d1.getFullYear() !== d2.getFullYear() || d1.getMonth() !== d2.getMonth() || d1.getDate() !== d2.getDate()+ }readonly property bool showSender: !!message.sender && (!previous || previous.sender !== message.sender || newDay)height: day.height + sender.height + content.height + meta.height + codeRow.height + 4@@ -818,7 +857,7 @@ Item {horizontalAlignment: Text.AlignHCenterrole: "label"muted: true- text: page.dayLabel(bubble.message.date)+ text: bubble.newDay ? page.dayLabel(bubble.message.date) : ""}// Who wrote it, in a group.Txt {@@ -877,12 +916,13 @@ Item {x: 14width: Math.min(implicitWidth, bubble.maxWidth - 28)visible: bubble.message.body.length > 0 || bubble.message.attachments > 0- text: bubble.message.body.length > 0 ? page.linkified(bubble.message.body)+ text: bubble.message.body.length > 0+ ? (bubble.hasUrl ? page.linkified(bubble.message.body) : bubble.message.body): qsTr("Attachment (open it on the phone)")readOnly: trueselectByMouse: truewrapMode: TextEdit.Wrap- textFormat: bubble.message.body.length > 0 ? TextEdit.RichText : TextEdit.PlainText+ textFormat: bubble.hasUrl ? TextEdit.RichText : TextEdit.PlainTextonLinkActivated: (link) => Qt.openUrlExternally(link)HoverHandler { cursorShape: text.hoveredLink.length > 0 ? Qt.PointingHandCursor : Qt.IBeamCursor }font.family: Theme.fontUidiff --git a/desktop/app/qml/pages/PairingPanel.qml b/desktop/app/qml/pages/PairingPanel.qmlindex 6612fdd..31d8225 100644--- a/desktop/app/qml/pages/PairingPanel.qml+++ b/desktop/app/qml/pages/PairingPanel.qml@@ -45,14 +45,14 @@ Item {Column {id: contentwidth: parent.width- spacing: 18+ spacing: 14// ---- Header ----Txt {width: parent.widthhorizontalAlignment: Text.AlignHCenterrole: "displaySmall"- size: 26+ size: 24wrapMode: Text.WordWraptext: {switch (panel.state_) {@@ -67,12 +67,12 @@ Item {// ---- QR code ----Column {width: parent.width- spacing: 14+ spacing: 12visible: (panel.state_ === "hosting" || panel.state_ === "starting" || panel.state_ === "idle") && !panel.showNearbyItem {anchors.horizontalCenter: parent.horizontalCenter- width: 236; height: 236+ width: 216; height: 216QrCode {anchors.fill: parentvisible: panel.state_ === "hosting"diff --git a/desktop/app/qml/pages/PhotosPage.qml b/desktop/app/qml/pages/PhotosPage.qmlindex 9f0ad7a..79a0adc 100644--- a/desktop/app/qml/pages/PhotosPage.qml+++ b/desktop/app/qml/pages/PhotosPage.qml@@ -54,10 +54,13 @@ Item {return sum > 0 ? sum : Photos.count}- function dayKey(ms) {- if (!ms || ms <= 0) return ""- const d = new Date(ms)- return d.getFullYear() + "-" + (d.getMonth() + 1) + "-" + d.getDate()+ function sameDay(a, b) {+ if (!a || !b || Math.abs(a - b) >= 86400000) return false+ const da = new Date(a)+ const db = new Date(b)+ return da.getDate() === db.getDate()+ && da.getMonth() === db.getMonth()+ && da.getFullYear() === db.getFullYear()}function dayLabel(ms) {@@ -114,10 +117,8 @@ Item {const from = Math.min(lastClickedIndex, index)const to = Math.max(lastClickedIndex, index)for (let r = from; r <= to; r++) {- try {- const item = JSON.parse(Photos.itemAt(r))- if (item && item.id) next[item.id] = true- } catch (e) {}+ const rowId = Photos.idAt(r)+ if (rowId.length > 0) next[rowId] = true}} else if (next[id]) {delete next[id]@@ -133,10 +134,8 @@ Item {const next = {}const n = Math.min(Photos.count, 500)for (let r = 0; r < n; r++) {- try {- const item = JSON.parse(Photos.itemAt(r))- if (item && item.id) next[item.id] = true- } catch (e) {}+ const rowId = Photos.idAt(r)+ if (rowId.length > 0) next[rowId] = true}selectedMap = nextselectedIds = Object.keys(next)@@ -177,6 +176,7 @@ Item {}onActiveChanged: if (active) load()+ Component.onCompleted: load()onDeviceIdChanged: {clearSelection()viewerIndex = -1@@ -284,7 +284,7 @@ Item {Item {id: albumPanevisible: !page.phoneOffline- width: 248+ width: page.width < 760 ? 200 : 248height: parent.heightItem {@@ -367,6 +367,7 @@ Item {anchors.left: albumPane.rightanchors.right: parent.rightheight: parent.height+ readonly property bool compactBar: width < 540// Top toolbar: album info OR multi-select actions.Item {@@ -376,16 +377,21 @@ Item {// Normal mode header (no selection active).Row {+ id: normalLeftRowanchors.left: parent.leftanchors.leftMargin: 20+ anchors.right: normalRightRow.visible ? normalRightRow.left : parent.right+ anchors.rightMargin: 12anchors.verticalCenter: parent.verticalCenterspacing: 10visible: page.selectedCount === 0 && !page.selectMode+ clip: trueTxt {anchors.verticalCenter: parent.verticalCenterrole: "title"size: 16+ elide: Text.ElideRighttext: page.currentAlbumName}Txt {@@ -398,6 +404,7 @@ Item {}Row {+ id: normalRightRowanchors.right: parent.rightanchors.rightMargin: 16anchors.verticalCenter: parent.verticalCenter@@ -407,7 +414,13 @@ Item {Chip {anchors.verticalCenter: parent.verticalCentericonPath: Icons.folder- text: Photos.saveFolder+ text: {+ const f = Photos.saveFolder || ""+ if (!gridPane.compactBar) return f+ const parts = f.split(/[\\/]/)+ return parts.length > 0 && parts[parts.length - 1].length > 0+ ? parts[parts.length - 1] : f+ }TapHandler { onTapped: defaultFolderPicker.open() }HoverHandler { cursorShape: Qt.PointingHandCursor }}@@ -442,10 +455,11 @@ Item {size: 15text: page.selectedCount > 0? qsTr("%1 selected").arg(page.selectedCount)- : qsTr("Click items to select")+ : (gridPane.compactBar ? qsTr("Select items") : qsTr("Click items to select"))}Button {anchors.verticalCenter: parent.verticalCenter+ visible: !gridPane.compactBar || page.selectedCount === 0variant: "text"size: "sm"text: qsTr("Select all")@@ -632,16 +646,15 @@ Item {}// Current top-visible item's day label, shown in the sticky day banner.+ readonly property int topVisibleRow: Math.max(+ 0,+ Math.floor(Math.max(0, contentY + 20) / Math.max(1, cellHeight)) * columns+ )readonly property string stickyDay: {if (Photos.revision < 0 || Photos.count === 0) return ""- const idx = indexAt(20, Math.max(0, contentY + 20))- const row = idx >= 0 ? idx : 0- try {- const item = JSON.parse(Photos.itemAt(row))- return item ? page.dayLabel(item.date) : ""- } catch (e) {- return ""- }+ const row = Math.min(topVisibleRow, Photos.count - 1)+ const ms = Photos.dateAt(row)+ return ms > 0 ? page.dayLabel(ms) : ""}delegate: PhotoTile {@@ -916,9 +929,13 @@ Item {signal clickedheight: 54+ activeFocusOnTab: trueAccessible.role: Accessible.ButtonAccessible.name: albumRow.titleAccessible.onPressAction: albumRow.clicked()+ Keys.onReturnPressed: albumRow.clicked()+ Keys.onEnterPressed: albumRow.clicked()+ Keys.onSpacePressed: albumRow.clicked()Rectangle {anchors.fill: parent@@ -932,8 +949,8 @@ Item {: albumHover.hovered? Qt.rgba(Theme.surfaceContent.r, Theme.surfaceContent.g, Theme.surfaceContent.b, 0.06): "transparent"- border.width: Theme.graphite && albumRow.selected ? 1 : 0- border.color: Theme.surfaceContent+ border.width: albumRow.activeFocus ? 2 : (Theme.graphite && albumRow.selected ? 1 : 0)+ border.color: albumRow.activeFocus ? Theme.primary : Theme.surfaceContentItem {id: coverBox@@ -1010,17 +1027,23 @@ Item {property string requestedThumbId: ""readonly property bool selected: page.selectedCount >= 0 && page.isSelected(itemId)- readonly property bool firstOfDay: index === 0 || page.dayKey(date) !== page.dayKey(prevDate)+ readonly property bool firstOfDay: index === 0 || !page.sameDay(date, prevDate)- Accessible.role: Accessible.Button- Accessible.name: tile.name- Accessible.onPressAction: {+ function activateTile() {if (page.selectMode || page.selectedCount > 0)page.toggleSelect(tile.itemId, tile.index, false)elsepage.openViewer(tile.index)}+ activeFocusOnTab: true+ Accessible.role: Accessible.Button+ Accessible.name: tile.name+ Accessible.onPressAction: tile.activateTile()+ Keys.onReturnPressed: tile.activateTile()+ Keys.onEnterPressed: tile.activateTile()+ Keys.onSpacePressed: page.toggleSelect(tile.itemId, tile.index, false)+function checkThumb() {if (thumb.length === 0 && itemId.length > 0) {if (requestedThumbId !== itemId) {@@ -1048,8 +1071,8 @@ Item {anchors.margins: 4radius: Theme.radiusSmcolor: Theme.surfaceContainerHigh- border.width: tile.selected ? 3 : (Theme.graphite ? 1 : 0)- border.color: tile.selected ? Theme.primary : Theme.outlineVariant+ border.width: tile.selected ? 3 : (tile.activeFocus ? 2 : (Theme.graphite ? 1 : 0))+ border.color: (tile.selected || tile.activeFocus) ? Theme.primary : Theme.outlineVariantclip: trueIcon {@@ -1100,7 +1123,8 @@ Item {role: "caption"size: 11color: "#ffffff"- text: page.shortDayLabel(tile.date)+ text: (tile.firstOfDay && tile.index > 0 && tile.date > 0)+ ? page.shortDayLabel(tile.date) : ""}}@@ -1138,7 +1162,7 @@ Item {role: "caption"size: 11color: "#ffffff"- text: page.formatVideoDuration(tile.duration)+ text: tile.isVideo ? page.formatVideoDuration(tile.duration) : ""}}diff --git a/desktop/app/qml/pages/SettingsPage.qml b/desktop/app/qml/pages/SettingsPage.qmlindex 033f583..c31e307 100644--- a/desktop/app/qml/pages/SettingsPage.qml+++ b/desktop/app/qml/pages/SettingsPage.qml@@ -42,12 +42,76 @@ Item {remote_files: qsTr("Browse this PC's files while away")})+ readonly property var toggleIcons: ({+ notifications: Icons.bell,+ messages: Icons.messages,+ calls: Icons.call,+ contacts: Icons.person,+ clipboard: Icons.clipboard,+ files: Icons.send,+ recordings: Icons.mic,+ media: Icons.music,+ photos: Icons.photo,+ toggles: Icons.phone,+ pc_actions: Icons.lock,+ mirroring: Icons.mirror,+ webcam: Icons.video,+ storage: Icons.folder,+ remote_input: Icons.deck,+ commands: Icons.terminal,+ remote_files: Icons.globe+ })+readonly property var toggleDescriptions: ({webcam: qsTr("Use this phone's camera as a webcam on this PC."),storage: qsTr("Show this phone's storage in File Explorer so you can browse, open and drop in files."),commands: qsTr("Lets this phone trigger Deck tiles that run shell commands configured on this PC. Off by default — only enable for a phone you control.")})+ readonly property var toggleGroups: [+ {+ title: qsTr("Calls, messages & notifications"),+ keys: ["notifications", "messages", "calls", "contacts"]+ },+ {+ title: qsTr("Files, photos & clipboard"),+ keys: ["clipboard", "files", "photos", "recordings", "storage", "remote_files"]+ },+ {+ title: qsTr("Screen, camera & control"),+ keys: ["media", "toggles", "mirroring", "webcam", "pc_actions", "remote_input", "commands"]+ }+ ]++ function groupTogglesFor(allToggles, groupKeys, isLastGroup, allGroupKeys) {+ if (!allToggles || allToggles.length === 0)+ return []+ const res = []+ for (let i = 0; i < groupKeys.length; i++) {+ const k = groupKeys[i]+ for (let j = 0; j < allToggles.length; j++) {+ if (allToggles[j].name === k) {+ res.push(allToggles[j])+ break+ }+ }+ }+ if (isLastGroup) {+ for (let j = 0; j < allToggles.length; j++) {+ const name = allToggles[j].name+ if (allGroupKeys.indexOf(name) === -1)+ res.push(allToggles[j])+ }+ }+ return res+ }++ readonly property var allGroupedKeys: [+ "notifications", "messages", "calls", "contacts",+ "clipboard", "files", "photos", "recordings", "storage", "remote_files",+ "media", "toggles", "mirroring", "webcam", "pc_actions", "remote_input", "commands"+ ]+FolderDialog {id: recordingsFolderPickertitle: qsTr("Save recordings in")@@ -88,7 +152,7 @@ Item {Divider { width: parent.width }ListRow {width: parent.width- iconPath: Icons.info+ iconPath: Icons.moontitle: qsTr("Mode")Segmented {options: [@@ -435,60 +499,58 @@ Item {}}- // ---- Connection ----- Txt { text: qsTr("Connection"); role: "label"; muted: true }+ // ---- Connection & this PC ----+ Txt { text: qsTr("Connection & this PC"); role: "label"; muted: true }Card {width: parent.width- ListRow {- width: parent.width- iconPath: Icons.wifi- title: qsTr("Connection Doctor")- description: qsTr("Finds what keeps your phone from reaching this PC (the firewall, the network, a VPN) and fixes what it can.")- Button {- variant: "tonal"- size: "sm"- text: qsTr("Check")- onClicked: AppController.runDoctor()- }- }- }-- // ---- This PC ----- Txt { text: qsTr("This PC"); role: "label"; muted: true }- Card {- width: parent.width- ListRow {+ Column {width: parent.width- iconPath: Icons.power- title: qsTr("Wake from your phone")- description: {- const adapter = AppController.wakeAdapter- const state = AppController.wakeState- const wired = AppController.wakeWired- if (state === "none" || adapter.length === 0)- return qsTr("No active Ethernet or Wi-Fi adapter found. Connect this PC to your network so your phone can learn how to wake it.")- if (state === "enabled") {- return wired- ? qsTr("%1 · Wake on Magic Packet is on. If this PC still won't wake from sleep or shutdown, check that Wake-on-LAN is enabled in BIOS/UEFI.").arg(adapter)- : qsTr("%1 · Wake on Magic Packet is on. Wi-Fi wake usually works from sleep, not full shutdown; use Ethernet for shutdown wake.").arg(adapter)+ ListRow {+ width: parent.width+ iconPath: Icons.wifi+ title: qsTr("Connection Doctor")+ description: qsTr("Finds what keeps your phone from reaching this PC (the firewall, the network, a VPN) and fixes what it can.")+ Button {+ variant: "tonal"+ size: "sm"+ text: qsTr("Check")+ onClicked: AppController.runDoctor()}- 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)}- Row {- spacing: 6- StatusDot {- anchors.verticalCenter: parent.verticalCenter- online: AppController.wakeState === "enabled"+ Divider { width: parent.width }+ ListRow {+ width: parent.width+ iconPath: Icons.power+ title: qsTr("Wake from your phone")+ description: {+ const adapter = AppController.wakeAdapter+ const state = AppController.wakeState+ const wired = AppController.wakeWired+ if (state === "none" || adapter.length === 0)+ return qsTr("No active Ethernet or Wi-Fi adapter found. Connect this PC to your network so your phone can learn how to wake it.")+ if (state === "enabled") {+ return wired+ ? qsTr("%1 · Wake on Magic Packet is on. If this PC still won't wake from sleep or shutdown, check that Wake-on-LAN is enabled in BIOS/UEFI.").arg(adapter)+ : qsTr("%1 · Wake on Magic Packet is on. Wi-Fi wake usually works from sleep, not full shutdown; use Ethernet for shutdown wake.").arg(adapter)+ }+ const wifiNote = wired ? "" : qsTr(" Wi-Fi wake rarely works from shutdown.")+ return qsTr("%1 · To wake this PC while it sleeps or is shut down, enable Wake on Magic Packet in Device Manager → Network adapters → %1 → Properties (Advanced tab → Wake on Magic Packet → Enabled; Power Management tab → Allow this device to wake the computer, Only allow a magic packet), and enable Wake-on-LAN in BIOS/UEFI.%2").arg(adapter).arg(wifiNote)}- 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")+ 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")+ }}}}@@ -600,7 +662,7 @@ Item {Column {width: parent.width- spacing: 4+ spacing: 14Row {width: parent.widthspacing: 12@@ -608,11 +670,19 @@ Item {Column {anchors.verticalCenter: parent.verticalCenterwidth: parent.width - 36 - 12 - unpair.width - 12- Txt { width: parent.width; text: deviceCard.name; role: "title" }- Txt {- text: deviceCard.online ? qsTr("Connected") : qsTr("Not connected")- role: "bodySmall"- muted: true+ Txt { width: parent.width; text: deviceCard.name; role: "title"; elide: Text.ElideRight }+ Row {+ spacing: 6+ StatusDot {+ anchors.verticalCenter: parent.verticalCenter+ online: deviceCard.online+ }+ Txt {+ anchors.verticalCenter: parent.verticalCenter+ text: deviceCard.online ? qsTr("Connected") : qsTr("Not connected")+ role: "bodySmall"+ muted: true+ }}}Button {@@ -629,30 +699,74 @@ Item {}}}- Item { width: 1; height: 8 }Repeater {- model: deviceCard.toggles- delegate: ListRow {+ model: page.toggleGroups+ delegate: Column {+ id: groupColrequired property var modelData+ required property int index+ readonly property var groupItems: page.groupTogglesFor(+ deviceCard.toggles,+ modelData.keys,+ index === page.toggleGroups.length - 1,+ page.allGroupedKeys+ )+ visible: groupItems.length > 0width: parent.width- title: page.toggleNames[modelData.name] || modelData.name- description: page.toggleDescriptions[modelData.name] || ""- Row {- spacing: 10- Button {- visible: modelData.name === "storage" && modelData.on- anchors.verticalCenter: parent.verticalCenter- variant: "tonal"- size: "sm"- iconPath: Icons.folder- text: qsTr("Open in File Explorer")- onClicked: AppController.openPhoneStorage(deviceCard.deviceId)- }- Toggle {- anchors.verticalCenter: parent.verticalCenter- label: page.toggleNames[modelData.name] || modelData.name- checked: modelData.on- onToggled: (on) => AppController.setDeviceToggle(deviceCard.deviceId, modelData.name, on)+ spacing: 6+ Txt {+ text: groupCol.modelData.title+ role: "label"+ muted: true+ }+ Rectangle {+ width: parent.width+ height: groupInnerCol.height + 8+ radius: Theme.radiusMd+ color: Theme.surfaceContainerLow+ border.width: 1+ border.color: Theme.outlineVariant+ Column {+ id: groupInnerCol+ x: 14+ y: 4+ width: parent.width - 28+ Repeater {+ model: groupCol.groupItems+ delegate: Column {+ required property var modelData+ required property int index+ width: parent.width+ Divider {+ width: parent.width+ visible: index > 0+ }+ ListRow {+ width: parent.width+ iconPath: page.toggleIcons[modelData.name] || ""+ title: page.toggleNames[modelData.name] || modelData.name+ description: page.toggleDescriptions[modelData.name] || ""+ Row {+ spacing: 10+ Button {+ visible: modelData.name === "storage" && modelData.on+ anchors.verticalCenter: parent.verticalCenter+ variant: "tonal"+ size: "sm"+ iconPath: Icons.folder+ text: qsTr("Open in File Explorer")+ onClicked: AppController.openPhoneStorage(deviceCard.deviceId)+ }+ Toggle {+ anchors.verticalCenter: parent.verticalCenter+ label: page.toggleNames[modelData.name] || modelData.name+ checked: modelData.on+ onToggled: (on) => AppController.setDeviceToggle(deviceCard.deviceId, modelData.name, on)+ }+ }+ }+ }+ }}}}diff --git a/desktop/app/src/bridge/app.rs b/desktop/app/src/bridge/app.rsindex ddd2fa2..5002ddc 100644--- a/desktop/app/src/bridge/app.rs+++ b/desktop/app/src/bridge/app.rs@@ -88,6 +88,10 @@ pub mod qobject {#[qproperty(QString, wake_state)]/// True when `wake_adapter` is wired Ethernet, false for Wi-Fi or none.#[qproperty(bool, wake_wired)]+ /// Selected navigation page and device index, kept in Rust across tray+ /// unloads so the window can be destroyed in the background.+ #[qproperty(QString, current_page)]+ #[qproperty(i32, current_device)]type AppController = super::AppControllerRust;/// Asks a paired device to ring (or stop).@@ -215,6 +219,8 @@ pub struct AppControllerRust {wake_adapter: QString,wake_state: QString,wake_wired: bool,+ current_page: QString,+ current_device: i32,tray: Option<tray::Tray>,}@@ -319,6 +325,7 @@ pub(crate) fn describe(error: &Error) -> String {impl cxx_qt::Initialize for qobject::AppController {fn initialize(mut self: Pin<&mut Self>) {self.as_mut().set_version(QString::from(env!("CARGO_PKG_VERSION")));+ self.as_mut().set_current_page(QString::from("home"));self.as_mut().set_can_update(crate::updater::can_update());self.as_mut().refresh_appearance();let qt = self.qt_thread();@@ -715,6 +722,9 @@ impl qobject::AppController {pub fn trim_working_set(&self) {crate::webcam::release_idle_resources();+ crate::photos::release_idle_resources();+ crate::messages::release_idle_resources();+ crate::calls::release_idle_resources();super::native::ffi::trim_memory_caches();}}diff --git a/desktop/app/src/bridge/devices.rs b/desktop/app/src/bridge/devices.rsindex f94629f..3b69bb8 100644--- a/desktop/app/src/bridge/devices.rs+++ b/desktop/app/src/bridge/devices.rs@@ -83,6 +83,12 @@ pub mod qobject {#[qinvokable]#[cxx_name = "rowOf"]fn row_of(self: &DeviceList, device_id: &QString) -> i32;+ #[qinvokable]+ #[cxx_name = "deviceIdAt"]+ fn device_id_at(self: &DeviceList, row: i32) -> QString;+ #[qinvokable]+ #[cxx_name = "deviceNameAt"]+ fn device_name_at(self: &DeviceList, row: i32) -> QString;}unsafe extern "C++" {@@ -232,6 +238,22 @@ impl qobject::DeviceList {let id = String::from(device_id);self.rows.iter().position(|d| d.id.to_string() == id).map_or(-1, |r| r as i32)}++ pub fn device_id_at(&self, row: i32) -> QString {+ usize::try_from(row)+ .ok()+ .and_then(|i| self.rows.get(i))+ .map(|d| QString::from(&d.id.to_string()))+ .unwrap_or_default()+ }++ pub fn device_name_at(&self, row: i32) -> QString {+ usize::try_from(row)+ .ok()+ .and_then(|i| self.rows.get(i))+ .map(|d| QString::from(&d.info.name))+ .unwrap_or_default()+ }}#[cfg(test)]diff --git a/desktop/app/src/bridge/mod.rs b/desktop/app/src/bridge/mod.rsindex ee4a05f..ea6d3c6 100644--- a/desktop/app/src/bridge/mod.rs+++ b/desktop/app/src/bridge/mod.rs@@ -89,32 +89,40 @@ pub(crate) enum Edit {/// so QML delegates keep their state and animate. A row that moved (e.g. an/// updated notification going to the top) is removed and inserted again;/// the model is never reset.-pub(crate) fn diff<T: PartialEq, K: PartialEq>(old: &[T], new: &[T], key: impl Fn(&T) -> K) -> Vec<Edit> {+pub(crate) fn diff<T: PartialEq, K: Eq + std::hash::Hash>(+ old: &[T],+ new: &[T],+ key: impl Fn(&T) -> K,+) -> Vec<Edit> {let mut edits = Vec::new();+ if old.is_empty() && new.is_empty() {+ return edits;+ }+ let new_keys: Vec<K> = new.iter().map(&key).collect();+ let new_set: std::collections::HashSet<&K> = new_keys.iter().collect();// Rows as they are after each edit so far.- let mut rows: Vec<&T> = old.iter().collect();+ let mut rows: Vec<(K, &T)> = old.iter().map(|r| (key(r), r)).collect();// Removals first, from the end so earlier indices stay valid.for row in (0..rows.len()).rev() {- if !new.iter().any(|n| key(n) == key(rows[row])) {+ if !new_set.contains(&rows[row].0) {rows.remove(row);edits.push(Edit::Remove(row));}}- for (row, item) in new.iter().enumerate() {- let k = key(item);- if rows.get(row).is_some_and(|r| key(r) == k) {- if *rows[row] != *item {- rows[row] = item;+ for (row, (item, k)) in new.iter().zip(new_keys).enumerate() {+ if rows.get(row).is_some_and(|(rk, _)| *rk == k) {+ if *rows[row].1 != *item {+ rows[row].1 = item;edits.push(Edit::Change(row));}continue;}// Moved here from further down: take it out there first.- if let Some(from) = rows.iter().skip(row).position(|r| key(r) == k).map(|i| i + row) {+ if let Some(from) = rows.iter().skip(row).position(|(rk, _)| *rk == k).map(|i| i + row) {rows.remove(from);edits.push(Edit::Remove(from));}- rows.insert(row, item);+ rows.insert(row, (k, item));edits.push(Edit::Insert(row));}editsdiff --git a/desktop/app/src/bridge/native.rs b/desktop/app/src/bridge/native.rsindex ea1d8a5..bc97966 100644--- a/desktop/app/src/bridge/native.rs+++ b/desktop/app/src/bridge/native.rs@@ -6,6 +6,8 @@ pub mod ffi {unsafe extern "C++" {include!("app_helpers.h");include!("video_view.h");+ include!("cxx-qt-lib/qqmlapplicationengine.h");+ type QQmlApplicationEngine = cxx_qt_lib::QQmlApplicationEngine;/// The latest picture of a video stream (32-bit BGRX rows), for/// `VideoView`s showing it. Any thread.@@ -23,5 +25,8 @@ pub mod ffi {fn load_bundled_fonts() -> i32;/// Clears Qt pixmap caches and trims the process working set.fn trim_memory_caches();+ /// Records the active QML engine so `trim_memory_caches` can run GC and+ /// clear component caches.+ fn register_qml_app_engine(engine: Pin<&mut QQmlApplicationEngine>);}}diff --git a/desktop/app/src/bridge/photos.rs b/desktop/app/src/bridge/photos.rsindex b1e40cb..58f3936 100644--- a/desktop/app/src/bridge/photos.rs+++ b/desktop/app/src/bridge/photos.rs@@ -134,6 +134,12 @@ pub mod qobject {#[qinvokable]#[cxx_name = "itemAt"]fn item_at(self: &Photos, row: i32) -> QString;+ #[qinvokable]+ #[cxx_name = "idAt"]+ fn id_at(self: &Photos, row: i32) -> QString;+ #[qinvokable]+ #[cxx_name = "dateAt"]+ fn date_at(self: &Photos, row: i32) -> f64;}impl cxx_qt::Threading for Photos {}@@ -234,32 +240,73 @@ impl qobject::Photos {self.as_mut().set_save_folder(QString::from(&view.save_folder));let root = QModelIndex::default();- for edit in diff(&self.rows, &view.rows, |r| r.id.clone()) {- match edit {- Edit::Remove(row) => {- let r = row as i32;- // SAFETY: row exists; begin/end are balanced.- unsafe {- self.as_mut().begin_remove_rows(&root, r, r);- self.as_mut().rust_mut().rows.remove(row);- self.as_mut().end_remove_rows();- }- }- Edit::Insert(row) => {- let r = row as i32;- // SAFETY: row <= len; begin/end are balanced.- unsafe {- self.as_mut().begin_insert_rows(&root, r, r);- self.as_mut().rust_mut().rows.insert(row, view.rows[row].clone());- self.as_mut().end_insert_rows();- }+ if view.rows.is_empty() {+ if !self.rows.is_empty() {+ let last = (self.rows.len() - 1) as i32;+ // SAFETY: 0..=last exists; begin/end are balanced.+ unsafe {+ self.as_mut().begin_remove_rows(&root, 0, last);+ self.as_mut().rust_mut().rows = Vec::new();+ self.as_mut().end_remove_rows();}- Edit::Change(row) => {+ }+ } else if self.rows.is_empty() {+ let last = (view.rows.len() - 1) as i32;+ // SAFETY: 0..=last is valid for empty model; begin/end are balanced.+ unsafe {+ self.as_mut().begin_insert_rows(&root, 0, last);+ self.as_mut().rust_mut().rows = view.rows;+ self.as_mut().end_insert_rows();+ }+ } else if view.rows.len() >= self.rows.len()+ && self.rows.iter().zip(&view.rows).all(|(a, b)| a.id == b.id)+ {+ let old_len = self.rows.len();+ for row in 0..old_len {+ if self.rows[row] != view.rows[row] {self.as_mut().rust_mut().rows[row] = view.rows[row].clone();let index = self.index(row as i32, 0, &root);self.as_mut().data_changed(&index, &index, &QList::default());}}+ if view.rows.len() > old_len {+ let first = old_len as i32;+ let last = (view.rows.len() - 1) as i32;+ // SAFETY: first..=last appends to end; begin/end are balanced.+ unsafe {+ self.as_mut().begin_insert_rows(&root, first, last);+ self.as_mut().rust_mut().rows.extend_from_slice(&view.rows[old_len..]);+ self.as_mut().end_insert_rows();+ }+ }+ } else {+ for edit in diff(&self.rows, &view.rows, |r| r.id.clone()) {+ match edit {+ Edit::Remove(row) => {+ let r = row as i32;+ // SAFETY: row exists; begin/end are balanced.+ unsafe {+ self.as_mut().begin_remove_rows(&root, r, r);+ self.as_mut().rust_mut().rows.remove(row);+ self.as_mut().end_remove_rows();+ }+ }+ Edit::Insert(row) => {+ let r = row as i32;+ // SAFETY: row <= len; begin/end are balanced.+ unsafe {+ self.as_mut().begin_insert_rows(&root, r, r);+ self.as_mut().rust_mut().rows.insert(row, view.rows[row].clone());+ self.as_mut().end_insert_rows();+ }+ }+ Edit::Change(row) => {+ self.as_mut().rust_mut().rows[row] = view.rows[row].clone();+ let index = self.index(row as i32, 0, &root);+ self.as_mut().data_changed(&index, &index, &QList::default());+ }+ }+ }}let count = self.rows.len() as i32;self.as_mut().set_count(count);@@ -359,6 +406,18 @@ impl qobject::Photos {.to_string(),)}++ pub fn id_at(&self, row: i32) -> QString {+ usize::try_from(row)+ .ok()+ .and_then(|i| self.rows.get(i))+ .map(|r| QString::from(&r.id))+ .unwrap_or_default()+ }++ pub fn date_at(&self, row: i32) -> f64 {+ usize::try_from(row).ok().and_then(|i| self.rows.get(i)).map_or(0.0, |r| r.date as f64)+ }}#[cfg(test)]diff --git a/desktop/app/src/calls.rs b/desktop/app/src/calls.rsindex 4362857..1dbab5a 100644--- a/desktop/app/src/calls.rs+++ b/desktop/app/src/calls.rs@@ -404,6 +404,22 @@ fn page_changed() {core_host::host().hub.changed(Changes::CALLS);}+/// Drops in-memory call logs and contacts while the window is closed to the+/// tray; active calls (`IN_PROGRESS`) are kept for notifications.+pub fn release_idle_resources() {+ let mut released = false;+ page_state(|s| {+ if !s.dialing && (s.device.is_some() || !s.log.is_empty() || !s.contacts.is_empty()) {+ let generation = s.generation.wrapping_add(1);+ *s = PageState { generation, ..PageState::default() };+ released = true;+ }+ });+ if released {+ page_changed();+ }+}+#[derive(Debug, Clone, PartialEq)]pub struct View {pub device: Option<DeviceId>,diff --git a/desktop/app/src/main.rs b/desktop/app/src/main.rsindex 4f98262..308691b 100644--- a/desktop/app/src/main.rs+++ b/desktop/app/src/main.rs@@ -346,7 +346,8 @@ fn main() -> ExitCode {}let mut engine = QQmlApplicationEngine::new();- if let Some(engine) = engine.as_mut() {+ if let Some(mut engine) = engine.as_mut() {+ bridge::native::ffi::register_qml_app_engine(engine.as_mut());engine.load(&QUrl::from("qrc:/qt/qml/app/nectarlink/qml/App.qml"));}let code = app.as_mut().map_or(1, |app| app.exec());diff --git a/desktop/app/src/messages.rs b/desktop/app/src/messages.rsindex 02762b6..8b923fc 100644--- a/desktop/app/src/messages.rs+++ b/desktop/app/src/messages.rs@@ -12,7 +12,7 @@ use crate::{core_host, state::Changes};/// Conversations listed, and messages read at a time.const THREADS: u32 = 60;-const PAGE: u32 = 30;+const PAGE: u32 = 100;/// What the Messages page can show.#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]@@ -88,6 +88,22 @@ fn changed() {core_host::host().hub.changed(Changes::MESSAGES);}+/// Drops in-memory SMS threads and messages while the window is closed to the+/// tray; reopening the Messages page reloads them.+pub fn release_idle_resources() {+ let mut released = false;+ state(|s| {+ if !s.sending && (s.device.is_some() || !s.threads.is_empty() || !s.messages.is_empty()) {+ let generation = s.generation.wrapping_add(1);+ *s = State { generation, ..State::default() };+ released = true;+ }+ });+ if released {+ changed();+ }+}+fn files_dir() -> PathBuf {crate::notifications::images_dir()}diff --git a/desktop/app/src/photos.rs b/desktop/app/src/photos.rsindex efa1aa3..f5eb2e5 100644--- a/desktop/app/src/photos.rs+++ b/desktop/app/src/photos.rs@@ -502,6 +502,23 @@ fn gallery_changed() {core_host::host().hub.changed(Changes::PHOTOS);}+/// Drops in-memory gallery items, album lists, and thumbnail path maps while+/// the window is closed to the tray; reopening the Photos page reloads them.+pub fn release_idle_resources() {+ let mut released = false;+ gallery_state(|g| {+ if !g.saving && (g.device.is_some() || !g.items.is_empty() || !g.albums.is_empty()) {+ let save_folder = g.save_folder.take();+ let generation = g.generation.wrapping_add(1);+ *g = GalleryState { save_folder, generation, ..GalleryState::default() };+ released = true;+ }+ });+ if released {+ gallery_changed();+ }+}+fn thumbs_dir(device: DeviceId) -> PathBuf {core_host::host().data_dir.join("cache").join("photos-thumbs").join(device.to_string())}diff --git a/desktop/vcam/Cargo.toml b/desktop/vcam/Cargo.tomlindex 77c0427..b89d277 100644--- a/desktop/vcam/Cargo.toml+++ b/desktop/vcam/Cargo.toml@@ -14,6 +14,7 @@ name = "nectarlink_vcam"crate-type = ["cdylib", "rlib"][target.'cfg(windows)'.dependencies]+ab_glyph = "0.2"windows = { workspace = true, features = ["Win32_Foundation","Win32_Media_KernelStreaming",diff --git a/desktop/vcam/src/shm.rs b/desktop/vcam/src/shm.rsindex c3c3c98..95da1f6 100644--- a/desktop/vcam/src/shm.rs+++ b/desktop/vcam/src/shm.rs@@ -5,6 +5,8 @@use std::sync::atomic::{AtomicU8, AtomicU32, AtomicU64, Ordering};+use ab_glyph::{Font, FontRef, GlyphId, PxScale, ScaleFont, point};+use windows::{Win32::{Foundation::{CloseHandle, HANDLE, HLOCAL, INVALID_HANDLE_VALUE, LocalFree},@@ -419,149 +421,316 @@ pub fn bgrx_to_nv12(bgrx: &[u8], width: u32, height: u32, nv12: &mut [u8]) {}}-/// Renders a clean placeholder frame ("NECTARLINK WEBCAM" / "START THE WEBCAM ON <PHONE>")-/// into `bgrx` (`width * height * 4`).+const FIGTREE_TTF: &[u8] = include_bytes!("../../../assets/fonts/Figtree.ttf");++/// Honey primary (`docs/design/tokens.json`) and white ink for the Nectarlink mark.+const MARK_BG_BGR: [u8; 3] = [0x00, 0x51, 0x8A];+const MARK_INK_BGR: [u8; 3] = [0xFF, 0xFF, 0xFF];+const MARK_HEXAGON: [(f32, f32); 6] =+ [(12.0, 2.5), (20.2, 7.25), (20.2, 16.75), (12.0, 21.5), (3.8, 16.75), (3.8, 7.25)];+const MARK_BAR: ((f32, f32), (f32, f32)) = ((9.0, 12.0), (15.0, 12.0));++struct CachedPlaceholderCard {+ width: u32,+ height: u32,+ phone_name: String,+ card_x: usize,+ card_y: usize,+ card_w: usize,+ card_h: usize,+ card_bgrx: Vec<u8>,+}++static PLACEHOLDER_CACHE: std::sync::Mutex<Option<CachedPlaceholderCard>> = std::sync::Mutex::new(None);++/// Renders a clean, calm placeholder frame with the Nectarlink mark and+/// `"Start the webcam on <phone>"` in anti-aliased Figtree into `bgrx` (`width * height * 4`).pub fn render_placeholder_bgrx(bgrx: &mut [u8], width: u32, height: u32, phone_name: &str) {let w = width as usize;let h = height as usize;if bgrx.len() < w * h * 4 || w == 0 || h == 0 {return;}- // Dark slate background (#14171F)+ // Theme-neutral dark background (#111318 -> BGR 0x18, 0x13, 0x11)+ let bg_px = [0x18u8, 0x13, 0x11, 0xFF];for px in bgrx[..w * h * 4].as_chunks_mut::<4>().0 {- px.copy_from_slice(&[0x1F, 0x17, 0x14, 0xFF]);- }-- // Center card (#1D222E) with subtle amber top accent bar (#F59E0B -> BGR 0x0B, 0x9E, 0xF5)- let card_w = (w * 3 / 5).clamp(320.min(w), w);- let card_h = (h * 2 / 5).clamp(180.min(h), h);- let cx0 = (w - card_w) / 2;- let cy0 = (h - card_h) / 2;- fill_rect(bgrx, w, h, cx0, cy0, card_w, card_h, [0x2E, 0x22, 0x1D, 0xFF]);- fill_rect(bgrx, w, h, cx0, cy0, card_w, 4.min(card_h), [0x0B, 0x9E, 0xF5, 0xFF]);-- // Camera icon in the middle-top of the card- let scale = (h / 360).clamp(2, 4);- let icon_w = 18 * scale;- let icon_h = 12 * scale;- let ix = w / 2 - icon_w / 2;- let iy = cy0 + card_h / 4;- fill_rect(bgrx, w, h, ix, iy, icon_w * 3 / 4, icon_h, [0x0B, 0x9E, 0xF5, 0xFF]);- fill_rect(- bgrx,- w,- h,- ix + icon_w * 3 / 4 + scale,- iy + icon_h / 4,- icon_w / 4,- icon_h / 2,- [0x0B, 0x9E, 0xF5, 0xFF],- );+ px.copy_from_slice(&bg_px);+ }- let title = "NECTARLINK WEBCAM";- let subtitle = if phone_name.trim().is_empty() {- "START THE WEBCAM ON YOUR PHONE".to_owned()+ let trimmed = phone_name.trim();+ if let Ok(mut guard) = PLACEHOLDER_CACHE.lock() {+ let hit =+ guard.as_ref().is_some_and(|c| c.width == width && c.height == height && c.phone_name == trimmed);+ if !hit {+ *guard = Some(build_placeholder_card(width, height, trimmed));+ }+ if let Some(cached) = guard.as_ref() {+ blit_card(bgrx, w, h, cached);+ return;+ }+ }++ let card = build_placeholder_card(width, height, trimmed);+ blit_card(bgrx, w, h, &card);+}++fn blit_card(bgrx: &mut [u8], w: usize, h: usize, card: &CachedPlaceholderCard) {+ let max_rows = card.card_h.min(h.saturating_sub(card.card_y));+ let max_cols = card.card_w.min(w.saturating_sub(card.card_x));+ for row in 0..max_rows {+ let dst_off = ((card.card_y + row) * w + card.card_x) * 4;+ let src_off = row * card.card_w * 4;+ bgrx[dst_off..dst_off + max_cols * 4]+ .copy_from_slice(&card.card_bgrx[src_off..src_off + max_cols * 4]);+ }+}++fn build_placeholder_card(width: u32, height: u32, phone_name: &str) -> CachedPlaceholderCard {+ let w = width as usize;+ let h = height as usize;+ let scale = (h as f32 / 720.0).clamp(0.45, 1.6);++ let headline = if phone_name.is_empty() {+ "Start the webcam on your phone".to_owned()} else {- format!("START THE WEBCAM ON {}", phone_name.trim().to_ascii_uppercase())+ format!("Start the webcam on {phone_name}")};- draw_text_centered(bgrx, w, h, iy + icon_h + 8 * scale, scale, title, [0xF4, 0xF0, 0xEC, 0xFF]);- draw_text_centered(- bgrx,- w,- h,- iy + icon_h + 20 * scale,- (scale - 1).max(1),- &subtitle,- [0xB8, 0xA8, 0x9C, 0xFF],- );+ let caption = "Nectarlink Camera";++ let font = TrueTypeFont::parse(FIGTREE_TTF);+ let head_px = (22.0 * scale).clamp(12.0, 38.0);+ let cap_px = (14.0 * scale).clamp(10.0, 24.0);+ let head_w = font.as_ref().map_or(260, |f| f.measure_text(&headline, head_px));+ let cap_w = font.as_ref().map_or(140, |f| f.measure_text(caption, cap_px));++ let pad_x = (44.0 * scale).round() as usize;+ let min_card_w = (360.0 * scale).round() as usize;+ let card_w = (head_w.max(cap_w) + pad_x * 2).max(min_card_w).min(w.saturating_sub(16).max(1));+ let card_h = ((208.0 * scale).round() as usize).clamp(96.min(h), h.saturating_sub(16).max(1));+ let card_x = (w - card_w) / 2;+ let card_y = (h - card_h) / 2;++ let mut card_bgrx = vec![0u8; card_w * card_h * 4];+ let bg_bgr = [0x18u8, 0x13, 0x11];+ let surface_bgr = [0x23u8, 0x1C, 0x19]; // #191C23+ let border_bgr = [0x36u8, 0x2C, 0x27]; // #272C36+ let radius = (20.0 * scale).clamp(8.0, 32.0);++ draw_rounded_card(&mut card_bgrx, card_w, card_h, radius, bg_bgr, surface_bgr, border_bgr);++ let mark_size = ((52.0 * scale).round() as usize).clamp(24, 88).min(card_h / 2);+ let mark_x = card_w.saturating_sub(mark_size) / 2;+ let total_content_h = mark_size+ + (18.0 * scale).round() as usize+ + head_px.round() as usize+ + (8.0 * scale).round() as usize+ + cap_px.round() as usize;+ let mark_y = card_h.saturating_sub(total_content_h) / 2;+ blend_mark(&mut card_bgrx, card_w, card_h, mark_x, mark_y, mark_size);++ if let Some(font) = font.as_ref() {+ let head_baseline =+ mark_y + mark_size + (16.0 * scale).round() as usize + (head_px * 0.82).round() as usize;+ // Primary ink (#F2F0EC -> BGR 0xEC, 0xF0, 0xF2)+ font.draw_text_centered(+ &mut card_bgrx,+ card_w,+ card_h,+ head_baseline as f32,+ head_px,+ &headline,+ [0xEC, 0xF0, 0xF2],+ );++ let cap_baseline = head_baseline + (10.0 * scale).round() as usize + (cap_px * 0.85).round() as usize;+ // Secondary muted ink (#9399A6 -> BGR 0xA6, 0x99, 0x93)+ font.draw_text_centered(+ &mut card_bgrx,+ card_w,+ card_h,+ cap_baseline as f32,+ cap_px,+ caption,+ [0xA6, 0x99, 0x93],+ );+ }++ CachedPlaceholderCard {+ width,+ height,+ phone_name: phone_name.to_owned(),+ card_x,+ card_y,+ card_w,+ card_h,+ card_bgrx,+ }}-#[allow(clippy::too_many_arguments)]-fn fill_rect(+fn draw_rounded_card(bgrx: &mut [u8],w: usize,h: usize,- x0: usize,- y0: usize,- rw: usize,- rh: usize,- color: [u8; 4],+ radius: f32,+ outside_bgr: [u8; 3],+ fill_bgr: [u8; 3],+ border_bgr: [u8; 3],) {- let x1 = (x0 + rw).min(w);- let y1 = (y0 + rh).min(h);- for y in y0.min(h)..y1 {- let row = &mut bgrx[y * w * 4..(y + 1) * w * 4];- for x in x0.min(w)..x1 {- row[x * 4..x * 4 + 4].copy_from_slice(&color);+ let wf = w as f32;+ let hf = h as f32;+ let r = radius.min(wf * 0.5).min(hf * 0.5);+ for py in 0..h {+ for px in 0..w {+ let x = px as f32 + 0.5;+ let y = py as f32 + 0.5;+ let cx = x.clamp(r, wf - r);+ let cy = y.clamp(r, hf - r);+ let dist = ((x - cx).powi(2) + (y - cy).powi(2)).sqrt() - r;+ let fill_alpha = (0.5 - dist).clamp(0.0, 1.0);+ let inner_alpha = (-0.6 - dist).clamp(0.0, 1.0);+ let mut rgb = [0f32; 3];+ for c in 0..3 {+ let card_c = border_bgr[c] as f32 * (1.0 - inner_alpha) + fill_bgr[c] as f32 * inner_alpha;+ rgb[c] = outside_bgr[c] as f32 * (1.0 - fill_alpha) + card_c * fill_alpha;+ }+ let idx = (py * w + px) * 4;+ bgrx[idx] = rgb[0].round() as u8;+ bgrx[idx + 1] = rgb[1].round() as u8;+ bgrx[idx + 2] = rgb[2].round() as u8;+ bgrx[idx + 3] = 0xFF;}}}-fn draw_text_centered(- bgrx: &mut [u8],- w: usize,- h: usize,- y: usize,- scale: usize,- text: &str,- color: [u8; 4],-) {- let char_adv = 6 * scale;- let total_w = text.chars().count().saturating_mul(char_adv);- let start_x = w.saturating_sub(total_w) / 2;- for (i, ch) in text.chars().enumerate() {- let glyph = glyph_5x7(ch);- let gx = start_x + i * char_adv;- for (row_idx, &bits) in glyph.iter().enumerate() {- for col_idx in 0..5 {- if (bits >> (4 - col_idx)) & 1 != 0 {- fill_rect(bgrx, w, h, gx + col_idx * scale, y + row_idx * scale, scale, scale, color);+fn blend_mark(bgrx: &mut [u8], w: usize, h: usize, ox: usize, oy: usize, size: usize) {+ const SS: usize = 4;+ let s = size as f32;+ let radius = s * 0.28;+ let glyph = s * 0.62;+ let scale = glyph / 24.0;+ let offset = (s - glyph) / 2.0;+ let stroke = (1.8 * scale).max(1.4);+ let hex: Vec<(f32, f32)> =+ MARK_HEXAGON.iter().map(|&(x, y)| (offset + x * scale, offset + y * scale)).collect();+ let bar = (+ (offset + MARK_BAR.0.0 * scale, offset + MARK_BAR.0.1 * scale),+ (offset + MARK_BAR.1.0 * scale, offset + MARK_BAR.1.1 * scale),+ );++ for py in 0..size {+ let dy = oy + py;+ if dy >= h {+ break;+ }+ for px in 0..size {+ let dx = ox + px;+ if dx >= w {+ break;+ }+ let (mut tile, mut ink) = (0usize, 0usize);+ for sy in 0..SS {+ for sx in 0..SS {+ let x = px as f32 + (sx as f32 + 0.5) / SS as f32;+ let y = py as f32 + (sy as f32 + 0.5) / SS as f32;+ let cx = x.clamp(radius, s - radius);+ let cy = y.clamp(radius, s - radius);+ if (x - cx).powi(2) + (y - cy).powi(2) > radius * radius {+ continue;+ }+ tile += 1;+ let on_hex = (0..hex.len())+ .any(|i| dist_to_segment((x, y), hex[i], hex[(i + 1) % hex.len()]) <= stroke / 2.0);+ if on_hex || dist_to_segment((x, y), bar.0, bar.1) <= stroke / 2.0 {+ ink += 1;+ }}}+ if tile == 0 {+ continue;+ }+ let t = ink as f32 / tile as f32;+ let alpha = tile as f32 / (SS * SS) as f32;+ let idx = (dy * w + dx) * 4;+ for c in 0..3 {+ let mark_c = MARK_BG_BGR[c] as f32 * (1.0 - t) + MARK_INK_BGR[c] as f32 * t;+ bgrx[idx + c] = (bgrx[idx + c] as f32 * (1.0 - alpha) + mark_c * alpha).round() as u8;+ }}}}-fn glyph_5x7(ch: char) -> [u8; 7] {- match ch.to_ascii_uppercase() {- 'A' => [0b01110, 0b10001, 0b10001, 0b11111, 0b10001, 0b10001, 0b10001],- 'B' => [0b11110, 0b10001, 0b10001, 0b11110, 0b10001, 0b10001, 0b11110],- 'C' => [0b01110, 0b10001, 0b10000, 0b10000, 0b10000, 0b10001, 0b01110],- 'D' => [0b11100, 0b10010, 0b10001, 0b10001, 0b10001, 0b10010, 0b11100],- 'E' => [0b11111, 0b10000, 0b10000, 0b11110, 0b10000, 0b10000, 0b11111],- 'F' => [0b11111, 0b10000, 0b10000, 0b11110, 0b10000, 0b10000, 0b10000],- 'G' => [0b01110, 0b10001, 0b10000, 0b10111, 0b10001, 0b10001, 0b01110],- 'H' => [0b10001, 0b10001, 0b10001, 0b11111, 0b10001, 0b10001, 0b10001],- 'I' => [0b01110, 0b00100, 0b00100, 0b00100, 0b00100, 0b00100, 0b01110],- 'J' => [0b00111, 0b00010, 0b00010, 0b00010, 0b10010, 0b10010, 0b01100],- 'K' => [0b10001, 0b10010, 0b10100, 0b11000, 0b10100, 0b10010, 0b10001],- 'L' => [0b10000, 0b10000, 0b10000, 0b10000, 0b10000, 0b10000, 0b11111],- 'M' => [0b10001, 0b11011, 0b10101, 0b10101, 0b10001, 0b10001, 0b10001],- 'N' => [0b10001, 0b11001, 0b10101, 0b10011, 0b10001, 0b10001, 0b10001],- 'O' => [0b01110, 0b10001, 0b10001, 0b10001, 0b10001, 0b10001, 0b01110],- 'P' => [0b11110, 0b10001, 0b10001, 0b11110, 0b10000, 0b10000, 0b10000],- 'Q' => [0b01110, 0b10001, 0b10001, 0b10001, 0b10101, 0b10010, 0b01101],- 'R' => [0b11110, 0b10001, 0b10001, 0b11110, 0b10100, 0b10010, 0b10001],- 'S' => [0b01111, 0b10000, 0b10000, 0b01110, 0b00001, 0b00001, 0b11110],- 'T' => [0b11111, 0b00100, 0b00100, 0b00100, 0b00100, 0b00100, 0b00100],- 'U' => [0b10001, 0b10001, 0b10001, 0b10001, 0b10001, 0b10001, 0b01110],- 'V' => [0b10001, 0b10001, 0b10001, 0b10001, 0b10001, 0b01010, 0b00100],- 'W' => [0b10001, 0b10001, 0b10001, 0b10101, 0b10101, 0b11011, 0b10001],- 'X' => [0b10001, 0b10001, 0b01010, 0b00100, 0b01010, 0b10001, 0b10001],- 'Y' => [0b10001, 0b10001, 0b01010, 0b00100, 0b00100, 0b00100, 0b00100],- 'Z' => [0b11111, 0b00001, 0b00010, 0b00100, 0b01000, 0b10000, 0b11111],- '0' => [0b01110, 0b10001, 0b10011, 0b10101, 0b11001, 0b10001, 0b01110],- '1' => [0b00100, 0b01100, 0b00100, 0b00100, 0b00100, 0b00100, 0b01110],- '2' => [0b01110, 0b10001, 0b00001, 0b00010, 0b00100, 0b01000, 0b11111],- '3' => [0b11110, 0b00001, 0b00001, 0b01110, 0b00001, 0b00001, 0b11110],- '4' => [0b00010, 0b00110, 0b01010, 0b10010, 0b11111, 0b00010, 0b00010],- '5' => [0b11111, 0b10000, 0b11110, 0b00001, 0b00001, 0b10001, 0b01110],- '6' => [0b01110, 0b10000, 0b10000, 0b11110, 0b10001, 0b10001, 0b01110],- '7' => [0b11111, 0b00001, 0b00010, 0b00100, 0b01000, 0b01000, 0b01000],- '8' => [0b01110, 0b10001, 0b10001, 0b01110, 0b10001, 0b10001, 0b01110],- '9' => [0b01110, 0b10001, 0b10001, 0b01111, 0b00001, 0b00001, 0b01110],- '-' => [0b00000, 0b00000, 0b00000, 0b11111, 0b00000, 0b00000, 0b00000],- _ => [0; 7],+fn dist_to_segment(p: (f32, f32), a: (f32, f32), b: (f32, f32)) -> f32 {+ let (dx, dy) = (b.0 - a.0, b.1 - a.1);+ let len2 = dx * dx + dy * dy;+ let t = if len2 == 0.0 { 0.0 } else { (((p.0 - a.0) * dx + (p.1 - a.1) * dy) / len2).clamp(0.0, 1.0) };+ let (qx, qy) = (a.0 + t * dx, a.1 + t * dy);+ ((p.0 - qx).powi(2) + (p.1 - qy).powi(2)).sqrt()+}++/// The bundled Figtree font, laid out and drawn with `ab_glyph`.+struct TrueTypeFont {+ font: FontRef<'static>,+}++impl TrueTypeFont {+ fn parse(data: &'static [u8]) -> Option<Self> {+ FontRef::try_from_slice(data).ok().map(|font| Self { font })+ }++ /// Each glyph of `text` at `px_size` with its pen position (no wrapping),+ /// and the line's width.+ fn layout(&self, text: &str, px_size: f32) -> (Vec<(GlyphId, f32)>, f32) {+ let font = self.font.as_scaled(PxScale::from(px_size));+ let mut pen = 0.0;+ let mut previous = None;+ let mut glyphs = Vec::with_capacity(text.len());+ for ch in text.chars() {+ let id = font.glyph_id(ch);+ if let Some(previous) = previous {+ pen += font.kern(previous, id);+ }+ glyphs.push((id, pen));+ pen += font.h_advance(id);+ previous = Some(id);+ }+ (glyphs, pen)+ }++ fn measure_text(&self, text: &str, px_size: f32) -> usize {+ self.layout(text, px_size).1.ceil() as usize+ }++ #[allow(clippy::too_many_arguments)]+ fn draw_text_centered(+ &self,+ bgrx: &mut [u8],+ w: usize,+ h: usize,+ baseline_y: f32,+ px_size: f32,+ text: &str,+ ink_bgr: [u8; 3],+ ) {+ let (glyphs, width) = self.layout(text, px_size);+ let left = ((w as f32 - width) * 0.5).max(0.0);+ for (id, x) in glyphs {+ let glyph = id.with_scale_and_position(PxScale::from(px_size), point(left + x, baseline_y));+ let Some(outlined) = self.font.outline_glyph(glyph) else { continue };+ let bounds = outlined.px_bounds();+ outlined.draw(|gx, gy, coverage| {+ let px = bounds.min.x as i64 + i64::from(gx);+ let py = bounds.min.y as i64 + i64::from(gy);+ if px < 0 || py < 0 || px as usize >= w || py as usize >= h {+ return;+ }+ let alpha = coverage.clamp(0.0, 1.0);+ let idx = (py as usize * w + px as usize) * 4;+ for c in 0..3 {+ bgrx[idx + c] = (f32::from(bgrx[idx + c]) * (1.0 - alpha) + f32::from(ink_bgr[c]) * alpha)+ .round() as u8;+ }+ });+ }}}@@ -586,4 +755,23 @@ mod tests {let name = format!(r"Local\NectarlinkVcamMissing_{}", std::process::id());assert!(SharedFrameMapping::open_existing(&name).is_err());}++ #[test]+ fn placeholder_renders_mark_and_antialiased_figtree_text() {+ let (w, h) = (1280u32, 720u32);+ let mut frame = vec![0u8; (w * h * 4) as usize];+ render_placeholder_bgrx(&mut frame, w, h, "Pixel 9");+ // Corner pixel is dark neutral background (#111318 -> BGR 0x18, 0x13, 0x11).+ assert_eq!(&frame[0..4], &[0x18, 0x13, 0x11, 0xFF]);+ // Center card contains the honey mark (#8A5100 -> BGR 0x00, 0x51, 0x8A) and anti-aliased text.+ let has_honey_mark = frame+ .as_chunks::<4>()+ .0+ .iter()+ .any(|px| px[0] == 0x00 && px[1] == 0x51 && px[2] == 0x8A && px[3] == 0xFF);+ assert!(has_honey_mark, "placeholder should include the Nectarlink honey mark");+ let has_text_ink =+ frame.as_chunks::<4>().0.iter().any(|px| px[0] > 0xD0 && px[1] > 0xD0 && px[2] > 0xD0);+ assert!(has_text_ink, "placeholder should include bright headline text ink");+ }}