Your Android phone and your Windows PC, working as one. Local-first, end-to-end encrypted, no account.
Photos on the PC: the phone's gallery with albums, a viewer, save and copy
Bee9cf89f4c7816
diff --git a/README.md b/README.mdindex 2d9c9e4..6202598 100644--- a/README.md+++ b/README.md@@ -122,8 +122,12 @@ tests; there are no releases yet.set up (Android 12 and later), also mute, switch to the speaker, hold anduse the keypad. The call's audio stays on the phone. Calls nobody answeredshow as missed.-- **New photos and screenshots** from the phone pop up on the PC with a- preview: save them to Downloads or copy them, ready to paste.+- **Photos and videos**: a Photos page on the PC with the phone's camera roll,+ screenshots and albums, grouped by day. View photos in the app (with arrow+ keys between them), open them in Windows Photos, copy a photo to the+ clipboard, or save one or many to a folder you pick (`Downloads\Nectarlink`+ by default). New photos and screenshots from the phone also pop up on the PC+ with a preview, ready to save or copy.- **Media** both ways: what plays on the phone shows on the PC, in the app andin Windows' own media flyout (so the keyboard's media keys work too), andwhat plays on the PC shows in the phone's media controls, with artwork and@@ -133,7 +137,7 @@ tests; there are no releases yet.- **Capability matrix**: both apps compute which features work for a pair ofdevices and what would enable the rest, so the interface never offerssomething that can't work.-- **Windows app**: home, messages, calls and settings, two themes in light and dark (Bloom,+- **Windows app**: home, messages, calls, photos 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 ituses about 10 MB of memory (as shown in Task Manager).diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xmlindex ed1faed..2e29949 100644--- a/android/app/src/main/AndroidManifest.xml+++ b/android/app/src/main/AndroidManifest.xml@@ -58,8 +58,10 @@<!-- Texts, read and sent from paired PCs (asked for in the app). --><uses-permission android:name="android.permission.READ_SMS" /><uses-permission android:name="android.permission.SEND_SMS" />- <!-- New photos and screenshots, shown on paired PCs (asked for in the app). -->+ <!-- Photos, screenshots and videos, shown on paired PCs (asked for in the app). --><uses-permission android:name="android.permission.READ_MEDIA_IMAGES" />+ <uses-permission android:name="android.permission.READ_MEDIA_VIDEO" />+ <uses-permission android:name="android.permission.READ_MEDIA_VISUAL_USER_SELECTED" /><uses-permissionandroid:name="android.permission.READ_EXTERNAL_STORAGE"android:maxSdkVersion="32" />diff --git a/android/app/src/main/kotlin/app/nectarlink/android/core/Core.kt b/android/app/src/main/kotlin/app/nectarlink/android/core/Core.ktindex 96b113d..871d14c 100644--- a/android/app/src/main/kotlin/app/nectarlink/android/core/Core.kt+++ b/android/app/src/main/kotlin/app/nectarlink/android/core/Core.kt@@ -99,11 +99,17 @@ class Core(context: Context, private val scope: CoroutineScope) : EventListenerprivate val contacts = PhoneContacts(this.context) {notificationOps.trySend { it.contactsChanged() }}- private val photos = RecentPhotos(this.context) { photo ->- notificationOps.trySend { node ->- runCatching { node.photoTaken(photo) }.onFailure { Log.i(TAG, "a new photo wasn't announced", it) }- }- }+ private val photos = RecentPhotos(+ this.context,+ onPhoto = { photo ->+ notificationOps.trySend { node ->+ runCatching { node.photoTaken(photo) }.onFailure { Log.i(TAG, "a new photo wasn't announced", it) }+ }+ },+ onChanged = {+ notificationOps.trySend { it.photosChanged() }+ },+ )/** What plays on the PCs, in Android's media controls. */val pcMedia = PcMedia(this.context) { pc, player, action, position ->@@ -177,6 +183,7 @@ class Core(context: Context, private val scope: CoroutineScope) : EventListener_state.update {it.copy(photoAccess = RecentPhotos.hasAccess(context),+ photoPartialAccess = RecentPhotos.hasPartialAccess(context),callAccess = PhoneCalls.hasAll(context),contactsAccess = PhoneContacts.canRead(context),smsAccess = PhoneSms.hasAll(context),@@ -232,6 +239,7 @@ class Core(context: Context, private val scope: CoroutineScope) : EventListenerval granted = NotificationListener.hasAccess(context)val unrestricted = BackgroundAccess.isUnrestricted(context)val photoAccess = RecentPhotos.hasAccess(context)+ val photoPartialAccess = RecentPhotos.hasPartialAccess(context)val callAccess = PhoneCalls.hasAll(context)val contactsAccess = PhoneContacts.canRead(context)val smsAccess = PhoneSms.hasAll(context)@@ -242,11 +250,13 @@ class Core(context: Context, private val scope: CoroutineScope) : EventListener// Just allowed: reach the PCs now rather than at the next retry.scope.launch { node?.networkChanged() }}+ val prevPhotos = _state.value.photoAccess_state.update {it.copy(notificationAccess = granted,backgroundUnrestricted = unrestricted,photoAccess = photoAccess,+ photoPartialAccess = photoPartialAccess,callAccess = callAccess,contactsAccess = contactsAccess,smsAccess = smsAccess,@@ -265,7 +275,10 @@ class Core(context: Context, private val scope: CoroutineScope) : EventListenerif (contactsAccess) contacts.start() else contacts.stop()if (PhoneSms.canRead(context)) sms.start() else sms.stop()}- notificationOps.trySend { it.updatePower(powerLevel(), capabilities(_state.value.notificationAccess)) }+ notificationOps.trySend {+ it.updatePower(powerLevel(), capabilities(_state.value.notificationAccess))+ if (photoAccess && (!prevPhotos || photoPartialAccess)) it.photosChanged()+ }}}diff --git a/android/app/src/main/kotlin/app/nectarlink/android/core/CoreState.kt b/android/app/src/main/kotlin/app/nectarlink/android/core/CoreState.ktindex 99869f4..507fb47 100644--- a/android/app/src/main/kotlin/app/nectarlink/android/core/CoreState.kt+++ b/android/app/src/main/kotlin/app/nectarlink/android/core/CoreState.kt@@ -74,8 +74,10 @@ data class CoreState(val callAccess: Boolean = false,/** Whether the user let Nectarlink read contacts (for PCs). */val contactsAccess: Boolean = false,- /** Whether the user let Nectarlink see the phone's photos (to show new ones on PCs). */+ /** Whether the user let Nectarlink see the phone's photos (to show them on PCs). */val photoAccess: Boolean = false,+ /** Whether Android 14+ "Select photos and videos" partial access is active. */+ val photoPartialAccess: Boolean = false,/** Whether Android lets Nectarlink run unrestricted in the background. */val backgroundUnrestricted: Boolean = true,/** File transfers, newest first (running ones and the latest finished). */@@ -124,6 +126,7 @@ data class CoreState(is Event.MediaChanged -> this// PCs only: phones announce their own photos, calls, contacts, texts and screen.is Event.PhotoAdded,+ is Event.PhotosChanged,is Event.CallChanged,is Event.CallLogChanged,is Event.ContactsChanged,diff --git a/android/app/src/main/kotlin/app/nectarlink/android/core/PhonePlatform.kt b/android/app/src/main/kotlin/app/nectarlink/android/core/PhonePlatform.ktindex 28ce77f..3147b40 100644--- a/android/app/src/main/kotlin/app/nectarlink/android/core/PhonePlatform.kt+++ b/android/app/src/main/kotlin/app/nectarlink/android/core/PhonePlatform.kt@@ -32,6 +32,9 @@ import app.nectarlink.core.MediaActionimport app.nectarlink.core.MirrorInputEventimport app.nectarlink.core.MirrorOptionsimport app.nectarlink.core.PhoneApp+import app.nectarlink.core.PhotoAlbum+import app.nectarlink.core.PhotoItem+import app.nectarlink.core.PhotoThumbimport app.nectarlink.core.NotificationFailureimport app.nectarlink.core.Platform@@ -74,6 +77,13 @@ internal class PhonePlatform(override fun openPhoto(id: String): FileToSend? = RecentPhotos.open(context, id)+ override fun photoAlbums(): List<PhotoAlbum> = RecentPhotos.albums(context)++ override fun photoList(album: String?, before: Long?, beforeId: String, limit: UInt): List<PhotoItem> =+ RecentPhotos.list(context, album, before, beforeId, limit.toInt())++ override fun photoThumbs(ids: List<String>): List<PhotoThumb> = RecentPhotos.thumbs(context, ids)+override fun callCommand(id: String, command: CallCommand): Boolean = calls().command(id, command)override fun callLog(before: Long?, limit: UInt): List<CallLogEntry> =diff --git a/android/app/src/main/kotlin/app/nectarlink/android/photos/RecentPhotos.kt b/android/app/src/main/kotlin/app/nectarlink/android/photos/RecentPhotos.ktindex ad2917b..20aa49f 100644--- a/android/app/src/main/kotlin/app/nectarlink/android/photos/RecentPhotos.kt+++ b/android/app/src/main/kotlin/app/nectarlink/android/photos/RecentPhotos.kt@@ -6,6 +6,7 @@ import android.content.ContentUrisimport android.content.Contextimport android.content.pm.PackageManagerimport android.database.ContentObserver+import android.database.Cursorimport android.graphics.Bitmapimport android.net.Uriimport android.os.Build@@ -18,14 +19,22 @@ import androidx.core.content.ContextCompatimport androidx.core.content.editimport app.nectarlink.core.FileToSendimport app.nectarlink.core.Photo+import app.nectarlink.core.PhotoAlbum+import app.nectarlink.core.PhotoItem+import app.nectarlink.core.PhotoThumbimport java.io.ByteArrayOutputStream/**- * New photos and screenshots, for PCs (docs/protocol/photos.md): watches- * the phone's pictures while the app runs and reports each new one with a- * small preview. A PC then asks for the photo itself by its ID.+ * Photos, screenshots and videos for PCs (docs/protocol/photos.md): watches+ * the phone's gallery while the app runs, reports each new photo with a small+ * preview, notifies PCs when the library changes, and answers gallery album,+ * item, thumbnail, and full-file queries.*/-internal class RecentPhotos(context: Context, private val onPhoto: (Photo) -> Unit) {+internal class RecentPhotos(+ context: Context,+ private val onPhoto: (Photo) -> Unit,+ private val onChanged: () -> Unit = {},+) {private val context = context.applicationContextprivate val prefs = context.getSharedPreferences("photos", Context.MODE_PRIVATE)private val handler = Handler(Looper.getMainLooper())@@ -43,7 +52,10 @@ internal class RecentPhotos(context: Context, private val onPhoto: (Photo) -> Unhandler.removeCallbacks(check)handler.postDelayed(check, SETTLE_MS)}- }.also { context.contentResolver.registerContentObserver(COLLECTION, true, it) }+ }.also {+ context.contentResolver.registerContentObserver(IMAGES_URI, true, it)+ context.contentResolver.registerContentObserver(VIDEOS_URI, true, it)+ }}fun stop() {@@ -54,6 +66,7 @@ internal class RecentPhotos(context: Context, private val onPhoto: (Photo) -> Un@Synchronizedprivate fun checkNow() {+ onChanged()val lastSeen = prefs.getLong(LAST_SEEN, System.currentTimeMillis() / 1000)var newest = lastSeenval columns = arrayOf(@@ -67,7 +80,7 @@ internal class RecentPhotos(context: Context, private val onPhoto: (Photo) -> Unval pending = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) " AND ${MediaStore.Images.Media.IS_PENDING} = 0" else ""val found = runCatching {context.contentResolver.query(- COLLECTION,+ IMAGES_URI,columns,"${MediaStore.Images.Media.DATE_ADDED} > ?$pending",arrayOf(lastSeen.toString()),@@ -98,72 +111,279 @@ internal class RecentPhotos(context: Context, private val onPhoto: (Photo) -> Un// A burst (a camera's burst mode, a downloaded album) isn't news// photo by photo: only the latest few.for (photo in found.takeLast(MAX_PER_CHECK)) {- val thumb = preview(photo.id) ?: continue- onPhoto(Photo(ID_PREFIX + photo.id, photo.name, photo.size.toULong(), photo.taken, photo.screenshot, thumb))+ val thumb = encodeThumbnail(context, IMAGES_URI, photo.id, isVideo = false, PREVIEW_PX, MAX_PREVIEW_BYTES) ?: continue+ onPhoto(Photo(IMAGE_PREFIX + photo.id, photo.name, photo.size.coerceAtLeast(0L).toULong(), photo.taken, photo.screenshot, thumb))}}private data class Found(val id: Long, val name: String, val size: Long, val taken: Long, val screenshot: Boolean)- /** A JPEG of at most 96 KB, 512 pixels a side. */- private fun preview(id: Long): ByteArray? = runCatching {- val uri = ContentUris.withAppendedId(COLLECTION, id)- val bitmap = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {- context.contentResolver.loadThumbnail(uri, Size(PREVIEW_PX, PREVIEW_PX), null)- } else {- @Suppress("DEPRECATION")- MediaStore.Images.Thumbnails.getThumbnail(context.contentResolver, id, MediaStore.Images.Thumbnails.MINI_KIND, null)- } ?: return null- try {- // Lower quality until it fits.- generateSequence(85) { it - 15 }.takeWhile { it >= 40 }- .map { quality -> ByteArrayOutputStream().also { bitmap.compress(Bitmap.CompressFormat.JPEG, quality, it) }.toByteArray() }- .firstOrNull { it.size <= MAX_PREVIEW_BYTES }- } finally {- bitmap.recycle()- }- }.getOrElse {- Log.i(TAG, "no preview for a new photo", it)- null- }-companion object {private const val TAG = "RecentPhotos"private const val LAST_SEEN = "lastSeen"- private const val ID_PREFIX = "media:"+ private const val IMAGE_PREFIX = "media:"+ private const val VIDEO_PREFIX = "video:"private const val SETTLE_MS = 1500Lprivate const val MAX_PER_CHECK = 3private const val PREVIEW_PX = 512private const val MAX_PREVIEW_BYTES = 96 * 1024- private val COLLECTION: Uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI+ private const val THUMB_PX = 256+ private const val MAX_THUMB_BYTES = 32 * 1024+ private const val MAX_BATCH = 24+ private val IMAGES_URI: Uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI+ private val VIDEOS_URI: Uri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI++ /** The gallery's order: when taken, or else when last written (as [dateOf]). */+ private val DATE_KEY =+ "COALESCE(${MediaStore.MediaColumns.DATE_TAKEN}, ${MediaStore.MediaColumns.DATE_MODIFIED} * 1000)"- /** What to ask for (Android 13 split photos from other files). */- val permissions: Array<String> =+ /** Permissions to request from the user for photos and videos. */+ val permissions: Array<String> = when {+ Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE -> arrayOf(+ Manifest.permission.READ_MEDIA_IMAGES,+ Manifest.permission.READ_MEDIA_VIDEO,+ Manifest.permission.READ_MEDIA_VISUAL_USER_SELECTED,+ )+ Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU -> arrayOf(+ Manifest.permission.READ_MEDIA_IMAGES,+ Manifest.permission.READ_MEDIA_VIDEO,+ )+ else -> arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE)+ }++ /** Whether the user granted access to all photos and videos. */+ fun hasFullAccess(context: Context): Boolean =if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {- arrayOf(Manifest.permission.READ_MEDIA_IMAGES)+ ContextCompat.checkSelfPermission(context, Manifest.permission.READ_MEDIA_IMAGES) == PackageManager.PERMISSION_GRANTED &&+ ContextCompat.checkSelfPermission(context, Manifest.permission.READ_MEDIA_VIDEO) == PackageManager.PERMISSION_GRANTED} else {- arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE)+ ContextCompat.checkSelfPermission(context, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED+ }++ /**+ * Whether the app sees some photos or videos: all photos (what+ * versions before the gallery asked for), all videos, or the ones+ * the user picked (Android 14's "Select photos and videos").+ */+ fun hasAccess(context: Context): Boolean = hasFullAccess(context) || listOfNotNull(+ Manifest.permission.READ_MEDIA_IMAGES.takeIf { Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU },+ Manifest.permission.READ_MEDIA_VIDEO.takeIf { Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU },+ Manifest.permission.READ_MEDIA_VISUAL_USER_SELECTED.takeIf {+ Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE+ },+ ).any { ContextCompat.checkSelfPermission(context, it) == PackageManager.PERMISSION_GRANTED }++ /** Whether it sees only some of them: the user can allow the rest. */+ fun hasPartialAccess(context: Context): Boolean = hasAccess(context) && !hasFullAccess(context)++ /** Lists photo and video albums (MediaStore buckets), Camera and Screenshots first. */+ fun albums(context: Context): List<PhotoAlbum> {+ if (!hasAccess(context)) return emptyList()+ class Bucket(val id: String, val name: String) {+ var count = 0+ var newest = Long.MIN_VALUE to Long.MIN_VALUE+ var cover: String? = null}+ val buckets = LinkedHashMap<String, Bucket>()+ for ((uri, prefix) in listOf(IMAGES_URI to IMAGE_PREFIX, VIDEOS_URI to VIDEO_PREFIX)) {+ runCatching {+ context.contentResolver.query(+ uri,+ arrayOf(+ MediaStore.MediaColumns._ID,+ MediaStore.MediaColumns.BUCKET_ID,+ MediaStore.MediaColumns.BUCKET_DISPLAY_NAME,+ MediaStore.MediaColumns.DATE_TAKEN,+ MediaStore.MediaColumns.DATE_MODIFIED,+ ),+ notPending(),+ null,+ null,+ )?.use { cursor ->+ while (cursor.moveToNext()) {+ val id = cursor.getLong(0)+ val bucketId = cursor.getString(1)?.takeIf { it.isNotBlank() } ?: continue+ val bucket = buckets.getOrPut(bucketId) {+ Bucket(bucketId, cursor.getString(2)?.takeIf { it.isNotBlank() } ?: "Photos")+ }+ bucket.count += 1+ val key = dateOf(cursor, 3, 4) to id+ if (compareValuesBy(key, bucket.newest, { it.first }, { it.second }) > 0) {+ bucket.newest = key+ bucket.cover = prefix + id+ }+ }+ }+ }.onFailure { Log.w(TAG, "can't list albums", it) }+ }+ return buckets.values+ .sortedWith(+ compareBy<Bucket> {+ when {+ it.name.equals("Camera", ignoreCase = true) -> 0+ it.name.equals("Screenshots", ignoreCase = true) -> 1+ else -> 2+ }+ }.thenByDescending { it.count }.thenBy { it.name.lowercase() },+ )+ .map { PhotoAlbum(id = it.id, name = it.name, count = it.count.toUInt(), cover = it.cover) }+ }/**- * Whether the app sees every new photo. Access to only some photos- * (Android 14) isn't enough: new ones wouldn't show up.+ * Lists photos and videos (in `album` when given), newest first by+ * when they were taken, then by media ID. With `before`, only those+ * after the previous page's last item (`before`, `beforeId`).*/- fun hasAccess(context: Context): Boolean = permissions.all {- ContextCompat.checkSelfPermission(context, it) == PackageManager.PERMISSION_GRANTED+ fun list(context: Context, album: String?, before: Long?, beforeId: String, limit: Int): List<PhotoItem> {+ if (!hasAccess(context) || limit <= 0) return emptyList()+ val max = limit.coerceIn(1, 200)+ // Images and videos share one ID space (MediaStore's files table).+ val lastId = parseId(beforeId)?.second+ val out = ArrayList<Pair<PhotoItem, Long>>(max * 2)+ for ((uri, prefix) in listOf(IMAGES_URI to IMAGE_PREFIX, VIDEOS_URI to VIDEO_PREFIX)) {+ val isVideo = prefix == VIDEO_PREFIX+ val columns = arrayOf(+ MediaStore.MediaColumns._ID,+ MediaStore.MediaColumns.DISPLAY_NAME,+ MediaStore.MediaColumns.SIZE,+ MediaStore.MediaColumns.DATE_TAKEN,+ MediaStore.MediaColumns.DATE_MODIFIED,+ MediaStore.MediaColumns.WIDTH,+ MediaStore.MediaColumns.HEIGHT,+ MediaStore.MediaColumns.BUCKET_ID,+ ) + if (isVideo) arrayOf(MediaStore.Video.VideoColumns.DURATION) else emptyArray()+ val clauses = listOfNotNull(notPending()).toMutableList()+ val args = mutableListOf<String>()+ if (!album.isNullOrBlank()) {+ clauses += "${MediaStore.MediaColumns.BUCKET_ID} = ?"+ args += album+ }+ // Arguments arrive as text, and SQLite orders any number before+ // any text unless told otherwise (the date has no column type).+ if (before != null) {+ if (lastId != null) {+ clauses += "($DATE_KEY < CAST(? AS INTEGER) OR ($DATE_KEY = CAST(? AS INTEGER) AND " ++ "${MediaStore.MediaColumns._ID} < CAST(? AS INTEGER)))"+ args += listOf(before.toString(), before.toString(), lastId.toString())+ } else {+ clauses += "$DATE_KEY < CAST(? AS INTEGER)"+ args += before.toString()+ }+ }+ runCatching {+ context.contentResolver.query(+ uri,+ columns,+ clauses.joinToString(" AND ").ifEmpty { null },+ args.toTypedArray().ifEmpty { null },+ "$DATE_KEY DESC, ${MediaStore.MediaColumns._ID} DESC",+ )?.use { cursor ->+ var count = 0+ while (count < max && cursor.moveToNext()) {+ val id = cursor.getLong(0)+ val fallback = if (isVideo) "VID_$id.mp4" else "IMG_$id.jpg"+ out += PhotoItem(+ id = prefix + id,+ name = cursor.getString(1)?.takeIf { it.isNotBlank() } ?: fallback,+ date = dateOf(cursor, 3, 4),+ size = cursor.getLong(2).coerceAtLeast(0L).toULong(),+ width = cursor.getInt(5).coerceAtLeast(0).toUInt(),+ height = cursor.getInt(6).coerceAtLeast(0).toUInt(),+ duration = if (isVideo) cursor.getLong(8).coerceIn(0L, UInt.MAX_VALUE.toLong()).toUInt() else null,+ album = cursor.getString(7)?.takeIf { it.isNotBlank() },+ ) to id+ count += 1+ }+ }+ }.onFailure { Log.w(TAG, "can't list gallery items", it) }+ }+ return out.sortedWith(compareByDescending<Pair<PhotoItem, Long>> { it.first.date }.thenByDescending { it.second })+ .take(max)+ .map { it.first }}- /** Opens a photo a PC asked for; `null` when it's gone or not one of ours. */+ /** Only finished files (Android 10+ marks ones still being written as pending). */+ private fun notPending(): String? =+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) "${MediaStore.MediaColumns.IS_PENDING} = 0" else null++ /** When it was taken (ms), or else when the file was last written; as [DATE_KEY]. */+ private fun dateOf(cursor: Cursor, taken: Int, modified: Int): Long =+ cursor.getLong(taken).takeIf { !cursor.isNull(taken) } ?: (cursor.getLong(modified) * 1000L)++ /** Loads small JPEG thumbnails (<= 32 KiB, ~256 px) for a batch of item IDs. */+ fun thumbs(context: Context, ids: List<String>): List<PhotoThumb> {+ if (!hasAccess(context) || ids.isEmpty()) return emptyList()+ return ids.take(MAX_BATCH).mapNotNull { rawId ->+ val (uri, mediaId, isVideo) = parseId(rawId) ?: return@mapNotNull null+ val bytes = encodeThumbnail(context, uri, mediaId, isVideo, THUMB_PX, MAX_THUMB_BYTES)+ ?: return@mapNotNull null+ PhotoThumb(id = rawId, data = bytes)+ }+ }++ /** Opens a photo or video a PC asked for; `null` when it's gone or not one of ours. */fun open(context: Context, id: String): FileToSend? {- val mediaId = id.removePrefix(ID_PREFIX).takeIf { id.startsWith(ID_PREFIX) }?.toLongOrNull() ?: return null- val uri = ContentUris.withAppendedId(COLLECTION, mediaId)+ if (!hasAccess(context)) return null+ val (collection, mediaId, isVideo) = parseId(id) ?: return null+ val uri = ContentUris.withAppendedId(collection, mediaId)+ val fallback = if (isVideo) "VID_$mediaId.mp4" else "IMG_$mediaId.jpg"val name = runCatching {- context.contentResolver.query(uri, arrayOf(MediaStore.Images.Media.DISPLAY_NAME), null, null, null)?.use {+ context.contentResolver.query(uri, arrayOf(MediaStore.MediaColumns.DISPLAY_NAME), null, null, null)?.use {if (it.moveToFirst()) it.getString(0) else null}- }.getOrNull() ?: return null+ }.getOrNull()?.takeIf { it.isNotBlank() } ?: fallbackval fd = runCatching { context.contentResolver.openFileDescriptor(uri, "r") }.getOrNull() ?: return nullreturn FileToSend.Fd(name = name, fd = fd.detachFd(), folder = null)}++ private fun parseId(id: String): Triple<Uri, Long, Boolean>? = when {+ id.startsWith(IMAGE_PREFIX) -> id.removePrefix(IMAGE_PREFIX).toLongOrNull()?.let { Triple(IMAGES_URI, it, false) }+ id.startsWith(VIDEO_PREFIX) -> id.removePrefix(VIDEO_PREFIX).toLongOrNull()?.let { Triple(VIDEOS_URI, it, true) }+ else -> null+ }++ private fun encodeThumbnail(+ context: Context,+ collection: Uri,+ mediaId: Long,+ isVideo: Boolean,+ targetPx: Int,+ maxBytes: Int,+ ): ByteArray? = runCatching {+ val uri = ContentUris.withAppendedId(collection, mediaId)+ val bitmap = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {+ context.contentResolver.loadThumbnail(uri, Size(targetPx, targetPx), null)+ } else {+ @Suppress("DEPRECATION")+ if (isVideo) {+ MediaStore.Video.Thumbnails.getThumbnail(+ context.contentResolver,+ mediaId,+ MediaStore.Video.Thumbnails.MINI_KIND,+ null,+ )+ } else {+ MediaStore.Images.Thumbnails.getThumbnail(+ context.contentResolver,+ mediaId,+ MediaStore.Images.Thumbnails.MINI_KIND,+ null,+ )+ }+ } ?: return null+ try {+ generateSequence(82) { it - 15 }.takeWhile { it >= 35 }+ .map { quality ->+ ByteArrayOutputStream().also { bitmap.compress(Bitmap.CompressFormat.JPEG, quality, it) }.toByteArray()+ }+ .firstOrNull { it.size <= maxBytes }+ } finally {+ bitmap.recycle()+ }+ }.getOrElse {+ Log.i(TAG, "no thumbnail for media item", it)+ null+ }}}+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 d0bdf48..921c031 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@@ -53,6 +53,7 @@ import app.nectarlink.android.contacts.PhoneContactsimport app.nectarlink.android.elevated.Elevatedimport app.nectarlink.android.elevated.PairingNotificationimport app.nectarlink.android.mirror.InputService+import app.nectarlink.android.photos.RecentPhotosimport app.nectarlink.android.sms.PhoneSmsimport app.nectarlink.android.update.AppUpdaterimport app.nectarlink.android.update.CheckForUpdates@@ -118,6 +119,14 @@ fun SettingsScreen()}+ Section(stringResource(R.string.settings_photos)) {+ PhotosAccess(+ granted = state.photoAccess,+ partial = state.photoPartialAccess,+ onAccessChanged = onAccessChanged,+ )+ }+Section(stringResource(R.string.settings_control)) {ControlAccess(state.inputAccess)ElevatedAccess()@@ -381,6 +390,48 @@ private fun RuntimePermissionAccess(}}+@Composable+private fun PhotosAccess(+ granted: Boolean,+ partial: Boolean,+ onAccessChanged: () -> Unit,+) {+ val context = LocalContext.current+ val ask = rememberLauncherForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) {+ onAccessChanged()+ }+ Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth()) {+ Column(Modifier.weight(1f).padding(end = 12.dp)) {+ Text(stringResource(R.string.photos_title), style = MaterialTheme.typography.titleSmall)+ Text(+ stringResource(+ when {+ partial -> R.string.photos_partial+ granted -> R.string.photos_on+ else -> R.string.photos_off+ },+ ),+ style = MaterialTheme.typography.bodySmall,+ color = MaterialTheme.colorScheme.onSurfaceVariant,+ )+ }+ when {+ partial -> OutlinedButton(onClick = { ask.launch(RecentPhotos.permissions) }) {+ Text(stringResource(R.string.action_select_photos))+ }+ granted -> OutlinedButton(onClick = {+ context.startActivity(+ Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.fromParts("package", context.packageName, null))+ .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK),+ )+ }) { Text(stringResource(R.string.action_manage)) }+ else -> Button(onClick = { ask.launch(RecentPhotos.permissions) }) {+ Text(stringResource(R.string.action_allow))+ }+ }+ }+}+@Composableprivate fun Section(title: String, content: @Composable () -> Unit) {Text(diff --git a/android/app/src/main/res/values/strings.xml b/android/app/src/main/res/values/strings.xmlindex 433dbbb..06533e9 100644--- a/android/app/src/main/res/values/strings.xml+++ b/android/app/src/main/res/values/strings.xml@@ -118,8 +118,12 @@<string name="contacts_title">Contacts on your PC</string><string name="contacts_on">On. Your contacts are available in Calls and Messages on your PC.</string><string name="contacts_off">Search your contacts and start a call or text from your PC. Nectarlink needs access to your contacts for that.</string>- <string name="photos_title">Show new photos on your PC</string>- <string name="photos_off">Screenshots and photos you take pop up on your PC, ready to save or paste. Nectarlink needs access to your photos for that.</string>+ <string name="settings_photos">Photos and videos</string>+ <string name="photos_title">Photos and videos on your PC</string>+ <string name="photos_on">On. Your photos, screenshots and videos are available on your PC.</string>+ <string name="photos_partial">Some of your photos and videos aren\'t available on your PC. Allow all of them to browse your whole gallery there.</string>+ <string name="photos_off">Browse your photos, screenshots and videos on your PC, and get new screenshots right away. Nectarlink needs access to your photos and videos for that.</string>+ <string name="action_select_photos">Allow all</string><string name="transfer_too_many">That folder has too many files to send at once.</string><string name="transfers_title">Transfers</string><string name="transfer_sending">Sending to %1$s</string>diff --git a/core/nectarlink-cli/src/main.rs b/core/nectarlink-cli/src/main.rsindex 448078a..d7d2064 100644--- a/core/nectarlink-cli/src/main.rs+++ b/core/nectarlink-cli/src/main.rs@@ -159,9 +159,14 @@ enum Command {},/// Open a web link on a paired device.Open { device: String, url: String },- /// Show new photos from paired phones as this PC would, and fetch each- /// one; stays online until Ctrl+C.- Photos,+ /// Browse a paired phone's gallery (albums, photos, thumbnails, download),+ /// or with no arguments watch for new photos from paired phones until Ctrl+C.+ Photos {+ /// Paired phone (omit to watch for new photos from any phone).+ device: Option<String>,+ #[command(subcommand)]+ action: Option<PhotosArg>,+ },/// Ask a paired phone for its screen and save the video (H.264, Annex B)/// for `seconds`; prints what arrived.Mirror {@@ -406,6 +411,45 @@ enum SmsArg {Send { to: String, body: String },}+#[derive(Debug, Subcommand)]+enum PhotosArg {+ /// List photo and video albums on the phone.+ Albums,+ /// List photos and videos on the phone (newest first).+ List {+ /// Only items in this album ID.+ #[arg(long, allow_hyphen_values = true)]+ album: Option<String>,+ /// Only items after this one (the previous page's last), given as+ /// `<date ms>:<id>`, or `<date ms>` for items older than that.+ #[arg(long, value_parser = parse_photo_cursor)]+ before: Option<(i64, String)>,+ /// Maximum number of items to list.+ #[arg(long, default_value_t = 30)]+ limit: u32,+ },+ /// Fetch thumbnails for one or more item IDs.+ Thumbs {+ #[arg(required = true)]+ ids: Vec<String>,+ /// Directory to save `<id>.jpg` files into (default: current directory).+ #[arg(long)]+ out: Option<PathBuf>,+ },+ /// Download one or more full-size photos or videos into Downloads\Nectarlink.+ Get {+ #[arg(required = true)]+ ids: Vec<String>,+ },+}++/// `--before <date ms>[:<id>]` for `photos list`.+fn parse_photo_cursor(s: &str) -> std::result::Result<(i64, String), String> {+ let (date, id) = s.split_once(':').unwrap_or((s, ""));+ let date = date.parse().map_err(|_| format!("not a date in ms: {date}"))?;+ Ok((date, id.to_owned()))+}+#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]enum CallArg {Answer,@@ -764,6 +808,353 @@ static CALL_CONTROLS: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBstatic PHOTO: std::sync::OnceLock<PathBuf> = std::sync::OnceLock::new();const PHOTO_ID: &str = "cli-photo";+struct SampleGalleryItem {+ item: nectarlink_core::PhotoItem,+ thumb_jpeg: Vec<u8>,+ full_path: PathBuf,+}++static GALLERY_ALBUMS: std::sync::Mutex<Vec<nectarlink_core::PhotoAlbum>> = std::sync::Mutex::new(Vec::new());+static GALLERY_ITEMS: std::sync::Mutex<Vec<SampleGalleryItem>> = std::sync::Mutex::new(Vec::new());++/// Encodes a baseline JFIF JPEG (width and height rounded to multiples of 8)+/// with a smooth vertical gradient between `top` and `bottom` RGB and a bright+/// accent circle.+fn sample_jpeg(+ width: u16,+ height: u16,+ top: (u8, u8, u8),+ bottom: (u8, u8, u8),+ sun: (u8, u8, u8),+) -> Vec<u8> {+ let bw = (width.max(8) / 8) as usize;+ let bh = (height.max(8) / 8) as usize;+ let (w, h) = ((bw * 8) as u16, (bh * 8) as u16);++ let mut out = Vec::with_capacity(4096);+ // SOI + APP0 (JFIF 1.01)+ out.extend_from_slice(&[+ 0xFF, 0xD8, 0xFF, 0xE0, 0x00, 0x10, b'J', b'F', b'I', b'F', 0x00, 0x01, 0x01, 0x00, 0x00, 0x01, 0x00,+ 0x01, 0x00, 0x00,+ ]);+ // DQT: table 0, 8-bit precision, all 64 entries = 8 so quantized DC == (level - 128).+ out.extend_from_slice(&[0xFF, 0xDB, 0x00, 0x43, 0x00]);+ out.extend_from_slice(&[8u8; 64]);+ // SOF0: baseline DCT, 8-bit, 3 components (Y=1, Cb=2, Cr=3) at 1x1 sampling.+ out.extend_from_slice(&[+ 0xFF,+ 0xC0,+ 0x00,+ 0x11,+ 0x08,+ (h >> 8) as u8,+ (h & 0xFF) as u8,+ (w >> 8) as u8,+ (w & 0xFF) as u8,+ 0x03,+ 0x01,+ 0x11,+ 0x00,+ 0x02,+ 0x11,+ 0x00,+ 0x03,+ 0x11,+ 0x00,+ ]);+ // DHT DC table 0: 12 symbols (0..=11), each 4 bits long (codes 0000..=1011).+ out.extend_from_slice(&[0xFF, 0xC4, 0x00, 0x1F, 0x00]);+ out.extend_from_slice(&[0, 0, 0, 12, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);+ out.extend_from_slice(&[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]);+ // DHT AC table 0: 1 symbol (0x00 = EOB), 1 bit long (code 0).+ out.extend_from_slice(&[0xFF, 0xC4, 0x00, 0x14, 0x10]);+ out.extend_from_slice(&[1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);+ out.push(0x00);+ // SOS: 3 components, all using DC table 0 / AC table 0.+ out.extend_from_slice(&[+ 0xFF, 0xDA, 0x00, 0x0C, 0x03, 0x01, 0x00, 0x02, 0x00, 0x03, 0x00, 0x00, 0x3F, 0x00,+ ]);++ let mut bit_buf = 0u32;+ let mut bit_count = 0u32;+ fn push_bits(bit_buf: &mut u32, bit_count: &mut u32, bits: u16, len: u32, out: &mut Vec<u8>) {+ *bit_buf = (*bit_buf << len) | u32::from(bits & ((1 << len) - 1));+ *bit_count += len;+ while *bit_count >= 8 {+ *bit_count -= 8;+ let byte = ((*bit_buf >> *bit_count) & 0xFF) as u8;+ out.push(byte);+ if byte == 0xFF {+ out.push(0x00);+ }+ }+ }++ let mut prev_dc = [0i32; 3];+ let sun_x = (bw as f32) * 0.68;+ let sun_y = (bh as f32) * 0.30;+ let sun_r2 = ((bh.min(bw) as f32) * 0.18).powi(2).max(1.0);++ for by in 0..bh {+ let t = (by as f32) / ((bh.max(2) - 1) as f32);+ let horizon = t > 0.62;+ for bx in 0..bw {+ let dx = (bx as f32) - sun_x;+ let dy = (by as f32) - sun_y;+ let in_sun = dx * dx + dy * dy <= sun_r2;+ let (r, g, b) = if in_sun {+ sun+ } else if horizon {+ let ht = (t - 0.62) / 0.38;+ (+ (f32::from(bottom.0) * (1.0 - 0.25 * ht)) as u8,+ (f32::from(bottom.1) * (1.0 - 0.25 * ht)) as u8,+ (f32::from(bottom.2) * (1.0 - 0.25 * ht)) as u8,+ )+ } else {+ let st = t / 0.62;+ (+ (f32::from(top.0) * (1.0 - st) + f32::from(bottom.0) * st) as u8,+ (f32::from(top.1) * (1.0 - st) + f32::from(bottom.1) * st) as u8,+ (f32::from(top.2) * (1.0 - st) + f32::from(bottom.2) * st) as u8,+ )+ };+ let (rf, gf, bf) = (f32::from(r), f32::from(g), f32::from(b));+ let y = (0.299 * rf + 0.587 * gf + 0.114 * bf).round().clamp(0.0, 255.0) as i32 - 128;+ let cb =+ (128.0 - 0.168736 * rf - 0.331264 * gf + 0.5 * bf).round().clamp(0.0, 255.0) as i32 - 128;+ let cr =+ (128.0 + 0.5 * rf - 0.418688 * gf - 0.081312 * bf).round().clamp(0.0, 255.0) as i32 - 128;++ for (comp, dc) in [y, cb, cr].into_iter().enumerate() {+ let diff = dc - prev_dc[comp];+ prev_dc[comp] = dc;+ if diff == 0 {+ // DC category 0 (4 bits: 0000) + AC EOB (1 bit: 0)+ push_bits(&mut bit_buf, &mut bit_count, 0, 5, &mut out);+ } else {+ let abs = diff.unsigned_abs();+ let cat = 32 - abs.leading_zeros();+ let mag = if diff > 0 { diff as u16 } else { ((1u32 << cat) - 1 - abs) as u16 };+ push_bits(&mut bit_buf, &mut bit_count, cat as u16, 4, &mut out);+ push_bits(&mut bit_buf, &mut bit_count, mag, cat, &mut out);+ // AC EOB (1 bit: 0)+ push_bits(&mut bit_buf, &mut bit_count, 0, 1, &mut out);+ }+ }+ }+ }+ if bit_count > 0 {+ let pad = 8 - bit_count;+ push_bits(&mut bit_buf, &mut bit_count, (1u16 << pad) - 1, pad, &mut out);+ }+ // EOI+ out.extend_from_slice(&[0xFF, 0xD9]);+ out+}++fn sample_photos() {+ use nectarlink_core::{PhotoAlbum, PhotoItem};+ let now = std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .map_or(0, |d| d.as_millis() as i64);+ let min = 60_000i64;+ let hour = 60 * min;++ let specs = [+ (+ "media:demo-1",+ "IMG_20260406_184210.jpg",+ now - 25 * min,+ 1920,+ 1440,+ None,+ "bucket:camera",+ (255, 140, 82),+ (180, 62, 92),+ (255, 232, 160),+ ),+ (+ "media:demo-2",+ "IMG_20260406_161504.jpg",+ now - 2 * hour,+ 1920,+ 1440,+ None,+ "bucket:camera",+ (72, 158, 235),+ (26, 94, 150),+ (255, 246, 210),+ ),+ (+ "media:demo-5",+ "Screenshot_20260406_142011.jpg",+ now - 3 * hour,+ 1080,+ 2400,+ None,+ "bucket:screenshots",+ (46, 64, 87),+ (28, 40, 56),+ (110, 212, 196),+ ),+ (+ "video:demo-1",+ "VID_20260406_123000.mp4",+ now - 4 * hour,+ 1920,+ 1080,+ Some(18_000),+ "bucket:camera",+ (88, 178, 128),+ (38, 102, 68),+ (242, 248, 185),+ ),+ (+ "media:demo-3",+ "IMG_20260405_191200.jpg",+ now - 26 * hour,+ 1920,+ 1440,+ None,+ "bucket:camera",+ (118, 92, 196),+ (218, 112, 118),+ (255, 224, 152),+ ),+ (+ "media:demo-4",+ "IMG_20260405_154022.jpg",+ now - 29 * hour,+ 1920,+ 1440,+ None,+ "bucket:camera",+ (64, 188, 206),+ (28, 106, 128),+ (240, 250, 255),+ ),+ (+ "media:demo-6",+ "Screenshot_20260405_110509.jpg",+ now - 32 * hour,+ 1080,+ 2400,+ None,+ "bucket:screenshots",+ (238, 228, 212),+ (196, 180, 158),+ (226, 118, 76),+ ),+ (+ "media:demo-7",+ "IMG_20260405_093015.jpg",+ now - 35 * hour,+ 1920,+ 1440,+ None,+ "bucket:trips",+ (142, 182, 214),+ (76, 118, 104),+ (255, 240, 198),+ ),+ (+ "media:demo-8",+ "IMG_20260403_174500.jpg",+ now - 74 * hour,+ 1920,+ 1440,+ None,+ "bucket:trips",+ (232, 146, 102),+ (164, 74, 48),+ (255, 228, 168),+ ),+ (+ "media:demo-9",+ "IMG_20260403_141130.jpg",+ now - 77 * hour,+ 1920,+ 1440,+ None,+ "bucket:trips",+ (94, 186, 148),+ (36, 114, 82),+ (232, 250, 200),+ ),+ (+ "media:demo-10",+ "IMG_20260403_112045.jpg",+ now - 80 * hour,+ 1920,+ 1440,+ None,+ "bucket:trips",+ (102, 152, 224),+ (54, 88, 156),+ (255, 236, 184),+ ),+ (+ "media:demo-11",+ "IMG_20260403_085012.jpg",+ now - 82 * hour,+ 1920,+ 1440,+ None,+ "bucket:camera",+ (198, 148, 108),+ (116, 74, 48),+ (250, 222, 182),+ ),+ ];++ 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());+ 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 {+ item: PhotoItem {+ id: id.into(),+ name: name.into(),+ date,+ size,+ width: w,+ height: h,+ duration,+ album: Some(album.into()),+ },+ thumb_jpeg,+ full_path,+ });+ }+ *GALLERY_ITEMS.lock().unwrap() = items;+ *GALLERY_ALBUMS.lock().unwrap() = vec![+ PhotoAlbum {+ id: "bucket:camera".into(),+ name: "Camera".into(),+ count: 6,+ cover: Some("media:demo-1".into()),+ },+ PhotoAlbum {+ id: "bucket:screenshots".into(),+ name: "Screenshots".into(),+ count: 2,+ cover: Some("media:demo-5".into()),+ },+ PhotoAlbum {+ id: "bucket:trips".into(),+ name: "Weekend Trip".into(),+ count: 4,+ cover: Some("media:demo-7".into()),+ },+ ];+}+/// Rings by printing to the terminal (the CLI has no speaker access).#[derive(Debug)]struct TerminalPlatform;@@ -1045,13 +1436,57 @@ impl Platform for TerminalPlatform {items.sort_by_key(|a| (!a.starred, a.name.to_lowercase()));Ok(items.into_iter().skip(offset as usize).take(limit as usize).collect())}+ fn photo_albums(&self) -> std::result::Result<Vec<nectarlink_core::PhotoAlbum>, String> {+ Ok(GALLERY_ALBUMS.lock().unwrap().clone())+ }+ fn photo_list(+ &self,+ album: Option<&str>,+ before: Option<(i64, &str)>,+ limit: u32,+ ) -> std::result::Result<Vec<nectarlink_core::PhotoItem>, String> {+ let mut items: Vec<nectarlink_core::PhotoItem> = GALLERY_ITEMS+ .lock()+ .unwrap()+ .iter()+ .filter(|entry| {+ album.is_none_or(|a| entry.item.album.as_deref() == Some(a))+ && before.is_none_or(|(date, id)| (entry.item.date, entry.item.id.as_str()) < (date, id))+ })+ .map(|entry| entry.item.clone())+ .collect();+ items.sort_by(|a, b| (b.date, &b.id).cmp(&(a.date, &a.id)));+ items.truncate(limit as usize);+ Ok(items)+ }+ fn photo_thumbs(&self, ids: &[String]) -> std::result::Result<Vec<nectarlink_core::PhotoThumb>, String> {+ let items = GALLERY_ITEMS.lock().unwrap();+ Ok(ids+ .iter()+ .filter_map(|id| {+ let entry = items.iter().find(|e| e.item.id == *id)?;+ Some(nectarlink_core::PhotoThumb { id: id.clone(), data: entry.thumb_jpeg.clone() })+ })+ .collect())+ }fn open_photo(&self, id: &str) -> std::result::Result<nectarlink_core::OutgoingFile, String> {- let path = PHOTO.get().filter(|_| id == PHOTO_ID).ok_or("no such photo")?;- println!("A PC asked for the photo; sending it.");+ if id == PHOTO_ID+ && let Some(path) = PHOTO.get()+ {+ println!("A PC asked for the photo; sending it.");+ return Ok(nectarlink_core::OutgoingFile {+ name: nectarlink_core::safe_file_name(&path.to_string_lossy()),+ folder: None,+ source: nectarlink_core::FileSource::Path(path.clone()),+ });+ }+ let items = GALLERY_ITEMS.lock().unwrap();+ let entry = items.iter().find(|e| e.item.id == id).ok_or("no such photo")?;+ println!("A PC asked for gallery item {id}; sending it.");Ok(nectarlink_core::OutgoingFile {- name: nectarlink_core::safe_file_name(&path.to_string_lossy()),+ name: entry.item.name.clone(),folder: None,- source: nectarlink_core::FileSource::Path(path.clone()),+ source: nectarlink_core::FileSource::Path(entry.full_path.clone()),})}fn start_ringing(&self) {@@ -1293,12 +1728,88 @@ async fn run(cli: &Cli, node: &Node) -> Result<()> {println!("{name} is now {}", if on { "on" } else { "off" });}Command::Run => watch(node, false).await?,- Command::Photos => {+ Command::Photos { device: None, .. } => {let mut offers = cli.offers.clone();offers.push(nectarlink_core::PHOTOS_SHOW.into());node.update_power(node_power(cli), offers).await;watch(node, true).await?;}+ Command::Photos { device: Some(device), action } => {+ let mut offers = cli.offers.clone();+ offers.push(nectarlink_core::PHOTOS_SHOW.into());+ node.update_power(node_power(cli), offers).await;+ let id = resolve(node, device)?;+ wait_until_online(node, id).await?;+ match action.as_ref().unwrap_or(&PhotosArg::List { album: None, before: None, limit: 30 }) {+ PhotosArg::Albums => {+ for a in node.photo_albums(id).await.context("can't list albums")? {+ println!(+ "{:<24} {:>5} {} (cover {})",+ a.id,+ a.count,+ a.name,+ a.cover.as_deref().unwrap_or("-")+ );+ }+ }+ PhotosArg::List { album, before, limit } => {+ for item in node+ .photo_list(id, album.clone(), before.clone(), *limit)+ .await+ .context("can't list photos")?+ {+ let dim = if item.width > 0 && item.height > 0 {+ format!(" {}x{}", item.width, item.height)+ } else {+ String::new()+ };+ let dur = item+ .duration+ .map(|ms| format!(" video {}", clock(u64::from(ms))))+ .unwrap_or_default();+ let alb = item.album.map(|a| format!(" [{a}]")).unwrap_or_default();+ println!(+ "{:<18} {:>9} B {} {}{}{}{}",+ item.id, item.size, item.date, item.name, dim, dur, alb+ );+ }+ }+ PhotosArg::Thumbs { ids, out } => {+ let dir = out.clone().unwrap_or_else(|| PathBuf::from("."));+ std::fs::create_dir_all(&dir).context("can't create output directory")?;+ let thumbs =+ node.photo_thumbs(id, ids.clone()).await.context("can't fetch thumbnails")?;+ for t in thumbs {+ let safe = t.id.replace(':', "-");+ let path = dir.join(format!("{safe}.jpg"));+ std::fs::write(&path, &t.data).context("can't write thumbnail")?;+ println!("{} ({} B) -> {}", t.id, t.data.len(), path.display());+ }+ }+ PhotosArg::Get { ids } => {+ let mut events = node.events();+ let transfer_id =+ node.fetch_photos(id, ids.clone()).await.context("can't download photos")?;+ loop {+ match events.recv().await {+ Ok(NodeEvent::Transfer(t)) if t.id == transfer_id => match t.state {+ TransferState::Done { saved } => {+ for path in saved {+ println!("{}", path.display());+ }+ break;+ }+ TransferState::Failed(why) => bail!("download failed: {why:?}"),+ TransferState::Cancelled => bail!("download cancelled"),+ _ => {}+ },+ Ok(_) | Err(RecvError::Lagged(_)) => {}+ Err(RecvError::Closed) => bail!("node stopped"),+ }+ }+ }+ }+ }Command::Input { device, session, action } => {use nectarlink_core::{MirrorInput, TouchAction};let mut offers = cli.offers.clone();@@ -1584,6 +2095,7 @@ async fn run(cli: &Cli, node: &Node) -> Result<()> {sample_texts();sample_contacts();sample_call_log();+ sample_photos();let _ = TEXTS_NODE.set(node.clone());let _ = CALL_NODE.set(node.clone());CALL_CONTROLS.store(true, std::sync::atomic::Ordering::Relaxed);@@ -1603,6 +2115,7 @@ async fn run(cli: &Cli, node: &Node) -> Result<()> {nectarlink_core::CALLS_LOG,nectarlink_core::CALLS_DIAL,nectarlink_core::CONTACTS_READ,+ nectarlink_core::PHOTOS_READ,].map(str::to_owned),);@@ -2231,6 +2744,7 @@ fn print_event(node: &Node, event: &NodeEvent) {),NodeEvent::CallLogChanged { device } => println!("{}: call log changed", name(device)),NodeEvent::ContactsChanged { device } => println!("{}: contacts changed", name(device)),+ NodeEvent::PhotosChanged { device } => println!("{}: photo library changed", name(device)),NodeEvent::PhotoAdded { device, photo } => println!("{}: new {} {} ({} bytes, preview {} bytes)",name(device),diff --git a/core/nectarlink-core/src/config.rs b/core/nectarlink-core/src/config.rsindex 06ca75c..e192a40 100644--- a/core/nectarlink-core/src/config.rs+++ b/core/nectarlink-core/src/config.rs@@ -116,9 +116,33 @@ pub trait Platform: Send + Sync + 'static {Err("this device doesn't open links".into())}- /// Open a photo this phone announced (with- /// [`Node::photo_taken`](crate::Node::photo_taken)), for sending it to a- /// PC that asked. `Err` (a reason for logs) when it's gone.+ /// List photo and video albums on this phone (`photos.albums`).+ fn photo_albums(&self) -> Result<Vec<crate::PhotoAlbum>, String> {+ Err("this device doesn't share photos".into())+ }++ /// List photos and videos on this phone (or in `album`), newest first by+ /// date and then by a stable order of its own (`photos.list`). `before`+ /// is the previous page's last item (date and ID): list only what comes+ /// after it in that order; from the latest when `None`.+ fn photo_list(+ &self,+ _album: Option<&str>,+ _before: Option<(i64, &str)>,+ _limit: u32,+ ) -> Result<Vec<crate::PhotoItem>, String> {+ Err("this device doesn't share photos".into())+ }++ /// Small JPEG thumbnails for the requested item IDs (`photos.thumbs`).+ /// Items whose thumbnail can't be generated are omitted rather than+ /// failing the batch.+ fn photo_thumbs(&self, _ids: &[String]) -> Result<Vec<crate::PhotoThumb>, String> {+ Err("this device doesn't share photos".into())+ }++ /// Open a photo or video on this phone for sending it to a PC that asked+ /// (`photos.get`). `Err` (a reason for logs) when it's gone.fn open_photo(&self, _id: &str) -> Result<crate::OutgoingFile, String> {Err("this device doesn't share photos".into())}diff --git a/core/nectarlink-core/src/events.rs b/core/nectarlink-core/src/events.rsindex 5996a4d..88f1b7f 100644--- a/core/nectarlink-core/src/events.rs+++ b/core/nectarlink-core/src/events.rs@@ -134,6 +134,10 @@ pub enum NodeEvent {device: DeviceId,photo: crate::Photo,},+ /// A phone's photo or video library changed.+ PhotosChanged {+ device: DeviceId,+ },/// A call on a phone rang, was answered or ended.Call {device: DeviceId,diff --git a/core/nectarlink-core/src/lib.rs b/core/nectarlink-core/src/lib.rsindex 4b5c9fd..697dc11 100644--- a/core/nectarlink-core/src/lib.rs+++ b/core/nectarlink-core/src/lib.rs@@ -45,8 +45,8 @@ pub use nectarlink_protocol::{messages::{Battery, CLIP_MAX_BYTES, CallControls, CallLogEntry, CallState, Contact, ContactNumber, DeviceInfo,DeviceKind, MediaPlayer, MirrorAudioConfig, MirrorConfig, MirrorInput, MirrorResize, MirrorStart,- Notification, NotificationAction, PhoneApp, PhotoNew as Photo, PowerLevel, SmsMessage, SmsPart,- SmsThread, TouchAction,+ Notification, NotificationAction, PhoneApp, PhotoAlbum, PhotoItem, PhotoNew as Photo, PhotoThumb,+ PowerLevel, SmsMessage, SmsPart, SmsThread, TouchAction,calls::{CONTROL as CALLS_CONTROL, DIAL as CALLS_DIAL, IN_CALL as CALLS_IN_CALL, LOG as CALLS_LOG,SHOW as CALLS_SHOW, STATE as CALLS_STATE,@@ -60,7 +60,11 @@ pub use nectarlink_protocol::{VIRTUAL_DISPLAY as MIRROR_VIRTUAL_DISPLAY,},mirror_keys,- photos::{MAX_THUMB_BYTES as PHOTO_MAX_THUMB_BYTES, READ as PHOTOS_READ, SHOW as PHOTOS_SHOW},+ photos::{+ MAX_GET_ITEMS as PHOTO_MAX_GET_ITEMS, MAX_PAGE as PHOTO_MAX_PAGE,+ MAX_THUMB_BATCH as PHOTO_MAX_THUMB_BATCH, MAX_THUMB_BYTES as PHOTO_MAX_THUMB_BYTES,+ READ as PHOTOS_READ, SHOW as PHOTOS_SHOW,+ },sms::{READ as SMS_READ, SEND as SMS_SEND, SHOW as SMS_SHOW},},pairing::PairingUri,diff --git a/core/nectarlink-core/src/node.rs b/core/nectarlink-core/src/node.rsindex 54bfb99..fe17788 100644--- a/core/nectarlink-core/src/node.rs+++ b/core/nectarlink-core/src/node.rs@@ -118,8 +118,6 @@ pub(crate) struct Shared {pub notifications: Feed,/// This device's media players (docs/protocol/media.md).pub players: crate::media::Players,- /// Photos this phone announced lately (docs/protocol/photos.md).- pub(crate) photos: crate::photos::Recent,/// This phone's call in progress (docs/protocol/calls.md).pub(crate) calls: crate::calls::Current,/// Stop signals for phone screens shown here, by phone.@@ -619,7 +617,6 @@ impl Node {memory,notifications: Feed::default(),players: Default::default(),- photos: Default::default(),calls: Default::default(),mirror_stops: Mutex::new(HashMap::new()),data_dir: config.data_dir.clone(),@@ -1100,13 +1097,52 @@ impl Node {self.shared.photo_taken(photo).await}- /// Asks a phone for a photo it announced; returns the ID of the- /// transfer that brings it (reported like any other).+ /// This phone's photo or video library changed: connected PCs that show+ /// photos catch up.+ pub async fn photos_changed(&self) {+ self.shared.photos_changed().await;+ }++ /// Lists a paired phone's photo and video albums.+ pub async fn photo_albums(&self, peer: DeviceId) -> Result<Vec<crate::PhotoAlbum>> {+ let session = self.connected(&peer)?;+ crate::photos::albums(&self.shared, &session).await+ }++ /// Lists a paired phone's photos and videos (in `album`, or all when+ /// `None`), newest first: from the latest, or after `before`, the+ /// previous page's last item (its date and ID).+ pub async fn photo_list(+ &self,+ peer: DeviceId,+ album: Option<String>,+ before: Option<(i64, String)>,+ limit: u32,+ ) -> Result<Vec<crate::PhotoItem>> {+ let session = self.connected(&peer)?;+ crate::photos::list(&self.shared, &session, album, before, limit).await+ }++ /// Fetches small JPEG thumbnails for a batch of item IDs on a paired phone.+ pub async fn photo_thumbs(&self, peer: DeviceId, ids: Vec<String>) -> Result<Vec<crate::PhotoThumb>> {+ let session = self.connected(&peer)?;+ crate::photos::thumbs(&self.shared, &session, ids).await+ }++ /// Asks a phone for a photo or video; returns the ID of the transfer+ /// that brings it (reported like any other).pub async fn fetch_photo(&self, peer: DeviceId, id: String) -> Result<String> {let session = self.connected(&peer)?;crate::photos::fetch(&self.shared, &session, id).await}+ /// Asks a phone for one or more photos or videos in a single transfer;+ /// returns the transfer ID.+ pub async fn fetch_photos(&self, peer: DeviceId, ids: Vec<String>) -> Result<String> {+ let session = self.connected(&peer)?;+ crate::photos::fetch_many(&self.shared, &session, ids).await+ }+// ---- Media (docs/protocol/media.md) ----/// This device's media players changed (most relevant first); sent todiff --git a/core/nectarlink-core/src/photos.rs b/core/nectarlink-core/src/photos.rsindex 7e9678d..51ec07b 100644--- a/core/nectarlink-core/src/photos.rs+++ b/core/nectarlink-core/src/photos.rs@@ -1,40 +1,24 @@// SPDX-License-Identifier: MPL-2.0-//! Recent photos (docs/protocol/photos.md): a phone announces each new-//! photo or screenshot to PCs with a preview, and sends the photo itself-//! (as a files transfer) when a PC asks for it.+//! Photos and gallery (docs/protocol/photos.md): a phone announces each new+//! photo or screenshot to PCs with a preview, lists its albums and items,+//! serves thumbnails in batches, and sends full photos or videos (as a files+//! transfer) when a PC asks for them.-use std::{collections::VecDeque, sync::Arc};+use std::sync::Arc;use nectarlink_protocol::{DeviceId, Envelope, ErrorCode,- messages::{PhotoGet, PhotoNew, PhotoSending, photos, types},+ messages::{+ PhotoAlbum, PhotoAlbumsGet, PhotoAlbumsList, PhotoGet, PhotoItem, PhotoItems, PhotoListGet, PhotoNew,+ PhotoSending, PhotoThumb, PhotoThumbsGet, PhotoThumbsList, PhotosChanged, is_valid_photo_id, photos,+ types,+ },};-use crate::{Error, Result, events::NodeEvent, node::Shared, session::Session};+use crate::{Error, Result, events::NodeEvent, node::Shared, session::Session, transfer::safe_file_name};-/// The device toggle that allows recent photos for a device.+/// The device toggle that allows photos and gallery access for a device.pub(crate) const TOGGLE: &str = "photos";-/// A PC can ask for this many of the latest announced photos.-const REMEMBERED: usize = 50;--/// The photos this phone announced lately: the only ones a PC may ask for.-#[derive(Debug, Default)]-pub(crate) struct Recent(std::sync::Mutex<VecDeque<String>>);--impl Recent {- fn add(&self, id: &str) {- let mut ids = self.0.lock().unwrap_or_else(|e| e.into_inner());- ids.retain(|known| known != id);- ids.push_back(id.to_owned());- while ids.len() > REMEMBERED {- ids.pop_front();- }- }-- fn contains(&self, id: &str) -> bool {- self.0.lock().unwrap_or_else(|e| e.into_inner()).iter().any(|known| known == id)- }-}impl Shared {/// PCs that show photos and are allowed them.@@ -62,26 +46,100 @@ impl Shared {Error::Protocol("invalid photo".into())});}- self.photos.add(&photo.id);let env = Envelope::new(types::PHOTOS_NEW, &photo)?;for session in self.photo_targets() {let _ = session.send(env.clone()).await;}Ok(())}++ pub(crate) async fn photos_changed(&self) {+ let Ok(env) = Envelope::new(types::PHOTOS_CHANGED, &PhotosChanged {}) else { return };+ for session in self.photo_targets() {+ let _ = session.send(env.clone()).await;+ }+ }+}++// ---- A PC asking ----++fn allowed(shared: &Shared, peer: &DeviceId) -> Result<()> {+ if shared.toggle_on(peer, TOGGLE) { Ok(()) } else { Err(Error::Denied) }+}++/// Lists a phone's photo and video albums (`photos.albums`).+pub(crate) async fn albums(shared: &Shared, session: &Session) -> Result<Vec<PhotoAlbum>> {+ allowed(shared, &session.peer)?;+ let env = Envelope::new(types::PHOTOS_ALBUMS, &PhotoAlbumsGet {})?;+ let PhotoAlbumsList { albums } = session+ .request(env, crate::session::REQUEST_TIMEOUT)+ .await?+ .expect_body(types::PHOTOS_ALBUMS_LIST)?;+ Ok(albums)}-/// Asks a phone for a photo it announced; returns the transfer that brings it.+/// Lists a phone's photos and videos (`photos.list`), newest first.+pub(crate) async fn list(+ shared: &Shared,+ session: &Session,+ album: Option<String>,+ before: Option<(i64, String)>,+ limit: u32,+) -> Result<Vec<PhotoItem>> {+ allowed(shared, &session.peer)?;+ let album = album.map(|a| a.trim().to_owned()).filter(|a| !a.is_empty());+ let (before, before_id) = before.map_or((None, None), |(date, id)| (Some(date), Some(id)));+ let env = Envelope::new(+ types::PHOTOS_LIST,+ &PhotoListGet { album, before, before_id, limit: limit.clamp(1, photos::MAX_PAGE) },+ )?;+ let PhotoItems { items } =+ session.request(env, crate::session::REQUEST_TIMEOUT).await?.expect_body(types::PHOTOS_ITEMS)?;+ Ok(items)+}++/// Fetches small JPEG thumbnails for a batch of item IDs (`photos.thumbs`).+pub(crate) async fn thumbs(+ shared: &Shared,+ session: &Session,+ mut ids: Vec<String>,+) -> Result<Vec<PhotoThumb>> {+ allowed(shared, &session.peer)?;+ ids.retain(|id| is_valid_photo_id(id));+ ids.truncate(photos::MAX_THUMB_BATCH);+ if ids.is_empty() {+ return Ok(Vec::new());+ }+ let env = Envelope::new(types::PHOTOS_THUMBS, &PhotoThumbsGet { ids })?;+ let PhotoThumbsList { thumbs } = session+ .request(env, crate::session::REQUEST_TIMEOUT)+ .await?+ .expect_body(types::PHOTOS_THUMBS_LIST)?;+ Ok(thumbs)+}++/// Asks a phone for a photo or video; returns the transfer that brings it.pub(crate) async fn fetch(shared: &Shared, session: &Session, id: String) -> Result<String> {- if !shared.toggle_on(&session.peer, TOGGLE) {- return Err(Error::Denied);+ fetch_many(shared, session, vec![id]).await+}++/// Asks a phone for one or more photos or videos in a single transfer.+pub(crate) async fn fetch_many(shared: &Shared, session: &Session, mut ids: Vec<String>) -> Result<String> {+ allowed(shared, &session.peer)?;+ ids.retain(|id| is_valid_photo_id(id));+ ids.truncate(photos::MAX_GET_ITEMS);+ if ids.is_empty() {+ return Err(Error::Protocol("no photo IDs requested".into()));}- let env = Envelope::new(types::PHOTOS_GET, &PhotoGet { id })?;+ let id = if ids.len() == 1 { ids[0].clone() } else { String::new() };+ let env = Envelope::new(types::PHOTOS_GET, &PhotoGet { id, ids })?;let reply = session.request(env, crate::session::REQUEST_TIMEOUT).await?;let PhotoSending { transfer } = reply.expect_body(types::PHOTOS_SENDING)?;Ok(transfer)}+// ---- The phone answering ----+/// Handles `photos.*`. Returns false for other types.pub(crate) async fn handle(shared: &Arc<Shared>, session: &Arc<Session>, env: &Envelope) -> Result<bool> {let peer = session.peer;@@ -94,14 +152,34 @@ pub(crate) async fn handle(shared: &Arc<Shared>, session: &Arc<Session>, env: &E}Ok(true)}+ types::PHOTOS_CHANGED => {+ let PhotosChanged {} = env.body()?;+ let shows = shared.local_capabilities().iter().any(|c| c == photos::SHOW);+ if shows && shared.toggle_on(&peer, TOGGLE) {+ shared.emit(NodeEvent::PhotosChanged { device: peer });+ }+ Ok(true)+ }+ types::PHOTOS_ALBUMS | types::PHOTOS_LIST | types::PHOTOS_THUMBS => {+ let reply = answer_query(shared, peer, env).await.unwrap_or_else(|e| {+ tracing::debug!(error = %e, "bad photos request");+ Envelope::error(ErrorCode::BadMessage, "invalid request")+ });+ session.send(reply.reply_to(env.id)).await?;+ Ok(true)+ }types::PHOTOS_GET => {- let PhotoGet { id } = env.body()?;- let reply = match send_photo(shared, peer, &id).await {+ let get: PhotoGet = env.body()?;+ let reply = match send_photos(shared, peer, get.requested_ids()).await {Ok(transfer) => Envelope::new(types::PHOTOS_SENDING, &PhotoSending { transfer })?,Err(Error::Denied) => {Envelope::error(ErrorCode::Denied, "photos or files are off for this device")}+ Err(Error::Unsupported) => {+ Envelope::error(ErrorCode::Unsupported, "this phone doesn't share photos")+ }Err(Error::NotFound) => Envelope::error(ErrorCode::NotFound, "no such photo"),+ Err(Error::Protocol(_)) => Envelope::error(ErrorCode::BadMessage, "invalid photo request"),Err(e) => {tracing::warn!(error = %e, "can't send a photo");Envelope::error(ErrorCode::Internal, "can't send it")@@ -114,23 +192,133 @@ pub(crate) async fn handle(shared: &Arc<Shared>, session: &Arc<Session>, env: &E}}-async fn send_photo(shared: &Arc<Shared>, peer: DeviceId, id: &str) -> Result<String> {+async fn answer_query(shared: &Arc<Shared>, peer: DeviceId, env: &Envelope) -> Result<Envelope> {+ if !shared.toggle_on(&peer, TOGGLE) {+ return Ok(Envelope::error(ErrorCode::Denied, "photos are off for this device"));+ }+ if !shared.local_capabilities().iter().any(|c| c == photos::READ) {+ return Ok(Envelope::error(ErrorCode::Unsupported, "this phone doesn't share photos"));+ }+ let platform = shared.platform.clone();+ let result = match env.t.as_str() {+ types::PHOTOS_ALBUMS => {+ let PhotoAlbumsGet {} = env.body()?;+ tokio::task::spawn_blocking(move || {+ let albums = sanitize_albums(platform.photo_albums()?);+ crate::sms::fit(albums, |albums| {+ Envelope::new(types::PHOTOS_ALBUMS_LIST, &PhotoAlbumsList { albums })+ })+ })+ .await+ .unwrap_or_else(|e| Err(e.to_string()))+ }+ types::PHOTOS_LIST => {+ let PhotoListGet { album, before, before_id, limit } = env.body()?;+ let album = album.map(|a| a.trim().to_owned()).filter(|a| !a.is_empty());+ let limit = limit.clamp(1, photos::MAX_PAGE);+ // An older PC sends only `before`: everything from that date on+ // was on its pages.+ let before_id = before_id.filter(|id| is_valid_photo_id(id)).unwrap_or_default();+ tokio::task::spawn_blocking(move || {+ let before = before.map(|date| (date, before_id.as_str()));+ let items = sanitize_items(platform.photo_list(album.as_deref(), before, limit)?);+ crate::sms::fit(items, |items| Envelope::new(types::PHOTOS_ITEMS, &PhotoItems { items }))+ })+ .await+ .unwrap_or_else(|e| Err(e.to_string()))+ }+ types::PHOTOS_THUMBS => {+ let PhotoThumbsGet { mut ids } = env.body()?;+ ids.retain(|id| is_valid_photo_id(id));+ ids.truncate(photos::MAX_THUMB_BATCH);+ if ids.is_empty() {+ return Envelope::new(types::PHOTOS_THUMBS_LIST, &PhotoThumbsList { thumbs: Vec::new() })+ .map_err(Into::into);+ }+ tokio::task::spawn_blocking(move || {+ let thumbs = sanitize_thumbs(platform.photo_thumbs(&ids)?);+ crate::sms::fit(thumbs, |thumbs| {+ Envelope::new(types::PHOTOS_THUMBS_LIST, &PhotoThumbsList { thumbs })+ })+ })+ .await+ .unwrap_or_else(|e| Err(e.to_string()))+ }+ _ => unreachable!(),+ };+ Ok(result.unwrap_or_else(|reason| {+ tracing::warn!(reason, "a photos request failed");+ Envelope::error(ErrorCode::Internal, "the phone couldn't read photos")+ }))+}++fn sanitize_albums(albums: Vec<PhotoAlbum>) -> Vec<PhotoAlbum> {+ albums+ .into_iter()+ .filter_map(|mut a| {+ let id = a.id.trim().to_owned();+ let name = a.name.trim().to_owned();+ if id.is_empty() || name.is_empty() || a.count == 0 {+ return None;+ }+ a.id = id;+ a.name = name;+ a.cover = a.cover.filter(|c| is_valid_photo_id(c));+ Some(a)+ })+ .collect()+}++fn sanitize_items(items: Vec<PhotoItem>) -> Vec<PhotoItem> {+ items+ .into_iter()+ .filter_map(|mut item| {+ if !is_valid_photo_id(&item.id) {+ return None;+ }+ item.name = safe_file_name(&item.name);+ item.album = item.album.map(|a| a.trim().to_owned()).filter(|a| !a.is_empty());+ Some(item)+ })+ .collect()+}++fn sanitize_thumbs(thumbs: Vec<PhotoThumb>) -> Vec<PhotoThumb> {+ thumbs+ .into_iter()+ .filter(|t| is_valid_photo_id(&t.id) && !t.data.is_empty() && t.data.len() <= photos::MAX_THUMB_BYTES)+ .collect()+}++async fn send_photos(shared: &Arc<Shared>, peer: DeviceId, mut ids: Vec<String>) -> Result<String> {if !shared.toggle_on(&peer, TOGGLE) {return Err(Error::Denied);}- if !shared.photos.contains(id) {- return Err(Error::NotFound);+ if !shared.local_capabilities().iter().any(|c| c == photos::READ) {+ return Err(Error::Unsupported);+ }+ ids.retain(|id| is_valid_photo_id(id));+ ids.truncate(photos::MAX_GET_ITEMS);+ if ids.is_empty() {+ return Err(Error::Protocol("no valid photo IDs".into()));}let platform = shared.platform.clone();- let owned = id.to_owned();- let file = tokio::task::spawn_blocking(move || platform.open_photo(&owned))- .await- .map_err(|e| Error::Internal(e.to_string()))?- .map_err(|reason| {- tracing::info!(reason, "an announced photo can't be opened");- Error::NotFound- })?;- crate::transfer::send(shared, peer, vec![file]).await+ let files = tokio::task::spawn_blocking(move || -> Result<Vec<crate::OutgoingFile>> {+ let mut out = Vec::with_capacity(ids.len());+ for id in &ids {+ match platform.open_photo(id) {+ Ok(file) => out.push(file),+ Err(reason) => {+ tracing::info!(reason, "a requested photo can't be opened");+ return Err(Error::NotFound);+ }+ }+ }+ Ok(out)+ })+ .await+ .map_err(|e| Error::Internal(e.to_string()))??;+ crate::transfer::send(shared, peer, files).await}#[cfg(test)]@@ -138,17 +326,48 @@ mod tests {use super::*;#[test]- fn only_the_latest_are_remembered() {- let recent = Recent::default();- for i in 0..REMEMBERED + 5 {- recent.add(&i.to_string());- }- assert!(!recent.contains("0") && !recent.contains("4"));- assert!(recent.contains("5") && recent.contains(&(REMEMBERED + 4).to_string()));- // Announcing one again moves it to the end.- recent.add("5");- recent.add("new");- assert!(recent.contains("5"));- assert!(!recent.contains("6"));+ fn sanitizing_cleans_albums_items_and_thumbs() {+ let albums = sanitize_albums(vec![+ PhotoAlbum { id: " b1 ".into(), name: " Camera ".into(), count: 3, cover: Some("p1".into()) },+ PhotoAlbum { id: "b2".into(), name: "Empty".into(), count: 0, cover: None },+ PhotoAlbum { id: "b3".into(), name: "Bad cover".into(), count: 1, cover: Some("bad id".into()) },+ ]);+ assert_eq!(albums.len(), 2);+ assert_eq!((albums[0].id.as_str(), albums[0].name.as_str()), ("b1", "Camera"));+ assert_eq!(albums[1].cover, None);++ let items = sanitize_items(vec![+ PhotoItem {+ id: "p1".into(),+ name: "../IMG_001.jpg".into(),+ date: 100,+ size: 10,+ width: 800,+ height: 600,+ duration: None,+ album: Some(" b1 ".into()),+ },+ PhotoItem {+ id: "bad id".into(),+ name: "x.jpg".into(),+ date: 90,+ size: 10,+ width: 0,+ height: 0,+ duration: None,+ album: None,+ },+ ]);+ assert_eq!(items.len(), 1);+ assert_eq!(items[0].name, "IMG_001.jpg");+ assert_eq!(items[0].album.as_deref(), Some("b1"));++ let thumbs = sanitize_thumbs(vec![+ PhotoThumb { id: "p1".into(), data: vec![0xff, 0xd8] },+ PhotoThumb { id: "p2".into(), data: Vec::new() },+ PhotoThumb { id: "p3".into(), data: vec![0; photos::MAX_THUMB_BYTES + 1] },+ ]);+ assert_eq!(thumbs.len(), 1);+ assert_eq!(thumbs[0].id, "p1");}}diff --git a/core/nectarlink-core/src/session.rs b/core/nectarlink-core/src/session.rsindex aa66b2e..1c5196b 100644--- a/core/nectarlink-core/src/session.rs+++ b/core/nectarlink-core/src/session.rs@@ -318,6 +318,9 @@ fn is_background_rpc(t: &str) -> bool {| types::NOTIFY_ACTION| types::PC_POWER| types::LINK_OPEN+ | types::PHOTOS_ALBUMS+ | types::PHOTOS_LIST+ | types::PHOTOS_THUMBS| types::PHOTOS_GET| types::MIRROR_START| types::MIRROR_APPSdiff --git a/core/nectarlink-core/tests/two_devices.rs b/core/nectarlink-core/tests/two_devices.rsindex e6c3f3e..18cec9f 100644--- a/core/nectarlink-core/tests/two_devices.rs+++ b/core/nectarlink-core/tests/two_devices.rs@@ -273,6 +273,102 @@ impl Platform for RecordingPlatform {let name = path.file_name().unwrap().to_string_lossy().into_owned();Ok(OutgoingFile { name, folder: None, source: FileSource::Path(path) })}+ fn photo_albums(&self) -> Result<Vec<nectarlink_core::PhotoAlbum>, String> {+ use nectarlink_core::PhotoAlbum;+ Ok(vec![+ PhotoAlbum { id: "cam".into(), name: "Camera".into(), count: 3, cover: Some("media:4".into()) },+ PhotoAlbum {+ id: "shots".into(),+ name: "Screenshots".into(),+ count: 2,+ cover: Some("media:3".into()),+ },+ ])+ }+ fn photo_list(+ &self,+ album: Option<&str>,+ before: Option<(i64, &str)>,+ limit: u32,+ ) -> Result<Vec<nectarlink_core::PhotoItem>, String> {+ use nectarlink_core::PhotoItem;+ let all = vec![+ PhotoItem {+ id: "media:4".into(),+ name: "IMG_4.jpg".into(),+ date: 4_000,+ size: 100,+ width: 1920,+ height: 1080,+ duration: None,+ album: Some("cam".into()),+ },+ PhotoItem {+ id: "media:3".into(),+ name: "Screenshot_3.png".into(),+ date: 3_000,+ size: 80,+ width: 1080,+ height: 2400,+ duration: None,+ album: Some("shots".into()),+ },+ PhotoItem {+ id: "media:2".into(),+ name: "VID_2.mp4".into(),+ // Taken the same millisecond as media:3, across a page break.+ date: 3_000,+ size: 5_000,+ width: 1920,+ height: 1080,+ duration: Some(14),+ album: Some("cam".into()),+ },+ PhotoItem {+ id: "media:1".into(),+ name: "IMG_1.jpg".into(),+ date: 1_000,+ size: 90,+ width: 1920,+ height: 1080,+ duration: None,+ album: Some("cam".into()),+ },+ PhotoItem {+ id: "media:0".into(),+ name: "Screenshot_0.png".into(),+ date: 500,+ size: 70,+ width: 1080,+ height: 2400,+ duration: None,+ album: Some("shots".into()),+ },+ ];+ Ok(all+ .into_iter()+ .filter(|i| album.is_none_or(|a| i.album.as_deref() == Some(a)))+ .filter(|i| before.is_none_or(|(date, id)| i.date < date || (i.date == date && *i.id < *id)))+ .take(limit as usize)+ .collect())+ }+ fn photo_thumbs(&self, ids: &[String]) -> Result<Vec<nectarlink_core::PhotoThumb>, String> {+ use nectarlink_core::PhotoThumb;+ Ok(ids+ .iter()+ .filter_map(|id| match id.as_str() {+ "media:4" | "media:3" | "media:2" | "media:1" | "media:0" => Some(PhotoThumb {+ id: id.clone(),+ data: vec![0xff, 0xd8, id.as_bytes().last().copied().unwrap()],+ }),+ "oversized" => Some(PhotoThumb {+ id: id.clone(),+ data: vec![0; nectarlink_core::PHOTO_MAX_THUMB_BYTES + 1],+ }),+ _ => None,+ })+ .collect())+ }fn media_command(&self,player: &str,@@ -1407,11 +1503,17 @@ async fn phone_apps_open_in_windows_of_their_own() {}).await;assert_eq!(ended, 7);- let asks = phone.platform.mirror_asks.lock().unwrap().clone();+ // The phone handles some of these off the control stream, so give it a+ // moment to get to all of them.for wanted in["start 1280 com.example.chat as 7", "resize 7 1024x768", "Key(back) on 7", "keyframe 7", "stop 7"]{- assert!(asks.iter().any(|a| a == wanted), "{wanted}: {asks:?}");+ let deadline = std::time::Instant::now() + Duration::from_secs(5);+ while !phone.platform.mirror_asks.lock().unwrap().iter().any(|a| a == wanted) {+ let asks = phone.platform.mirror_asks.lock().unwrap().clone();+ assert!(std::time::Instant::now() < deadline, "{wanted}: {asks:?}");+ tokio::time::sleep(Duration::from_millis(20)).await;+ }}assert_eq!(*pc.platform.mirror_asks.lock().unwrap(), ["sink 7"]);@@ -1852,3 +1954,107 @@ async fn contacts_list_search_page_and_respect_permissions_and_toggles() {phone.node.set_device_toggle(pc_id, "contacts", false).unwrap();assert!(matches!(pc.node.contacts(phone_id, None, 0, 10).await, Err(Error::Denied)));}++#[tokio::test(flavor = "multi_thread")]+async fn gallery_albums_paging_thumbs_download_and_toggles() {+ let mut pc = device_with("Desktop", DeviceKind::Desktop, &[nectarlink_core::PHOTOS_SHOW]).await;+ let mut phone = device_with("Pixel", DeviceKind::Phone, &[]).await;+ pair_qr(&mut pc, &mut phone).await;+ let (pc_id, phone_id) = (pc.node.device_id(), phone.node.device_id());++ // Without `photos.read` on the phone, gallery queries are unsupported.+ assert!(matches!(pc.node.photo_albums(phone_id).await, Err(Error::Unsupported)));+ assert!(matches!(pc.node.photo_list(phone_id, None, None, 10).await, Err(Error::Unsupported)));+ assert!(matches!(pc.node.photo_thumbs(phone_id, vec!["media:4".into()]).await, Err(Error::Unsupported)));++ phone+ .node+ .update_power(+ PowerLevel::NotApplicable,+ vec!["media.control".into(), nectarlink_core::PHOTOS_READ.into()],+ )+ .await;+ wait_for(&mut pc, "photos.read unlocked", |e| match e {+ NodeEvent::Capabilities(m)+ if m.device == phone_id && m.state("files.recent_photos") == Some(FeatureState::Available) =>+ {+ Some(())+ }+ _ => None,+ })+ .await;++ // Albums list.+ let albums = with_timeout("albums", pc.node.photo_albums(phone_id)).await.unwrap();+ assert_eq!(albums.len(), 2);+ assert_eq!((&*albums[0].id, &*albums[0].name, albums[0].count), ("cam", "Camera", 3));+ assert_eq!(albums[0].cover.as_deref(), Some("media:4"));+ assert_eq!((&*albums[1].id, &*albums[1].name, albums[1].count), ("shots", "Screenshots", 2));++ // Paging all items newest-first; an item sharing the last one's date+ // still comes on the next page.+ let page1 = with_timeout("list page 1", pc.node.photo_list(phone_id, None, None, 2)).await.unwrap();+ assert_eq!(page1.iter().map(|i| i.id.as_str()).collect::<Vec<_>>(), ["media:4", "media:3"]);+ let last = Some((page1[1].date, page1[1].id.clone()));+ let page2 = with_timeout("list page 2", pc.node.photo_list(phone_id, None, last, 2)).await.unwrap();+ assert_eq!(page2.iter().map(|i| i.id.as_str()).collect::<Vec<_>>(), ["media:2", "media:1"]);+ assert_eq!(page2[0].duration, Some(14));++ // Filtering by album.+ let shots = with_timeout("list album", pc.node.photo_list(phone_id, Some("shots".into()), None, 10))+ .await+ .unwrap();+ assert_eq!(shots.iter().map(|i| i.id.as_str()).collect::<Vec<_>>(), ["media:3", "media:0"]);++ // Batch thumbnails (oversized or missing ones are skipped without failing the batch).+ let thumbs = with_timeout(+ "thumbs",+ pc.node.photo_thumbs(+ phone_id,+ vec!["media:4".into(), "oversized".into(), "gone".into(), "media:2".into()],+ ),+ )+ .await+ .unwrap();+ assert_eq!(thumbs.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(), ["media:4", "media:2"]);+ assert_eq!(thumbs[0].data, vec![0xff, 0xd8, b'4']);+ assert_eq!(thumbs[1].data, vec![0xff, 0xd8, b'2']);++ // Multi-file download via `fetch_photos`.+ let img4 = phone.dir.path().join("IMG_4.jpg");+ let vid2 = phone.dir.path().join("VID_2.mp4");+ let bytes4 = data(50_000, 11);+ let bytes2 = data(120_000, 12);+ std::fs::write(&img4, &bytes4).unwrap();+ std::fs::write(&vid2, &bytes2).unwrap();+ {+ let mut map = phone.platform.photos.lock().unwrap();+ map.insert("media:4".into(), img4);+ map.insert("media:2".into(), vid2);+ }+ let tid = with_timeout(+ "fetch_photos",+ pc.node.fetch_photos(phone_id, vec!["media:4".into(), "media:2".into()]),+ )+ .await+ .unwrap();+ let files = wait_transfer(&mut pc, &tid, "gallery files", saved).await;+ assert_eq!(files.len(), 2);+ assert_eq!(std::fs::read(&files[0]).unwrap(), bytes4);+ assert_eq!(std::fs::read(&files[1]).unwrap(), bytes2);++ // `photos.changed` notification.+ phone.node.photos_changed().await;+ wait_for(&mut pc, "photos changed", |e| match e {+ NodeEvent::PhotosChanged { device } if *device == phone_id => Some(()),+ _ => None,+ })+ .await;++ // Turning `photos` toggle off on the phone blocks albums, list, thumbs, and download.+ phone.node.set_device_toggle(pc_id, "photos", false).unwrap();+ assert!(matches!(pc.node.photo_albums(phone_id).await, Err(Error::Denied)));+ assert!(matches!(pc.node.photo_list(phone_id, None, None, 10).await, Err(Error::Denied)));+ assert!(matches!(pc.node.photo_thumbs(phone_id, vec!["media:4".into()]).await, Err(Error::Denied)));+ assert!(matches!(pc.node.fetch_photos(phone_id, vec!["media:4".into()]).await, Err(Error::Denied)));+}diff --git a/core/nectarlink-ffi/src/lib.rs b/core/nectarlink-ffi/src/lib.rsindex 0ee2f8c..4db562b 100644--- a/core/nectarlink-ffi/src/lib.rs+++ b/core/nectarlink-ffi/src/lib.rs@@ -454,6 +454,10 @@ pub enum Event {id: String,thread: Option<String>,},+ /// A paired phone's photo library changed (PCs only).+ PhotosChanged {+ id: String,+ },}/// What a mirroring video packet holds (docs/protocol/mirror.md).@@ -804,6 +808,41 @@ impl std::fmt::Debug for Photo {}}+/// An album (folder) in this phone's gallery (docs/protocol/photos.md).+#[derive(Clone, PartialEq, Eq, uniffi::Record)]+pub struct PhotoAlbum {+ pub id: String,+ pub name: String,+ pub count: u32,+ /// Newest item's ID in the album, for its cover thumbnail.+ pub cover: Option<String>,+}++/// A photo or video in this phone's gallery (docs/protocol/photos.md).+#[derive(Clone, PartialEq, Eq, uniffi::Record)]+pub struct PhotoItem {+ pub id: String,+ pub name: String,+ /// Unix milliseconds.+ pub date: i64,+ pub size: u64,+ pub width: u32,+ pub height: u32,+ /// Video duration in milliseconds; `None` for still photos.+ pub duration: Option<u32>,+ pub album: Option<String>,+}++/// A JPEG thumbnail for a gallery item (docs/protocol/photos.md).+#[derive(Clone, PartialEq, Eq, uniffi::Record)]+pub struct PhotoThumb {+ pub id: String,+ /// JPEG of at most 32 KiB, ~256 px on the longer side.+ pub data: Vec<u8>,+}++private_debug!(PhotoAlbum, PhotoItem, PhotoThumb);+#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error, uniffi::Error)]pub enum NectarlinkError {#[error("device is not paired")]@@ -1177,6 +1216,7 @@ impl From<NodeEvent> for Event {NodeEvent::CallLogChanged { device } => Event::CallLogChanged { id: device.to_string() },NodeEvent::ContactsChanged { device } => Event::ContactsChanged { id: device.to_string() },NodeEvent::SmsChanged { device, thread } => Event::SmsChanged { id: device.to_string(), thread },+ NodeEvent::PhotosChanged { device } => Event::PhotosChanged { id: device.to_string() },NodeEvent::Mirroring { device, session, on } => {Event::Mirroring { id: device.to_string(), session, on }}@@ -1283,9 +1323,27 @@ pub trait Platform: Send + Sync {/// A paired PC sent a web link (http or https, checked) to open./// False if it couldn't be shown.fn open_link(&self, from_id: String, url: String) -> bool;- /// A PC asked for a photo announced with `photo_taken`: open it, or+ /// A PC asked for a photo or video from the gallery: open it, or/// `null` when it's gone.fn open_photo(&self, id: String) -> Option<FileToSend>;+ /// A PC asked for this phone's photo albums (folders), Camera and+ /// Screenshots first, then by count.+ fn photo_albums(&self) -> Vec<PhotoAlbum>;+ /// A PC asked for photos and videos in `album` (or all when null),+ /// newest first by date, then by media ID (highest first). When+ /// `before` is set, only items after the previous page's last one:+ /// older than `before`, or of that date with an ID below `before_id`+ /// (none of that date when `before_id` is empty).+ fn photo_list(+ &self,+ album: Option<String>,+ before: Option<i64>,+ before_id: String,+ limit: u32,+ ) -> Vec<PhotoItem>;+ /// A PC asked for small JPEG thumbnails (at most 32 KiB each) for+ /// these gallery item IDs.+ fn photo_thumbs(&self, ids: Vec<String>) -> Vec<PhotoThumb>;/// A PC asked to answer, decline or silence call `id` (the call in/// progress). False if the phone couldn't.fn call_command(&self, id: String, command: CallCommand) -> bool;@@ -1525,6 +1583,45 @@ impl core::Platform for PlatformAdapter {let file = self.0.open_photo(id.to_owned()).ok_or("it's gone")?;file_to_send(file).map_err(|e| e.to_string())}+ fn photo_albums(&self) -> Result<Vec<core::PhotoAlbum>, String> {+ Ok(self+ .0+ .photo_albums()+ .into_iter()+ .map(|a| core::PhotoAlbum { id: a.id, name: a.name, count: a.count, cover: a.cover })+ .collect())+ }+ fn photo_list(+ &self,+ album: Option<&str>,+ before: Option<(i64, &str)>,+ limit: u32,+ ) -> Result<Vec<core::PhotoItem>, String> {+ let (date, id) = before.map_or((None, String::new()), |(date, id)| (Some(date), id.to_owned()));+ Ok(self+ .0+ .photo_list(album.map(str::to_owned), date, id, limit)+ .into_iter()+ .map(|i| core::PhotoItem {+ id: i.id,+ name: i.name,+ date: i.date,+ size: i.size,+ width: i.width,+ height: i.height,+ duration: i.duration,+ album: i.album,+ })+ .collect())+ }+ fn photo_thumbs(&self, ids: &[String]) -> Result<Vec<core::PhotoThumb>, String> {+ Ok(self+ .0+ .photo_thumbs(ids.to_vec())+ .into_iter()+ .map(|t| core::PhotoThumb { id: t.id, data: t.data })+ .collect())+ }}struct KeyProtectorAdapter(Arc<dyn KeyProtector>);@@ -1855,6 +1952,12 @@ impl NectarlinkNode {self.run(async move { node.contacts_changed().await }).await;}+ /// This phone's photo library changed: PCs that show it catch up.+ pub async fn photos_changed(&self) {+ let node = self.node.clone();+ self.run(async move { node.photos_changed().await }).await;+ }+/// A call on this phone rang, was answered or ended: tells the PCs that/// show calls (and are allowed them), now and when they connect during it.pub async fn call_changed(&self, call: Call) -> Result<()> {diff --git a/core/nectarlink-protocol/src/messages.rs b/core/nectarlink-protocol/src/messages.rsindex 829c07e..11031ca 100644--- a/core/nectarlink-protocol/src/messages.rs+++ b/core/nectarlink-protocol/src/messages.rs@@ -41,8 +41,15 @@ pub mod types {pub const PC_POWER: &str = "pc.power";pub const LINK_OPEN: &str = "link.open";pub const PHOTOS_NEW: &str = "photos.new";+ pub const PHOTOS_ALBUMS: &str = "photos.albums";+ pub const PHOTOS_ALBUMS_LIST: &str = "photos.albums.list";+ pub const PHOTOS_LIST: &str = "photos.list";+ pub const PHOTOS_ITEMS: &str = "photos.items";+ pub const PHOTOS_THUMBS: &str = "photos.thumbs";+ pub const PHOTOS_THUMBS_LIST: &str = "photos.thumbs.list";pub const PHOTOS_GET: &str = "photos.get";pub const PHOTOS_SENDING: &str = "photos.sending";+ pub const PHOTOS_CHANGED: &str = "photos.changed";pub const CALL_STATE: &str = "call.state";pub const CALL_ACTION: &str = "call.action";pub const CALL_LOG: &str = "call.log";@@ -1238,12 +1245,18 @@ pub struct ContactsChanged {}pub mod photos {/// Offered by phones that announce new photos (and can read them).pub const READ: &str = "photos.read";- /// Offered by PCs that show announced photos.+ /// Offered by PCs that show announced photos and the phone's gallery.pub const SHOW: &str = "photos.show";/// A photo's ID: at most this many bytes.pub const MAX_ID_BYTES: usize = 64;- /// A preview: a JPEG of at most this many bytes.+ /// A preview or thumbnail: a JPEG of at most this many bytes.pub const MAX_THUMB_BYTES: usize = 96 * 1024;+ /// Most items in one `photos.list` answer.+ pub const MAX_PAGE: u32 = 200;+ /// Most thumbnails requested in one `photos.thumbs` batch.+ pub const MAX_THUMB_BATCH: usize = 24;+ /// Most full items requested in one `photos.get` transfer.+ pub const MAX_GET_ITEMS: usize = 200;}/// Body of `photos.new`: a photo or screenshot just appeared on the phone.@@ -1288,10 +1301,153 @@ pub fn is_valid_photo_id(id: &str) -> bool {(1..=photos::MAX_ID_BYTES).contains(&id.len()) && id.bytes().all(|b| b.is_ascii_graphic())}-/// Body of `photos.get`: send this photo.+/// One album on the phone (`photos.albums.list`).+#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]+pub struct PhotoAlbum {+ /// Album bucket identifier on the phone.+ pub id: String,+ /// Display name, e.g. `"Camera"`, `"Screenshots"`.+ pub name: String,+ /// Number of photos and videos in the album.+ pub count: u32,+ /// Newest item's ID, for its cover thumbnail.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub cover: Option<String>,+}++/// Never prints the album's name (protocol v0 §11).+impl std::fmt::Debug for PhotoAlbum {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ f.debug_struct("PhotoAlbum").field("id", &self.id).field("count", &self.count).finish_non_exhaustive()+ }+}++/// Body of `photos.albums` request.+#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]+pub struct PhotoAlbumsGet {}++/// Answer to `photos.albums` (`photos.albums.list`).+#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]+pub struct PhotoAlbumsList {+ #[serde(default)]+ pub albums: Vec<PhotoAlbum>,+}++/// Body of `photos.list`: photos and videos on the phone (or in `album`),+/// newest first, after the item at (`before`, `before_id`) when given (the+/// last item of the previous page), else from the latest.+#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]+pub struct PhotoListGet {+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub album: Option<String>,+ /// The previous page's last `date` (Unix milliseconds).+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub before: Option<i64>,+ /// The previous page's last `id`, so items sharing its date aren't+ /// skipped or repeated.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub before_id: Option<String>,+ pub limit: u32,+}++impl std::fmt::Debug for PhotoListGet {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ f.debug_struct("PhotoListGet")+ .field("has_album", &self.album.is_some())+ .field("before", &self.before)+ .field("before_id", &self.before_id)+ .field("limit", &self.limit)+ .finish()+ }+}++/// One photo or video in `photos.items`.+#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]+pub struct PhotoItem {+ pub id: String,+ pub name: String,+ /// When it was taken (Unix milliseconds), or else when it was saved.+ pub date: i64,+ pub size: u64,+ #[serde(default)]+ pub width: u32,+ #[serde(default)]+ pub height: u32,+ /// Video duration in milliseconds (`None` for photos).+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub duration: Option<u32>,+ /// Album bucket identifier.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub album: Option<String>,+}++/// Never prints the file name (protocol v0 §11).+impl std::fmt::Debug for PhotoItem {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ f.debug_struct("PhotoItem")+ .field("id", &self.id)+ .field("date", &self.date)+ .field("size", &self.size)+ .field("video", &self.duration.is_some())+ .finish_non_exhaustive()+ }+}++/// Answer to `photos.list` (`photos.items`).+#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]+pub struct PhotoItems {+ #[serde(default)]+ pub items: Vec<PhotoItem>,+}++/// Body of `photos.thumbs`: ask for small JPEG thumbnails for these IDs.#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+pub struct PhotoThumbsGet {+ pub ids: Vec<String>,+}++/// One thumbnail in `photos.thumbs.list`.+#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]+pub struct PhotoThumb {+ pub id: String,+ #[serde(with = "serde_bytes")]+ pub data: Vec<u8>,+}++/// Never prints thumbnail bytes (protocol v0 §11).+impl std::fmt::Debug for PhotoThumb {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ f.debug_struct("PhotoThumb").field("id", &self.id).field("bytes", &self.data.len()).finish()+ }+}++/// Answer to `photos.thumbs` (`photos.thumbs.list`).+#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]+pub struct PhotoThumbsList {+ #[serde(default)]+ pub thumbs: Vec<PhotoThumb>,+}++/// Body of `photos.get`: send one (`id`) or several (`ids`) photos or videos.+#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]pub struct PhotoGet {+ #[serde(default, skip_serializing_if = "String::is_empty")]pub id: String,+ #[serde(default, skip_serializing_if = "Vec::is_empty")]+ pub ids: Vec<String>,+}++impl PhotoGet {+ /// Requested item IDs in order (`ids` when non-empty, otherwise `[id]`).+ pub fn requested_ids(&self) -> Vec<String> {+ if !self.ids.is_empty() {+ self.ids.clone()+ } else if !self.id.is_empty() {+ vec![self.id.clone()]+ } else {+ Vec::new()+ }+ }}/// Body of `photos.sending`, the answer to `photos.get`: the files@@ -1301,6 +1457,10 @@ pub struct PhotoSending {pub transfer: String,}+/// Body of `photos.changed`.+#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]+pub struct PhotosChanged {}+/// Body of `link.open`.#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]pub struct LinkOpen {@@ -1732,4 +1892,45 @@ mod tests {let back: ContactsList = Envelope::from_cbor(&env.to_cbor()).unwrap().body().unwrap();assert_eq!(back.contacts, vec![contact]);}++ #[test]+ fn gallery_messages_round_trip_and_hide_private_fields() {+ let album = PhotoAlbum {+ id: "b1".into(),+ name: "Private Vacation".into(),+ count: 12,+ cover: Some("p1".into()),+ };+ assert!(!format!("{album:?}").contains("Vacation"));+ let env = Envelope::new(types::PHOTOS_ALBUMS_LIST, &PhotoAlbumsList { albums: vec![album.clone()] })+ .unwrap();+ let back: PhotoAlbumsList = Envelope::from_cbor(&env.to_cbor()).unwrap().body().unwrap();+ assert_eq!(back.albums, vec![album]);++ let item = PhotoItem {+ id: "p1".into(),+ name: "secret_photo.jpg".into(),+ date: 1_790_000_000_000,+ size: 2048,+ width: 1920,+ height: 1080,+ duration: Some(5000),+ album: Some("b1".into()),+ };+ assert!(!format!("{item:?}").contains("secret_photo"));+ let env = Envelope::new(types::PHOTOS_ITEMS, &PhotoItems { items: vec![item.clone()] }).unwrap();+ let back: PhotoItems = Envelope::from_cbor(&env.to_cbor()).unwrap().body().unwrap();+ assert_eq!(back.items, vec![item]);++ let thumb = PhotoThumb { id: "p1".into(), data: vec![0xff, 0xd8, 0xff] };+ let env = Envelope::new(types::PHOTOS_THUMBS_LIST, &PhotoThumbsList { thumbs: vec![thumb.clone()] })+ .unwrap();+ let back: PhotoThumbsList = Envelope::from_cbor(&env.to_cbor()).unwrap().body().unwrap();+ assert_eq!(back.thumbs, vec![thumb]);++ let single = PhotoGet { id: "p1".into(), ids: Vec::new() };+ assert_eq!(single.requested_ids(), vec!["p1".to_owned()]);+ let multi = PhotoGet { id: String::new(), ids: vec!["p1".into(), "p2".into()] };+ assert_eq!(multi.requested_ids(), vec!["p1".to_owned(), "p2".to_owned()]);+ }}diff --git a/desktop/app/build.rs b/desktop/app/build.rsindex 7150209..b303be1 100644--- a/desktop/app/build.rs+++ b/desktop/app/build.rs@@ -51,6 +51,7 @@ const QML: &[&str] = &["qml/pages/HomePage.qml","qml/pages/MessagesPage.qml","qml/pages/PairingPanel.qml",+ "qml/pages/PhotosPage.qml","qml/pages/SettingsPage.qml","qml/pages/WelcomePage.qml",];@@ -208,6 +209,7 @@ fn main() {"src/bridge/mirror.rs","src/bridge/notifications.rs","src/bridge/pairing.rs",+ "src/bridge/photos.rs","src/bridge/prefs.rs","src/bridge/transfers.rs",])diff --git a/desktop/app/qml/Icons.qml b/desktop/app/qml/Icons.qmlindex 4262dff..7770a0c 100644--- a/desktop/app/qml/Icons.qml+++ b/desktop/app/qml/Icons.qml@@ -61,4 +61,7 @@ QtObject {readonly property string power: "M12 2v10M5.6 5.6a9 9 0 1 0 12.8 0"readonly property string folder: "M3 6a2 2 0 0 1 2-2h4l2 2h8a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"readonly property string sparkle: "M12 3l1.8 5.2L19 10l-5.2 1.8L12 17l-1.8-5.2L5 10l5.2-1.8z"+ readonly property string download: "M12 3v12M7 10l5 5 5-5M5 20h14"+ readonly property string openExternal: "M14 4h6v6M20 4l-9 9M19 14v5a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V7a2 2 0 0 1 2-2h5"+ readonly property string video: "M4 6h11a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2zM17 10l5-3v10l-5-3"}diff --git a/desktop/app/qml/MainWindow.qml b/desktop/app/qml/MainWindow.qmlindex 14b95b5..f3d5fc7 100644--- a/desktop/app/qml/MainWindow.qml+++ b/desktop/app/qml/MainWindow.qml@@ -122,6 +122,12 @@ NativeWindow {selected: window.page === "calls"onClicked: window.page = "calls"}+ NavItem {+ iconPath: Icons.photo+ text: qsTr("Photos")+ selected: window.page === "photos"+ onClicked: window.page = "photos"+ }NavItem {iconPath: Icons.settingstext: qsTr("Settings")@@ -161,6 +167,7 @@ NativeWindow {text: window.page === "home" ? qsTr("Home"): window.page === "messages" ? qsTr("Messages"): window.page === "calls" ? qsTr("Calls")+ : window.page === "photos" ? qsTr("Photos"): qsTr("Settings")role: "headline"size: 20@@ -220,6 +227,12 @@ NativeWindow {window.page = "messages"}}+ PhotosPage {+ anchors.fill: parent+ active: window.page === "photos"+ deviceId: homePage.currentDeviceId+ deviceName: homePage.currentDeviceName+ }SettingsPage {anchors.fill: parentactive: window.page === "settings"diff --git a/desktop/app/qml/pages/PhotosPage.qml b/desktop/app/qml/pages/PhotosPage.qmlnew file mode 100644index 0000000..9f0ad7a--- /dev/null+++ b/desktop/app/qml/pages/PhotosPage.qml@@ -0,0 +1,1192 @@+// SPDX-License-Identifier: GPL-3.0-or-later+import QtQuick+import QtQuick.Dialogs+import app.nectarlink++// Photos: the phone's gallery on the PC. Albums on the left, a virtualized+// GridView of thumbnails grouped by day on the right, multi-select, Save (to+// a chosen folder or Downloads\Nectarlink), Copy to clipboard, Open in the+// Windows Photos app, and an in-app viewer with arrow-key navigation.+Item {+ id: page+ property bool active: false+ property string deviceId+ property string deviceName++ readonly property var albums: { try { return JSON.parse(Photos.albums) } catch (e) { return [] } }+ readonly property var photosFeature: AppController.capsRevision >= 0 && page.deviceId.length > 0+ ? AppController.featureState(page.deviceId, "files.recent_photos") : ({})++ // Multi-select state: map of itemId -> true, and ordered array of selected IDs.+ property var selectedMap: ({})+ property var selectedIds: []+ readonly property int selectedCount: selectedIds.length+ property bool selectMode: false+ property int lastClickedIndex: -1++ // In-app viewer index (-1 when closed).+ property int viewerIndex: -1+ readonly property var viewedItem: {+ if (Photos.revision < 0 || viewerIndex < 0 || viewerIndex >= Photos.count)+ return null+ try { return JSON.parse(Photos.itemAt(viewerIndex)) } catch (e) { return null }+ }++ // Whether the single selected item is a video (Copy is for still images).+ readonly property bool singleSelectedIsVideo: {+ if (selectedCount !== 1 || Photos.revision < 0) return false+ const id = selectedIds[0]+ return id.indexOf("video:") === 0+ }++ readonly property string currentAlbumName: {+ if (Photos.album.length === 0) return qsTr("All photos")+ for (let i = 0; i < albums.length; i++) {+ if (albums[i].id === Photos.album) return albums[i].name+ }+ return qsTr("Album")+ }++ readonly property int totalPhotosCount: {+ let sum = 0+ for (let i = 0; i < albums.length; i++)+ sum += (albums[i].count || 0)+ 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 dayLabel(ms) {+ if (!ms || ms <= 0) return ""+ const date = new Date(ms)+ const today = new Date()+ const yesterday = new Date(today.getFullYear(), today.getMonth(), today.getDate() - 1)+ if (date.toDateString() === today.toDateString()) return qsTr("Today")+ if (date.toDateString() === yesterday.toDateString()) return qsTr("Yesterday")+ return date.toLocaleDateString(+ Qt.locale(),+ date.getFullYear() === today.getFullYear() ? "dddd, d MMMM" : Locale.LongFormat+ )+ }++ function shortDayLabel(ms) {+ if (!ms || ms <= 0) return ""+ const date = new Date(ms)+ const today = new Date()+ const yesterday = new Date(today.getFullYear(), today.getMonth(), today.getDate() - 1)+ if (date.toDateString() === today.toDateString()) return qsTr("Today")+ if (date.toDateString() === yesterday.toDateString()) return qsTr("Yesterday")+ return date.toLocaleDateString(+ Qt.locale(),+ date.getFullYear() === today.getFullYear() ? "d MMM" : "d MMM yyyy"+ )+ }++ function formatVideoDuration(ms) {+ if (!ms || ms <= 0) return "0:00"+ const totalSec = Math.max(1, Math.round(ms / 1000))+ const h = Math.floor(totalSec / 3600)+ const m = Math.floor((totalSec % 3600) / 60)+ const s = totalSec % 60+ if (h > 0)+ return h + ":" + String(m).padStart(2, "0") + ":" + String(s).padStart(2, "0")+ return m + ":" + String(s).padStart(2, "0")+ }++ function formatBytes(bytes) {+ if (!bytes || bytes <= 0) return ""+ if (bytes < 1024) return bytes + " B"+ if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(0) + " KB"+ return (bytes / (1024 * 1024)).toFixed(1) + " MB"+ }++ function isSelected(id) {+ return !!selectedMap[id]+ }++ function toggleSelect(id, index, shiftHeld) {+ const next = Object.assign({}, selectedMap)+ if (shiftHeld && lastClickedIndex >= 0 && index >= 0 && Photos.count > 0) {+ 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) {}+ }+ } else if (next[id]) {+ delete next[id]+ } else {+ next[id] = true+ }+ if (index >= 0) lastClickedIndex = index+ selectedMap = next+ selectedIds = Object.keys(next)+ }++ function selectAllLoaded() {+ 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) {}+ }+ selectedMap = next+ selectedIds = Object.keys(next)+ selectMode = true+ }++ function clearSelection() {+ selectedMap = ({})+ selectedIds = []+ selectMode = false+ lastClickedIndex = -1+ }++ function openViewer(index) {+ if (index < 0 || index >= Photos.count) return+ viewerIndex = index+ try {+ const item = JSON.parse(Photos.itemAt(index))+ if (item && !item.isVideo) {+ Photos.ensureFull(item.id)+ }+ } catch (e) {}+ if (index + 6 >= Photos.count && Photos.more) {+ Photos.loadOlder()+ }+ }++ function stepViewer(delta) {+ const next = viewerIndex + delta+ if (next >= 0 && next < Photos.count) {+ openViewer(next)+ }+ }++ function load() {+ if (active && deviceId.length > 0)+ Photos.open(deviceId)+ }++ onActiveChanged: if (active) load()+ onDeviceIdChanged: {+ clearSelection()+ viewerIndex = -1+ load()+ }++ opacity: active ? 1 : 0+ visible: opacity > 0+ Behavior on opacity { NumberAnimation { duration: Theme.fadeNormal } }+ transform: Translate {+ y: page.active || Theme.reduceMotion ? 0 : 12+ Behavior on y { SpringAnimation { spring: Theme.springGentle; damping: Theme.dampingGentle } }+ }++ // Keyboard shortcuts for viewer navigation and selection.+ Shortcut {+ sequence: "Left"+ enabled: page.active && page.viewerIndex > 0+ onActivated: page.stepViewer(-1)+ }+ Shortcut {+ sequence: "Right"+ enabled: page.active && page.viewerIndex >= 0 && page.viewerIndex + 1 < Photos.count+ onActivated: page.stepViewer(1)+ }+ Shortcut {+ sequence: "Esc"+ enabled: page.active && (page.viewerIndex >= 0 || page.selectedCount > 0 || page.selectMode)+ onActivated: {+ if (page.viewerIndex >= 0)+ page.viewerIndex = -1+ else+ page.clearSelection()+ }+ }+ Shortcut {+ sequence: StandardKey.Copy+ enabled: page.active && (+ (page.viewerIndex >= 0 && page.viewedItem !== null && !page.viewedItem.isVideo)+ || (page.selectedCount === 1 && !page.singleSelectedIsVideo)+ )+ onActivated: {+ if (page.viewerIndex >= 0 && page.viewedItem)+ Photos.copyItem(page.viewedItem.id)+ else if (page.selectedCount === 1)+ Photos.copyItem(page.selectedIds[0])+ }+ }++ FolderDialog {+ id: defaultFolderPicker+ title: qsTr("Choose default folder for saved photos")+ onAccepted: Photos.chooseSaveFolder(selectedFolder.toString())+ }++ FolderDialog {+ id: saveToFolderPicker+ property var pendingIds: []+ title: qsTr("Save to folder")+ onAccepted: {+ if (pendingIds.length > 0) {+ Photos.saveItems(pendingIds, selectedFolder.toString())+ if (page.viewerIndex < 0)+ page.clearSelection()+ }+ }+ }++ readonly property bool phoneOffline: page.deviceId.length === 0+ || (Photos.status === "offline" && Photos.count === 0 && page.albums.length === 0)++ // ---- No phone paired, or phone offline with nothing cached ----+ Column {+ anchors.centerIn: parent+ width: Math.min(parent.width - Theme.contentPadding * 2, 420)+ spacing: 12+ visible: page.phoneOffline+ Icon {+ anchors.horizontalCenter: parent.horizontalCenter+ width: 40; height: 40+ stroke: 1.5+ path: Icons.photo+ color: Theme.surfaceContentVariant+ }+ Txt {+ width: parent.width+ horizontalAlignment: Text.AlignHCenter+ role: "title"+ text: page.deviceId.length === 0 ? qsTr("Your phone's photos on your PC")+ : qsTr("%1 isn't connected").arg(page.deviceName)+ }+ Txt {+ width: parent.width+ horizontalAlignment: Text.AlignHCenter+ wrapMode: Text.WordWrap+ role: "body"+ muted: true+ text: page.deviceId.length === 0+ ? qsTr("Pair your phone to browse its camera roll, screenshots, and albums right from here.")+ : qsTr("Your photos and albums show up here when it's back.")+ }+ }++ // ---- Left pane: Albums list ----+ Item {+ id: albumPane+ visible: !page.phoneOffline+ width: 248+ height: parent.height++ Item {+ id: albumHeader+ width: parent.width+ height: 56+ Txt {+ anchors.left: parent.left+ anchors.leftMargin: 18+ anchors.verticalCenter: parent.verticalCenter+ role: "label"+ muted: true+ text: qsTr("Albums")+ }+ IconButton {+ anchors.right: parent.right+ anchors.rightMargin: 10+ anchors.verticalCenter: parent.verticalCenter+ iconPath: Icons.refresh+ label: qsTr("Refresh")+ enabled: Photos.status !== "loading"+ onClicked: Photos.refresh()+ }+ }++ Flickable {+ anchors.top: albumHeader.bottom+ anchors.bottom: parent.bottom+ width: parent.width+ contentHeight: albumCol.height + 16+ boundsBehavior: Flickable.StopAtBounds+ clip: true++ Column {+ id: albumCol+ width: parent.width+ spacing: 2++ AlbumRow {+ width: albumCol.width+ albumId: ""+ title: qsTr("All photos")+ count: page.totalPhotosCount+ thumbUrl: page.albums.length > 0 ? (page.albums[0].thumb || "") : ""+ selected: Photos.album === ""+ onClicked: {+ page.clearSelection()+ page.viewerIndex = -1+ Photos.selectAlbum("")+ }+ }++ Repeater {+ model: page.albums+ delegate: AlbumRow {+ required property var modelData+ width: albumCol.width+ albumId: modelData.id+ title: modelData.name+ count: modelData.count || 0+ thumbUrl: modelData.thumb || ""+ selected: Photos.album === modelData.id+ onClicked: {+ page.clearSelection()+ page.viewerIndex = -1+ Photos.selectAlbum(modelData.id)+ }+ }+ }+ }+ }++ Divider { anchors.right: parent.right; width: 1; height: parent.height }+ }++ // ---- Right pane: Toolbar + Virtualized GridView ----+ Item {+ id: gridPane+ visible: !page.phoneOffline+ anchors.left: albumPane.right+ anchors.right: parent.right+ height: parent.height++ // Top toolbar: album info OR multi-select actions.+ Item {+ id: toolbar+ width: parent.width+ height: 56++ // Normal mode header (no selection active).+ Row {+ anchors.left: parent.left+ anchors.leftMargin: 20+ anchors.verticalCenter: parent.verticalCenter+ spacing: 10+ visible: page.selectedCount === 0 && !page.selectMode++ Txt {+ anchors.verticalCenter: parent.verticalCenter+ role: "title"+ size: 16+ text: page.currentAlbumName+ }+ Txt {+ anchors.verticalCenter: parent.verticalCenter+ visible: Photos.count > 0+ role: "caption"+ muted: true+ text: Photos.more ? qsTr("%1+ items").arg(Photos.count) : qsTr("%1 items").arg(Photos.count)+ }+ }++ Row {+ anchors.right: parent.right+ anchors.rightMargin: 16+ anchors.verticalCenter: parent.verticalCenter+ spacing: 8+ visible: page.selectedCount === 0 && !page.selectMode && Photos.count > 0++ Chip {+ anchors.verticalCenter: parent.verticalCenter+ iconPath: Icons.folder+ text: Photos.saveFolder+ TapHandler { onTapped: defaultFolderPicker.open() }+ HoverHandler { cursorShape: Qt.PointingHandCursor }+ }++ Button {+ anchors.verticalCenter: parent.verticalCenter+ variant: "tonal"+ size: "sm"+ iconPath: Icons.check+ text: qsTr("Select")+ onClicked: page.selectMode = true+ }+ }++ // Selection mode toolbar.+ Row {+ anchors.left: parent.left+ anchors.leftMargin: 12+ anchors.verticalCenter: parent.verticalCenter+ spacing: 8+ visible: page.selectedCount > 0 || page.selectMode++ IconButton {+ anchors.verticalCenter: parent.verticalCenter+ iconPath: Icons.close+ label: qsTr("Cancel selection")+ onClicked: page.clearSelection()+ }+ Txt {+ anchors.verticalCenter: parent.verticalCenter+ role: "title"+ size: 15+ text: page.selectedCount > 0+ ? qsTr("%1 selected").arg(page.selectedCount)+ : qsTr("Click items to select")+ }+ Button {+ anchors.verticalCenter: parent.verticalCenter+ variant: "text"+ size: "sm"+ text: qsTr("Select all")+ onClicked: page.selectAllLoaded()+ }+ }++ Row {+ anchors.right: parent.right+ anchors.rightMargin: 16+ anchors.verticalCenter: parent.verticalCenter+ spacing: 8+ visible: page.selectedCount > 0 || page.selectMode++ Button {+ anchors.verticalCenter: parent.verticalCenter+ visible: page.selectedCount === 1 && !page.singleSelectedIsVideo+ variant: "tonal"+ size: "sm"+ iconPath: Icons.copy+ text: qsTr("Copy")+ enabled: !Photos.saving+ onClicked: Photos.copyItem(page.selectedIds[0])+ }++ Button {+ anchors.verticalCenter: parent.verticalCenter+ visible: page.selectedCount === 1+ variant: "tonal"+ size: "sm"+ iconPath: Icons.openExternal+ text: qsTr("Open")+ enabled: !Photos.saving+ onClicked: Photos.openItem(page.selectedIds[0])+ }++ Button {+ anchors.verticalCenter: parent.verticalCenter+ variant: "fill"+ size: "sm"+ iconPath: Icons.download+ busy: Photos.saving+ enabled: page.selectedCount > 0 && !Photos.saving+ text: page.selectedCount > 1+ ? qsTr("Save (%1)").arg(page.selectedCount)+ : qsTr("Save")+ onClicked: {+ Photos.saveItems(page.selectedIds, "")+ page.clearSelection()+ }+ }++ IconButton {+ anchors.verticalCenter: parent.verticalCenter+ tonal: true+ iconPath: Icons.folder+ label: qsTr("Save to folder…")+ enabled: page.selectedCount > 0 && !Photos.saving+ onClicked: {+ saveToFolderPicker.pendingIds = page.selectedIds.slice()+ saveToFolderPicker.open()+ }+ }+ }++ Divider { anchors.bottom: parent.bottom; width: parent.width }+ }++ // Content area below toolbar.+ Item {+ id: gridContainer+ anchors.top: toolbar.bottom+ anchors.bottom: parent.bottom+ width: parent.width++ Spinner {+ anchors.centerIn: parent+ visible: Photos.status === "loading" && Photos.count === 0+ }++ // Permission / toggle / error state.+ Column {+ anchors.centerIn: parent+ width: Math.min(parent.width - 48, 400)+ spacing: 10+ visible: Photos.count === 0 && Photos.status !== "loading" && Photos.status !== "ready"+ Icon {+ anchors.horizontalCenter: parent.horizontalCenter+ width: 34; height: 34+ stroke: 1.5+ path: Icons.photo+ color: Theme.surfaceContentVariant+ }+ Txt {+ width: parent.width+ horizontalAlignment: Text.AlignHCenter+ wrapMode: Text.WordWrap+ role: "title"+ size: 16+ text: Photos.status === "off" ? qsTr("Photos are off for %1").arg(page.deviceName)+ : Photos.status === "unsupported" ? qsTr("Allow photos on %1").arg(page.deviceName)+ : Photos.status === "offline" ? qsTr("%1 isn't connected").arg(page.deviceName)+ : qsTr("Couldn't load photos")+ }+ Txt {+ width: parent.width+ horizontalAlignment: Text.AlignHCenter+ wrapMode: Text.WordWrap+ role: "bodySmall"+ muted: true+ text: Photos.status === "off"+ ? qsTr("Turn on Photos for this phone, here in Settings and in the Nectarlink app on the phone.")+ : Photos.status === "unsupported"+ ? qsTr("In the Nectarlink app on your phone, tap Allow on “Photos and videos”.")+ : Photos.status === "offline"+ ? qsTr("Your photos and albums show up here when it's back.")+ : qsTr("Something went wrong reading the photo library from the phone.")+ }+ LockChip {+ anchors.horizontalCenter: parent.horizontalCenter+ visible: label.length > 0+ feature: page.photosFeature+ }+ Button {+ anchors.horizontalCenter: parent.horizontalCenter+ visible: Photos.status === "failed"+ variant: "tonal"+ size: "sm"+ text: qsTr("Try again")+ onClicked: Photos.refresh()+ }+ }++ // Empty album / library state.+ Column {+ anchors.centerIn: parent+ width: Math.min(parent.width - 48, 360)+ spacing: 8+ visible: Photos.status === "ready" && Photos.count === 0+ Icon {+ anchors.horizontalCenter: parent.horizontalCenter+ width: 32; height: 32+ stroke: 1.5+ path: Icons.photo+ color: Theme.surfaceContentVariant+ }+ Txt {+ width: parent.width+ horizontalAlignment: Text.AlignHCenter+ role: "title"+ size: 15+ text: qsTr("No photos or videos")+ }+ Txt {+ width: parent.width+ horizontalAlignment: Text.AlignHCenter+ wrapMode: Text.WordWrap+ role: "bodySmall"+ muted: true+ text: qsTr("Photos and videos on your phone will appear here.")+ }+ }++ // Virtualized thumbnail grid grouped by day.+ GridView {+ id: grid+ anchors.fill: parent+ anchors.leftMargin: 16+ anchors.rightMargin: 8+ topMargin: 44+ bottomMargin: 24+ visible: Photos.count > 0+ clip: true+ boundsBehavior: Flickable.StopAtBounds+ cacheBuffer: height+ readonly property int columns: Math.max(2, Math.floor((width - 8) / 164))+ cellWidth: Math.floor((width - 8) / columns)+ cellHeight: cellWidth+ model: Photos++ onAtYEndChanged: {+ if (atYEnd && Photos.more && count > 0)+ Photos.loadOlder()+ }++ // Current top-visible item's day label, shown in the sticky day banner.+ 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 ""+ }+ }++ delegate: PhotoTile {+ width: grid.cellWidth+ height: grid.cellHeight+ }++ footer: Item {+ width: grid.width+ height: Photos.loadingOlder ? 52 : 0+ Spinner {+ anchors.centerIn: parent+ visible: Photos.loadingOlder+ }+ }+ }++ // Sticky day group banner at the top of the grid.+ Rectangle {+ anchors.top: parent.top+ anchors.topMargin: 8+ anchors.left: parent.left+ anchors.leftMargin: 20+ visible: Photos.count > 0 && grid.stickyDay.length > 0+ height: 28+ width: stickyDayTxt.implicitWidth + 24+ radius: Theme.pill(height)+ color: Qt.rgba(Theme.surfaceContainerHigh.r, Theme.surfaceContainerHigh.g, Theme.surfaceContainerHigh.b, 0.92)+ border.width: Theme.graphite ? 1 : 0+ border.color: Theme.outlineVariant+ Txt {+ id: stickyDayTxt+ anchors.centerIn: parent+ role: "label"+ size: 12+ text: grid.stickyDay+ }+ }+ }+ }++ // ---- In-app Photo & Video Viewer Overlay ----+ Rectangle {+ id: viewer+ anchors.fill: parent+ visible: page.viewerIndex >= 0 && page.viewedItem !== null+ color: Theme.surface+ z: 10++ // Absorb background clicks.+ TapHandler { onTapped: {} }++ // Viewer top bar.+ Item {+ id: viewerBar+ width: parent.width+ height: 60++ IconButton {+ id: closeViewerBtn+ anchors.left: parent.left+ anchors.leftMargin: 16+ anchors.verticalCenter: parent.verticalCenter+ iconPath: Icons.back+ label: qsTr("Back to gallery")+ onClicked: page.viewerIndex = -1+ }++ Column {+ anchors.left: closeViewerBtn.right+ anchors.leftMargin: 12+ anchors.right: viewerActions.left+ anchors.rightMargin: 16+ anchors.verticalCenter: parent.verticalCenter+ spacing: 2+ Txt {+ width: parent.width+ role: "title"+ size: 15+ elide: Text.ElideMiddle+ text: page.viewedItem ? page.viewedItem.name : ""+ }+ Txt {+ width: parent.width+ role: "caption"+ muted: true+ elide: Text.ElideRight+ text: {+ if (!page.viewedItem) return ""+ const parts = []+ parts.push((page.viewerIndex + 1) + " / " + Photos.count)+ if (page.viewedItem.date > 0) {+ const d = new Date(page.viewedItem.date)+ parts.push(page.dayLabel(page.viewedItem.date) + " " + d.toLocaleTimeString(Qt.locale(), Locale.ShortFormat))+ }+ if (page.viewedItem.width > 0 && page.viewedItem.height > 0)+ parts.push(page.viewedItem.width + " × " + page.viewedItem.height)+ if (page.viewedItem.size > 0)+ parts.push(page.formatBytes(page.viewedItem.size))+ return parts.join(" · ")+ }+ }+ }++ Row {+ id: viewerActions+ anchors.right: parent.right+ anchors.rightMargin: 16+ anchors.verticalCenter: parent.verticalCenter+ spacing: 8++ Button {+ anchors.verticalCenter: parent.verticalCenter+ visible: page.viewedItem !== null && !page.viewedItem.isVideo+ variant: "tonal"+ size: "sm"+ iconPath: Icons.copy+ text: qsTr("Copy")+ enabled: !Photos.saving+ onClicked: if (page.viewedItem) Photos.copyItem(page.viewedItem.id)+ }++ Button {+ anchors.verticalCenter: parent.verticalCenter+ variant: "tonal"+ size: "sm"+ iconPath: page.viewedItem && page.viewedItem.isVideo ? Icons.play : Icons.openExternal+ text: page.viewedItem && page.viewedItem.isVideo ? qsTr("Play video") : qsTr("Open in Photos")+ enabled: !Photos.saving+ onClicked: if (page.viewedItem) Photos.openItem(page.viewedItem.id)+ }++ Button {+ anchors.verticalCenter: parent.verticalCenter+ variant: "fill"+ size: "sm"+ iconPath: Icons.download+ busy: Photos.saving+ enabled: !Photos.saving+ text: qsTr("Save")+ onClicked: if (page.viewedItem) Photos.saveItems([page.viewedItem.id], "")+ }++ IconButton {+ anchors.verticalCenter: parent.verticalCenter+ tonal: true+ iconPath: Icons.folder+ label: qsTr("Save to folder…")+ enabled: !Photos.saving+ onClicked: {+ if (page.viewedItem) {+ saveToFolderPicker.pendingIds = [page.viewedItem.id]+ saveToFolderPicker.open()+ }+ }+ }+ }++ Divider { anchors.bottom: parent.bottom; width: parent.width }+ }++ // Main photo/video stage.+ Item {+ anchors.top: viewerBar.bottom+ anchors.bottom: parent.bottom+ width: parent.width++ Image {+ id: stageImage+ anchors.fill: parent+ anchors.margins: 32+ asynchronous: true+ fillMode: Image.PreserveAspectFit+ smooth: true+ mipmap: true+ source: {+ if (!page.viewedItem) return ""+ if (page.viewedItem.fullUrl && page.viewedItem.fullUrl.length > 0)+ return page.viewedItem.fullUrl+ return page.viewedItem.thumb || ""+ }+ }++ // Loading badge while full-resolution photo is downloading in background.+ Rectangle {+ anchors.bottom: parent.bottom+ anchors.bottomMargin: 20+ anchors.horizontalCenter: parent.horizontalCenter+ visible: page.viewedItem !== null+ && !page.viewedItem.isVideo+ && (!page.viewedItem.fullUrl || page.viewedItem.fullUrl.length === 0)+ && Photos.busyItem === page.viewedItem.id+ height: 32+ width: loadingRow.implicitWidth + 24+ radius: Theme.pill(height)+ color: Theme.surfaceContainerHigh+ border.width: Theme.graphite ? 1 : 0+ border.color: Theme.outlineVariant+ Row {+ id: loadingRow+ anchors.centerIn: parent+ spacing: 8+ Spinner { width: 14; height: 14; anchors.verticalCenter: parent.verticalCenter }+ Txt {+ anchors.verticalCenter: parent.verticalCenter+ role: "caption"+ text: qsTr("Loading full resolution…")+ }+ }+ }++ // Video play button overlay in viewer.+ Rectangle {+ anchors.centerIn: parent+ visible: page.viewedItem !== null && !!page.viewedItem.isVideo+ width: 76; height: 76+ radius: 38+ color: Qt.rgba(0, 0, 0, 0.68)+ border.width: 2+ border.color: "#ffffff"+ scale: playTap.pressed ? Theme.pressScale : 1+ Behavior on scale { SpringAnimation { spring: Theme.springSnappy; damping: Theme.dampingSnappy } }+ Icon {+ anchors.centerIn: parent+ width: 30; height: 30+ path: Icons.play+ color: "#ffffff"+ }+ HoverHandler { cursorShape: Qt.PointingHandCursor }+ TapHandler {+ id: playTap+ onTapped: if (page.viewedItem) Photos.openItem(page.viewedItem.id)+ }+ }++ // Previous photo button (Left arrow).+ IconButton {+ anchors.left: parent.left+ anchors.leftMargin: 16+ anchors.verticalCenter: parent.verticalCenter+ width: 44; height: 44+ tonal: true+ visible: page.viewerIndex > 0+ iconPath: Icons.back+ label: qsTr("Previous photo")+ onClicked: page.stepViewer(-1)+ }++ // Next photo button (Right arrow).+ IconButton {+ anchors.right: parent.right+ anchors.rightMargin: 16+ anchors.verticalCenter: parent.verticalCenter+ width: 44; height: 44+ tonal: true+ visible: page.viewerIndex + 1 < Photos.count+ iconPath: Icons.chevronRight+ label: qsTr("Next photo")+ onClicked: page.stepViewer(1)+ }+ }+ }++ // ---- Album row component ----+ component AlbumRow: Item {+ id: albumRow+ property string albumId+ property string title+ property int count: 0+ property string thumbUrl+ property bool selected: false+ signal clicked++ height: 54+ Accessible.role: Accessible.Button+ Accessible.name: albumRow.title+ Accessible.onPressAction: albumRow.clicked()++ Rectangle {+ anchors.fill: parent+ anchors.leftMargin: 10+ anchors.rightMargin: 10+ anchors.topMargin: 2+ anchors.bottomMargin: 2+ radius: Theme.graphite ? Theme.radiusSm : Theme.radiusMd+ color: albumRow.selected+ ? Theme.secondaryContainer+ : 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++ Item {+ id: coverBox+ x: 10+ anchors.verticalCenter: parent.verticalCenter+ width: 36; height: 36+ Rectangle {+ anchors.fill: parent+ radius: Theme.radiusSm+ color: Theme.surfaceContainerHigh+ Icon {+ anchors.centerIn: parent+ width: 16; height: 16+ path: Icons.photo+ color: Theme.surfaceContentVariant+ visible: coverImg.status !== Image.Ready+ }+ Image {+ id: coverImg+ anchors.fill: parent+ asynchronous: true+ fillMode: Image.PreserveAspectCrop+ sourceSize: Qt.size(72, 72)+ source: albumRow.thumbUrl+ visible: status === Image.Ready+ }+ }+ }++ Column {+ anchors.left: coverBox.right+ anchors.leftMargin: 10+ anchors.right: parent.right+ anchors.rightMargin: 10+ anchors.verticalCenter: parent.verticalCenter+ spacing: 1+ Txt {+ width: parent.width+ role: "body"+ elide: Text.ElideRight+ color: albumRow.selected ? Theme.secondaryContainerContent : Theme.surfaceContent+ text: albumRow.title+ }+ Txt {+ width: parent.width+ role: "caption"+ muted: !albumRow.selected+ color: albumRow.selected ? Theme.secondaryContainerContent : Theme.surfaceContentVariant+ text: qsTr("%1").arg(albumRow.count)+ }+ }+ }++ HoverHandler { id: albumHover; cursorShape: Qt.PointingHandCursor }+ TapHandler { onTapped: albumRow.clicked() }+ }++ // ---- Virtualized GridView cell component ----+ component PhotoTile: Item {+ id: tile+ required property int index+ required property string itemId+ required property string name+ required property real date+ required property real prevDate+ required property real size+ required property int itemWidth+ required property int itemHeight+ required property int duration+ required property bool isVideo+ required property string album+ required property string thumb+ required property string fullUrl++ 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)++ Accessible.role: Accessible.Button+ Accessible.name: tile.name+ Accessible.onPressAction: {+ if (page.selectMode || page.selectedCount > 0)+ page.toggleSelect(tile.itemId, tile.index, false)+ else+ page.openViewer(tile.index)+ }++ function checkThumb() {+ if (thumb.length === 0 && itemId.length > 0) {+ if (requestedThumbId !== itemId) {+ if (requestedThumbId.length > 0)+ Photos.dropThumb(requestedThumbId)+ requestedThumbId = itemId+ Photos.needThumb(itemId)+ }+ } else if (thumb.length > 0) {+ requestedThumbId = ""+ }+ }++ Component.onCompleted: checkThumb()+ onItemIdChanged: checkThumb()+ onThumbChanged: if (thumb.length > 0) requestedThumbId = ""+ Component.onDestruction: {+ if (requestedThumbId.length > 0 && thumb.length === 0)+ Photos.dropThumb(requestedThumbId)+ }++ Rectangle {+ id: cellCard+ anchors.fill: parent+ anchors.margins: 4+ radius: Theme.radiusSm+ color: Theme.surfaceContainerHigh+ border.width: tile.selected ? 3 : (Theme.graphite ? 1 : 0)+ border.color: tile.selected ? Theme.primary : Theme.outlineVariant+ clip: true++ Icon {+ anchors.centerIn: parent+ width: 24; height: 24+ path: tile.isVideo ? Icons.video : Icons.photo+ color: Theme.surfaceContentVariant+ visible: thumbImg.status !== Image.Ready+ }++ Image {+ id: thumbImg+ anchors.fill: parent+ anchors.margins: tile.selected ? 3 : 0+ asynchronous: true+ fillMode: Image.PreserveAspectCrop+ sourceSize: Qt.size(256, 256)+ source: tile.thumb+ opacity: status === Image.Ready ? 1 : 0+ Behavior on opacity { NumberAnimation { duration: Theme.fadeFast } }+ }++ // Subtle dark scrim when hovered or selected.+ Rectangle {+ anchors.fill: parent+ color: tile.selected+ ? Qt.rgba(Theme.primary.r, Theme.primary.g, Theme.primary.b, 0.18)+ : (tileHover.hovered ? Qt.rgba(0, 0, 0, 0.14) : "transparent")+ }++ // Day group pill on the first tile of each subsequent day.+ Rectangle {+ anchors.top: parent.top+ anchors.topMargin: 6+ anchors.left: parent.left+ anchors.leftMargin: 6+ visible: tile.firstOfDay && tile.index > 0 && tile.date > 0+ height: 22+ width: Math.min(parent.width - 40, dayBadgeTxt.implicitWidth + 14)+ radius: 11+ color: Qt.rgba(0, 0, 0, 0.68)+ Txt {+ id: dayBadgeTxt+ anchors.centerIn: parent+ width: parent.width - 12+ horizontalAlignment: Text.AlignHCenter+ elide: Text.ElideRight+ role: "caption"+ size: 11+ color: "#ffffff"+ text: page.shortDayLabel(tile.date)+ }+ }++ // Play badge in center for video items.+ Rectangle {+ anchors.centerIn: parent+ visible: tile.isVideo+ width: 36; height: 36+ radius: 18+ color: Qt.rgba(0, 0, 0, 0.62)+ border.width: 1.5+ border.color: "#ffffff"+ Icon {+ anchors.centerIn: parent+ width: 16; height: 16+ path: Icons.play+ color: "#ffffff"+ }+ }++ // Video duration badge in bottom-right.+ Rectangle {+ anchors.right: parent.right+ anchors.rightMargin: 6+ anchors.bottom: parent.bottom+ anchors.bottomMargin: 6+ visible: tile.isVideo+ height: 20+ width: durTxt.implicitWidth + 12+ radius: 10+ color: Qt.rgba(0, 0, 0, 0.72)+ Txt {+ id: durTxt+ anchors.centerIn: parent+ role: "caption"+ size: 11+ color: "#ffffff"+ text: page.formatVideoDuration(tile.duration)+ }+ }++ // Selection checkbox circle in top-right.+ Rectangle {+ id: checkCircle+ z: 2+ anchors.top: parent.top+ anchors.topMargin: 6+ anchors.right: parent.right+ anchors.rightMargin: 6+ width: 24; height: 24+ radius: 12+ visible: tile.selected || tileHover.hovered || page.selectMode || page.selectedCount > 0+ color: tile.selected ? Theme.primary : Qt.rgba(0, 0, 0, 0.48)+ border.width: tile.selected ? 0 : 1.5+ border.color: "#ffffff"+ Icon {+ anchors.centerIn: parent+ visible: tile.selected+ width: 14; height: 14+ path: Icons.check+ color: Theme.primaryContent+ }+ MouseArea {+ anchors.fill: parent+ anchors.margins: -6+ onClicked: (mouse) => page.toggleSelect(tile.itemId, tile.index,+ (mouse.modifiers & Qt.ShiftModifier) !== 0)+ }+ }++ HoverHandler { id: tileHover; cursorShape: Qt.PointingHandCursor }+ // Under the selection circle (its z is higher). A MouseArea, as+ // a TapHandler's event point doesn't carry the keyboard modifiers.+ MouseArea {+ anchors.fill: parent+ onClicked: (mouse) => {+ const mods = mouse.modifiers+ const shift = (mods & Qt.ShiftModifier) !== 0+ const ctrl = (mods & Qt.ControlModifier) !== 0+ if (page.selectMode || page.selectedCount > 0 || shift || ctrl) {+ page.toggleSelect(tile.itemId, tile.index, shift)+ } else {+ page.openViewer(tile.index)+ }+ }+ }+ }+ }+}diff --git a/desktop/app/src/bridge/mod.rs b/desktop/app/src/bridge/mod.rsindex 9f15bb0..fd3cfbd 100644--- a/desktop/app/src/bridge/mod.rs+++ b/desktop/app/src/bridge/mod.rs@@ -26,6 +26,8 @@ pub mod notifications;#[allow(unsafe_code)]pub mod pairing;#[allow(unsafe_code)]+pub mod photos;+#[allow(unsafe_code)]pub mod prefs;#[allow(unsafe_code)]pub mod transfers;diff --git a/desktop/app/src/bridge/photos.rs b/desktop/app/src/bridge/photos.rsnew file mode 100644index 0000000..b1e40cb--- /dev/null+++ b/desktop/app/src/bridge/photos.rs@@ -0,0 +1,391 @@+// SPDX-License-Identifier: GPL-3.0-or-later+//! `Photos`: a phone's photo and video gallery as a Qt list model for the+//! virtualized `GridView`, plus albums and full-file actions (Save, Copy,+//! Open, and in-app viewing).++use std::{path::PathBuf, pin::Pin};++use cxx_qt::{CxxQtType, Threading};+use cxx_qt_lib::{+ QByteArray, QHash, QHashPair_i32_QByteArray, QList, QModelIndex, QString, QStringList, QUrl, QVariant,+};+use serde_json::json;++use super::{Edit, diff};+use crate::{+ photos::{self, ItemRow},+ state::Changes,+};++#[cxx_qt::bridge]+pub mod qobject {+ unsafe extern "C++" {+ include!(<QtCore/QAbstractListModel>);+ type QAbstractListModel;++ include!("cxx-qt-lib/qmodelindex.h");+ type QModelIndex = cxx_qt_lib::QModelIndex;+ include!("cxx-qt-lib/qvariant.h");+ type QVariant = cxx_qt_lib::QVariant;+ include!("cxx-qt-lib/qhash.h");+ type QHash_i32_QByteArray = cxx_qt_lib::QHash<cxx_qt_lib::QHashPair_i32_QByteArray>;+ include!("cxx-qt-lib/qlist.h");+ type QList_i32 = cxx_qt_lib::QList<i32>;+ include!("cxx-qt-lib/qstring.h");+ type QString = cxx_qt_lib::QString;+ include!("cxx-qt-lib/qstringlist.h");+ type QStringList = cxx_qt_lib::QStringList;+ }++ unsafe extern "RustQt" {+ #[qobject]+ #[base = QAbstractListModel]+ #[qml_element]+ #[qml_singleton]+ #[qproperty(QString, device)]+ /// "idle", "loading", "ready", "offline", "off", "unsupported" or "failed".+ #[qproperty(QString, status)]+ /// Albums on the phone (JSON array).+ #[qproperty(QString, albums)]+ /// Selected album ID ("" for All photos).+ #[qproperty(QString, album)]+ #[qproperty(i32, count)]+ #[qproperty(bool, more)]+ #[qproperty(bool, loading_older, cxx_name = "loadingOlder")]+ #[qproperty(bool, saving)]+ #[qproperty(QString, busy_item, cxx_name = "busyItem")]+ #[qproperty(QString, save_folder, cxx_name = "saveFolder")]+ #[qproperty(i32, revision)]+ type Photos = super::PhotosRust;+ }++ // Inherited from QAbstractListModel.+ unsafe extern "RustQt" {+ #[inherit]+ #[cxx_name = "beginInsertRows"]+ unsafe fn begin_insert_rows(self: Pin<&mut Photos>, parent: &QModelIndex, first: i32, last: i32);+ #[inherit]+ #[cxx_name = "endInsertRows"]+ unsafe fn end_insert_rows(self: Pin<&mut Photos>);+ #[inherit]+ #[cxx_name = "beginRemoveRows"]+ unsafe fn begin_remove_rows(self: Pin<&mut Photos>, parent: &QModelIndex, first: i32, last: i32);+ #[inherit]+ #[cxx_name = "endRemoveRows"]+ unsafe fn end_remove_rows(self: Pin<&mut Photos>);+ #[inherit]+ fn index(self: &Photos, row: i32, column: i32, parent: &QModelIndex) -> QModelIndex;++ #[inherit]+ #[qsignal]+ #[cxx_name = "dataChanged"]+ fn data_changed(+ self: Pin<&mut Photos>,+ top_left: &QModelIndex,+ bottom_right: &QModelIndex,+ roles: &QList_i32,+ );+ }++ unsafe extern "RustQt" {+ #[qinvokable]+ #[cxx_override]+ fn data(self: &Photos, index: &QModelIndex, role: i32) -> QVariant;+ #[qinvokable]+ #[cxx_override]+ #[cxx_name = "roleNames"]+ fn role_names(self: &Photos) -> QHash_i32_QByteArray;+ #[qinvokable]+ #[cxx_override]+ #[cxx_name = "rowCount"]+ fn row_count(self: &Photos, parent: &QModelIndex) -> i32;++ #[qinvokable]+ fn open(self: &Photos, device: &QString);+ #[qinvokable]+ #[cxx_name = "selectAlbum"]+ fn select_album(self: &Photos, album: &QString);+ #[qinvokable]+ #[cxx_name = "loadOlder"]+ fn load_older(self: &Photos);+ #[qinvokable]+ fn refresh(self: &Photos);+ #[qinvokable]+ #[cxx_name = "needThumb"]+ fn need_thumb(self: &Photos, id: &QString);+ #[qinvokable]+ #[cxx_name = "dropThumb"]+ fn drop_thumb(self: &Photos, id: &QString);+ #[qinvokable]+ #[cxx_name = "ensureFull"]+ fn ensure_full(self: &Photos, id: &QString);+ #[qinvokable]+ #[cxx_name = "openItem"]+ fn open_item(self: &Photos, id: &QString);+ #[qinvokable]+ #[cxx_name = "copyItem"]+ fn copy_item(self: &Photos, id: &QString);+ #[qinvokable]+ #[cxx_name = "saveItems"]+ fn save_items(self: &Photos, ids: &QStringList, folder_url: &QString);+ #[qinvokable]+ #[cxx_name = "chooseSaveFolder"]+ fn choose_save_folder(self: &Photos, folder_url: &QString);+ #[qinvokable]+ #[cxx_name = "itemAt"]+ fn item_at(self: &Photos, row: i32) -> QString;+ }++ impl cxx_qt::Threading for Photos {}+ impl cxx_qt::Initialize for Photos {}+}++#[derive(Default)]+pub struct PhotosRust {+ device: QString,+ status: QString,+ albums: QString,+ album: QString,+ count: i32,+ more: bool,+ loading_older: bool,+ saving: bool,+ busy_item: QString,+ save_folder: QString,+ revision: i32,+ rows: Vec<ItemRow>,+ last_albums: String,+}++const ROLES: &[&str] = &[+ "itemId",+ "name",+ "date",+ "prevDate",+ "size",+ "itemWidth",+ "itemHeight",+ "duration",+ "isVideo",+ "album",+ "thumb",+ "fullUrl",+];+const USER_ROLE: i32 = 0x0100;++fn role_value(row: &ItemRow, role: &str) -> QVariant {+ let text = |s: &str| QVariant::from(&QString::from(s));+ match role {+ "itemId" => text(&row.id),+ "name" => text(&row.name),+ "date" => QVariant::from(&(row.date as f64)),+ "prevDate" => QVariant::from(&(row.prev_date as f64)),+ "size" => QVariant::from(&(row.size as f64)),+ "itemWidth" => QVariant::from(&(row.width as i32)),+ "itemHeight" => QVariant::from(&(row.height as i32)),+ "duration" => QVariant::from(&(row.duration as i32)),+ "isVideo" => QVariant::from(&row.is_video),+ "album" => text(&row.album),+ "thumb" => text(&row.thumb),+ "fullUrl" => text(&row.full_url),+ _ => QVariant::default(),+ }+}++fn folder_from_url(url: &QString) -> Option<PathBuf> {+ let raw = String::from(url);+ if raw.trim().is_empty() {+ return None;+ }+ if let Some(local) = QUrl::from(url).to_local_file() {+ let s = String::from(&local);+ if !s.is_empty() {+ return Some(PathBuf::from(s));+ }+ }+ Some(PathBuf::from(raw))+}++impl cxx_qt::Initialize for qobject::Photos {+ fn initialize(mut self: Pin<&mut Self>) {+ self.as_mut().set_status(QString::from("idle"));+ self.as_mut().set_albums(QString::from("[]"));+ self.as_mut().set_save_folder(QString::from(r"Downloads\Nectarlink"));+ super::subscribe(self.qt_thread(), Changes::PHOTOS, Self::update_view);+ self.update_view();+ }+}++impl qobject::Photos {+ fn update_view(mut self: Pin<&mut Self>) {+ let view = photos::view();+ self.as_mut().set_device(QString::from(&view.device.map(|d| d.to_string()).unwrap_or_default()));+ self.as_mut().set_status(QString::from(view.status.as_str()));+ let albums_str = view.albums.to_string();+ if self.rust().last_albums != albums_str {+ self.as_mut().set_albums(QString::from(&albums_str));+ self.as_mut().rust_mut().last_albums = albums_str;+ }+ self.as_mut().set_album(QString::from(&view.album));+ self.as_mut().set_more(view.more);+ self.as_mut().set_loading_older(view.loading_older);+ self.as_mut().set_saving(view.saving);+ self.as_mut().set_busy_item(QString::from(&view.busy_item));+ 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();+ }+ }+ 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);+ let rev = self.revision().wrapping_add(1);+ self.set_revision(rev);+ }++ pub fn data(&self, index: &QModelIndex, role: i32) -> QVariant {+ let row = usize::try_from(index.row()).ok();+ let role = usize::try_from(role - USER_ROLE).ok().and_then(|r| ROLES.get(r));+ match (row.and_then(|r| self.rows.get(r)), role) {+ (Some(row), Some(role)) => role_value(row, role),+ _ => QVariant::default(),+ }+ }++ pub fn role_names(&self) -> QHash<QHashPair_i32_QByteArray> {+ let mut roles = QHash::<QHashPair_i32_QByteArray>::default();+ for (i, name) in ROLES.iter().enumerate() {+ roles.insert(USER_ROLE + i as i32, QByteArray::from(*name));+ }+ roles+ }++ pub fn row_count(&self, _parent: &QModelIndex) -> i32 {+ self.rows.len() as i32+ }++ pub fn open(&self, device: &QString) {+ if let Some(device) = super::parse_device(device) {+ photos::open_device(device);+ }+ }++ pub fn select_album(&self, album: &QString) {+ photos::select_album(String::from(album));+ }++ pub fn load_older(&self) {+ photos::load_older();+ }++ pub fn refresh(&self) {+ photos::reload();+ }++ pub fn need_thumb(&self, id: &QString) {+ photos::need_thumb(String::from(id));+ }++ pub fn drop_thumb(&self, id: &QString) {+ photos::drop_thumb(&String::from(id));+ }++ pub fn ensure_full(&self, id: &QString) {+ photos::ensure_full(String::from(id));+ }++ pub fn open_item(&self, id: &QString) {+ photos::open_item(String::from(id));+ }++ pub fn copy_item(&self, id: &QString) {+ photos::copy_item(String::from(id));+ }++ pub fn save_items(&self, ids: &QStringList, folder_url: &QString) {+ let list: Vec<String> =+ QList::<QString>::from(ids).iter().map(String::from).filter(|id| !id.is_empty()).collect();+ let folder = folder_from_url(folder_url);+ photos::save_items(list, folder);+ }++ pub fn choose_save_folder(&self, folder_url: &QString) {+ photos::set_save_folder(folder_from_url(folder_url));+ }++ pub fn item_at(&self, row: i32) -> QString {+ let Some(r) = usize::try_from(row).ok().and_then(|i| self.rows.get(i)) else {+ return QString::from("null");+ };+ QString::from(+ &json!({+ "id": r.id,+ "name": r.name,+ "date": r.date,+ "prevDate": r.prev_date,+ "size": r.size,+ "width": r.width,+ "height": r.height,+ "duration": r.duration,+ "isVideo": r.is_video,+ "album": r.album,+ "thumb": r.thumb,+ "fullUrl": r.full_url,+ })+ .to_string(),+ )+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn roles_describe_gallery_item() {+ let row = ItemRow {+ id: "media:42".into(),+ name: "IMG_0042.jpg".into(),+ date: 1_710_000_000_000,+ prev_date: 1_709_900_000_000,+ size: 204_800,+ width: 4000,+ height: 3000,+ duration: 0,+ is_video: false,+ album: "bucket:1".into(),+ thumb: "file:///C:/cache/thumb.jpg".into(),+ full_url: String::new(),+ };+ let text = |role| role_value(&row, role).value::<QString>().map(String::from).unwrap_or_default();+ assert_eq!(text("itemId"), "media:42");+ assert_eq!(text("name"), "IMG_0042.jpg");+ assert_eq!(text("thumb"), "file:///C:/cache/thumb.jpg");+ assert_eq!(role_value(&row, "itemWidth").value::<i32>(), Some(4000));+ assert_eq!(role_value(&row, "isVideo").value::<bool>(), Some(false));+ }+}diff --git a/desktop/app/src/photos.rs b/desktop/app/src/photos.rsindex 76dbff0..efa1aa3 100644--- a/desktop/app/src/photos.rs+++ b/desktop/app/src/photos.rs@@ -1,20 +1,30 @@// SPDX-License-Identifier: GPL-3.0-or-later-//! New photos from a phone (docs/protocol/photos.md): a Windows-//! notification with the preview, to open the photo, save it, or copy it.-//! The photo itself comes as a files transfer when the user asks.+//! Photos and videos from a phone (docs/protocol/photos.md):+//! - Windows notification with preview when a new photo or screenshot is taken,+//! to open, save, or copy it.+//! - The Photos gallery page: albums, paged items newest-first, on-demand+//! batched thumbnails cached on disk, in-app viewer, Save (to a chosen+//! folder or `Downloads\Nectarlink`), Copy to clipboard, and Open in the+//! Windows Photos app or default video player.use std::{- collections::HashMap,+ collections::{HashMap, HashSet},path::{Path, PathBuf},sync::Mutex,time::{Duration, Instant},};-use nectarlink_core::{DeviceId, Direction, Error, NodeEvent, Photo, Transfer, TransferState};+use nectarlink_core::{+ DeviceId, Direction, Error, FeatureState, LinkState, NodeEvent, Photo, PhotoAlbum, PhotoItem, PhotoThumb,+ Transfer, TransferState,+};+use serde_json::{Value, json};use crate::{bridge::app::{describe, show_message},core_host,+ messages::Status,+ state::Changes,win::toast::{self, Toast},};@@ -23,21 +33,35 @@ pub const TOAST_GROUP: &str = "photos";pub const ACTION_SAVE: &str = "save";pub const ACTION_COPY: &str = "copy";-/// What the user wants done with a photo once it's here.-#[derive(Debug, Clone, Copy, PartialEq, Eq)]+/// Items requested per gallery page, and thumbnails requested per batch.+const PAGE: u32 = 80;+const THUMB_BATCH: usize = 24;++/// What the user wants done with a transfer bringing one or more photos/videos.+#[derive(Debug, Clone, PartialEq, Eq)]enum Intent {- /// Kept in Downloads (the usual "saved" notification says so).- Save,- /// Opened in its app.- Open,- /// Put on the clipboard; not kept.- Copy,+ /// Kept in Downloads from a toast (the usual "saved" notification says so).+ ToastSave,+ /// Opened in its default app (Windows Photos or video player).+ Open { item_id: Option<String> },+ /// Put on the clipboard; not kept in Downloads.+ Copy { item_id: Option<String>, notify_ui: bool },+ /// Downloaded for the in-app viewer (moved into the gallery cache).+ View { device: DeviceId, item_id: String },+ /// Saved from the gallery to `Downloads\Nectarlink` or a user-chosen folder.+ GallerySave { ids: Vec<String>, folder: Option<PathBuf> },}#[derive(Debug, Default)]struct State {/// Transfers bringing photos the user asked for.pending: HashMap<String, Intent>,+ /// Transfers whose completion is handled here (so `transfers.rs` suppresses+ /// its generic "saved in Downloads" toast).+ handled: HashMap<String, Instant>,+ /// Transfers that bring a file the user doesn't keep (the viewer's, or+ /// one only for the clipboard): not listed with the others.+ private: HashMap<String, Instant>,/// Incoming transfers that finished lately, in case one finishes/// before the phone's answer says which it was.finished: HashMap<String, (Instant, Vec<PathBuf>)>,@@ -45,23 +69,76 @@ struct State {static STATE: Mutex<Option<State>> = Mutex::new(None);const KEEP_FINISHED: Duration = Duration::from_secs(60);+/// How long a private transfer stays out of the list (longer than any+/// photo or video takes to arrive).+const KEEP_PRIVATE: Duration = Duration::from_secs(6 * 60 * 60);fn state<T>(f: impl FnOnce(&mut State) -> T) -> T {f(STATE.lock().unwrap_or_else(|e| e.into_inner()).get_or_insert_default())}pub fn on_event(event: &NodeEvent) {+ let page_device = gallery_state(|s| s.device);match event {- NodeEvent::PhotoAdded { device, photo } => show(*device, photo),+ NodeEvent::PhotoAdded { device, photo } => {+ show(*device, photo);+ if !photo.thumb.is_empty() {+ let _ = write_thumb(*device, &photo.id, &photo.thumb);+ }+ if Some(*device) == page_device {+ reload_quiet();+ }+ }+ NodeEvent::PhotosChanged { device } if Some(*device) == page_device => {+ reload_quiet();+ }+ NodeEvent::LinkChanged { device, link: LinkState::Online { .. } } if Some(*device) == page_device => {+ if gallery_state(|s| s.status != Status::Ready) {+ reload();+ }+ }+ NodeEvent::LinkChanged { device, link: LinkState::Offline { .. } }+ if Some(*device) == page_device =>+ {+ gallery_state(|s| {+ s.status = Status::Offline;+ s.loading_older = false;+ });+ gallery_changed();+ }+ NodeEvent::Capabilities(matrix) if Some(matrix.device) == page_device => {+ match matrix.state("files.recent_photos") {+ Some(FeatureState::Available)+ if gallery_state(|s| !matches!(s.status, Status::Ready | Status::Loading)) =>+ {+ reload();+ }+ Some(FeatureState::Locked { .. } | FeatureState::Unsupported { .. })+ if gallery_state(|s| s.status == Status::Ready) =>+ {+ reload();+ }+ _ => {}+ }+ }NodeEvent::Transfer(t) if t.direction == Direction::Incoming => finished(t),_ => {}}}-/// Whether this transfer brings a photo the user asked to open or copy,-/// so the usual "saved" notification isn't wanted.+/// Whether this transfer brings a photo the user asked to open, copy, view, or+/// save from the gallery, so the usual "saved" toast notification isn't wanted.+/// Whether this transfer brings a file the user doesn't keep, so it isn't+/// listed with the other transfers.+pub fn is_private(transfer_id: &str) -> bool {+ state(|s| s.private.contains_key(transfer_id))+}+pub fn handles(transfer_id: &str) -> bool {- state(|s| s.pending.get(transfer_id).is_some_and(|intent| *intent != Intent::Save))+ state(|s| {+ s.handled.contains_key(transfer_id)+ || s.pending.get(transfer_id).is_some_and(|intent| *intent != Intent::ToastSave)+ })}fn show(device: DeviceId, photo: &Photo) {@@ -119,9 +196,9 @@ pub fn on_toast(key: &str, action: Option<&str>) {let Some((device, photo_id)) = key.split_once(' ') else { return };let Ok(device) = device.parse::<DeviceId>() else { return };let intent = match action {- None => Intent::Open,- Some(ACTION_SAVE) => Intent::Save,- Some(ACTION_COPY) => Intent::Copy,+ None => Intent::Open { item_id: Some(photo_id.to_owned()) },+ Some(ACTION_SAVE) => Intent::ToastSave,+ Some(ACTION_COPY) => Intent::Copy { item_id: Some(photo_id.to_owned()), notify_ui: false },Some(_) => return,};let Some(node) = core_host::node() else { return };@@ -137,20 +214,34 @@ pub fn on_toast(key: &str, action: Option<&str>) {}fn asked(transfer: String, intent: Intent) {+ let private = matches!(intent, Intent::View { .. } | Intent::Copy { .. });+ let id = transfer.clone();let done = state(|s| {let now = Instant::now();s.finished.retain(|_, (at, _)| now.duration_since(*at) < KEEP_FINISHED);+ s.handled.retain(|_, at| now.duration_since(*at) < KEEP_FINISHED);+ s.private.retain(|_, at| now.duration_since(*at) < KEEP_PRIVATE);+ if intent != Intent::ToastSave {+ s.handled.insert(transfer.clone(), now);+ }+ if private {+ s.private.insert(transfer.clone(), now);+ }match s.finished.remove(&transfer) {Some((_, saved)) => Some(saved),None => {- s.pending.insert(transfer, intent);+ s.pending.insert(transfer, intent.clone());None}}});+ if private {+ // It may have started before the phone said which transfer it was.+ core_host::host().hub.update(|s| s.forget_transfer(&id));+ }// Already here: the usual notification came first.if let Some(saved) = done {- if let (true, Some(first)) = (intent != Intent::Save, saved.first()) {+ if let (true, Some(first)) = (intent != Intent::ToastSave, saved.first()) {toast::remove(crate::transfers::TOAST_GROUP, &first.to_string_lossy());}deliver(intent, &saved);@@ -161,16 +252,32 @@ fn finished(t: &Transfer) {let saved = match &t.state {TransferState::Done { saved } => saved.clone(),TransferState::Failed(_) | TransferState::Cancelled => {- state(|s| s.pending.remove(&t.id));+ let removed = state(|s| s.pending.remove(&t.id));+ if removed.is_some() {+ gallery_state(|g| {+ g.saving = false;+ g.busy_item = None;+ });+ gallery_changed();+ }return;}_ => return,};- let intent = state(|s| match s.pending.remove(&t.id) {- Some(intent) => Some(intent),- None => {- s.finished.insert(t.id.clone(), (Instant::now(), saved.clone()));- None+ let intent = state(|s| {+ let now = Instant::now();+ s.handled.retain(|_, at| now.duration_since(*at) < KEEP_FINISHED);+ match s.pending.remove(&t.id) {+ Some(intent) => {+ if intent != Intent::ToastSave {+ s.handled.insert(t.id.clone(), now);+ }+ Some(intent)+ }+ None => {+ s.finished.insert(t.id.clone(), (now, saved.clone()));+ None+ }}});if let Some(intent) = intent {@@ -179,15 +286,133 @@ fn finished(t: &Transfer) {}fn deliver(intent: Intent, saved: &[PathBuf]) {- let Some(path) = saved.first() else { return };+ let Some(first) = saved.first() else {+ gallery_state(|g| {+ g.saving = false;+ g.busy_item = None;+ });+ gallery_changed();+ return;+ };match intent {- Intent::Save => {}- Intent::Open => crate::transfers::open(path),- Intent::Copy => copy(path),+ Intent::ToastSave => {}+ Intent::Open { item_id } => {+ if let Some(id) = item_id {+ gallery_state(|g| {+ g.full_files.insert(id, first.clone());+ if g.busy_item.is_some() {+ g.busy_item = None;+ }+ g.saving = false;+ });+ gallery_changed();+ }+ crate::transfers::open(first);+ }+ Intent::Copy { item_id: _, notify_ui } => {+ gallery_state(|g| {+ g.saving = false;+ g.busy_item = None;+ });+ gallery_changed();+ copy_file_to_clipboard(first, true, notify_ui);+ }+ Intent::View { device, item_id } => {+ let ext = first.extension().and_then(|e| e.to_str()).filter(|e| !e.is_empty()).unwrap_or("jpg");+ let dir = thumbs_dir(device);+ let cached = dir.join(format!("full-{:016x}.{ext}", fingerprint(&item_id)));+ let final_path =+ if std::fs::create_dir_all(&dir).and_then(|()| move_or_copy(first, &cached)).is_ok() {+ cached+ } else {+ first.clone()+ };+ gallery_state(|g| {+ g.full_files.insert(item_id.clone(), final_path);+ if g.busy_item.as_deref() == Some(item_id.as_str()) {+ g.busy_item = None;+ }+ });+ gallery_changed();+ }+ Intent::GallerySave { ids, folder } => {+ let mut final_paths = Vec::with_capacity(saved.len());+ let dest_label = match &folder {+ Some(dir) => {+ let _ = std::fs::create_dir_all(dir);+ for src in saved {+ let name = src.file_name().and_then(|n| n.to_str()).unwrap_or("photo.jpg");+ let dst = free_path(dir, name);+ if dst == *src || move_or_copy(src, &dst).is_ok() {+ final_paths.push(dst);+ } else {+ final_paths.push(src.clone());+ }+ }+ folder_display_name(dir)+ }+ None => {+ final_paths.extend(saved.iter().cloned());+ r"Downloads\Nectarlink".to_owned()+ }+ };+ gallery_state(|g| {+ if ids.len() == final_paths.len() {+ for (id, path) in ids.into_iter().zip(final_paths.iter().cloned()) {+ g.full_files.insert(id, path);+ }+ }+ g.saving = false;+ g.busy_item = None;+ });+ gallery_changed();+ match final_paths.as_slice() {+ [one] => {+ let name = one.file_name().and_then(|n| n.to_str()).unwrap_or("Photo");+ show_message(format!("Saved {name} to {dest_label}."));+ }+ many if !many.is_empty() => {+ show_message(format!("Saved {} items to {dest_label}.", many.len()));+ }+ _ => {}+ }+ }+ }+}++fn move_or_copy(src: &Path, dst: &Path) -> std::io::Result<()> {+ if src == dst {+ return Ok(());+ }+ if std::fs::rename(src, dst).is_ok() {+ return Ok(());}+ std::fs::copy(src, dst)?;+ let _ = std::fs::remove_file(src);+ Ok(())}-fn copy(path: &Path) {+fn free_path(dir: &Path, name: &str) -> PathBuf {+ let first = dir.join(name);+ if !first.exists() {+ return first;+ }+ let path = Path::new(name);+ let stem = path.file_stem().and_then(|s| s.to_str()).unwrap_or(name);+ let ext = path.extension().and_then(|e| e.to_str());+ for n in 2..10_000u32 {+ let candidate = match ext {+ Some(ext) => dir.join(format!("{stem} ({n}).{ext}")),+ None => dir.join(format!("{stem} ({n})")),+ };+ if !candidate.exists() {+ return candidate;+ }+ }+ first+}++fn copy_file_to_clipboard(path: &Path, remove_after: bool, notify_ui: bool) {let mime = match path.extension().and_then(|e| e.to_str()).map(str::to_ascii_lowercase).as_deref() {Some("png") => "image/png",_ => "image/jpeg",@@ -196,13 +421,739 @@ fn copy(path: &Path) {.map_err(|e| e.to_string()).and_then(|bytes| crate::win::clipboard::write_image(mime, &bytes));match copied {- // Only wanted on the clipboard.Ok(()) => {- let _ = std::fs::remove_file(path);+ if remove_after {+ let _ = std::fs::remove_file(path);+ }+ if notify_ui {+ show_message("Copied to clipboard.");+ }}Err(reason) => {tracing::warn!(reason, "can't copy a photo");- show_message("The photo couldn't be copied. It's in Downloads\\Nectarlink.");+ if remove_after {+ show_message("The photo couldn't be copied. It's in Downloads\\Nectarlink.");+ } else {+ show_message("The photo couldn't be copied to the clipboard.");+ }+ }+ }+}++// ---- Photos gallery page ----++#[derive(Debug, Clone, PartialEq)]+pub struct ItemRow {+ pub id: String,+ pub name: String,+ pub date: i64,+ pub prev_date: i64,+ pub size: u64,+ pub width: u32,+ pub height: u32,+ pub duration: u32,+ pub is_video: bool,+ pub album: String,+ pub thumb: String,+ pub full_url: String,+}++#[derive(Debug, Clone, PartialEq)]+pub struct View {+ pub device: Option<DeviceId>,+ pub status: Status,+ pub albums: Value,+ pub album: String,+ pub rows: Vec<ItemRow>,+ pub more: bool,+ pub loading_older: bool,+ pub saving: bool,+ pub busy_item: String,+ pub save_folder: String,+}++#[derive(Debug, Default)]+struct GalleryState {+ device: Option<DeviceId>,+ status: Status,+ albums: Vec<PhotoAlbum>,+ album: String,+ items: Vec<PhotoItem>,+ more: bool,+ loading_older: bool,+ thumbs: HashMap<String, PathBuf>,+ failed_thumbs: HashSet<String>,+ full_files: HashMap<String, PathBuf>,+ wanted_thumbs: Vec<String>,+ fetching_thumbs: bool,+ saving: bool,+ busy_item: Option<String>,+ save_folder: Option<PathBuf>,+ generation: u64,+}++static GALLERY: Mutex<Option<GalleryState>> = Mutex::new(None);++fn gallery_state<T>(f: impl FnOnce(&mut GalleryState) -> T) -> T {+ f(GALLERY.lock().unwrap_or_else(|e| e.into_inner()).get_or_insert_default())+}++fn gallery_changed() {+ core_host::host().hub.changed(Changes::PHOTOS);+}++fn thumbs_dir(device: DeviceId) -> PathBuf {+ core_host::host().data_dir.join("cache").join("photos-thumbs").join(device.to_string())+}++/// How much the gallery keeps on disk per phone: thumbnails, and full+/// photos opened in the viewer. The least recently written go first.+const THUMBS_BUDGET: u64 = 64 << 20;+const FULL_BUDGET: u64 = 512 << 20;++/// Trims a phone's gallery cache to its budgets.+fn prune_cache(device: DeviceId) {+ let Ok(entries) = std::fs::read_dir(thumbs_dir(device)) else { return };+ let (mut thumbs, mut full): (Vec<_>, Vec<_>) = entries+ .filter_map(|e| {+ let e = e.ok()?;+ let meta = e.metadata().ok().filter(|m| m.is_file())?;+ Some((meta.modified().ok()?, meta.len(), e.path()))+ })+ .partition(|(_, _, path)| {+ path.file_name().and_then(|n| n.to_str()).is_some_and(|n| n.starts_with("thumb-"))+ });+ for (files, budget) in [(&mut thumbs, THUMBS_BUDGET), (&mut full, FULL_BUDGET)] {+ // Newest first; delete beyond the budget.+ files.sort_by_key(|f| std::cmp::Reverse(f.0));+ let mut kept = 0u64;+ for (_, len, path) in files.iter() {+ kept += len;+ if kept > budget {+ let _ = std::fs::remove_file(path);+ }+ }+ }+}++fn thumb_path(device: DeviceId, id: &str) -> PathBuf {+ thumbs_dir(device).join(format!("thumb-{:016x}.jpg", fingerprint(id)))+}++fn write_thumb(device: DeviceId, id: &str, jpeg: &[u8]) -> Option<PathBuf> {+ if jpeg.is_empty() {+ return None;+ }+ let dir = thumbs_dir(device);+ let path = thumb_path(device, id);+ std::fs::create_dir_all(&dir).ok()?;+ std::fs::write(&path, jpeg).ok()?;+ gallery_state(|s| {+ if s.device == Some(device) {+ s.thumbs.insert(id.to_owned(), path.clone());+ }+ });+ Some(path)+}++fn populate_disk_thumbs(device: DeviceId, ids: impl IntoIterator<Item = String>) {+ let mut found = Vec::new();+ for id in ids {+ let already = gallery_state(|s| s.thumbs.contains_key(&id));+ if already {+ continue;+ }+ let path = thumb_path(device, &id);+ if path.exists() {+ found.push((id, path));+ }+ }+ if !found.is_empty() {+ gallery_state(|s| {+ if s.device == Some(device) {+ for (id, path) in found {+ s.thumbs.insert(id, path);+ }+ }+ });+ }+}++fn folder_display_name(dir: &Path) -> String {+ if let Some(home) = dirs::home_dir()+ && let Ok(rel) = dir.strip_prefix(&home)+ && !rel.as_os_str().is_empty()+ {+ return rel.to_string_lossy().into_owned();+ }+ dir.to_string_lossy().into_owned()+}++pub fn view() -> View {+ gallery_state(|s| {+ let mut prev_date = 0i64;+ let rows: Vec<ItemRow> = s+ .items+ .iter()+ .map(|item| {+ let thumb = s.thumbs.get(&item.id).map(|p| crate::icons::file_url(p)).unwrap_or_default();+ let full_url = s+ .full_files+ .get(&item.id)+ .filter(|p| p.exists())+ .map(|p| crate::icons::file_url(p))+ .unwrap_or_default();+ let row = ItemRow {+ id: item.id.clone(),+ name: item.name.clone(),+ date: item.date,+ prev_date,+ size: item.size,+ width: item.width,+ height: item.height,+ duration: item.duration.unwrap_or(0),+ is_video: item.duration.is_some() || item.id.starts_with("video:"),+ album: item.album.clone().unwrap_or_default(),+ thumb,+ full_url,+ };+ prev_date = item.date;+ row+ })+ .collect();+ let albums = Value::Array(+ s.albums+ .iter()+ .map(|a| {+ let cover = a.cover.clone().unwrap_or_default();+ let thumb = (!cover.is_empty())+ .then(|| s.thumbs.get(&cover))+ .flatten()+ .map(|p| crate::icons::file_url(p))+ .unwrap_or_default();+ json!({+ "id": a.id,+ "name": a.name,+ "count": a.count,+ "cover": cover,+ "thumb": thumb,+ })+ })+ .collect(),+ );+ let save_folder = s+ .save_folder+ .as_deref()+ .map(folder_display_name)+ .unwrap_or_else(|| r"Downloads\Nectarlink".to_owned());+ View {+ device: s.device,+ status: s.status,+ albums,+ album: s.album.clone(),+ rows,+ more: s.more,+ loading_older: s.loading_older,+ saving: s.saving,+ busy_item: s.busy_item.clone().unwrap_or_default(),+ save_folder,+ }+ })+}++/// Opens the gallery for `device` (reloads albums and items).+pub fn open_device(device: DeviceId) {+ let same = gallery_state(|s| {+ let same = s.device == Some(device);+ if !same {+ let save_folder = s.save_folder.take();+ *s = GalleryState {+ device: Some(device),+ save_folder,+ generation: s.generation + 1,+ ..GalleryState::default()+ };+ }+ same+ });+ if !same {+ gallery_changed();+ core_host::spawn(async move {+ let _ = tokio::task::spawn_blocking(move || prune_cache(device)).await;+ });+ }+ reload();+}++/// Switches to `album` (`""` for All photos) and loads its items.+pub fn select_album(album: String) {+ let changed_album = gallery_state(|s| {+ if s.album == album && !s.items.is_empty() {+ return false;+ }+ s.album = album;+ s.items.clear();+ s.more = false;+ s.loading_older = false;+ s.wanted_thumbs.clear();+ s.generation += 1;+ true+ });+ if changed_album {+ gallery_changed();+ load_items(None);+ }+}++pub fn reload() {+ load_albums();+ load_items(None);+}++fn reload_quiet() {+ load_albums();+ load_items(None);+}++pub fn load_older() {+ let before = gallery_state(|s| {+ if s.loading_older || !s.more {+ return None;+ }+ s.loading_older = true;+ s.items.last().map(|i| (i.date, i.id.clone()))+ });+ if before.is_some() {+ gallery_changed();+ load_items(before);+ }+}++fn load_albums() {+ let Some((device, generation)) = gallery_state(|s| s.device.map(|d| (d, s.generation))) else {+ return;+ };+ let Some(node) = core_host::node() else { return };+ core_host::spawn(async move {+ let Ok(albums) = node.photo_albums(device).await else {+ return;+ };+ let covers: Vec<String> =+ albums.iter().filter_map(|a| a.cover.clone()).filter(|c| !c.is_empty()).collect();+ populate_disk_thumbs(device, covers.clone());+ gallery_state(|s| {+ if s.device != Some(device) || s.generation != generation {+ return;+ }+ s.albums = albums;+ });+ gallery_changed();+ // Queue missing cover thumbnails so album covers appear promptly.+ for cover in covers {+ need_thumb(cover);+ }+ });+}++fn load_items(before: Option<(i64, String)>) {+ let Some((device, album, generation)) = gallery_state(|s| {+ if before.is_none() && s.items.is_empty() {+ s.status = Status::Loading;+ }+ let album = (!s.album.is_empty()).then(|| s.album.clone());+ s.device.map(|d| (d, album, s.generation))+ }) else {+ return;+ };+ gallery_changed();+ let Some(node) = core_host::node() else { return };+ core_host::spawn(async move {+ let first_page = before.is_none();+ let result = node.photo_list(device, album, before, PAGE).await;+ if let Ok(ref page) = result {+ populate_disk_thumbs(device, page.iter().map(|i| i.id.clone()));+ }+ gallery_state(|s| {+ s.loading_older = false;+ if s.device != Some(device) || s.generation != generation {+ return;+ }+ match result {+ Ok(page) => {+ let full = page.len() as u32 >= PAGE;+ if first_page {+ // A refresh: keep the older pages already loaded+ // beyond this one.+ let oldest = page.last().map(|i| i.date).unwrap_or(i64::MAX);+ let fresh: HashSet<&str> = page.iter().map(|i| i.id.as_str()).collect();+ let older: Vec<PhotoItem> = s+ .items+ .drain(..)+ .filter(|i| full && i.date <= oldest && !fresh.contains(i.id.as_str()))+ .collect();+ s.items = page;+ s.items.extend(older);+ s.more = full;+ } else {+ let existing: HashSet<String> = s.items.iter().map(|i| i.id.clone()).collect();+ s.items.extend(page.into_iter().filter(|i| !existing.contains(&i.id)));+ s.more = full;+ }+ s.status = Status::Ready;+ }+ Err(e) => {+ tracing::debug!(error = %e, "can't list photos");+ s.status = Status::of(&e);+ }+ }+ });+ gallery_changed();+ });+}++/// Requests a thumbnail for `id` (called by visible tiles in `GridView`).+pub fn need_thumb(id: String) {+ if id.is_empty() {+ return;+ }+ let Some(device) = gallery_state(|s| s.device) else { return };+ if gallery_state(|s| s.thumbs.contains_key(&id) || s.failed_thumbs.contains(&id)) {+ return;+ }+ let disk_path = thumb_path(device, &id);+ if disk_path.exists() {+ gallery_state(|s| {+ if s.device == Some(device) {+ s.thumbs.insert(id, disk_path);+ }+ });+ gallery_changed();+ return;+ }+ let start_pump = gallery_state(|s| {+ if s.device != Some(device) {+ return None;+ }+ if !s.wanted_thumbs.contains(&id) {+ s.wanted_thumbs.push(id);+ }+ if !s.fetching_thumbs {+ s.fetching_thumbs = true;+ Some((device, s.generation))+ } else {+ None+ }+ });+ if let Some((device, generation)) = start_pump {+ pump_thumbs(device, generation);+ }+}++/// Drops a pending thumbnail request when a tile scrolls off-screen before+/// being fetched.+pub fn drop_thumb(id: &str) {+ if id.is_empty() {+ return;+ }+ gallery_state(|s| {+ s.wanted_thumbs.retain(|wanted| wanted != id);+ });+}++fn pump_thumbs(device: DeviceId, generation: u64) {+ let Some(node) = core_host::node() else {+ gallery_state(|s| s.fetching_thumbs = false);+ return;+ };+ core_host::spawn(async move {+ loop {+ // Brief coalesce window so all tiles becoming visible in the same+ // frame are requested in one batch, and tiles scrolled past are+ // dropped before network I/O.+ tokio::time::sleep(Duration::from_millis(25)).await;+ let batch: Vec<String> = gallery_state(|s| {+ if s.device != Some(device) || s.generation != generation || s.wanted_thumbs.is_empty() {+ s.fetching_thumbs = false;+ return Vec::new();+ }+ let take = s.wanted_thumbs.len().min(THUMB_BATCH);+ s.wanted_thumbs.drain(..take).collect()+ });+ if batch.is_empty() {+ return;+ }+ match node.photo_thumbs(device, batch.clone()).await {+ Ok(thumbs) => {+ save_thumb_batch(device, generation, &batch, thumbs);+ gallery_changed();+ }+ Err(e) => {+ tracing::debug!(error = %e, "can't fetch photo thumbnails");+ gallery_state(|s| {+ for id in &batch {+ s.failed_thumbs.insert(id.clone());+ }+ s.fetching_thumbs = false;+ });+ return;+ }+ }+ }+ });+}++fn save_thumb_batch(device: DeviceId, generation: u64, requested: &[String], thumbs: Vec<PhotoThumb>) {+ let dir = thumbs_dir(device);+ let _ = std::fs::create_dir_all(&dir);+ let mut saved = HashMap::new();+ for t in thumbs {+ if t.data.is_empty() {+ continue;+ }+ let path = thumb_path(device, &t.id);+ if std::fs::write(&path, &t.data).is_ok() {+ saved.insert(t.id, path);+ }+ }+ gallery_state(|s| {+ if s.device != Some(device) || s.generation != generation {+ return;+ }+ for id in requested {+ if !saved.contains_key(id) {+ s.failed_thumbs.insert(id.clone());+ }+ }+ s.thumbs.extend(saved);+ });+}++/// Ensures the full-resolution image for `id` is downloaded for the in-app+/// viewer (for still photos; videos are opened in the default player on click).+pub fn ensure_full(id: String) {+ if id.is_empty() || id.starts_with("video:") {+ return;+ }+ let Some(device) = gallery_state(|s| {+ if s.full_files.get(&id).is_some_and(|p| p.exists()) {+ return None;+ }+ let is_video = s.items.iter().find(|i| i.id == id).is_some_and(|i| i.duration.is_some());+ if is_video {+ return None;+ }+ let dir = s.device.map(thumbs_dir)?;+ for ext in ["jpg", "jpeg", "png", "webp", "heic"] {+ let candidate = dir.join(format!("full-{:016x}.{ext}", fingerprint(&id)));+ if candidate.exists() {+ s.full_files.insert(id.clone(), candidate);+ return None;+ }+ }+ s.busy_item = Some(id.clone());+ s.device+ }) else {+ gallery_changed();+ return;+ };+ gallery_changed();+ let Some(node) = core_host::node() else { return };+ core_host::spawn(async move {+ match node.fetch_photo(device, id.clone()).await {+ Ok(transfer) => asked(transfer, Intent::View { device, item_id: id }),+ Err(e) => {+ tracing::debug!(error = %e, "can't fetch full photo for viewer");+ gallery_state(|s| {+ if s.busy_item.as_deref() == Some(id.as_str()) {+ s.busy_item = None;+ }+ });+ gallery_changed();+ }}+ });+}++/// Opens `id` in the Windows Photos app (or default video player), downloading+/// it first if needed.+pub fn open_item(id: String) {+ if id.is_empty() {+ return;+ }+ if let Some(existing) = gallery_state(|s| s.full_files.get(&id).filter(|p| p.exists()).cloned()) {+ crate::transfers::open(&existing);+ return;+ }+ let Some(device) = gallery_state(|s| {+ s.saving = true;+ s.busy_item = Some(id.clone());+ s.device+ }) else {+ return;+ };+ gallery_changed();+ let Some(node) = core_host::node() else { return };+ core_host::spawn(async move {+ match node.fetch_photo(device, id.clone()).await {+ Ok(transfer) => asked(transfer, Intent::Open { item_id: Some(id) }),+ Err(e) => {+ gallery_state(|s| {+ s.saving = false;+ s.busy_item = None;+ });+ gallery_changed();+ show_photo_error(&e);+ }+ }+ });+}++/// Copies one image `id` to the PC clipboard, downloading it first if needed.+pub fn copy_item(id: String) {+ if id.is_empty() {+ return;+ }+ if let Some(existing) = gallery_state(|s| s.full_files.get(&id).filter(|p| p.exists()).cloned()) {+ copy_file_to_clipboard(&existing, false, true);+ return;+ }+ let Some(device) = gallery_state(|s| {+ s.saving = true;+ s.busy_item = Some(id.clone());+ s.device+ }) else {+ return;+ };+ gallery_changed();+ let Some(node) = core_host::node() else { return };+ core_host::spawn(async move {+ match node.fetch_photo(device, id.clone()).await {+ Ok(transfer) => asked(transfer, Intent::Copy { item_id: Some(id), notify_ui: true }),+ Err(e) => {+ gallery_state(|s| {+ s.saving = false;+ s.busy_item = None;+ });+ gallery_changed();+ show_photo_error(&e);+ }+ }+ });+}++/// Sets the preferred destination folder for saving gallery items (`None`+/// resets to `Downloads\Nectarlink`).+pub fn set_save_folder(folder: Option<PathBuf>) {+ gallery_state(|s| s.save_folder = folder);+ gallery_changed();+}++/// Downloads and saves `ids` to `folder` (or the remembered `save_folder`, or+/// default `Downloads\Nectarlink`).+pub fn save_items(ids: Vec<String>, folder: Option<PathBuf>) {+ let ids: Vec<String> = ids.into_iter().filter(|id| !id.is_empty()).collect();+ if ids.is_empty() {+ return;+ }+ let Some((device, target_folder)) = gallery_state(|s| {+ if folder.is_some() {+ s.save_folder = folder.clone();+ }+ s.saving = true;+ s.device.map(|d| (d, folder.or_else(|| s.save_folder.clone())))+ }) else {+ return;+ };+ gallery_changed();+ let Some(node) = core_host::node() else { return };+ core_host::spawn(async move {+ match node.fetch_photos(device, ids.clone()).await {+ Ok(transfer) => asked(transfer, Intent::GallerySave { ids, folder: target_folder }),+ Err(e) => {+ gallery_state(|s| {+ s.saving = false;+ s.busy_item = None;+ });+ gallery_changed();+ show_photo_error(&e);+ }+ }+ });+}++fn show_photo_error(error: &Error) {+ match error {+ Error::NotFound => show_message("That photo isn't on the phone anymore."),+ Error::Denied => show_message("The phone doesn't share photos or files with this PC."),+ other => show_message(describe(other)),+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn gallery_view_formats_rows_and_prev_dates() {+ gallery_state(|s| {+ *s = GalleryState {+ status: Status::Ready,+ album: "bucket:1".into(),+ albums: vec![PhotoAlbum {+ id: "bucket:1".into(),+ name: "Camera".into(),+ count: 2,+ cover: Some("media:2".into()),+ }],+ items: vec![+ PhotoItem {+ id: "media:2".into(),+ name: "IMG_0002.jpg".into(),+ date: 1_710_000_000_000,+ size: 120_000,+ width: 1920,+ height: 1080,+ duration: None,+ album: Some("bucket:1".into()),+ },+ PhotoItem {+ id: "video:1".into(),+ name: "VID_0001.mp4".into(),+ date: 1_709_900_000_000,+ size: 4_500_000,+ width: 1280,+ height: 720,+ duration: Some(14_500),+ album: Some("bucket:1".into()),+ },+ ],+ more: true,+ ..GalleryState::default()+ };+ });++ let v = view();+ assert_eq!(v.status, Status::Ready);+ assert_eq!(v.album, "bucket:1");+ assert!(v.more);+ assert_eq!(v.rows.len(), 2);+ assert_eq!(v.rows[0].id, "media:2");+ assert_eq!(v.rows[0].prev_date, 0);+ assert!(!v.rows[0].is_video);+ assert_eq!(v.rows[1].id, "video:1");+ assert_eq!(v.rows[1].prev_date, 1_710_000_000_000);+ assert!(v.rows[1].is_video);+ assert_eq!(v.rows[1].duration, 14_500);+ }++ #[test]+ fn free_path_picks_unused_numbered_name() {+ let dir = tempfile::tempdir().unwrap();+ let first = free_path(dir.path(), "IMG_1.jpg");+ assert_eq!(first, dir.path().join("IMG_1.jpg"));+ std::fs::write(&first, b"a").unwrap();++ let second = free_path(dir.path(), "IMG_1.jpg");+ assert_eq!(second, dir.path().join("IMG_1 (2).jpg"));}}diff --git a/desktop/app/src/state.rs b/desktop/app/src/state.rsindex d8d30c9..8651dc8 100644--- a/desktop/app/src/state.rs+++ b/desktop/app/src/state.rs@@ -42,6 +42,8 @@ impl Changes {pub const MIRROR: Changes = Changes(1 << 13);/// A call in progress on a phone (kept by crate::calls).pub const CALLS: Changes = Changes(1 << 14);+ /// A phone's photo gallery (kept by crate::photos).+ pub const PHOTOS: Changes = Changes(1 << 15);pub fn is_empty(self) -> bool {self.0 == 0@@ -391,11 +393,17 @@ impl AppState {// crate::mirror).NodeEvent::ClipboardReceived { .. }| NodeEvent::PhotoAdded { .. }+ | NodeEvent::PhotosChanged { .. }| NodeEvent::Call { .. }| NodeEvent::CallLogChanged { .. }| NodeEvent::ContactsChanged { .. }| NodeEvent::SmsChanged { .. }| NodeEvent::Mirroring { .. } => Changes::NONE,+ // The gallery's own downloads (for its viewer, or the clipboard)+ // aren't files the user keeps.+ NodeEvent::Transfer(transfer) if crate::photos::is_private(&transfer.id) => {+ self.forget_transfer(&transfer.id)+ }NodeEvent::Transfer(transfer) => self.update_transfer(transfer.clone(), Instant::now()),// With artwork saved first (see crate::media).NodeEvent::MediaChanged { .. } => Changes::NONE,@@ -445,6 +453,13 @@ impl AppState {Changes::TRANSFERS}+ /// Forgets a transfer, finished or not.+ pub fn forget_transfer(&mut self, id: &str) -> Changes {+ let before = self.transfers.len();+ self.transfers.retain(|t| t.transfer.id != id);+ if self.transfers.len() == before { Changes::NONE } else { Changes::TRANSFERS }+ }+/// Forgets finished transfers.pub fn clear_finished_transfers(&mut self) -> Changes {let before = self.transfers.len();diff --git a/docs/protocol/capabilities.md b/docs/protocol/capabilities.mdindex 03d7626..e60be15 100644--- a/docs/protocol/capabilities.md+++ b/docs/protocol/capabilities.md@@ -45,7 +45,7 @@ capability is missing.| `clip.write` | Accepts clipboard content from the PC ([clipboard service](clipboard.md)) | app update || `clip.share` | Sends the clipboard when the user taps "Send" | app update || `clip.read.auto` | Sends clipboard changes automatically, in the background | Elevated |-| `photos.read` | Announces new photos and screenshots and sends them on request ([photos](photos.md)) | photos permission |+| `photos.read` | Announces new photos and screenshots, lists albums and items, serves thumbnails, and sends files on request ([photos](photos.md)) | photos permission || `mirror.capture` | Streams its screen (with the system's capture prompt at Basic; [mirroring](mirror.md)) | app update || `mirror.input` | Accepts touch, key and scroll input while mirrored | Assist || `mirror.virtual_display` | Runs apps on displays of their own, shown in windows on the PC ([mirroring](mirror.md)) | Elevated, Android 11+ |@@ -58,7 +58,7 @@ capability is missing.| ID | Meaning | Unlocked by ||---|---|---|| `pc.power` | Locks or sleeps on request ([actions](actions.md)) | app update |-| `photos.show` | Shows a phone's new photos ([photos](photos.md)) | app update |+| `photos.show` | Shows a phone's new photos and gallery ([photos](photos.md)) | app update || `call.show` | Shows a phone's calls, recent calls and dialer ([calls](calls.md)) | app update || `contacts.show` | Shows a phone's contacts ([contacts](contacts.md)) | app update || `sms.show` | Shows a phone's text messages ([messages](sms.md)) | app update |diff --git a/docs/protocol/photos.md b/docs/protocol/photos.mdindex 52cb839..5bd483b 100644--- a/docs/protocol/photos.md+++ b/docs/protocol/photos.md@@ -5,26 +5,27 @@> License: CC BY 4.0.A phone tells its PCs about each photo or screenshot it takes, with a small-preview, so the PC can offer it right away. The photo itself comes only-when the PC asks, as an ordinary files transfer.+preview, so the PC can offer it right away, and lets a PC browse its albums,+photos and videos with thumbnails fetched on demand. Full files come only when+the PC asks, as an ordinary files transfer.## 1. Capabilities| ID | Offered by | Meaning ||---|---|---|-| `photos.read` | phone | Announces new photos and sends them on request (needs the phone's photos permission) |-| `photos.show` | PC | Shows announced photos |+| `photos.read` | phone | Announces new photos, lists albums and items, serves thumbnails, and sends full files on request (needs the phone's photos permission) |+| `photos.show` | PC | Shows announced photos and the phone's gallery |-A phone announces photos only to PCs that offer `photos.show`, and only-while both devices allow it (the `photos` device toggle, on by default, on-each side).+A phone announces photos and library changes only to PCs that offer+`photos.show`, and only while both devices allow it (the `photos` device+toggle, on by default, on each side).## 2. MessagesOn the control stream.```-t = "photos.new" b = {+t = "photos.new" b = {id: text, // The phone's ID for it: 1–64 printable ASCII charactersname: text, // A file name, as in files.offersize: uint, // Bytes@@ -32,8 +33,40 @@ t = "photos.new" b = {screenshot: bool, // Optional, false when missingthumb: bytes, // A JPEG preview: at most 96 KiB, at most 512 pixels a side}-t = "photos.get" id = n b = { id: text }-t = "photos.sending" re = n b = { transfer: text }+t = "photos.albums" id = n b = {}+t = "photos.albums.list" re = n b = { albums: [ PhotoAlbum, ... ] }+t = "photos.list" id = n b = { album?: text, before?: int, before_id?: text, limit: uint }+t = "photos.items" re = n b = { items: [ PhotoItem, ... ] }+t = "photos.thumbs" id = n b = { ids: [ text, ... ] }+t = "photos.thumbs.list" re = n b = { thumbs: [ PhotoThumb, ... ] }+t = "photos.get" id = n b = { id?: text, ids?: [ text, ... ] }+t = "photos.sending" re = n b = { transfer: text }+t = "photos.changed" b = {}+```++```+PhotoAlbum = {+ id: text, // Album bucket ID on the phone+ name: text, // Display name, e.g. "Camera", "Screenshots"+ count: uint, // Number of photos and videos in the album+ cover?: text, // Newest item's ID, for its thumbnail+}++PhotoItem = {+ id: text, // Item ID on the phone (1–64 printable ASCII characters)+ name: text, // File name, sanitized as in files.offer+ date: int, // When it was taken (Unix ms), or else when it was saved+ size: uint, // Full file size in bytes+ width: uint, // Pixels (0 when unknown)+ height: uint, // Pixels (0 when unknown)+ duration?: uint, // Video duration in milliseconds (absent for photos)+ album?: text, // Album bucket ID+}++PhotoThumb = {+ id: text, // Item ID+ data: bytes, // A JPEG thumbnail: at most 96 KiB, ~256 pixels a side+}```### 2.1 `photos.new`@@ -43,18 +76,50 @@ connects later doesn't hear about it. It isn't answered. Phones **SHOULD**leave out bursts (a camera's burst mode, a downloaded album) beyond thelatest few. A PC drops announcements that break the rules above.-### 2.2 `photos.get`+### 2.2 `photos.albums`++Lists the phone's photo and video albums (MediaStore buckets), with each+album's item count and newest item ID (`cover`).-Asks for an announced photo. The phone starts sending it as a files-transfer ([files](files.md) §2) and answers with that transfer's `id`; the-PC finds the file there when the transfer is done.+### 2.3 `photos.list`-A phone keeps at least the 50 latest announced IDs and sends only photos-it announced. Errors: `NOT_FOUND` when the ID isn't one of them or the-photo is gone; `DENIED` when photos or files are off for the PC.+Lists photos and videos on the phone (or in `album` when given), newest+first by `date`, then in an order of the phone's own that never changes+(Android: by media ID). To get the next page, the PC sends the last item of+the one before as `before` (its `date`) and `before_id` (its `id`); the+phone answers with the items after it in that order, so items sharing a+date are neither skipped nor repeated. With `before` alone, only items+older than `before` come. `limit` is capped at 200, and the phone trims the+page if needed so the frame fits within `MAX_FRAME_LEN`; fewer items than+`limit` means there are no more.++### 2.4 `photos.thumbs`++Fetches small JPEG thumbnails for up to 24 item IDs in one batch. Items+whose thumbnail cannot be generated are omitted from `thumbs` rather than+failing the batch. The PC caches thumbnails on disk and only asks for+items currently visible in the grid.++### 2.5 `photos.get`++Asks for one (`id`) or several (`ids`, up to 200) photos or videos. The+phone starts sending them as a files transfer ([files](files.md) §2) and+answers with that transfer's `id`; the PC finds the file(s) there when the+transfer is done.++Errors: `NOT_FOUND` when a requested item is gone; `DENIED` when photos or+files are off for the PC.++### 2.6 `photos.changed`++Sent (debounced) when the phone's photo or video library changes so+connected PCs can refresh their album and item lists. It isn't answered.## 3. Privacy-- Nothing is sent before the user gives the phone app access to photos,- and only photos taken from then on are announced.-- Previews and photos are never logged; names neither (v0 §11).+- Nothing is sent before the user gives the phone app access to photos and+ videos (including Android 14's "Select photos" access, where only the+ chosen items are visible), and only new photos taken from then on are+ announced with `photos.new`.+- Previews, thumbnails and photos are never logged; names neither (v0 §11).+