Skip to content

Your Android phone and your Windows PC, working as one. Local-first, end-to-end encrypted, no account.

App windows: icons, resizing, remembered places, and closing cleanly

Bee4493daa7e26f
diff --git a/README.md b/README.md
index 7e8da18..2d9c9e4 100644
--- a/README.md
+++ b/README.md
@@ -101,9 +101,13 @@ tests; there are no releases yet.
nothing else to install; Nectarlink turns Wireless debugging back on by
itself after a reboot.
- **Phone apps in windows** on the PC: with Wireless debugging set up
- (Android 11 and later), pick any of the phone's apps and it opens in a
- window of its own, running on the phone beside whatever its screen
- shows; use it with the mouse and keyboard, and open several at once.
+ (Android 11 and later), pick any of the phone's apps (with a Recent row
+ for the ones opened most recently) and it opens in a window of its own with
+ its own taskbar icon, running on the phone beside whatever its screen shows
+ and without popping the phone's keyboard up on its screen; resize the
+ window and the app re-lays out to fit, its size and position are remembered
+ for next time, and if it closes on the phone the window offers to open it
+ again.
- **Texts** on the PC: a Messages page with the phone's conversations
(pictures included), to reply or start a new one (searching contacts as
you type); texts go out through the phone. Search them, copy a one-time
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.kt
index 7bac279..28ce77f 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
@@ -101,6 +101,10 @@ internal class PhonePlatform(
override fun mirrorKeyframeRequested(pcId: String, session: UInt) =
if (session == SCREEN) MirrorService.keyframe(pcId) else appWindows.keyframe(pcId, session)
+ override fun mirrorResizeRequested(pcId: String, session: UInt, width: UInt, height: UInt) {
+ if (session != SCREEN) appWindows.resize(pcId, session, width.toInt(), height.toInt())
+ }
+
// Real events when Elevated runs; gestures through the accessibility service otherwise.
override fun mirrorInput(pcId: String, session: UInt, input: MirrorInputEvent) {
if (session != SCREEN) return appWindows.input(pcId, session, input)
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.kt
index d5a47ca..1a4a252 100644
--- a/android/app/src/main/kotlin/app/nectarlink/android/elevated/AppDisplay.kt
+++ b/android/app/src/main/kotlin/app/nectarlink/android/elevated/AppDisplay.kt
@@ -32,6 +32,7 @@ class AppDisplay(
private val fps: Int,
) {
@Volatile private var running = true
+ @Volatile private var nextSize: Triple<Int, Int, Int>? = null
private var display: VirtualDisplay? = null
/** The display's ID, once made. */
@@ -40,39 +41,61 @@ class AppDisplay(
/** 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)
+ var curW = width
+ var curH = height
+ var curDpi = dpi
+ var codec: MediaCodec? = null
+ var surface: Surface? = null
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)
+ val (firstCodec, firstSurface) = createEncoder(curW, curH)
+ codec = firstCodec
+ surface = firstSurface
+ val made = createDisplay(curW, curH, curDpi, firstSurface)
display = made
displayId = made.display.displayId
- codec.start()
- codecForKeyframes = codec
+ hideIme(displayId)
+ firstCodec.start()
+ codecForKeyframes = firstCodec
write(data, KIND_CONFIG, 0, ByteArray(12).also {
- java.nio.ByteBuffer.wrap(it).putInt(width).putInt(height).putInt(displayId)
+ java.nio.ByteBuffer.wrap(it).putInt(curW).putInt(curH).putInt(displayId)
})
data.flush()
launch(pkg, displayId)
- drain(codec, data)
+ watchActivities(displayId)
+ while (running) {
+ drain(codec!!, data)
+ if (!running) break
+ val (newW, newH, newDpi) = nextSize ?: continue
+ nextSize = null
+ if (newW == curW && newH == curH && newDpi == curDpi) continue
+ codecForKeyframes = null
+ runCatching { codec.stop() }
+ runCatching { codec.release() }
+ codec = null
+ runCatching { surface?.release() }
+ surface = null
+ val (nextCodec, nextSurface) = createEncoder(newW, newH)
+ codec = nextCodec
+ surface = nextSurface
+ nextCodec.start()
+ codecForKeyframes = nextCodec
+ made.resize(newW, newH, newDpi)
+ made.surface = nextSurface
+ curW = newW
+ curH = newH
+ curDpi = newDpi
+ write(data, KIND_CONFIG, 0, ByteArray(12).also {
+ java.nio.ByteBuffer.wrap(it).putInt(curW).putInt(curH).putInt(displayId)
+ })
+ data.flush()
+ }
} finally {
running = false
codecForKeyframes = null
- runCatching { codec.stop() }
- codec.release()
+ runCatching { codec?.stop() }
+ runCatching { codec?.release() }
+ runCatching { surface?.release() }
display?.release()
display = null
}
@@ -82,6 +105,10 @@ class AppDisplay(
running = false
}
+ fun resize(w: Int, h: Int, newDpi: Int) {
+ nextSize = Triple(w, h, newDpi)
+ }
+
@Volatile private var codecForKeyframes: MediaCodec? = null
/** The PC's decoder lost its place: a keyframe next. */
@@ -92,11 +119,33 @@ class AppDisplay(
}
}
+ private fun createEncoder(w: Int, h: Int): Pair<MediaCodec, Surface> {
+ val format = MediaFormat.createVideoFormat(MediaFormat.MIMETYPE_VIDEO_AVC, w, h).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)
+ setInteger(MediaFormat.KEY_MAX_B_FRAMES, 0)
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
+ setInteger(MediaFormat.KEY_LATENCY, 1)
+ }
+ }
+ val codec = MediaCodec.createEncoderByType(MediaFormat.MIMETYPE_VIDEO_AVC)
+ codec.configure(format, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE)
+ return codec to codec.createInputSurface()
+ }
+
private fun drain(codec: MediaCodec, out: DataOutputStream) {
val info = MediaCodec.BufferInfo()
var parameters = ByteArray(0)
- while (running) {
- val index = codec.dequeueOutputBuffer(info, 100_000)
+ while (running && nextSize == null) {
+ val index = codec.dequeueOutputBuffer(info, 50_000)
if (index < 0) continue
val buffer = codec.getOutputBuffer(index)
if (buffer != null && info.size > 0) {
@@ -127,7 +176,7 @@ class AppDisplay(
out.write(bytes)
}
- private fun createDisplay(surface: Surface): VirtualDisplay {
+ private fun createDisplay(w: Int, h: Int, d: Int, 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
@@ -141,7 +190,24 @@ class AppDisplay(
// 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)
+ return manager.createVirtualDisplay("Nectarlink", w, h, d, surface, flags)
+ }
+
+ /** Hides the soft keyboard on this virtual display so typing from the PC never pops it up on the phone. */
+ private fun hideIme(display: Int) {
+ val hidden = runCatching {
+ val wmg = Class.forName("android.view.WindowManagerGlobal")
+ val wm = wmg.getMethod("getWindowManagerService").invoke(null) ?: return@runCatching false
+ wm.javaClass
+ .getMethod("setDisplayImePolicy", Int::class.javaPrimitiveType, Int::class.javaPrimitiveType)
+ .invoke(wm, display, DISPLAY_IME_POLICY_HIDE)
+ true
+ }.getOrDefault(false)
+ if (!hidden) {
+ runCatching {
+ Runtime.getRuntime().exec(arrayOf("wm", "set-display-ime-policy", display.toString(), "hide")).waitFor()
+ }
+ }
}
private fun launch(pkg: String, display: Int) {
@@ -153,11 +219,63 @@ class AppDisplay(
Runtime.getRuntime().exec(command).waitFor()
}
+ /** Stops the stream when the app on [display] finishes its last activity. */
+ private fun watchActivities(display: Int) {
+ Thread({
+ try {
+ Thread.sleep(1_500)
+ var seen = false
+ var emptyCount = 0
+ var ticks = 0
+ while (running) {
+ if (hasActivityOnDisplay(display)) {
+ seen = true
+ emptyCount = 0
+ } else if (seen || ticks >= 15) {
+ emptyCount++
+ if (emptyCount >= 2) {
+ System.err.println("the app on display $display closed")
+ running = false
+ break
+ }
+ }
+ ticks++
+ Thread.sleep(1_000)
+ }
+ } catch (_: InterruptedException) {
+ }
+ }, "app-display-watch").apply {
+ isDaemon = true
+ start()
+ }
+ }
+
+ /**
+ * Whether the display still has a visible task, asked of the activity
+ * manager (Android 12+). When it can't tell, the window stays open:
+ * closing someone's window by mistake is worse than a stale picture.
+ */
+ @SuppressLint("PrivateApi", "DiscouragedPrivateApi")
+ private fun hasActivityOnDisplay(display: Int): Boolean = runCatching {
+ val service = Class.forName("android.app.ActivityTaskManager").getMethod("getService").invoke(null)!!
+ val tasks = service.javaClass
+ .getMethod("getAllRootTaskInfosOnDisplay", Int::class.javaPrimitiveType)
+ .invoke(service, display) as List<*>
+ tasks.any { task ->
+ val visible = runCatching { task!!.javaClass.getField("visible").getBoolean(task) }.getOrDefault(true)
+ val children = runCatching { (task!!.javaClass.getField("childTaskIds").get(task) as IntArray).size }.getOrDefault(1)
+ visible && children > 0
+ }
+ }.getOrDefault(true)
+
companion object {
const val KIND_CONFIG = 0
const val KIND_FRAME = 1
const val KIND_KEYFRAME = 2
+ /** WindowManager.DISPLAY_IME_POLICY_HIDE. */
+ private const val DISPLAY_IME_POLICY_HIDE = 2
+
// DisplayManager.VIRTUAL_DISPLAY_FLAG_* (some hidden).
private const val PUBLIC = 1
private const val OWN_CONTENT_ONLY = 1 shl 3
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.kt
index efbd0c7..160ccba 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
@@ -113,12 +113,25 @@ object InputServer {
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))
windows.add(window)
- // Further lines: keyframe requests; the end of them closes the window.
+ // Further lines: keyframe or resize requests; the end of them closes the window.
Thread {
try {
while (true) {
val line = reader.nextLine() ?: break
- if (line == "K") window.requestKeyframe()
+ when {
+ line == "K" -> window.requestKeyframe()
+ line.startsWith("R ") -> {
+ val r = line.split(' ')
+ val rw = r.getOrNull(1)?.toIntOrNull()
+ val rh = r.getOrNull(2)?.toIntOrNull()
+ val rdpi = r.getOrNull(3)?.toIntOrNull()
+ if (rw != null && rh != null && rdpi != null &&
+ rw in 16..4096 && rh in 16..4096 && rdpi in 72..1000
+ ) {
+ window.resize(rw, rh, rdpi)
+ }
+ }
+ }
}
} catch (_: java.io.IOException) {
}
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.kt
index d59e389..af0bdd9 100644
--- a/android/app/src/main/kotlin/app/nectarlink/android/mirror/AppWindows.kt
+++ b/android/app/src/main/kotlin/app/nectarlink/android/mirror/AppWindows.kt
@@ -54,8 +54,10 @@ class AppWindows(
val pc: String,
val session: UInt,
val socket: Socket,
- val width: Int,
- val height: Int,
+ @Volatile var width: Int,
+ @Volatile var height: Int,
+ val dpi: Int,
+ val maxSize: Int,
) {
@Volatile var display: Int = -1
}
@@ -70,9 +72,10 @@ class AppWindows(
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 maxSize = options.maxSize.toInt().coerceIn(320, 1920)
+ val (width, height, dpi) = size(maxSize)
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)
+ val window = Window(pc, options.session, socket, width, height, dpi, maxSize)
windows.put(pc to options.session, window)?.let { runCatching { it.socket.close() } }
changed()
scope.launch(Dispatchers.IO) {
@@ -100,6 +103,8 @@ class AppWindows(
AppDisplay.KIND_CONFIG -> {
val fields = java.nio.ByteBuffer.wrap(data)
val (w, h) = fields.int to fields.int
+ window.width = w
+ window.height = h
window.display = fields.int
stream.send(VideoPacketKind.CONFIG, 0u, mirrorConfig(w.toUInt(), h.toUInt(), window.session))
}
@@ -150,6 +155,27 @@ class AppWindows(
}
}
+ /** The PC resized an app window: fit to encoder limits and tell the helper. */
+ fun resize(pc: String, session: UInt, width: Int, height: Int) {
+ val window = windows[pc to session] ?: return
+ val w = width.coerceAtLeast(240)
+ val h = height.coerceAtLeast(240)
+ val scale = minOf(1f, window.maxSize.toFloat() / max(w, h))
+ fun fit(v: Int) = max(240, ((v * scale) / 16).roundToInt() * 16)
+ val (newW, newH) = fit(w) to fit(h)
+ if (newW == window.width && newH == window.height) return
+ window.width = newW
+ window.height = newH
+ runCatching {
+ synchronized(window) {
+ window.socket.getOutputStream().apply {
+ write("R $newW $newH ${window.dpi}\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
diff --git a/core/nectarlink-cli/src/main.rs b/core/nectarlink-cli/src/main.rs
index 0140769..448078a 100644
--- a/core/nectarlink-cli/src/main.rs
+++ b/core/nectarlink-cli/src/main.rs
@@ -184,6 +184,9 @@ enum Command {
/// "x,y" in fractions of the screen (repeatable).
#[arg(long)]
tap: Vec<String>,
+ /// Resize the app window ("WxH", with --app) 2 s after the first frame.
+ #[arg(long)]
+ resize: Option<String>,
},
/// List the apps a paired phone can open in windows of their own.
Apps {
@@ -541,6 +544,13 @@ static SCREEN_ASKS: std::sync::OnceLock<tokio::sync::mpsc::UnboundedSender<(Devi
std::sync::OnceLock::new();
/// Whether `screen` offers apps in windows.
static SCREEN_APPS: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
+/// Active `screen` sessions: (session, pending resize (width, height), stream).
+type ScreenSession = (
+ u32,
+ std::sync::Arc<std::sync::Mutex<Option<(u32, u32)>>>,
+ std::sync::Arc<nectarlink_core::MirrorStream>,
+);
+static SCREEN_SESSIONS: std::sync::Mutex<Vec<ScreenSession>> = std::sync::Mutex::new(Vec::new());
/// The apps `screen --apps` offers.
const SAMPLE_APPS: &[(&str, &str)] = &[
("com.example.calendar", "Calendar"),
@@ -791,9 +801,38 @@ impl Platform for TerminalPlatform {
}
fn mirror_stop_requested(&self, _peer: &DeviceId, session: u32) {
println!("The PC stopped watching (session {session}).");
+ let mut sessions = SCREEN_SESSIONS.lock().unwrap();
+ sessions.retain(|(s, _, stream)| {
+ if *s == session {
+ stream.close();
+ false
+ } else {
+ true
+ }
+ });
+ }
+ fn mirror_resize_requested(&self, _peer: &DeviceId, session: u32, width: u32, height: u32) {
+ let (w, h) = ((width & !1).max(64), (height & !1).max(64));
+ println!("The PC resized session {session} to {w}x{h}.");
+ for (s, pending, _) in SCREEN_SESSIONS.lock().unwrap().iter() {
+ if *s == session {
+ *pending.lock().unwrap() = Some((w, h));
+ }
+ }
}
fn mirror_input(&self, _peer: &DeviceId, session: u32, input: nectarlink_core::MirrorInput) {
println!("Input on session {session}: {input:?}");
+ if session != 0 && matches!(&input, nectarlink_core::MirrorInput::Key { key } if key == "home") {
+ let mut sessions = SCREEN_SESSIONS.lock().unwrap();
+ sessions.retain(|(s, _, stream)| {
+ if *s == session {
+ stream.close();
+ false
+ } else {
+ true
+ }
+ });
+ }
}
fn phone_apps(&self) -> std::result::Result<Vec<nectarlink_core::PhoneApp>, String> {
if !SCREEN_APPS.load(std::sync::atomic::Ordering::Relaxed) {
@@ -1312,7 +1351,7 @@ async fn run(cli: &Cli, node: &Node) -> Result<()> {
);
}
}
- Command::Mirror { device, out, seconds, at, sound, app, tap } => {
+ Command::Mirror { device, out, seconds, at, sound, app, tap, resize } => {
let recording = std::sync::Arc::new(Recording::default());
*recording.file.lock().unwrap() =
Some(std::fs::File::create(out).context("can't create the file")?);
@@ -1349,6 +1388,13 @@ async fn run(cli: &Cli, node: &Node) -> Result<()> {
}
}
let started = std::time::Instant::now();
+ if let Some(dim) = resize {
+ tokio::time::sleep(std::time::Duration::from_secs(2)).await;
+ let (w, h) = dim.split_once('x').context("--resize takes WxH")?;
+ let (w, h): (u32, u32) = (w.trim().parse()?, h.trim().parse()?);
+ node.mirror_resize(id, session, w, h).await.context("resize not sent")?;
+ println!("Resized to {w}x{h}.");
+ }
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")?;
@@ -1362,7 +1408,16 @@ async fn run(cli: &Cli, node: &Node) -> Result<()> {
println!("Tapped {x},{y}.");
}
let left = std::time::Duration::from_secs(*seconds).saturating_sub(started.elapsed());
- tokio::time::sleep(left).await;
+ let _ = tokio::time::timeout(left, async {
+ loop {
+ if let Ok(NodeEvent::Mirroring { session: s, on: false, .. }) = events.recv().await
+ && s == session
+ {
+ break;
+ }
+ }
+ })
+ .await;
node.mirror_stop(id, session).await;
let RecordingStats { frames, keyframes, bytes, size } = *recording.stats.lock().unwrap();
let secs = started.elapsed().as_secs_f64();
@@ -1434,8 +1489,23 @@ async fn run(cli: &Cli, node: &Node) -> Result<()> {
continue;
}
};
+ let pending = std::sync::Arc::new(std::sync::Mutex::new(None));
+ {
+ let mut sessions = SCREEN_SESSIONS.lock().unwrap();
+ sessions.retain(|(s, _, old)| {
+ if *s == session {
+ old.close();
+ false
+ } else {
+ true
+ }
+ });
+ sessions.push((session, pending.clone(), mirror.clone()));
+ }
let units = units.clone();
- std::thread::spawn(move || stream_screen(&mirror, &units, width, height, fps, session));
+ std::thread::spawn(move || {
+ stream_screen(&mirror, &units, width, height, fps, session, &pending)
+ });
if let (true, Some((rate, channels, samples))) = (wants_sound, sound.clone()) {
match streamer.mirror_open_audio(pc).await {
Ok(stream) => {
@@ -2355,12 +2425,14 @@ fn stream_screen(
height: u32,
fps: u32,
session: u32,
+ pending: &std::sync::Mutex<Option<(u32, u32)>>,
) {
use nectarlink_core::{MirrorSend, PacketKind};
let config = nectarlink_core::MirrorConfig { codec: "h264".into(), width, height, session }.to_cbor();
if mirror.send(PacketKind::Config, 0, config) == MirrorSend::Closed {
return;
}
+ let keyframe = units.iter().find(|u| is_keyframe(u));
let frame = std::time::Duration::from_secs_f64(1.0 / f64::from(fps.max(1)));
let started = std::time::Instant::now();
let mut dropped = 0u32;
@@ -2369,8 +2441,20 @@ fn stream_screen(
if let Some(wait) = due.checked_duration_since(std::time::Instant::now()) {
std::thread::sleep(wait);
}
- let kind = if is_keyframe(unit) { PacketKind::Keyframe } else { PacketKind::Frame };
let time = started.elapsed().as_micros() as u64;
+ if let Some((w, h)) = pending.lock().unwrap().take() {
+ let cfg = nectarlink_core::MirrorConfig { codec: "h264".into(), width: w, height: h, session }
+ .to_cbor();
+ if mirror.send(PacketKind::Config, time, cfg) == MirrorSend::Closed {
+ break;
+ }
+ if let Some(kf) = keyframe
+ && mirror.send(PacketKind::Keyframe, time, kf.clone()) == MirrorSend::Closed
+ {
+ break;
+ }
+ }
+ let kind = if is_keyframe(unit) { PacketKind::Keyframe } else { PacketKind::Frame };
match mirror.send(kind, time, unit.clone()) {
MirrorSend::Queued => {}
MirrorSend::NeedKeyframe | MirrorSend::Dropped => dropped += 1,
diff --git a/core/nectarlink-core/src/config.rs b/core/nectarlink-core/src/config.rs
index 7fa8873..06ca75c 100644
--- a/core/nectarlink-core/src/config.rs
+++ b/core/nectarlink-core/src/config.rs
@@ -161,6 +161,17 @@ pub trait Platform: Send + Sync + 'static {
/// The PC's decoder needs a fresh start: encode a keyframe next.
fn mirror_keyframe_requested(&self, _peer: &nectarlink_protocol::DeviceId, _session: u32) {}
+ /// The PC resized an app window (`session` != 0): resize its display and
+ /// restart its encoder at `width × height` pixels.
+ fn mirror_resize_requested(
+ &self,
+ _peer: &nectarlink_protocol::DeviceId,
+ _session: u32,
+ _width: u32,
+ _height: 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> {
diff --git a/core/nectarlink-core/src/lib.rs b/core/nectarlink-core/src/lib.rs
index 33629db..4b5c9fd 100644
--- a/core/nectarlink-core/src/lib.rs
+++ b/core/nectarlink-core/src/lib.rs
@@ -44,9 +44,9 @@ pub use nectarlink_protocol::{
DeviceId, PacketKind,
messages::{
Battery, CLIP_MAX_BYTES, CallControls, CallLogEntry, CallState, Contact, ContactNumber, DeviceInfo,
- DeviceKind, MediaPlayer, MirrorAudioConfig, MirrorConfig, MirrorInput, MirrorStart, Notification,
- NotificationAction, PhoneApp, PhotoNew as Photo, PowerLevel, SmsMessage, SmsPart, SmsThread,
- TouchAction,
+ DeviceKind, MediaPlayer, MirrorAudioConfig, MirrorConfig, MirrorInput, MirrorResize, MirrorStart,
+ Notification, NotificationAction, PhoneApp, PhotoNew as Photo, PowerLevel, SmsMessage, SmsPart,
+ SmsThread, TouchAction,
calls::{
CONTROL as CALLS_CONTROL, DIAL as CALLS_DIAL, IN_CALL as CALLS_IN_CALL, LOG as CALLS_LOG,
SHOW as CALLS_SHOW, STATE as CALLS_STATE,
diff --git a/core/nectarlink-core/src/mirror.rs b/core/nectarlink-core/src/mirror.rs
index b8065ad..93ea674 100644
--- a/core/nectarlink-core/src/mirror.rs
+++ b/core/nectarlink-core/src/mirror.rs
@@ -23,8 +23,8 @@ use iroh::endpoint::{RecvStream, SendStream, VarInt};
use nectarlink_protocol::{
DeviceId, Envelope, ErrorCode, PacketKind,
messages::{
- MirrorAudioConfig, MirrorConfig, MirrorInput, MirrorSession, MirrorStart, PhoneApp, PhoneApps,
- StreamHeader, mirror, types,
+ MirrorAudioConfig, MirrorConfig, MirrorInput, MirrorResize, MirrorSession, MirrorStart, PhoneApp,
+ PhoneApps, StreamHeader, mirror, types,
},
read_video_packet, video_packet_header, write_frame,
};
@@ -113,6 +113,24 @@ pub(crate) async fn request_keyframe(session: &Session, mirroring: u32) {
}
}
+/// Resize an app window's display (`mirroring` != 0) on a phone.
+pub(crate) async fn resize(
+ shared: &Shared,
+ session: &Session,
+ mirroring: u32,
+ width: u32,
+ height: u32,
+) -> Result<()> {
+ if !shared.toggle_on(&session.peer, TOGGLE) {
+ return Err(Error::Denied);
+ }
+ let msg = MirrorResize { session: mirroring, width, height };
+ if !msg.is_valid() {
+ return Err(Error::Protocol("invalid resize".into()));
+ }
+ session.send(Envelope::new(types::MIRROR_RESIZE, &msg)?).await
+}
+
/// The apps a phone can open in windows of their own, by name.
pub(crate) async fn apps(shared: &Shared, session: &Session) -> Result<Vec<PhoneApp>> {
if !shared.toggle_on(&session.peer, TOGGLE) {
@@ -271,6 +289,16 @@ pub(crate) async fn handle(shared: &Arc<Shared>, session: &Arc<Session>, env: &E
let MirrorSession { session: mirroring } = env.body()?;
tokio::task::spawn_blocking(move || platform.mirror_keyframe_requested(&peer, mirroring));
}
+ types::MIRROR_RESIZE => {
+ let resize: MirrorResize = env.body()?;
+ let allowed = shared.toggle_on(&peer, TOGGLE)
+ && shared.local_capabilities().iter().any(|c| c == mirror::VIRTUAL_DISPLAY);
+ if allowed && resize.is_valid() {
+ tokio::task::spawn_blocking(move || {
+ platform.mirror_resize_requested(&peer, resize.session, resize.width, resize.height);
+ });
+ }
+ }
types::MIRROR_INPUT => {
let input: MirrorInput = env.body()?;
let MirrorSession { session: mirroring } = env.body()?;
@@ -340,6 +368,9 @@ pub enum MirrorSend {
pub struct MirrorStream {
queue: mpsc::Sender<(PacketKind, u64, Vec<u8>)>,
closed: Arc<AtomicBool>,
+ /// Wakes the sending task when the stream is closed, so it finishes the
+ /// stream even if no more packets come.
+ stop: Arc<tokio::sync::Notify>,
/// Frames are being dropped until a keyframe.
resyncing: Mutex<bool>,
/// Sound: each packet stands alone, so a dropped one needs no keyframe.
@@ -384,6 +415,7 @@ impl MirrorStream {
/// Ends the stream (the phone stopped sharing).
pub fn close(&self) {
self.closed.store(true, Ordering::Release);
+ self.stop.notify_one();
}
pub fn is_closed(&self) -> bool {
@@ -408,6 +440,8 @@ pub(crate) async fn open(shared: &Arc<Shared>, session: &Session, audio: bool) -
mpsc::channel::<(PacketKind, u64, Vec<u8>)>(if audio { AUDIO_QUEUE } else { QUEUE });
let closed = Arc::new(AtomicBool::new(false));
let done = closed.clone();
+ let stop = Arc::new(tokio::sync::Notify::new());
+ let stopped = stop.clone();
tokio::spawn(async move {
let mut ended = Box::pin(async move {
// The PC stops reading (STOP_SENDING) when it's done watching.
@@ -416,6 +450,7 @@ pub(crate) async fn open(shared: &Arc<Shared>, session: &Session, audio: bool) -
loop {
let next = tokio::select! {
_ = &mut ended => break,
+ _ = stopped.notified() => break,
next = packets.recv() => next,
};
let Some((kind, time, data)) = next else { break };
@@ -434,7 +469,7 @@ pub(crate) async fn open(shared: &Arc<Shared>, session: &Session, audio: bool) -
done.store(true, Ordering::Release);
let _ = send.finish();
});
- Ok(MirrorStream { queue, closed, resyncing: Mutex::new(false), audio })
+ Ok(MirrorStream { queue, closed, stop, resyncing: Mutex::new(false), audio })
}
impl Shared {
@@ -468,8 +503,13 @@ mod tests {
#[tokio::test(flavor = "multi_thread")]
async fn a_full_queue_drops_frames_until_a_keyframe() {
let (queue, mut packets) = mpsc::channel(2);
- let stream =
- MirrorStream { queue, closed: Arc::default(), resyncing: Mutex::new(false), audio: false };
+ let stream = MirrorStream {
+ queue,
+ closed: Arc::default(),
+ stop: Arc::default(),
+ resyncing: Mutex::new(false),
+ audio: false,
+ };
let send = |kind| tokio::task::block_in_place(|| stream.send(kind, 0, vec![1]));
assert_eq!(send(PacketKind::Keyframe), MirrorSend::Queued);
assert_eq!(send(PacketKind::Frame), MirrorSend::Queued);
@@ -487,8 +527,13 @@ mod tests {
#[tokio::test(flavor = "multi_thread")]
async fn sound_drops_only_what_doesnt_fit() {
let (queue, mut packets) = mpsc::channel(1);
- let stream =
- MirrorStream { queue, closed: Arc::default(), resyncing: Mutex::new(false), audio: true };
+ let stream = MirrorStream {
+ queue,
+ closed: Arc::default(),
+ stop: Arc::default(),
+ resyncing: Mutex::new(false),
+ audio: true,
+ };
let send = |kind| tokio::task::block_in_place(|| stream.send(kind, 0, vec![1]));
assert_eq!(send(PacketKind::Frame), MirrorSend::Queued);
assert_eq!(send(PacketKind::Frame), MirrorSend::Dropped, "full");
diff --git a/core/nectarlink-core/src/node.rs b/core/nectarlink-core/src/node.rs
index 1c6b029..54bfb99 100644
--- a/core/nectarlink-core/src/node.rs
+++ b/core/nectarlink-core/src/node.rs
@@ -198,9 +198,13 @@ impl Shared {
lock(&self.links).get(peer).cloned().unwrap_or(LinkState::Offline { last_seen })
}
- /// Publishes the session's current path and round-trip time.
+ /// Publishes the session's current path and round-trip time, if it's
+ /// still the peer's session (a replaced one has nothing to say).
pub fn publish_online(&self, session: &Session) {
- self.set_link(session.peer, LinkState::Online { path: session.path(), rtt_ms: session.rtt_ms() });
+ let sessions = lock(&self.sessions);
+ if sessions.get(&session.peer).is_some_and(|current| std::ptr::eq(current.as_ref(), session)) {
+ self.set_link(session.peer, LinkState::Online { path: session.path(), rtt_ms: session.rtt_ms() });
+ }
}
/// Our direct addresses, for pairing links. Waits briefly for the
@@ -365,16 +369,18 @@ impl Shared {
}
fn on_session_end(&self, ended: &Arc<Session>) {
- let removed = {
- let mut sessions = lock(&self.sessions);
- match sessions.get(&ended.peer) {
- Some(current) if Arc::ptr_eq(current, ended) => sessions.remove(&ended.peer).is_some(),
- _ => false,
+ let paired = self.store.is_paired(&ended.peer).unwrap_or(false);
+ let mut sessions = lock(&self.sessions);
+ let current = sessions.get(&ended.peer).is_some_and(|current| Arc::ptr_eq(current, ended));
+ if current {
+ sessions.remove(&ended.peer);
+ if paired {
+ tracing::info!(peer = %ended.peer.short(), "disconnected");
+ // Still under the lock: a new session for the peer can't
+ // register (and say it's online) until this is said, so a
+ // stale "offline" never lands after a fresh "online".
+ self.set_link(ended.peer, LinkState::Offline { last_seen: Some(crate::now_unix()) });
}
- };
- if removed && self.store.is_paired(&ended.peer).unwrap_or(false) {
- tracing::info!(peer = %ended.peer.short(), "disconnected");
- self.set_link(ended.peer, LinkState::Offline { last_seen: Some(crate::now_unix()) });
}
}
@@ -952,6 +958,12 @@ impl Node {
}
}
+ /// Resizes an app window's display (`mirroring` != 0) on a phone.
+ pub async fn mirror_resize(&self, peer: DeviceId, mirroring: u32, width: u32, height: u32) -> Result<()> {
+ let session = self.connected(&peer)?;
+ crate::mirror::resize(&self.shared, &session, mirroring, width, height).await
+ }
+
/// The PC's mouse and keyboard on a phone's mirrored screen or app window.
pub async fn mirror_input(
&self,
diff --git a/core/nectarlink-core/tests/two_devices.rs b/core/nectarlink-core/tests/two_devices.rs
index 4f307c7..e6c3f3e 100644
--- a/core/nectarlink-core/tests/two_devices.rs
+++ b/core/nectarlink-core/tests/two_devices.rs
@@ -105,6 +105,15 @@ impl Platform for RecordingPlatform {
fn mirror_keyframe_requested(&self, _peer: &nectarlink_core::DeviceId, session: u32) {
self.mirror_asks.lock().unwrap().push(format!("keyframe {session}"));
}
+ fn mirror_resize_requested(
+ &self,
+ _peer: &nectarlink_core::DeviceId,
+ session: u32,
+ width: u32,
+ height: u32,
+ ) {
+ self.mirror_asks.lock().unwrap().push(format!("resize {session} {width}x{height}"));
+ }
fn mirror_input(
&self,
_peer: &nectarlink_core::DeviceId,
@@ -1386,6 +1395,9 @@ async fn phone_apps_open_in_windows_of_their_own() {
})
.await;
assert_eq!(session, 7);
+ assert!(matches!(pc.node.mirror_resize(phone_id, 0, 800, 600).await, Err(Error::Protocol(_))));
+ assert!(matches!(pc.node.mirror_resize(phone_id, 7, 10, 600).await, Err(Error::Protocol(_))));
+ pc.node.mirror_resize(phone_id, 7, 1024, 768).await.unwrap();
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;
@@ -1396,10 +1408,29 @@ async fn phone_apps_open_in_windows_of_their_own() {
.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"] {
+ for wanted in
+ ["start 1280 com.example.chat as 7", "resize 7 1024x768", "Key(back) on 7", "keyframe 7", "stop 7"]
+ {
assert!(asks.iter().any(|a| a == wanted), "{wanted}: {asks:?}");
}
assert_eq!(*pc.platform.mirror_asks.lock().unwrap(), ["sink 7"]);
+
+ // The app closes on the phone: its window's stream ends at once, even
+ // with no more pictures to send.
+ with_timeout("start again", pc.node.mirror_start(phone_id, app(8))).await.unwrap();
+ let stream = Arc::new(with_timeout("open again", phone.node.mirror_open(pc_id)).await.unwrap());
+ let config = nectarlink_core::MirrorConfig { codec: "h264".into(), width: 720, height: 1280, session: 8 };
+ let sender = stream.clone();
+ tokio::task::spawn_blocking(move || sender.send(PacketKind::Config, 0, config.to_cbor())).await.unwrap();
+ wait_for(&mut pc, "showing 8", |e| {
+ matches!(e, NodeEvent::Mirroring { session: 8, on: true, .. }).then_some(())
+ })
+ .await;
+ stream.close();
+ wait_for(&mut pc, "ended 8", |e| {
+ matches!(e, NodeEvent::Mirroring { session: 8, on: false, .. }).then_some(())
+ })
+ .await;
}
#[tokio::test(flavor = "multi_thread")]
diff --git a/core/nectarlink-ffi/src/lib.rs b/core/nectarlink-ffi/src/lib.rs
index b7214cb..0ee2f8c 100644
--- a/core/nectarlink-ffi/src/lib.rs
+++ b/core/nectarlink-ffi/src/lib.rs
@@ -1308,6 +1308,8 @@ pub trait Platform: Send + Sync {
fn mirror_stop_requested(&self, pc_id: String, session: u32);
/// The PC needs a keyframe.
fn mirror_keyframe_requested(&self, pc_id: String, session: u32);
+ /// The PC resized an app window (`session` != 0) to `width × height`.
+ fn mirror_resize_requested(&self, pc_id: String, session: u32, width: u32, height: u32);
/// The PC's mouse or keyboard on the mirrored screen (only while this
/// phone offers `mirror.input`) or an app window. Return quickly.
fn mirror_input(&self, pc_id: String, session: u32, input: MirrorInputEvent);
@@ -1406,6 +1408,9 @@ impl core::Platform for PlatformAdapter {
fn mirror_keyframe_requested(&self, peer: &DeviceId, session: u32) {
self.0.mirror_keyframe_requested(peer.to_string(), session);
}
+ fn mirror_resize_requested(&self, peer: &DeviceId, session: u32, width: u32, height: u32) {
+ self.0.mirror_resize_requested(peer.to_string(), session, width, height);
+ }
fn mirror_input(&self, peer: &DeviceId, session: u32, input: core::MirrorInput) {
self.0.mirror_input(peer.to_string(), session, input.into());
}
diff --git a/core/nectarlink-protocol/src/messages.rs b/core/nectarlink-protocol/src/messages.rs
index 862bd2f..829c07e 100644
--- a/core/nectarlink-protocol/src/messages.rs
+++ b/core/nectarlink-protocol/src/messages.rs
@@ -58,6 +58,7 @@ pub mod types {
pub const MIRROR_START: &str = "mirror.start";
pub const MIRROR_STOP: &str = "mirror.stop";
pub const MIRROR_KEYFRAME: &str = "mirror.keyframe";
+ pub const MIRROR_RESIZE: &str = "mirror.resize";
pub const MIRROR_INPUT: &str = "mirror.input";
pub const MIRROR_APPS: &str = "mirror.apps";
}
@@ -561,6 +562,22 @@ pub struct MirrorSession {
pub session: u32,
}
+/// Body of `mirror.resize`: resize an app window's display (`session != 0`).
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
+pub struct MirrorResize {
+ pub session: u32,
+ pub width: u32,
+ pub height: u32,
+}
+
+impl MirrorResize {
+ pub fn is_valid(&self) -> bool {
+ self.session != mirror::SCREEN
+ && (64..=4096).contains(&self.width)
+ && (64..=4096).contains(&self.height)
+ }
+}
+
/// An app a PC can open in a window (in a `mirror.apps` answer).
#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PhoneApp {
diff --git a/desktop/app/build.rs b/desktop/app/build.rs
index 5559c9a..7150209 100644
--- a/desktop/app/build.rs
+++ b/desktop/app/build.rs
@@ -213,7 +213,9 @@ fn main() {
])
.build();
- // The C++ window code calls DWM and user32 directly.
+ // The C++ window code calls DWM, Shell property store, and user32 directly.
println!("cargo:rustc-link-lib=dwmapi");
+ println!("cargo:rustc-link-lib=ole32");
+ println!("cargo:rustc-link-lib=shell32");
println!("cargo:rustc-link-lib=user32");
}
diff --git a/desktop/app/cpp/video_view.cpp b/desktop/app/cpp/video_view.cpp
index b2df454..217da22 100644
--- a/desktop/app/cpp/video_view.cpp
+++ b/desktop/app/cpp/video_view.cpp
@@ -2,11 +2,21 @@
#include "video_view.h"
#include <QtCore/QHash>
+#include <QtCore/QUrl>
+#include <QtGui/QIcon>
#include <QtGui/QImage>
+#include <QtGui/QPixmap>
#include <QtQuick/QQuickWindow>
#include <QtQuick/QSGSimpleTextureNode>
#include <QtQuick/QSGTexture>
+#ifdef _WIN32
+#include <windows.h>
+#include <propkey.h>
+#include <propsys.h>
+#include <shobjidl.h>
+#endif
+
#include <algorithm>
#include <mutex>
#include <vector>
@@ -78,6 +88,67 @@ void VideoView::setStream(const QString &stream)
frameArrived();
}
+void VideoView::setWindowIcon(const QString &icon)
+{
+ if (icon == m_windowIcon)
+ return;
+ m_windowIcon = icon;
+ emit windowIconChanged();
+ applyWindowChrome();
+}
+
+void VideoView::setWindowAppId(const QString &appId)
+{
+ if (appId == m_windowAppId)
+ return;
+ m_windowAppId = appId;
+ emit windowAppIdChanged();
+ applyWindowChrome();
+}
+
+void VideoView::itemChange(ItemChange change, const ItemChangeData &value)
+{
+ QQuickItem::itemChange(change, value);
+ if (change == ItemSceneChange && value.window) {
+ connect(value.window, &QWindow::visibleChanged, this, [this](bool) { applyWindowChrome(); });
+ applyWindowChrome();
+ }
+}
+
+void VideoView::applyWindowChrome()
+{
+ QQuickWindow *win = window();
+ if (!win)
+ return;
+#ifdef _WIN32
+ if (!m_windowAppId.isEmpty()) {
+ if (HWND hwnd = reinterpret_cast<HWND>(win->winId())) {
+ IPropertyStore *store = nullptr;
+ if (SUCCEEDED(SHGetPropertyStoreForWindow(hwnd, IID_PPV_ARGS(&store))) && store) {
+ PROPVARIANT pv{};
+ pv.vt = VT_LPWSTR;
+ pv.pwszVal = const_cast<LPWSTR>(reinterpret_cast<LPCWSTR>(m_windowAppId.utf16()));
+ store->SetValue(PKEY_AppUserModel_ID, pv);
+ store->Commit();
+ store->Release();
+ }
+ }
+ }
+#endif
+ if (!m_windowIcon.isEmpty()) {
+ const QUrl url(m_windowIcon);
+ const QString path = url.isLocalFile() ? url.toLocalFile() : m_windowIcon;
+ const QImage img(path);
+ if (!img.isNull()) {
+ QIcon icon;
+ for (int sz : {16, 20, 24, 32, 40, 48, 64, 256}) {
+ icon.addPixmap(QPixmap::fromImage(img.scaled(sz, sz, Qt::KeepAspectRatio, Qt::SmoothTransformation)));
+ }
+ win->setIcon(icon);
+ }
+ }
+}
+
QRectF VideoView::pictureRect() const
{
if (m_frameSize.isEmpty())
diff --git a/desktop/app/cpp/video_view.h b/desktop/app/cpp/video_view.h
index 666dbe4..1bd6c6a 100644
--- a/desktop/app/cpp/video_view.h
+++ b/desktop/app/cpp/video_view.h
@@ -24,6 +24,10 @@ class VideoView : public QQuickItem
Q_PROPERTY(QSize frameSize READ frameSize NOTIFY frameSizeChanged)
// Pictures shown so far, for a frame rate readout.
Q_PROPERTY(quint64 frames READ frames NOTIFY framesChanged)
+ // Optional PNG icon file URL/path for the containing window and taskbar button.
+ Q_PROPERTY(QString windowIcon READ windowIcon WRITE setWindowIcon NOTIFY windowIconChanged)
+ // Optional Windows AppUserModelID so each app window gets its own taskbar identity.
+ Q_PROPERTY(QString windowAppId READ windowAppId WRITE setWindowAppId NOTIFY windowAppIdChanged)
public:
explicit VideoView(QQuickItem *parent = nullptr);
@@ -33,6 +37,10 @@ public:
void setStream(const QString &stream);
QSize frameSize() const { return m_frameSize; }
quint64 frames() const { return m_frames; }
+ QString windowIcon() const { return m_windowIcon; }
+ void setWindowIcon(const QString &icon);
+ QString windowAppId() const { return m_windowAppId; }
+ void setWindowAppId(const QString &appId);
// Where the picture is drawn in the item (letterboxed).
Q_INVOKABLE QRectF pictureRect() const;
@@ -41,18 +49,24 @@ signals:
void streamChanged();
void frameSizeChanged();
void framesChanged();
+ void windowIconChanged();
+ void windowAppIdChanged();
protected:
QSGNode *updatePaintNode(QSGNode *old, UpdatePaintNodeData *) override;
+ void itemChange(ItemChange change, const ItemChangeData &value) override;
private:
Q_INVOKABLE void frameArrived();
+ void applyWindowChrome();
QString m_stream;
QSize m_frameSize;
quint64 m_frames = 0;
// The serial of the picture on screen.
quint64 m_shown = 0;
+ QString m_windowIcon;
+ QString m_windowAppId;
};
// The latest picture of `stream`: `width` x `height`, 32-bit BGRX rows.
diff --git a/desktop/app/qml/MirrorWindow.qml b/desktop/app/qml/MirrorWindow.qml
index 22cf17c..c8688bc 100644
--- a/desktop/app/qml/MirrorWindow.qml
+++ b/desktop/app/qml/MirrorWindow.qml
@@ -28,29 +28,88 @@ Window {
minimumHeight: 240
// A phone-shaped window the first time a picture arrives (portrait or
- // landscape), within the screen.
+ // landscape), within the screen, or restored to where the user left it.
readonly property size frame: video.frameSize
property bool sized: false
+ property bool readyForResize: false
+
+ Timer {
+ id: resizeTimer
+ interval: 300
+ repeat: false
+ onTriggered: {
+ if (!win.info.app || !win.sized)
+ return
+ Mirror.saveGeometry(win.mirrorKey, win.x, win.y, win.width, win.height)
+ if (win.phase === "showing")
+ Mirror.resize(win.mirrorKey, win.width, win.height)
+ }
+ }
+
+ Timer {
+ id: moveTimer
+ interval: 300
+ repeat: false
+ onTriggered: {
+ if (win.info.app && win.sized)
+ Mirror.saveGeometry(win.mirrorKey, win.x, win.y, win.width, win.height)
+ }
+ }
+
+ onWidthChanged: if (info.app && sized && readyForResize) resizeTimer.restart()
+ onHeightChanged: if (info.app && sized && readyForResize) resizeTimer.restart()
+ onXChanged: if (info.app && sized && readyForResize) moveTimer.restart()
+ onYChanged: if (info.app && sized && readyForResize) moveTimer.restart()
+ onPhaseChanged: if (phase === "showing" && info.app && sized) resizeTimer.restart()
+
onFrameChanged: {
if (frame.width <= 0)
return
- const maxH = Screen.desktopAvailableHeight * 0.85
- const maxW = Screen.desktopAvailableWidth * 0.85
+ const availW = Screen.desktopAvailableWidth > 0 ? Screen.desktopAvailableWidth : 1920
+ const availH = Screen.desktopAvailableHeight > 0 ? Screen.desktopAvailableHeight : 1080
+ if (!sized && info.app && (info.savedWidth || 0) >= 240 && (info.savedHeight || 0) >= 240) {
+ readyForResize = false
+ const w = Math.max(240, Math.min(Math.round(availW * 0.95), info.savedWidth))
+ const h = Math.max(240, Math.min(Math.round(availH * 0.95), info.savedHeight))
+ width = w
+ height = h
+ if (info.savedX !== null && info.savedX !== undefined && info.savedY !== null && info.savedY !== undefined) {
+ x = Math.max(0, Math.min(availW - w, info.savedX))
+ y = Math.max(0, Math.min(availH - h, info.savedY))
+ }
+ sized = true
+ Qt.callLater(() => { win.readyForResize = true })
+ return
+ }
+ const maxH = availH * 0.85
+ const maxW = availW * 0.85
const scale = Math.min(maxH / frame.height, maxW / frame.width, 1)
- if (!sized || Math.abs(width / height - frame.width / frame.height) > 0.05) {
+ if (!sized || (!info.app && Math.abs(width / height - frame.width / frame.height) > 0.05)) {
+ readyForResize = false
width = Math.round(frame.width * scale)
height = Math.round(frame.height * scale)
sized = true
+ if (info.app)
+ Mirror.saveGeometry(mirrorKey, x, y, width, height)
+ Qt.callLater(() => { win.readyForResize = true })
}
}
width: 420
height: 860
- onClosing: Mirror.stop(mirrorKey)
+ onClosing: {
+ if (info.app && sized)
+ Mirror.saveGeometry(mirrorKey, x, y, width, height)
+ Mirror.stop(mirrorKey)
+ }
VideoView {
id: video
anchors.fill: parent
stream: win.mirrorKey
+ windowIcon: win.info.icon || ""
+ windowAppId: win.info.app && (win.info.pkg || "").length > 0
+ ? "Nectarlink.App." + (win.info.device || "").slice(0, 8) + "." + win.info.pkg
+ : ""
focus: true
// Where on the phone's screen a point in the window is (0 to 1).
@@ -200,9 +259,16 @@ Window {
visible: win.phase !== "ended"
width: 28; height: 28
}
+ RoundedImage {
+ anchors.horizontalCenter: parent.horizontalCenter
+ visible: win.phase === "ended" && win.info.app === true && (win.info.icon || "").length > 0
+ width: 40; height: 40
+ radius: 10
+ source: win.info.icon || ""
+ }
Icon {
anchors.horizontalCenter: parent.horizontalCenter
- visible: win.phase === "ended"
+ visible: win.phase === "ended" && !(win.info.app === true && (win.info.icon || "").length > 0)
width: 32; height: 32
path: Icons.mirror
color: Theme.surfaceContentVariant
@@ -225,16 +291,16 @@ Window {
text: win.phase === "asking" && !win.info.app
? qsTr("Tap the notification on %1, then choose to share the entire screen.").arg(win.deviceName)
: win.phase === "ended" ? ((win.info.reason || "").length > 0 ? win.info.reason
- : win.info.app ? qsTr("The phone closed the window.")
+ : win.info.app ? qsTr("The app closed on %1.").arg(win.deviceName)
: qsTr("The phone stopped sharing its screen."))
: ""
}
Button {
anchors.horizontalCenter: parent.horizontalCenter
- visible: win.phase === "ended" && !win.info.app
+ visible: win.phase === "ended"
variant: "tonal"
- text: qsTr("Try again")
- onClicked: Mirror.start(win.info.device)
+ text: win.info.app ? qsTr("Open again") : qsTr("Try again")
+ onClicked: Mirror.reopen(win.mirrorKey)
}
}
}
diff --git a/desktop/app/qml/components/AppsSheet.qml b/desktop/app/qml/components/AppsSheet.qml
index a688e1e..055d8c9 100644
--- a/desktop/app/qml/components/AppsSheet.qml
+++ b/desktop/app/qml/components/AppsSheet.qml
@@ -25,6 +25,11 @@ Sheet {
return []
try { return JSON.parse(Mirror.apps) } catch (e) { return [] }
}
+ readonly property var recent: {
+ if (Mirror.appsDevice !== deviceId)
+ return []
+ try { return JSON.parse(Mirror.recentApps) } 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)
@@ -135,10 +140,90 @@ Sheet {
}
}
+ // Recently opened on this PC.
+ Column {
+ id: recentSection
+ width: parent.width
+ visible: sheet.loadState === "ready" && sheet.query.length === 0 && sheet.recent.length > 0
+ spacing: 8
+
+ Txt {
+ role: "label"
+ muted: true
+ text: qsTr("Recent")
+ }
+
+ Row {
+ width: parent.width
+ spacing: 4
+ Repeater {
+ model: sheet.recent
+ delegate: Item {
+ id: recentCell
+ required property var modelData
+ width: Math.min(96, Math.floor((recentSection.width - 20) / Math.max(1, sheet.recent.length)))
+ height: 82
+ Accessible.role: Accessible.Button
+ Accessible.name: modelData.label
+ Accessible.onPressAction: sheet.launch(modelData)
+
+ Rectangle {
+ anchors.fill: parent
+ anchors.margins: 2
+ radius: Theme.radiusMd
+ color: Theme.surfaceContent
+ opacity: recentTap.pressed ? 0.12 : (recentHover.hovered ? 0.06 : 0)
+ }
+ Column {
+ anchors.centerIn: parent
+ width: parent.width - 8
+ spacing: 6
+ Item {
+ anchors.horizontalCenter: parent.horizontalCenter
+ width: 38; height: 38
+ Image {
+ id: recentIcon
+ anchors.fill: parent
+ source: recentCell.modelData.icon
+ sourceSize: Qt.size(76, 76)
+ smooth: true
+ mipmap: true
+ visible: status === Image.Ready
+ }
+ Avatar {
+ anchors.fill: parent
+ visible: recentIcon.status !== Image.Ready
+ name: recentCell.modelData.label
+ }
+ }
+ Txt {
+ width: parent.width
+ horizontalAlignment: Text.AlignHCenter
+ role: "bodySmall"
+ text: recentCell.modelData.label
+ elide: Text.ElideRight
+ maximumLineCount: 1
+ }
+ }
+ HoverHandler { id: recentHover; cursorShape: Qt.PointingHandCursor }
+ TapHandler { id: recentTap; onTapped: sheet.launch(recentCell.modelData) }
+ }
+ }
+ }
+
+ Divider {}
+
+ Txt {
+ role: "label"
+ muted: true
+ text: qsTr("All apps")
+ }
+ }
+
GridView {
id: grid
width: parent.width
- height: Math.min(contentHeight, 420)
+ height: Math.min(contentHeight, recentSection.visible ? 300 : 420)
visible: sheet.loadState === "ready" && sheet.shown.length > 0
clip: true
model: sheet.shown
diff --git a/desktop/app/src/bridge/mirror.rs b/desktop/app/src/bridge/mirror.rs
index 1cca2ee..bad2d0a 100644
--- a/desktop/app/src/bridge/mirror.rs
+++ b/desktop/app/src/bridge/mirror.rs
@@ -35,6 +35,9 @@ pub mod qobject {
#[qproperty(QString, apps_device, cxx_name = "appsDevice")]
/// Its apps, as JSON: `[{ pkg, label, icon }]` (icon: a file URL or "").
#[qproperty(QString, apps)]
+ /// The apps opened from this PC most recently on `appsDevice`, as JSON:
+ /// `[{ pkg, label, icon }]` (up to 6).
+ #[qproperty(QString, recent_apps, cxx_name = "recentApps")]
/// "", "loading", "ready" or "failed".
#[qproperty(QString, apps_state, cxx_name = "appsState")]
/// Why they couldn't be loaded.
@@ -53,9 +56,19 @@ pub mod qobject {
#[qinvokable]
#[cxx_name = "startApp"]
fn start_app(self: &Mirror, device: &QString, pkg: &QString, label: &QString);
+ /// Reopens an ended window (the screen or an app window).
+ #[qinvokable]
+ fn reopen(self: &Mirror, key: &QString);
/// Closes a window, ending its mirroring.
#[qinvokable]
fn stop(self: &Mirror, key: &QString);
+ /// Resizes an app window's display on the phone.
+ #[qinvokable]
+ fn resize(self: &Mirror, key: &QString, width: u32, height: u32);
+ /// Saves an app window's position and size on this PC.
+ #[qinvokable]
+ #[cxx_name = "saveGeometry"]
+ fn save_geometry(self: &Mirror, key: &QString, x: i32, y: i32, width: u32, height: u32);
/// Loads a phone's apps (into `apps`).
#[qinvokable]
#[cxx_name = "loadApps"]
@@ -89,6 +102,7 @@ pub struct MirrorRust {
muted: bool,
apps_device: QString,
apps: QString,
+ recent_apps: QString,
apps_state: QString,
apps_error: QString,
}
@@ -105,7 +119,9 @@ impl cxx_qt::Initialize for qobject::Mirror {
impl qobject::Mirror {
fn refresh(mut self: Pin<&mut Self>) {
- let hub = &crate::core_host::host().hub;
+ let host = crate::core_host::host();
+ let hub = &host.hub;
+ let data_dir = &host.data_dir;
let windows: Vec<serde_json::Value> = mirror::windows()
.into_iter()
.map(|(window, shown)| {
@@ -125,17 +141,31 @@ impl qobject::Mirror {
Phase::Showing => ("showing", String::new()),
Phase::Ended(reason) => ("ended", reason.unwrap_or_default()),
};
+ let pkg = shown.pkg.clone().unwrap_or_default();
+ let icon = (!pkg.is_empty())
+ .then(|| crate::icons::existing(data_dir, &pkg))
+ .flatten()
+ .as_deref()
+ .map(crate::icons::file_url)
+ .unwrap_or_default();
+ let geom = (!pkg.is_empty()).then(|| mirror::geometry(&window.device, &pkg)).flatten();
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()),
+ "pkg": pkg,
+ "icon": icon,
"app": shown.app.is_some(),
"phase": phase,
"reason": reason,
"canControl": control,
"sound": window.session == MIRROR_SCREEN && mirror::has_sound(&window.device),
+ "savedX": geom.map(|g| g.x),
+ "savedY": geom.map(|g| g.y),
+ "savedWidth": geom.map(|g| g.width).unwrap_or(0),
+ "savedHeight": geom.map(|g| g.height).unwrap_or(0),
})
})
.collect();
@@ -152,6 +182,19 @@ impl qobject::Mirror {
Some(Apps::Failed(why)) => ("failed", Vec::new(), why),
Some(Apps::Ready(apps)) => ("ready", apps, String::new()),
};
+ let recent_pkgs = mirror::recent_apps(&device);
+ let recent: Vec<serde_json::Value> = recent_pkgs
+ .iter()
+ .filter_map(|pkg| apps.iter().find(|a| &a.pkg == pkg))
+ .take(6)
+ .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();
let apps: Vec<serde_json::Value> = apps
.into_iter()
.map(|a| {
@@ -162,6 +205,7 @@ impl qobject::Mirror {
})
})
.collect();
+ self.as_mut().set_recent_apps(QString::from(&serde_json::Value::Array(recent).to_string()));
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));
@@ -180,12 +224,30 @@ impl qobject::Mirror {
}
}
+ pub fn reopen(&self, key: &QString) {
+ if let Some(window) = Window::parse(&String::from(key)) {
+ mirror::reopen(window);
+ }
+ }
+
pub fn stop(&self, key: &QString) {
if let Some(window) = Window::parse(&String::from(key)) {
mirror::stop(window);
}
}
+ pub fn resize(&self, key: &QString, width: u32, height: u32) {
+ if let Some(window) = Window::parse(&String::from(key)) {
+ mirror::resize(window, width, height);
+ }
+ }
+
+ pub fn save_geometry(&self, key: &QString, x: i32, y: i32, width: u32, height: u32) {
+ if let Some(window) = Window::parse(&String::from(key)) {
+ mirror::save_geometry(window, x, y, width, height);
+ }
+ }
+
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());
diff --git a/desktop/app/src/icons.rs b/desktop/app/src/icons.rs
index 49a84bc..ca536cd 100644
--- a/desktop/app/src/icons.rs
+++ b/desktop/app/src/icons.rs
@@ -46,6 +46,12 @@ pub fn file_url(path: &Path) -> String {
format!("file:///{}", path.to_string_lossy().replace('\\', "/"))
}
+/// Returns the cached PNG icon path for `app` if it exists on disk.
+pub fn existing(data_dir: &Path, app: &str) -> Option<PathBuf> {
+ let path = icons_dir(data_dir).join(file_name(app));
+ path.is_file().then_some(path)
+}
+
#[cfg(test)]
mod tests {
use super::*;
diff --git a/desktop/app/src/mirror.rs b/desktop/app/src/mirror.rs
index c3da0b6..3d6c735 100644
--- a/desktop/app/src/mirror.rs
+++ b/desktop/app/src/mirror.rs
@@ -105,12 +105,66 @@ pub struct App {
pub icon: Option<PathBuf>,
}
-#[derive(Debug, Default)]
+/// Remembered window position and size on this PC for an app window.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
+pub struct WindowGeometry {
+ pub x: i32,
+ pub y: i32,
+ pub width: u32,
+ pub height: u32,
+}
+
+#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
+struct SavedWindows {
+ /// Keyed by `<device>/<pkg>`.
+ #[serde(default)]
+ geometry: HashMap<String, WindowGeometry>,
+ /// Keyed by `<device>`, most recently opened `pkg` first.
+ #[serde(default)]
+ recent: HashMap<String, Vec<String>>,
+}
+
+impl SavedWindows {
+ fn path() -> PathBuf {
+ core_host::host().data_dir.join("app-windows.json")
+ }
+
+ fn load() -> Self {
+ std::fs::read_to_string(Self::path())
+ .ok()
+ .and_then(|s| serde_json::from_str(&s).ok())
+ .unwrap_or_default()
+ }
+
+ fn save(&self) {
+ let path = Self::path();
+ if let Ok(json) = serde_json::to_string_pretty(self) {
+ let tmp = path.with_extension("json.tmp");
+ if std::fs::write(&tmp, json).is_ok() {
+ let _ = std::fs::rename(&tmp, &path);
+ }
+ }
+ }
+}
+
+#[derive(Debug)]
struct State {
windows: HashMap<Window, Shown>,
/// Phones whose sound is coming in.
sound: HashSet<DeviceId>,
apps: HashMap<DeviceId, Apps>,
+ saved: SavedWindows,
+}
+
+impl Default for State {
+ fn default() -> Self {
+ Self {
+ windows: HashMap::new(),
+ sound: HashSet::new(),
+ apps: HashMap::new(),
+ saved: SavedWindows::load(),
+ }
+ }
}
/// The user turned the phones' sound off on this PC (until turned on).
@@ -164,6 +218,39 @@ pub fn windows() -> Vec<(Window, Shown)> {
all
}
+/// Remembered window position and size for `(device, pkg)`.
+pub fn geometry(device: &DeviceId, pkg: &str) -> Option<WindowGeometry> {
+ state(|s| s.saved.geometry.get(&format!("{device}/{pkg}")).copied())
+}
+
+/// Saves an app window's position and size on this PC.
+pub fn save_geometry(window: Window, x: i32, y: i32, width: u32, height: u32) {
+ if window.session == MIRROR_SCREEN || width < 200 || height < 200 {
+ return;
+ }
+ state(|s| {
+ let Some(pkg) = s.windows.get(&window).and_then(|w| w.pkg.clone()) else { return };
+ let key = format!("{}/{pkg}", window.device);
+ let geom = WindowGeometry { x, y, width, height };
+ if s.saved.geometry.insert(key, geom) != Some(geom) {
+ s.saved.save();
+ }
+ });
+}
+
+/// Package names of apps opened on `device` from this PC, most recent first.
+pub fn recent_apps(device: &DeviceId) -> Vec<String> {
+ state(|s| s.saved.recent.get(&device.to_string()).cloned().unwrap_or_default())
+}
+
+fn record_recent(s: &mut State, device: &DeviceId, pkg: &str) {
+ let list = s.saved.recent.entry(device.to_string()).or_default();
+ list.retain(|p| p != pkg);
+ list.insert(0, pkg.to_owned());
+ list.truncate(12);
+ s.saved.save();
+}
+
/// Asks the phone for its screen.
pub fn start(device: DeviceId) {
let window = Window::screen(device);
@@ -173,24 +260,70 @@ pub fn start(device: DeviceId) {
}
/// Opens one of the phone's apps in a window of its own (or does nothing
-/// when it's already open).
+/// when it's already open; reuses an ended window for that app).
pub fn start_app(device: DeviceId, pkg: String, label: String) {
- let open = state(|s| {
- s.windows.iter().any(|(w, shown)| {
+ let window = state(|s| {
+ if s.windows.iter().any(|(w, shown)| {
w.device == device
&& shown.pkg.as_deref() == Some(pkg.as_str())
&& matches!(shown.phase, Phase::Asking | Phase::Showing)
- })
+ }) {
+ return None;
+ }
+ record_recent(s, &device, &pkg);
+ let ended = s
+ .windows
+ .iter()
+ .find(|(w, shown)| w.device == device && shown.pkg.as_deref() == Some(pkg.as_str()))
+ .map(|(w, _)| *w);
+ let window =
+ ended.unwrap_or_else(|| Window { device, session: NEXT_SESSION.fetch_add(1, Ordering::Relaxed) });
+ s.windows.insert(window, Shown { phase: Phase::Asking, app: Some(label), pkg: Some(pkg.clone()) });
+ Some(window)
});
- if open {
+ let Some(window) = window else { return };
+ ffi::video_clear(&window.key());
+ request(window, MirrorStart { audio: false, session: window.session, app: Some(pkg), ..OPTIONS });
+}
+
+/// Reopens a mirroring window that ended (the screen or an app window).
+pub fn reopen(window: Window) {
+ if window.session == MIRROR_SCREEN {
+ start(window.device);
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()) })
+ let pkg = state(|s| {
+ let shown = s.windows.get_mut(&window)?;
+ let pkg = shown.pkg.clone()?;
+ shown.phase = Phase::Asking;
+ record_recent(s, &window.device, &pkg);
+ Some(pkg)
+ });
+ let Some(pkg) = pkg else { return };
+ ffi::video_clear(&window.key());
+ request(window, MirrorStart { audio: false, session: window.session, app: Some(pkg), ..OPTIONS });
+}
+
+/// Resizes an app window's display on the phone (`width` and `height` are the
+/// window's logical dimensions on the PC).
+pub fn resize(window: Window, width: u32, height: u32) {
+ if window.session == MIRROR_SCREEN || width < 120 || height < 120 {
+ return;
+ }
+ let (mut w, mut h) = (width.saturating_mul(2), height.saturating_mul(2));
+ let longest = w.max(h);
+ if longest > OPTIONS.max_size {
+ w = (u64::from(w) * u64::from(OPTIONS.max_size) / u64::from(longest)) as u32;
+ h = (u64::from(h) * u64::from(OPTIONS.max_size) / u64::from(longest)) as u32;
+ }
+ let w = (w & !1).clamp(240, 4096);
+ let h = (h & !1).clamp(240, 4096);
+ let Some(node) = core_host::node() else { return };
+ core_host::spawn(async move {
+ if let Err(e) = node.mirror_resize(window.device, window.session, w, h).await {
+ tracing::debug!(error = %e, "resize didn't reach the phone");
+ }
});
- request(window, MirrorStart { audio: false, session, app: Some(pkg), ..OPTIONS });
}
fn request(window: Window, options: MirrorStart) {
@@ -227,7 +360,17 @@ pub fn stop(window: Window) {
pub fn on_event(event: &NodeEvent) {
match event {
NodeEvent::Mirroring { device, session, on: true } => {
- set_phase(Window { device: *device, session: *session }, Phase::Showing);
+ let window = Window { device: *device, session: *session };
+ set_phase(window, Phase::Showing);
+ if *session != MIRROR_SCREEN {
+ let saved = state(|s| {
+ let pkg = s.windows.get(&window).and_then(|w| w.pkg.as_deref())?;
+ s.saved.geometry.get(&format!("{device}/{pkg}")).copied()
+ });
+ if let Some(geom) = saved {
+ resize(window, geom.width, geom.height);
+ }
+ }
}
// Closed here: nothing to say. Stopped on the phone: say so.
NodeEvent::Mirroring { device, session, on: false } => {
@@ -440,6 +583,9 @@ fn decode(window: Window, items: &Receiver<Item>, waiting: &AtomicUsize) {
while let Ok(item) = items.recv() {
match item {
Item::Config(config) => {
+ if size != (0, 0) && size != (config.width, config.height) {
+ decoder.flush();
+ }
size = (config.width, config.height);
need_keyframe = true;
}
@@ -465,8 +611,14 @@ fn decode(window: Window, items: &Receiver<Item>, waiting: &AtomicUsize) {
if let (Some(picture), false) = (pictures.last(), behind) {
let converted = Instant::now();
let (w, h) = if size.0 > 0 { size } else { (picture.width, picture.height) };
+ let (src_w, src_h) = (w.min(picture.width), h.min(picture.height));
let bgrx = to_bgrx(picture, w, h);
- ffi::video_frame(&stream, w.min(picture.width), h.min(picture.height), &bgrx);
+ if (src_w, src_h) == (w, h) || src_w == 0 || src_h == 0 {
+ ffi::video_frame(&stream, src_w, src_h, &bgrx);
+ } else {
+ let scaled = scale_bgrx(&bgrx, src_w, src_h, w, h);
+ ffi::video_frame(&stream, w, h, &scaled);
+ }
stats.shown(decoded, converted.elapsed());
} else {
stats.skipped();
@@ -478,6 +630,20 @@ fn decode(window: Window, items: &Receiver<Item>, waiting: &AtomicUsize) {
ffi::video_clear(&stream);
}
+fn scale_bgrx(src: &[u8], src_w: u32, src_h: u32, dst_w: u32, dst_h: u32) -> Vec<u8> {
+ let mut dst = vec![0u8; (dst_w * dst_h * 4) as usize];
+ for y in 0..dst_h {
+ let sy = ((u64::from(y) * u64::from(src_h)) / u64::from(dst_h)) as usize;
+ let src_row = &src[sy * (src_w as usize * 4)..(sy + 1) * (src_w as usize * 4)];
+ let dst_row = &mut dst[(y as usize) * (dst_w as usize * 4)..(y as usize + 1) * (dst_w as usize * 4)];
+ for x in 0..dst_w as usize {
+ let sx = ((x as u64 * u64::from(src_w)) / u64::from(dst_w)) as usize;
+ dst_row[x * 4..x * 4 + 4].copy_from_slice(&src_row[sx * 4..sx * 4 + 4]);
+ }
+ }
+ dst
+}
+
/// Decode and conversion times, logged now and then.
struct Stats {
since: Instant,
diff --git a/docs/protocol/mirror.md b/docs/protocol/mirror.md
index 3a70fc9..6eee04a 100644
--- a/docs/protocol/mirror.md
+++ b/docs/protocol/mirror.md
@@ -33,6 +33,7 @@ t = "mirror.start" id = n b = { max_size: uint, fps: uint, bitrate: uint,
? session: uint, ? app: text }
t = "mirror.stop" id = n b = { ? session: uint }
t = "mirror.keyframe" b = { ? session: uint }
+t = "mirror.resize" b = { session: uint, width: uint, height: uint }
t = "mirror.apps" id = n
t = "mirror.apps" re = n b = { apps: [{ pkg: text, label: text, ? icon: bytes }] }
t = "ok" re = n
@@ -53,6 +54,9 @@ means 0, so PCs and phones that predate sessions work as before.
the phone stops sharing and finishes it.
- `mirror.keyframe` (PC → phone): the decoder lost its place; send a
keyframe next. Not answered.
+- `mirror.resize` (PC → phone): resize an app window's display (`session != 0`)
+ to `width × height` pixels. Not answered; the phone sends a new `config`
+ packet on the video stream once its encoder restarts at the new size.
## 3. The video stream
@@ -148,13 +152,20 @@ window of its own, beside whatever the phone's screen shows:
- `mirror.input` gains `? session: uint`: input for an app window goes to
its display. App windows take input whenever the phone offers
`mirror.virtual_display`; the screen still needs `mirror.input`.
+- `mirror.resize` with `session`, `width` and `height` resizes that window's
+ virtual display (clamped to even dimensions within encoder limits, keeping
+ density sensible) and restarts its H.264 encoder, sending a new `config`
+ packet and keyframe so the app re-lays out at the new aspect ratio.
- `mirror.stop` and `mirror.keyframe` with a `session` are about that
window; stopping one closes the app's display (the app closes with it).
+ When the app closes its last activity on the phone, the phone finishes
+ that session's video stream.
On Android, the Elevated helper (running as the shell user) makes a
-virtual display for each window with an H.264 encoder drawing from it, and
-starts the app there; the phone shows a notification while any app window
-is open, with a button to close them all.
+virtual display for each window with its display IME policy set to hide the
+soft keyboard, attaches an H.264 encoder drawing from it, and starts the app
+there; the phone shows a notification while any app window is open, with a
+button to close them all.
## 7. Latency over completeness