Your Android phone and your Windows PC, working as one. Local-first, end-to-end encrypted, no account.
Phone apps in windows of their own on the PC
Bee9e04b56a9e38
diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xmlindex 591b3c7..db5add3 100644--- a/android/app/src/main/AndroidManifest.xml+++ b/android/app/src/main/AndroidManifest.xml@@ -217,6 +217,10 @@android:exported="false"android:foregroundServiceType="mediaProjection" />+ <receiver+ android:name=".mirror.AppWindows$CloseReceiver"+ android:exported="false" />+<serviceandroid:name=".service.ConnectionService"android:exported="false"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 ec7ab6d..0d57937 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@@ -20,6 +20,7 @@ import app.nectarlink.android.notifications.NotificationListenerimport app.nectarlink.android.calls.CallCompanionimport app.nectarlink.android.calls.PhoneCallsimport app.nectarlink.android.elevated.Elevated+import app.nectarlink.android.mirror.AppWindowsimport app.nectarlink.android.mirror.InputServiceimport app.nectarlink.android.mirror.MirrorRequestsimport app.nectarlink.android.photos.RecentPhotos@@ -76,6 +77,7 @@ class Core(context: Context, private val scope: CoroutineScope) : EventListeneronMirror = { pc, request ->MirrorRequests.show(this.context, request, _state.value.nameOf(pc).orEmpty())},+ appWindows = AppWindows(this.context, scope, open = { pc -> mirrorOpen(pc) }, nameOf = { pc -> _state.value.nameOf(pc).orEmpty() }),)private val sms = PhoneSms(this.context) {notificationOps.trySend { it.smsChanged(null) }@@ -396,6 +398,8 @@ class Core(context: Context, private val scope: CoroutineScope) : EventListener(if (PhoneSms.canRead(context)) listOf("sms.read") else emptyList()) +(if (PhoneSms.canSend(context)) listOf("sms.send") else emptyList()) +(if (InputService.running || Elevated.running) listOf("mirror.input") else emptyList()) ++ // Apps in windows of their own run on displays the Elevated helper makes.+ (if (Elevated.running && Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) listOf("mirror.virtual_display") else emptyList()) +// Asked for when a PC wants the sound.(if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) listOf("mirror.audio.playback") else emptyList())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 fe1b7f2..8b6bc98 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@@ -13,6 +13,7 @@ import app.nectarlink.android.notifications.NotificationListenerimport app.nectarlink.android.media.PhoneMediaimport app.nectarlink.android.photos.RecentPhotosimport app.nectarlink.android.elevated.Elevated+import app.nectarlink.android.mirror.AppWindowsimport app.nectarlink.android.mirror.InputServiceimport app.nectarlink.android.mirror.MirrorRequestimport app.nectarlink.android.mirror.MirrorRequests@@ -25,6 +26,8 @@ import app.nectarlink.core.SmsThreadimport app.nectarlink.core.FileToSendimport app.nectarlink.core.MediaActionimport app.nectarlink.core.MirrorInputEvent+import app.nectarlink.core.MirrorOptions+import app.nectarlink.core.PhoneAppimport app.nectarlink.core.NotificationFailureimport app.nectarlink.core.Platform@@ -44,6 +47,8 @@ internal class PhonePlatform(private val sms: () -> PhoneSms,/** Asks the user to share the screen with a PC: (PC's ID, request) → asked. */private val onMirror: (String, MirrorRequest) -> Boolean,+ /** Apps in windows of their own on PCs (Elevated). */+ private val appWindows: AppWindows,) : Platform {private val context = context.applicationContext@@ -65,21 +70,31 @@ internal class PhonePlatform(override fun callCommand(id: String, command: CallCommand): Boolean = onCall(id, command)- override fun mirrorRequested(pcId: String, maxSize: UInt, fps: UInt, bitrate: UInt, audio: Boolean): Boolean =- onMirror(pcId, MirrorRequest(pcId, maxSize.toInt(), fps.toInt(), bitrate.toInt(), audio))+ override fun mirrorRequested(pcId: String, options: MirrorOptions): Boolean =+ if (options.app != null) {+ appWindows.open(pcId, options)+ } else {+ val request = MirrorRequest(pcId, options.maxSize.toInt(), options.fps.toInt(), options.bitrate.toInt(), options.audio)+ onMirror(pcId, request)+ }- override fun mirrorStopRequested(pcId: String) {+ override fun mirrorStopRequested(pcId: String, session: UInt) {+ if (session != SCREEN) return appWindows.close(pcId, session)MirrorRequests.dismiss(context, pcId)MirrorService.stop(pcId)}- override fun mirrorKeyframeRequested(pcId: String) = MirrorService.keyframe(pcId)+ override fun mirrorKeyframeRequested(pcId: String, session: UInt) =+ if (session == SCREEN) MirrorService.keyframe(pcId) else appWindows.keyframe(pcId, session)// Real events when Elevated runs; gestures through the accessibility service otherwise.- override fun mirrorInput(pcId: String, input: MirrorInputEvent) {+ override fun mirrorInput(pcId: String, session: UInt, input: MirrorInputEvent) {+ if (session != SCREEN) return appWindows.input(pcId, session, input)if (!Elevated.handle(input)) InputService.handle(input)}+ override fun phoneApps(): List<PhoneApp> = AppWindows.list(context)+override fun smsThreads(limit: UInt): List<SmsThread> = sms().threads(limit.toInt())override fun smsMessages(thread: String, before: Long?, limit: UInt): List<SmsMessage> =@@ -132,4 +147,9 @@ internal class PhonePlatform(}return ActivityOptions.makeBasic().setPendingIntentBackgroundActivityStartMode(mode).toBundle()}++ private companion object {+ /** The phone's own screen's mirroring session. */+ const val SCREEN = 0u+ }}diff --git a/android/app/src/main/kotlin/app/nectarlink/android/elevated/AppDisplay.kt b/android/app/src/main/kotlin/app/nectarlink/android/elevated/AppDisplay.ktnew file mode 100644index 0000000..d5a47ca--- /dev/null+++ b/android/app/src/main/kotlin/app/nectarlink/android/elevated/AppDisplay.kt@@ -0,0 +1,215 @@+// SPDX-License-Identifier: GPL-3.0-or-later+package app.nectarlink.android.elevated++import android.annotation.SuppressLint+import android.content.Context+import android.content.ContextWrapper+import android.hardware.display.DisplayManager+import android.hardware.display.VirtualDisplay+import android.media.MediaCodec+import android.media.MediaCodecInfo+import android.media.MediaFormat+import android.os.Build+import android.os.Looper+import android.view.Surface+import java.io.DataOutputStream+import java.io.OutputStream++/**+ * An app in a window of its own (Elevated): a virtual display of its own,+ * made by the shell-side helper (apps may not put other apps on their+ * displays), with an H.264 encoder drawing from it, and the app started on+ * it. The encoded video goes to [out] as packets:+ * `u32 length | u8 kind | u64 time µs | data` (kind 0: config, as+ * `u32 width | u32 height | u32 display id`; 1: frame; 2: keyframe).+ */+@SuppressLint("PrivateApi", "DiscouragedPrivateApi", "BlockedPrivateApi")+class AppDisplay(+ private val width: Int,+ private val height: Int,+ private val dpi: Int,+ private val bitrate: Int,+ private val fps: Int,+) {+ @Volatile private var running = true+ private var display: VirtualDisplay? = null++ /** The display's ID, once made. */+ var displayId: Int = -1+ private set++ /** Streams until [stop] or until [out] fails; starts [pkg] on the display first. */+ fun run(pkg: String, out: OutputStream) {+ val format = MediaFormat.createVideoFormat(MediaFormat.MIMETYPE_VIDEO_AVC, width, height).apply {+ setInteger(MediaFormat.KEY_COLOR_FORMAT, MediaCodecInfo.CodecCapabilities.COLOR_FormatSurface)+ setInteger(MediaFormat.KEY_BIT_RATE, bitrate)+ setInteger(MediaFormat.KEY_FRAME_RATE, fps)+ setInteger(MediaFormat.KEY_I_FRAME_INTERVAL, 10)+ // Frames only when the picture changes; repeat now and then so a+ // still app still reaches a PC that just joined.+ setLong(MediaFormat.KEY_REPEAT_PREVIOUS_FRAME_AFTER, 100_000)+ setInteger(MediaFormat.KEY_COLOR_STANDARD, MediaFormat.COLOR_STANDARD_BT709)+ setInteger(MediaFormat.KEY_COLOR_RANGE, MediaFormat.COLOR_RANGE_LIMITED)+ setInteger(MediaFormat.KEY_PRIORITY, 0)+ }+ val codec = MediaCodec.createEncoderByType(MediaFormat.MIMETYPE_VIDEO_AVC)+ val data = DataOutputStream(out.buffered(1 shl 16))+ try {+ codec.configure(format, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE)+ val surface = codec.createInputSurface()+ val made = createDisplay(surface)+ display = made+ displayId = made.display.displayId+ codec.start()+ codecForKeyframes = codec+ write(data, KIND_CONFIG, 0, ByteArray(12).also {+ java.nio.ByteBuffer.wrap(it).putInt(width).putInt(height).putInt(displayId)+ })+ data.flush()+ launch(pkg, displayId)+ drain(codec, data)+ } finally {+ running = false+ codecForKeyframes = null+ runCatching { codec.stop() }+ codec.release()+ display?.release()+ display = null+ }+ }++ fun stop() {+ running = false+ }++ @Volatile private var codecForKeyframes: MediaCodec? = null++ /** The PC's decoder lost its place: a keyframe next. */+ fun requestKeyframe() {+ val codec = codecForKeyframes ?: return+ runCatching {+ codec.setParameters(android.os.Bundle().apply { putInt(MediaCodec.PARAMETER_KEY_REQUEST_SYNC_FRAME, 0) })+ }+ }++ private fun drain(codec: MediaCodec, out: DataOutputStream) {+ val info = MediaCodec.BufferInfo()+ var parameters = ByteArray(0)+ while (running) {+ val index = codec.dequeueOutputBuffer(info, 100_000)+ if (index < 0) continue+ val buffer = codec.getOutputBuffer(index)+ if (buffer != null && info.size > 0) {+ val bytes = ByteArray(info.size)+ buffer.position(info.offset)+ buffer.get(bytes)+ when {+ info.flags and MediaCodec.BUFFER_FLAG_CODEC_CONFIG != 0 -> parameters = bytes+ info.flags and MediaCodec.BUFFER_FLAG_KEY_FRAME != 0 -> {+ write(out, KIND_KEYFRAME, info.presentationTimeUs, parameters + bytes)+ out.flush()+ }+ else -> {+ write(out, KIND_FRAME, info.presentationTimeUs, bytes)+ out.flush()+ }+ }+ }+ codec.releaseOutputBuffer(index, false)+ if (info.flags and MediaCodec.BUFFER_FLAG_END_OF_STREAM != 0) return+ }+ }++ private fun write(out: DataOutputStream, kind: Int, timeUs: Long, bytes: ByteArray) {+ out.writeInt(1 + 8 + bytes.size)+ out.writeByte(kind)+ out.writeLong(timeUs)+ out.write(bytes)+ }++ private fun createDisplay(surface: Surface): VirtualDisplay {+ var flags = PUBLIC or OWN_CONTENT_ONLY or SUPPORTS_TOUCH or ROTATES_WITH_CONTENT or DESTROY_CONTENT_ON_REMOVAL+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {+ flags = flags or TRUSTED or OWN_DISPLAY_GROUP or ALWAYS_UNLOCKED or TOUCH_FEEDBACK_DISABLED+ }+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {+ flags = flags or OWN_FOCUS or DEVICE_DISPLAY_GROUP+ }+ val constructor = DisplayManager::class.java.getDeclaredConstructor(Context::class.java)+ constructor.isAccessible = true+ val manager = constructor.newInstance(ShellContext.get())+ // Some of the flags are hidden ones (TRUSTED, OWN_FOCUS...), which+ // the shell may use.+ @SuppressLint("WrongConstant")+ return manager.createVirtualDisplay("Nectarlink", width, height, dpi, surface, flags)+ }++ private fun launch(pkg: String, display: Int) {+ val command = arrayOf(+ "am", "start", "--display", display.toString(), "--windowingMode", "1",+ "-a", "android.intent.action.MAIN", "-c", "android.intent.category.LAUNCHER", "-p", pkg,+ "-f", (FLAG_NEW_TASK or FLAG_MULTIPLE_TASK).toString(),+ )+ Runtime.getRuntime().exec(command).waitFor()+ }++ companion object {+ const val KIND_CONFIG = 0+ const val KIND_FRAME = 1+ const val KIND_KEYFRAME = 2++ // DisplayManager.VIRTUAL_DISPLAY_FLAG_* (some hidden).+ private const val PUBLIC = 1+ private const val OWN_CONTENT_ONLY = 1 shl 3+ private const val SUPPORTS_TOUCH = 1 shl 6+ private const val ROTATES_WITH_CONTENT = 1 shl 7+ private const val DESTROY_CONTENT_ON_REMOVAL = 1 shl 8+ private const val TRUSTED = 1 shl 10+ private const val OWN_DISPLAY_GROUP = 1 shl 11+ private const val ALWAYS_UNLOCKED = 1 shl 12+ private const val TOUCH_FEEDBACK_DISABLED = 1 shl 13+ private const val OWN_FOCUS = 1 shl 14+ private const val DEVICE_DISPLAY_GROUP = 1 shl 15++ private const val FLAG_NEW_TASK = 0x10000000+ private const val FLAG_MULTIPLE_TASK = 0x08000000+ }+}++/**+ * A context for system services in the shell-side helper, which has no app+ * of its own: the system context, speaking as the shell package (scrcpy+ * does the same).+ */+@SuppressLint("PrivateApi", "DiscouragedPrivateApi", "SoonBlockedPrivateApi")+internal class ShellContext private constructor(base: Context) : ContextWrapper(base) {+ override fun getPackageName(): String = SHELL+ override fun getOpPackageName(): String = SHELL+ override fun getApplicationContext(): Context = this++ @Suppress("NewApi")+ override fun getAttributionSource(): android.content.AttributionSource =+ android.content.AttributionSource.Builder(android.os.Process.SHELL_UID).setPackageName(SHELL).build()++ companion object {+ private const val SHELL = "com.android.shell"+ @Volatile private var instance: ShellContext? = null++ @Synchronized+ fun get(): ShellContext = instance ?: ShellContext(systemContext()).also { instance = it }++ private fun systemContext(): Context {+ if (Looper.getMainLooper() == null) {+ @Suppress("DEPRECATION")+ Looper.prepareMainLooper()+ }+ val type = Class.forName("android.app.ActivityThread")+ val constructor = type.getDeclaredConstructor().apply { isAccessible = true }+ val thread = constructor.newInstance()+ type.getDeclaredField("sCurrentActivityThread").apply { isAccessible = true }.set(null, thread)+ // Hidden-API rules are for apps; this runs in the shell's own process.+ runCatching { type.getDeclaredField("mSystemThread").apply { isAccessible = true }.setBoolean(thread, true) }+ return type.getDeclaredMethod("getSystemContext").invoke(thread) as Context+ }+ }+}diff --git a/android/app/src/main/kotlin/app/nectarlink/android/elevated/Elevated.kt b/android/app/src/main/kotlin/app/nectarlink/android/elevated/Elevated.ktindex 48f2b31..43fe660 100644--- a/android/app/src/main/kotlin/app/nectarlink/android/elevated/Elevated.kt+++ b/android/app/src/main/kotlin/app/nectarlink/android/elevated/Elevated.kt@@ -69,6 +69,8 @@ object Elevated {private var shell: AdbStream? = null@Volatile private var input: Writer? = nullprivate var socket: java.net.Socket? = null+ /** Where the helper listens, and the token it wants, while it runs. */+ @Volatile private var helper: Pair<Int, String>? = nullval running: Boolean get() = input != null@@ -198,6 +200,7 @@ object Elevated {val first = output.readLine().orEmpty()val port = first.removePrefix("ready ").toIntOrNull()check(first.startsWith("ready ") && port != null) { "the helper said ${first.ifEmpty { "nothing" }}" }+ helper = port to tokenval local = java.net.Socket(java.net.InetAddress.getLoopbackAddress(), port).apply { tcpNoDelay = true }socket = localval writer = OutputStreamWriter(local.outputStream, Charsets.UTF_8)@@ -240,6 +243,7 @@ object Elevated {private fun stopLocked() {input = null+ helper = nullrunCatching { socket?.close() }runCatching { shell?.close() }runCatching { adb?.disconnect() }@@ -267,9 +271,18 @@ object Elevated {/** The PC's input as real events; false if Elevated isn't running. */fun handle(event: MirrorInputEvent): Boolean {- val writer = input ?: return falseval (w, h) = screen()- val line = when (event) {+ return handleOn(null, w, h, event)+ }++ /**+ * The PC's input on display [display] (an app window's, [w] × [h]+ * pixels), or the screen when null.+ */+ fun handleOn(display: Int?, w: Float, h: Float, event: MirrorInputEvent): Boolean {+ val writer = input ?: return false+ val to = display?.let { "@$it " }.orEmpty()+ val line = to + when (event) {is MirrorInputEvent.Touch -> {val action = when (event.action) {TouchPhase.DOWN -> "D"@@ -280,15 +293,33 @@ object Elevated {}is MirrorInputEvent.Scroll -> "S ${event.x * w} ${event.y * h} ${event.dx} ${event.dy}"is MirrorInputEvent.Key -> keys[event.key]?.let { "K $it" }- ?: if (event.key == "notifications") "C cmd statusbar expand-notifications" else return true+ ?: if (event.key == "notifications" && display == null) "C cmd statusbar expand-notifications" else return true// One line per piece: no line breaks inside.is MirrorInputEvent.Text -> return event.text.split('\n').withIndex().all { (i, piece) ->- (i == 0 || send(writer, "K ${KeyEvent.KEYCODE_ENTER}")) && (piece.isEmpty() || send(writer, "T $piece"))+ (i == 0 || send(writer, "${to}K ${KeyEvent.KEYCODE_ENTER}")) && (piece.isEmpty() || send(writer, "${to}T $piece"))}}return send(writer, line)}+ /**+ * Opens an app window: the helper runs [pkg] on a display of its own of+ * [width] × [height] pixels at [dpi], and streams it on the returned+ * connection (packets as [AppDisplay] writes them). Null when Elevated+ * isn't running. Write "K\n" for a keyframe; close it to close the window.+ */+ fun openApp(pkg: String, width: Int, height: Int, dpi: Int, bitrate: Int, fps: Int): java.net.Socket? {+ val (port, token) = helper ?: return null+ return runCatching {+ java.net.Socket(java.net.InetAddress.getLoopbackAddress(), port).apply {+ tcpNoDelay = true+ val out = OutputStreamWriter(getOutputStream(), Charsets.UTF_8)+ out.write("$token\nV $width $height $dpi $bitrate $fps $pkg\n")+ out.flush()+ }+ }.onFailure { Log.w(TAG, "can't open an app window", it) }.getOrNull()+ }+private fun send(writer: Writer, line: String): Boolean = try {synchronized(writer) {writer.write(line + "\n")diff --git a/android/app/src/main/kotlin/app/nectarlink/android/elevated/InputServer.kt b/android/app/src/main/kotlin/app/nectarlink/android/elevated/InputServer.ktindex 5956406..c853738 100644--- a/android/app/src/main/kotlin/app/nectarlink/android/elevated/InputServer.kt+++ b/android/app/src/main/kotlin/app/nectarlink/android/elevated/InputServer.kt@@ -28,6 +28,14 @@ import java.security.MessageDigest* K keycode a key, pressed and released* T text typed text (what the keyboard map can type)* C command... a shell command of a fixed set (see `allowed`)+ * Any of these after `@display ` goes to that display (an app window's).+ *+ * A connection whose first line (after the token) is+ * V width height dpi bitrate fps package+ * is an app window instead: the helper makes it a display of its own, runs+ * the app there and streams the display's video back on that connection+ * (see [AppDisplay]); a `K` line asks for a keyframe; closing the+ * connection closes the window.*/object InputServer {@JvmStatic@@ -55,17 +63,50 @@ object InputServer {// Compared in constant time: the token is the only key.val given = runCatching { reader.readLine() }.getOrNull() ?: returnif (!MessageDigest.isEqual(given.toByteArray(), token.toByteArray())) return- while (true) {- val line = reader.readLine() ?: return- runCatching { injector.handle(line) }.onFailure { System.err.println("input failed: $it") }+ val first = reader.readLine() ?: return+ if (first.startsWith("V ")) return appWindow(client, first, reader)+ var line: String? = first+ while (line != null) {+ val input = line+ runCatching { injector.handle(input) }.onFailure { System.err.println("input failed: $it") }+ line = reader.readLine()}}}+ /** An app window on this connection, until it closes. */+ private fun appWindow(client: Socket, request: String, reader: java.io.BufferedReader) {+ val parts = request.split(' ')+ val numbers = parts.subList(1, 6).map { it.toIntOrNull() ?: return }+ val (width, height, dpi, bitrate, fps) = numbers+ val pkg = parts.getOrNull(6)?.takeIf { PACKAGE.matches(it) } ?: return+ if (width !in 16..4096 || height !in 16..4096 || dpi !in 72..1000) return+ val window = AppDisplay(width, height, dpi, bitrate.coerceIn(500_000, 40_000_000), fps.coerceIn(1, 120))+ // Further lines: keyframe requests; the end of them closes the window.+ Thread {+ try {+ while (true) {+ val line = reader.readLine() ?: break+ if (line == "K") window.requestKeyframe()+ }+ } catch (_: java.io.IOException) {+ }+ window.stop()+ }.start()+ runCatching { window.run(pkg, client.getOutputStream()) }.onFailure { System.err.println("app window ended: $it") }+ }++ private val PACKAGE = Regex("[A-Za-z][A-Za-z0-9_]*(\\.[A-Za-z][A-Za-z0-9_]*)+")+private class Injector {private val manager: Anyprivate val inject: Methodprivate var downTime = 0L+ /** The display the line being handled is for (-1: the screen's own). */+ private var display = -1+ private val setDisplayId: Method? = runCatching {+ InputEvent::class.java.getMethod("setDisplayId", Int::class.javaPrimitiveType)+ }.getOrNull()init {// Android 14 moved injection to InputManagerGlobal.@@ -75,7 +116,14 @@ object InputServer {inject = owner.getMethod("injectInputEvent", InputEvent::class.java, Int::class.javaPrimitiveType)}- fun handle(line: String) {+ fun handle(full: String) {+ var line = full+ display = -1+ if (line.startsWith("@")) {+ val space = line.indexOf(' ')+ display = line.substring(1, space).toInt()+ line = line.substring(space + 1)+ }val parts = line.split(' ', limit = 2)val rest = parts.getOrElse(1) { "" }when (parts[0]) {@@ -89,11 +137,12 @@ object InputServer {}"K" -> key(rest.toInt())"T" -> type(rest)- "C" -> if (rest in allowed) Runtime.getRuntime().exec(rest.split(' ').toTypedArray()).waitFor()+ "C" -> if (rest in allowed && display < 0) Runtime.getRuntime().exec(rest.split(' ').toTypedArray()).waitFor()}}private fun send(event: InputEvent) {+ if (display >= 0) setDisplayId?.invoke(event, display)// 0: asynchronous; the app doesn't wait for the target app.inject.invoke(manager, event, 0)}diff --git a/android/app/src/main/kotlin/app/nectarlink/android/mirror/AppWindows.kt b/android/app/src/main/kotlin/app/nectarlink/android/mirror/AppWindows.ktnew file mode 100644index 0000000..d59e389--- /dev/null+++ b/android/app/src/main/kotlin/app/nectarlink/android/mirror/AppWindows.kt@@ -0,0 +1,268 @@+// SPDX-License-Identifier: GPL-3.0-or-later+package app.nectarlink.android.mirror++import android.app.PendingIntent+import android.content.BroadcastReceiver+import android.content.Context+import android.content.Intent+import android.content.pm.PackageManager+import android.graphics.Bitmap+import android.graphics.Canvas+import android.os.Build+import android.util.Log+import android.view.WindowManager+import androidx.core.app.NotificationCompat+import androidx.core.app.NotificationManagerCompat+import app.nectarlink.android.R+import app.nectarlink.android.elevated.AppDisplay+import app.nectarlink.android.elevated.Elevated+import app.nectarlink.core.MirrorInputEvent+import app.nectarlink.core.MirrorOptions+import app.nectarlink.core.MirrorSendResult+import app.nectarlink.core.MirrorStream+import app.nectarlink.core.PhoneApp+import app.nectarlink.core.VideoPacketKind+import app.nectarlink.core.mirrorConfig+import java.io.ByteArrayOutputStream+import java.io.DataInputStream+import java.io.EOFException+import java.net.Socket+import java.util.concurrent.ConcurrentHashMap+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.launch+import kotlin.math.max+import kotlin.math.roundToInt++/**+ * Phone apps in windows of their own on a PC (Elevated): each runs on a+ * display the shell-side helper makes for it, whose video goes to the PC+ * as a mirroring session of its own. A notification says so while any are+ * open, with a button to close them.+ */+class AppWindows(+ context: Context,+ private val scope: CoroutineScope,+ /** Opens a video stream to a PC. */+ private val open: suspend (String) -> MirrorStream,+ /** A PC's name. */+ private val nameOf: (String) -> String,+) {+ private val context = context.applicationContext++ private class Window(+ val pc: String,+ val session: UInt,+ val socket: Socket,+ val width: Int,+ val height: Int,+ ) {+ @Volatile var display: Int = -1+ }++ private val windows = ConcurrentHashMap<Pair<String, UInt>, Window>()++ init {+ instance = this+ }++ /** Runs the PC's app on a display of its own and streams it; false if it can't. */+ fun open(pc: String, options: MirrorOptions): Boolean {+ val pkg = options.app ?: return false+ if (pkg == context.packageName) return false+ val (width, height, dpi) = size(options.maxSize.toInt())+ val socket = Elevated.openApp(pkg, width, height, dpi, options.bitrate.toInt(), options.fps.toInt()) ?: return false+ val window = Window(pc, options.session, socket, width, height)+ windows.put(pc to options.session, window)?.let { runCatching { it.socket.close() } }+ changed()+ scope.launch(Dispatchers.IO) {+ val stream = runCatching { open(pc) }.getOrElse {+ Log.w(TAG, "can't stream an app window", it)+ close(window)+ return@launch+ }+ Thread({ forward(window, stream) }, "app-window").start()+ }+ return true+ }++ /** The helper's packets to the PC, until either side closes. */+ private fun forward(window: Window, stream: MirrorStream) {+ try {+ val input = DataInputStream(window.socket.getInputStream().buffered(1 shl 16))+ while (true) {+ val length = input.readInt()+ if (length < 9 || length > MAX_PACKET) return+ val kind = input.readUnsignedByte()+ val time = input.readLong().toULong()+ val data = ByteArray(length - 9).also { input.readFully(it) }+ val result = when (kind) {+ AppDisplay.KIND_CONFIG -> {+ val fields = java.nio.ByteBuffer.wrap(data)+ val (w, h) = fields.int to fields.int+ window.display = fields.int+ stream.send(VideoPacketKind.CONFIG, 0u, mirrorConfig(w.toUInt(), h.toUInt(), window.session))+ }+ AppDisplay.KIND_KEYFRAME -> stream.send(VideoPacketKind.KEYFRAME, time, data)+ else -> stream.send(VideoPacketKind.FRAME, time, data)+ }+ when (result) {+ MirrorSendResult.CLOSED -> return+ MirrorSendResult.NEED_KEYFRAME, MirrorSendResult.DROPPED -> keyframe(window)+ MirrorSendResult.QUEUED -> {}+ }+ }+ } catch (_: EOFException) {+ } catch (e: java.io.IOException) {+ Log.d(TAG, "an app window ended", e)+ } finally {+ stream.end()+ close(window)+ }+ }++ /** The PC closed a window. */+ fun close(pc: String, session: UInt) {+ windows[pc to session]?.let(::close)+ }++ private fun close(window: Window) {+ runCatching { window.socket.close() }+ if (windows.remove(window.pc to window.session, window)) changed()+ }++ fun closeAll() {+ windows.values.toList().forEach(::close)+ }++ fun keyframe(pc: String, session: UInt) {+ windows[pc to session]?.let(::keyframe)+ }++ private fun keyframe(window: Window) {+ runCatching {+ synchronized(window) {+ window.socket.getOutputStream().apply {+ write("K\n".toByteArray())+ flush()+ }+ }+ }+ }++ /** The PC's mouse and keyboard on a window. */+ fun input(pc: String, session: UInt, event: MirrorInputEvent) {+ val window = windows[pc to session] ?: return+ if (window.display < 0) return+ Elevated.handleOn(window.display, window.width.toFloat(), window.height.toFloat(), event)+ }++ /** The phone's screen size scaled to fit [maxSize] (multiples of 16, for encoders), and its density likewise. */+ private fun size(maxSize: Int): Triple<Int, Int, Int> {+ val windows = context.getSystemService(WindowManager::class.java)+ val (w, h) = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {+ windows.maximumWindowMetrics.bounds.let { it.width() to it.height() }+ } else {+ val metrics = android.util.DisplayMetrics()+ @Suppress("DEPRECATION")+ windows.defaultDisplay.getRealMetrics(metrics)+ metrics.widthPixels to metrics.heightPixels+ }+ // Upright, like a phone held normally.+ val (shortSide, longSide) = minOf(w, h) to maxOf(w, h)+ val scale = minOf(1f, maxSize.coerceAtLeast(320).toFloat() / longSide)+ fun fit(v: Int) = max(16, ((v * scale) / 16).toInt() * 16)+ val dpi = (context.resources.displayMetrics.densityDpi * scale).roundToInt().coerceIn(120, 640)+ return Triple(fit(shortSide), fit(longSide), dpi)+ }++ private fun changed() {+ val manager = NotificationManagerCompat.from(context)+ if (windows.isEmpty()) {+ manager.cancel(NOTIFICATION_ID)+ return+ }+ val allowed = Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU ||+ context.checkSelfPermission(android.Manifest.permission.POST_NOTIFICATIONS) == PackageManager.PERMISSION_GRANTED+ if (!allowed) return+ MirrorService.createChannel(context)+ val pcs = windows.values.map { it.pc }.distinct().map(nameOf).filter { it.isNotEmpty() }+ val closeAll = PendingIntent.getBroadcast(+ context, 0, Intent(context, CloseReceiver::class.java),+ PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT,+ )+ val notification = NotificationCompat.Builder(context, MirrorService.CHANNEL)+ .setSmallIcon(R.drawable.ic_notification)+ .setContentTitle(+ context.resources.getQuantityString(R.plurals.app_windows_title, windows.size, windows.size),+ )+ .setContentText(+ context.getString(R.string.app_windows_text, pcs.joinToString().ifEmpty { context.getString(R.string.your_pc) }),+ )+ .setOngoing(true)+ .setSilent(true)+ .setCategory(NotificationCompat.CATEGORY_SERVICE)+ .addAction(0, context.getString(R.string.action_close_all), closeAll)+ .build()+ try {+ manager.notify(NOTIFICATION_ID, notification)+ } catch (e: SecurityException) {+ Log.i(TAG, "can't say the app windows are open", e)+ }+ }++ /** The notification's Close all. */+ class CloseReceiver : BroadcastReceiver() {+ override fun onReceive(context: Context, intent: Intent) {+ instance?.closeAll()+ }+ }++ companion object {+ private const val TAG = "AppWindows"+ private const val NOTIFICATION_ID = 7+ /** Packets from the helper, at most. */+ private const val MAX_PACKET = 8 shl 20++ @Volatile private var instance: AppWindows? = null++ /** The apps a PC may open in windows: launchable ones, by name, with small icons. */+ fun list(context: Context): List<PhoneApp> {+ val manager = context.packageManager+ val launcher = Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_LAUNCHER)+ val found = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {+ manager.queryIntentActivities(launcher, PackageManager.ResolveInfoFlags.of(0))+ } else {+ @Suppress("DEPRECATION")+ manager.queryIntentActivities(launcher, 0)+ }+ return found+ .map { it.activityInfo }+ .filter { it.packageName != context.packageName }+ .distinctBy { it.packageName }+ .map { info ->+ PhoneApp(+ pkg = info.packageName,+ label = info.loadLabel(manager).toString().trim().ifEmpty { info.packageName },+ icon = runCatching { icon(info.loadIcon(manager)) }.getOrNull(),+ )+ }+ .sortedBy { it.label.lowercase() }+ }++ /** A PNG of the icon: 64 pixels, or 48 when that's too big. */+ private fun icon(drawable: android.graphics.drawable.Drawable): ByteArray? {+ for (size in intArrayOf(64, 48)) {+ val bitmap = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888)+ drawable.setBounds(0, 0, size, size)+ drawable.draw(Canvas(bitmap))+ val png = ByteArrayOutputStream().also { bitmap.compress(Bitmap.CompressFormat.PNG, 100, it) }.toByteArray()+ bitmap.recycle()+ if (png.size <= MAX_ICON_BYTES) return png+ }+ return null+ }++ private const val MAX_ICON_BYTES = 8 * 1024+ }+}diff --git a/android/app/src/main/kotlin/app/nectarlink/android/mirror/MirrorService.kt b/android/app/src/main/kotlin/app/nectarlink/android/mirror/MirrorService.ktindex 7c772c9..cb7bfd6 100644--- a/android/app/src/main/kotlin/app/nectarlink/android/mirror/MirrorService.kt+++ b/android/app/src/main/kotlin/app/nectarlink/android/mirror/MirrorService.kt@@ -154,7 +154,7 @@ class MirrorService : Service() {companion object {private const val TAG = "MirrorService"- private const val CHANNEL = "mirroring"+ internal const val CHANNEL = "mirroring"private const val NOTIFICATION_ID = 4private const val ACTION_STOP = "app.nectarlink.android.mirror.STOP"private const val EXTRA_PC = "pc"diff --git a/android/app/src/main/kotlin/app/nectarlink/android/mirror/ScreenEncoder.kt b/android/app/src/main/kotlin/app/nectarlink/android/mirror/ScreenEncoder.ktindex 51425c8..9aa58ce 100644--- a/android/app/src/main/kotlin/app/nectarlink/android/mirror/ScreenEncoder.kt+++ b/android/app/src/main/kotlin/app/nectarlink/android/mirror/ScreenEncoder.kt@@ -93,7 +93,7 @@ internal class ScreenEncoder(current.resize(size.width, size.height, size.dpi)current.surface = surface}- val closed = stream.send(VideoPacketKind.CONFIG, 0u, mirrorConfig(size.width.toUInt(), size.height.toUInt())) ==+ val closed = stream.send(VideoPacketKind.CONFIG, 0u, mirrorConfig(size.width.toUInt(), size.height.toUInt(), 0u)) ==MirrorSendResult.CLOSED || drain(codec)runCatching { codec.stop() }codec.release()diff --git a/android/app/src/main/res/values/strings.xml b/android/app/src/main/res/values/strings.xmlindex 3d7f27d..88add62 100644--- a/android/app/src/main/res/values/strings.xml+++ b/android/app/src/main/res/values/strings.xml@@ -102,6 +102,12 @@<string name="mirror_request_text">Tap to share it. You can stop anytime.</string><string name="mirror_sharing">Sharing your screen with %1$s</string><string name="action_stop">Stop</string>+ <plurals name="app_windows_title">+ <item quantity="one">An app is open in a window on a PC</item>+ <item quantity="other">%d apps are open in windows on a PC</item>+ </plurals>+ <string name="app_windows_text">Shown on %1$s. They run here, beside what\'s on your screen.</string>+ <string name="action_close_all">Close all</string><string name="sms_title">Text from your PC</string><string name="sms_off">Read your conversations and send texts from your PC. Nectarlink needs access to your messages and contacts for that.</string><string name="calls_title">Show calls on your PC</string>diff --git a/core/nectarlink-cli/src/main.rs b/core/nectarlink-cli/src/main.rsindex dd12fd0..5b0716a 100644--- a/core/nectarlink-cli/src/main.rs+++ b/core/nectarlink-cli/src/main.rs@@ -176,11 +176,29 @@ enum Command {/// Also ask for the phone's sound, and save it here (WAV).#[arg(long)]sound: Option<PathBuf>,+ /// An app (package name) to show in a window of its own instead of+ /// the screen (Elevated phones; `apps` lists them).+ #[arg(long)]+ app: Option<String>,+ /// Taps while recording, one every 2 s from the first frame, each+ /// "x,y" in fractions of the screen (repeatable).+ #[arg(long)]+ tap: Vec<String>,+ },+ /// List the apps a paired phone can open in windows of their own.+ Apps {+ device: String,+ /// Where to reach the phone, when discovery can't.+ #[arg(long)]+ at: Vec<std::net::SocketAddr>,},/// Use a paired phone's screen: tap at x,y (fractions of the screen),/// swipe, scroll, press a key (back, home, recents, enter...) or type.Input {device: String,+ /// The app window's session (from `mirror --app`), or 0 for the screen.+ #[arg(long, default_value_t = 0)]+ session: u32,#[command(subcommand)]action: InputArg,},@@ -199,6 +217,10 @@ enum Command {/// file of 16-bit PCM).#[arg(long)]sound: Option<PathBuf>,+ /// Also offer a few sample apps to open in windows (as an Elevated+ /// phone would), each streaming the same video.+ #[arg(long)]+ apps: bool,},/// Act as a phone with a few sample conversations (use with --as-phone),/// so a PC can read them and text through this client; stays online.@@ -494,10 +516,83 @@ fn stream_sound(sound: &nectarlink_core::MirrorStream, rate: u32, channels: u8,println!("Stopped sharing the sound.");}-/// PCs that asked for the screen (and whether they want the sound), for-/// `screen`.-static SCREEN_ASKS: std::sync::OnceLock<tokio::sync::mpsc::UnboundedSender<(DeviceId, bool)>> =+/// PCs that asked for the screen or an app (whether they want the sound,+/// and the session), for `screen`.+static SCREEN_ASKS: std::sync::OnceLock<tokio::sync::mpsc::UnboundedSender<(DeviceId, bool, u32)>> =std::sync::OnceLock::new();+/// Whether `screen` offers apps in windows.+static SCREEN_APPS: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);+/// The apps `screen --apps` offers.+const SAMPLE_APPS: &[(&str, &str)] = &[+ ("com.example.calendar", "Calendar"),+ ("com.example.camera", "Camera"),+ ("com.example.chat", "Chat"),+ ("com.example.maps", "Maps"),+ ("com.example.music", "Music"),+ ("com.example.notes", "Notes"),+ ("com.example.photos", "Photos"),+ ("com.example.settings", "Settings"),+];++/// A small, plain PNG icon in a color of its own (a rounded square would+/// need drawing; a solid one is enough to tell them apart).+fn sample_icon(i: usize) -> Vec<u8> {+ const SIZE: u32 = 48;+ let hues = [(234, 67, 53), (66, 133, 244), (52, 168, 83), (251, 188, 5), (171, 71, 188), (0, 172, 193)];+ let (r, g, b) = hues[i % hues.len()];+ // Each scanline: no filter, then its pixels.+ let line: Vec<u8> =+ std::iter::once(0).chain(std::iter::repeat_n([r, g, b], SIZE as usize).flatten()).collect();+ let raw = line.repeat(SIZE as usize);+ png(SIZE, SIZE, &raw)+}++/// An RGB PNG from filtered scanlines (stored, uncompressed).+fn png(width: u32, height: u32, raw: &[u8]) -> Vec<u8> {+ fn crc(data: &[u8]) -> u32 {+ let mut c = 0xffff_ffffu32;+ for &b in data {+ c ^= u32::from(b);+ for _ in 0..8 {+ c = if c & 1 != 0 { 0xedb8_8320 ^ (c >> 1) } else { c >> 1 };+ }+ }+ !c+ }+ fn chunk(out: &mut Vec<u8>, kind: &[u8], data: &[u8]) {+ out.extend_from_slice(&(data.len() as u32).to_be_bytes());+ let start = out.len();+ out.extend_from_slice(kind);+ out.extend_from_slice(data);+ let sum = crc(&out[start..]);+ out.extend_from_slice(&sum.to_be_bytes());+ }+ // zlib with stored blocks, and its Adler-32.+ let mut zlib = vec![0x78, 0x01];+ for (i, block) in raw.chunks(65_535).enumerate() {+ let last = (i + 1) * 65_535 >= raw.len();+ zlib.push(u8::from(last));+ let len = block.len() as u16;+ zlib.extend_from_slice(&len.to_le_bytes());+ zlib.extend_from_slice(&(!len).to_le_bytes());+ zlib.extend_from_slice(block);+ }+ let (mut a, mut b) = (1u32, 0u32);+ for &byte in raw {+ a = (a + u32::from(byte)) % 65_521;+ b = (b + a) % 65_521;+ }+ zlib.extend_from_slice(&((b << 16) | a).to_be_bytes());+ let mut out = b"\x89PNG\r\n\x1a\n".to_vec();+ let mut header = Vec::new();+ header.extend_from_slice(&width.to_be_bytes());+ header.extend_from_slice(&height.to_be_bytes());+ header.extend_from_slice(&[8, 2, 0, 0, 0]);+ chunk(&mut out, b"IHDR", &header);+ chunk(&mut out, b"IDAT", &zlib);+ chunk(&mut out, b"IEND", &[]);+ out+}/// A sample text for `texts`: (thread, number, name, incoming, body, Unix ms).type SampleText = (u32, String, String, bool, String, i64);@@ -548,7 +643,11 @@ const PHOTO_ID: &str = "cli-photo";struct TerminalPlatform;impl Platform for TerminalPlatform {- fn mirror_sink(&self, _peer: &DeviceId) -> Option<std::sync::Arc<dyn nectarlink_core::MirrorSink>> {+ fn mirror_sink(+ &self,+ _peer: &DeviceId,+ _session: u32,+ ) -> Option<std::sync::Arc<dyn nectarlink_core::MirrorSink>> {RECORDING.get().map(|r| r.clone() as std::sync::Arc<dyn nectarlink_core::MirrorSink>)}fn mirror_requested(@@ -557,16 +656,44 @@ impl Platform for TerminalPlatform {options: &nectarlink_core::MirrorStart,) -> std::result::Result<(), String> {let asks = SCREEN_ASKS.get().ok_or("not sharing a screen (run `screen`)")?;- if options.audio {- println!("It wants the sound too.");+ match &options.app {+ Some(app) if SAMPLE_APPS.iter().any(|(pkg, _)| pkg == app) => {+ println!("A PC opened {app} in a window (session {}).", options.session);+ }+ Some(_) => return Err("no such app".into()),+ None => {+ if options.audio {+ println!("It wants the sound too.");+ }+ println!(+ "A PC asked for the screen ({}px, {} fps); sharing it.",+ options.max_size, options.fps+ );+ }}- println!("A PC asked for the screen ({}px, {} fps); sharing it.", options.max_size, options.fps);- asks.send((*peer, options.audio)).map_err(|e| e.to_string())+ asks.send((*peer, options.audio, options.session)).map_err(|e| e.to_string())+ }+ fn mirror_stop_requested(&self, _peer: &DeviceId, session: u32) {+ println!("The PC stopped watching (session {session}).");}- fn mirror_stop_requested(&self, _peer: &DeviceId) {- println!("The PC stopped watching.");+ fn mirror_input(&self, _peer: &DeviceId, session: u32, input: nectarlink_core::MirrorInput) {+ println!("Input on session {session}: {input:?}");+ }+ fn phone_apps(&self) -> std::result::Result<Vec<nectarlink_core::PhoneApp>, String> {+ if !SCREEN_APPS.load(std::sync::atomic::Ordering::Relaxed) {+ return Err("not offering apps (run `screen --apps`)".into());+ }+ Ok(SAMPLE_APPS+ .iter()+ .enumerate()+ .map(|(i, (pkg, label))| nectarlink_core::PhoneApp {+ pkg: (*pkg).into(),+ label: (*label).into(),+ icon: Some(sample_icon(i)),+ })+ .collect())}- fn mirror_keyframe_requested(&self, _peer: &DeviceId) {+ fn mirror_keyframe_requested(&self, _peer: &DeviceId, _session: u32) {println!("The PC asked for a keyframe.");}fn sms_threads(&self, limit: u32) -> std::result::Result<Vec<nectarlink_core::SmsThread>, String> {@@ -935,7 +1062,7 @@ async fn run(cli: &Cli, node: &Node) -> Result<()> {node.update_power(node_power(cli), offers).await;watch(node, true).await?;}- Command::Input { device, action } => {+ Command::Input { device, session, action } => {use nectarlink_core::{MirrorInput, TouchAction};let mut offers = cli.offers.clone();offers.push(nectarlink_core::MIRROR_VIEW.into());@@ -965,14 +1092,29 @@ async fn run(cli: &Cli, node: &Node) -> Result<()> {InputArg::Type { text } => vec![MirrorInput::Text { text: text.clone() }],};for input in inputs {- node.mirror_input(id, input).await.context("not sent")?;+ node.mirror_input(id, *session, input).await.context("not sent")?;tokio::time::sleep(Duration::from_millis(30)).await;}// Let it leave before this client goes.tokio::time::sleep(Duration::from_millis(500)).await;println!("Sent.");}- Command::Mirror { device, out, seconds, at, sound } => {+ Command::Apps { device, at } => {+ let id = resolve(node, device)?;+ if !at.is_empty() {+ node.add_known_addrs(id, at);+ }+ wait_until_online(node, id).await?;+ for app in node.mirror_apps(id).await.context("no apps")? {+ println!(+ "{:<40} {}{}",+ app.pkg,+ app.label,+ app.icon.map(|i| format!(" ({} B icon)", i.len())).unwrap_or_default()+ );+ }+ }+ Command::Mirror { device, out, seconds, at, sound, app, tap } => {let recording = std::sync::Arc::new(Recording::default());*recording.file.lock().unwrap() =Some(std::fs::File::create(out).context("can't create the file")?);@@ -988,11 +1130,15 @@ async fn run(cli: &Cli, node: &Node) -> Result<()> {node.add_known_addrs(id, at);}wait_until_online(node, id).await?;+ // An app window is a session of its own.+ let session = u32::from(app.is_some());let options = nectarlink_core::MirrorStart {max_size: 1920,fps: 60,bitrate: 8_000_000,- audio: sound.is_some(),+ audio: sound.is_some() && app.is_none(),+ session,+ app: app.clone(),};node.mirror_start(id, options).await.context("the phone didn't ask its user")?;println!(@@ -1005,8 +1151,21 @@ async fn run(cli: &Cli, node: &Node) -> Result<()> {}}let started = std::time::Instant::now();- tokio::time::sleep(std::time::Duration::from_secs(*seconds)).await;- node.mirror_stop(id).await;+ for at in tap {+ tokio::time::sleep(std::time::Duration::from_secs(2)).await;+ let (x, y) = at.split_once(',').context("--tap takes x,y")?;+ let (x, y): (f32, f32) = (x.trim().parse()?, y.trim().parse()?);+ use nectarlink_core::{MirrorInput, TouchAction};+ for action in [TouchAction::Down, TouchAction::Up] {+ node.mirror_input(id, session, MirrorInput::Touch { action, x, y })+ .await+ .context("not sent")?;+ }+ println!("Tapped {x},{y}.");+ }+ let left = std::time::Duration::from_secs(*seconds).saturating_sub(started.elapsed());+ tokio::time::sleep(left).await;+ node.mirror_stop(id, session).await;let RecordingStats { frames, keyframes, bytes, size } = *recording.stats.lock().unwrap();let secs = started.elapsed().as_secs_f64();println!(@@ -1036,7 +1195,7 @@ async fn run(cli: &Cli, node: &Node) -> Result<()> {}}}- Command::Screen { video, width, height, fps, sound } => {+ Command::Screen { video, width, height, fps, sound, apps } => {if !cli.as_phone {bail!("screens are shared by phones: add --as-phone");}@@ -1060,12 +1219,16 @@ async fn run(cli: &Cli, node: &Node) -> Result<()> {if sound.is_some() {offers.push(nectarlink_core::MIRROR_AUDIO_PLAYBACK.into());}+ if *apps {+ SCREEN_APPS.store(true, std::sync::atomic::Ordering::Relaxed);+ offers.push(nectarlink_core::MIRROR_VIRTUAL_DISPLAY.into());+ }node.update_power(node_power(cli), offers).await;println!("Sharing a {width}x{height} screen ({} frames) with PCs that ask.", units.len());let streamer = node.clone();let (width, height, fps) = (*width, *height, *fps);tokio::spawn(async move {- while let Some((pc, wants_sound)) = asked.recv().await {+ while let Some((pc, wants_sound, session)) = asked.recv().await {let mirror = match streamer.mirror_open(pc).await {Ok(mirror) => std::sync::Arc::new(mirror),Err(e) => {@@ -1074,7 +1237,7 @@ async fn run(cli: &Cli, node: &Node) -> Result<()> {}};let units = units.clone();- std::thread::spawn(move || stream_screen(&mirror, &units, width, height, fps));+ std::thread::spawn(move || stream_screen(&mirror, &units, width, height, fps, session));if let (true, Some((rate, channels, samples))) = (wants_sound, sound.clone()) {match streamer.mirror_open_audio(pc).await {Ok(stream) => {@@ -1905,9 +2068,10 @@ fn stream_screen(width: u32,height: u32,fps: u32,+ session: u32,) {use nectarlink_core::{MirrorSend, PacketKind};- let config = nectarlink_core::MirrorConfig { codec: "h264".into(), width, height }.to_cbor();+ let config = nectarlink_core::MirrorConfig { codec: "h264".into(), width, height, session }.to_cbor();if mirror.send(PacketKind::Config, 0, config) == MirrorSend::Closed {return;}diff --git a/core/nectarlink-core/src/config.rs b/core/nectarlink-core/src/config.rsindex 941c2d4..5905b09 100644--- a/core/nectarlink-core/src/config.rs+++ b/core/nectarlink-core/src/config.rs@@ -123,19 +123,24 @@ pub trait Platform: Send + Sync + 'static {Err("this device doesn't share photos".into())}- /// Where a phone's screen goes on this PC, when it starts streaming- /// (after [`Node::mirror_start`](crate::Node::mirror_start)). `None`- /// refuses the stream.+ /// Where a phone's screen (`session` 0, with its sound) or app window+ /// goes on this PC, when it starts streaming (after+ /// [`Node::mirror_start`](crate::Node::mirror_start)). `None` refuses+ /// the stream.fn mirror_sink(&self,_peer: &nectarlink_protocol::DeviceId,+ _session: u32,) -> Option<std::sync::Arc<dyn crate::MirrorSink>> {None}/// A PC asked for this phone's screen: ask the user, then (if they/// agree) stream it with [`Node::mirror_open`](crate::Node::mirror_open).- /// `Err` (a reason for logs) when the user can't be asked.+ /// Or, with `options.app`, for an app in a window of its own: run it on+ /// a display of its own and stream that (no asking: that's Elevated).+ /// The stream's config packets carry `options.session`. `Err` (a+ /// reason for logs) when it can't.fn mirror_requested(&self,_peer: &nectarlink_protocol::DeviceId,@@ -144,15 +149,23 @@ pub trait Platform: Send + Sync + 'static {Err("this device doesn't share its screen".into())}- /// The PC stopped watching: stop sharing the screen.- fn mirror_stop_requested(&self, _peer: &nectarlink_protocol::DeviceId) {}+ /// The PC stopped watching: stop sharing the screen or app window.+ fn mirror_stop_requested(&self, _peer: &nectarlink_protocol::DeviceId, _session: u32) {}- /// The PC's mouse or keyboard on this phone's mirrored screen (checked,- /// and only while it offers `mirror.input`). Must return quickly.- fn mirror_input(&self, _peer: &nectarlink_protocol::DeviceId, _input: crate::MirrorInput) {}+ /// The PC's mouse or keyboard on this phone's mirrored screen or app+ /// window (checked, and only while it offers `mirror.input`, or+ /// `mirror.virtual_display` for app windows). Must return quickly.+ fn mirror_input(&self, _peer: &nectarlink_protocol::DeviceId, _session: u32, _input: crate::MirrorInput) {+ }/// The PC's decoder needs a fresh start: encode a keyframe next.- fn mirror_keyframe_requested(&self, _peer: &nectarlink_protocol::DeviceId) {}+ fn mirror_keyframe_requested(&self, _peer: &nectarlink_protocol::DeviceId, _session: u32) {}++ /// The apps a PC may open in windows of their own (launchable ones),+ /// with small PNG icons (a PC asked).+ fn phone_apps(&self) -> Result<Vec<crate::PhoneApp>, String> {+ Err("this device doesn't open apps in windows".into())+ }/// This phone's latest conversations, newest first (a PC asked).fn sms_threads(&self, _limit: u32) -> Result<Vec<crate::SmsThread>, String> {diff --git a/core/nectarlink-core/src/events.rs b/core/nectarlink-core/src/events.rsindex 6e45ce7..4234239 100644--- a/core/nectarlink-core/src/events.rs+++ b/core/nectarlink-core/src/events.rs@@ -142,6 +142,8 @@ pub enum NodeEvent {/// A phone's screen started or stopped showing here.Mirroring {device: DeviceId,+ /// Which mirroring: 0 for the screen, others for app windows.+ session: u32,on: bool,},/// A phone's messages changed: in `thread`, or anywhere when `None`.diff --git a/core/nectarlink-core/src/features.rs b/core/nectarlink-core/src/features.rsindex c6b4bf5..2437c1d 100644--- a/core/nectarlink-core/src/features.rs+++ b/core/nectarlink-core/src/features.rs@@ -673,6 +673,8 @@ pub const FEATURES: &[FeatureDef] = &[phone("mirror.virtual_display", ELEVATED),PowerAtLeast(PowerLevel::Elevated),AndroidAtLeast(11),+ desktop("mirror.view", UPDATE),+ DeviceToggle("mirroring"),],partial: None,},diff --git a/core/nectarlink-core/src/lib.rs b/core/nectarlink-core/src/lib.rsindex 857011d..0e9b390 100644--- a/core/nectarlink-core/src/lib.rs+++ b/core/nectarlink-core/src/lib.rs@@ -44,14 +44,16 @@ pub use nectarlink_protocol::{messages::{Battery, CLIP_MAX_BYTES, CallControls, CallState, DeviceInfo, DeviceKind, MediaPlayer,MirrorAudioConfig, MirrorConfig, MirrorInput, MirrorStart, Notification, NotificationAction,- PhotoNew as Photo, PowerLevel, SmsMessage, SmsPart, SmsThread, TouchAction,+ PhoneApp, PhotoNew as Photo, PowerLevel, SmsMessage, SmsPart, SmsThread, TouchAction,calls::{CONTROL as CALLS_CONTROL, IN_CALL as CALLS_IN_CALL, SHOW as CALLS_SHOW, STATE as CALLS_STATE,},+ is_package_name,mirror::{AUDIO as MIRROR_AUDIO, AUDIO_PLAYBACK as MIRROR_AUDIO_PLAYBACK, CAPTURE as MIRROR_CAPTURE,INPUT as MIRROR_INPUT, LISTEN as MIRROR_LISTEN, MAX_TEXT_BYTES as MIRROR_MAX_TEXT_BYTES,- PCM as MIRROR_PCM, VIEW as MIRROR_VIEW,+ PCM as MIRROR_PCM, SCREEN as MIRROR_SCREEN, VIEW as MIRROR_VIEW,+ 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},diff --git a/core/nectarlink-core/src/mirror.rs b/core/nectarlink-core/src/mirror.rsindex 7f27776..b8065ad 100644--- a/core/nectarlink-core/src/mirror.rs+++ b/core/nectarlink-core/src/mirror.rs@@ -9,6 +9,10 @@//!//! When the PC asks for it and the phone can, the phone's sound comes on a//! second stream (PCM), dropped rather than delayed in the same way.+//!+//! Each mirroring is a session the PC numbers: 0 for the phone's screen,+//! others for apps the phone runs on displays of their own (Elevated), each+//! in a window of its own on the PC.use std::sync::{Arc, Mutex,@@ -18,7 +22,10 @@ use std::sync::{use iroh::endpoint::{RecvStream, SendStream, VarInt};use nectarlink_protocol::{DeviceId, Envelope, ErrorCode, PacketKind,- messages::{MirrorAudioConfig, MirrorConfig, MirrorInput, MirrorStart, StreamHeader, mirror, types},+ messages::{+ MirrorAudioConfig, MirrorConfig, MirrorInput, MirrorSession, MirrorStart, PhoneApp, PhoneApps,+ StreamHeader, mirror, types,+ },read_video_packet, video_packet_header, write_frame,};use tokio::sync::mpsc;@@ -32,6 +39,9 @@ pub(crate) const TOGGLE: &str = "mirroring";const QUEUE: usize = 4;/// Sound packets waiting to go out, at most (each is a few milliseconds).const AUDIO_QUEUE: usize = 24;+/// Icons in a `mirror.apps` answer, at most, in bytes: the rest go without+/// (the answer stays well inside a frame).+const ICONS_BUDGET: usize = 768 * 1024;/// What the PC's app gets of a mirroring stream. Called from the core's/// threads; must return quickly (hand the work to a thread of its own).@@ -62,46 +72,95 @@ pub(crate) async fn start(shared: &Shared, session: &Session, options: MirrorStaif !shared.toggle_on(&session.peer, TOGGLE) {return Err(Error::Denied);}+ if !options.is_valid() {+ return Err(Error::Protocol("invalid mirroring options".into()));+ }let env = Envelope::new(types::MIRROR_START, &options)?;session.request(env, crate::session::REQUEST_TIMEOUT).await?.expect(types::OK)?;Ok(())}-pub(crate) async fn stop(session: &Session) -> Result<()> {- session- .request(Envelope::empty(types::MIRROR_STOP), crate::session::REQUEST_TIMEOUT)- .await?- .expect(types::OK)?;+pub(crate) async fn stop(session: &Session, mirroring: u32) -> Result<()> {+ let env = Envelope::new(types::MIRROR_STOP, &MirrorSession { session: mirroring })?;+ session.request(env, crate::session::REQUEST_TIMEOUT).await?.expect(types::OK)?;Ok(())}-/// Mouse and keyboard on a phone's mirrored screen (not answered: input-/// is only worth it right away).-pub(crate) async fn input(shared: &Shared, session: &Session, input: MirrorInput) -> Result<()> {+/// Mouse and keyboard on a phone's mirrored screen or app window (not+/// answered: input is only worth it right away).+pub(crate) async fn input(+ shared: &Shared,+ session: &Session,+ mirroring: u32,+ input: MirrorInput,+) -> Result<()> {if !shared.toggle_on(&session.peer, TOGGLE) {return Err(Error::Denied);}if !input.is_valid() {return Err(Error::Protocol("invalid input".into()));}- session.send(Envelope::new(types::MIRROR_INPUT, &input)?).await+ session.send(input_envelope(&input, mirroring)?).await+}++fn input_envelope(input: &MirrorInput, mirroring: u32) -> Result<Envelope> {+ Ok(nectarlink_protocol::messages::mirror_input_envelope(input, mirroring)?)}-pub(crate) async fn request_keyframe(session: &Session) {- let _ = session.send(Envelope::empty(types::MIRROR_KEYFRAME)).await;+pub(crate) async fn request_keyframe(session: &Session, mirroring: u32) {+ if let Ok(env) = Envelope::new(types::MIRROR_KEYFRAME, &MirrorSession { session: mirroring }) {+ let _ = session.send(env).await;+ }}-/// A phone opened a video stream (its header already read).+/// The apps a phone can open in windows of their own, by name.+pub(crate) async fn apps(shared: &Shared, session: &Session) -> Result<Vec<PhoneApp>> {+ if !shared.toggle_on(&session.peer, TOGGLE) {+ return Err(Error::Denied);+ }+ let env = Envelope::empty(types::MIRROR_APPS);+ let PhoneApps { mut apps } =+ session.request(env, crate::session::REQUEST_TIMEOUT).await?.expect_body(types::MIRROR_APPS)?;+ apps.retain(|a| nectarlink_protocol::messages::is_package_name(&a.pkg));+ apps.truncate(mirror::MAX_APPS);+ for app in &mut apps {+ app.label = app.label.chars().take(100).collect();+ if app.icon.as_ref().is_some_and(|i| i.len() > mirror::MAX_ICON_BYTES) {+ app.icon = None;+ }+ }+ apps.sort_by_cached_key(|a| a.label.to_lowercase());+ Ok(apps)+}++/// A phone opened a video stream (its header already read). Its first+/// packet says which mirroring it is.pub(crate) async fn receive(shared: Arc<Shared>, peer: DeviceId, mut send: SendStream, mut recv: RecvStream) {- let shows = shared.local_capabilities().iter().any(|c| c == mirror::VIEW);- let sink = shows.then(|| shared.platform.mirror_sink(&peer)).flatten();- let Some(sink) = sink.filter(|_| shared.toggle_on(&peer, TOGGLE)) else {+ let refuse = |mut send: SendStream, mut recv: RecvStream| {let _ = send.reset(VarInt::from_u32(mirror::STOPPED));let _ = recv.stop(VarInt::from_u32(mirror::STOPPED));- return;};- shared.emit(NodeEvent::Mirroring { device: peer, on: true });- let stopped = shared.new_mirror_stop(&peer, mirror::OP_VIDEO);+ let shows = shared.local_capabilities().iter().any(|c| c == mirror::VIEW);+ if !shows || !shared.toggle_on(&peer, TOGGLE) {+ return refuse(send, recv);+ }+ let first = match read_video_packet(&mut recv).await {+ Ok(Some(p)) if p.kind == PacketKind::Config => {+ MirrorConfig::from_cbor(&p.data).ok().filter(|c| c.is_valid())+ }+ _ => None,+ };+ let Some(config) = first else {+ tracing::warn!("a phone sent a video format this PC can't show");+ return refuse(send, recv);+ };+ let mirroring = config.session;+ let Some(sink) = shared.platform.mirror_sink(&peer, mirroring) else {+ return refuse(send, recv);+ };+ shared.emit(NodeEvent::Mirroring { device: peer, session: mirroring, on: true });+ let stopped = shared.new_mirror_stop(&peer, mirroring, mirror::OP_VIDEO);+ sink.config(config);loop {let packet = tokio::select! {_ = stopped.notified() => break,@@ -109,7 +168,7 @@ pub(crate) async fn receive(shared: Arc<Shared>, peer: DeviceId, mut send: SendS};match packet {Ok(Some(p)) if p.kind == PacketKind::Config => match MirrorConfig::from_cbor(&p.data) {- Ok(config) if config.is_valid() => sink.config(config),+ Ok(config) if config.is_valid() && config.session == mirroring => sink.config(config),_ => {tracing::warn!("a phone sent a video format this PC can't show");break;@@ -126,7 +185,7 @@ pub(crate) async fn receive(shared: Arc<Shared>, peer: DeviceId, mut send: SendSlet _ = recv.stop(VarInt::from_u32(mirror::STOPPED));let _ = send.finish();sink.ended();- shared.emit(NodeEvent::Mirroring { device: peer, on: false });+ shared.emit(NodeEvent::Mirroring { device: peer, session: mirroring, on: false });}/// A phone opened a sound stream (its header already read).@@ -136,14 +195,15 @@ pub(crate) async fn receive_audio(mut send: SendStream,mut recv: RecvStream,) {+ // Sound comes with the screen only.let listens = shared.local_capabilities().iter().any(|c| c == mirror::LISTEN);- let sink = listens.then(|| shared.platform.mirror_sink(&peer)).flatten();+ let sink = listens.then(|| shared.platform.mirror_sink(&peer, mirror::SCREEN)).flatten();let Some(sink) = sink.filter(|_| shared.toggle_on(&peer, TOGGLE)) else {let _ = send.reset(VarInt::from_u32(mirror::STOPPED));let _ = recv.stop(VarInt::from_u32(mirror::STOPPED));return;};- let stopped = shared.new_mirror_stop(&peer, mirror::OP_AUDIO);+ let stopped = shared.new_mirror_stop(&peer, mirror::SCREEN, mirror::OP_AUDIO);loop {let packet = tokio::select! {_ = stopped.notified() => break,@@ -179,10 +239,13 @@ pub(crate) async fn handle(shared: &Arc<Shared>, session: &Arc<Session>, env: &Ematch env.t.as_str() {types::MIRROR_START => {let options: MirrorStart = env.body()?;+ let needs = if options.app.is_some() { mirror::VIRTUAL_DISPLAY } else { mirror::CAPTURE };let reply = if !shared.toggle_on(&peer, TOGGLE) {Envelope::error(ErrorCode::Denied, "mirroring is off for this device")- } else if !shared.local_capabilities().iter().any(|c| c == mirror::CAPTURE) {- Envelope::error(ErrorCode::Unsupported, "this device doesn't share its screen")+ } else if !options.is_valid() {+ Envelope::error(ErrorCode::BadMessage, "invalid mirroring options")+ } else if !shared.local_capabilities().iter().any(|c| c == needs) {+ Envelope::error(ErrorCode::Unsupported, "this device doesn't share that")} else {match tokio::task::spawn_blocking(move || platform.mirror_requested(&peer, &options)).await@@ -198,27 +261,67 @@ pub(crate) async fn handle(shared: &Arc<Shared>, session: &Arc<Session>, env: &Esession.send(reply.reply_to(env.id)).await?;}types::MIRROR_STOP => {+ let MirrorSession { session: mirroring } = env.body()?;// The PC's side: stop showing; the phone's: stop sharing.- shared.stop_showing(&peer);- tokio::task::spawn_blocking(move || platform.mirror_stop_requested(&peer));+ shared.stop_showing(&peer, mirroring);+ tokio::task::spawn_blocking(move || platform.mirror_stop_requested(&peer, mirroring));session.send(Envelope::empty(types::OK).reply_to(env.id)).await?;}types::MIRROR_KEYFRAME => {- tokio::task::spawn_blocking(move || platform.mirror_keyframe_requested(&peer));+ let MirrorSession { session: mirroring } = env.body()?;+ tokio::task::spawn_blocking(move || platform.mirror_keyframe_requested(&peer, mirroring));}types::MIRROR_INPUT => {let input: MirrorInput = env.body()?;- let allowed = shared.toggle_on(&peer, TOGGLE)- && shared.local_capabilities().iter().any(|c| c == mirror::INPUT);+ let MirrorSession { session: mirroring } = env.body()?;+ // App windows take input as they're Elevated; the screen, with mirror.input.+ let needs = if mirroring == mirror::SCREEN { mirror::INPUT } else { mirror::VIRTUAL_DISPLAY };+ let allowed =+ shared.toggle_on(&peer, TOGGLE) && shared.local_capabilities().iter().any(|c| c == needs);if allowed && input.is_valid() {- platform.mirror_input(&peer, input);+ platform.mirror_input(&peer, mirroring, input);}}+ types::MIRROR_APPS => {+ let reply = if !shared.toggle_on(&peer, TOGGLE) {+ Envelope::error(ErrorCode::Denied, "mirroring is off for this device")+ } else if !shared.local_capabilities().iter().any(|c| c == mirror::VIRTUAL_DISPLAY) {+ Envelope::error(ErrorCode::Unsupported, "this device doesn't open apps in windows")+ } else {+ match tokio::task::spawn_blocking(move || platform.phone_apps())+ .await+ .unwrap_or_else(|e| Err(e.to_string()))+ {+ Ok(apps) => Envelope::new(types::MIRROR_APPS, &PhoneApps { apps: fit_apps(apps) })?,+ Err(reason) => {+ tracing::warn!(reason, "can't list the apps");+ Envelope::error(ErrorCode::Internal, "the phone couldn't list its apps")+ }+ }+ };+ session.send(reply.reply_to(env.id)).await?;+ }_ => return Ok(false),}Ok(true)}+/// Apps within the limits: at most [`mirror::MAX_APPS`], icons small and+/// within [`ICONS_BUDGET`] all together.+fn fit_apps(mut apps: Vec<PhoneApp>) -> Vec<PhoneApp> {+ apps.retain(|a| nectarlink_protocol::messages::is_package_name(&a.pkg));+ apps.truncate(mirror::MAX_APPS);+ let mut budget = ICONS_BUDGET;+ for app in &mut apps {+ app.label = app.label.chars().take(100).collect();+ match app.icon.as_ref().map(Vec::len) {+ Some(len) if len <= mirror::MAX_ICON_BYTES && len <= budget => budget -= len,+ _ => app.icon = None,+ }+ }+ apps+}+/// What became of a packet handed to [`MirrorStream::send`].#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub enum MirrorSend {@@ -336,19 +439,22 @@ pub(crate) async fn open(shared: &Arc<Shared>, session: &Session, audio: bool) -impl Shared {/// A new stop signal for the PC's reader of `peer`'s video or sound- /// stream (`op`).- fn new_mirror_stop(&self, peer: &DeviceId, op: &'static str) -> Arc<tokio::sync::Notify> {+ /// stream (`op`) of a mirroring.+ fn new_mirror_stop(&self, peer: &DeviceId, mirroring: u32, op: &'static str) -> Arc<tokio::sync::Notify> {let signal = Arc::new(tokio::sync::Notify::new());- self.mirror_stops.lock().unwrap_or_else(|e| e.into_inner()).insert((*peer, op), signal.clone());+ self.mirror_stops+ .lock()+ .unwrap_or_else(|e| e.into_inner())+ .insert((*peer, mirroring, op), signal.clone());signal}- /// Stops showing (and playing) `peer`'s screen here (kept until the- /// readers see it).- pub(crate) fn stop_showing(&self, peer: &DeviceId) {+ /// Stops showing (and playing) a mirroring of `peer` here (kept until+ /// the readers see it).+ pub(crate) fn stop_showing(&self, peer: &DeviceId, mirroring: u32) {let mut stops = self.mirror_stops.lock().unwrap_or_else(|e| e.into_inner());for op in [mirror::OP_VIDEO, mirror::OP_AUDIO] {- if let Some(signal) = stops.remove(&(*peer, op)) {+ if let Some(signal) = stops.remove(&(*peer, mirroring, op)) {signal.notify_one();}}diff --git a/core/nectarlink-core/src/node.rs b/core/nectarlink-core/src/node.rsindex b3288a9..6f1f993 100644--- a/core/nectarlink-core/src/node.rs+++ b/core/nectarlink-core/src/node.rs@@ -93,6 +93,9 @@ struct Supervisor {cancel: CancellationToken,}+/// A PC's reader of a phone's mirroring: the phone, the session, video or sound.+pub(crate) type MirrorStop = (DeviceId, u32, &'static str);+/// State shared by the node, its sessions and background tasks.pub(crate) struct Shared {pub id: DeviceId,@@ -120,7 +123,7 @@ pub(crate) struct Shared {/// 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.- pub(crate) mirror_stops: Mutex<HashMap<(DeviceId, &'static str), Arc<tokio::sync::Notify>>>,+ pub(crate) mirror_stops: Mutex<HashMap<MirrorStop, Arc<tokio::sync::Notify>>>,pub data_dir: std::path::PathBuf,/// Where received files go.pub downloads_dir: std::path::PathBuf,@@ -933,25 +936,37 @@ impl Node {crate::mirror::start(&self.shared, &session, options).await}- /// Stops showing a phone's screen, and tells the phone.- pub async fn mirror_stop(&self, peer: DeviceId) {- self.shared.stop_showing(&peer);+ /// Stops showing a phone's screen or app window (`mirroring`), and+ /// tells the phone.+ pub async fn mirror_stop(&self, peer: DeviceId, mirroring: u32) {+ self.shared.stop_showing(&peer, mirroring);if let Ok(session) = self.connected(&peer) {- let _ = crate::mirror::stop(&session).await;+ let _ = crate::mirror::stop(&session, mirroring).await;}}/// Asks a phone for a keyframe (the decoder lost its place).- pub async fn mirror_keyframe(&self, peer: DeviceId) {+ pub async fn mirror_keyframe(&self, peer: DeviceId, mirroring: u32) {if let Ok(session) = self.connected(&peer) {- crate::mirror::request_keyframe(&session).await;+ crate::mirror::request_keyframe(&session, mirroring).await;}}- /// The PC's mouse and keyboard on a phone's mirrored screen.- pub async fn mirror_input(&self, peer: DeviceId, input: crate::MirrorInput) -> Result<()> {+ /// The PC's mouse and keyboard on a phone's mirrored screen or app window.+ pub async fn mirror_input(+ &self,+ peer: DeviceId,+ mirroring: u32,+ input: crate::MirrorInput,+ ) -> Result<()> {+ let session = self.connected(&peer)?;+ crate::mirror::input(&self.shared, &session, mirroring, input).await+ }++ /// The apps a phone can open in windows of their own (Elevated), by name.+ pub async fn mirror_apps(&self, peer: DeviceId) -> Result<Vec<crate::PhoneApp>> {let session = self.connected(&peer)?;- crate::mirror::input(&self.shared, &session, input).await+ crate::mirror::apps(&self.shared, &session).await}/// Opens this phone's video stream to a PC that asked for the screen.diff --git a/core/nectarlink-core/tests/two_devices.rs b/core/nectarlink-core/tests/two_devices.rsindex a07f33f..f8f306b 100644--- a/core/nectarlink-core/tests/two_devices.rs+++ b/core/nectarlink-core/tests/two_devices.rs@@ -78,7 +78,12 @@ impl Platform for RecordingPlatform {self.links.lock().unwrap().push(url.to_owned());Ok(())}- fn mirror_sink(&self, _peer: &nectarlink_core::DeviceId) -> Option<Arc<dyn nectarlink_core::MirrorSink>> {+ fn mirror_sink(+ &self,+ _peer: &nectarlink_core::DeviceId,+ session: u32,+ ) -> Option<Arc<dyn nectarlink_core::MirrorSink>> {+ self.mirror_asks.lock().unwrap().push(format!("sink {session}"));Some(self.screen.clone())}fn mirror_requested(@@ -87,17 +92,38 @@ impl Platform for RecordingPlatform {options: &nectarlink_core::MirrorStart,) -> Result<(), String> {let sound = if options.audio { " with sound" } else { "" };- self.mirror_asks.lock().unwrap().push(format!("start {}{sound}", options.max_size));+ let app = options.app.as_deref().map(|a| format!(" {a} as {}", options.session)).unwrap_or_default();+ self.mirror_asks.lock().unwrap().push(format!("start {}{sound}{app}", options.max_size));Ok(())}- fn mirror_stop_requested(&self, _peer: &nectarlink_core::DeviceId) {- self.mirror_asks.lock().unwrap().push("stop".into());+ fn mirror_stop_requested(&self, _peer: &nectarlink_core::DeviceId, session: u32) {+ self.mirror_asks.lock().unwrap().push(format!("stop {session}"));+ }+ fn mirror_keyframe_requested(&self, _peer: &nectarlink_core::DeviceId, session: u32) {+ self.mirror_asks.lock().unwrap().push(format!("keyframe {session}"));}- fn mirror_keyframe_requested(&self, _peer: &nectarlink_core::DeviceId) {- self.mirror_asks.lock().unwrap().push("keyframe".into());+ fn mirror_input(+ &self,+ _peer: &nectarlink_core::DeviceId,+ session: u32,+ input: nectarlink_core::MirrorInput,+ ) {+ self.mirror_asks.lock().unwrap().push(format!("{input:?} on {session}"));}- fn mirror_input(&self, _peer: &nectarlink_core::DeviceId, input: nectarlink_core::MirrorInput) {- self.mirror_asks.lock().unwrap().push(format!("{input:?}"));+ fn phone_apps(&self) -> Result<Vec<nectarlink_core::PhoneApp>, String> {+ let app = |pkg: &str, label: &str, icon: usize| nectarlink_core::PhoneApp {+ pkg: pkg.into(),+ label: label.into(),+ icon: Some(vec![1; icon]),+ };+ Ok(vec![+ app("com.example.notes", "notes", 100),+ app("com.example.chat", "Chat", 100),+ // Not a package name: never offered.+ app("not a package", "Bad", 10),+ // Too big an icon: shown without.+ app("com.example.maps", "Maps", 9 * 1024),+ ])}fn sms_threads(&self, limit: u32) -> Result<Vec<nectarlink_core::SmsThread>, String> {let thread = |i: u32| nectarlink_core::SmsThread {@@ -1063,13 +1089,21 @@ async fn the_phone_screen_streams_to_the_pc() {pair_qr(&mut pc, &mut phone).await;let (pc_id, phone_id) = (pc.node.device_id(), phone.node.device_id());- let options = nectarlink_core::MirrorStart { max_size: 1920, fps: 60, bitrate: 8_000_000, audio: true };+ let options = nectarlink_core::MirrorStart {+ max_size: 1920,+ fps: 60,+ bitrate: 8_000_000,+ audio: true,+ session: 0,+ app: None,+ };with_timeout("start", pc.node.mirror_start(phone_id, options)).await.unwrap();assert_eq!(*phone.platform.mirror_asks.lock().unwrap(), ["start 1920 with sound"]);// The user agreed: the phone streams.let stream = Arc::new(with_timeout("open", phone.node.mirror_open(pc_id)).await.unwrap());- let config = nectarlink_core::MirrorConfig { codec: "h264".into(), width: 1080, height: 2400 };+ let config =+ nectarlink_core::MirrorConfig { codec: "h264".into(), width: 1080, height: 2400, session: 0 };let sender = stream.clone();let sent = tokio::task::spawn_blocking(move || {[@@ -1112,17 +1146,17 @@ async fn the_phone_screen_streams_to_the_pc() {}assert_eq!(screen.got.lock().unwrap()[3..], ["sound 48000 Hz x2", "sound 10000 1920"]);- pc.node.mirror_keyframe(phone_id).await;+ pc.node.mirror_keyframe(phone_id, 0).await;// The PC's mouse on the phone's screen; nonsense never leaves the PC.use nectarlink_core::{MirrorInput, TouchAction};pc.node- .mirror_input(phone_id, MirrorInput::Touch { action: TouchAction::Down, x: 0.5, y: 0.25 })+ .mirror_input(phone_id, 0, MirrorInput::Touch { action: TouchAction::Down, x: 0.5, y: 0.25 }).await.unwrap();- pc.node.mirror_input(phone_id, MirrorInput::Key { key: "back".into() }).await.unwrap();- assert!(pc.node.mirror_input(phone_id, MirrorInput::Key { key: "power".into() }).await.is_err());+ pc.node.mirror_input(phone_id, 0, MirrorInput::Key { key: "back".into() }).await.unwrap();+ assert!(pc.node.mirror_input(phone_id, 0, MirrorInput::Key { key: "power".into() }).await.is_err());// The PC stops watching: the phone hears it, and its stream closes.- pc.node.mirror_stop(phone_id).await;+ pc.node.mirror_stop(phone_id, 0).await;wait_for(&mut pc, "stopped", |e| matches!(e, NodeEvent::Mirroring { on: false, .. }).then_some(())).await;let deadline = tokio::time::Instant::now() + WAIT;while !screen.got.lock().unwrap().iter().any(|g| g == "sound ended")@@ -1147,9 +1181,87 @@ async fn the_phone_screen_streams_to_the_pc() {}assert!(sound.is_closed(), "and its sound stream");let asks = phone.platform.mirror_asks.lock().unwrap().clone();- for wanted in ["keyframe", "Touch(Down)", "Key(back)", "stop"] {+ for wanted in ["keyframe 0", "Touch(Down) on 0", "Key(back) on 0", "stop 0"] {+ assert!(asks.iter().any(|a| a == wanted), "{wanted}: {asks:?}");+ }+ let shown = pc.platform.mirror_asks.lock().unwrap().clone();+ assert_eq!(shown, ["sink 0", "sink 0"], "the screen and its sound");+}++#[tokio::test(flavor = "multi_thread")]+async fn phone_apps_open_in_windows_of_their_own() {+ use nectarlink_core::{MirrorInput, MirrorSend, PacketKind};+ let mut pc = device_with("Desktop", DeviceKind::Desktop, &[nectarlink_core::MIRROR_VIEW]).await;+ let mut phone = device_with("Pixel", DeviceKind::Phone, &[nectarlink_core::MIRROR_CAPTURE]).await;+ pair_qr(&mut pc, &mut phone).await;+ let (pc_id, phone_id) = (pc.node.device_id(), phone.node.device_id());+ let app = |session: u32| nectarlink_core::MirrorStart {+ max_size: 1280,+ fps: 30,+ bitrate: 4_000_000,+ audio: false,+ session,+ app: Some("com.example.chat".into()),+ };++ // Not Elevated yet: no apps, no app windows.+ assert!(pc.node.mirror_apps(phone_id).await.is_err());+ assert!(pc.node.mirror_start(phone_id, app(7)).await.is_err());+ phone+ .node+ .update_power(+ PowerLevel::Elevated,+ vec![nectarlink_core::MIRROR_CAPTURE.into(), nectarlink_core::MIRROR_VIRTUAL_DISPLAY.into()],+ )+ .await;+ let deadline = tokio::time::Instant::now() + WAIT;+ let apps = loop {+ match pc.node.mirror_apps(phone_id).await {+ Ok(apps) => break apps,+ Err(_) if tokio::time::Instant::now() < deadline => {+ tokio::time::sleep(std::time::Duration::from_millis(50)).await+ }+ Err(e) => panic!("no apps: {e}"),+ }+ };+ let listed: Vec<_> = apps.iter().map(|a| (a.label.as_str(), a.icon.is_some())).collect();+ assert_eq!(listed, [("Chat", true), ("Maps", false), ("notes", true)], "by name; big icons left out");++ // An app window is a session of its own; the screen's (0) can't have an app.+ assert!(pc.node.mirror_start(phone_id, app(0)).await.is_err());+ with_timeout("start", pc.node.mirror_start(phone_id, app(7))).await.unwrap();+ let stream = Arc::new(with_timeout("open", phone.node.mirror_open(pc_id)).await.unwrap());+ let config = nectarlink_core::MirrorConfig { codec: "h264".into(), width: 720, height: 1280, session: 7 };+ let sender = stream.clone();+ let sent = tokio::task::spawn_blocking(move || {+ [+ sender.send(PacketKind::Config, 0, config.to_cbor()),+ sender.send(PacketKind::Keyframe, 1, vec![0; 10]),+ ]+ })+ .await+ .unwrap();+ assert!(sent.iter().all(|s| *s == MirrorSend::Queued), "{sent:?}");+ let session = wait_for(&mut pc, "showing", |e| match e {+ NodeEvent::Mirroring { session, on: true, .. } => Some(*session),+ _ => None,+ })+ .await;+ assert_eq!(session, 7);+ pc.node.mirror_input(phone_id, 7, MirrorInput::Key { key: "back".into() }).await.unwrap();+ pc.node.mirror_keyframe(phone_id, 7).await;+ pc.node.mirror_stop(phone_id, 7).await;+ let ended = wait_for(&mut pc, "stopped", |e| match e {+ NodeEvent::Mirroring { session, on: false, .. } => Some(*session),+ _ => None,+ })+ .await;+ assert_eq!(ended, 7);+ let asks = phone.platform.mirror_asks.lock().unwrap().clone();+ for wanted in ["start 1280 com.example.chat as 7", "Key(back) on 7", "keyframe 7", "stop 7"] {assert!(asks.iter().any(|a| a == wanted), "{wanted}: {asks:?}");}+ assert_eq!(*pc.platform.mirror_asks.lock().unwrap(), ["sink 7"]);}#[tokio::test(flavor = "multi_thread")]diff --git a/core/nectarlink-ffi/src/lib.rs b/core/nectarlink-ffi/src/lib.rsindex 3a65595..db136a3 100644--- a/core/nectarlink-ffi/src/lib.rs+++ b/core/nectarlink-ffi/src/lib.rs@@ -434,9 +434,11 @@ pub enum Event {id: String,call_id: String,},- /// A paired phone's screen started or stopped showing (PCs only).+ /// A paired phone's screen (session 0) or app window started or+ /// stopped showing (PCs only).Mirroring {id: String,+ session: u32,on: bool,},/// A paired phone's messages changed (PCs only).@@ -559,10 +561,42 @@ impl MirrorStream {}}-/// The bytes of a config packet for an H.264 stream of this size.+/// The bytes of a config packet for an H.264 stream of this size, for the+/// screen (session 0) or an app window.#[uniffi::export]-pub fn mirror_config(width: u32, height: u32) -> Vec<u8> {- core::MirrorConfig { codec: "h264".into(), width, height }.to_cbor()+pub fn mirror_config(width: u32, height: u32, session: u32) -> Vec<u8> {+ core::MirrorConfig { codec: "h264".into(), width, height, session }.to_cbor()+}++/// What a PC asked to mirror, and how (docs/protocol/mirror.md).+#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)]+pub struct MirrorOptions {+ /// The longer side, in pixels, at most.+ pub max_size: u32,+ pub fps: u32,+ pub bitrate: u32,+ /// The sound too (the screen only).+ pub audio: bool,+ /// 0 for the screen; another for an app window.+ pub session: u32,+ /// The app (package name) to show in a window of its own.+ pub app: Option<String>,+}++/// An app a PC can open in a window (docs/protocol/mirror.md).+#[derive(Clone, PartialEq, Eq, uniffi::Record)]+pub struct PhoneApp {+ /// Package name.+ pub pkg: String,+ pub label: String,+ /// A small PNG icon (at most 8 KiB).+ pub icon: Option<Vec<u8>>,+}++impl std::fmt::Debug for PhoneApp {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ f.debug_struct("PhoneApp").field("pkg", &self.pkg).finish_non_exhaustive()+ }}/// The bytes of a config packet for 16-bit PCM sound.@@ -1097,7 +1131,9 @@ impl From<NodeEvent> for Event {Event::CallChanged { id: device.to_string(), call_id: call.id }}NodeEvent::SmsChanged { device, thread } => Event::SmsChanged { id: device.to_string(), thread },- NodeEvent::Mirroring { device, on } => Event::Mirroring { id: device.to_string(), on },+ NodeEvent::Mirroring { device, session, on } => {+ Event::Mirroring { id: device.to_string(), session, on }+ }}}}@@ -1209,15 +1245,19 @@ pub trait Platform: Send + Sync {fn call_command(&self, id: String, command: CallCommand) -> bool;/// A PC asked for this phone's screen (and, with `audio`, its sound):/// ask the user (then call `mirror_open`, and `mirror_open_audio` for- /// the sound). False if the user couldn't be asked.- fn mirror_requested(&self, pc_id: String, max_size: u32, fps: u32, bitrate: u32, audio: bool) -> bool;- /// The PC stopped watching: stop sharing.- fn mirror_stop_requested(&self, pc_id: String);+ /// the sound). With `app` (and a `session` other than 0): run that app+ /// on a display of its own and stream it with `mirror_open`, its config+ /// packets carrying the session. False if it can't.+ fn mirror_requested(&self, pc_id: String, options: MirrorOptions) -> bool;+ /// The PC stopped watching the screen (session 0) or an app window.+ fn mirror_stop_requested(&self, pc_id: String, session: u32);/// The PC needs a keyframe.- fn mirror_keyframe_requested(&self, pc_id: String);+ fn mirror_keyframe_requested(&self, pc_id: String, session: u32);/// The PC's mouse or keyboard on the mirrored screen (only while this- /// phone offers `mirror.input`). Return quickly.- fn mirror_input(&self, pc_id: String, input: MirrorInputEvent);+ /// phone offers `mirror.input`) or an app window. Return quickly.+ fn mirror_input(&self, pc_id: String, session: u32, input: MirrorInputEvent);+ /// A PC asked for the apps it may open in windows (launchable ones).+ fn phone_apps(&self) -> Vec<PhoneApp>;/// A PC asked for the latest conversations, newest first.fn sms_threads(&self, limit: u32) -> Vec<SmsThread>;/// A PC asked for a conversation's messages before `before` (Unix ms;@@ -1291,26 +1331,36 @@ impl core::Platform for PlatformAdapter {}}fn mirror_requested(&self, peer: &DeviceId, options: &core::MirrorStart) -> Result<(), String> {- if self.0.mirror_requested(- peer.to_string(),- options.max_size,- options.fps,- options.bitrate,- options.audio,- ) {+ let options = MirrorOptions {+ max_size: options.max_size,+ fps: options.fps,+ bitrate: options.bitrate,+ audio: options.audio,+ session: options.session,+ app: options.app.clone(),+ };+ if self.0.mirror_requested(peer.to_string(), options) {Ok(())} else {- Err("the user couldn't be asked".into())+ Err("the phone couldn't".into())}}- fn mirror_stop_requested(&self, peer: &DeviceId) {- self.0.mirror_stop_requested(peer.to_string());+ fn mirror_stop_requested(&self, peer: &DeviceId, session: u32) {+ self.0.mirror_stop_requested(peer.to_string(), session);+ }+ fn mirror_keyframe_requested(&self, peer: &DeviceId, session: u32) {+ self.0.mirror_keyframe_requested(peer.to_string(), session);}- fn mirror_keyframe_requested(&self, peer: &DeviceId) {- self.0.mirror_keyframe_requested(peer.to_string());+ fn mirror_input(&self, peer: &DeviceId, session: u32, input: core::MirrorInput) {+ self.0.mirror_input(peer.to_string(), session, input.into());}- fn mirror_input(&self, peer: &DeviceId, input: core::MirrorInput) {- self.0.mirror_input(peer.to_string(), input.into());+ fn phone_apps(&self) -> Result<Vec<core::PhoneApp>, String> {+ Ok(self+ .0+ .phone_apps()+ .into_iter()+ .map(|a| core::PhoneApp { pkg: a.pkg, label: a.label, icon: a.icon })+ .collect())}fn sms_threads(&self, limit: u32) -> Result<Vec<core::SmsThread>, String> {Ok(selfdiff --git a/core/nectarlink-protocol/src/messages.rs b/core/nectarlink-protocol/src/messages.rsindex 476a35a..3552f95 100644--- a/core/nectarlink-protocol/src/messages.rs+++ b/core/nectarlink-protocol/src/messages.rs@@ -54,6 +54,7 @@ pub mod types {pub const MIRROR_STOP: &str = "mirror.stop";pub const MIRROR_KEYFRAME: &str = "mirror.keyframe";pub const MIRROR_INPUT: &str = "mirror.input";+ pub const MIRROR_APPS: &str = "mirror.apps";}/// What kind of device this is.@@ -493,6 +494,26 @@ pub mod mirror {pub const OP_AUDIO: &str = "audio";/// 16-bit little-endian PCM, channels interleaved.pub const PCM: &str = "pcm_s16le";+ /// Offered by phones that run an app on a display of its own, shown in+ /// a window of its own (Elevated).+ pub const VIRTUAL_DISPLAY: &str = "mirror.virtual_display";+ /// The session of the phone's own screen; app windows have others.+ pub const SCREEN: u32 = 0;+ /// Apps in a `mirror.apps` answer, at most.+ pub const MAX_APPS: usize = 500;+ /// An app's icon (PNG), at most.+ pub const MAX_ICON_BYTES: usize = 8 * 1024;+}++/// Whether `name` looks like an Android package name.+pub fn is_package_name(name: &str) -> bool {+ !name.is_empty()+ && name.len() <= 255+ && name.split('.').count() >= 2+ && name.split('.').all(|part| {+ part.chars().next().is_some_and(|c| c.is_ascii_alphabetic())+ && part.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')+ })}/// Body of `mirror.start`: show me your screen.@@ -507,6 +528,58 @@ pub struct MirrorStart {/// Also stream the phone's sound, when it can.#[serde(default)]pub audio: bool,+ /// The PC's number for this mirroring: [`mirror::SCREEN`] for the+ /// phone's screen, any other for an app window.+ #[serde(default)]+ pub session: u32,+ /// An app (package name) to run on a display of its own and show,+ /// instead of the phone's screen (with a session other than SCREEN).+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub app: Option<String>,+}++impl MirrorStart {+ /// The screen without an app, or an app with a session of its own.+ pub fn is_valid(&self) -> bool {+ match &self.app {+ None => self.session == mirror::SCREEN,+ Some(app) => self.session != mirror::SCREEN && is_package_name(app),+ }+ }+}++/// Which mirroring a `mirror.stop`, `mirror.keyframe` or `mirror.input` is+/// about (its body, or part of it; missing means the screen).+#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]+pub struct MirrorSession {+ #[serde(default)]+ pub session: u32,+}++/// An app a PC can open in a window (in a `mirror.apps` answer).+#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]+pub struct PhoneApp {+ /// Package name.+ pub pkg: String,+ pub label: String,+ /// A small icon (PNG), at most [`mirror::MAX_ICON_BYTES`].+ #[serde(default, skip_serializing_if = "Option::is_none", with = "serde_bytes")]+ pub icon: Option<Vec<u8>>,+}++impl std::fmt::Debug for PhoneApp {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ f.debug_struct("PhoneApp")+ .field("pkg", &self.pkg)+ .field("icon", &self.icon.as_ref().map(Vec::len))+ .finish_non_exhaustive()+ }+}++/// Body of a `mirror.apps` answer: the phone's apps, by name.+#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]+pub struct PhoneApps {+ pub apps: Vec<PhoneApp>,}/// Body of `mirror.input`: the PC's mouse and keyboard, on the mirrored@@ -552,6 +625,21 @@ pub mod mirror_keys {&[BACK, HOME, RECENTS, ENTER, BACKSPACE, DELETE, LEFT, RIGHT, UP, DOWN, TAB, NOTIFICATIONS];}+/// `mirror.input`: the input's fields, and the session when it isn't the+/// screen (phones that predate sessions ignore it).+pub fn mirror_input_envelope(+ input: &MirrorInput,+ session: u32,+) -> Result<crate::Envelope, crate::ProtocolError> {+ let mut env = crate::Envelope::new(types::MIRROR_INPUT, input)?;+ if session != mirror::SCREEN+ && let Some(ciborium::Value::Map(fields)) = env.b.as_mut()+ {+ fields.push((ciborium::Value::Text("session".into()), ciborium::Value::Integer(session.into())));+ }+ Ok(env)+}+/// Never prints typed text (protocol v0 §11).impl std::fmt::Debug for MirrorInput {fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {@@ -590,6 +678,9 @@ pub struct MirrorConfig {pub codec: String,pub width: u32,pub height: u32,+ /// Which mirroring this stream is (see [`MirrorStart::session`]).+ #[serde(default)]+ pub session: u32,}impl MirrorConfig {diff --git a/desktop/app/build.rs b/desktop/app/build.rsindex 2feebb8..929e47e 100644--- a/desktop/app/build.rs+++ b/desktop/app/build.rs@@ -19,6 +19,7 @@ const QML: &[&str] = &["qml/App.qml","qml/MainWindow.qml","qml/MirrorWindow.qml",+ "qml/components/AppsSheet.qml","qml/components/Avatar.qml","qml/components/Button.qml","qml/components/CallCard.qml",diff --git a/desktop/app/qml/App.qml b/desktop/app/qml/App.qmlindex 5bad199..b0cce7e 100644--- a/desktop/app/qml/App.qml+++ b/desktop/app/qml/App.qml@@ -1,5 +1,7 @@// SPDX-License-Identifier: GPL-3.0-or-laterimport QtQuick+import QtQml+import QtQml.Modelsimport app.nectarlink// Application root. The main window exists only while it's open: closing it@@ -9,8 +11,39 @@ QtObject {id: appproperty MainWindow mainWindow: null- // A phone's screen; shows itself while mirroring.- readonly property MirrorWindow mirrorWindow: MirrorWindow {}+ // A window for each phone screen or app being mirrored. The model+ // keeps a row per window (by key), so a window lives as long as its+ // mirroring, whatever else changes.+ readonly property ListModel mirrorWindows: ListModel {}+ readonly property Instantiator mirrorInstantiator: Instantiator {+ model: app.mirrorWindows+ delegate: MirrorWindow {+ required property string key+ mirrorKey: key+ }+ }+ readonly property Connections mirrorSync: Connections {+ target: Mirror+ function onWindowsChanged() { app.syncMirrorWindows() }+ }++ function syncMirrorWindows() {+ let keys = []+ try {+ keys = JSON.parse(Mirror.windows).map(w => w.key)+ } catch (e) {}+ for (let i = mirrorWindows.count - 1; i >= 0; i--) {+ if (keys.indexOf(mirrorWindows.get(i).key) < 0)+ mirrorWindows.remove(i)+ }+ for (const key of keys) {+ let known = false+ for (let i = 0; i < mirrorWindows.count; i++)+ known = known || mirrorWindows.get(i).key === key+ if (!known)+ mirrorWindows.append({ key: key })+ }+ }readonly property Component mainComponent: Component { MainWindow {} }readonly property bool startMinimized: Qt.application.arguments.indexOf("--minimized") >= 0|| Qt.application.arguments.indexOf("--send-to") >= 0diff --git a/desktop/app/qml/MirrorWindow.qml b/desktop/app/qml/MirrorWindow.qmlindex e9b4af6..1fc5742 100644--- a/desktop/app/qml/MirrorWindow.qml+++ b/desktop/app/qml/MirrorWindow.qml@@ -3,13 +3,26 @@ import QtQuickimport QtQuick.Windowimport app.nectarlink-// A phone's screen in a window of its own, sized like the phone.+// A phone's screen, or one of its apps, in a window of its own, sized like+// the phone. One per mirroring (`mirrorKey`); closing it ends that one.Window {id: win- readonly property string deviceName: Mirror.name+ required property string mirrorKey+ // This window's mirroring (see Mirror.windows).+ readonly property var info: {+ try {+ return JSON.parse(Mirror.windows).find(w => w.key === mirrorKey) || ({})+ } catch (e) {+ return ({})+ }+ }+ readonly property string deviceName: info.name || ""+ readonly property string phase: info.phase || ""+ readonly property bool canControl: info.canControl === true- visible: Mirror.phase.length > 0- title: deviceName.length > 0 ? qsTr("%1 · Nectarlink").arg(deviceName) : qsTr("Phone screen · Nectarlink")+ visible: true+ title: info.app ? qsTr("%1 · %2").arg(info.title).arg(deviceName)+ : deviceName.length > 0 ? qsTr("%1 · Nectarlink").arg(deviceName) : qsTr("Phone screen · Nectarlink")color: "black"minimumWidth: 240minimumHeight: 240@@ -30,19 +43,14 @@ Window {sized = true}}- onVisibleChanged: {- if (visible) {- sized = false- width = 420- height = 860- }- }- onClosing: Mirror.stop()+ width: 420+ height: 860+ onClosing: Mirror.stop(mirrorKey)VideoView {id: videoanchors.fill: parent- stream: Mirror.device+ stream: win.mirrorKeyfocus: true// Where on the phone's screen a point in the window is (0 to 1).@@ -55,7 +63,7 @@ Window {// The mouse: left is a finger, right is Back, middle is Home.MouseArea {anchors.fill: parent- enabled: Mirror.canControl && Mirror.phase === "showing"+ enabled: win.canControl && win.phase === "showing"acceptedButtons: Qt.LeftButton | Qt.RightButton | Qt.MiddleButtoncursorShape: enabled ? Qt.PointingHandCursor : Qt.ArrowCursorproperty bool down: false@@ -63,11 +71,11 @@ Window {onPressed: (mouse) => {video.forceActiveFocus()const p = video.at(mouse.x, mouse.y)- if (mouse.button === Qt.RightButton) { Mirror.key("back"); return }- if (mouse.button === Qt.MiddleButton) { Mirror.key("home"); return }+ if (mouse.button === Qt.RightButton) { Mirror.press(win.mirrorKey, "back"); return }+ if (mouse.button === Qt.MiddleButton) { Mirror.press(win.mirrorKey, "home"); return }if (!p.inside) returndown = true- Mirror.touch("down", p.x, p.y)+ Mirror.touch(win.mirrorKey, "down", p.x, p.y)}onPositionChanged: (mouse) => {if (!down) return@@ -76,25 +84,25 @@ Window {if (now - lastMove < 16) returnlastMove = nowconst p = video.at(mouse.x, mouse.y)- Mirror.touch("move", p.x, p.y)+ Mirror.touch(win.mirrorKey, "move", p.x, p.y)}onReleased: (mouse) => {if (!down) returndown = falseconst p = video.at(mouse.x, mouse.y)- Mirror.touch("up", p.x, p.y)+ Mirror.touch(win.mirrorKey, "up", p.x, p.y)}onWheel: (wheel) => {const p = video.at(wheel.x, wheel.y)if (p.inside)- Mirror.scroll(p.x, p.y, -wheel.angleDelta.x / 120, -wheel.angleDelta.y / 120)+ Mirror.scroll(win.mirrorKey, p.x, p.y, -wheel.angleDelta.x / 120, -wheel.angleDelta.y / 120)}}// The keyboard: text goes into the phone's text field; a few keys// have phone meanings.Keys.onPressed: (event) => {- if (!Mirror.canControl || Mirror.phase !== "showing")+ if (!win.canControl || win.phase !== "showing")returnconst keys = {}keys[Qt.Key_Escape] = "back"@@ -110,14 +118,14 @@ Window {keys[Qt.Key_Down] = "down"keys[Qt.Key_Tab] = "tab"if ((event.modifiers & Qt.ControlModifier) && event.key === Qt.Key_V) {- Mirror.paste()+ Mirror.paste(win.mirrorKey)event.accepted = true} else if (keys[event.key] !== undefined) {- Mirror.key(keys[event.key])+ Mirror.press(win.mirrorKey, keys[event.key])event.accepted = true} else if (event.text.length > 0 && !(event.modifiers & (Qt.ControlModifier | Qt.AltModifier))&& event.text.charCodeAt(0) >= 32) {- Mirror.text(event.text)+ Mirror.text(win.mirrorKey, event.text)event.accepted = true}}@@ -133,7 +141,7 @@ Window {width: 40; height: 40radius: 20color: Qt.rgba(0, 0, 0, 0.6)- visible: Mirror.sound && Mirror.phase === "showing"+ visible: win.info.sound === true && win.phase === "showing"opacity: hovering.hovered || Mirror.muted ? 1 : 0Behavior on opacity { NumberAnimation { duration: Theme.fadeFast } }IconButton {@@ -153,7 +161,7 @@ Window {anchors.margins: 12height: hint.implicitHeight + 20radius: Theme.radiusMd- visible: Mirror.phase === "showing" && video.frameSize.width > 0 && !Mirror.canControl && !hintClose.closed+ visible: win.phase === "showing" && video.frameSize.width > 0 && !win.canControl && !win.info.app && !hintClose.closedcolor: Qt.rgba(0, 0, 0, 0.72)Txt {id: hint@@ -181,7 +189,7 @@ Window {// Before the picture: waiting for the phone, or why it ended.Rectangle {anchors.fill: parent- visible: Mirror.phase !== "showing" || video.frameSize.width <= 0+ visible: win.phase !== "showing" || video.frameSize.width <= 0color: Theme.surfaceColumn {anchors.centerIn: parent@@ -189,12 +197,12 @@ Window {spacing: 14Spinner {anchors.horizontalCenter: parent.horizontalCenter- visible: Mirror.phase !== "ended"+ visible: win.phase !== "ended"width: 28; height: 28}Icon {anchors.horizontalCenter: parent.horizontalCenter- visible: Mirror.phase === "ended"+ visible: win.phase === "ended"width: 32; height: 32path: Icons.mirrorcolor: Theme.surfaceContentVariant@@ -204,8 +212,8 @@ Window {horizontalAlignment: Text.AlignHCenterwrapMode: Text.WordWraprole: "title"- text: Mirror.phase === "asking" ? qsTr("Allow it on your phone")- : Mirror.phase === "ended" ? qsTr("Mirroring stopped")+ text: win.phase === "asking" ? (win.info.app ? qsTr("Opening %1").arg(win.info.title) : qsTr("Allow it on your phone"))+ : win.phase === "ended" ? (win.info.app ? qsTr("%1 closed").arg(win.info.title) : qsTr("Mirroring stopped")): qsTr("Starting…")}Txt {@@ -214,17 +222,24 @@ Window {wrapMode: Text.WordWraprole: "body"muted: true- text: Mirror.phase === "asking"+ text: win.phase === "asking" && !win.info.app? qsTr("Tap the notification on %1, then choose to share the entire screen.").arg(win.deviceName)- : Mirror.phase === "ended" ? (Mirror.reason.length > 0 ? Mirror.reason : qsTr("The phone stopped sharing its screen."))+ : win.phase === "ended" ? ((win.info.reason || "").length > 0 ? win.info.reason+ : win.info.app ? qsTr("The phone closed the window.")+ : qsTr("The phone stopped sharing its screen.")): ""}Button {anchors.horizontalCenter: parent.horizontalCenter- visible: Mirror.phase === "ended"+ visible: win.phase === "ended" && !win.info.appvariant: "tonal"text: qsTr("Try again")- onClicked: Mirror.start(Mirror.device)+ // A new window takes this one's place.+ onClicked: {+ const device = win.info.device+ Mirror.stop(win.mirrorKey)+ Mirror.start(device)+ }}}}diff --git a/desktop/app/qml/components/AppsSheet.qml b/desktop/app/qml/components/AppsSheet.qmlnew file mode 100644index 0000000..a688e1e--- /dev/null+++ b/desktop/app/qml/components/AppsSheet.qml@@ -0,0 +1,201 @@+// SPDX-License-Identifier: GPL-3.0-or-later+import QtQuick+import app.nectarlink++// A phone's apps, to open one in a window of its own on this PC (Elevated:+// the phone runs it on a display of its own). Searchable; Enter opens the+// first match.+Sheet {+ id: sheet+ property string deviceId+ property string phoneName+ cardWidth: 640++ function openFor(device, name) {+ deviceId = device+ phoneName = name+ search.text = ""+ Mirror.loadApps(device)+ open()+ search.forceActiveFocus()+ }++ readonly property var apps: {+ if (Mirror.appsDevice !== deviceId)+ return []+ try { return JSON.parse(Mirror.apps) } catch (e) { return [] }+ }+ readonly property string query: search.text.trim().toLocaleLowerCase()+ readonly property var shown: query.length === 0 ? apps+ : apps.filter(a => a.label.toLocaleLowerCase().indexOf(query) >= 0 || a.pkg.indexOf(query) >= 0)+ readonly property string loadState: Mirror.appsDevice === deviceId ? Mirror.appsState : ""++ function launch(app) {+ Mirror.startApp(deviceId, app.pkg, app.label)+ close()+ }++ Column {+ width: parent.width+ spacing: 14++ Item {+ width: parent.width+ height: Math.max(title.height, refresh.height)+ Txt {+ id: title+ anchors.left: parent.left+ anchors.right: refresh.left+ anchors.verticalCenter: parent.verticalCenter+ text: qsTr("Open an app from %1").arg(sheet.phoneName)+ role: "headline"+ elide: Text.ElideRight+ }+ IconButton {+ id: refresh+ anchors.right: parent.right+ anchors.verticalCenter: parent.verticalCenter+ iconPath: Icons.refresh+ label: qsTr("Refresh")+ enabled: sheet.loadState !== "loading"+ onClicked: Mirror.loadApps(sheet.deviceId)+ }+ }+ Txt {+ width: parent.width+ wrapMode: Text.WordWrap+ role: "bodySmall"+ muted: true+ text: qsTr("It opens in a window of its own and runs on the phone, beside what's on the phone's screen.")+ }++ Rectangle {+ width: parent.width+ height: 40+ radius: Theme.graphite ? Theme.radiusSm : height / 2+ color: Theme.graphite ? "transparent" : Theme.surfaceContainerHighest+ border.width: search.activeFocus ? 2 : (Theme.graphite ? 1 : 0)+ border.color: search.activeFocus ? Theme.primary : Theme.outlineVariant+ Icon {+ id: searchIcon+ anchors.left: parent.left+ anchors.leftMargin: 14+ anchors.verticalCenter: parent.verticalCenter+ width: 18; height: 18+ path: Icons.search+ color: Theme.surfaceContentVariant+ }+ TextInput {+ id: search+ anchors.left: searchIcon.right+ anchors.leftMargin: 10+ anchors.right: parent.right+ anchors.rightMargin: 14+ anchors.verticalCenter: parent.verticalCenter+ font.family: Theme.fontUi+ font.pixelSize: 14+ color: Theme.surfaceContent+ selectionColor: Theme.primaryContainer+ selectedTextColor: Theme.primaryContainerContent+ clip: true+ Accessible.name: qsTr("Search apps")+ Keys.onReturnPressed: if (sheet.shown.length > 0) sheet.launch(sheet.shown[0])+ Keys.onEnterPressed: if (sheet.shown.length > 0) sheet.launch(sheet.shown[0])+ Txt {+ anchors.verticalCenter: parent.verticalCenter+ visible: search.text.length === 0+ role: "body"+ muted: true+ text: qsTr("Search apps")+ }+ }+ }++ // Loading, failed or empty.+ Column {+ width: parent.width+ visible: sheet.loadState !== "ready" || sheet.shown.length === 0+ spacing: 10+ topPadding: 24+ bottomPadding: 24+ Spinner {+ anchors.horizontalCenter: parent.horizontalCenter+ visible: sheet.loadState === "loading" || sheet.loadState === ""+ width: 24; height: 24+ }+ Txt {+ width: parent.width+ horizontalAlignment: Text.AlignHCenter+ wrapMode: Text.WordWrap+ role: "body"+ muted: true+ text: sheet.loadState === "failed" ? Mirror.appsError+ : sheet.loadState === "ready" ? (sheet.query.length > 0 ? qsTr("No apps match.") : qsTr("No apps to open."))+ : qsTr("Getting the phone's apps…")+ }+ }++ GridView {+ id: grid+ width: parent.width+ height: Math.min(contentHeight, 420)+ visible: sheet.loadState === "ready" && sheet.shown.length > 0+ clip: true+ model: sheet.shown+ cellWidth: Math.floor(width / Math.max(1, Math.floor(width / 112)))+ cellHeight: 104+ boundsBehavior: Flickable.StopAtBounds+ delegate: Item {+ id: cell+ required property var modelData+ width: grid.cellWidth+ height: grid.cellHeight+ Accessible.role: Accessible.Button+ Accessible.name: modelData.label+ Accessible.onPressAction: sheet.launch(modelData)++ Rectangle {+ anchors.fill: parent+ anchors.margins: 4+ radius: Theme.radiusMd+ color: Theme.surfaceContent+ opacity: tap.pressed ? 0.12 : (hover.hovered ? 0.06 : 0)+ }+ Column {+ anchors.centerIn: parent+ width: parent.width - 12+ spacing: 8+ Item {+ anchors.horizontalCenter: parent.horizontalCenter+ width: 44; height: 44+ Image {+ id: icon+ anchors.fill: parent+ source: cell.modelData.icon+ sourceSize: Qt.size(88, 88)+ smooth: true+ mipmap: true+ visible: status === Image.Ready+ }+ Avatar {+ anchors.fill: parent+ visible: icon.status !== Image.Ready+ name: cell.modelData.label+ }+ }+ Txt {+ width: parent.width+ horizontalAlignment: Text.AlignHCenter+ role: "bodySmall"+ text: cell.modelData.label+ elide: Text.ElideRight+ maximumLineCount: 2+ wrapMode: Text.WordWrap+ }+ }+ HoverHandler { id: hover; cursorShape: Qt.PointingHandCursor }+ TapHandler { id: tap; onTapped: sheet.launch(cell.modelData) }+ }+ }+ }+}diff --git a/desktop/app/qml/pages/HomePage.qml b/desktop/app/qml/pages/HomePage.qmlindex 1e540cc..45620f0 100644--- a/desktop/app/qml/pages/HomePage.qml+++ b/desktop/app/qml/pages/HomePage.qml@@ -277,8 +277,19 @@ Item {subtitle: qsTr("See it on this PC")iconPath: Icons.mirrorfeature: home.feature("mirroring.view")- active: Mirror.device === home.deviceId && Mirror.phase !== "" && Mirror.phase !== "ended"+ // The phone's screen is showing (its session is 0).+ active: {+ try {+ return JSON.parse(Mirror.windows).some(w => w.device === home.deviceId && w.session === 0+ && w.phase !== "ended")+ } catch (e) {+ return false+ }+ }onClicked: Mirror.start(home.deviceId)+ sideIcon: home.feature("mirroring.app_windows").state === "available" ? Icons.apps : ""+ sideLabel: qsTr("Open an app")+ onSideClicked: appsSheet.openFor(home.deviceId, home.name)}ActionTile {width: actions.tileWidth@@ -646,6 +657,10 @@ Item {}// Notifications from the last day that are gone from the phone.+ AppsSheet {+ id: appsSheet+ }+Sheet {id: historySheetcardWidth: 560diff --git a/desktop/app/src/bridge/mirror.rs b/desktop/app/src/bridge/mirror.rsindex fbe671b..1cca2ee 100644--- a/desktop/app/src/bridge/mirror.rs+++ b/desktop/app/src/bridge/mirror.rs@@ -1,15 +1,16 @@// SPDX-License-Identifier: GPL-3.0-or-later-//! `Mirror`: the phone whose screen the mirror window shows, and how far-//! along it is.+//! `Mirror`: the phone screens and app windows shown on this PC (each a+//! window, by key), the phone's apps that open in windows, and the input+//! QML sends to them.use std::pin::Pin;-use cxx_qt::{CxxQtType, Threading};+use cxx_qt::Threading;use cxx_qt_lib::QString;-use nectarlink_core::DeviceId;+use nectarlink_core::{FeatureState, MIRROR_SCREEN, MirrorInput};use crate::{- mirror::{self, Phase},+ mirror::{self, Apps, Phase, Window},state::Changes,};@@ -24,19 +25,20 @@ pub mod qobject {#[qobject]#[qml_element]#[qml_singleton]- /// The phone shown ("" when the window is closed).- #[qproperty(QString, device)]- #[qproperty(QString, name)]- /// "asking", "showing" or "ended" ("" when closed).- #[qproperty(QString, phase)]- /// Why it ended, when there's something to say.- #[qproperty(QString, reason)]- /// The PC's mouse and keyboard work on the phone.- #[qproperty(bool, can_control, cxx_name = "canControl")]- /// The phone's sound is coming in.- #[qproperty(bool, sound)]- /// The user turned the sound off on this PC.+ /// The windows, as JSON: `[{ key, device, session, name, title,+ /// phase ("asking", "showing", "ended"), reason, canControl, sound,+ /// app }]`.+ #[qproperty(QString, windows)]+ /// The user turned the phones' sound off on this PC.#[qproperty(bool, muted)]+ /// The phone whose apps [`apps`] lists.+ #[qproperty(QString, apps_device, cxx_name = "appsDevice")]+ /// Its apps, as JSON: `[{ pkg, label, icon }]` (icon: a file URL or "").+ #[qproperty(QString, apps)]+ /// "", "loading", "ready" or "failed".+ #[qproperty(QString, apps_state, cxx_name = "appsState")]+ /// Why they couldn't be loaded.+ #[qproperty(QString, apps_error, cxx_name = "appsError")]type Mirror = super::MirrorRust;}@@ -44,29 +46,37 @@ pub mod qobject {impl cxx_qt::Initialize for Mirror {}unsafe extern "RustQt" {- /// Asks a phone for its screen and opens the window.+ /// Asks a phone for its screen (a window opens).#[qinvokable]- fn start(self: Pin<&mut Mirror>, device: &QString);- /// Closes the window and stops mirroring.+ fn start(self: &Mirror, device: &QString);+ /// Opens one of a phone's apps in a window of its own.#[qinvokable]- fn stop(self: Pin<&mut Mirror>);- /// A finger on the screen: "down", "move" or "up", at a fraction of- /// the screen's width and height.+ #[cxx_name = "startApp"]+ fn start_app(self: &Mirror, device: &QString, pkg: &QString, label: &QString);+ /// Closes a window, ending its mirroring.#[qinvokable]- fn touch(self: &Mirror, action: &QString, x: f64, y: f64);+ fn stop(self: &Mirror, key: &QString);+ /// Loads a phone's apps (into `apps`).+ #[qinvokable]+ #[cxx_name = "loadApps"]+ fn load_apps(self: Pin<&mut Mirror>, device: &QString);+ /// A finger on a window's screen: "down", "move" or "up", at a+ /// fraction of its width and height.+ #[qinvokable]+ fn touch(self: &Mirror, key: &QString, action: &QString, x: f64, y: f64);/// The mouse wheel, in notches (positive: down / right).#[qinvokable]- fn scroll(self: &Mirror, x: f64, y: f64, dx: f64, dy: f64);+ fn scroll(self: &Mirror, key: &QString, x: f64, y: f64, dx: f64, dy: f64);/// A key without text ("back", "home", "enter"...).#[qinvokable]- fn key(self: &Mirror, key: &QString);+ fn press(self: &Mirror, key: &QString, name: &QString);/// Typed text.#[qinvokable]- fn text(self: &Mirror, text: &QString);+ fn text(self: &Mirror, key: &QString, text: &QString);/// Types the PC's clipboard text on the phone.#[qinvokable]- fn paste(self: &Mirror);- /// Turns the phone's sound off on this PC, or back on.+ fn paste(self: &Mirror, key: &QString);+ /// Turns the phones' sound off on this PC, or back on.#[qinvokable]#[cxx_name = "toggleSound"]fn toggle_sound(self: &Mirror);@@ -75,65 +85,122 @@ pub mod qobject {#[derive(Default)]pub struct MirrorRust {- device: QString,- name: QString,- phase: QString,- reason: QString,- can_control: bool,- sound: bool,+ windows: QString,muted: bool,- shown: Option<DeviceId>,+ apps_device: QString,+ apps: QString,+ apps_state: QString,+ apps_error: QString,}impl cxx_qt::Initialize for qobject::Mirror {fn initialize(self: Pin<&mut Self>) {- super::subscribe(self.qt_thread(), Changes::MIRROR | Changes::CAPABILITIES, Self::refresh);+ super::subscribe(+ self.qt_thread(),+ Changes::MIRROR | Changes::CAPABILITIES | Changes::DEVICES,+ Self::refresh,+ );}}impl qobject::Mirror {fn refresh(mut self: Pin<&mut Self>) {- let Some(device) = self.rust().shown else {- self.as_mut().set_phase(QString::default());- return;- };- let control = crate::core_host::host().hub.read(|s| {- s.matrices.get(&device).and_then(|m| m.state("mirroring.control"))- == Some(nectarlink_core::FeatureState::Available)- });- self.as_mut().set_can_control(control);- self.as_mut().set_sound(mirror::has_sound(&device));+ let hub = &crate::core_host::host().hub;+ let windows: Vec<serde_json::Value> = mirror::windows()+ .into_iter()+ .map(|(window, shown)| {+ let (control, name) = hub.read(|s| {+ // The screen needs control turned on; app windows are Elevated already.+ let feature = if window.session == MIRROR_SCREEN {+ "mirroring.control"+ } else {+ "mirroring.app_windows"+ };+ let control = s.matrices.get(&window.device).and_then(|m| m.state(feature))+ == Some(FeatureState::Available);+ (control, s.name_of(&window.device).unwrap_or_default())+ });+ let (phase, reason) = match shown.phase {+ Phase::Asking => ("asking", String::new()),+ Phase::Showing => ("showing", String::new()),+ Phase::Ended(reason) => ("ended", reason.unwrap_or_default()),+ };+ serde_json::json!({+ "key": window.key(),+ "device": window.device.to_string(),+ "session": window.session,+ "name": name,+ "title": shown.app.clone().unwrap_or_else(|| name.clone()),+ "app": shown.app.is_some(),+ "phase": phase,+ "reason": reason,+ "canControl": control,+ "sound": window.session == MIRROR_SCREEN && mirror::has_sound(&window.device),+ })+ })+ .collect();+ let json = serde_json::Value::Array(windows).to_string();+ if self.windows.to_string() != json {+ self.as_mut().set_windows(QString::from(&json));+ }self.as_mut().set_muted(mirror::muted());- let (phase, reason) = match mirror::phase(&device) {- None => ("", String::new()),- Some(Phase::Asking) => ("asking", String::new()),- Some(Phase::Showing) => ("showing", String::new()),- Some(Phase::Ended(reason)) => ("ended", reason.unwrap_or_default()),++ let Some(device) = super::parse_device(&self.apps_device) else { return };+ let (state, apps, error) = match mirror::apps(&device) {+ None => ("", Vec::new(), String::new()),+ Some(Apps::Loading) => ("loading", Vec::new(), String::new()),+ Some(Apps::Failed(why)) => ("failed", Vec::new(), why),+ Some(Apps::Ready(apps)) => ("ready", apps, String::new()),};- self.as_mut().set_reason(QString::from(&reason));- self.as_mut().set_phase(QString::from(phase));+ let apps: Vec<serde_json::Value> = apps+ .into_iter()+ .map(|a| {+ serde_json::json!({+ "pkg": a.pkg,+ "label": a.label,+ "icon": a.icon.as_deref().map(crate::icons::file_url).unwrap_or_default(),+ })+ })+ .collect();+ self.as_mut().set_apps(QString::from(&serde_json::Value::Array(apps).to_string()));+ self.as_mut().set_apps_error(QString::from(&error));+ self.as_mut().set_apps_state(QString::from(state));}- pub fn start(mut self: Pin<&mut Self>, device: &QString) {- let Some(id) = super::parse_device(device) else { return };- if let Some(previous) = self.rust().shown.filter(|p| *p != id) {- mirror::stop(previous);+ pub fn start(&self, device: &QString) {+ if let Some(device) = super::parse_device(device) {+ mirror::start(device);+ }+ }++ pub fn start_app(&self, device: &QString, pkg: &QString, label: &QString) {+ let pkg = String::from(pkg);+ if let (Some(device), true) = (super::parse_device(device), nectarlink_core::is_package_name(&pkg)) {+ mirror::start_app(device, pkg, String::from(label));}- self.as_mut().rust_mut().shown = Some(id);- self.as_mut().set_device(device.clone());- let name = crate::core_host::host().hub.read(|s| s.name_of(&id)).unwrap_or_default();- self.as_mut().set_name(QString::from(&name));- mirror::start(id);+ }++ pub fn stop(&self, key: &QString) {+ if let Some(window) = Window::parse(&String::from(key)) {+ mirror::stop(window);+ }+ }++ pub fn load_apps(mut self: Pin<&mut Self>, device: &QString) {+ let Some(id) = super::parse_device(device) else { return };+ self.as_mut().set_apps_device(device.clone());+ mirror::load_apps(id);self.refresh();}- fn send(&self, input: nectarlink_core::MirrorInput) {- if let (Some(device), true) = (self.rust().shown, self.rust().can_control) {- mirror::input(device, input);+ fn send(&self, key: &QString, input: MirrorInput) {+ let Some(window) = Window::parse(&String::from(key)) else { return };+ if matches!(mirror::phase(&window), Some(Phase::Showing)) {+ mirror::input(window, input);}}- pub fn touch(&self, action: &QString, x: f64, y: f64) {+ pub fn touch(&self, key: &QString, action: &QString, x: f64, y: f64) {use nectarlink_core::TouchAction;let action = match String::from(action).as_str() {"down" => TouchAction::Down,@@ -141,41 +208,44 @@ impl qobject::Mirror {"up" => TouchAction::Up,_ => return,};- self.send(nectarlink_core::MirrorInput::Touch { action, x: fraction(x), y: fraction(y) });+ self.send(key, MirrorInput::Touch { action, x: fraction(x), y: fraction(y) });}- pub fn scroll(&self, x: f64, y: f64, dx: f64, dy: f64) {- self.send(nectarlink_core::MirrorInput::Scroll {- x: fraction(x),- y: fraction(y),- dx: dx.clamp(-100.0, 100.0) as f32,- dy: dy.clamp(-100.0, 100.0) as f32,- });+ pub fn scroll(&self, key: &QString, x: f64, y: f64, dx: f64, dy: f64) {+ self.send(+ key,+ MirrorInput::Scroll {+ x: fraction(x),+ y: fraction(y),+ dx: dx.clamp(-100.0, 100.0) as f32,+ dy: dy.clamp(-100.0, 100.0) as f32,+ },+ );}- pub fn key(&self, key: &QString) {- self.send(nectarlink_core::MirrorInput::Key { key: String::from(key) });+ pub fn press(&self, key: &QString, name: &QString) {+ self.send(key, MirrorInput::Key { key: String::from(name) });}- pub fn text(&self, text: &QString) {+ pub fn text(&self, key: &QString, text: &QString) {let text = String::from(text);if !text.is_empty() && text.len() <= nectarlink_core::MIRROR_MAX_TEXT_BYTES {- self.send(nectarlink_core::MirrorInput::Text { text });+ self.send(key, MirrorInput::Text { text });}}- pub fn paste(&self) {+ pub fn paste(&self, key: &QString) {if let crate::win::clipboard::Clip::Text(text) = crate::win::clipboard::read() {// Long text goes in pieces, each a whole number of characters.let mut piece = String::new();for c in text.chars() {if piece.len() + c.len_utf8() > nectarlink_core::MIRROR_MAX_TEXT_BYTES {- self.send(nectarlink_core::MirrorInput::Text { text: std::mem::take(&mut piece) });+ self.send(key, MirrorInput::Text { text: std::mem::take(&mut piece) });}piece.push(c);}if !piece.is_empty() {- self.send(nectarlink_core::MirrorInput::Text { text: piece });+ self.send(key, MirrorInput::Text { text: piece });}}}@@ -183,15 +253,6 @@ impl qobject::Mirror {pub fn toggle_sound(&self) {mirror::set_muted(!mirror::muted());}-- pub fn stop(mut self: Pin<&mut Self>) {- if let Some(id) = self.as_mut().rust_mut().shown.take() {- mirror::stop(id);- }- self.as_mut().set_device(QString::default());- self.as_mut().set_reason(QString::default());- self.set_phase(QString::default());- }}/// A position on the screen, kept on it.diff --git a/desktop/app/src/main.rs b/desktop/app/src/main.rsindex 2750868..d9078d3 100644--- a/desktop/app/src/main.rs+++ b/desktop/app/src/main.rs@@ -90,8 +90,9 @@ impl Platform for DesktopPlatform {fn mirror_sink(&self,peer: &nectarlink_core::DeviceId,+ session: u32,) -> Option<std::sync::Arc<dyn nectarlink_core::MirrorSink>> {- mirror::sink(peer)+ mirror::sink(peer, session)}}diff --git a/desktop/app/src/mirror.rs b/desktop/app/src/mirror.rsindex d9bb09c..8b1bfa9 100644--- a/desktop/app/src/mirror.rs+++ b/desktop/app/src/mirror.rs@@ -7,16 +7,19 @@//! speakers.use std::{- collections::HashMap,+ collections::{HashMap, HashSet},+ path::PathBuf,sync::{Arc, Mutex, OnceLock,- atomic::{AtomicUsize, Ordering},+ atomic::{AtomicBool, AtomicU32, AtomicUsize, Ordering},mpsc::{Receiver, SyncSender, TrySendError, sync_channel},},time::{Duration, Instant},};-use nectarlink_core::{DeviceId, Error, MirrorAudioConfig, MirrorConfig, MirrorSink, MirrorStart, NodeEvent};+use nectarlink_core::{+ DeviceId, Error, MIRROR_SCREEN, MirrorAudioConfig, MirrorConfig, MirrorSink, MirrorStart, NodeEvent,+};use crate::{bridge::{app::describe, native::ffi},@@ -29,31 +32,91 @@ use crate::{};/// What the PC asks for: the phone scales its screen to fit.-const OPTIONS: MirrorStart = MirrorStart { max_size: 1920, fps: 60, bitrate: 8_000_000, audio: true };+const OPTIONS: MirrorStart = MirrorStart {+ max_size: 1920,+ fps: 60,+ bitrate: 8_000_000,+ audio: true,+ session: MIRROR_SCREEN,+ app: None,+};/// Packets waiting for the decoder, at most (about two seconds).const BACKLOG: usize = 120;/// How often decode times are logged.const STATS_EVERY: Duration = Duration::from_secs(10);-/// Where mirroring of a phone stands.+/// A mirroring on this PC: a phone and the session, 0 for its screen,+/// others for its apps in windows of their own.+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]+pub struct Window {+ pub device: DeviceId,+ pub session: u32,+}++impl Window {+ pub fn screen(device: DeviceId) -> Window {+ Window { device, session: MIRROR_SCREEN }+ }++ /// Its name for QML and for `VideoView`'s stream: `<device>/<session>`.+ pub fn key(&self) -> String {+ format!("{}/{}", self.device, self.session)+ }++ pub fn parse(key: &str) -> Option<Window> {+ let (device, session) = key.split_once('/')?;+ Some(Window { device: device.parse().ok()?, session: session.parse().ok()? })+ }+}++/// Where a mirroring stands.#[derive(Debug, Clone, PartialEq, Eq)]pub enum Phase {- /// Waiting for the phone's user to agree.+ /// Waiting for the phone (its user agreeing to share the screen, or the+ /// app starting).Asking,Showing,/// It ended; the reason for the window, if any.Ended(Option<String>),}+/// A mirroring the PC asked for.+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct Shown {+ pub phase: Phase,+ /// For an app window: the app's name, and its package.+ pub app: Option<String>,+ pub pkg: Option<String>,+}++/// A phone's apps that open in windows.+#[derive(Debug, Clone, PartialEq, Eq)]+pub enum Apps {+ Loading,+ Ready(Vec<App>),+ Failed(String),+}++#[derive(Debug, Clone, PartialEq, Eq)]+pub struct App {+ pub pkg: String,+ pub label: String,+ /// The icon, saved for QML.+ pub icon: Option<PathBuf>,+}+#[derive(Debug, Default)]struct State {- phases: HashMap<DeviceId, Phase>,+ windows: HashMap<Window, Shown>,/// Phones whose sound is coming in.- sound: std::collections::HashSet<DeviceId>,+ sound: HashSet<DeviceId>,+ apps: HashMap<DeviceId, Apps>,}/// The user turned the phones' sound off on this PC (until turned on).-static MUTED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);+static MUTED: AtomicBool = AtomicBool::new(false);+/// The next app window's session.+static NEXT_SESSION: AtomicU32 = AtomicU32::new(1);pub fn muted() -> bool {MUTED.load(Ordering::Relaxed)@@ -80,66 +143,156 @@ fn state<T>(f: impl FnOnce(&mut State) -> T) -> T {f(STATE.lock().unwrap_or_else(|e| e.into_inner()).get_or_insert_default())}-fn set_phase(device: DeviceId, phase: Phase) {- state(|s| s.phases.insert(device, phase));+fn set_phase(window: Window, phase: Phase) {+ state(|s| {+ if let Some(shown) = s.windows.get_mut(&window) {+ shown.phase = phase;+ }+ });core_host::host().hub.changed(Changes::MIRROR);}-/// Where mirroring of `device` stands (`None`: not asked).-pub fn phase(device: &DeviceId) -> Option<Phase> {- state(|s| s.phases.get(device).cloned())+/// Where a mirroring stands (`None`: not asked, or closed).+pub fn phase(window: &Window) -> Option<Phase> {+ state(|s| s.windows.get(window).map(|w| w.phase.clone()))+}++/// Every mirroring the PC asked for, oldest first.+pub fn windows() -> Vec<(Window, Shown)> {+ let mut all: Vec<_> = state(|s| s.windows.iter().map(|(w, s)| (*w, s.clone())).collect());+ all.sort_by_key(|(w, _)| (w.device.to_string(), w.session));+ all}/// Asks the phone for its screen.pub fn start(device: DeviceId) {- set_phase(device, Phase::Asking);+ let window = Window::screen(device);+ state(|s| s.windows.insert(window, Shown { phase: Phase::Asking, app: None, pkg: None }));+ request(window, OPTIONS);+}++/// Opens one of the phone's apps in a window of its own (or does nothing+/// when it's already open).+pub fn start_app(device: DeviceId, pkg: String, label: String) {+ let open = state(|s| {+ s.windows.iter().any(|(w, shown)| {+ w.device == device+ && shown.pkg.as_deref() == Some(pkg.as_str())+ && matches!(shown.phase, Phase::Asking | Phase::Showing)+ })+ });+ if open {+ return;+ }+ let session = NEXT_SESSION.fetch_add(1, Ordering::Relaxed);+ let window = Window { device, session };+ state(|s| {+ s.windows.insert(window, Shown { phase: Phase::Asking, app: Some(label), pkg: Some(pkg.clone()) })+ });+ request(window, MirrorStart { audio: false, session, app: Some(pkg), ..OPTIONS });+}++fn request(window: Window, options: MirrorStart) {+ core_host::host().hub.changed(Changes::MIRROR);let Some(node) = core_host::node() else { return };+ let app = options.app.is_some();core_host::spawn(async move {- if let Err(e) = node.mirror_start(device, OPTIONS).await {+ if let Err(e) = node.mirror_start(window.device, options).await {let reason = match e {Error::Denied => "Mirroring is turned off for this phone.".to_owned(),+ Error::Unsupported if app => {+ "Set up Wireless debugging in Nectarlink on the phone to open its apps here.".into()+ }Error::Unsupported => {"This phone's app doesn't share its screen yet. Update Nectarlink on the phone.".into()}Error::Offline | Error::NotPaired => "The phone isn't connected.".into(),e => describe(&e),};- set_phase(device, Phase::Ended(Some(reason)));+ set_phase(window, Phase::Ended(Some(reason)));}});}-/// Stops showing the phone's screen (closing the window).-pub fn stop(device: DeviceId) {- state(|s| s.phases.remove(&device));- ffi::video_clear(&device.to_string());+/// Stops a mirroring (its window closed).+pub fn stop(window: Window) {+ state(|s| s.windows.remove(&window));+ ffi::video_clear(&window.key());core_host::host().hub.changed(Changes::MIRROR);let Some(node) = core_host::node() else { return };- core_host::spawn(async move { node.mirror_stop(device).await });+ core_host::spawn(async move { node.mirror_stop(window.device, window.session).await });}pub fn on_event(event: &NodeEvent) {match event {- NodeEvent::Mirroring { device, on: true } => set_phase(*device, Phase::Showing),+ NodeEvent::Mirroring { device, session, on: true } => {+ set_phase(Window { device: *device, session: *session }, Phase::Showing);+ }// Closed here: nothing to say. Stopped on the phone: say so.- NodeEvent::Mirroring { device, on: false } if phase(device).is_some() => {- set_phase(*device, Phase::Ended(None));+ NodeEvent::Mirroring { device, session, on: false } => {+ let window = Window { device: *device, session: *session };+ if phase(&window).is_some() {+ set_phase(window, Phase::Ended(None));+ }+ }+ // A phone that went away takes its app list with it.+ NodeEvent::LinkChanged { device, link: nectarlink_core::LinkState::Offline { .. } } => {+ state(|s| s.apps.remove(device));}_ => {}}}-/// The PC's mouse and keyboard on the shown phone, sent in order.-pub fn input(device: DeviceId, input: nectarlink_core::MirrorInput) {+/// A phone's apps that open in windows, as last loaded.+pub fn apps(device: &DeviceId) -> Option<Apps> {+ state(|s| s.apps.get(device).cloned())+}++/// Loads (or reloads) a phone's apps, with their icons.+pub fn load_apps(device: DeviceId) {+ state(|s| s.apps.insert(device, Apps::Loading));+ core_host::host().hub.changed(Changes::MIRROR);+ let Some(node) = core_host::node() else { return };+ core_host::spawn(async move {+ let loaded = match node.mirror_apps(device).await {+ Ok(apps) => {+ let data_dir = core_host::host().data_dir.clone();+ let apps = tokio::task::spawn_blocking(move || {+ apps.into_iter()+ .map(|a| App {+ icon: a.icon.and_then(|png| crate::icons::save(&data_dir, &a.pkg, &png).ok()),+ pkg: a.pkg,+ label: a.label,+ })+ .collect()+ })+ .await+ .unwrap_or_default();+ Apps::Ready(apps)+ }+ Err(Error::Unsupported) => Apps::Failed(+ "Set up Wireless debugging in Nectarlink on the phone to open its apps here.".into(),+ ),+ Err(e) => Apps::Failed(describe(&e)),+ };+ state(|s| s.apps.insert(device, loaded));+ core_host::host().hub.changed(Changes::MIRROR);+ });+}++/// The PC's mouse and keyboard on a mirrored screen or app window, sent in+/// order.+pub fn input(window: Window, input: nectarlink_core::MirrorInput) {static QUEUE: std::sync::OnceLock<- tokio::sync::mpsc::UnboundedSender<(DeviceId, nectarlink_core::MirrorInput)>,+ tokio::sync::mpsc::UnboundedSender<(Window, nectarlink_core::MirrorInput)>,> = std::sync::OnceLock::new();let queue = QUEUE.get_or_init(|| {- let (queue, mut inputs) = tokio::sync::mpsc::unbounded_channel();+ let (queue, mut inputs) =+ tokio::sync::mpsc::unbounded_channel::<(Window, nectarlink_core::MirrorInput)>();core_host::spawn(async move {- while let Some((device, input)) = inputs.recv().await {+ while let Some((window, input)) = inputs.recv().await {if let Some(node) = core_host::node()- && let Err(e) = node.mirror_input(device, input).await+ && let Err(e) = node.mirror_input(window.device, window.session, input).await{tracing::debug!(error = %e, "input didn't reach the phone");}@@ -147,14 +300,15 @@ pub fn input(device: DeviceId, input: nectarlink_core::MirrorInput) {});queue});- let _ = queue.send((device, input));+ let _ = queue.send((window, input));}-/// Where the core puts a phone's video (or sound, from a stream of its-/// own): only for phones this PC asked.-pub fn sink(device: &DeviceId) -> Option<Arc<dyn MirrorSink>> {- matches!(phase(device), Some(Phase::Asking | Phase::Showing))- .then(|| Arc::new(Sink::new(*device)) as Arc<dyn MirrorSink>)+/// Where the core puts a phone's video (or the screen's sound, from a+/// stream of its own): only for mirrorings this PC asked for.+pub fn sink(device: &DeviceId, session: u32) -> Option<Arc<dyn MirrorSink>> {+ let window = Window { device: *device, session };+ matches!(phase(&window), Some(Phase::Asking | Phase::Showing))+ .then(|| Arc::new(Sink::new(window)) as Arc<dyn MirrorSink>)}enum Item {@@ -166,7 +320,7 @@ enum Item {/// Hands the core's packets to the decoder thread, or its sound to the/// player; each starts with its stream's first packet (the format).struct Sink {- device: DeviceId,+ window: Window,video: OnceLock<Video>,sound: Mutex<Option<Player>>,}@@ -179,19 +333,19 @@ struct Video {}impl Sink {- fn new(device: DeviceId) -> Sink {- Sink { device, video: OnceLock::new(), sound: Mutex::new(None) }+ fn new(window: Window) -> Sink {+ Sink { window, video: OnceLock::new(), sound: Mutex::new(None) }}}impl Video {- fn start(device: DeviceId) -> Video {+ fn start(window: Window) -> Video {let (queue, items) = sync_channel(BACKLOG);let waiting = Arc::new(AtomicUsize::new(0));let counter = waiting.clone();let started = std::thread::Builder::new().name("mirror-decoder".into())- .spawn(move || decode(device, &items, &counter));+ .spawn(move || decode(window, &items, &counter));if let Err(e) = started {tracing::error!(error = %e, "can't start the video decoder");}@@ -201,16 +355,16 @@ impl Video {impl Sink {fn keyframe_please(&self) {- let device = self.device;+ let window = self.window;if let Some(node) = core_host::node() {- core_host::spawn(async move { node.mirror_keyframe(device).await });+ core_host::spawn(async move { node.mirror_keyframe(window.device, window.session).await });}}}impl MirrorSink for Sink {fn config(&self, config: MirrorConfig) {- let video = self.video.get_or_init(|| Video::start(self.device));+ let video = self.video.get_or_init(|| Video::start(self.window));// The format matters: wait for room rather than drop it.let _ = video.queue.send(Item::Config(config));}@@ -243,7 +397,7 @@ impl MirrorSink for Sink {None}};- set_sound(self.device, sound.is_some());+ set_sound(self.window.device, sound.is_some());}fn audio(&self, _time_us: u64, data: Vec<u8>) {@@ -257,25 +411,25 @@ impl MirrorSink for Sink {fn audio_ended(&self) {self.sound.lock().unwrap_or_else(|e| e.into_inner()).take();- set_sound(self.device, false);+ set_sound(self.window.device, false);}}/// The decoder thread: decodes everything (later pictures depend on/// earlier ones), shows the newest picture of each batch.-fn decode(device: DeviceId, items: &Receiver<Item>, waiting: &AtomicUsize) {- let stream = device.to_string();+fn decode(window: Window, items: &Receiver<Item>, waiting: &AtomicUsize) {+ let stream = window.key();let mut decoder = match Decoder::new() {Ok(decoder) => decoder,Err(e) => {tracing::error!(error = %e, "no H.264 decoder");- set_phase(device, Phase::Ended(Some("This PC can't decode the phone's video.".into())));+ set_phase(window, Phase::Ended(Some("This PC can't decode the phone's video.".into())));return;}};let keyframe_please = || {if let Some(node) = core_host::node() {- core_host::spawn(async move { node.mirror_keyframe(device).await });+ core_host::spawn(async move { node.mirror_keyframe(window.device, window.session).await });}};let mut size = (0, 0);diff --git a/x.h264 b/x.h264new file mode 100644index 0000000..e69de29