All your machines, one app. For you and your AI agents: agent sessions, desktops, files, logs and GitHub across your Macs, Linux and Windows machines, with an MCP server.
Monitors, real and virtual; split terminals; Nerd Font icons
Adib Hanna68b6183c0571
diff --git a/AGENTS.md b/AGENTS.mdindex e319a12..eedc8b7 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -114,6 +114,7 @@ The CLI equivalents are `muxen session ls|start|read|send|attach|restart|rename|- `machine_connection` says how Muxen reaches a machine: `direct` (QUIC), `ssh` (one live ssh connection) or `none`, with a measured round trip and the `network` it goes over ("Local network", "Tailscale", ...). `direct_connection(machine_id, enabled)` pairs for direct connections (it installs a user service on the machine; only when asked).- Tailscale, when it's on this computer, keeps machines reachable away from home: Muxen uses the local network when the machine is on it and Tailscale otherwise, and switches by itself when the network changes. A machine's `tailnet` (in `get_machine` and `machine_connection`) says whether Tailscale sees it online and whether traffic goes peer-to-peer (`path: "direct"`) or through a slower relay (`"relay"`). An `unreachable.kind` of `"tailscale-off"` means Tailscale is off or signed out on this computer: tell the user to turn it on; Muxen never changes Tailscale's settings.- `desktop_screenshot(machine_id)` returns a picture of the machine's screen (Linux with X11, and Macs). `desktop_input(machine_id, events)` clicks, types, scrolls and presses keys there, in that picture's pixels: look first, act, then look again. It's the user's real screen: only when asked, and never type passwords.+- A machine can have several monitors. `desktop_displays(machine_id)` lists them (each with an `id`; Muxen's virtual ones have `virtual: true`); pass `display` to `desktop_screenshot` and `desktop_input` to use one. `desktop_add_display(machine_id, width?, height?, name?)` adds a virtual monitor to the desktop, as if another screen were plugged in, and `desktop_remove_display(machine_id, display)` takes it away. `desktop_set_display(machine_id, display, width?, height?, scale?)` changes a monitor's resolution (one of its `modes`) or the desktop's scale on it (`scales`; on Linux X11 one scale for all monitors): a 4K monitor at scale 2 reads like 1080p and stays sharp. They change the user's real desktop: only when asked.## Cloud machinesdiff --git a/README.md b/README.mdindex 6c0f1cf..b658701 100644--- a/README.md+++ b/README.md@@ -172,7 +172,8 @@ The MCP server has these tools:| `list_ssh_hosts` | Hosts to add: your `~/.ssh/config`, your Tailscale network, and this network. || `list_files`, `copy_files`, `cancel_operation` | Browse a folder on a machine; copy files and folders between machines; stop a copy. || `machine_connection`, `direct_connection` | How a machine is reached (direct, ssh, which network, Tailscale's view); pair it for direct connections. |-| `desktop_screenshot`, `desktop_input` | Look at a Linux machine's screen; click, type and scroll there. |+| `desktop_screenshot`, `desktop_input` | Look at a machine's screen (or one monitor of it); click, type and scroll there. |+| `desktop_displays`, `desktop_add_display`, `desktop_remove_display`, `desktop_set_display` | A machine's monitors; add or remove virtual ones, change their resolution or scale. || `session_list`, `session_start`, `session_read`, `session_send`, `session_rename`, `session_stop` | Agent sessions on the machines. || `github_inbox`, `github_repos`, `github_repo`, `github_item`, `local_checkouts`, `git_sync`, … | The user's GitHub, and git checkouts on the machines. || `workspace_create`, `workspace_list`, `workspace_get` | Check out a machine as a work environment; see what exists. |@@ -304,9 +305,10 @@ muxen checkouts --machine beelink --path ~/code/api --git pullStart an AI agent on one of your machines and come back to it whenever you like, from the app, from your own terminal, or through another agent.-- **Keeps running.** Sessions live in Muxen's agent on the machine (`~/.muxen/bin/muxen-agent`), a small background program that holds each session's terminal, the way tmux would. Closing the app, sleeping your laptop or losing the network only detaches; the agent keeps working until you end the session.+- **Keeps running.** Sessions live in Muxen's agent on the machine (`~/.muxen/bin/muxen-agent`), a small background program that holds each session's terminal, the way tmux would. Closing the app, sleeping your laptop or losing the network only detaches; the agent keeps working until you end the session, and reopening it shows the screen as it is with its recent scrollback. A restart of the machine ends its sessions, as with tmux.- **Nothing to install.** When Muxen connects to a machine it uploads the agent build for that OS and CPU (macOS and Linux, x86_64 and arm64; static binaries, about 1 MB) and keeps it up to date. Windows machines run sessions in the app's terminal for now, so they end with the window.-- **A real terminal in the app.** Everything goes to the agent: Esc, Ctrl-C, Tab, arrows, Option/Shift+Enter for newlines. ⌘C copies a selection, ⌘V pastes, the wheel scrolls back. Right-click a machine for a new terminal or agent session.+- **Split panes.** ⌘D splits a terminal to the right, ⇧⌘D below it (or the buttons in its header): a new shell on the same machine, in the same folder. ⌥⌘← and ⌥⌘→ move between panes, or click one. Each pane is a session of its own, so it keeps running like any other; type `exit` to close it, or × on its bar to take it out of the split. Splits come back when you reopen Muxen.+- **A real terminal in the app.** Everything goes to the agent: Esc, Ctrl-C, Tab, arrows, Option/Shift+Enter for newlines. ⌘C copies a selection, ⌘V pastes, the wheel scrolls back. Nerd Font icons (Neovim's file icons, prompt glyphs) show with any terminal font: Muxen brings the symbols. Right-click a machine for a new terminal or agent session.- **Names you choose.** Right-click a machine or a session and pick **Rename…** (or ⇧⌘P › Rename on its page). A machine keeps its id, so its runners, sessions and favorites stay with it; `config.toml` gets `id = "<old id>"` when the new name would give a different one. A session's title is kept by the agent on its machine (`~/.muxen/titles.json`), so every Muxen sees it; an empty title goes back to the one it started with.- **Your environment.** The agent starts in your login shell, in the folder you pick, so nvm/fnm/asdf and the CLI's own login work as they do in your terminal. Muxen finds which agent CLIs each machine has: `claude`, `codex`, `opencode`, `gemini`, `amp`.- **Agents can drive agents.** `session_start`, `session_read` (the screen as text), `session_send` (type into it) and `session_stop` are MCP tools and CLI commands too.@@ -334,6 +336,16 @@ Muxen first reaches a machine with `ssh`, installs its small agent there, and fr**Desktop.** On a Linux machine with an X11 desktop, or a Mac, **Show desktop** (on its page, or its right-click menu) shows its screen live and sends your mouse and keyboard to it. On Linux ⌘ works as Ctrl; on a Mac it stays ⌘. An open desktop is listed under its machine in the sidebar (and keeps streaming while you look elsewhere); close it there.+**Monitors, real and virtual.** A machine with more than one monitor gets a picker above its desktop: show one monitor at a time (on Linux, or all of them). **Add monitor** (or **Add virtual monitor…** in the machine's right-click menu) plugs in a monitor that isn't there, the way [DeskPad](https://github.com/Stengo/DeskPad) does on a Mac: pick a name and a size (720p to 4K), and it joins the desktop like a real one, to the right of the others. Windows move onto it, the machine's own tools (System Settings, RustDesk) see it, and while the machine's desktop is open, Muxen lists it under the Desktop item in the sidebar to open it directly. It starts at the main monitor's size and offers every common one (720p to 4K). Above a monitor, pick its resolution, and on Linux desktops that offer it, its scale: 200% makes things twice as big and just as sharp, so a 4K monitor reads like 1080p (the stream is always the screen's own size, so it stays crisp). Right-click a monitor (in the picker or the sidebar) to rename or remove it, and in the all-screens view, click a monitor's name to open it. On Cinnamon each virtual monitor gets copies of the main monitor's panels (menu, clock, dock with the same pinned apps), so it's usable on its own. It stays until you remove it (**Remove monitor**) or the machine restarts. Handy on a machine with no screen (a dummy HDMI plug, a server), or to give an agent a monitor of its own. On a Mac it's a CGVirtualDisplay. On Linux (X11) it's a software dummy plug: Muxen plugs a made-up monitor (at the size you picked) into a video output with nothing connected, and the desktop sets it up like a real one. That takes root, so when sudo wants a password Muxen asks for yours, only then, sends it to sudo over its encrypted connection, and keeps it in memory only until you quit. Nothing is installed.++```sh+muxen desktop displays beelink # its monitors (virtual ones marked)+muxen desktop add beelink --size 2560x1440 # another monitor, "Display 2"+muxen desktop shot beelink --display DisplayPort-0 # a screenshot of just that one+muxen desktop set beelink HDMI-A-0 --size 3840x2160 --scale 2 # 4K, things twice as big+muxen desktop remove beelink DisplayPort-0+```+- **Macs** ask once, on their own screen, to allow `muxen-agent` under Privacy & Security › Screen Recording (to see it) and Accessibility (to control it). The screen goes over ssh to the agent's background service in your session there, so no other network permission is needed. Release builds sign the agent with a Developer ID, so the permissions survive updates.- Pick 720p, 1080p, 1440p, 4K or Native from the bar above it. On a local network it starts at the screen's own resolution, further away at 1080p.diff --git a/agent/Cargo.toml b/agent/Cargo.tomlindex 55c5996..d8baab4 100644--- a/agent/Cargo.toml+++ b/agent/Cargo.toml@@ -22,7 +22,7 @@ tokio = { version = "1", features = ["rt-multi-thread", "net", "io-util", "macro# The desktop view (`screen`): X11 capture and input on Linux, JPEG frames.[target.'cfg(target_os = "linux")'.dependencies]-x11rb = { version = "0.13", features = ["xtest", "shm", "xfixes"] }+x11rb = { version = "0.13", features = ["xtest", "shm", "xfixes", "randr"] }[target.'cfg(any(target_os = "linux", target_os = "macos"))'.dependencies]jpeg-encoder = "0.6"diff --git a/agent/build.rs b/agent/build.rsindex e9a11a4..2c121eb 100644--- a/agent/build.rs+++ b/agent/build.rs@@ -7,7 +7,7 @@ fn main() {return;}cc::Build::new().file("src/mac_screen.m").flag("-fobjc-arc").flag("-mmacosx-version-min=12.3").compile("muxen_screen");- for framework in ["CoreGraphics", "CoreMedia", "CoreVideo", "Foundation"] {+ for framework in ["AppKit", "CoreGraphics", "CoreMedia", "CoreVideo", "Foundation"] {println!("cargo:rustc-link-lib=framework={framework}");}// Weak: the agent still runs (without a desktop) on macOS before 12.3.diff --git a/agent/src/client.rs b/agent/src/client.rsindex d397c22..23dcc3f 100644--- a/agent/src/client.rs+++ b/agent/src/client.rs@@ -92,6 +92,11 @@ pub fn handle(req: &Value) -> Value {},"start" => request(&req, true),"rename" => rename(&req),+ "displays" => crate::displays::list(),+ "display_create" => crate::displays::create(&req),+ "display_remove" => crate::displays::remove(&req),+ "display_rename" => crate::displays::rename(&req),+ "display_set" => crate::displays::set(&req),_ => request(&req, false),}}diff --git a/agent/src/desktop.rs b/agent/src/desktop.rsindex 68e1520..d957f9c 100644--- a/agent/src/desktop.rs+++ b/agent/src/desktop.rs@@ -70,15 +70,18 @@ pub fn session_env() -> Option<Vec<(String, String)>> {Some(Vec::new())}-/// `muxen-agent screen [fps] [quality] [max_width] [tiles|frames]`: streams-/// the screen on stdout and applies input from stdin until either closes.+/// `muxen-agent screen [fps] [quality] [max_width] [tiles|frames] [display]`:+/// streams a screen on stdout and applies input from stdin until either+/// closes. `display` is one from `displays` (see displays.rs); without it, the+/// whole desktop (Linux) or the main display (a Mac).pub fn run(args: &[String]) -> i32 {let num = |i: usize, default: u32| args.get(i).and_then(|a| a.parse::<u32>().ok()).unwrap_or(default);let (fps, quality, max_width) = (num(0, 30).clamp(1, 60), num(1, 75).clamp(20, 95), num(2, 1920).max(320));let tiles = args.get(3).map(String::as_str) == Some("tiles");+ let display = args.get(4).map(String::as_str).filter(|d| !d.is_empty() && *d != "main");#[cfg(target_os = "linux")]{- match x11::X11::open() {+ match x11::X11::open(display) {Ok(screen) => stream(screen, fps, quality as u8, max_width, tiles),Err(e) => {hello(&serde_json::json!({ "error": e }));@@ -88,7 +91,15 @@ pub fn run(args: &[String]) -> i32 {}#[cfg(target_os = "macos")]{- match mac::Mac::open(fps, max_width) {+ let id = match display.map(|d| d.parse::<u32>()) {+ None => 0,+ Some(Ok(id)) => id,+ Some(Err(_)) => {+ hello(&serde_json::json!({ "error": format!("No display called {}.", display.unwrap_or_default()) }));+ return 1;+ }+ };+ match mac::Mac::open(fps, max_width, id) {Ok(screen) => stream(screen, fps, quality as u8, max_width, tiles),Err(e) => {hello(&serde_json::json!({ "error": e }));@@ -98,7 +109,7 @@ pub fn run(args: &[String]) -> i32 {}#[cfg(not(any(target_os = "linux", target_os = "macos")))]{- let _ = (fps, quality, max_width, tiles);+ let _ = (fps, quality, max_width, tiles, display);hello(&serde_json::json!({ "error": "Showing the desktop works on Linux and macOS so far." }));1}@@ -377,19 +388,56 @@ mod x11 {pub struct X11 {conn: RustConnection,root: u32,+ /// The part of the desktop shown: one monitor's area, or all of it.+ ox: i16,+ oy: i16,sw: usize,sh: usize,shm: Option<(u32, *mut u8, usize)>,scratch: Vec<u8>,/// keysym → (keycode, needs shift)keys: HashMap<u32, (u8, bool)>,+ /// The monitor shown (None: all of them), and when its place was last checked.+ monitor: Option<String>,+ checked: std::time::Instant,+ /// Keys and buttons pressed and not yet let go: let go when the stream+ /// ends, so none stays held (a key held down freezes the desktop's input).+ pressed: Vec<u8>,+ buttons: Vec<u8>,+ }++ impl Drop for X11 {+ fn drop(&mut self) {+ for code in self.pressed.drain(..) {+ let _ = self.conn.xtest_fake_input(KEY_RELEASE_EVENT, code, 0, self.root, 0, 0, 0);+ }+ for b in self.buttons.drain(..) {+ let _ = self.conn.xtest_fake_input(BUTTON_RELEASE_EVENT, b, 0, self.root, 0, 0, 0);+ }+ let _ = self.conn.flush();+ }+ }++ /// Where a monitor is on the desktop (None: the whole desktop), right now.+ fn area(conn: &RustConnection, root: u32, monitor: Option<&str>) -> Result<(i16, i16, usize, usize), String> {+ use x11rb::protocol::randr::ConnectionExt as _;+ let Some(name) = monitor else {+ let g = conn.get_geometry(root).map_err(|e| e.to_string())?.reply().map_err(|e| e.to_string())?;+ return Ok((0, 0, g.width as usize, g.height as usize));+ };+ let monitors = conn.randr_get_monitors(root, true).ok().and_then(|c| c.reply().ok()).map(|r| r.monitors).unwrap_or_default();+ let found = monitors.into_iter().find(|m| conn.get_atom_name(m.name).ok().and_then(|c| c.reply().ok()).is_some_and(|a| a.name == name.as_bytes()));+ let m = found.ok_or_else(|| format!("No display called {name} here (it may have been turned off)."))?;+ Ok((m.x, m.y, m.width as usize, m.height as usize))}impl X11 {- pub fn open() -> Result<X11, String> {+ /// The desktop, or one monitor of it (a RandR monitor's name; "all": everything).+ pub fn open(monitor: Option<&str>) -> Result<X11, String> {let (conn, screen_num) = x11rb::connect(None).map_err(|e| format!("Can't reach the desktop ({e}). Is someone logged in to a graphical session?"))?;- let screen = &conn.setup().roots[screen_num];- let (root, sw, sh) = (screen.root, screen.width_in_pixels as usize, screen.height_in_pixels as usize);+ let root = conn.setup().roots[screen_num].root;+ let monitor = monitor.filter(|m| *m != "all").map(str::to_string);+ let (ox, oy, sw, sh) = area(&conn, root, monitor.as_deref())?;let shm = attach_shm(&conn, sw * sh * 4);let mut keys: HashMap<u32, (u8, bool)> = HashMap::new();let (min, max) = (conn.setup().min_keycode, conn.setup().max_keycode);@@ -403,7 +451,7 @@ mod x11 {}}}- Ok(X11 { conn, root, sw, sh, shm, scratch: Vec::new(), keys })+ Ok(X11 { conn, root, ox, oy, sw, sh, shm, scratch: Vec::new(), keys, monitor, checked: std::time::Instant::now(), pressed: Vec::new(), buttons: Vec::new() })}}@@ -431,16 +479,27 @@ mod x11 {fn grab(&mut self) -> Option<Option<&[u8]>> {use x11rb::protocol::shm::ConnectionExt as _;+ // Monitors get resized and moved: follow one that moved; one that+ // changed size (or went) ends the stream, for one at its new size.+ if self.checked.elapsed() >= std::time::Duration::from_secs(1) {+ self.checked = std::time::Instant::now();+ let (ox, oy, sw, sh) = area(&self.conn, self.root, self.monitor.as_deref()).ok()?;+ if (sw, sh) != (self.sw, self.sh) {+ eprintln!("screen: the monitor is now {sw}x{sh}");+ return None;+ }+ (self.ox, self.oy) = (ox, oy);+ }let (w, h) = (self.sw as u16, self.sh as u16);if let Some((seg, addr, size)) = self.shm {- if self.conn.shm_get_image(self.root, 0, 0, w, h, !0, ImageFormat::Z_PIXMAP.into(), seg, 0).ok().and_then(|c| c.reply().ok()).is_some() {+ if self.conn.shm_get_image(self.root, self.ox, self.oy, w, h, !0, ImageFormat::Z_PIXMAP.into(), seg, 0).ok().and_then(|c| c.reply().ok()).is_some() {return Some(Some(unsafe { std::slice::from_raw_parts(addr, size) }));}// Shared memory stopped working: copy through the socket from now on.eprintln!("screen: shared-memory capture failed; using GetImage");self.shm = None;}- self.scratch = self.conn.get_image(ImageFormat::Z_PIXMAP, self.root, 0, 0, w, h, !0).ok()?.reply().ok()?.data;+ self.scratch = self.conn.get_image(ImageFormat::Z_PIXMAP, self.root, self.ox, self.oy, w, h, !0).ok()?.reply().ok()?.data;Some(Some(self.scratch.as_slice()))}@@ -451,7 +510,8 @@ mod x11 {fn apply(&mut self, e: &Value, frame: (usize, usize)) {let (conn, root, keys) = (&self.conn, self.root, &self.keys);let scale = (self.sw as f64 / frame.0 as f64, self.sh as f64 / frame.1 as f64);- let at = |e: &Value| ((e["x"].as_f64().unwrap_or(0.) * scale.0) as i16, (e["y"].as_f64().unwrap_or(0.) * scale.1) as i16);+ let (ox, oy) = (self.ox, self.oy);+ let at = |e: &Value| ((e["x"].as_f64().unwrap_or(0.) * scale.0) as i16 + ox, (e["y"].as_f64().unwrap_or(0.) * scale.1) as i16 + oy);let fake = |kind: u8, detail: u8, x: i16, y: i16| {let _ = conn.xtest_fake_input(kind, detail, 0, root, x, y, 0);};@@ -464,7 +524,12 @@ mod x11 {let (x, y) = at(e);fake(MOTION_NOTIFY_EVENT, 0, x, y);let b = e["b"].as_u64().unwrap_or(1).clamp(1, 9) as u8;- fake(if e["down"].as_bool().unwrap_or(false) { BUTTON_PRESS_EVENT } else { BUTTON_RELEASE_EVENT }, b, 0, 0);+ let down = e["down"].as_bool().unwrap_or(false);+ fake(if down { BUTTON_PRESS_EVENT } else { BUTTON_RELEASE_EVENT }, b, 0, 0);+ self.buttons.retain(|x| *x != b);+ if down {+ self.buttons.push(b);+ }}"scroll" => {let (x, y) = at(e);@@ -504,9 +569,13 @@ mod x11 {let sym = e["keysym"].as_u64().unwrap_or(0) as u32;// Letters arrive lowercase; shift comes as its own key.let found = keys.get(&sym).or_else(|| char::from_u32(sym).map(|c| c.to_ascii_lowercase() as u32).and_then(|s| keys.get(&s)));- if let Some((code, _)) = found {+ if let Some(&(code, _)) = found {let down = e["down"].as_bool().unwrap_or(false);- fake(if down { KEY_PRESS_EVENT } else { KEY_RELEASE_EVENT }, *code, 0, 0);+ fake(if down { KEY_PRESS_EVENT } else { KEY_RELEASE_EVENT }, code, 0, 0);+ self.pressed.retain(|x| *x != code);+ if down {+ self.pressed.push(code);+ }}}_ => {}@@ -525,10 +594,10 @@ mod mac {type FrameFn = extern "C" fn(*mut std::ffi::c_void, *const u8, usize, usize, usize);unsafe extern "C" {- fn muxen_display(pixels_w: *mut usize, pixels_h: *mut usize, points_w: *mut f64, points_h: *mut f64);+ fn muxen_display(id: u32, pixels_w: *mut usize, pixels_h: *mut usize, points_w: *mut f64, points_h: *mut f64, x: *mut f64, y: *mut f64);fn muxen_capture_allowed(ask: i32) -> i32;fn muxen_input_allowed(ask: i32) -> i32;- fn muxen_capture_start(fps: i32, width: usize, height: usize, f: FrameFn, ctx: *mut std::ffi::c_void, err: *mut u8, errlen: usize) -> i32;+ fn muxen_capture_start(id: u32, fps: i32, width: usize, height: usize, f: FrameFn, ctx: *mut std::ffi::c_void, err: *mut u8, errlen: usize) -> i32;fn muxen_capture_stopped() -> i32;fn muxen_mouse(kind: u32, x: f64, y: f64, button: u32, clicks: i64);fn muxen_scroll(dy: i32, dx: i32);@@ -554,14 +623,15 @@ mod mac {l.fresh = true;}- /// A Mac's main display: captured at the frame's size by ScreenCaptureKit,+ /// One of a Mac's displays: captured at the frame's size by ScreenCaptureKit,/// input through CoreGraphics events.pub struct Mac {/// The frame size ScreenCaptureKit delivers.fw: usize,fh: usize,- /// The display in points (input coordinates).+ /// The display in points (input coordinates), and where it sits on the desktop.points: (f64, f64),+ origin: (f64, f64),latest: Arc<Mutex<Latest>>,frame: Vec<u8>,input: bool,@@ -569,12 +639,31 @@ mod mac {held: [bool; 3],flags: u64,last_click: Option<(Instant, u32, f64, f64, i64)>,+ /// Keys pressed and not yet let go, and where the pointer was: let go+ /// when the stream ends, so none stays held.+ pressed: Vec<u16>,+ at: (f64, f64),+ }++ impl Drop for Mac {+ fn drop(&mut self) {+ for code in self.pressed.drain(..) {+ unsafe { muxen_key(code, 0, 0) };+ }+ let (x, y) = self.at;+ for (i, up) in [LEFT_UP, RIGHT_UP, OTHER_UP].into_iter().enumerate() {+ if self.held[i] {+ unsafe { muxen_mouse(up, x, y, i as u32, 1) };+ }+ }+ }}impl Mac {- pub fn open(fps: u32, max_width: u32) -> Result<Mac, String> {- let (mut pw, mut ph, mut ptw, mut pth) = (0usize, 0usize, 0f64, 0f64);- unsafe { muxen_display(&mut pw, &mut ph, &mut ptw, &mut pth) };+ /// Display `id` (0: the main one).+ pub fn open(fps: u32, max_width: u32, id: u32) -> Result<Mac, String> {+ let (mut pw, mut ph, mut ptw, mut pth, mut ox, mut oy) = (0usize, 0usize, 0f64, 0f64, 0f64, 0f64);+ unsafe { muxen_display(id, &mut pw, &mut ph, &mut ptw, &mut pth, &mut ox, &mut oy) };if pw == 0 || ph == 0 {return Err("No display here.".into());}@@ -588,18 +677,18 @@ mod mac {let mut err = [0u8; 512];// ScreenCaptureKit keeps calling with this pointer while the process lives.let ctx = Arc::into_raw(latest.clone()) as *mut std::ffi::c_void;- let started = unsafe { muxen_capture_start(fps as i32, fw, fh, on_frame, ctx, err.as_mut_ptr(), err.len()) };+ let started = unsafe { muxen_capture_start(id, fps as i32, fw, fh, on_frame, ctx, err.as_mut_ptr(), err.len()) };if started != 0 {let why = String::from_utf8_lossy(&err[..err.iter().position(|b| *b == 0).unwrap_or(err.len())]).into_owned();return Err(format!("Can't capture the screen: {why}"));}- Ok(Mac { fw, fh, points: (ptw, pth), latest, frame: Vec::new(), input, held: [false; 3], flags: 0, last_click: None })+ Ok(Mac { fw, fh, points: (ptw, pth), origin: (ox, oy), latest, frame: Vec::new(), input, held: [false; 3], flags: 0, last_click: None, pressed: Vec::new(), at: (ox, oy) })}fn point(&self, e: &Value, frame: (usize, usize)) -> (f64, f64) {let x = e["x"].as_f64().unwrap_or(0.) * self.points.0 / frame.0 as f64;let y = e["y"].as_f64().unwrap_or(0.) * self.points.1 / frame.1 as f64;- (x, y)+ (self.origin.0 + x, self.origin.1 + y)}}@@ -647,6 +736,7 @@ mod mac {match e["t"].as_str().unwrap_or("") {"move" => {let (x, y) = self.point(e, frame);+ self.at = (x, y);let kind = if self.held[0] {LEFT_DRAGGED} else if self.held[1] {@@ -679,6 +769,7 @@ mod mac {self.last_click.map(|c| c.4).unwrap_or(1)};self.held[index] = down;+ self.at = (x, y);unsafe { muxen_mouse(if down { kinds.0 } else { kinds.1 }, x, y, button, clicks) };}"scroll" => {@@ -705,6 +796,10 @@ mod mac {}if let Some(code) = keycode(sym) {unsafe { muxen_key(code, down as i32, self.flags) };+ self.pressed.retain(|x| *x != code);+ if down {+ self.pressed.push(code);+ }}}_ => {}diff --git a/agent/src/displays.rs b/agent/src/displays.rsnew file mode 100644index 0000000..a047eed--- /dev/null+++ b/agent/src/displays.rs@@ -0,0 +1,1699 @@+//! A machine's displays: its monitors, and virtual ones Muxen adds the way+//! DeskPad does on a Mac: extra monitors on the same desktop, that windows+//! move to and the desktop view shows, with no screen plugged in.+//!+//! Linux (X11): a software dummy plug. A made-up monitor (an EDID Muxen+//! writes, at the size asked for) is plugged into a video output with nothing+//! connected, through the kernel's own switches; the desktop then sets it up+//! like a real one. That takes root: sudo, with the user's password when it+//! asks (the app sends it; nothing is installed). A Mac: CGVirtualDisplay,+//! held by a small `muxen-agent vdisplay` process in the user's session for+//! as long as the monitor should exist.+//!+//! Muxen's own virtual monitors are kept in ~/.muxen/displays.json, so they+//! can be told apart and removed. Ids: on Linux the RandR monitor's name+//! ("HDMI-A-0", "DisplayPort-0"; "all" for the whole desktop), on a Mac the+//! CGDirectDisplayID.++use std::io::Read;+use std::process::{Command, Stdio};++use serde_json::{Value, json};++use crate::{home_dir, now};++fn registry_path() -> std::path::PathBuf {+ home_dir().join("displays.json")+}++/// Muxen's virtual monitors, as recorded (some may be gone; see `prune`).+fn registry() -> Vec<Value> {+ std::fs::read_to_string(registry_path()).ok().and_then(|t| serde_json::from_str::<Vec<Value>>(&t).ok()).unwrap_or_default()+}++fn save(entries: &[Value]) {+ let path = registry_path();+ if entries.is_empty() {+ let _ = std::fs::remove_file(&path);+ return;+ }+ let tmp = path.with_extension(format!("json.{}", std::process::id()));+ if std::fs::write(&tmp, Value::Array(entries.to_vec()).to_string()).is_ok() {+ let _ = std::fs::rename(&tmp, &path);+ }+}++/// Names the user gave displays, by id (`~/.muxen/display-names.json`).+fn names_path() -> std::path::PathBuf {+ home_dir().join("display-names.json")+}++fn names() -> serde_json::Map<String, Value> {+ std::fs::read_to_string(names_path()).ok().and_then(|t| serde_json::from_str::<Value>(&t).ok()).and_then(|v| v.as_object().cloned()).unwrap_or_default()+}++fn save_names(names: &serde_json::Map<String, Value>) {+ let path = names_path();+ if names.is_empty() {+ let _ = std::fs::remove_file(&path);+ } else {+ let _ = std::fs::write(&path, Value::Object(names.clone()).to_string());+ }+}++/// Whether one of Muxen's virtual monitors still exists: its output is still+/// plugged (Linux), its holder still running (a Mac). Not from a listing:+/// the desktop briefly drops monitors while it rearranges them.+fn alive(entry: &Value) -> bool {+ if let Some(c) = entry["connector"].as_str() {+ return std::fs::read_to_string(format!("/sys/class/drm/{c}/status")).is_ok_and(|s| s.trim() == "connected");+ }+ match entry["pid"].as_u64() {+ Some(pid) => unsafe { libc::kill(pid as i32, 0) == 0 },+ None => false,+ }+}++/// `{"op": "displays"}`: every display, Muxen's virtual ones marked, with+/// the names the user gave them.+pub fn list() -> Value {+ match query() {+ Ok(mut displays) => {+ let mut reg = registry();+ // Forget virtual monitors that are really gone (the machine restarted, one was unplugged).+ let (live, gone): (Vec<Value>, Vec<Value>) = reg.drain(..).partition(alive);+ reg = live;+ gone.iter().for_each(drop_panel);+ if place_panels(&mut reg, &displays) || !gone.is_empty() {+ save(®);+ }+ #[cfg(target_os = "linux")]+ if let Some(layout) = layout() {+ for d in displays.iter_mut() {+ let Some(id) = d["id"].as_str().map(str::to_string) else { continue };+ let mut sizes: Vec<(u32, u32)> = layout.modes(&id).iter().map(|m| (m.w, m.h)).collect();+ if sizes.is_empty() {+ continue;+ }+ sizes.sort_by_key(|(w, h)| std::cmp::Reverse(w * h));+ sizes.dedup();+ d["modes"] = json!(sizes);+ if let Some(p) = layout.placed(&id).map(|i| &layout.monitors[i]) {+ d["scale"] = json!(p.scale);+ }+ if let Some(m) = layout.current(&id) {+ d["scales"] = json!(m.scales);+ }+ }+ }+ let names = names();+ for d in displays.iter_mut() {+ if let Some(e) = reg.iter().find(|e| e["id"] == d["id"]) {+ d["virtual"] = json!(true);+ d["name"] = e["label"].clone();+ }+ if let Some(n) = d["id"].as_str().and_then(|id| names.get(id)) {+ d["name"] = n.clone();+ }+ }+ json!({ "ok": true, "displays": displays })+ }+ Err(e) => json!({ "ok": false, "error": e }),+ }+}++/// `{"op": "display_rename", "display", "name"}`: what to call a display+/// (real or virtual). An empty name goes back to its own.+pub fn rename(req: &Value) -> Value {+ let id = req["display"].as_str().unwrap_or("");+ let name = req["name"].as_str().unwrap_or("").split_whitespace().collect::<Vec<_>>().join(" ");+ if id.is_empty() {+ return json!({ "ok": false, "error": "Which display?" });+ }+ let mut all = names();+ if name.is_empty() {+ all.remove(id);+ } else {+ all.insert(id.to_string(), json!(name));+ }+ save_names(&all);+ json!({ "ok": true })+}++/// The displays, from `muxen-agent displays` run where it can see them: in+/// the desktop session (with its DISPLAY on Linux, through the background+/// service on a Mac reached over ssh).+fn query() -> Result<Vec<Value>, String> {+ let reply = in_session(&["displays".to_string()])?;+ match reply["displays"].as_array() {+ Some(d) => Ok(d.clone()),+ None => Err(reply["error"].as_str().unwrap_or("Couldn't read the displays.").to_string()),+ }+}++/// Runs `muxen-agent <args>` where it can see the screens, for its JSON reply.+fn in_session(args: &[String]) -> Result<Value, String> {+ let out = if crate::gui::needed() {+ let mut stream = crate::gui::connect(args)?;+ let mut text = String::new();+ stream.read_to_string(&mut text).map_err(|e| e.to_string())?;+ text+ } else {+ let env = crate::desktop::session_env().ok_or("No graphical session found here (nobody logged in to a desktop?).")?;+ let exe = std::env::current_exe().map_err(|e| e.to_string())?;+ let output = Command::new(exe).args(args).envs(env).stdin(Stdio::null()).output().map_err(|e| e.to_string())?;+ String::from_utf8_lossy(&output.stdout).into_owned()+ };+ serde_json::from_str(out.trim()).map_err(|_| "Couldn't read the displays.".to_string())+}++/// `muxen-agent displays`: prints the displays as JSON (run in the desktop session).+pub fn run_list() -> i32 {+ let reply = match monitors() {+ Ok(d) => json!({ "displays": d }),+ Err(e) => json!({ "error": e }),+ };+ println!("{reply}");+ 0+}++/// `{"op": "display_create", "width", "height", "label"}`: a new virtual monitor.+pub fn create(req: &Value) -> Value {+ let w = req["width"].as_u64().unwrap_or(1920).clamp(640, 7680) as u32;+ let h = req["height"].as_u64().unwrap_or(1080).clamp(480, 4320) as u32;+ // Like plugging in another one: "Display 3" when there are two.+ let label = req["label"].as_str().map(str::trim).filter(|l| !l.is_empty()).map(str::to_string);+ let label = label.unwrap_or_else(|| {+ let count = query().map(|d| d.iter().filter(|d| d["id"] != "all").count()).unwrap_or_else(|_| registry().len() + 1);+ format!("Display {}", count + 1)+ });+ match add(w, h, &label, req["password"].as_str()) {+ Ok(mut entry) => {+ entry["label"] = json!(label);+ entry["width"] = json!(w);+ entry["height"] = json!(h);+ entry["created"] = json!(now());+ let mut reg = registry();+ reg.push(entry.clone());+ if let Ok(displays) = query() {+ place_panels(&mut reg, &displays);+ }+ save(®);+ json!({ "ok": true, "display": { "id": entry["id"], "name": label, "width": w, "height": h, "virtual": true } })+ }+ Err(e) => json!({ "ok": false, "password": e == NEEDS_PASSWORD || e == WRONG_PASSWORD, "error": e }),+ }+}++/// `{"op": "display_remove", "display"}`: removes one of Muxen's virtual+/// monitors. (Not "id": a link's requests carry their own.)+pub fn remove(req: &Value) -> Value {+ let id = req["display"].as_str().unwrap_or("");+ let mut reg = registry();+ let Some(i) = reg.iter().position(|e| e["id"].as_str() == Some(id)) else {+ return json!({ "ok": false, "error": format!("{id} isn't a virtual monitor Muxen added.") });+ };+ let entry = reg.remove(i);+ #[cfg(target_os = "linux")]+ let laid_out = layout();+ match take_down(&entry, req["password"].as_str()) {+ Ok(()) => {+ save(®);+ drop_panel(&entry);+ // Once it's gone: the others' sizes and scale as they were, and+ // their panels' numbers shifted.+ for _ in 0..25 {+ std::thread::sleep(std::time::Duration::from_millis(200));+ // The X server only notices an output went dark when asked to+ // look again (a full RandR query); the desktop then lets it go.+ #[cfg(target_os = "linux")]+ let _ = xrandr(&[]);+ if let Some(displays) = query().ok().filter(|d| !d.iter().any(|d| d["id"].as_str() == Some(id))) {+ #[cfg(target_os = "linux")]+ if let Some(laid_out) = &laid_out {+ std::thread::sleep(std::time::Duration::from_millis(1500));+ restore(laid_out, None, Some(id));+ }+ if place_panels(&mut reg, &displays) {+ save(®);+ }+ break;+ }+ }+ let mut all = names();+ if all.remove(id).is_some() {+ save_names(&all);+ }+ json!({ "ok": true })+ }+ Err(e) => json!({ "ok": false, "password": e == NEEDS_PASSWORD || e == WRONG_PASSWORD, "error": e }),+ }+}++// ---------------------------------------------------------------------------+// Linux: RandR monitors, outputs switched on with xrandr.++#[cfg(target_os = "linux")]+fn monitors() -> Result<Vec<Value>, String> {+ use x11rb::connection::Connection;+ use x11rb::protocol::randr::ConnectionExt as _;+ use x11rb::protocol::xproto::ConnectionExt as _;++ let (conn, n) = x11rb::connect(None).map_err(|e| format!("Can't reach the desktop ({e})."))?;+ let screen = &conn.setup().roots[n];+ let (root, sw, sh) = (screen.root, screen.width_in_pixels, screen.height_in_pixels);+ let monitors = conn.randr_get_monitors(root, true).map_err(|e| e.to_string())?.reply().map_err(|e| e.to_string())?.monitors;+ let mut out = Vec::new();+ if monitors.len() > 1 {+ out.push(json!({ "id": "all", "name": "All screens", "x": 0, "y": 0, "width": sw, "height": sh, "main": false }));+ }+ let names: Vec<String> = monitors+ .iter()+ .map(|m| conn.get_atom_name(m.name).ok().and_then(|c| c.reply().ok()).map(|r| String::from_utf8_lossy(&r.name).into_owned()).unwrap_or_default())+ .collect();+ let kinds: Vec<&str> = names.iter().map(|n| output_kind(n)).collect();+ // The sizes each one offers.+ let res = conn.randr_get_screen_resources_current(root).ok().and_then(|c| c.reply().ok());+ let sizes = |m: &x11rb::protocol::randr::MonitorInfo| -> Vec<(u32, u32)> {+ let Some(res) = &res else { return Vec::new() };+ let Some(info) = m.outputs.first().and_then(|o| conn.randr_get_output_info(*o, res.config_timestamp).ok()?.reply().ok()) else { return Vec::new() };+ let mut sizes: Vec<(u32, u32)> = info.modes.iter().filter_map(|id| res.modes.iter().find(|m| m.id == *id)).map(|m| (m.width as u32, m.height as u32)).collect();+ sizes.sort_by_key(|(w, h)| std::cmp::Reverse(w * h));+ sizes.dedup();+ sizes+ };+ for (i, m) in monitors.iter().enumerate() {+ // "HDMI", or "HDMI 2" when there are two.+ let kind = kinds[i];+ let same = kinds.iter().filter(|k| **k == kind).count();+ let name = if same > 1 { format!("{kind} {}", kinds[..=i].iter().filter(|k| **k == kind).count()) } else { kind.to_string() };+ out.push(json!({ "id": names[i], "name": name, "x": m.x, "y": m.y, "width": m.width, "height": m.height, "main": m.primary, "modes": sizes(m), "any_size": true }));+ }+ if out.is_empty() {+ out.push(json!({ "id": "all", "name": "Screen", "x": 0, "y": 0, "width": sw, "height": sh, "main": true }));+ }+ Ok(out)+}++/// What kind of connector an output is, in words ("HDMI-A-0" -> "HDMI").+#[cfg_attr(not(target_os = "linux"), allow(dead_code))]+fn output_kind(name: &str) -> &str {+ let n = name.to_ascii_uppercase();+ if n.starts_with("EDP") || n.starts_with("LVDS") || n.starts_with("DSI") {+ "Built-in display"+ } else if n.starts_with("HDMI") {+ "HDMI"+ } else if n.starts_with("DP") || n.starts_with("DISPLAYPORT") {+ "DisplayPort"+ } else if n.starts_with("VGA") {+ "VGA"+ } else if n.starts_with("DVI") {+ "DVI"+ } else if n.starts_with("VIRTUAL") {+ "Virtual"+ } else {+ name+ }+}++/// An output as `xrandr` lists it.+#[cfg_attr(not(target_os = "linux"), allow(dead_code))]+struct Output {+ name: String,+ connected: bool,+ /// x, y, width, height when it's on.+ geometry: Option<(i64, i64, i64, i64)>,+}++/// Outputs and every mode name `xrandr` knows.+#[cfg_attr(not(target_os = "linux"), allow(dead_code))]+fn parse_xrandr(text: &str) -> (Vec<Output>, Vec<String>) {+ let mut outputs = Vec::new();+ let mut modes = Vec::new();+ for line in text.lines() {+ if line.starts_with(' ') {+ if let Some(m) = line.split_whitespace().next() {+ modes.push(m.to_string());+ }+ continue;+ }+ let words: Vec<&str> = line.split_whitespace().collect();+ if words.len() < 2 || !matches!(words[1], "connected" | "disconnected") {+ continue;+ }+ // "HDMI-A-0 connected primary 3840x2160+0+0 (...)"+ let geometry = words[2..].iter().find_map(|w| {+ let (size, pos) = w.split_once('+')?;+ let (wd, ht) = size.split_once('x')?;+ let (x, y) = pos.split_once('+')?;+ Some((x.parse().ok()?, y.parse().ok()?, wd.parse().ok()?, ht.parse().ok()?))+ });+ outputs.push(Output { name: words[0].to_string(), connected: words[1] == "connected", geometry });+ }+ (outputs, modes)+}++#[cfg(target_os = "linux")]+fn xrandr(args: &[String]) -> Result<String, String> {+ let env = crate::desktop::session_env().ok_or("No graphical session found here (nobody logged in to a desktop?).")?;+ let out = Command::new("xrandr")+ .args(args)+ .envs(env)+ .stdin(Stdio::null())+ .output()+ .map_err(|e| if e.kind() == std::io::ErrorKind::NotFound { "xrandr isn't installed here.".to_string() } else { e.to_string() })?;+ if out.status.success() {+ Ok(String::from_utf8_lossy(&out.stdout).into_owned())+ } else {+ let err = String::from_utf8_lossy(&out.stderr).trim().to_string();+ Err(if err.is_empty() { format!("xrandr {} failed", args.join(" ")) } else { err })+ }+}++/// What `create` and `remove` say when they need the user's password (the app asks for it).+pub const NEEDS_PASSWORD: &str = "Muxen needs your password on this machine to plug in a monitor.";+pub const WRONG_PASSWORD: &str = "That password didn't work.";++/// Plugs a made-up monitor (its EDID in the file `$2`) into the video output+/// `$1`, which must have nothing on it, through the kernel's own switches+/// for that: `edid_override` in debugfs and `status` in sysfs. Run as root.+#[cfg_attr(not(target_os = "linux"), allow(dead_code))]+const PLUG: &str = r#"set -eu+c=$1+case "$c" in card[0-9]*-*) ;; *) echo "not a video output: $c" >&2; exit 1 ;; esac+case "$c" in *[!A-Za-z0-9-]*) echo "not a video output: $c" >&2; exit 1 ;; esac+[ "$(cat "/sys/class/drm/$c/status")" = disconnected ] || { echo "$c has a screen on it" >&2; exit 1; }+mountpoint -q /sys/kernel/debug || mount -t debugfs none /sys/kernel/debug 2>/dev/null || true+card=${c%%-*}; dir="/sys/kernel/debug/dri/${card#card}/${c#*-}"+[ -e "$dir/edid_override" ] || for d in /sys/kernel/debug/dri/*/"${c#*-}"; do [ -e "$d/edid_override" ] && dir=$d && break; done+[ -e "$dir/edid_override" ] || { echo "this machine's kernel can't take a monitor description" >&2; exit 1; }+cat "$2" > "$dir/edid_override"+echo on > "/sys/class/drm/$c/status"+"#;++/// Unplugs it again. Switched off rather than probed again ("detect"): some+/// drivers (amdgpu) go on reporting a monitor they were told about until a+/// real one is plugged in. (A real screen plugged into that output later+/// shows up after a restart.)+#[cfg_attr(not(target_os = "linux"), allow(dead_code))]+const UNPLUG: &str = r#"set -eu+c=$1+case "$c" in card[0-9]*-*) ;; *) echo "not a video output: $c" >&2; exit 1 ;; esac+case "$c" in *[!A-Za-z0-9-]*) echo "not a video output: $c" >&2; exit 1 ;; esac+echo off > "/sys/class/drm/$c/status"+card=${c%%-*}; dir="/sys/kernel/debug/dri/${card#card}/${c#*-}"+[ -e "$dir/edid_override" ] || for d in /sys/kernel/debug/dri/*/"${c#*-}"; do [ -e "$d/edid_override" ] && dir=$d && break; done+[ -e "$dir/edid_override" ] && echo reset > "$dir/edid_override" || true+[ "$(cat "/sys/class/drm/$c/status")" = disconnected ] || { echo "The machine kept the monitor plugged in." >&2; exit 1; }+"#;++/// Runs `script` as root: without a password when sudo allows it here+/// (passwordless, or used a moment ago), else with `password` on sudo's+/// stdin. The password goes nowhere else.+#[cfg(target_os = "linux")]+fn as_root(script: &str, args: &[&str], password: Option<&str>) -> Result<(), String> {+ use std::io::Write;+ // Whether sudo needs a password here at all (its wording differs between versions).+ let free = Command::new("sudo").args(["-n", "true"]).stdin(Stdio::null()).stdout(Stdio::null()).stderr(Stdio::null()).status().is_ok_and(|s| s.success());+ if free {+ let out = Command::new("sudo").args(["-n", "sh", "-c", script, "muxen"]).args(args).stdin(Stdio::null()).stdout(Stdio::null()).output().map_err(|e| e.to_string())?;+ return if out.status.success() { Ok(()) } else { Err(String::from_utf8_lossy(&out.stderr).trim().to_string()) };+ }+ let password = password.filter(|p| !p.is_empty()).ok_or(NEEDS_PASSWORD)?;+ let mut child = Command::new("sudo")+ .args(["-S", "-p", "", "sh", "-c", script, "muxen"])+ .args(args)+ .stdin(Stdio::piped())+ .stdout(Stdio::null())+ .stderr(Stdio::piped())+ .spawn()+ .map_err(|e| e.to_string())?;+ if let Some(mut stdin) = child.stdin.take() {+ let _ = stdin.write_all(format!("{password}\n").as_bytes());+ }+ let out = child.wait_with_output().map_err(|e| e.to_string())?;+ if out.status.success() {+ return Ok(());+ }+ let err = String::from_utf8_lossy(&out.stderr);+ if err.contains("incorrect password") || err.contains("Sorry, try again") {+ Err(WRONG_PASSWORD.into())+ } else if err.contains("not in the sudoers") || err.contains("is not allowed") {+ Err("This account can't use sudo on this machine.".into())+ } else {+ Err(err.lines().filter(|l| !l.trim().is_empty()).last().unwrap_or("").trim().to_string())+ }+}++/// The video outputs the kernel knows ("card1-DP-1") with nothing on them.+#[cfg(target_os = "linux")]+fn free_connectors() -> Vec<String> {+ let mut names: Vec<String> = std::fs::read_dir("/sys/class/drm")+ .into_iter()+ .flatten()+ .flatten()+ .filter_map(|e| e.file_name().into_string().ok())+ .filter(|n| n.starts_with("card") && n.contains('-') && (n.contains("-DP-") || n.contains("-HDMI-") || n.contains("-DVI-")))+ .filter(|n| std::fs::read_to_string(format!("/sys/class/drm/{n}/status")).is_ok_and(|s| s.trim() == "disconnected"))+ .collect();+ // DisplayPort first: most GPUs have more of those to spare.+ names.sort_by_key(|n| (!n.contains("-DP-"), n.clone()));+ names+}++/// Plugs a made-up `w`×`h` monitor into a free output, like connecting a real+/// one: the desktop sets it up (wallpaper, panels, windows) the same way.+#[cfg(target_os = "linux")]+fn add(w: u32, h: u32, label: &str, password: Option<&str>) -> Result<Value, String> {+ let used: Vec<String> = registry().iter().filter_map(|e| e["connector"].as_str().map(str::to_string)).collect();+ let connector = free_connectors().into_iter().find(|c| !used.contains(c)).ok_or("This machine has no free video output for another monitor.")?;+ let (before, _) = parse_xrandr(&xrandr(&[])?);+ let laid_out = layout();+ let file = home_dir().join(format!("edid-{}.bin", std::process::id()));+ std::fs::write(&file, edid(w, h, label)).map_err(|e| e.to_string())?;+ let plugged = as_root(PLUG, &[&connector, &file.to_string_lossy()], password);+ let _ = std::fs::remove_file(&file);+ plugged?;+ // The desktop notices it like a real monitor; find the output it shows up as.+ let mut output = None;+ for _ in 0..30 {+ std::thread::sleep(std::time::Duration::from_millis(200));+ let (now, _) = parse_xrandr(&xrandr(&[])?);+ if let Some(o) = now.iter().find(|o| o.connected && !before.iter().any(|b| b.name == o.name && b.connected)) {+ output = Some((o.name.clone(), o.geometry.is_some()));+ break;+ }+ }+ let Some((name, _)) = output else {+ let _ = as_root(UNPLUG, &[&connector], password);+ return Err("The machine didn't pick up the new monitor.".into());+ };+ // The desktop lays out the new set of monitors its own way, which can+ // change the ones already there (a 4K screen dropped to 1080p). Once it+ // settles, put those back as they were and the new one to their right.+ std::thread::sleep(std::time::Duration::from_millis(2000));+ if let Some(laid_out) = laid_out {+ restore(&laid_out, Some(&name), None);+ return Ok(json!({ "id": name, "connector": connector }));+ }+ let (now, _) = parse_xrandr(&xrandr(&[])?);+ let s = |v: &str| v.to_string();+ let mut args = Vec::new();+ for b in before.iter().filter(|b| b.connected) {+ if let (Some((x, y, w, h)), Some(n)) = (b.geometry, now.iter().find(|n| n.name == b.name)) {+ if n.geometry != b.geometry {+ args.extend([s("--output"), b.name.clone(), s("--mode"), format!("{w}x{h}"), s("--pos"), format!("{x}x{y}")]);+ }+ }+ }+ let right = before.iter().filter(|b| b.connected).filter_map(|b| b.geometry).map(|(x, _, w, _)| x + w).max().unwrap_or(0);+ let new_at = now.iter().find(|n| n.name == name).and_then(|n| n.geometry);+ if !args.is_empty() || new_at.is_none_or(|(x, y, ..)| (x, y) != (right, 0)) {+ args.extend([s("--output"), name.clone(), s("--auto"), s("--pos"), format!("{right}x0")]);+ xrandr(&args)?;+ }+ Ok(json!({ "id": name, "connector": connector }))+}++#[cfg(target_os = "linux")]+fn take_down(entry: &Value, password: Option<&str>) -> Result<(), String> {+ let connector = entry["connector"].as_str().ok_or("Muxen doesn't know which output it's on.")?;+ as_root(UNPLUG, &[connector], password)+}++// Cinnamon puts its panels (the menu, the window list) on the main monitor+// only, so a new monitor would be bare wallpaper with nothing to click. Each+// of Muxen's monitors gets copies of the main monitor's panels (the same+// applets, pinned apps, sizes; not its shortcuts), and loses them when it+// goes. Panels name their monitor by number (the RandR order, main first),+// which shifts as monitors come and go, so they're placed again whenever the+// list changes. Other desktops: left as they are.++/// The user's desktop session bus, for a command run from outside the session.+#[cfg(target_os = "linux")]+fn session_bus(cmd: &mut Command) {+ if std::env::var_os("DBUS_SESSION_BUS_ADDRESS").is_none() {+ cmd.env("DBUS_SESSION_BUS_ADDRESS", format!("unix:path=/run/user/{}/bus", unsafe { libc::getuid() }));+ }+}++/// `gsettings` in the user's desktop session; its output when it worked.+#[cfg(target_os = "linux")]+fn gsettings(args: &[&str]) -> Option<String> {+ let mut cmd = Command::new("gsettings");+ cmd.args(args).stdin(Stdio::null()).stderr(Stdio::null());+ session_bus(&mut cmd);+ let out = cmd.output().ok()?;+ out.status.success().then(|| String::from_utf8_lossy(&out.stdout).trim().to_string())+}++/// The strings in a GVariant list: `['1:0:top', '2:0:bottom']`.+#[cfg_attr(not(target_os = "linux"), allow(dead_code))]+fn strings(list: &str) -> Vec<String> {+ list.split('\'').skip(1).step_by(2).map(str::to_string).collect()+}++#[cfg_attr(not(target_os = "linux"), allow(dead_code))]+fn gvariant(items: &[String]) -> String {+ format!("[{}]", items.iter().map(|i| format!("'{i}'")).collect::<Vec<_>>().join(", "))+}++/// Cinnamon's panels and applets, when Cinnamon is the desktop.+#[cfg(target_os = "linux")]+fn cinnamon_panels() -> Option<(Vec<String>, Vec<String>)> {+ let running = Command::new("pgrep").args(["-x", "cinnamon"]).stdout(Stdio::null()).status().is_ok_and(|s| s.success());+ if !running {+ return None;+ }+ let panels = strings(&gsettings(&["get", "org.cinnamon", "panels-enabled"])?);+ let applets = strings(&gsettings(&["get", "org.cinnamon", "enabled-applets"])?);+ Some((panels, applets))+}++/// Cinnamon's per-panel settings kept as "<panel id>:<value>" lists.+#[cfg(target_os = "linux")]+const PANEL_LISTS: [&str; 4] = ["panels-height", "panels-autohide", "panels-show-delay", "panels-hide-delay"];+/// ... and as JSON lists of {"panelId": id, ...}.+#[cfg(target_os = "linux")]+const PANEL_ZONES: [&str; 3] = ["panel-zone-icon-sizes", "panel-zone-symbolic-icon-sizes", "panel-zone-text-sizes"];++#[cfg(target_os = "linux")]+fn cinnamon_list(key: &str) -> Option<Vec<String>> {+ gsettings(&["get", "org.cinnamon", key]).map(|v| strings(&v))+}++#[cfg(target_os = "linux")]+fn cinnamon_json(key: &str) -> Option<Vec<Value>> {+ let raw = gsettings(&["get", "org.cinnamon", key])?;+ let text = raw.trim().trim_start_matches('\'').trim_end_matches('\'').replace("\\'", "'").replace("\\\\", "\\");+ serde_json::from_str(&text).ok()+}++#[cfg(target_os = "linux")]+fn set_cinnamon_json(key: &str, items: Vec<Value>) {+ let text = Value::Array(items).to_string();+ gsettings(&["set", "org.cinnamon", key, &format!("'{}'", text.replace('\\', "\\\\").replace('\'', "\\'"))]);+}++/// Where Cinnamon keeps each applet's settings: `<uuid>/<instance>.json`.+#[cfg(target_os = "linux")]+fn spices() -> std::path::PathBuf {+ std::path::PathBuf::from(std::env::var("HOME").unwrap_or_default()).join(".config/cinnamon/spices")+}++/// Gives a copied applet the original's settings (its pinned apps, ...),+/// without its keyboard shortcuts (the menu's Super key stays with the main+/// screen's). Whether there were any.+#[cfg(target_os = "linux")]+fn copy_applet_settings(uuid: &str, from: &str, to: u64) -> bool {+ let dir = spices().join(uuid);+ let Some(mut settings) = std::fs::read_to_string(dir.join(format!("{from}.json"))).ok().and_then(|t| serde_json::from_str::<Value>(&t).ok()) else { return false };+ if let Some(all) = settings.as_object_mut() {+ for s in all.values_mut().filter(|s| s["type"] == "keybinding") {+ s["value"] = json!("");+ }+ }+ std::fs::write(dir.join(format!("{to}.json")), settings.to_string()).is_ok()+}++/// Whether an applet may run more than once (its `max-instances`; one when+/// it doesn't say): the tray, sound, network ... stay on the main screen.+#[cfg(target_os = "linux")]+fn copyable(uuid: &str) -> bool {+ let home = std::path::PathBuf::from(std::env::var("HOME").unwrap_or_default());+ [home.join(".local/share/cinnamon/applets"), "/usr/share/cinnamon/applets".into()]+ .iter()+ .find_map(|dir| std::fs::read_to_string(dir.join(uuid).join("metadata.json")).ok())+ .and_then(|t| serde_json::from_str::<Value>(&t).ok())+ .and_then(|m| m["max-instances"].as_i64())+ .is_some_and(|n| n < 0 || n > 1)+}++/// Panel id, monitor number and side of a `panels-enabled` entry ("3:1:bottom").+#[cfg_attr(not(target_os = "linux"), allow(dead_code))]+fn panel_parts(p: &str) -> Option<(u64, usize, &str)> {+ let mut it = p.splitn(3, ':');+ Some((it.next()?.parse().ok()?, it.next()?.parse().ok()?, it.next()?))+}++/// The panels a virtual monitor has (Muxen's first ones were a single "panel").+#[cfg_attr(not(target_os = "linux"), allow(dead_code))]+fn panels_of(entry: &Value) -> Vec<u64> {+ match entry["panels"].as_array() {+ Some(ids) => ids.iter().filter_map(Value::as_u64).collect(),+ None => entry["panel"].as_u64().into_iter().collect(),+ }+}++/// Gives every virtual monitor in `reg` copies of the main monitor's panels+/// and points them at its monitor's current number. True when `reg` changed.+#[cfg(target_os = "linux")]+fn place_panels(reg: &mut [Value], displays: &[Value]) -> bool {+ let screens: Vec<&Value> = displays.iter().filter(|d| d["id"] != "all").collect();+ let order: Vec<&str> = screens.iter().filter_map(|d| d["id"].as_str()).collect();+ // Mid-rearrangement (one missing): the next listing will do it.+ if reg.is_empty() || reg.iter().any(|e| e["id"].as_str().is_none_or(|id| !order.contains(&id))) {+ return false;+ }+ if cinnamon_panels().is_none() {+ return false;+ }+ let mut changed = false;+ // Muxen's first panel (a menu and a window list of its own): replaced by copies.+ for e in reg.iter_mut().filter(|e| e.get("panel").is_some()) {+ drop_panel(e);+ if let Some(o) = e.as_object_mut() {+ o.remove("panel");+ }+ changed = true;+ }+ let Some((before, applets_before)) = cinnamon_panels() else { return changed };+ let (mut panels, mut applets) = (before.clone(), applets_before.clone());+ let owned: Vec<u64> = reg.iter().flat_map(panels_of).collect();+ let main = screens.iter().position(|d| d["main"] == true).unwrap_or(0);+ let templates: Vec<(u64, String)> =+ before.iter().filter_map(|p| panel_parts(p)).filter(|(id, monitor, _)| *monitor == main && !owned.contains(id)).map(|(id, _, side)| (id, side.to_string())).collect();+ let mut next_panel = before.iter().filter_map(|p| panel_parts(p)).map(|p| p.0).chain(owned.iter().copied()).max().unwrap_or(0) + 1;+ let mut next_applet = applets.iter().filter_map(|a| a.rsplit(':').next()?.parse::<u64>().ok()).max().unwrap_or(0) + 1;+ let mut copies = Vec::new();+ for e in reg.iter_mut() {+ let index = order.iter().position(|id| e["id"] == *id).unwrap_or(0);+ if e["panels"].is_array() {+ // A panel the user took away stays away.+ for id in panels_of(e) {+ if let Some(slot) = panels.iter_mut().find(|s| panel_parts(s).is_some_and(|p| p.0 == id)) {+ let side = slot.rsplit(':').next().unwrap_or("bottom").to_string();+ *slot = format!("{id}:{index}:{side}");+ }+ }+ continue;+ }+ let (mut mine, mut files) = (Vec::new(), Vec::new());+ for (t, side) in &templates {+ let n = next_panel;+ next_panel += 1;+ panels.push(format!("{n}:{index}:{side}"));+ for a in applets_before.iter().filter(|a| a.starts_with(&format!("panel{t}:"))) {+ // panel<id>:<zone>:<order>:<uuid>:<instance>+ let parts: Vec<&str> = a.split(':').collect();+ let [_, zone, place, uuid, from] = parts[..] else { continue };+ if !copyable(uuid) {+ continue;+ }+ let to = next_applet;+ next_applet += 1;+ applets.push(format!("panel{n}:{zone}:{place}:{uuid}:{to}"));+ if copy_applet_settings(uuid, from, to) {+ files.push(json!([uuid, to]));+ }+ }+ copies.push((*t, n));+ mine.push(n);+ }+ e["panels"] = json!(mine);+ e["applet_settings"] = json!(files);+ changed = true;+ }+ // Their heights, icon sizes, ... like the panels they copy.+ if !copies.is_empty() {+ for key in PANEL_LISTS {+ let Some(mut list) = cinnamon_list(key) else { continue };+ for (t, n) in &copies {+ if let Some(value) = list.iter().find_map(|x| x.strip_prefix(&format!("{t}:"))).map(str::to_string) {+ list.retain(|x| !x.starts_with(&format!("{n}:")));+ list.push(format!("{n}:{value}"));+ }+ }+ gsettings(&["set", "org.cinnamon", key, &gvariant(&list)]);+ }+ for key in PANEL_ZONES {+ let Some(mut items) = cinnamon_json(key) else { continue };+ for (t, n) in &copies {+ if let Some(mut item) = items.iter().find(|i| i["panelId"] == json!(t)).cloned() {+ items.retain(|i| i["panelId"] != json!(n));+ item["panelId"] = json!(n);+ items.push(item);+ }+ }+ set_cinnamon_json(key, items);+ }+ }+ // The panels first: Cinnamon loads their applets once they're there.+ if panels != before {+ gsettings(&["set", "org.cinnamon", "panels-enabled", &gvariant(&panels)]);+ }+ if applets != applets_before {+ gsettings(&["set", "org.cinnamon", "enabled-applets", &gvariant(&applets)]);+ }+ changed+}++/// Takes away the panels a virtual monitor had, with their settings.+#[cfg(target_os = "linux")]+fn drop_panel(entry: &Value) {+ let ids = panels_of(entry);+ if ids.is_empty() {+ return;+ }+ let Some((panels, applets)) = cinnamon_panels() else { return };+ let ours = |p: &str| panel_parts(p).is_some_and(|p| ids.contains(&p.0));+ let on_ours = |a: &str| ids.iter().any(|i| a.starts_with(&format!("panel{i}:")));+ let kept_applets: Vec<String> = applets.iter().filter(|a| !on_ours(a)).cloned().collect();+ if kept_applets != applets {+ gsettings(&["set", "org.cinnamon", "enabled-applets", &gvariant(&kept_applets)]);+ }+ let kept: Vec<String> = panels.iter().filter(|p| !ours(p)).cloned().collect();+ if kept != panels {+ gsettings(&["set", "org.cinnamon", "panels-enabled", &gvariant(&kept)]);+ }+ for key in PANEL_LISTS {+ if let Some(list) = cinnamon_list(key) {+ let kept: Vec<String> = list.iter().filter(|x| !ids.iter().any(|i| x.starts_with(&format!("{i}:")))).cloned().collect();+ if kept != list {+ gsettings(&["set", "org.cinnamon", key, &gvariant(&kept)]);+ }+ }+ }+ for key in PANEL_ZONES {+ if let Some(items) = cinnamon_json(key) {+ let before = items.len();+ let kept: Vec<Value> = items.into_iter().filter(|i| !ids.iter().any(|id| i["panelId"] == json!(id))).collect();+ if kept.len() != before {+ set_cinnamon_json(key, kept);+ }+ }+ }+ // The applets' settings on those panels.+ for a in applets.iter().filter(|a| on_ours(a)) {+ let parts: Vec<&str> = a.split(':').collect();+ if let [_, _, _, uuid, instance] = parts[..] {+ let _ = std::fs::remove_file(spices().join(uuid).join(format!("{instance}.json")));+ }+ }+}++/// CVT reduced-blanking timings for `w`×`h` at 60 Hz: what a monitor of that+/// size would ask for.+#[cfg_attr(not(target_os = "linux"), allow(dead_code))]+struct Timing {+ w: u32,+ h: u32,+ /// Pixel clock in units of 10 kHz.+ clock: u32,+ h_blank: u32,+ h_front: u32,+ h_sync: u32,+ v_blank: u32,+ v_front: u32,+ v_sync: u32,+}++#[cfg_attr(not(target_os = "linux"), allow(dead_code))]+fn timing(w: u32, h: u32) -> Timing {+ let w = w / 8 * 8;+ let v_sync = match (w * 3 == h * 4, w * 9 == h * 16, w * 10 == h * 16, w * 4 == h * 5) {+ (true, ..) => 4,+ (_, true, ..) => 5,+ (_, _, true, _) => 6,+ (_, _, _, true) => 7,+ _ => 10,+ };+ let h_period = (1_000_000.0 / 60.0 - 460.0) / h as f64;+ let v_blank = ((460.0 / h_period).floor() as u32 + 1).max(3 + v_sync + 6);+ let mhz = ((60.0 * (w + 160) as f64 * (h + v_blank) as f64 / 1_000_000.0) / 0.25).floor() * 0.25;+ Timing { w, h, clock: (mhz * 100.0).round() as u32, h_blank: 160, h_front: 48, h_sync: 32, v_blank, v_front: 3, v_sync }+}++/// The detailed timing of one mode, as an EDID writes it (18 bytes).+#[cfg_attr(not(target_os = "linux"), allow(dead_code))]+fn dtd(t: &Timing) -> [u8; 18] {+ // About 96 dpi.+ let (mm_w, mm_h) = (t.w * 254 / 960, t.h * 254 / 960);+ let mut d = [0u8; 18];+ d[0..2].copy_from_slice(&(t.clock as u16).to_le_bytes());+ d[2] = (t.w & 0xff) as u8;+ d[3] = (t.h_blank & 0xff) as u8;+ d[4] = (((t.w >> 8) << 4) | (t.h_blank >> 8)) as u8;+ d[5] = (t.h & 0xff) as u8;+ d[6] = (t.v_blank & 0xff) as u8;+ d[7] = (((t.h >> 8) << 4) | (t.v_blank >> 8)) as u8;+ d[8] = (t.h_front & 0xff) as u8;+ d[9] = (t.h_sync & 0xff) as u8;+ d[10] = (((t.v_front & 15) << 4) | (t.v_sync & 15)) as u8;+ d[11] = (((t.h_front >> 8) << 6) | ((t.h_sync >> 8) << 4) | ((t.v_front >> 4) << 2) | (t.v_sync >> 4)) as u8;+ d[12] = (mm_w & 0xff) as u8;+ d[13] = (mm_h & 0xff) as u8;+ d[14] = (((mm_w >> 8) << 4) | (mm_h >> 8)) as u8;+ d[17] = 0x1A; // digital separate sync, +hsync -vsync+ d+}++/// Bigger modes a real monitor offers, beyond what the base block lists+/// (its standard timings stop at 2288 pixels wide).+#[cfg_attr(not(target_os = "linux"), allow(dead_code))]+const LARGE_MODES: &[(u32, u32)] = &[(3840, 2160), (3200, 1800), (2560, 1600), (2560, 1440), (2048, 1152)];++/// A monitor's self-description for a `w`×`h` screen called `name`: EDID 1.3+/// with that size as its preferred mode, plus every common size (720p up to+/// 4K) so it can be switched in the machine's display settings like a real+/// one; the bigger ones in a CTA-861 extension block. 256 bytes.+#[cfg_attr(not(target_os = "linux"), allow(dead_code))]+fn edid(w: u32, h: u32, name: &str) -> Vec<u8> {+ let t = timing(w, h);+ let (mm_w, mm_h) = (t.w * 254 / 960, t.h * 254 / 960);+ let mut e = vec![0u8; 256];+ e[0..8].copy_from_slice(&[0, 255, 255, 255, 255, 255, 255, 0]);+ e[8..10].copy_from_slice(&[0x36, 0xAE]); // "MXN"+ e[10..12].copy_from_slice(&1u16.to_le_bytes());+ e[12..16].copy_from_slice(&(now() as u32).to_le_bytes());+ e[16] = 1;+ e[17] = 36; // 2026+ e[18] = 1;+ e[19] = 3;+ e[20] = 0x80; // digital+ e[21] = (mm_w / 10).min(255) as u8;+ e[22] = (mm_h / 10).min(255) as u8;+ e[23] = 120; // gamma 2.2+ e[24] = 0x0A; // RGB, preferred timing first+ e[25..35].copy_from_slice(&[0xEE, 0x91, 0xA3, 0x54, 0x4C, 0x99, 0x26, 0x0F, 0x50, 0x54]);+ // Established timings: 640×480, 800×600 and 1024×768 at 60 Hz.+ e[35] = 0x21;+ e[36] = 0x08;+ // Standard timings, at 60 Hz: (width / 8 - 31, aspect bits | refresh - 60).+ let standard: [(u32, u8); 8] = [(1280, 0xC0), (1280, 0x00), (1280, 0x80), (1440, 0x00), (1600, 0xC0), (1680, 0x00), (1920, 0xC0), (1920, 0x00)];+ for (i, (sw, aspect)) in standard.iter().enumerate() {+ e[38 + i * 2] = (sw / 8 - 31) as u8;+ e[39 + i * 2] = *aspect;+ }+ e[54..72].copy_from_slice(&dtd(&t));+ // Its name (up to 13 characters).+ let mut n: Vec<u8> = name.bytes().filter(|b| b.is_ascii_graphic() || *b == b' ').take(13).collect();+ if n.len() < 13 {+ n.push(b'\n');+ }+ n.resize(13, b' ');+ e[72..77].copy_from_slice(&[0, 0, 0, 0xFC, 0]);+ e[77..90].copy_from_slice(&n);+ // Range limits: 50-75 Hz, 30-160 kHz, up to 600 MHz.+ e[90..102].copy_from_slice(&[0, 0, 0, 0xFD, 0, 50, 75, 30, 160, 60, 0, 0x0A]);+ e[102..108].copy_from_slice(&[b' '; 6]);+ e[108..113].copy_from_slice(&[0, 0, 0, 0x10, 0]);+ e[126] = 1; // one extension+ e[127] = checksum(&e[..127]);+ // CTA-861 extension: no data blocks, the bigger modes as detailed timings.+ let x = &mut e[128..];+ x[0] = 0x02;+ x[1] = 0x03;+ x[2] = 4;+ let mut at = 4;+ for &(lw, lh) in LARGE_MODES.iter().filter(|m| **m != (t.w, t.h)) {+ if at + 18 > 127 {+ break;+ }+ x[at..at + 18].copy_from_slice(&dtd(&timing(lw, lh)));+ at += 18;+ }+ x[127] = checksum(&x[..127]);+ e+}++#[cfg_attr(not(target_os = "linux"), allow(dead_code))]+fn checksum(bytes: &[u8]) -> u8 {+ let sum: u32 = bytes.iter().map(|b| *b as u32).sum();+ ((256 - sum % 256) % 256) as u8+}++// ---------------------------------------------------------------------------+// Linux: a monitor's size and scale through the desktop's own display service+// (Mutter's DisplayConfig, in Cinnamon and GNOME), as its Display settings+// set them, so the desktop lays itself out for them; RandR (sizes only)+// elsewhere. Applied as temporary changes: a lasting one makes the desktop+// ask "Keep these settings?" on its own screen. It drops them when monitors+// come and go, so adding or removing one puts them back.++/// A GVariant in the text form `gdbus` prints: tuples and arrays are lists.+#[derive(Debug, Clone, PartialEq)]+#[cfg_attr(not(target_os = "linux"), allow(dead_code))]+enum Gv {+ Str(String),+ Num(f64),+ Bool(bool),+ List(Vec<Gv>),+ Dict(Vec<(Gv, Gv)>),+}++#[cfg_attr(not(target_os = "linux"), allow(dead_code))]+impl Gv {+ fn parse(text: &str) -> Option<Gv> {+ gv_value(text.as_bytes(), &mut 0)+ }++ fn at(&self, i: usize) -> Option<&Gv> {+ self.list().get(i)+ }++ fn list(&self) -> &[Gv] {+ match self {+ Gv::List(l) => l,+ _ => &[],+ }+ }++ fn str(&self) -> &str {+ match self {+ Gv::Str(s) => s,+ _ => "",+ }+ }++ fn num(&self) -> f64 {+ match self {+ Gv::Num(n) => *n,+ _ => 0.0,+ }+ }++ fn get(&self, key: &str) -> Option<&Gv> {+ match self {+ Gv::Dict(d) => d.iter().find(|(k, _)| k.str() == key).map(|(_, v)| v),+ _ => None,+ }+ }+}++#[cfg_attr(not(target_os = "linux"), allow(dead_code))]+fn gv_value(b: &[u8], at: &mut usize) -> Option<Gv> {+ let skip = |at: &mut usize| {+ while b.get(*at).is_some_and(u8::is_ascii_whitespace) {+ *at += 1;+ }+ };+ skip(at);+ let c = *b.get(*at)?;+ match c {+ b'(' | b'[' | b'{' => {+ let close = match c {+ b'(' => b')',+ b'[' => b']',+ _ => b'}',+ };+ *at += 1;+ let (mut items, mut pairs) = (Vec::new(), Vec::new());+ loop {+ skip(at);+ if *b.get(*at)? == close {+ *at += 1;+ break;+ }+ let v = gv_value(b, at)?;+ if c == b'{' {+ skip(at);+ if *b.get(*at)? != b':' {+ return None;+ }+ *at += 1;+ pairs.push((v, gv_value(b, at)?));+ } else {+ items.push(v);+ }+ skip(at);+ match *b.get(*at)? {+ b',' => *at += 1,+ x if x == close => {}+ _ => return None,+ }+ }+ Some(if c == b'{' { Gv::Dict(pairs) } else { Gv::List(items) })+ }+ b'<' => {+ *at += 1;+ let v = gv_value(b, at)?;+ skip(at);+ if *b.get(*at)? != b'>' {+ return None;+ }+ *at += 1;+ Some(v)+ }+ b'\'' | b'"' => {+ *at += 1;+ let mut text = Vec::new();+ loop {+ let ch = *b.get(*at)?;+ *at += 1;+ match ch {+ b'\\' => {+ text.push(*b.get(*at)?);+ *at += 1;+ }+ _ if ch == c => break,+ _ => text.push(ch),+ }+ }+ Some(Gv::Str(String::from_utf8_lossy(&text).into_owned()))+ }+ b'@' => {+ // A type ("@a{sv} {}"): the value follows.+ while b.get(*at).is_some_and(|x| !x.is_ascii_whitespace()) {+ *at += 1;+ }+ gv_value(b, at)+ }+ b'-' | b'+' | b'.' | b'0'..=b'9' => {+ let start = *at;+ while b.get(*at).is_some_and(|x| x.is_ascii_digit() || b".-+eE".contains(x)) {+ *at += 1;+ }+ std::str::from_utf8(&b[start..*at]).ok()?.parse().ok().map(Gv::Num)+ }+ _ => {+ let start = *at;+ while b.get(*at).is_some_and(|x| x.is_ascii_alphanumeric() || *x == b'_') {+ *at += 1;+ }+ match &b[start..*at] {+ b"true" => Some(Gv::Bool(true)),+ b"false" => Some(Gv::Bool(false)),+ b"" => None,+ // A type ("uint32 0"): the value follows.+ _ => gv_value(b, at),+ }+ }+ }+}++/// Where the display service is: Cinnamon's, else GNOME's.+#[cfg(target_os = "linux")]+const DISPLAY_SERVICES: [&str; 2] = ["org.cinnamon.Muffin.DisplayConfig", "org.gnome.Mutter.DisplayConfig"];++#[cfg(target_os = "linux")]+fn gdbus(service: &str, method: &str, args: &[&str]) -> Result<String, String> {+ let path = format!("/{}", service.replace('.', "/"));+ let mut cmd = Command::new("gdbus");+ cmd.args(["call", "--session", "--timeout", "10", "--dest", service, "--object-path", &path, "--method", &format!("{service}.{method}")]).args(args);+ session_bus(&mut cmd);+ let out = cmd.stdin(Stdio::null()).output().map_err(|e| e.to_string())?;+ if out.status.success() {+ Ok(String::from_utf8_lossy(&out.stdout).into_owned())+ } else {+ Err(String::from_utf8_lossy(&out.stderr).lines().next().unwrap_or("The desktop said no.").to_string())+ }+}++#[cfg_attr(not(target_os = "linux"), allow(dead_code))]+#[derive(Debug, Clone)]+struct Mode {+ id: String,+ w: u32,+ h: u32,+ hz: f64,+ scales: Vec<f64>,+ current: bool,+}++/// A monitor as the desktop lays it out: where, how scaled, which outputs.+#[cfg_attr(not(target_os = "linux"), allow(dead_code))]+#[derive(Debug, Clone)]+struct Placed {+ x: i64,+ y: i64,+ scale: f64,+ transform: u64,+ primary: bool,+ outputs: Vec<String>,+}++/// The desktop's monitors, as its display service has them.+#[cfg_attr(not(target_os = "linux"), allow(dead_code))]+#[derive(Debug, Clone)]+struct Layout {+ service: &'static str,+ serial: u64,+ /// Each output (by connector name, "HDMI-A-0") and its modes.+ outputs: Vec<(String, Vec<Mode>)>,+ monitors: Vec<Placed>,+ /// Positions count real pixels (X11), else scaled ones.+ physical: bool,+ /// Every monitor has the same scale (X11).+ one_scale: bool,+}++#[cfg_attr(not(target_os = "linux"), allow(dead_code))]+impl Layout {+ fn read(service: &'static str, text: &str) -> Option<Layout> {+ let state = Gv::parse(text.trim())?;+ let outputs = state+ .at(1)?+ .list()+ .iter()+ .map(|o| {+ let name = o.at(0).and_then(|i| i.at(0)).map(|c| c.str().to_string()).unwrap_or_default();+ let modes = o+ .at(1)+ .map(Gv::list)+ .unwrap_or_default()+ .iter()+ .map(|m| Mode {+ id: m.at(0).map(|v| v.str().to_string()).unwrap_or_default(),+ w: m.at(1).map(Gv::num).unwrap_or(0.) as u32,+ h: m.at(2).map(Gv::num).unwrap_or(0.) as u32,+ hz: m.at(3).map(Gv::num).unwrap_or(0.),+ scales: m.at(5).map(|s| s.list().iter().map(Gv::num).collect()).unwrap_or_default(),+ current: m.at(6).and_then(|p| p.get("is-current")) == Some(&Gv::Bool(true)),+ })+ .collect();+ (name, modes)+ })+ .collect();+ let monitors = state+ .at(2)?+ .list()+ .iter()+ .map(|l| Placed {+ x: l.at(0).map(Gv::num).unwrap_or(0.) as i64,+ y: l.at(1).map(Gv::num).unwrap_or(0.) as i64,+ scale: l.at(2).map(Gv::num).unwrap_or(1.),+ transform: l.at(3).map(Gv::num).unwrap_or(0.) as u64,+ primary: l.at(4) == Some(&Gv::Bool(true)),+ outputs: l.at(5).map(Gv::list).unwrap_or_default().iter().filter_map(|o| o.at(0).map(|c| c.str().to_string())).collect(),+ })+ .collect();+ let props = state.at(3);+ Some(Layout {+ service,+ serial: state.at(0)?.num() as u64,+ outputs,+ monitors,+ physical: props.and_then(|p| p.get("layout-mode")).map(Gv::num) != Some(1.),+ one_scale: props.and_then(|p| p.get("global-scale-required")) == Some(&Gv::Bool(true)),+ })+ }++ fn modes(&self, output: &str) -> &[Mode] {+ self.outputs.iter().find(|(o, _)| o == output).map(|(_, m)| m.as_slice()).unwrap_or_default()+ }++ fn current(&self, output: &str) -> Option<&Mode> {+ self.modes(output).iter().find(|m| m.current)+ }++ /// The best mode of `output` at `w`×`h`: 60 Hz or the nearest under it.+ fn mode_at(&self, output: &str, (w, h): (u32, u32)) -> Option<&Mode> {+ let key = |m: &Mode| (m.hz <= 61., (m.hz * 1000.) as i64);+ self.modes(output).iter().filter(|m| (m.w, m.h) == (w, h)).max_by_key(|m| key(m))+ }++ fn placed(&self, output: &str) -> Option<usize> {+ self.monitors.iter().position(|p| p.outputs.iter().any(|o| o == output))+ }++ /// How wide a monitor is in layout units, at `size` (else its own).+ fn width(&self, p: &Placed, size: Option<(u32, u32)>) -> i64 {+ let Some((w, h)) = size.or_else(|| p.outputs.first().and_then(|o| self.current(o)).map(|m| (m.w, m.h))) else { return 0 };+ let w = if p.transform % 2 == 1 { h } else { w };+ if self.physical { w as i64 } else { (w as f64 / p.scale).round() as i64 }+ }++ /// Asks the desktop for `monitors`, each output at the size in `sizes`+ /// (else the one it has).+ #[cfg(target_os = "linux")]+ fn apply(&self, monitors: &[Placed], sizes: &[(String, (u32, u32))]) -> Result<(), String> {+ let mut parts = Vec::new();+ for p in monitors {+ let mut outputs = Vec::new();+ for o in &p.outputs {+ let mode = match sizes.iter().find(|(n, _)| n == o) {+ Some((_, size)) => self.mode_at(o, *size),+ None => self.current(o),+ }+ .ok_or("That size isn't one this monitor offers.")?;+ if !mode.scales.is_empty() && !mode.scales.iter().any(|s| (s - p.scale).abs() < 0.01) {+ return Err(format!("This monitor can't be shown at {}% at that size.", (p.scale * 100.).round()));+ }+ outputs.push(format!("('{o}', '{}', @a{{sv}} {{}})", mode.id));+ }+ parts.push(format!("({}, {}, {:?}, {}, {}, [{}])", p.x, p.y, p.scale, p.transform, p.primary, outputs.join(", ")));+ }+ let config = format!("[{}]", parts.join(", "));+ gdbus(self.service, "ApplyMonitorsConfig", &[&self.serial.to_string(), "1", &config, "@a{sv} {}"]).map(|_| ())+ }+}++/// The desktop's monitors, when it has a display service.+#[cfg(target_os = "linux")]+fn layout() -> Option<Layout> {+ DISPLAY_SERVICES.iter().find_map(|service| Layout::read(service, &gdbus(service, "GetCurrentState", &[]).ok()?))+}++/// Puts the desktop back the way `before` had it after a monitor came or+/// went (it resets sizes and scale then): the ones still there as they were,+/// a new one (`added`) to their right, the ones right of a removed one moved+/// over.+#[cfg(target_os = "linux")]+fn restore(before: &Layout, added: Option<&str>, removed: Option<&str>) {+ let Some(now) = layout() else { return };+ let scale = before.monitors.iter().find(|p| p.primary).or(before.monitors.first()).map(|p| p.scale).unwrap_or(1.);+ let gap = removed.and_then(|r| before.placed(r)).map(|i| {+ let p = &before.monitors[i];+ (p.x + before.width(p, None), before.width(p, None))+ });+ let mut monitors = Vec::new();+ let mut sizes = Vec::new();+ for p in &now.monitors {+ let was = p.outputs.first().and_then(|o| before.placed(o)).map(|i| &before.monitors[i]);+ match was {+ Some(was) => {+ let mut q = was.clone();+ if let Some((edge, width)) = gap {+ if q.x >= edge {+ q.x -= width;+ }+ }+ for o in &q.outputs {+ if let Some(m) = before.current(o) {+ sizes.push((o.clone(), (m.w, m.h)));+ }+ }+ monitors.push(q);+ }+ None if added.is_some_and(|a| p.outputs.iter().any(|o| o == a)) => {+ let right = before.monitors.iter().map(|q| q.x + before.width(q, None)).max().unwrap_or(0);+ let mut q = Placed { x: right, y: 0, scale, transform: 0, primary: false, outputs: p.outputs.clone() };+ // A scale it can't do: as it came.+ if p.outputs.first().and_then(|o| now.current(o)).is_some_and(|m| !m.scales.is_empty() && !m.scales.iter().any(|s| (s - scale).abs() < 0.01)) {+ q.scale = p.scale;+ }+ monitors.push(q);+ }+ None => monitors.push(p.clone()),+ }+ }+ if let Err(e) = now.apply(&monitors, &sizes) {+ eprintln!("displays: couldn't put the monitors back: {e}");+ }+}++/// `{"op": "display_set", "display", "width"?, "height"?, "scale"?}`: a+/// monitor's size, and how much the desktop scales things up on it (one+/// scale for them all on X11).+pub fn set(req: &Value) -> Value {+ let id = req["display"].as_str().unwrap_or("");+ let size = req["width"].as_u64().zip(req["height"].as_u64()).map(|(w, h)| (w as u32, h as u32));+ let scale = req["scale"].as_f64();+ if id.is_empty() || id == "all" || (size.is_none() && scale.is_none()) {+ return json!({ "ok": false, "error": "Which monitor, and what size or scale?" });+ }+ match set_display(id, size, scale) {+ Ok(()) => {+ if let Some((w, h)) = size {+ let mut reg = registry();+ if let Some(e) = reg.iter_mut().find(|e| e["id"] == id) {+ e["width"] = json!(w);+ e["height"] = json!(h);+ save(®);+ }+ }+ json!({ "ok": true })+ }+ Err(e) => json!({ "ok": false, "error": e }),+ }+}++#[cfg(target_os = "linux")]+fn set_display(id: &str, size: Option<(u32, u32)>, scale: Option<f64>) -> Result<(), String> {+ // A size the monitor doesn't list: give it one (X11 takes any).+ if let Some((w, h)) = size {+ let (outputs, modes) = parse_xrandr(&xrandr(&[])?);+ let listed = layout().map(|l| l.mode_at(id, (w, h)).is_some()).unwrap_or_else(|| outputs.iter().any(|o| o.name == id) && modes.iter().any(|m| m.starts_with(&format!("{w}x{h}"))));+ if !listed {+ add_mode(id, w, h)?;+ }+ }+ let Some(layout) = layout() else {+ if scale.is_some() {+ return Err("This desktop doesn't let Muxen change its scale.".into());+ }+ return xrandr_size(id, size.unwrap_or_default());+ };+ let i = layout.placed(id).ok_or("That monitor isn't on.")?;+ let mut monitors = layout.monitors.clone();+ let target = monitors[i].clone();+ let old = layout.width(&target, None);+ if let Some(s) = scale {+ for (j, p) in monitors.iter_mut().enumerate() {+ if j == i || layout.one_scale {+ // Scaled positions grow and shrink with the scale.+ if !layout.physical && layout.one_scale {+ p.x = (p.x as f64 * p.scale / s).round() as i64;+ p.y = (p.y as f64 * p.scale / s).round() as i64;+ }+ p.scale = s;+ }+ }+ }+ // The ones to its right move over when it gets wider or narrower.+ let new = layout.width(&monitors[i], size);+ if !(layout.one_scale && !layout.physical && scale.is_some()) {+ let edge = target.x + old;+ for p in monitors.iter_mut() {+ if p.x >= edge {+ p.x += new - old;+ }+ }+ }+ let sizes: Vec<(String, (u32, u32))> = size.map(|s| target.outputs.iter().map(|o| (o.clone(), s)).collect()).unwrap_or_default();+ layout.apply(&monitors, &sizes)+}++/// Gives an output a `w`×`h` mode at 60 Hz (CVT reduced blanking, like the+/// monitors Muxen adds), then waits for the desktop to see it.+#[cfg(target_os = "linux")]+fn add_mode(output: &str, w: u32, h: u32) -> Result<(), String> {+ let t = timing(w, h);+ let name = format!("{w}x{h}_muxen");+ let (hs, vs) = (t.w + t.h_front, t.h + t.v_front);+ let line = [+ format!("{:.2}", t.clock as f64 / 100.),+ t.w.to_string(),+ hs.to_string(),+ (hs + t.h_sync).to_string(),+ (t.w + t.h_blank).to_string(),+ t.h.to_string(),+ vs.to_string(),+ (vs + t.v_sync).to_string(),+ (t.h + t.v_blank).to_string(),+ ];+ // Already made for another output: only added to this one.+ let mut args = vec!["--newmode".to_string(), name.clone()];+ args.extend(line);+ args.extend(["+hsync".to_string(), "-vsync".to_string()]);+ let _ = xrandr(&args);+ xrandr(&["--addmode".to_string(), output.to_string(), name]).map_err(|_| format!("This monitor won't take {w}×{h}."))?;+ for _ in 0..10 {+ if layout().is_none_or(|l| l.mode_at(output, (w, h)).is_some()) {+ break;+ }+ std::thread::sleep(std::time::Duration::from_millis(200));+ }+ Ok(())+}++/// A monitor's size through RandR, the ones to its right moved over.+#[cfg(target_os = "linux")]+fn xrandr_size(id: &str, (w, h): (u32, u32)) -> Result<(), String> {+ let (outputs, _) = parse_xrandr(&xrandr(&[])?);+ let (x, _, old_w, _) = outputs.iter().find(|o| o.name == id).and_then(|o| o.geometry).ok_or("That monitor isn't on.")?;+ let (_, modes) = parse_xrandr(&xrandr(&[])?);+ let ours = format!("{w}x{h}_muxen");+ let mode = if modes.contains(&ours) && !modes.contains(&format!("{w}x{h}")) { ours } else { format!("{w}x{h}") };+ let mut args = vec!["--output".to_string(), id.to_string(), "--mode".into(), mode];+ for o in outputs.iter().filter(|o| o.name != id) {+ if let Some((ox, oy, ..)) = o.geometry.filter(|g| g.0 >= x + old_w) {+ args.extend(["--output".to_string(), o.name.clone(), "--pos".into(), format!("{}x{oy}", ox + w as i64 - old_w)]);+ }+ }+ xrandr(&args).map(|_| ())+}++#[cfg(target_os = "macos")]+fn set_display(id: &str, size: Option<(u32, u32)>, scale: Option<f64>) -> Result<(), String> {+ let Some((w, h)) = size else {+ return Err(if scale.is_some() { "On a Mac, pick a size: it's sharp when the monitor has a Retina version of it." } else { "What size?" }.into());+ };+ let reply = in_session(&["display-mode".into(), id.into(), w.to_string(), h.to_string()])?;+ match reply["error"].as_str() {+ Some(e) => Err(e.to_string()),+ None => Ok(()),+ }+}++#[cfg(not(any(target_os = "linux", target_os = "macos")))]+fn set_display(_: &str, _: Option<(u32, u32)>, _: Option<f64>) -> Result<(), String> {+ Err("Not on this kind of machine yet.".into())+}++// ---------------------------------------------------------------------------+// A Mac: CoreGraphics displays; virtual ones held by `muxen-agent vdisplay`.++#[cfg(target_os = "macos")]+unsafe extern "C" {+ fn muxen_display_list(ids: *mut u32, max: usize) -> usize;+ fn muxen_display(id: u32, pixels_w: *mut usize, pixels_h: *mut usize, points_w: *mut f64, points_h: *mut f64, x: *mut f64, y: *mut f64);+ fn muxen_display_builtin(id: u32) -> i32;+ fn muxen_display_name(id: u32, buf: *mut u8, len: usize) -> usize;+ fn muxen_display_main() -> u32;+ fn muxen_display_modes(id: u32, sizes: *mut u32, max: usize) -> usize;+ fn muxen_display_set_mode(id: u32, w: u32, h: u32, err: *mut u8, errlen: usize) -> i32;+ fn muxen_vdisplay_create(w: u32, h: u32, name: *const std::ffi::c_char, err: *mut u8, errlen: usize) -> u32;+ fn muxen_vdisplay_run();+}++#[cfg(target_os = "macos")]+fn monitors() -> Result<Vec<Value>, String> {+ let mut ids = [0u32; 16];+ let n = unsafe { muxen_display_list(ids.as_mut_ptr(), ids.len()) };+ if n == 0 {+ return Err("No display here.".into());+ }+ let main = unsafe { muxen_display_main() };+ let mut external = 0;+ let own_name = |id: u32| {+ let mut buf = [0u8; 256];+ let n = unsafe { muxen_display_name(id, buf.as_mut_ptr(), buf.len()) };+ (n > 0).then(|| String::from_utf8_lossy(&buf[..n]).into_owned())+ };+ Ok(ids[..n]+ .iter()+ .map(|&id| {+ let (mut pw, mut ph, mut tw, mut th, mut x, mut y) = (0usize, 0usize, 0f64, 0f64, 0f64, 0f64);+ unsafe { muxen_display(id, &mut pw, &mut ph, &mut tw, &mut th, &mut x, &mut y) };+ let name = match own_name(id) {+ Some(n) => n,+ None if unsafe { muxen_display_builtin(id) } == 1 => "Built-in display".to_string(),+ None => {+ external += 1;+ format!("Display {external}")+ }+ };+ let mut modes = [(0u32, 0u32); 64];+ let count = unsafe { muxen_display_modes(id, modes.as_mut_ptr() as *mut u32, modes.len()) };+ let mut sizes: Vec<(u32, u32)> = modes[..count].to_vec();+ sizes.sort_by_key(|(w, h)| std::cmp::Reverse(w * h));+ sizes.dedup();+ let scale = if tw > 0. { (pw as f64 / tw * 100.).round() / 100. } else { 1. };+ json!({ "id": id.to_string(), "name": name, "x": x, "y": y, "width": tw, "height": th, "pixel_width": pw, "pixel_height": ph, "main": id == main, "modes": sizes, "scale": scale })+ })+ .collect())+}++/// `muxen-agent display-mode ID W H`: switches a display to that size (in+/// points; a Retina version of it when there is one). Run in the session.+#[cfg(target_os = "macos")]+pub fn run_mode(args: &[String]) -> i32 {+ let num = |i: usize| args.get(i).and_then(|a| a.parse::<u32>().ok()).unwrap_or(0);+ let mut err = [0u8; 256];+ let ok = unsafe { muxen_display_set_mode(num(0), num(1), num(2), err.as_mut_ptr(), err.len()) } == 0;+ let reply = if ok {+ json!({ "ok": true })+ } else {+ let end = err.iter().position(|b| *b == 0).unwrap_or(err.len());+ json!({ "error": String::from_utf8_lossy(&err[..end]) })+ };+ println!("{reply}");+ 0+}++/// Starts the process that holds the new display (in the desktop session) and+/// waits for its id.+#[cfg(target_os = "macos")]+fn add(w: u32, h: u32, label: &str, _password: Option<&str>) -> Result<Value, String> {+ let args = vec!["vdisplay".to_string(), w.to_string(), h.to_string(), label.to_string()];+ let line = if crate::gui::needed() {+ let mut stream = crate::gui::connect(&args)?;+ let mut text = String::new();+ stream.read_to_string(&mut text).map_err(|e| e.to_string())?;+ text+ } else {+ start_holder(&args)?+ };+ let reply: Value = serde_json::from_str(line.trim()).map_err(|_| "The virtual display didn't start.".to_string())?;+ match (reply["display"].as_u64(), reply["pid"].as_u64()) {+ (Some(id), Some(pid)) => Ok(json!({ "id": id.to_string(), "pid": pid })),+ _ => Err(reply["error"].as_str().unwrap_or("The virtual display didn't start.").to_string()),+ }+}++/// Runs `muxen-agent vdisplay ...` on its own (it outlives this process) and+/// returns its first line, with its pid added.+#[cfg(target_os = "macos")]+pub fn start_holder(args: &[String]) -> Result<String, String> {+ use std::io::BufRead;+ use std::os::unix::process::CommandExt;+ let exe = std::env::current_exe().map_err(|e| e.to_string())?;+ let mut cmd = Command::new(exe);+ cmd.args(args).stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::null());+ unsafe {+ cmd.pre_exec(|| {+ libc::setsid();+ Ok(())+ });+ }+ let mut child = cmd.spawn().map_err(|e| e.to_string())?;+ let pid = child.id();+ let stdout = child.stdout.take().ok_or("no output")?;+ let mut line = String::new();+ std::io::BufReader::new(stdout).read_line(&mut line).map_err(|e| e.to_string())?;+ let mut reply: Value = serde_json::from_str(line.trim()).unwrap_or_else(|_| json!({ "error": "The virtual display didn't start." }));+ reply["pid"] = json!(pid);+ // It keeps running; reap it later if it ends on its own.+ std::thread::spawn(move || {+ let _ = child.wait();+ });+ Ok(reply.to_string())+}++#[cfg(target_os = "macos")]+fn take_down(entry: &Value, _password: Option<&str>) -> Result<(), String> {+ let pid = entry["pid"].as_u64().ok_or("No process holds it.")? as i32;+ // Only our own holder: it was started with this registry entry.+ unsafe { libc::kill(pid, libc::SIGTERM) };+ Ok(())+}++/// `muxen-agent vdisplay <width> <height> <label>`: makes a virtual display,+/// says its id on stdout, and holds it until the process ends.+#[cfg(target_os = "macos")]+pub fn run_holder(args: &[String]) -> i32 {+ use std::io::Write;+ let num = |i: usize, d: u32| args.get(i).and_then(|a| a.parse::<u32>().ok()).unwrap_or(d);+ let (w, h) = (num(0, 1920), num(1, 1080));+ let label = args.get(2).cloned().unwrap_or_else(|| "Virtual".into());+ // Named like a real one: it shows as this in System Settings › Displays.+ let name = std::ffi::CString::new(label).unwrap_or_default();+ let mut err = [0u8; 256];+ let id = unsafe { muxen_vdisplay_create(w, h, name.as_ptr(), err.as_mut_ptr(), err.len()) };+ let mut out = std::io::stdout();+ if id == 0 {+ let why = String::from_utf8_lossy(&err[..err.iter().position(|b| *b == 0).unwrap_or(err.len())]).into_owned();+ let _ = writeln!(out, "{}", json!({ "error": format!("Couldn't make a virtual display: {why}") }));+ return 1;+ }+ let _ = writeln!(out, "{}", json!({ "display": id }));+ let _ = out.flush();+ unsafe { muxen_vdisplay_run() };+ 0+}++#[cfg(not(any(target_os = "linux", target_os = "macos")))]+fn monitors() -> Result<Vec<Value>, String> {+ Err("Displays work on Linux and macOS so far.".into())+}++#[cfg(not(any(target_os = "linux", target_os = "macos")))]+fn add(_: u32, _: u32, _: &str, _: Option<&str>) -> Result<Value, String> {+ Err("Virtual monitors work on Linux and macOS so far.".into())+}++#[cfg(not(target_os = "linux"))]+fn place_panels(_: &mut [Value], _: &[Value]) -> bool {+ false+}++#[cfg(not(target_os = "linux"))]+fn drop_panel(_: &Value) {}++#[cfg(not(any(target_os = "linux", target_os = "macos")))]+fn take_down(_: &Value, _: Option<&str>) -> Result<(), String> {+ Ok(())+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn reads_the_display_service() {+ let text = "(uint32 58, [(('DisplayPort-0', 'MUN', 'Display 2', '0x6acbefea'), [('[email protected]', 1920, 1080, 59.93, 1.0, [1.0, 2.0, 3.0], {'is-current': <true>, 'is-preferred': <true>}), ('1280x720@60', 1280, 720, 60.0, 1.0, [1.0, 2.0], {})], {'is-builtin': <false>, 'display-name': <'MUN 23\\'s'>}), (('HDMI-A-0', 'UGR', 'UGREEN', '0x2'), [('3840x2160@60', 3840, 2160, 60.0, 1.0, [1.0, 2.0], {'is-current': <true>})], {})], [(3840, 0, 2.0, uint32 0, false, [('DisplayPort-0', 'MUN', 'Display 2', '0x6acbefea')], @a{sv} {}), (0, 0, 2.0, 0, true, [('HDMI-A-0', 'UGR', 'UGREEN', '0x2')], {})], {'layout-mode': <uint32 2>, 'global-scale-required': <true>})\n";+ let l = Layout::read("org.cinnamon.Muffin.DisplayConfig", text).expect("parses");+ assert_eq!(l.serial, 58);+ assert!(l.physical && l.one_scale);+ assert_eq!(l.current("DisplayPort-0").map(|m| (m.w, m.h, m.id.as_str())), Some((1920, 1080, "[email protected]")));+ assert_eq!(l.mode_at("DisplayPort-0", (1280, 720)).map(|m| m.id.as_str()), Some("1280x720@60"));+ assert_eq!(l.monitors[1].outputs, ["HDMI-A-0"]);+ assert!(l.monitors[1].primary);+ assert_eq!(l.width(&l.monitors[0], None), 1920);+ assert_eq!(l.width(&l.monitors[0], Some((3840, 2160))), 3840);+ }++ #[test]+ fn edits_gvariant_lists() {+ let panels = strings("['1:0:top', '2:0:bottom']");+ assert_eq!(panels, ["1:0:top", "2:0:bottom"]);+ assert_eq!(gvariant(&panels), "['1:0:top', '2:0:bottom']");+ assert!(strings("@as []").is_empty());+ }++ #[test]+ fn reads_xrandr() {+ let text = r"Screen 0: minimum 320 x 200, current 3840 x 2160, maximum 16384 x 16384+DisplayPort-0 disconnected (normal left inverted right x axis y axis)+HDMI-A-0 connected primary 3840x2160+0+0 (normal left inverted right x axis y axis) 800mm x 450mm+ 1920x1080 60.00 + 120.00+ 3840x2160 60.00* 50.00+DisplayPort-1 disconnected 1920x1080+3840+0 (normal left inverted right x axis y axis) 0mm x 0mm+";+ let (outputs, modes) = parse_xrandr(text);+ assert_eq!(outputs.len(), 3);+ assert!(!outputs[0].connected && outputs[0].geometry.is_none());+ assert_eq!(outputs[1].geometry, Some((0, 0, 3840, 2160)));+ assert_eq!(outputs[2].geometry, Some((3840, 0, 1920, 1080)));+ assert_eq!(modes, vec!["1920x1080", "3840x2160"]);+ }++ #[test]+ fn names_outputs() {+ assert_eq!(output_kind("HDMI-A-0"), "HDMI");+ assert_eq!(output_kind("DisplayPort-1"), "DisplayPort");+ assert_eq!(output_kind("DP-2"), "DisplayPort");+ assert_eq!(output_kind("eDP-1"), "Built-in display");+ assert_eq!(output_kind("weird-0"), "weird-0");+ }++ #[test]+ fn describes_a_monitor() {+ let e = edid(1920, 1080, "Display 2");+ assert_eq!(e.len(), 256);+ assert_eq!(&e[..8], &[0, 255, 255, 255, 255, 255, 255, 0]);+ assert_eq!(e[..128].iter().map(|b| *b as u32).sum::<u32>() % 256, 0, "base checksum");+ assert_eq!(e[128..].iter().map(|b| *b as u32).sum::<u32>() % 256, 0, "extension checksum");+ assert_eq!((e[126], e[128]), (1, 0x02), "a CTA extension follows");+ // Every detailed timing: the size asked for first, then the bigger ones.+ let size = |d: &[u8]| ((d[2] as u32) | ((d[4] as u32 >> 4) << 8), (d[5] as u32) | ((d[7] as u32 >> 4) << 8));+ let mut sizes = vec![size(&e[54..72])];+ sizes.extend(e[132..].chunks(18).take_while(|d| d.len() == 18 && d[0..2] != [0, 0]).map(size));+ assert_eq!(sizes, [(1920, 1080), (3840, 2160), (3200, 1800), (2560, 1600), (2560, 1440), (2048, 1152)]);+ // A 4K one doesn't list itself twice.+ let k = edid(3840, 2160, "4K");+ assert_eq!(size(&k[54..72]), (3840, 2160));+ assert_eq!(size(&k[132..150]), (3200, 1800));+ // The detailed timing: 138.50 MHz, 1920 × 1080.+ assert_eq!(u16::from_le_bytes([e[54], e[55]]), 13850);+ assert_eq!((e[56] as u32) | ((e[58] as u32 >> 4) << 8), 1920);+ assert_eq!((e[59] as u32) | ((e[61] as u32 >> 4) << 8), 1080);+ assert_eq!(&e[77..87], b"Display 2\n");+ // 4K still fits the format.+ let k = edid(3840, 2160, "A very long monitor name");+ assert_eq!(k[..128].iter().map(|b| *b as u32).sum::<u32>() % 256, 0);+ assert_eq!(k[128..].iter().map(|b| *b as u32).sum::<u32>() % 256, 0);+ assert_eq!(&k[77..90], b"A very long m");+ }++ #[test]+ fn times_like_cvt() {+ // cvt -r 1920 1080: 138.50 1920 1968 2000 2080 1080 1083 1088 1111 +hsync -vsync+ let t = timing(1920, 1080);+ assert_eq!(t.clock, 13850);+ assert_eq!((t.w + t.h_front, t.w + t.h_front + t.h_sync, t.w + t.h_blank), (1968, 2000, 2080));+ assert_eq!((t.h + t.v_front, t.h + t.v_front + t.v_sync, t.h + t.v_blank), (1083, 1088, 1111));+ }+}diff --git a/agent/src/gui.rs b/agent/src/gui.rsindex 1c2bd0d..82b43bd 100644--- a/agent/src/gui.rs+++ b/agent/src/gui.rs@@ -52,7 +52,14 @@ fn run(mut conn: UnixStream) {let Ok(req) = crate::proto::read_line(&mut conn) else { return };let args: Vec<String> = req["run"].as_array().map(|a| a.iter().filter_map(|v| v.as_str().map(str::to_string)).collect()).unwrap_or_default();// Only the programs that need the session.- if !matches!(args.first().map(String::as_str), Some("screen" | "clip")) {+ if !matches!(args.first().map(String::as_str), Some("screen" | "clip" | "displays" | "display-mode" | "vdisplay")) {+ return;+ }+ // A virtual display's holder outlives the connection: start it, say its id.+ #[cfg(target_os = "macos")]+ if args.first().map(String::as_str) == Some("vdisplay") {+ let line = crate::displays::start_holder(&args).unwrap_or_else(|e| json!({ "error": e }).to_string());+ let _ = writeln!(conn, "{line}");return;}let Ok(exe) = std::env::current_exe() else { return };diff --git a/agent/src/link.rs b/agent/src/link.rsindex 7a56870..7bf5ab6 100644--- a/agent/src/link.rs+++ b/agent/src/link.rs@@ -359,7 +359,8 @@ fn attach(req: &Value, out: &Out, attached: &Attached) -> Value {}/// Starts streaming the desktop on a channel: `{"op": "desktop", "channel",-/// "fps", "quality", "max_width"}`. Replies with the frame size.+/// "fps", "quality", "max_width", "display"}` (see displays.rs; empty: the+/// whole desktop or the main display). Replies with the frame size.fn desktop(req: &Value, out: &Out, attached: &Attached) -> Value {let channel = req["channel"].as_u64().unwrap_or(0) as u32;if channel == CONTROL {@@ -370,7 +371,8 @@ fn desktop(req: &Value, out: &Out, attached: &Attached) -> Value {};let arg = |k: &str, d: u64| req[k].as_u64().unwrap_or(d).to_string();let mode = if req["tiles"].as_bool() == Some(true) { "tiles" } else { "frames" };- let args = vec!["screen".to_string(), arg("fps", 30), arg("quality", 75), arg("max_width", 1920), mode.to_string()];+ let display = req["display"].as_str().unwrap_or("").to_string();+ let args = vec!["screen".to_string(), arg("fps", 30), arg("quality", 75), arg("max_width", 1920), mode.to_string(), display];let (program, mut frames) = match Program::start(&args, env) {Ok(p) => p,Err(e) => return json!({ "ok": false, "error": format!("couldn't start capturing the screen: {e}") }),diff --git a/agent/src/mac_screen.m b/agent/src/mac_screen.mindex ea6a2a6..975952a 100644--- a/agent/src/mac_screen.m+++ b/agent/src/mac_screen.m@@ -1,7 +1,8 @@-// The Mac's screen for `muxen-agent screen`: ScreenCaptureKit streams the-// main display at the size asked for, and each new frame (BGRA) goes to a+// The Mac's screen for `muxen-agent screen`: ScreenCaptureKit streams a+// display at the size asked for, and each new frame (BGRA) goes to a// callback in Rust (see desktop.rs). Needs Screen Recording permission.+#import <AppKit/AppKit.h>#import <Foundation/Foundation.h>#import <CoreGraphics/CoreGraphics.h>#import <CoreMedia/CoreMedia.h>@@ -52,9 +53,12 @@ static void say(char *err, size_t len, NSString *what) {snprintf(err, len, "%s", what.UTF8String ? what.UTF8String : "unknown error");}-/// The main display: its size in pixels and in points (what input uses).-void muxen_display(size_t *pixels_w, size_t *pixels_h, double *points_w, double *points_h) {- CGDirectDisplayID id = CGMainDisplayID();+/// A display (0: the main one): its size in pixels and in points (what input+/// uses), and where it sits on the desktop, in points.+void muxen_display(uint32_t id, size_t *pixels_w, size_t *pixels_h, double *points_w, double *points_h, double *x, double *y) {+ if (id == 0) {+ id = CGMainDisplayID();+ }CGDisplayModeRef mode = CGDisplayCopyDisplayMode(id);*pixels_w = mode ? CGDisplayModeGetPixelWidth(mode) : CGDisplayPixelsWide(id);*pixels_h = mode ? CGDisplayModeGetPixelHeight(mode) : CGDisplayPixelsHigh(id);@@ -64,11 +68,123 @@ void muxen_display(size_t *pixels_w, size_t *pixels_h, double *points_w, doubleCGRect bounds = CGDisplayBounds(id);*points_w = bounds.size.width;*points_h = bounds.size.height;+ *x = bounds.origin.x;+ *y = bounds.origin.y;+}++uint32_t muxen_display_main(void) {+ return CGMainDisplayID();+}++/// The displays in use; how many.+size_t muxen_display_list(uint32_t *ids, size_t max) {+ uint32_t n = 0;+ if (CGGetActiveDisplayList((uint32_t)max, ids, &n) != kCGErrorSuccess) {+ return 0;+ }+ return n;}-/// Starts streaming the main display at width×height. 0 when it's going;+int muxen_display_builtin(uint32_t id) {+ return CGDisplayIsBuiltin(id) ? 1 : 0;+}++/// The display's own name ("Studio Display", "DELL U2720Q") into `buf`; its+/// length, or 0 when macOS doesn't say.+size_t muxen_display_name(uint32_t id, char *buf, size_t len) {+ @autoreleasepool {+ if (@available(macOS 10.15, *)) {+ for (NSScreen *screen in NSScreen.screens) {+ NSNumber *number = screen.deviceDescription[@"NSScreenNumber"];+ if (number && number.unsignedIntValue == id) {+ const char *name = screen.localizedName.UTF8String;+ if (!name || !*name) {+ return 0;+ }+ snprintf(buf, len, "%s", name);+ return strlen(buf);+ }+ }+ }+ return 0;+ }+}++/// A display's modes, Retina versions included.+static CFArrayRef muxen_modes(uint32_t id) {+ const void *keys[] = { kCGDisplayShowDuplicateLowResolutionModes };+ const void *values[] = { kCFBooleanTrue };+ CFDictionaryRef options = CFDictionaryCreate(NULL, keys, values, 1, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);+ CFArrayRef modes = CGDisplayCopyAllDisplayModes(id, options);+ CFRelease(options);+ return modes;+}++/// The sizes a display can be set to, in points, as width/height pairs into+/// `sizes` (room for `max` of them); how many (repeats included).+size_t muxen_display_modes(uint32_t id, uint32_t *sizes, size_t max) {+ CFArrayRef modes = muxen_modes(id);+ if (!modes) {+ return 0;+ }+ size_t n = 0;+ for (CFIndex i = 0; i < CFArrayGetCount(modes) && n < max; i++) {+ CGDisplayModeRef mode = (CGDisplayModeRef)CFArrayGetValueAtIndex(modes, i);+ if (!CGDisplayModeIsUsableForDesktopGUI(mode)) {+ continue;+ }+ sizes[n * 2] = (uint32_t)CGDisplayModeGetWidth(mode);+ sizes[n * 2 + 1] = (uint32_t)CGDisplayModeGetHeight(mode);+ n++;+ }+ CFRelease(modes);+ return n;+}++/// Switches a display to `w`×`h` points: the sharpest version of that size+/// (Retina when it has one), at the highest refresh rate. 0 when done;/// otherwise 1 and why in `err`.-int muxen_capture_start(int fps, size_t width, size_t height, muxen_frame_fn fn, void *ctx, char *err, size_t errlen) {+int muxen_display_set_mode(uint32_t id, uint32_t w, uint32_t h, char *err, size_t errlen) {+ CFArrayRef modes = muxen_modes(id);+ if (!modes) {+ snprintf(err, errlen, "That display isn't on.");+ return 1;+ }+ CGDisplayModeRef best = NULL;+ for (CFIndex i = 0; i < CFArrayGetCount(modes); i++) {+ CGDisplayModeRef mode = (CGDisplayModeRef)CFArrayGetValueAtIndex(modes, i);+ if (!CGDisplayModeIsUsableForDesktopGUI(mode) || CGDisplayModeGetWidth(mode) != w || CGDisplayModeGetHeight(mode) != h) {+ continue;+ }+ if (!best || CGDisplayModeGetPixelWidth(mode) > CGDisplayModeGetPixelWidth(best) ||+ (CGDisplayModeGetPixelWidth(mode) == CGDisplayModeGetPixelWidth(best) && CGDisplayModeGetRefreshRate(mode) > CGDisplayModeGetRefreshRate(best))) {+ best = mode;+ }+ }+ int failed = 1;+ CGDisplayConfigRef config;+ if (!best) {+ snprintf(err, errlen, "That size isn't one this display offers.");+ } else if (CGBeginDisplayConfiguration(&config) == kCGErrorSuccess) {+ CGConfigureDisplayWithDisplayMode(config, id, best, NULL);+ // Kept like a choice in System Settings; a virtual display only for now.+ if (CGCompleteDisplayConfiguration(config, kCGConfigurePermanently) == kCGErrorSuccess) {+ failed = 0;+ } else if (CGBeginDisplayConfiguration(&config) == kCGErrorSuccess) {+ CGConfigureDisplayWithDisplayMode(config, id, best, NULL);+ failed = CGCompleteDisplayConfiguration(config, kCGConfigureForSession) != kCGErrorSuccess;+ }+ if (failed) {+ snprintf(err, errlen, "macOS didn't switch the display.");+ }+ }+ CFRelease(modes);+ return failed;+}++/// Starts streaming a display (0: the main one) at width×height. 0 when it's+/// going; otherwise 1 and why in `err`.+int muxen_capture_start(uint32_t id, int fps, size_t width, size_t height, muxen_frame_fn fn, void *ctx, char *err, size_t errlen) {@autoreleasepool {dispatch_semaphore_t done = dispatch_semaphore_create(0);__block SCShareableContent *content = nil;@@ -88,13 +204,14 @@ int muxen_capture_start(int fps, size_t width, size_t height, muxen_frame_fn fn,say(err, errlen, failure ? failure.localizedDescription : @"no screen to show");return 1;}+ CGDirectDisplayID want = id ? id : CGMainDisplayID();SCDisplay *display = nil;for (SCDisplay *d in content.displays) {- if (d.displayID == CGMainDisplayID()) {+ if (d.displayID == want) {display = d;}}- if (!display) {+ if (!display && id == 0) {display = content.displays.firstObject;}if (!display) {@@ -211,3 +328,94 @@ void muxen_text(const uint16_t *utf16, size_t len) {}}}++// ---------------------------------------------------------------------------+// Virtual displays (like DeskPad): CGVirtualDisplay, part of CoreGraphics but+// not in its public headers. The display exists while this process holds it.++@interface CGVirtualDisplayDescriptor : NSObject+@property(retain, nonatomic) NSString *name;+@property(nonatomic) unsigned int maxPixelsHigh;+@property(nonatomic) unsigned int maxPixelsWide;+@property(nonatomic) CGSize sizeInMillimeters;+@property(nonatomic) unsigned int serialNum;+@property(nonatomic) unsigned int productID;+@property(nonatomic) unsigned int vendorID;+@property(copy, nonatomic) void (^terminationHandler)(id, id);+- (void)setDispatchQueue:(dispatch_queue_t)queue;+@end++@interface CGVirtualDisplayMode : NSObject+- (instancetype)initWithWidth:(unsigned int)width height:(unsigned int)height refreshRate:(double)refreshRate;+@end++@interface CGVirtualDisplaySettings : NSObject+@property(nonatomic) unsigned int hiDPI;+@property(retain, nonatomic) NSArray *modes;+@end++@interface CGVirtualDisplay : NSObject+- (instancetype)initWithDescriptor:(CGVirtualDisplayDescriptor *)descriptor;+- (BOOL)applySettings:(CGVirtualDisplaySettings *)settings;+@property(readonly, nonatomic) unsigned int displayID;+@end++static CGVirtualDisplay *muxen_virtual;++/// Makes a virtual display of width×height (points = pixels) called `name`;+/// its id, or 0 and why in `err`. Keep the process running to keep it.+uint32_t muxen_vdisplay_create(uint32_t width, uint32_t height, const char *name, char *err, size_t errlen) {+ @autoreleasepool {+ Class descriptorClass = NSClassFromString(@"CGVirtualDisplayDescriptor");+ Class displayClass = NSClassFromString(@"CGVirtualDisplay");+ Class settingsClass = NSClassFromString(@"CGVirtualDisplaySettings");+ Class modeClass = NSClassFromString(@"CGVirtualDisplayMode");+ if (!descriptorClass || !displayClass || !settingsClass || !modeClass) {+ say(err, errlen, @"this version of macOS can't make virtual displays");+ return 0;+ }+ CGVirtualDisplayDescriptor *descriptor = [[descriptorClass alloc] init];+ [descriptor setDispatchQueue:dispatch_get_main_queue()];+ descriptor.name = [NSString stringWithUTF8String:name ? name : "Muxen"];+ // Room for every size it offers (like a real monitor's list).+ descriptor.maxPixelsWide = width > 3840 ? width : 3840;+ descriptor.maxPixelsHigh = height > 2160 ? height : 2160;+ // About 96 dpi.+ descriptor.sizeInMillimeters = CGSizeMake(width * 0.2646, height * 0.2646);+ descriptor.vendorID = 0x4d58; // "MX"+ descriptor.productID = 0x0001;+ descriptor.serialNum = (unsigned int)getpid();+ descriptor.terminationHandler = ^(id a, id b) {+ exit(0);+ };+ muxen_virtual = [[displayClass alloc] initWithDescriptor:descriptor];+ if (!muxen_virtual || muxen_virtual.displayID == 0) {+ say(err, errlen, @"macOS refused the virtual display");+ return 0;+ }+ CGVirtualDisplaySettings *settings = [[settingsClass alloc] init];+ settings.hiDPI = 0;+ // The size asked for first (what it starts at), then the usual ones,+ // so System Settings › Displays can switch it like a real monitor.+ static const unsigned int sizes[][2] = {{3840, 2160}, {3200, 1800}, {2560, 1600}, {2560, 1440}, {2048, 1152}, {1920, 1200},+ {1920, 1080}, {1680, 1050}, {1600, 900}, {1440, 900}, {1280, 800}, {1280, 720}, {1024, 768}};+ NSMutableArray *modes = [NSMutableArray arrayWithObject:[[modeClass alloc] initWithWidth:width height:height refreshRate:60]];+ for (size_t i = 0; i < sizeof sizes / sizeof sizes[0]; i++) {+ if (sizes[i][0] != width || sizes[i][1] != height) {+ [modes addObject:[[modeClass alloc] initWithWidth:sizes[i][0] height:sizes[i][1] refreshRate:60]];+ }+ }+ settings.modes = modes;+ if (![muxen_virtual applySettings:settings]) {+ say(err, errlen, @"macOS didn't accept the display's size");+ muxen_virtual = nil;+ return 0;+ }+ return muxen_virtual.displayID;+ }+}++/// Holds the virtual display until the process is told to stop.+void muxen_vdisplay_run(void) {+ dispatch_main();+}diff --git a/agent/src/main.rs b/agent/src/main.rsindex b951a32..4d9ad0d 100644--- a/agent/src/main.rs+++ b/agent/src/main.rs@@ -25,6 +25,8 @@ mod detect;#[cfg(unix)]mod desktop;#[cfg(unix)]+mod displays;+#[cfg(unix)]mod direct;#[cfg(unix)]mod files;@@ -65,6 +67,12 @@ fn main() {Some("migrate") => direct::migrate(),#[cfg(unix)]Some("screen") => desktop::run(&args[1..]),+ #[cfg(unix)]+ Some("displays") => displays::run_list(),+ #[cfg(target_os = "macos")]+ Some("vdisplay") => displays::run_holder(&args[1..]),+ #[cfg(target_os = "macos")]+ Some("display-mode") => displays::run_mode(&args[1..]),Some("clip") => clipboard::run(),#[cfg(unix)]Some("attach") => match args.get(1) {diff --git a/assets/fonts/NERD-FONTS-LICENSE.txt b/assets/fonts/NERD-FONTS-LICENSE.txtnew file mode 100644index 0000000..06eb073--- /dev/null+++ b/assets/fonts/NERD-FONTS-LICENSE.txt@@ -0,0 +1,21 @@+The MIT License (MIT)++Copyright (c) 2014 Ryan L McIntyre++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.diff --git a/assets/fonts/symbols-nerd-font-mono.ttf b/assets/fonts/symbols-nerd-font-mono.ttfnew file mode 100644index 0000000..3b5a184Binary files /dev/null and b/assets/fonts/symbols-nerd-font-mono.ttf differdiff --git a/assets/icons/columns-2.svg b/assets/icons/columns-2.svgnew file mode 100644index 0000000..be4fc9c--- /dev/null+++ b/assets/icons/columns-2.svg@@ -0,0 +1,15 @@+<!-- @license lucide-static v1.53.0 - ISC -->+<svg+ class="lucide lucide-columns-2"+ xmlns="http://www.w3.org/2000/svg"+ width="24"+ height="24"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ stroke-width="1.6"+ stroke-linecap="round"+ stroke-linejoin="round"+>+ <rect width="18" height="18" x="3" y="3" rx="2" /><path d="M12 3v18" />+</svg>diff --git a/assets/icons/rows-2.svg b/assets/icons/rows-2.svgnew file mode 100644index 0000000..e41bf8b--- /dev/null+++ b/assets/icons/rows-2.svg@@ -0,0 +1,15 @@+<!-- @license lucide-static v1.53.0 - ISC -->+<svg+ class="lucide lucide-rows-2"+ xmlns="http://www.w3.org/2000/svg"+ width="24"+ height="24"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ stroke-width="1.6"+ stroke-linecap="round"+ stroke-linejoin="round"+>+ <rect width="18" height="18" x="3" y="3" rx="2" /><path d="M3 12h18" />+</svg>diff --git a/src/api.rs b/src/api.rsindex 7b5bd17..93286dd 100644--- a/src/api.rs+++ b/src/api.rs@@ -2972,22 +2972,100 @@ pub async fn set_direct(engine: &Arc<Engine>, req: DirectRequest) -> ApiResult<c#[serde(deny_unknown_fields)]pub struct DesktopInputRequest {pub machine_id: String,+ /// One of the machine's displays (desktop_displays); default: the whole desktop or the main display.+ #[serde(default)]+ pub display: Option<String>,pub events: Vec<crate::fleet::desktop::DesktopEvent>,}-/// What's on a machine's screen (a JPEG, plus its size).-pub async fn desktop_screenshot(engine: &Arc<Engine>, machine_id: &str) -> ApiResult<crate::fleet::desktop::Screenshot> {+/// What's on a machine's screen, or one of its displays (a JPEG, plus its size).+pub async fn desktop_screenshot(engine: &Arc<Engine>, machine_id: &str, display: Option<&str>) -> ApiResult<crate::fleet::desktop::Screenshot> {let m = find_machine(&engine.current(), machine_id)?.clone();- engine.desktop_screenshot(&m.id).await.map_err(|e| ApiError::new("operation_failed", e))+ engine.desktop_screenshot(&m.id, display).await.map_err(|e| ApiError::new("operation_failed", e))}/// Moves, clicks, scrolls and types on a machine's desktop.pub async fn desktop_input(engine: &Arc<Engine>, req: DesktopInputRequest) -> ApiResult<serde_json::Value> {let m = find_machine(&engine.current(), &req.machine_id)?.clone();- let n = engine.desktop_input(&m.id, &req.events).await.map_err(|e| ApiError::new("operation_failed", e))?;+ let n = engine.desktop_input(&m.id, req.display.as_deref(), &req.events).await.map_err(|e| ApiError::new("operation_failed", e))?;Ok(serde_json::json!({ "machine_id": m.id, "events": n, "next": "Take a desktop_screenshot to see the result." }))}+/// A machine's monitors, virtual ones included.+pub async fn desktop_displays(engine: &Arc<Engine>, req: MachineRequest) -> ApiResult<Vec<crate::fleet::model::DisplayInfo>> {+ let m = find_machine(&engine.current(), &req.machine_id)?.clone();+ engine.displays(&m.id).await.map_err(|e| ApiError::new("operation_failed", e))+}++#[derive(Debug, Deserialize)]+#[serde(deny_unknown_fields)]+pub struct AddDisplayRequest {+ pub machine_id: String,+ /// Default 1920×1080.+ #[serde(default)]+ pub width: Option<u32>,+ #[serde(default)]+ pub height: Option<u32>,+ #[serde(default)]+ pub name: Option<String>,+}++/// Agents don't type the user's password: the app asks for it.+fn display_error(e: crate::fleet::desktop::AddDisplayError) -> ApiError {+ match e {+ crate::fleet::desktop::AddDisplayError::NeedsPassword(why) => ApiError::invalid(why)+ .with_hint("Ask the user to add or remove this monitor from the Muxen app (the machine's desktop › Add monitor); it asks for their password there."),+ crate::fleet::desktop::AddDisplayError::Failed(why) => ApiError::new("operation_failed", why),+ }+}++/// Adds a virtual monitor to a machine's desktop.+pub async fn desktop_add_display(engine: &Arc<Engine>, req: AddDisplayRequest) -> ApiResult<crate::fleet::model::DisplayInfo> {+ let m = find_machine(&engine.current(), &req.machine_id)?.clone();+ // The main monitor's size unless told otherwise.+ let known = if m.displays.is_empty() && (req.width.is_none() || req.height.is_none()) { engine.displays(&m.id).await.unwrap_or_default() } else { m.displays.clone() };+ let screens: Vec<_> = known.iter().filter(|d| d.id != "all").collect();+ let main = screens.iter().find(|d| d.main).or(screens.first()).map(|d| (d.width.round() as u32, d.height.round() as u32)).unwrap_or((1920, 1080));+ let (w, h) = (req.width.unwrap_or(main.0), req.height.unwrap_or(main.1));+ engine.add_display(&m.id, w, h, req.name.as_deref()).await.map_err(display_error)+}++#[derive(Debug, Deserialize)]+#[serde(deny_unknown_fields)]+pub struct SetDisplayRequest {+ pub machine_id: String,+ pub display: String,+ pub width: Option<u32>,+ pub height: Option<u32>,+ pub scale: Option<f64>,+}++/// Sets a monitor's size (one it offers: see `modes`) or the desktop's scale on it.+pub async fn desktop_set_display(engine: &Arc<Engine>, req: SetDisplayRequest) -> ApiResult<crate::fleet::model::DisplayInfo> {+ let m = find_machine(&engine.current(), &req.machine_id)?.clone();+ let size = req.width.zip(req.height);+ if size.is_none() && req.scale.is_none() {+ return Err(ApiError::new("invalid", "Pass width and height, or scale."));+ }+ engine.set_display(&m.id, &req.display, size, req.scale).await.map_err(|e| ApiError::new("operation_failed", e))?;+ let shown = engine.current().machines.iter().find(|x| x.id == m.id).and_then(|x| x.displays.iter().find(|d| d.id == req.display).cloned());+ shown.ok_or_else(|| ApiError::new("not_found", format!("{} isn't one of {}'s displays now.", req.display, m.name)))+}++#[derive(Debug, Deserialize)]+#[serde(deny_unknown_fields)]+pub struct RemoveDisplayRequest {+ pub machine_id: String,+ pub display: String,+}++/// Removes a virtual monitor Muxen added.+pub async fn desktop_remove_display(engine: &Arc<Engine>, req: RemoveDisplayRequest) -> ApiResult<serde_json::Value> {+ let m = find_machine(&engine.current(), &req.machine_id)?.clone();+ engine.remove_display(&m.id, &req.display).await.map_err(display_error)?;+ Ok(serde_json::json!({ "machine_id": m.id, "removed": req.display }))+}+/// Git checkouts on the machines, re-read first.pub async fn checkouts(engine: &Arc<Engine>, req: CheckoutsRequest) -> ApiResult<Vec<Checkout>> {let machines = session_machines(engine, req.machine_id.as_deref())?;diff --git a/src/fleet/build.rs b/src/fleet/build.rsindex 91aaa72..aaa99b3 100644--- a/src/fleet/build.rs+++ b/src/fleet/build.rs@@ -192,6 +192,7 @@ pub fn build(input: &Inputs) -> Snapshot {},}}),+ displays: Vec::new(),});}diff --git a/src/fleet/desktop.rs b/src/fleet/desktop.rsindex 4486520..e638d77 100644--- a/src/fleet/desktop.rs+++ b/src/fleet/desktop.rs@@ -11,6 +11,7 @@ use tokio::sync::mpsc;use super::link::{self, Link};use super::Engine;+use super::model::DisplayInfo;/// Desktop frames and input on a link channel.pub const FRAME: u8 = 20;@@ -107,14 +108,14 @@ impl Drop for Opened {}impl Engine {- async fn open_desktop(self: &Arc<Self>, machine_id: &str, fps: u32) -> Result<Opened, String> {+ async fn open_desktop(self: &Arc<Self>, machine_id: &str, display: Option<&str>, fps: u32) -> Result<Opened, String> {let (spec, _) = self.machine(machine_id).ok_or_else(|| format!("No machine called {machine_id}."))?;if self.demo_world().is_some() {return Err("The demo has no desktops to show.".into());}let link = link::get(&spec).await.ok_or_else(|| format!("Can't reach the agent on {}.", spec.name))?;let (channel, frames) = link.open_channel();- let reply = link.request(json!({ "op": "desktop", "channel": channel, "fps": fps, "quality": 75, "max_width": 1920 }), Duration::from_secs(20)).await;+ let reply = link.request(json!({ "op": "desktop", "channel": channel, "fps": fps, "quality": 75, "max_width": 1920, "display": display.unwrap_or("") }), Duration::from_secs(20)).await;match reply {Ok(r) if r["ok"].as_bool() == Some(true) => Ok(Opened { link, channel, frames, info: r }),Ok(r) => {@@ -128,9 +129,9 @@ impl Engine {}}- /// What's on the machine's screen right now, as a JPEG.- pub async fn desktop_screenshot(self: &Arc<Self>, machine_id: &str) -> Result<Screenshot, String> {- let mut d = self.open_desktop(machine_id, 2).await?;+ /// What's on the machine's screen right now (or one of its displays), as a JPEG.+ pub async fn desktop_screenshot(self: &Arc<Self>, machine_id: &str, display: Option<&str>) -> Result<Screenshot, String> {+ let mut d = self.open_desktop(machine_id, display, 2).await?;let size = |k: &str| d.info[k].as_u64().unwrap_or(0) as u32;let (width, height, screen_width, screen_height) = (size("width"), size("height"), size("screen_width"), size("screen_height"));let first = tokio::time::timeout(Duration::from_secs(15), async {@@ -149,12 +150,13 @@ impl Engine {}}- /// Moves, clicks, scrolls and types on the machine's desktop, in order.- pub async fn desktop_input(self: &Arc<Self>, machine_id: &str, events: &[DesktopEvent]) -> Result<usize, String> {+ /// Moves, clicks, scrolls and types on the machine's desktop (or one of+ /// its displays), in order.+ pub async fn desktop_input(self: &Arc<Self>, machine_id: &str, display: Option<&str>, events: &[DesktopEvent]) -> Result<usize, String> {if events.is_empty() {return Err("Give at least one event.".into());}- let d = self.open_desktop(machine_id, 1).await?;+ let d = self.open_desktop(machine_id, display, 1).await?;let pause = || tokio::time::sleep(Duration::from_millis(40));for e in events {match e {@@ -190,4 +192,167 @@ impl Engine {drop(d);Ok(events.len())}++ /// The machine's monitors, virtual ones included (and remembers them).+ pub async fn displays(self: &Arc<Self>, machine_id: &str) -> Result<Vec<DisplayInfo>, String> {+ let (spec, probe) = self.machine(machine_id).ok_or_else(|| format!("No machine called {machine_id}."))?;+ let found = if self.demo_world().is_some() {+ demo_displays(&spec.id)+ } else {+ super::sessions::agent::ensure(&spec, probe.as_ref()).await?;+ let reply = super::sessions::agent::ctl(&spec, &json!({ "op": "displays" })).await?;+ serde_json::from_value(reply["displays"].clone()).map_err(|_| format!("{} gave a list of displays Muxen can't read.", spec.name))?+ };+ self.set_displays(&spec.id, found.clone());+ Ok(found)+ }++ /// Adds a virtual monitor (`width`×`height`) to the machine's desktop.+ pub async fn add_display(self: &Arc<Self>, machine_id: &str, width: u32, height: u32, name: Option<&str>) -> Result<DisplayInfo, AddDisplayError> {+ let (spec, probe) = self.machine(machine_id).ok_or_else(|| format!("No machine called {machine_id}."))?;+ if self.demo_world().is_some() {+ return Err("The demo doesn't add monitors.".into());+ }+ super::sessions::agent::ensure(&spec, probe.as_ref()).await?;+ let password = password_for(&spec.id);+ let request = json!({ "op": "display_create", "width": width, "height": height, "label": name.unwrap_or(""), "password": password.as_deref().unwrap_or("") });+ let reply = super::sessions::agent::ctl_reply(&spec, &request).await?;+ if reply["ok"].as_bool() != Some(true) {+ return Err(refusal(&spec.id, &reply, "The machine couldn't add a monitor."));+ }+ let id = reply["display"]["id"].as_str().unwrap_or_default().to_string();+ // Its place on the desktop and its name, as the machine lists it now.+ let all = self.displays(&spec.id).await.unwrap_or_default();+ all.into_iter().find(|d| d.id == id).ok_or_else(|| format!("The new monitor didn't show up on {}.", spec.name).into())+ }++ /// What to call one of a machine's displays (kept on the machine, so every+ /// Muxen sees it). An empty name goes back to its own.+ pub async fn rename_display(self: &Arc<Self>, machine_id: &str, display: &str, name: &str) -> Result<(), String> {+ let (spec, probe) = self.machine(machine_id).ok_or_else(|| format!("No machine called {machine_id}."))?;+ if self.demo_world().is_some() {+ return Err("The demo doesn't rename monitors.".into());+ }+ super::sessions::agent::ensure(&spec, probe.as_ref()).await?;+ super::sessions::agent::ctl(&spec, &json!({ "op": "display_rename", "display": display, "name": name })).await?;+ let _ = self.displays(&spec.id).await;+ Ok(())+ }++ /// Sets a monitor's size, or how much the desktop scales things up on it+ /// (on X11, one scale for all its monitors).+ pub async fn set_display(self: &Arc<Self>, machine_id: &str, display: &str, size: Option<(u32, u32)>, scale: Option<f64>) -> Result<(), String> {+ let (spec, probe) = self.machine(machine_id).ok_or_else(|| format!("No machine called {machine_id}."))?;+ if self.demo_world().is_some() {+ return Err("The demo doesn't change monitors.".into());+ }+ super::sessions::agent::ensure(&spec, probe.as_ref()).await?;+ let mut request = json!({ "op": "display_set", "display": display });+ if let Some((w, h)) = size {+ request["width"] = json!(w);+ request["height"] = json!(h);+ }+ if let Some(s) = scale {+ request["scale"] = json!(s);+ }+ super::sessions::agent::ctl(&spec, &request).await?;+ let _ = self.displays(&spec.id).await;+ Ok(())+ }++ /// The user's password on a machine, for adding and removing its virtual+ /// monitors (Linux asks sudo). Kept in memory while Muxen runs, nowhere else.+ pub fn remember_password(&self, machine_id: &str, password: String) {+ passwords().lock().unwrap().insert(machine_id.to_string(), password);+ }++ /// Removes a virtual monitor Muxen added.+ pub async fn remove_display(self: &Arc<Self>, machine_id: &str, display: &str) -> Result<(), AddDisplayError> {+ let (spec, probe) = self.machine(machine_id).ok_or_else(|| format!("No machine called {machine_id}."))?;+ if self.demo_world().is_some() {+ return Err("The demo doesn't remove monitors.".into());+ }+ super::sessions::agent::ensure(&spec, probe.as_ref()).await?;+ let password = password_for(&spec.id);+ let request = json!({ "op": "display_remove", "display": display, "password": password.as_deref().unwrap_or("") });+ let reply = super::sessions::agent::ctl_reply(&spec, &request).await?;+ if reply["ok"].as_bool() != Some(true) {+ return Err(refusal(&spec.id, &reply, "The machine couldn't remove the monitor."));+ }+ let _ = self.displays(&spec.id).await;+ Ok(())+ }+}++/// Passwords the user gave this session, by machine (see `remember_password`).+fn passwords() -> &'static std::sync::Mutex<std::collections::HashMap<String, String>> {+ static PASSWORDS: std::sync::OnceLock<std::sync::Mutex<std::collections::HashMap<String, String>>> = std::sync::OnceLock::new();+ PASSWORDS.get_or_init(Default::default)+}++fn password_for(machine_id: &str) -> Option<String> {+ passwords().lock().unwrap().get(machine_id).cloned()+}++/// Why the machine said no; a password it didn't take is forgotten.+fn refusal(machine_id: &str, reply: &Value, fallback: &str) -> AddDisplayError {+ let why = reply["error"].as_str().unwrap_or(fallback).to_string();+ if reply["password"].as_bool() == Some(true) {+ passwords().lock().unwrap().remove(machine_id);+ AddDisplayError::NeedsPassword(why)+ } else {+ AddDisplayError::Failed(why)+ }+}++/// Why a monitor wasn't added or removed.+#[derive(Debug, Clone)]+pub enum AddDisplayError {+ /// The machine wants the user's password (sudo, on Linux): the app asks for it.+ NeedsPassword(String),+ Failed(String),+}++impl From<String> for AddDisplayError {+ fn from(e: String) -> Self {+ AddDisplayError::Failed(e)+ }+}++impl From<&str> for AddDisplayError {+ fn from(e: &str) -> Self {+ AddDisplayError::Failed(e.to_string())+ }+}++impl std::fmt::Display for AddDisplayError {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ match self {+ AddDisplayError::NeedsPassword(e) | AddDisplayError::Failed(e) => f.write_str(e),+ }+ }+}++/// The demo's monitors: one each, two on Forge.+fn demo_displays(machine_id: &str) -> Vec<DisplayInfo> {+ let one = |id: &str, name: &str, x: f64, w: f64, h: f64, main: bool| DisplayInfo {+ id: id.into(),+ name: name.into(),+ x,+ y: 0.,+ width: w,+ height: h,+ main,+ is_virtual: false,+ modes: vec![(w as u32, h as u32)],+ any_size: false,+ scale: 1.,+ scales: Vec::new(),+ };+ match machine_id {+ "forge" => vec![one("1", "Studio Display", 0., 2560., 1440., true), one("2", "Built-in display", 2560., 1512., 982., false)],+ "orbit" | "harbor" => vec![one("1", "Built-in display", 0., 1728., 1117., true)],+ "pebble" => vec![one("eDP-1", "eDP-1", 0., 1920., 1200., true)],+ _ => Vec::new(),+ }}diff --git a/src/fleet/engine.rs b/src/fleet/engine.rsindex 3447cf3..bdd3f8e 100644--- a/src/fleet/engine.rs+++ b/src/fleet/engine.rs@@ -75,6 +75,8 @@ struct State {tailscale: Option<super::model::TailscaleStatus>,/// Cloud machines' power as the provider last reported it ("active", "off", ...).droplets: HashMap<String, String>,+ /// Machines' monitors, as last listed (see fleet::desktop).+ displays: HashMap<String, Vec<super::model::DisplayInfo>>,/// Stop flags of the operations that can be cancelled.cancels: HashMap<u64, Arc<std::sync::atomic::AtomicBool>>,}@@ -146,6 +148,7 @@ impl Engine {tailnet: persisted.tailnet,tailscale: None,droplets: persisted.droplets,+ displays: HashMap::new(),cancels: HashMap::new(),};let (tx, _) = watch::channel(Arc::new(Snapshot::default()));@@ -224,6 +227,23 @@ impl Engine {self.rt.spawn(async move { me.tailnet_loop().await });let me = self.clone();self.rt.spawn(async move { me.network_loop().await });+ // Monitors aren't kept between runs: ask the machines with a desktop+ // now, not at the next check (which may be minutes away).+ let me = self.clone();+ self.rt.spawn(async move {+ if me.demo.is_some() {+ return;+ }+ let snap = me.current();+ let ids: Vec<String> = snap+ .machines+ .iter()+ .filter(|m| m.status != "offline" && !m.host.is_empty())+ .filter(|m| m.platform.starts_with("darwin") || m.probe.as_ref().and_then(|p| p.desktop) == Some(true))+ .map(|m| m.id.clone())+ .collect();+ futures::future::join_all(ids.iter().map(|id| me.displays(id))).await;+ });}pub fn subscribe(&self) -> watch::Receiver<Arc<Snapshot>> {@@ -589,6 +609,15 @@ impl Engine {self.publish(&mut st);}+ /// What the machine's monitors are now (see fleet::desktop).+ pub(crate) fn set_displays(&self, machine_id: &str, displays: Vec<super::model::DisplayInfo>) {+ let mut st = self.state.lock().unwrap();+ if st.displays.get(machine_id) != Some(&displays) {+ st.displays.insert(machine_id.to_string(), displays);+ self.publish(&mut st);+ }+ }+/// Renames a direct session; its info afterwards.pub(crate) fn set_direct_title(&self, id: &str, title: &str) -> Option<SessionInfo> {let mut st = self.state.lock().unwrap();@@ -929,6 +958,8 @@ impl Engine {let mut st = self.state.lock().unwrap();st.checking.remove(&id);let result = result.after(st.probes.get(&id));+ // Its monitors are worth knowing when it has a desktop to show.+ let desktop = result.os.as_deref() == Some("darwin") || result.desktop == Some(true);st.probes.insert(id.clone(), result);self.publish(&mut st);drop(st);@@ -937,6 +968,9 @@ impl Engine {let me = self.clone();self.rt.spawn(async move {let _ = me.refresh_sessions(&id).await;+ if desktop {+ let _ = me.displays(&id).await;+ }});}}@@ -1092,6 +1126,9 @@ impl Engine {snapshot.operations = st.operations.iter().cloned().collect();snapshot.workspaces = workspaces::snapshot_infos(&st.workspaces, &snapshot.machines, &st.inventory.machines);for m in &mut snapshot.machines {+ if let Some(d) = st.displays.get(&m.id) {+ m.displays = d.clone();+ }if let Some(found) = st.sessions.get(&m.id) {m.agents = found.agents.clone();m.agent_version = found.agent_version.clone();diff --git a/src/fleet/model.rs b/src/fleet/model.rsindex a1013b8..f441317 100644--- a/src/fleet/model.rs+++ b/src/fleet/model.rs@@ -212,6 +212,43 @@ pub struct Machine {pub tailnet: Option<TailnetDevice>,/// A cloud machine Muxen created: where it runs and what it costs.pub cloud: Option<CloudInfo>,+ /// Its monitors, virtual ones included, as last listed (empty until then).+ pub displays: Vec<DisplayInfo>,+}++/// One of a machine's monitors: a real one, or a virtual one Muxen added.+#[derive(Debug, Clone, Serialize, serde::Deserialize, PartialEq)]+pub struct DisplayInfo {+ /// What to pass as `display`: a RandR monitor's name on Linux ("all": the+ /// whole desktop), the display's number on a Mac.+ pub id: String,+ pub name: String,+ #[serde(default)]+ pub x: f64,+ #[serde(default)]+ pub y: f64,+ pub width: f64,+ pub height: f64,+ /// The main (primary) display.+ #[serde(default)]+ pub main: bool,+ /// A virtual monitor Muxen added (and can remove).+ #[serde(default, rename = "virtual")]+ pub is_virtual: bool,+ /// The sizes it can be set to, biggest first (empty: it can't be, or+ /// nobody knows).+ #[serde(default)]+ pub modes: Vec<(u32, u32)>,+ /// Any size can be given to it, not only `modes` (Linux).+ #[serde(default)]+ pub any_size: bool,+ /// How much the desktop scales things up on it (2: twice as big, as+ /// sharp); 0 when unknown.+ #[serde(default)]+ pub scale: f64,+ /// The scales it can be set to (empty: it can't be).+ #[serde(default)]+ pub scales: Vec<f64>,}#[derive(Debug, Clone, Serialize)]diff --git a/src/fleet/sessions/agent.rs b/src/fleet/sessions/agent.rsindex cc0c24b..3ada748 100644--- a/src/fleet/sessions/agent.rs+++ b/src/fleet/sessions/agent.rs@@ -185,13 +185,20 @@ pub async fn gh_token(spec: &MachineSpec, gh: &str, hostname: &str) -> Result<St/// One request to the agent; its JSON reply, or the error it gave. Over the/// machine's live link when there is one, else a one-off ssh call.pub async fn ctl(spec: &MachineSpec, request: &Value) -> Result<Value, String> {+ let reply = ctl_reply(spec, request).await?;+ if reply["ok"].as_bool() == Some(true) {+ Ok(reply)+ } else {+ Err(reply["error"].as_str().unwrap_or("the agent couldn't do that").to_string())+ }+}++/// Like `ctl`, but the agent's whole reply, refusals included (for the+/// details beside the error). Err only when it couldn't be asked.+pub async fn ctl_reply(spec: &MachineSpec, request: &Value) -> Result<Value, String> {if let Some(link) = crate::fleet::link::get(spec).await {if let Ok(reply) = link.request(request.clone(), CTL_TIMEOUT).await {- return if reply["ok"].as_bool() == Some(true) {- Ok(reply)- } else {- Err(reply["error"].as_str().unwrap_or("the agent couldn't do that").to_string())- };+ return Ok(reply);}}let json = request.to_string();@@ -210,9 +217,5 @@ pub async fn ctl(spec: &MachineSpec, request: &Value) -> Result<Value, String> {.find(|l| l.trim_start().starts_with('{')).and_then(|l| serde_json::from_str(l).ok()).ok_or_else(|| format!("The agent on {} gave no answer.", spec.name))?;- if reply["ok"].as_bool() == Some(true) {- Ok(reply)- } else {- Err(reply["error"].as_str().unwrap_or("the agent couldn't do that").to_string())- }+ Ok(reply)}diff --git a/src/fleet/sessions/mod.rs b/src/fleet/sessions/mod.rsindex 4669d02..583f913 100644--- a/src/fleet/sessions/mod.rs+++ b/src/fleet/sessions/mod.rs@@ -264,7 +264,11 @@ impl Engine {let name = format!("{}-{}", kind.id, super::workspaces::random_id(4));let cwd = if req.cwd.trim().is_empty() { "~".to_string() } else { req.cwd.trim().to_string() };let title = req.title.clone().filter(|t| !t.trim().is_empty()).unwrap_or_else(|| default_title(kind, &cwd));- // "Shell · home", "Shell · home 2", ... so sessions on a machine are told apart.+ // "Shell · home", "Shell · home 2", ... so sessions on a machine are told apart+ // (knowing which it has: the CLI starts without having asked).+ if self.sessions_of(&spec.id).is_none_or(|f| f.checked_at.is_none()) && self.demo_world().is_none() {+ let _ = self.refresh_sessions(&spec.id).await;+ }let taken: Vec<String> = self.sessions_of(&spec.id).map(|f| f.sessions.into_iter().map(|s| s.title).collect()).unwrap_or_default();let title = unique_title(&title, &taken);@@ -540,6 +544,15 @@ fn closes_on_exit(s: &SessionInfo) -> bool {s.status == "exited" && (s.agent == "shell" || s.exit_code == Some(0))}+#[cfg(test)]+#[test]+fn titles_name_the_folder() {+ let shell = agent("shell").unwrap();+ for (cwd, title) in [("~", "Shell · home"), ("/home/adib", "Shell · home"), ("/Users/adib/", "Shell · home"), ("/root", "Shell · home"), ("~/code/api", "Shell · api"), ("/home/adib/openrunner", "Shell · openrunner")] {+ assert_eq!(default_title(shell, cwd), title, "{cwd}");+ }+}+/// `title`, or `title 2`, `title 3`, ... when a session already has it.fn unique_title(title: &str, taken: &[String]) -> String {if !taken.iter().any(|t| t == title) {@@ -560,7 +573,11 @@ fn clean_title(title: &str) -> Result<String, String> {/// A short default title: the agent and the folder it works in.fn default_title(kind: &AgentKind, cwd: &str) -> String {- let folder = cwd.trim_end_matches('/').rsplit('/').next().filter(|f| !f.is_empty() && *f != "~").unwrap_or("home");+ let path = cwd.trim_end_matches('/');+ // The home folder, however it's written: "~", /home/adib, /Users/adib, /root.+ let parts: Vec<&str> = path.split('/').collect();+ let home = path.is_empty() || path == "~" || path == "/root" || matches!(parts[..], ["", "home" | "Users", user] if !user.is_empty());+ let folder = if home { "home" } else { path.rsplit('/').next().filter(|f| !f.is_empty()).unwrap_or("home") };format!("{} · {folder}", kind.name)}diff --git a/src/fleet/workspaces/tests.rs b/src/fleet/workspaces/tests.rsindex dfd67e5..7a33dd0 100644--- a/src/fleet/workspaces/tests.rs+++ b/src/fleet/workspaces/tests.rs@@ -91,6 +91,7 @@ fn machine(id: &str, platform: &str, cpu: f64, working: usize, disk_free: u64, aunreachable: None,tailnet: None,cloud: None,+ displays: Vec::new(),}}diff --git a/src/main.rs b/src/main.rsindex 47e3604..18e1cea 100644--- a/src/main.rs+++ b/src/main.rs@@ -472,6 +472,54 @@ enum DesktopCommand {Shot(DesktopShotArgs),/// Send input: a JSON list like '[{"type":"click","x":100,"y":200},{"type":"text","text":"hi"}]'Input(DesktopInputArgs),+ /// List the machine's monitors, virtual ones included+ Displays(MachineArgs),+ /// Add a virtual monitor (like plugging in another screen)+ Add(DesktopAddArgs),+ /// Remove a virtual monitor Muxen added+ Remove(DesktopRemoveArgs),+ /// Change a monitor's resolution or scale+ Set(DesktopSetArgs),+}++#[derive(Args)]+struct DesktopSetArgs {+ #[command(flatten)]+ agent: AgentArgs,+ /// Machine id or name+ machine: String,+ /// The display's id (see `muxen desktop displays`)+ display: String,+ /// Its resolution, e.g. 3840x2160 (one it offers)+ #[arg(long)]+ size: Option<String>,+ /// How much the desktop scales things up: 1, 2, ...+ #[arg(long)]+ scale: Option<f64>,+}++#[derive(Args)]+struct DesktopAddArgs {+ #[command(flatten)]+ agent: AgentArgs,+ /// Machine id or name+ machine: String,+ /// Its size, e.g. 2560x1440 (default: the main monitor's)+ #[arg(long)]+ size: Option<String>,+ /// What to call it+ #[arg(long)]+ name: Option<String>,+}++#[derive(Args)]+struct DesktopRemoveArgs {+ #[command(flatten)]+ agent: AgentArgs,+ /// Machine id or name+ machine: String,+ /// The display's id (see `muxen desktop displays`)+ display: String,}#[derive(Args)]@@ -483,6 +531,9 @@ struct DesktopShotArgs {/// Where to save it (default: <machine>-desktop.jpg)#[arg(short, long)]output: Option<std::path::PathBuf>,+ /// One of its displays (see `muxen desktop displays`)+ #[arg(long)]+ display: Option<String>,}#[derive(Args)]@@ -493,6 +544,9 @@ struct DesktopInputArgs {machine: String,/// The events, as JSONevents: String,+ /// One of its displays (see `muxen desktop displays`)+ #[arg(long)]+ display: Option<String>,}#[derive(Args)]@@ -1527,14 +1581,15 @@ fn desktop(cmd: DesktopCommand, runtime: &tokio::runtime::Runtime) -> u8 {DesktopCommand::Shot(a) => {let machine = a.machine.clone();let path = a.output.clone().unwrap_or_else(|| format!("{machine}-desktop.jpg").into());- run(runtime, &a.agent, async move |e| api::desktop_screenshot(&e, &machine).await, move |shot| match std::fs::write(&path, &shot.jpeg) {+ let display = a.display.clone();+ run(runtime, &a.agent, async move |e| api::desktop_screenshot(&e, &machine, display.as_deref()).await, move |shot| match std::fs::write(&path, &shot.jpeg) {Ok(()) => format!("Saved {} ({}×{}, screen {}×{}).\n", path.display(), shot.width, shot.height, shot.screen_width, shot.screen_height),Err(e) => format!("Couldn't save {}: {e}\n", path.display()),})}DesktopCommand::Input(a) => match serde_json::from_str(&a.events) {Ok(events) => {- let req = api::DesktopInputRequest { machine_id: a.machine, events };+ let req = api::DesktopInputRequest { machine_id: a.machine, display: a.display, events };run(runtime, &a.agent, async move |e| api::desktop_input(&e, req).await, |v| format!("Sent {} events.\n", v["events"]))}Err(e) => {@@ -1542,9 +1597,55 @@ fn desktop(cmd: DesktopCommand, runtime: &tokio::runtime::Runtime) -> u8 {2}},+ DesktopCommand::Displays(a) => {+ let req = api::MachineRequest { machine_id: a.machine_id };+ run(runtime, &a.agent, async move |e| api::desktop_displays(&e, req).await, |displays| {+ displays+ .iter()+ .map(|d| {+ let tags = [d.main.then_some("main"), d.is_virtual.then_some("virtual")].into_iter().flatten().collect::<Vec<_>>().join(", ");+ format!("{:<16} {:<20} {:>5}×{:<5} at {},{}{}\n", d.id, d.name, d.width, d.height, d.x, d.y, if tags.is_empty() { String::new() } else { format!(" ({tags})") })+ })+ .collect::<String>()+ })+ }+ DesktopCommand::Add(a) => {+ let size = match a.size.as_deref().map(parse_size) {+ Some(Some(size)) => Some(size),+ Some(None) => {+ eprintln!("error: --size looks like 1920x1080");+ return 2;+ }+ None => None,+ };+ let req = api::AddDisplayRequest { machine_id: a.machine, width: size.map(|s| s.0), height: size.map(|s| s.1), name: a.name };+ run(runtime, &a.agent, async move |e| api::desktop_add_display(&e, req).await, |d| format!("Added {} ({}×{}) as display {}.\n", d.name, d.width, d.height, d.id))+ }+ DesktopCommand::Set(a) => {+ let size = match a.size.as_deref().map(parse_size) {+ Some(Some(size)) => Some(size),+ Some(None) => {+ eprintln!("error: --size looks like 3840x2160");+ return 2;+ }+ None => None,+ };+ let req = api::SetDisplayRequest { machine_id: a.machine, display: a.display, width: size.map(|s| s.0), height: size.map(|s| s.1), scale: a.scale };+ run(runtime, &a.agent, async move |e| api::desktop_set_display(&e, req).await, |d| format!("{} is now {}×{}.\n", d.name, d.width, d.height))+ }+ DesktopCommand::Remove(a) => {+ let req = api::RemoveDisplayRequest { machine_id: a.machine, display: a.display };+ run(runtime, &a.agent, async move |e| api::desktop_remove_display(&e, req).await, |v| format!("Removed display {}.\n", v["removed"].as_str().unwrap_or("")))+ }}}+/// "1920x1080" as (1920, 1080).+fn parse_size(text: &str) -> Option<(u32, u32)> {+ let (w, h) = text.split_once(['x', '×'])?;+ Some((w.trim().parse().ok()?, h.trim().parse().ok()?))+}+fn git(cmd: GitCommand, runtime: &tokio::runtime::Runtime) -> u8 {match cmd {GitCommand::Status(a) => {diff --git a/src/mcp.rs b/src/mcp.rsindex 4f53a33..aa86f3c 100644--- a/src/mcp.rs+++ b/src/mcp.rs@@ -186,7 +186,8 @@ pub async fn call_tool(engine: &Arc<Engine>, session: &Session, name: &str, args// A screenshot comes back as an image the model can look at.if name == "desktop_screenshot" {let machine = args["machine_id"].as_str().unwrap_or("").to_string();- return match api::desktop_screenshot(engine, &machine).await {+ let display = args["display"].as_str().map(str::to_string);+ return match api::desktop_screenshot(engine, &machine, display.as_deref()).await {Ok(shot) => {use base64::Engine as _;let about = format!(@@ -338,6 +339,10 @@ async fn dispatch(engine: &Arc<Engine>, session: &Session, name: &str, a: Value)"git_status" => ok(api::git_status(engine, &args::<api::GitStatusRequest>(a)?.machine_id).await?),"machine_connection" => ok(api::machine_connection(engine, &args::<api::GitStatusRequest>(a)?.machine_id).await?),"desktop_input" => ok(api::desktop_input(engine, args(a)?).await?),+ "desktop_displays" => ok(json!({ "displays": api::desktop_displays(engine, args(a)?).await? })),+ "desktop_add_display" => ok(api::desktop_add_display(engine, args(a)?).await?),+ "desktop_remove_display" => ok(api::desktop_remove_display(engine, args(a)?).await?),+ "desktop_set_display" => ok(api::desktop_set_display(engine, args(a)?).await?),"direct_connection" => ok(api::set_direct(engine, args(a)?).await?),"git_setup" => ok(api::git_setup(engine, args(a)?).await?),other => Err(ApiError::not_found(format!("Unknown tool: {other}"))),@@ -359,6 +364,7 @@ fn schema(properties: Value, required: &[&str]) -> Value {}const MACHINE_ID: &str = "Machine id (a slug like \"mac-studio\"; the display name also works).";+const DISPLAY_ID: &str = "One of the machine's displays, by its id from desktop_displays. Default: the whole desktop (Linux) or the main display (a Mac).";const WORKSPACE_ID: &str = "Workspace id from workspace_create or workspace_list, e.g. \"ws-7f3a2c\".";const WS_PATH: &str = "Path relative to the workspace folder, e.g. \"src/main.rs\". Absolute paths and \"..\" escapes are rejected.";const SESSION_ID: &str = "Session id from session_list or session_start: \"<machine-id>/<name>\", e.g. \"beelink/claude-3f9a\". A bare name works when unique.";@@ -819,8 +825,11 @@ pub fn tools() -> Vec<Value> {}),json!({"name": "desktop_screenshot",- "description": "A picture of a machine's screen (Linux with an X11 desktop, or a Mac on a direct connection). Coordinates for desktop_input are in its pixels.",- "inputSchema": schema(json!({ "machine_id": { "type": "string", "description": MACHINE_ID } }), &["machine_id"]),+ "description": "A picture of a machine's screen (Linux with an X11 desktop, or a Mac on a direct connection), or of one of its displays. Coordinates for desktop_input are in its pixels.",+ "inputSchema": schema(json!({+ "machine_id": { "type": "string", "description": MACHINE_ID },+ "display": { "type": "string", "description": DISPLAY_ID }+ }), &["machine_id"]),"annotations": annotations("Desktop screenshot", true, false, false, false),}),json!({@@ -828,10 +837,49 @@ pub fn tools() -> Vec<Value> {"description": "Use a machine's desktop like a person: events run in order. {type: move|click|scroll|key|text|wait}: click {x, y, button?: left|right|middle, double?}; move {x, y}; scroll {x, y, dy} (positive scrolls down); key {key: \"enter\" | \"ctrl+c\" | \"alt+tab\" ...}; text {text}; wait {ms}. Coordinates in desktop_screenshot pixels; take a screenshot after to see what happened. It acts on the user's real screen: only when asked.","inputSchema": schema(json!({"machine_id": { "type": "string", "description": MACHINE_ID },+ "display": { "type": "string", "description": DISPLAY_ID },"events": { "type": "array", "items": { "type": "object" } }}), &["machine_id", "events"]),"annotations": annotations("Desktop input", false, true, false, false),}),+ json!({+ "name": "desktop_displays",+ "description": "A machine's monitors: real ones and virtual ones Muxen added (virtual: true), each with an id to pass as `display`, its name, size and place on the desktop. On Linux, \"all\" is the whole desktop.",+ "inputSchema": schema(json!({ "machine_id": { "type": "string", "description": MACHINE_ID } }), &["machine_id"]),+ "annotations": annotations("List displays", true, false, true, false),+ }),+ json!({+ "name": "desktop_add_display",+ "description": "Add a virtual monitor to a machine's desktop, like plugging in another screen (no screen needed): windows can move there, and you can screenshot and use it on its own (pass its id as `display`). Linux (X11) and macOS. On Linux it takes root: when sudo there wants a password, this fails and the user adds the monitor from the Muxen app, which asks for it. Stays until removed or the machine restarts. Only when asked.",+ "inputSchema": schema(json!({+ "machine_id": { "type": "string", "description": MACHINE_ID },+ "width": { "type": "integer", "minimum": 640, "maximum": 7680, "description": "Default: the main monitor's width." },+ "height": { "type": "integer", "minimum": 480, "maximum": 4320, "description": "Default: the main monitor's height." },+ "name": { "type": "string", "description": "What to call it, e.g. \"Agent screen\"." }+ }), &["machine_id"]),+ "annotations": annotations("Add virtual monitor", false, false, false, false),+ }),+ json!({+ "name": "desktop_remove_display",+ "description": "Remove a virtual monitor Muxen added (desktop_displays shows them as virtual: true). Windows on it move to the other monitors.",+ "inputSchema": schema(json!({+ "machine_id": { "type": "string", "description": MACHINE_ID },+ "display": { "type": "string", "description": DISPLAY_ID }+ }), &["machine_id", "display"]),+ "annotations": annotations("Remove virtual monitor", false, true, true, false),+ }),+ json!({+ "name": "desktop_set_display",+ "description": "Change a monitor's resolution (one of its `modes` from desktop_displays) or how much the desktop scales things up on it (`scales`; 2: twice as big and as sharp, like a Retina screen; on Linux X11 one scale applies to every monitor). A 4K monitor at scale 2 reads like 1080p but stays sharp. Changes the user's real desktop: only when asked.",+ "inputSchema": schema(json!({+ "machine_id": { "type": "string", "description": MACHINE_ID },+ "display": { "type": "string", "description": DISPLAY_ID },+ "width": { "type": "integer", "description": "With height: the new resolution." },+ "height": { "type": "integer" },+ "scale": { "type": "number", "description": "1, 2, ... (Linux desktops that offer it)." }+ }), &["machine_id", "display"]),+ "annotations": annotations("Set monitor resolution or scale", false, false, true, false),+ }),json!({"name": "git_status","description": "Whether git on one of the user's machines can commit and push to GitHub: its name and email (can_commit), how a push gets a GitHub login (push: gh, other, none), the machine's GitHub CLI account, and the identity git_setup would use.",@@ -895,7 +943,7 @@ mod tests {#[test]fn tool_schemas_are_well_formed() {let tools = tools();- assert_eq!(tools.len(), 58);+ assert_eq!(tools.len(), 62);let mut names: Vec<&str> = tools.iter().map(|t| t["name"].as_str().unwrap()).collect();names.sort();names.dedup();diff --git a/src/ui/assets.rs b/src/ui/assets.rsindex fada9f9..27cb52c 100644--- a/src/ui/assets.rs+++ b/src/ui/assets.rs@@ -23,7 +23,7 @@ icons!("bot", "square-terminal", "power", "plug", "unplug","agent-claude", "agent-codex", "agent-gemini", "agent-opencode", "agent-amp", "agent-pi", "agent-github","circle-dot", "git-pull-request", "git-pull-request-draft", "git-merge", "message-square", "lock", "star",- "arrow-down", "arrow-up", "book-open", "star-filled", "maximize", "minimize", "panel-right", "panel-left",+ "arrow-down", "arrow-up", "book-open", "star-filled", "maximize", "minimize", "panel-right", "panel-left", "columns-2", "rows-2","folder", "file", "sliders-horizontal", "palette", "keyboard", "cloud", "brand-digitalocean", "pencil",// The glyphs of each icon style (see kit::IconStyle): pf- Phosphor (MIT),// so- Solar (CC BY 4.0), mc- MingCute (Apache-2.0), fl- Fluent (MIT),@@ -76,8 +76,17 @@ const FONTS: &[&[u8]] = &[include_bytes!("../../assets/fonts/geist-600.ttf"),include_bytes!("../../assets/fonts/geist-mono-400.ttf"),include_bytes!("../../assets/fonts/geist-mono-500.ttf"),+ NERD_SYMBOLS,];+/// Nerd Font icons (Neovim's file icons, prompt glyphs), drawn when the+/// terminal font doesn't have them: Symbols Nerd Font Mono (MIT, see+/// NERD-FONTS-LICENSE.txt), one cell wide each.+const NERD_SYMBOLS: &[u8] = include_bytes!("../../assets/fonts/symbols-nerd-font-mono.ttf");+/// Its names, for the terminal font's fallbacks: PostScript (what macOS+/// looks fallbacks up by), then family.+pub const NERD_SYMBOLS_NAMES: [&str; 2] = ["SymbolsNFM", "Symbols Nerd Font Mono"];+/// The app icon, for the Dock when running outside an .app bundle.pub const APP_ICON_PNG: &[u8] = include_bytes!("../../assets/brand/icon-512.png");/// Small copy of the icon for the sidebar.@@ -113,6 +122,43 @@ pub fn load_fonts(cx: &mut App) {if let Err(e) = cx.text_system().add_fonts(fonts) {tracing::warn!("couldn't load bundled fonts: {e}");}+ #[cfg(target_os = "macos")]+ register_with_core_text(NERD_SYMBOLS);+}++/// Makes a bundled font known to macOS by name, for this app only: font+/// fallbacks are looked up that way, and GPUI's own fonts aren't.+#[cfg(target_os = "macos")]+fn register_with_core_text(bytes: &'static [u8]) {+ use std::ffi::c_void;+ #[link(name = "CoreGraphics", kind = "framework")]+ unsafe extern "C" {+ fn CGDataProviderCreateWithData(info: *mut c_void, data: *const c_void, size: usize, release: *const c_void) -> *const c_void;+ fn CGDataProviderRelease(provider: *const c_void);+ fn CGFontCreateWithDataProvider(provider: *const c_void) -> *const c_void;+ fn CGFontRelease(font: *const c_void);+ }+ #[link(name = "CoreText", kind = "framework")]+ unsafe extern "C" {+ fn CTFontManagerRegisterGraphicsFont(font: *const c_void, error: *mut *const c_void) -> bool;+ }+ // SAFETY: `bytes` lives for the whole program; each object made here is released here.+ unsafe {+ let provider = CGDataProviderCreateWithData(std::ptr::null_mut(), bytes.as_ptr().cast(), bytes.len(), std::ptr::null());+ if provider.is_null() {+ return;+ }+ let font = CGFontCreateWithDataProvider(provider);+ CGDataProviderRelease(provider);+ if font.is_null() {+ return;+ }+ let mut error = std::ptr::null();+ if !CTFontManagerRegisterGraphicsFont(font, &mut error) {+ tracing::warn!("couldn't register the Nerd Font symbols");+ }+ CGFontRelease(font);+ }}/// Shows the Muxen icon in the Dock. Bundled builds get it from Info.plist;diff --git a/src/ui/desktop.rs b/src/ui/desktop.rsindex 76b011d..7654644 100644--- a/src/ui/desktop.rs+++ b/src/ui/desktop.rs@@ -48,6 +48,8 @@ enum Msg {/// The stream ended: why, and whether it may well work again in a moment/// (the connection dropped, as opposed to the machine saying no).Ended(String, bool),+ /// The monitor asked for is gone: showing the default one instead.+ Gone,}/// The machine's screen as last received: patches land here as they arrive,@@ -63,9 +65,11 @@ struct Canvas {/// Tries at picking a dropped stream back up before saying it ended.const RETRIES: u32 = 6;-/// Frame widths to choose from; `NATIVE` is the screen's own size.+/// A frame width meaning the screen's own size.pub const NATIVE: u32 = 16384;-pub const RESOLUTIONS: [(&str, u32); 5] = [("720p", 1280), ("1080p", 1920), ("1440p", 2560), ("4K", 3840), ("Native", NATIVE)];++/// Monitor sizes with a short name, offered when the monitor has them.+const SIZES: [((u32, u32), &str); 4] = [((1280, 720), "720p"), ((1920, 1080), "1080p"), ((2560, 1440), "1440p"), ((3840, 2160), "4K")];/// The desktop's channel on the machine's link.struct Remote {@@ -88,10 +92,11 @@ impl Drop for Remote {pub struct DesktopView {engine: Arc<Engine>,machine: String,+ /// One of the machine's displays (None: the whole desktop, or a Mac's main display).+ display: Option<String>,/// The frame width asked for (None: native on a local network, else 1080p).width: Option<u32>,- /// What the stream ended up using, and how it travels ("Direct · Local network").- chosen: u32,+ /// How the stream travels ("Direct · Local network").via: String,canvas: Arc<std::sync::Mutex<Canvas>>,/// A Changed message is on its way (so patches don't queue up draws).@@ -104,9 +109,15 @@ pub struct DesktopView {size: (u32, u32),/// Where the frame was last drawn, for mapping the mouse.shown: Rc<Cell<Option<Bounds<Pixels>>>>,+ /// The area it was drawn in (to place things over the picture).+ area: Rc<Cell<Option<Bounds<Pixels>>>>,focus: FocusHandle,/// Modifier keys the machine has been told are down.held: Modifiers,+ /// Other keys (keysyms) and mouse buttons it has been told are down, let+ /// go when the view loses focus (else they'd stay held there).+ keys_down: Vec<u32>,+ buttons_down: Vec<u64>,last_move: Instant,scroll_rest: f32,frames: u64,@@ -116,11 +127,15 @@ pub struct DesktopView {mac: bool,/// What the machine says about the stream (e.g. view only).note: Option<String>,+ /// A monitor's size or scale being changed, and why the last change didn't happen.+ changing: bool,+ change_error: Option<String>,/// Picking a dropped stream back up: tries so far, and the next one.resuming: bool,retries: u32,retry: Option<Task<()>>,_tasks: Vec<Task<()>>,+ _subscriptions: Vec<gpui::Subscription>,}impl Focusable for DesktopView {@@ -134,8 +149,8 @@ impl DesktopView {let mut view = DesktopView {engine,machine: machine_id,+ display: None,width: None,- chosen: 0,via: String::new(),canvas: Arc::new(std::sync::Mutex::new(Canvas::default())),pending: Arc::new(std::sync::atomic::AtomicBool::new(false)),@@ -145,8 +160,11 @@ impl DesktopView {frame: None,size: (0, 0),shown: Rc::new(Cell::new(None)),+ area: Rc::new(Cell::new(None)),focus: cx.focus_handle(),held: Modifiers::default(),+ keys_down: Vec::new(),+ buttons_down: Vec::new(),last_move: Instant::now(),scroll_rest: 0.,frames: 0,@@ -156,10 +174,22 @@ impl DesktopView {resuming: false,retries: 0,retry: None,+ changing: false,+ change_error: None,_tasks: Vec::new(),+ _subscriptions: Vec::new(),};view.mac = view.engine.current().machines.iter().any(|m| m.id == view.machine && m.platform.starts_with("darwin"));view.start(window, cx);+ // Keys and buttons held when the view loses the keyboard (another+ // app, ⌘Q, a click elsewhere): let go on the machine too.+ let blur = cx.on_focus_out(&view.focus, window, |this, _, _, _| this.let_go());+ let away = cx.observe_window_activation(window, |this, window, _| {+ if !window.is_window_active() {+ this.let_go();+ }+ });+ view._subscriptions = vec![blur, away];// Follow the machine: say so when it goes offline, and pick the stream// back up when it returns.let mut rx = view.engine.subscribe();@@ -198,24 +228,65 @@ impl DesktopView {cx.notify();}- /// The frame width in use, for the resolution picker.- pub fn resolution(&self) -> u32 {- self.width.unwrap_or(self.chosen)- }-/// How the stream travels, e.g. "Direct · Local network".pub fn via(&self) -> &str {&self.via}- /// Switches resolution: a new stream at that width.- pub fn set_resolution(&mut self, width: u32, window: &mut Window, cx: &mut Context<Self>) {- if Some(width) != self.width {- self.width = Some(width);+ /// The display shown (None: the default one).+ pub fn display(&self) -> Option<&str> {+ self.display.as_deref()+ }++ /// Shows another of the machine's displays: a new stream.+ pub fn set_display(&mut self, display: Option<String>, window: &mut Window, cx: &mut Context<Self>) {+ if display != self.display {+ self.display = display;+ self.retries = 0;+ // Not the last monitor's picture while the new one comes.+ if let Some(old) = self.frame.take() {+ cx.drop_image(old, Some(window));+ }self.start(window, cx);+ cx.notify();}}+ /// Sets a monitor's size or scale on the machine; a new stream at its new+ /// size once it has one.+ pub fn change_display(&mut self, display: String, size: Option<(u32, u32)>, scale: Option<f64>, window: &mut Window, cx: &mut Context<Self>) {+ if self.changing {+ return;+ }+ self.changing = true;+ self.change_error = None;+ cx.notify();+ let (engine, machine) = (self.engine.clone(), self.machine.clone());+ let job = engine.runtime().spawn({+ let engine = engine.clone();+ async move { engine.set_display(&machine, &display, size, scale).await }+ });+ cx.spawn_in(window, async move |this, cx| {+ let result = job.await.unwrap_or_else(|e| Err(e.to_string()));+ let _ = this.update_in(cx, |this, window, cx| {+ this.changing = false;+ match result {+ Ok(()) if size.is_some() => {+ this.retries = 0;+ if let Some(old) = this.frame.take() {+ cx.drop_image(old, Some(window));+ }+ this.start(window, cx);+ }+ Ok(()) => {}+ Err(e) => this.change_error = Some(e),+ }+ cx.notify();+ });+ })+ .detach();+ }+/// (Re)starts the stream from the machine.fn start(&mut self, window: &mut Window, cx: &mut Context<Self>) {self.remote = None;@@ -224,7 +295,7 @@ impl DesktopView {// mustn't hold up the new one.self.pending = Arc::new(std::sync::atomic::AtomicBool::new(false));let (tx, mut rx) = futures::channel::mpsc::unbounded::<Msg>();- let (engine, machine_id, wanted) = (self.engine.clone(), self.machine.clone(), self.width);+ let (engine, machine_id, wanted, mut display) = (self.engine.clone(), self.machine.clone(), self.width, self.display.clone().unwrap_or_default());let (canvas, pending) = (self.canvas.clone(), self.pending.clone());let rt = engine.runtime().clone();rt.spawn(async move {@@ -236,6 +307,22 @@ impl DesktopView {let _ = tx.unbounded_send(Msg::Ended("The demo has no desktops to show.".into(), false));return;}+ // Its monitors as they are now (one may have been added, removed+ // or resized since), for the picker; a gone one falls back to the default.+ if let Ok(displays) = engine.displays(&machine_id).await {+ if !display.is_empty() && display != "all" && !displays.iter().any(|d| d.id == display) {+ display.clear();+ let _ = tx.unbounded_send(Msg::Gone);+ }+ // The default: the main monitor (the agent's own default on+ // Linux is the whole desktop).+ if display.is_empty()+ && displays.iter().any(|d| d.id == "all")+ && let Some(main) = displays.iter().find(|d| d.main && d.id != "all")+ {+ display = main.id.clone();+ }+ }let Some(link) = crate::fleet::link::get(&spec).await else {let _ = tx.unbounded_send(Msg::Ended(format!("Can't reach the agent on {}.", spec.name), true));return;@@ -245,7 +332,7 @@ impl DesktopView {let width = wanted.unwrap_or(if matches!(network, Some("Local network" | "This computer")) { NATIVE } else { 1920 });let via = [Some(if link.transport() == "direct" { "Direct" } else { "Over ssh" }), network].into_iter().flatten().collect::<Vec<_>>().join(" · ");let (channel, mut frames) = link.open_channel();- let request = json!({ "op": "desktop", "channel": channel, "fps": 30, "quality": 78, "max_width": width, "tiles": true });+ let request = json!({ "op": "desktop", "channel": channel, "fps": 30, "quality": 78, "max_width": width, "tiles": true, "display": display });match link.request(request, Duration::from_secs(20)).await {Ok(r) if r["ok"].as_bool() == Some(true) => {let (w, h) = (r["width"].as_u64().unwrap_or(0) as u32, r["height"].as_u64().unwrap_or(0) as u32);@@ -296,9 +383,7 @@ impl DesktopView {this.state = State::Live;this.retries = 0;this.resuming = false;- let (via, width) = via.split_once('|').unwrap_or((&via, "0"));- this.via = via.to_string();- this.chosen = width.parse().unwrap_or(0);+ this.via = via.split_once('|').map_or(via.as_str(), |(v, _)| v).to_string();}Msg::Changed => {this.pending.store(false, std::sync::atomic::Ordering::Release);@@ -315,6 +400,7 @@ impl DesktopView {}}}+ Msg::Gone => this.display = None,Msg::Ended(why, may_return) => {this.remote = None;// The connection dropped (another network, a@@ -350,11 +436,67 @@ impl DesktopView {self.stream = Some(feed);}+ /// While the whole desktop shows, a label over each monitor's corner that+ /// opens that monitor (clicks elsewhere still go to the machine).+ fn monitor_labels(&self, cx: &mut Context<Self>) -> Vec<AnyElement> {+ if self.display.as_deref() != Some("all") || self.frame.is_none() {+ return Vec::new();+ }+ let displays = self.engine.current().machines.iter().find(|m| m.id == self.machine).map(|m| m.displays.clone()).unwrap_or_default();+ let Some(all) = displays.iter().find(|d| d.id == "all") else { return Vec::new() };+ let (Some(rect), Some(area)) = (self.shown.get(), self.area.get()) else { return Vec::new() };+ if all.width <= 0. {+ return Vec::new();+ }+ let theme = cx.theme();+ let scale = f32::from(rect.size.width) / all.width as f32;+ let (ox, oy) = (f32::from(rect.origin.x - area.origin.x), f32::from(rect.origin.y - area.origin.y));+ displays+ .iter()+ .filter(|d| d.id != "all")+ .map(|d| {+ let id = d.id.clone();+ div()+ .id(SharedString::from(format!("mon-label-{}", d.id)))+ .absolute()+ .left(px(ox + d.x as f32 * scale + 8.))+ .top(px(oy + d.y as f32 * scale + 8.))+ .flex()+ .items_center()+ .gap(px(5.))+ .h(px(24.))+ .px(px(9.))+ .rounded(px(7.))+ .bg(gpui::black().opacity(0.62))+ .border_1()+ .border_color(gpui::white().opacity(0.18))+ .text_size(px(12.))+ .text_color(gpui::white())+ .cursor_pointer()+ .hover(|st| st.bg(theme.accent))+ .when(d.is_virtual, |el| el.child(kit::dot(theme.accent, 6.)))+ .child(d.name.clone())+ .child(kit::icon("external-link", 11., gpui::white().opacity(0.8)))+ // The click is for the label, not the machine.+ .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())+ .on_mouse_up(MouseButton::Left, |_, _, cx| cx.stop_propagation())+ .on_click(cx.listener(move |this, _, window, cx| this.set_display(Some(id.clone()), window, cx)))+ .into_any_element()+ })+ .collect()+ }+/// "Live", "Connecting…" or why it ended, for the page header.pub fn status(&self) -> String {if let (Some(why), false) = (&self.offline, matches!(self.state, State::Live)) {return why.clone();}+ if self.changing {+ return "Changing the monitor…".into();+ }+ if let Some(e) = &self.change_error {+ return e.clone();+ }match &self.state {State::Connecting if self.resuming => "Reconnecting…".into(),State::Connecting => "Connecting…".into(),@@ -406,6 +548,10 @@ impl DesktopView {window.focus(&self.focus);cx.notify();}+ self.buttons_down.retain(|x| *x != b);+ if down {+ self.buttons_down.push(b);+ }if let Some((x, y)) = self.at(position) {self.send(json!({ "t": "button", "b": b, "down": down, "x": x, "y": y }));} else if !down {@@ -449,9 +595,24 @@ impl DesktopView {fn key(&mut self, key: &str, down: bool, cx: &mut Context<Self>) {if let Some(sym) = keysym(key) {self.send(json!({ "t": "key", "keysym": sym, "down": down }));+ self.keys_down.retain(|x| *x != sym);+ if down {+ self.keys_down.push(sym);+ }cx.stop_propagation();}}++ /// Lets go of every key, modifier and button the machine was told is down.+ fn let_go(&mut self) {+ for sym in std::mem::take(&mut self.keys_down) {+ self.send(json!({ "t": "key", "keysym": sym, "down": false }));+ }+ self.modifiers(Modifiers::default());+ for b in std::mem::take(&mut self.buttons_down) {+ self.send(json!({ "t": "button", "b": b, "down": false, "x": 0, "y": 0 }));+ }+ }}/// Paints a TILES message into the canvas: `[w][h][count]`, then each@@ -524,9 +685,11 @@ impl Render for DesktopView {let frame = self.frame.clone();let size = self.size;let shown = self.shown.clone();+ let area = self.area.clone();let picture = canvas(|_, _, _| (),move |bounds, _, window, _| {+ area.set(Some(bounds));let Some(frame) = frame else { return };// Fit the frame inside, keeping its shape.let (w, h) = (size.0.max(1) as f32, size.1.max(1) as f32);@@ -580,6 +743,8 @@ impl Render for DesktopView {),_ => None,};+ // Showing every screen: each monitor's name over its corner opens it.+ let labels = self.monitor_labels(cx);div().id("desktop").key_context(CONTEXT)@@ -589,6 +754,7 @@ impl Render for DesktopView {.bg(gpui::black()).cursor_default().child(picture)+ .children(labels)// Over the last picture, dimmed: it's no longer live..children(waiting.map(|w| div().absolute().inset_0().flex().items_center().justify_center().when(self.frame.is_some(), |d| d.bg(gpui::black().opacity(0.72))).child(w))).on_mouse_move(cx.listener(Self::mouse_move))@@ -608,19 +774,60 @@ impl Render for DesktopView {}}+/// Opens a display's menu: (machine, display, where), from a right-click on it.+pub type DisplayMenu = Rc<dyn Fn(&str, &str, gpui::Point<Pixels>, &mut Window, &mut App)>;+/// Status, network and resolution for a desktop, then `extra` controls (close,/// pop out, full screen): the bar above every desktop view.pub fn toolbar(view: &Entity<DesktopView>, extra: Vec<AnyElement>, cx: &App) -> AnyElement {+ toolbar_with_menu(view, extra, None, cx)+}++/// The toolbar, with `menu` opening a monitor's menu on right-click.+pub fn toolbar_with_menu(view: &Entity<DesktopView>, extra: Vec<AnyElement>, menu: Option<DisplayMenu>, cx: &App) -> AnyElement {let theme = cx.theme();- let (status, via, current) = {+ let (status, via, machine, shown, engine) = {let v = view.read(cx);- (v.status(), v.via().to_string(), v.resolution())+ (v.status(), v.via().to_string(), v.machine.clone(), v.display.clone(), v.engine.clone())};- // 720p · 1080p · 1440p · 4K · Native- let picker = div().flex().gap(px(2.)).p(px(2.)).rounded(px(7.)).bg(theme.element).children(RESOLUTIONS.iter().map(|(label, width)| {- let (on, width, view) = (current == *width, *width, view.clone());+ // Its monitors, when it has more than one: pick the one to show.+ let displays = engine.current().machines.iter().find(|m| m.id == machine).map(|m| m.displays.clone()).unwrap_or_default();+ // Shown unless another is picked: the main monitor.+ let default = displays.iter().find(|d| d.main && d.id != "all").or_else(|| displays.iter().find(|d| d.id != "all")).map(|d| d.id.clone());+ let showing = shown.or(default);+ let monitors = (displays.len() > 1).then(|| {+ div().flex().gap(px(2.)).p(px(2.)).rounded(px(7.)).bg(theme.element).children(displays.iter().map(|d| {+ let (on, id, view) = (showing.as_deref() == Some(d.id.as_str()), d.id.clone(), view.clone());+ let right_click = menu.clone().filter(|_| d.id != "all").map(|menu| {+ let (machine, display) = (machine.clone(), d.id.clone());+ move |e: &MouseDownEvent, window: &mut Window, cx: &mut App| menu(&machine, &display, e.position, window, cx)+ });+ let name = if d.name.chars().count() > 18 { format!("{}…", d.name.chars().take(17).collect::<String>()) } else { d.name.clone() };+ div()+ .id(SharedString::from(format!("disp-{}", d.id)))+ .px(px(8.))+ .h(px(22.))+ .flex()+ .items_center()+ .gap(px(5.))+ .rounded(px(5.))+ .cursor_pointer()+ .text_size(px(11.5))+ .text_color(if on { theme.text } else { theme.text_placeholder })+ .when(on, |d| d.bg(theme.element_selected))+ .when(!on, |d| d.hover(|st| st.bg(theme.ghost_hover)))+ .when(d.is_virtual, |el| el.child(kit::dot(theme.accent, 5.)).tooltip(|window, cx| kit::Tooltip::view("Virtual monitor".into(), window, cx)))+ .child(name)+ .when_some(right_click, |el, f| el.on_mouse_down(MouseButton::Right, f))+ .on_click(move |_, window, cx| view.update(cx, |v, cx| v.set_display(Some(id.clone()), window, cx)))+ }))+ });+ // The monitor shown: its size (720p · 1080p · 1440p · 4K, the ones it+ // has) and scale (100% · 200%), set on the machine.+ let screen = showing.as_deref().filter(|id| *id != "all").and_then(|id| displays.iter().find(|d| d.id == id));+ let chip = |id: String, label: String, on: bool, tip: &'static str| {div()- .id(SharedString::from(format!("res-{label}")))+ .id(SharedString::from(id)).px(px(8.)).h(px(22.)).flex()@@ -631,9 +838,42 @@ pub fn toolbar(view: &Entity<DesktopView>, extra: Vec<AnyElement>, cx: &App) ->.text_color(if on { theme.text } else { theme.text_placeholder }).when(on, |d| d.bg(theme.element_selected)).when(!on, |d| d.hover(|st| st.bg(theme.ghost_hover)))- .child(*label)- .on_click(move |_, window, cx| view.update(cx, |v, cx| v.set_resolution(width, window, cx)))- }));+ .tooltip(move |window, cx| kit::Tooltip::view(tip.into(), window, cx))+ .child(label)+ };+ let group = |chips: Vec<gpui::Stateful<gpui::Div>>| div().flex_none().flex().gap(px(2.)).p(px(2.)).rounded(px(7.)).bg(theme.element).children(chips);+ let sizes = screen.and_then(|d| {+ let current = (d.width.round() as u32, d.height.round() as u32);+ let mut choices: Vec<((u32, u32), String)> = SIZES.iter().filter(|(size, _)| d.any_size || d.modes.contains(size)).map(|(size, label)| (*size, label.to_string())).collect();+ if !choices.iter().any(|(size, _)| *size == current) {+ choices.push((current, format!("{}×{}", current.0, current.1)));+ choices.sort_by_key(|((w, h), _)| w * h);+ }+ (choices.len() > 1).then(|| {+ group(+ choices+ .into_iter()+ .map(|(size, label)| {+ let (view, id) = (view.clone(), d.id.clone());+ chip(format!("size-{}x{}", size.0, size.1), label, size == current, "The monitor's resolution")+ .on_click(move |_, window, cx| view.update(cx, |v, cx| v.change_display(id.clone(), Some(size), None, window, cx)))+ })+ .collect(),+ )+ })+ });+ let scales = screen.filter(|d| [1., 2.].iter().all(|s| d.scales.iter().any(|x| (x - s).abs() < 0.01))).map(|d| {+ group(+ [(1., "100%"), (2., "200%")]+ .into_iter()+ .map(|(scale, label)| {+ let (view, id) = (view.clone(), d.id.clone());+ chip(format!("scale-{label}"), label.to_string(), (d.scale - scale).abs() < 0.01, "How big things are (200%: twice as big, just as sharp)")+ .on_click(move |_, window, cx| view.update(cx, |v, cx| v.change_display(id.clone(), None, Some(scale), window, cx)))+ })+ .collect(),+ )+ });div().flex().flex_none()@@ -659,7 +899,9 @@ pub fn toolbar(view: &Entity<DesktopView>, extra: Vec<AnyElement>, cx: &App) ->d.child(div().flex_none().flex().items_center().gap(px(5.)).text_size(px(12.)).text_color(theme.text_placeholder).child(kit::color_icon(&theme, "network", 12., theme.text_placeholder)).child(via))}),)- .child(picker.flex_none())+ .children(monitors.map(|m| m.flex_none()))+ .children(sizes)+ .children(scales).children(extra).into_any_element()}@@ -690,7 +932,7 @@ impl Render for DesktopWindow {}/// Opens a machine's desktop in its own window.-pub fn open_window(engine: Arc<Engine>, machine_id: String, name: String, cx: &mut App) {+pub fn open_window(engine: Arc<Engine>, machine_id: String, display: Option<String>, name: String, cx: &mut App) {let bounds = Bounds::centered(None, gpui::size(px(1440.), px(900.)), cx);let options = gpui::WindowOptions {window_bounds: Some(gpui::WindowBounds::Windowed(bounds)),@@ -701,7 +943,11 @@ pub fn open_window(engine: Arc<Engine>, machine_id: String, name: String, cx: &m};let opened = cx.open_window(options, |window, cx| {super::theme::apply(window, cx);- let view = cx.new(|cx| DesktopView::new(engine, machine_id, window, cx));+ let view = cx.new(|cx| {+ let mut v = DesktopView::new(engine, machine_id, window, cx);+ v.set_display(display, window, cx);+ v+ });window.focus(&view.focus_handle(cx));cx.new(|_| DesktopWindow { view })});diff --git a/src/ui/detail.rs b/src/ui/detail.rsindex 7534547..563c1f1 100644--- a/src/ui/detail.rs+++ b/src/ui/detail.rs@@ -81,21 +81,31 @@ impl Root {div().flex().gap(px(6.))- .child({- let mid = m.id.clone();- Button::new("m-install", "Install runner")- .icon("plus")- .style(ButtonStyle::Primary)- .disabled(m.host.is_empty() || busy || offline)- .on_click(cx.listener(move |this, _, window, cx| this.show_install_dialog(&mid, window, cx)))- })+ // What you come to a machine for first: a session, its desktop..child({let mid = m.id.clone();Button::new("m-session", "New session").icon("square-terminal")+ .style(ButtonStyle::Primary).disabled(m.host.is_empty() || offline).on_click(cx.listener(move |this, _, window, cx| this.show_new_session(Some(mid.clone()), window, cx)))})+ .when(super::format::has_desktop(&m) && !m.local, |d| {+ let mid = m.id.clone();+ d.child(+ Button::new("m-desktop", "Show desktop")+ .icon("monitor")+ .disabled(m.host.is_empty() || offline)+ .on_click(cx.listener(move |this, _, window, cx| this.show_display(mid.clone(), None, window, cx))),+ )+ })+ .child({+ let mid = m.id.clone();+ Button::new("m-install", "Install runner")+ .icon("plus")+ .disabled(m.host.is_empty() || busy || offline)+ .on_click(cx.listener(move |this, _, window, cx| this.show_install_dialog(&mid, window, cx)))+ }).when(!m.platform.starts_with("windows"), |d| {let mid = m.id.clone();d.child(diff --git a/src/ui/dialogs.rs b/src/ui/dialogs.rsindex be1cb1d..ec2f7a5 100644--- a/src/ui/dialogs.rs+++ b/src/ui/dialogs.rs@@ -32,6 +32,8 @@ pub enum DialogEvent {StartSession(StartSession),/// Set up the workspace first, then start the session in its folder.StartInWorkspace(CreateWorkspace, StartSession),+ /// A virtual monitor was added: (machine, display) to show.+ DisplayAdded(String, String),}pub(super) fn frame(theme: &Theme, title: impl Into<SharedString>, intro: Option<SharedString>) -> gpui::Div {@@ -602,6 +604,8 @@ impl InstallDialog {pub enum RenameTarget {Machine(String),Session(String),+ /// A machine's display: (machine, display id).+ Display(String, String),}pub struct RenameDialog {@@ -653,6 +657,28 @@ impl RenameDialog {cx.notify();}},+ // The machine keeps it: one round trip.+ RenameTarget::Display(machine, display) => {+ self.saving = true;+ cx.notify();+ let engine = self.engine.clone();+ let job = engine.runtime().spawn({+ let engine = engine.clone();+ async move { engine.rename_display(&machine, &display, &text).await }+ });+ cx.spawn(async move |this, cx| {+ let result = job.await.unwrap_or_else(|e| Err(e.to_string()));+ let _ = this.update(cx, |this, cx| match result {+ Ok(()) => cx.emit(DialogEvent::Dismissed),+ Err(e) => {+ this.saving = false;+ this.error = Some(e);+ cx.notify();+ }+ });+ })+ .detach();+ }// The agent on the machine keeps it: one round trip.RenameTarget::Session(id) => {self.saving = true;@@ -688,6 +714,11 @@ impl Render for RenameDialog {format!("Only the name Muxen shows changes. Its id ({id}), runners and sessions stay the same, and nothing on the machine changes."),"Name",),+ RenameTarget::Display(..) => (+ "Rename display",+ format!("What Muxen calls this monitor on {}. Its windows and settings stay as they are.", self.machine),+ "Name",+ ),RenameTarget::Session(_) => ("Rename session",format!("Muxen's agent on {} keeps the title, so it shows wherever you use Muxen. What runs in the session isn't touched.", self.machine),@@ -711,6 +742,280 @@ impl Render for RenameDialog {// ---------------------------------------------------------------------------+/// Sizes to pick from for a virtual monitor.+const MONITOR_SIZES: &[(u32, u32)] = &[(1280, 720), (1920, 1080), (2560, 1440), (3840, 2160)];++pub struct AddDisplayDialog {+ engine: Arc<Engine>,+ machine: String,+ machine_name: String,+ name: Entity<TextInput>,+ /// The machine's password, when it asks for one (cleared once read).+ password: Entity<TextInput>,+ size: (u32, u32),+ /// The size of the machine's main monitor, which a new one starts at.+ main: Option<(u32, u32)>,+ adding: bool,+ /// The machine wants the password (sudo, on Linux): ask for it.+ asking: bool,+ error: Option<String>,+ _subscriptions: Vec<Subscription>,+}++impl EventEmitter<DialogEvent> for AddDisplayDialog {}++impl AddDisplayDialog {+ pub fn new(engine: Arc<Engine>, machine: String, window: &mut Window, cx: &mut Context<Self>) -> Self {+ let snap = engine.current();+ let m = snap.machines.iter().find(|m| m.id == machine);+ let machine_name = m.map(|m| m.name.clone()).unwrap_or_else(|| machine.clone());+ // Named like plugging in another one: "Display 3" when there are two.+ let n = m.map(|m| m.displays.iter().filter(|d| d.id != "all").count()).unwrap_or(1) + 1;+ let screens: Vec<_> = m.map(|m| m.displays.iter().filter(|d| d.id != "all").collect()).unwrap_or_default();+ let main = screens.iter().find(|d| d.main).or(screens.first()).map(|d| (d.width.round() as u32, d.height.round() as u32)).filter(|(w, h)| *w >= 640 && *h >= 480);+ let name = cx.new(|cx| TextInput::new(cx, format!("Display {n}")));+ let password = cx.new(|cx| TextInput::new(cx, "Password").secret());+ let on_input = |this: &mut Self, _: &Entity<TextInput>, e: &InputEvent, window: &mut Window, cx: &mut Context<Self>| match e {+ InputEvent::Submit => this.submit(window, cx),+ InputEvent::Cancel => cx.emit(DialogEvent::Dismissed),+ InputEvent::Changed => {+ this.error = None;+ cx.notify()+ }+ };+ let subs = vec![cx.subscribe_in(&name, window, on_input), cx.subscribe_in(&password, window, on_input)];+ AddDisplayDialog { engine, machine, machine_name, name, password, size: main.unwrap_or((1920, 1080)), main, adding: false, asking: false, error: None, _subscriptions: subs }+ }++ pub fn first_focus(&self, cx: &App) -> FocusHandle {+ self.name.focus_handle(cx)+ }++ fn submit(&mut self, window: &mut Window, cx: &mut Context<Self>) {+ if self.adding {+ return;+ }+ if self.asking {+ // Read once, cleared from the field, kept only in memory while Muxen runs.+ let p = self.password.read(cx).text().to_string();+ if p.is_empty() {+ self.error = Some(format!("Type your password on {}.", self.machine_name));+ cx.notify();+ return;+ }+ self.password.update(cx, |i, cx| i.set_text("", cx));+ self.engine.remember_password(&self.machine, p);+ }+ self.adding = true;+ self.error = None;+ cx.notify();+ let typed = self.name.read(cx).text().trim().to_string();+ let (engine, machine, (w, h)) = (self.engine.clone(), self.machine.clone(), self.size);+ let job = engine.runtime().spawn({+ let (engine, machine) = (engine.clone(), machine.clone());+ async move { engine.add_display(&machine, w, h, Some(&typed).filter(|t| !t.is_empty()).map(|t| t.as_str())).await }+ });+ cx.spawn_in(window, async move |this, cx| {+ let result = job.await.unwrap_or_else(|e| Err(crate::fleet::desktop::AddDisplayError::Failed(e.to_string())));+ let _ = this.update_in(cx, |this, window, cx| {+ this.adding = false;+ match result {+ Ok(d) => cx.emit(DialogEvent::DisplayAdded(machine, d.id)),+ Err(crate::fleet::desktop::AddDisplayError::NeedsPassword(why)) => {+ // Asked for the first time, or the one given didn't work.+ if this.asking {+ this.error = Some(why);+ }+ this.asking = true;+ window.focus(&this.password.focus_handle(cx));+ }+ Err(e) => this.error = Some(e.to_string()),+ }+ cx.notify();+ });+ })+ .detach();+ }+}++impl Render for AddDisplayDialog {+ fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {+ let theme = cx.theme();+ // The usual sizes, and the main monitor's when it's another.+ let mut choices = MONITOR_SIZES.to_vec();+ if let Some(main) = self.main.filter(|m| !choices.contains(m)) {+ choices.push(main);+ choices.sort_by_key(|(w, h)| w * h);+ }+ let main = self.main;+ let sizes: Vec<AnyElement> = choices+ .into_iter()+ .map(|(w, h)| {+ let on = self.size == (w, h);+ div()+ .id(SharedString::from(format!("mon-{w}x{h}")))+ .flex_1()+ .flex()+ .flex_col()+ .items_center()+ .gap(px(2.))+ .py(px(8.))+ .rounded(px(7.))+ .border_1()+ .border_color(if on { theme.accent } else { theme.border_variant })+ .bg(if on { theme.accent.opacity(0.1) } else { theme.element })+ .cursor_pointer()+ .hover(|st| st.border_color(theme.accent.opacity(0.6)))+ .child(div().text_size(px(12.5)).text_color(theme.text).child(format!("{w}×{h}")))+ .child(div().text_size(px(11.)).text_color(theme.text_placeholder).child(match (w, h) {+ _ if main == Some((w, h)) => "Same as main",+ (1280, 720) => "720p",+ (1920, 1080) => "1080p",+ (2560, 1440) => "1440p",+ _ => "4K",+ }))+ .on_click(cx.listener(move |this, _, _, cx| {+ this.size = (w, h);+ cx.notify()+ }))+ .into_any_element()+ })+ .collect();+ if self.asking {+ return password_frame(&theme, &self.machine_name, "plug in the new monitor")+ .child(field(&theme, "Your password", self.password.clone(), None))+ .children(error_line(&theme, &self.error))+ .child(footer(vec![+ Button::new("ad-cancel", "Cancel").style(ButtonStyle::Ghost).on_click(cx.listener(|_, _, _, cx| cx.emit(DialogEvent::Dismissed))).into_any_element(),+ Button::new("ad-pass", if self.adding { "Adding…" } else { "Add monitor" })+ .style(ButtonStyle::Primary)+ .loading(self.adding)+ .key_hint("↵")+ .on_click(cx.listener(|this, _, window, cx| this.submit(window, cx)))+ .into_any_element(),+ ]))+ .into_any_element();+ }+ frame(+ &theme,+ "Add a virtual monitor",+ Some(format!("Like plugging another screen into {}: windows can move there, and Muxen shows it on its own. It stays until you remove it or the machine restarts.", self.machine_name).into()),+ )+ .child(field(&theme, "Name", self.name.clone(), None))+ .child(div().flex().flex_col().gap(px(6.)).child(label(&theme, "Size").text_size(px(12.)).text_color(theme.text_muted)).child(div().flex().gap(px(8.)).children(sizes)))+ .children(error_line(&theme, &self.error))+ .child(footer(vec![+ Button::new("ad-cancel", "Cancel").style(ButtonStyle::Ghost).on_click(cx.listener(|_, _, _, cx| cx.emit(DialogEvent::Dismissed))).into_any_element(),+ Button::new("ad-add", if self.adding { "Adding…" } else { "Add monitor" })+ .style(ButtonStyle::Primary)+ .loading(self.adding)+ .key_hint("↵")+ .on_click(cx.listener(|this, _, window, cx| this.submit(window, cx)))+ .into_any_element(),+ ]))+ .into_any_element()+ }+}++/// Asking for the machine's password: what it's for, and where it goes.+fn password_frame(theme: &Theme, machine: &str, what: &str) -> gpui::Div {+ frame(+ theme,+ format!("Your password on {machine}"),+ Some(format!("{machine} asks for it to {what}. Muxen sends it to sudo there over its encrypted connection, and keeps it only in memory until you quit.").into()),+ )+}++/// The machine's password, to remove a virtual monitor (Linux asks sudo).+pub struct MonitorPasswordDialog {+ engine: Arc<Engine>,+ machine: String,+ machine_name: String,+ display: String,+ password: Entity<TextInput>,+ busy: bool,+ error: Option<String>,+ _subscriptions: Vec<Subscription>,+}++impl EventEmitter<DialogEvent> for MonitorPasswordDialog {}++impl MonitorPasswordDialog {+ pub fn new(engine: Arc<Engine>, machine: String, display: String, error: Option<String>, window: &mut Window, cx: &mut Context<Self>) -> Self {+ let machine_name = engine.current().machines.iter().find(|m| m.id == machine).map(|m| m.name.clone()).unwrap_or_else(|| machine.clone());+ let password = cx.new(|cx| TextInput::new(cx, "Password").secret());+ let sub = cx.subscribe_in(&password, window, |this: &mut Self, _, e: &InputEvent, _, cx| match e {+ InputEvent::Submit => this.submit(cx),+ InputEvent::Cancel => cx.emit(DialogEvent::Dismissed),+ InputEvent::Changed => {+ this.error = None;+ cx.notify()+ }+ });+ // A password that didn't work says so; a first ask doesn't need to.+ let error = error.filter(|e| e.contains("didn't work"));+ MonitorPasswordDialog { engine, machine, machine_name, display, password, busy: false, error, _subscriptions: vec![sub] }+ }++ pub fn first_focus(&self, cx: &App) -> FocusHandle {+ self.password.focus_handle(cx)+ }++ fn submit(&mut self, cx: &mut Context<Self>) {+ if self.busy {+ return;+ }+ let p = self.password.read(cx).text().to_string();+ if p.is_empty() {+ self.error = Some(format!("Type your password on {}.", self.machine_name));+ cx.notify();+ return;+ }+ self.password.update(cx, |i, cx| i.set_text("", cx));+ self.engine.remember_password(&self.machine, p);+ self.busy = true;+ self.error = None;+ cx.notify();+ let (engine, machine, display) = (self.engine.clone(), self.machine.clone(), self.display.clone());+ let job = engine.runtime().spawn({+ let engine = engine.clone();+ async move { engine.remove_display(&machine, &display).await }+ });+ cx.spawn(async move |this, cx| {+ let result = job.await.unwrap_or_else(|e| Err(crate::fleet::desktop::AddDisplayError::Failed(e.to_string())));+ let _ = this.update(cx, |this, cx| match result {+ Ok(()) => cx.emit(DialogEvent::Dismissed),+ Err(e) => {+ this.busy = false;+ this.error = Some(e.to_string());+ cx.notify();+ }+ });+ })+ .detach();+ }+}++impl Render for MonitorPasswordDialog {+ fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {+ let theme = cx.theme();+ password_frame(&theme, &self.machine_name, "unplug the virtual monitor")+ .child(field(&theme, "Your password", self.password.clone(), None))+ .children(error_line(&theme, &self.error))+ .child(footer(vec![+ Button::new("mp-cancel", "Cancel").style(ButtonStyle::Ghost).on_click(cx.listener(|_, _, _, cx| cx.emit(DialogEvent::Dismissed))).into_any_element(),+ Button::new("mp-go", if self.busy { "Removing…" } else { "Remove monitor" })+ .style(ButtonStyle::Primary)+ .loading(self.busy)+ .key_hint("↵")+ .on_click(cx.listener(|this, _, _, cx| this.submit(cx)))+ .into_any_element(),+ ]))+ }+}++// ---------------------------------------------------------------------------+type ConfirmAction = Box<dyn Fn(bool, &Arc<Engine>) -> Result<Option<u64>, String>>;pub struct ConfirmDialog {diff --git a/src/ui/menu.rs b/src/ui/menu.rsindex c1be6ac..8a983f0 100644--- a/src/ui/menu.rs+++ b/src/ui/menu.rs@@ -23,6 +23,8 @@ pub enum MenuTarget {GithubAccounts,/// An agent workspace, by id.Workspace(String),+ /// One of a machine's monitors.+ Display { machine: String, display: String },}pub struct ContextMenu {@@ -61,6 +63,12 @@ enum Action {AddAccount,RenameMachine(String),RenameSession(String),+ AddDisplay(String),+ ShowDisplay(String, String),+ RenameDisplay(String, String),+ RemoveDisplay(String, String),+ /// A monitor's size or scale.+ SetDisplay(String, String, Option<(u32, u32)>, Option<f64>),}enum Item {@@ -108,6 +116,9 @@ impl Root {if super::format::has_desktop(m) && !m.local {items.push(needs_up(act("Show desktop", "monitor", Action::ShowDesktop(id.clone()))));}+ if super::format::has_desktop(m) && !s.demo {+ items.push(needs_up(act("Add virtual monitor…", "monitor", Action::AddDisplay(id.clone()))));+ }if !m.platform.starts_with("windows") {items.push(needs_up(act("Copy files…", "folder", Action::CopyFiles(id.clone()))));}@@ -209,6 +220,39 @@ impl Root {items.push(Item::Action { label: "End session…".into(), glyph: Glyph::Icon("power"), action: Action::End(id.clone()), danger: true });items}+ MenuTarget::Display { machine, display } => {+ let Some(d) = s.machines.iter().find(|m| &m.id == machine).and_then(|m| m.displays.iter().find(|d| &d.id == display)) else { return Vec::new() };+ let mut items = vec![+ act("Show", "monitor", Action::ShowDisplay(machine.clone(), display.clone())),+ act("Rename…", "pencil", Action::RenameDisplay(machine.clone(), display.clone())),+ ];+ // Every size it offers (from 1024 wide), and its scale.+ let current = (d.width.round() as u32, d.height.round() as u32);+ let sizes: Vec<(u32, u32)> = d.modes.iter().copied().filter(|(w, _)| *w >= 1024).collect();+ if sizes.len() > 1 {+ items.push(Item::Separator);+ items.push(Item::Note("Resolution".into()));+ for size in sizes {+ let glyph = if size == current { Glyph::Selected } else { Glyph::None };+ let action = Action::SetDisplay(machine.clone(), display.clone(), Some(size), None);+ items.push(Item::Action { label: format!("{} × {}", size.0, size.1), glyph, action, danger: false });+ }+ }+ if [1., 2.].iter().all(|s| d.scales.iter().any(|x| (x - s).abs() < 0.01)) {+ items.push(Item::Separator);+ items.push(Item::Note("Scale".into()));+ for (scale, label) in [(1., "100%"), (2., "200% (twice as big, as sharp)")] {+ let glyph = if (d.scale - scale).abs() < 0.01 { Glyph::Selected } else { Glyph::None };+ let action = Action::SetDisplay(machine.clone(), display.clone(), None, Some(scale));+ items.push(Item::Action { label: label.into(), glyph, action, danger: false });+ }+ }+ if d.is_virtual {+ items.push(Item::Separator);+ items.push(Item::Action { label: "Remove monitor".into(), glyph: Glyph::Icon("trash-2"), action: Action::RemoveDisplay(machine.clone(), display.clone()), danger: true });+ }+ items+ }MenuTarget::Repo(name) => {let favorite = self.gh_is_favorite(name);vec![@@ -296,6 +340,11 @@ impl Root {Action::Check(machine) => self.engine.trigger_check(Some(machine)),Action::Runner(id, action) => self.runner_action(&id, action, cx),Action::FavoriteMachine(id, favorite) => self.set_favorite_machine(&id, favorite, cx),+ Action::AddDisplay(id) => self.show_add_display(id, window, cx),+ Action::ShowDisplay(machine, display) => self.show_display(machine, Some(display), window, cx),+ Action::RenameDisplay(machine, display) => self.show_rename(super::dialogs::RenameTarget::Display(machine, display), window, cx),+ Action::RemoveDisplay(machine, display) => self.remove_display(machine, display, window, cx),+ Action::SetDisplay(machine, display, size, scale) => self.set_display(machine, display, size, scale, window, cx),Action::RenameMachine(id) => self.show_rename(super::dialogs::RenameTarget::Machine(id), window, cx),Action::RenameSession(id) => self.show_rename(super::dialogs::RenameTarget::Session(id), window, cx),Action::CloudPower(id, on) => self.cloud_power(&id, on, cx),diff --git a/src/ui/mod.rs b/src/ui/mod.rsindex 19c4766..93a4de7 100644--- a/src/ui/mod.rs+++ b/src/ui/mod.rs@@ -14,6 +14,7 @@ mod kit;mod menu;mod overview;mod palette;+mod panes;mod desktop;mod sessions;mod settings;diff --git a/src/ui/palette.rs b/src/ui/palette.rsindex 1791186..a0db654 100644--- a/src/ui/palette.rs+++ b/src/ui/palette.rs@@ -69,6 +69,8 @@ enum Command {#[derive(Clone)]enum Run {Go(Route),+ /// A machine's desktop on one of its monitors (None: the main one).+ Screen(String, Option<String>),Do(Command),/// A theme, by id.Theme(&'static str),@@ -276,6 +278,7 @@ impl Root {self.close_palette(window, cx);match run {Run::Go(route) => self.navigate(route, window, cx),+ Run::Screen(machine, display) => self.show_display(machine, display, window, cx),Run::Do(c) => match c {Command::AddMachine => self.show_add_machine(window, cx),Command::NewCloudMachine => self.show_cloud_dialog(window, cx),@@ -384,11 +387,21 @@ impl Root {out.push(item);}if format::has_desktop(m) && !m.local && m.status == "online" {- let mut item = Item::new("Desktop", "See and use its screen", "Desktop", Glyph::Icon("monitor"), Run::Go(Route::Desktop(m.id.clone())));+ let mut item = Item::new("Desktop", "See and use its screen", "Desktop", Glyph::Icon("monitor"), Run::Screen(m.id.clone(), None));item.indent = true;item.group = Some(m.id.clone());item.also = m.name.clone();out.push(item);+ // Its other monitors, virtual ones included.+ for d in m.displays.iter().filter(|d| d.id != "all" && !d.main) {+ let kind = if d.is_virtual { "Virtual monitor" } else { "Monitor" };+ let detail = format!("{kind} · {}×{}", d.width as u32, d.height as u32);+ let mut item = Item::new(d.name.clone(), detail, "Desktop", Glyph::Icon("monitor"), Run::Screen(m.id.clone(), Some(d.id.clone())));+ item.indent = true;+ item.group = Some(m.id.clone());+ item.also = m.name.clone();+ out.push(item);+ }}}// Sessions on machines that aren't in the fleet anymore.diff --git a/src/ui/panes.rs b/src/ui/panes.rsnew file mode 100644index 0000000..f7143cf--- /dev/null+++ b/src/ui/panes.rs@@ -0,0 +1,126 @@+//! Terminals split side by side or one above the other, like panes in tmux+//! or iTerm: a layout of sessions shown together on one session page. The+//! sessions themselves live on their machines; a layout only says how to+//! show them, and is saved (Appearance::panes) so it comes back after a+//! restart. Written as text: a session id, or `r(a,b)` (a left of b) and+//! `d(a,b)` (a above b).++#[derive(Clone, Debug, PartialEq)]+pub enum Panes {+ One(String),+ Split { down: bool, a: Box<Panes>, b: Box<Panes> },+}++impl Panes {+ pub fn contains(&self, id: &str) -> bool {+ match self {+ Panes::One(x) => x == id,+ Panes::Split { a, b, .. } => a.contains(id) || b.contains(id),+ }+ }++ /// The sessions, left to right and top to bottom.+ pub fn ids(&self) -> Vec<&str> {+ match self {+ Panes::One(x) => vec![x.as_str()],+ Panes::Split { a, b, .. } => {+ let mut ids = a.ids();+ ids.extend(b.ids());+ ids+ }+ }+ }++ /// Puts `new` beside `at` (right of it, or below when `down`).+ pub fn split(&mut self, at: &str, new: String, down: bool) -> bool {+ match self {+ Panes::One(x) if x == at => {+ let old = std::mem::replace(self, Panes::One(String::new()));+ *self = Panes::Split { down, a: Box::new(old), b: Box::new(Panes::One(new)) };+ true+ }+ Panes::One(_) => false,+ Panes::Split { a, b, .. } => a.split(at, new.clone(), down) || b.split(at, new, down),+ }+ }++ /// Without `id`: the pane next to it takes its place. None when nothing's left.+ pub fn without(self, id: &str) -> Option<Panes> {+ match self {+ Panes::One(x) if x == id => None,+ one @ Panes::One(_) => Some(one),+ Panes::Split { down, a, b } => match (a.without(id), b.without(id)) {+ (Some(a), Some(b)) => Some(Panes::Split { down, a: Box::new(a), b: Box::new(b) }),+ (Some(only), None) | (None, Some(only)) => Some(only),+ (None, None) => None,+ },+ }+ }++ /// The share of the width and height `id` gets (half per split above it).+ pub fn share(&self, id: &str) -> Option<(f32, f32)> {+ match self {+ Panes::One(x) => (x == id).then_some((1., 1.)),+ Panes::Split { down, a, b } => {+ let (w, h) = a.share(id).or_else(|| b.share(id))?;+ Some(if *down { (w, h / 2.) } else { (w / 2., h) })+ }+ }+ }++ pub fn encode(&self) -> String {+ match self {+ Panes::One(x) => x.clone(),+ Panes::Split { down, a, b } => format!("{}({},{})", if *down { "d" } else { "r" }, a.encode(), b.encode()),+ }+ }++ pub fn decode(text: &str) -> Option<Panes> {+ let (panes, rest) = parse(text.trim())?;+ rest.is_empty().then_some(panes)+ }+}++fn parse(text: &str) -> Option<(Panes, &str)> {+ if let Some(inner) = text.strip_prefix("r(").or_else(|| text.strip_prefix("d(")) {+ let down = text.starts_with('d');+ let (a, rest) = parse(inner)?;+ let (b, rest) = parse(rest.strip_prefix(',')?)?;+ return Some((Panes::Split { down, a: Box::new(a), b: Box::new(b) }, rest.strip_prefix(')')?));+ }+ let end = text.find([',', ')']).unwrap_or(text.len());+ let id = &text[..end];+ (!id.is_empty()).then(|| (Panes::One(id.to_string()), &text[end..]))+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn splits_and_closes() {+ let mut p = Panes::One("m/a".into());+ assert!(p.split("m/a", "m/b".into(), false));+ assert!(p.split("m/b", "m/c".into(), true));+ assert_eq!(p.encode(), "r(m/a,d(m/b,m/c))");+ assert_eq!(p.ids(), ["m/a", "m/b", "m/c"]);+ assert_eq!(p.share("m/a"), Some((0.5, 1.)));+ assert_eq!(p.share("m/c"), Some((0.5, 0.5)));+ assert_eq!(p.share("m/x"), None);+ assert!(!p.split("m/x", "m/y".into(), false));+ let p = p.without("m/b").unwrap();+ assert_eq!(p.encode(), "r(m/a,m/c)");+ let p = p.without("m/a").unwrap();+ assert_eq!(p, Panes::One("m/c".into()));+ assert_eq!(p.without("m/c"), None);+ }++ #[test]+ fn reads_what_it_writes() {+ for text in ["beelink/shell-ab12", "r(beelink/a,beelink/b)", "d(r(m/a,m/b),m/c-1)"] {+ assert_eq!(Panes::decode(text).map(|p| p.encode()).as_deref(), Some(text));+ }+ assert_eq!(Panes::decode("r(m/a,"), None);+ assert_eq!(Panes::decode("r(m/a,m/b))"), None);+ }+}diff --git a/src/ui/root.rs b/src/ui/root.rsindex 7264b1a..9706e0b 100644--- a/src/ui/root.rs+++ b/src/ui/root.rs@@ -10,7 +10,7 @@ use gpui::{MenuItem, MouseButton, ScrollHandle, SharedString, Subscription, Task, Window, actions, div, prelude::*, px,};-use super::dialogs::{AddMachineDialog, ConfirmDialog, DialogEvent, InstallDialog, NewSessionDialog, NewWorkspaceDialog, RenameDialog, RenameTarget};+use super::dialogs::{AddDisplayDialog, MonitorPasswordDialog, AddMachineDialog, ConfirmDialog, DialogEvent, InstallDialog, NewSessionDialog, NewWorkspaceDialog, RenameDialog, RenameTarget};use super::terminal::TerminalView;use super::format;use super::input::{InputEvent, TextInput};@@ -51,6 +51,10 @@ actions!(ToggleSidebar,AddMachine,NewSession,+ SplitRight,+ SplitDown,+ NextPane,+ PreviousPane,QuickOpen,CommandPalette,ShowAbout,@@ -172,6 +176,8 @@ pub enum Modal {Copy(Entity<super::files::CopyDialog>),Cloud(Entity<super::cloud_dialog::CloudDialog>),Rename(Entity<RenameDialog>),+ AddDisplay(Entity<AddDisplayDialog>),+ MonitorPassword(Entity<MonitorPasswordDialog>),}pub struct Notice {@@ -233,6 +239,8 @@ pub struct Root {desktops: std::collections::HashMap<String, Entity<super::desktop::DesktopView>>,/// Sessions showing their machine's desktop beside the terminal.pub(super) split: HashSet<String>,+ /// Terminals split into panes (see panes.rs); a session page shows the layout it's in.+ pub(super) panes: Vec<super::panes::Panes>,/// The terminal's share of a split page, and whether its divider is being dragged.pub(super) split_ratio: f32,pub(super) split_resizing: bool,@@ -369,6 +377,7 @@ impl Root {gh: Default::default(),desktops: Default::default(),split: Default::default(),+ panes: cx.global::<super::theme::Appearance>().panes.iter().filter_map(|t| super::panes::Panes::decode(t)).filter(|p| p.ids().len() > 1).collect(),split_ratio: cx.global::<super::theme::Appearance>().split_ratio.clamp(0.2, 0.8),split_resizing: false,machine_git: Default::default(),@@ -402,14 +411,19 @@ impl Root {// Terminals of sessions that ended go away (one without the agent stops with its terminal).self.terminals.retain(|id, _| snapshot.sessions.iter().any(|s| &s.id == id));// Looking at a session that just closed: back to its machine.- if let Route::Session(id) = &self.route {- let gone = !snapshot.sessions.iter().any(|s| &s.id == id) && self.snapshot.sessions.iter().any(|s| &s.id == id);+ if let Route::Session(id) = self.route.clone() {+ let gone = !snapshot.sessions.iter().any(|s| s.id == id) && self.snapshot.sessions.iter().any(|s| s.id == id);if gone {- let machine = id.split('/').next().unwrap_or_default().to_string();- self.show(Route::Machine(machine), cx);+ // In a split: the pane next to it.+ let next = self.panes.iter().find(|p| p.contains(&id)).and_then(|p| p.ids().into_iter().find(|x| *x != id && snapshot.sessions.iter().any(|s| s.id == *x)).map(str::to_string));+ match next {+ Some(next) => self.route = Route::Session(next),+ None => self.show(Route::Machine(id.split('/').next().unwrap_or_default().to_string()), cx),+ }self.refocus = true;}}+ self.prune_panes(&snapshot, cx);// Favorites of machines that are gone (removed, destroyed) go too. Not// while the list is empty: that's before config.toml has been read.let favorites = &cx.global::<super::theme::Appearance>().favorite_machines;@@ -474,7 +488,7 @@ impl Root {self.show(Route::Activity, cx);}- fn on_route_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {+ pub(super) fn on_route_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {if self.route == Route::Settings && self.settings.is_none() {let engine = self.engine.clone();self.settings = Some(cx.new(|cx| SettingsPage::new(engine, window, cx)));@@ -488,7 +502,7 @@ impl Root {// A desktop streams only while it's shown: its page, or beside a session.let showing = match &self.route {Route::Desktop(id) => Some(id.clone()),- Route::Session(sid) if self.split.contains(sid) => sid.split('/').next().map(str::to_string),+ Route::Session(sid) if self.page_split(sid).is_some() => sid.split('/').next().map(str::to_string),_ => None,};// Desktops in the sidebar keep streaming, so going back is instant.@@ -608,6 +622,7 @@ impl Root {self.show_install_dialog(arg, window, cx);}"add-machine" => self.show_add_machine(window, cx),+ "add-display" => self.show_add_display(arg.into(), window, cx),// "rename:<machine-id>", and "rename-session:<session-id>" (the first session without one)."rename" => self.show_rename(RenameTarget::Machine(arg.into()), window, cx),"rename-session" => {@@ -657,10 +672,44 @@ impl Root {}"activity" => self.show(Route::Activity, cx),"about" => self.navigate(Route::About, window, cx),- "desktop" => self.navigate(Route::Desktop(arg.into()), window, cx),+ // "desktop:<machine>", or "desktop:<machine>@<display>" for one of its displays.+ "desktop" => match arg.split_once('@') {+ Some((machine, display)) => self.show_display(machine.into(), Some(display.into()), window, cx),+ None => self.navigate(Route::Desktop(arg.into()), window, cx),+ },"desktop-window" => {let name = self.snapshot.machines.iter().find(|m| m.id == arg).map(|m| m.name.clone()).unwrap_or_else(|| arg.to_string());- super::desktop::open_window(self.engine.clone(), arg.to_string(), name, cx);+ super::desktop::open_window(self.engine.clone(), arg.to_string(), None, name, cx);+ }+ // Sessions split into panes: "panes:r(<id>+d(<id>+<id>))" (`+` for+ // the layout's commas, which separate views).+ "panes" => {+ if let Some(layout) = super::panes::Panes::decode(&arg.replace('+', ",")).filter(|p| p.ids().len() > 1) {+ let first = layout.ids()[0].to_string();+ self.panes.retain(|p| !layout.ids().iter().any(|id| p.contains(id)));+ self.panes.push(layout);+ let saved: Vec<String> = self.panes.iter().map(super::panes::Panes::encode).collect();+ super::theme::remember(cx, |a| a.panes = saved);+ self.navigate(Route::Session(first), window, cx);+ }+ }+ // The session shown, split: a new shell beside it or below it.+ // (once the session is known: sessions are found over the network).+ "split-right" | "split-down" => {+ let down = kind == "split-down";+ let task = cx.spawn_in(window, async move |this, cx| {+ for _ in 0..100 {+ let known = this+ .update(cx, |this, _| matches!(&this.route, Route::Session(id) if this.snapshot.sessions.iter().any(|s| &s.id == id)))+ .unwrap_or(false);+ if known {+ let _ = this.update_in(cx, |this, window, cx| this.split_session(down, window, cx));+ return;+ }+ cx.background_executor().timer(std::time::Duration::from_millis(200)).await;+ }+ });+ self.track(task);}// A session with its machine's desktop beside the terminal."split" => {@@ -868,6 +917,73 @@ impl Root {self._subscriptions.push(cx.subscribe_in(&dialog, window, Self::on_dialog_event));}+ /// Asks for a new virtual monitor's name and size.+ pub(super) fn show_add_display(&mut self, machine: String, window: &mut Window, cx: &mut Context<Self>) {+ let engine = self.engine.clone();+ let dialog = cx.new(|cx| AddDisplayDialog::new(engine, machine, window, cx));+ self.show_modal(Modal::AddDisplay(dialog.clone()), window, cx);+ self._subscriptions.push(cx.subscribe_in(&dialog, window, Self::on_dialog_event));+ }++ /// Shows one of a machine's displays (None: its default one) on the desktop page.+ pub(super) fn show_display(&mut self, machine: String, display: Option<String>, window: &mut Window, cx: &mut Context<Self>) {+ self.pin_desktop(&machine, cx);+ self.navigate(Route::Desktop(machine.clone()), window, cx);+ if let Some(view) = self.desktops.get(&machine).cloned() {+ view.update(cx, |v, cx| v.set_display(display, window, cx));+ }+ cx.notify();+ }++ /// Sets a monitor's size or scale, through its desktop view when one is+ /// open (it follows the new size).+ pub(super) fn set_display(&mut self, machine: String, display: String, size: Option<(u32, u32)>, scale: Option<f64>, window: &mut Window, cx: &mut Context<Self>) {+ if let Some(view) = self.desktops.get(&machine).cloned() {+ view.update(cx, |v, cx| v.change_display(display, size, scale, window, cx));+ return;+ }+ let engine = self.engine.clone();+ let job = engine.runtime().spawn({+ let engine = engine.clone();+ async move { engine.set_display(&machine, &display, size, scale).await }+ });+ let task = cx.spawn_in(window, async move |this, cx| {+ if let Ok(Err(e)) = job.await {+ let _ = this.update(cx, |this, cx| this.notify_user(e, true, cx));+ }+ });+ self.track(task);+ }++ /// Removes a virtual monitor; the desktop goes back to the default display.+ pub(super) fn remove_display(&mut self, machine: String, display: String, window: &mut Window, cx: &mut Context<Self>) {+ let (machine_for_dialog, display_for_dialog) = (machine.clone(), display.clone());+ if let Some(view) = self.desktops.get(&machine).cloned() {+ view.update(cx, |v, cx| v.set_display(None, window, cx));+ }+ let engine = self.engine.clone();+ let job = engine.runtime().spawn({+ let engine = engine.clone();+ async move { engine.remove_display(&machine, &display).await }+ });+ let task = cx.spawn_in(window, async move |this, cx| match job.await {+ // The machine asks for the password (sudo, on Linux).+ Ok(Err(crate::fleet::desktop::AddDisplayError::NeedsPassword(why))) => {+ let _ = this.update_in(cx, |this, window, cx| {+ let engine = this.engine.clone();+ let dialog = cx.new(|cx| MonitorPasswordDialog::new(engine, machine_for_dialog, display_for_dialog, Some(why), window, cx));+ this.show_modal(Modal::MonitorPassword(dialog.clone()), window, cx);+ this._subscriptions.push(cx.subscribe_in(&dialog, window, Self::on_dialog_event));+ });+ }+ Ok(Err(e)) => {+ let _ = this.update(cx, |this, cx| this.notify_user(e.to_string(), true, cx));+ }+ _ => {}+ });+ self.track(task);+ }+/// Asks for a machine's or a session's new name.pub(super) fn show_rename(&mut self, target: RenameTarget, window: &mut Window, cx: &mut Context<Self>) {let s = &self.snapshot;@@ -878,6 +994,13 @@ impl Root {Some(x) => (x.title.clone(), machine_name(&x.machine_id)),None => return,},+ RenameTarget::Display(machine, display) => {+ let name = s.machines.iter().find(|m| &m.id == machine).and_then(|m| m.displays.iter().find(|d| &d.id == display)).map(|d| d.name.clone());+ match name {+ Some(n) => (n, machine_name(machine)),+ None => return,+ }+ }};let engine = self.engine.clone();let dialog = cx.new(|cx| RenameDialog::new(engine, target, current, machine, window, cx));@@ -1093,6 +1216,8 @@ impl Root {Modal::Copy(d) => d.read(cx).first_focus(cx),Modal::Cloud(d) => d.read(cx).first_focus(cx),Modal::Rename(d) => d.read(cx).first_focus(cx),+ Modal::AddDisplay(d) => d.read(cx).first_focus(cx),+ Modal::MonitorPassword(d) => d.read(cx).first_focus(cx),Modal::Licenses(d) => d.focus_handle(cx),};window.focus(&focus);@@ -1111,6 +1236,7 @@ impl Root {DialogEvent::NewCloudMachine => self.show_cloud_dialog(window, cx),DialogEvent::CreateWorkspace(req, iso) => self.create_workspace(req.clone(), iso.clone(), window, cx),DialogEvent::StartInWorkspace(req, session) => self.start_in_workspace(req.clone(), session.clone(), window, cx),+ DialogEvent::DisplayAdded(machine, display) => self.show_display(machine.clone(), Some(display.clone()), window, cx),DialogEvent::StartSession(req) => {self.start_session(req.clone(), window, cx);cx.notify();@@ -1336,8 +1462,17 @@ impl Root {for x in sessions {rows.push(self.session_row(&theme, x, selected_session.as_deref() == Some(&x.id), cx).into_any_element());}+ // Which of its displays the desktop page shows, when it's on screen.+ let showing = (self.route == Route::Desktop(m.id.clone())).then(|| self.desktops.get(&m.id).map(|v| v.read(cx).display().map(str::to_string))).flatten();+ let on_virtual = showing.as_ref().is_some_and(|d| d.as_ref().is_some_and(|d| m.displays.iter().any(|x| &x.id == d && x.is_virtual)));+ // The open desktop: its main screen, then the virtual monitors+ // (closed together).if has_desktop {- rows.push(self.desktop_row(&theme, m, self.route == Route::Desktop(m.id.clone()), cx).into_any_element());+ rows.push(self.desktop_row(&theme, m, showing.is_some() && !on_virtual, cx).into_any_element());+ for d in m.displays.iter().filter(|d| d.is_virtual) {+ let selected = showing.as_ref().is_some_and(|s| s.as_deref() == Some(d.id.as_str()));+ rows.push(self.monitor_row(&theme, m, d, selected, cx).into_any_element());+ }}// Runners as one line; a search shows the ones it found.if !machine_match {@@ -2095,7 +2230,31 @@ impl Root {}let Some(view) = self.desktops.get(id).cloned() else { return div().into_any_element() };let (pop, close) = (id.to_string(), id.to_string());- let extra = vec![+ let machine = self.snapshot.machines.iter().find(|m| m.id == id);+ let shown = view.read(cx).display().map(str::to_string);+ let virtual_shown = shown.clone().filter(|d| machine.is_some_and(|m| m.displays.iter().any(|x| &x.id == d && x.is_virtual)));+ let can_add = machine.is_some() && !self.snapshot.demo;+ let mut extra = Vec::new();+ if let Some(display) = virtual_shown {+ let mid = id.to_string();+ extra.push(+ Button::new("desktop-remove-monitor", "Remove monitor")+ .style(ButtonStyle::Ghost)+ .icon("trash-2")+ .on_click(cx.listener(move |this, _, window, cx| this.remove_display(mid.clone(), display.clone(), window, cx)))+ .into_any_element(),+ );+ } else if can_add {+ let mid = id.to_string();+ extra.push(+ Button::new("desktop-add-monitor", "Add monitor")+ .style(ButtonStyle::Ghost)+ .icon("plus")+ .on_click(cx.listener(move |this, _, window, cx| this.show_add_display(mid.clone(), window, cx)))+ .into_any_element(),+ );+ }+ extra.extend(vec![Button::new("desktop-window", "Open in window").style(ButtonStyle::Ghost).icon("external-link")@@ -2106,12 +2265,17 @@ impl Root {.icon("x").on_click(cx.listener(move |this, _, window, cx| this.close_desktop(&close, window, cx))).into_any_element(),- ];+ ]);+ let root = cx.entity().downgrade();+ let menu: super::desktop::DisplayMenu = std::rc::Rc::new(move |machine: &str, display: &str, at, _window, cx| {+ let target = super::menu::MenuTarget::Display { machine: machine.to_string(), display: display.to_string() };+ let _ = root.update(cx, |this, cx| this.open_menu(target, at, cx));+ });div().size_full().flex().flex_col()- .child(super::desktop::toolbar(&view, extra, cx))+ .child(super::desktop::toolbar_with_menu(&view, extra, Some(menu), cx)).child(div().flex_1().min_h(px(0.)).child(view)).into_any_element()}@@ -2141,7 +2305,9 @@ impl Root {pub(super) fn desktop_to_sidebar(&mut self, session_id: &str, window: &mut Window, cx: &mut Context<Self>) {let machine = session_id.split('/').next().unwrap_or_default().to_string();self.pin_desktop(&machine, cx);- self.split.remove(session_id);+ if let Some(key) = self.page_split(session_id) {+ self.split.remove(&key);+ }self.navigate(Route::Desktop(machine), window, cx);}@@ -2149,9 +2315,17 @@ impl Root {fn desktop_row(&self, theme: &Theme, m: &Machine, selected: bool, cx: &mut Context<Self>) -> impl IntoElement {let (open, close) = (m.id.clone(), m.id.clone());let (from, to) = format::machine_tile(m);+ // Its main monitor: the size, and its menu on right-click (no Remove: it's real).+ let main = m.displays.iter().find(|d| d.main && d.id != "all").cloned();+ let size = main.as_ref().map(|d| format!("{}×{}", d.width as u32, d.height as u32));+ let right_click = main.map(|d| {+ let (machine, display) = (m.id.clone(), d.id);+ super::menu::on_right_click(move || super::menu::MenuTarget::Display { machine: machine.clone(), display: display.clone() }, cx)+ });div().id(SharedString::from(format!("side-d-{}", m.id))).group("desktop-row")+ .relative().flex().items_center().gap(px(8.))@@ -2165,31 +2339,92 @@ impl Root {.when(!selected, |d| d.hover(|st| st.bg(theme.ghost_hover))).child(kit::tile("monitor", from, to, 16.)).child(div().flex_1().text_size(px(12.5)).text_color(if selected { theme.text } else { theme.text_muted }).child("Desktop"))+ // The size lines up with the monitors' below; the close button+ // takes its place on hover.+ .children(size.map(|s| div().flex_none().font_family(mono_font()).text_size(px(10.5)).text_color(theme.text_placeholder).group_hover("desktop-row", |st| st.invisible()).child(s))).child(div().id(SharedString::from(format!("side-d-x-{}", m.id)))+ .absolute()+ .right(px(8.)).invisible().group_hover("desktop-row", |st| st.visible())+ .tooltip(|window, cx| kit::Tooltip::view("Close the desktop".into(), window, cx)).child(icon("x", 12., theme.text_placeholder)).on_click(cx.listener(move |this, _, window, cx| {cx.stop_propagation();this.close_desktop(&close, window, cx)})),)- .on_click(cx.listener(move |this, _, window, cx| this.navigate(Route::Desktop(open.clone()), window, cx)))+ .when_some(right_click, |el, f| el.on_mouse_down(MouseButton::Right, f))+ // Its main monitor (the virtual ones are listed below it).+ .on_click(cx.listener(move |this, _, window, cx| this.show_display(open.clone(), None, window, cx)))+ }++ /// A virtual monitor's item in the sidebar, under its machine: opens the+ /// desktop page on it.+ fn monitor_row(&self, theme: &Theme, m: &Machine, d: &crate::fleet::model::DisplayInfo, selected: bool, cx: &mut Context<Self>) -> impl IntoElement {+ let (machine, display) = (m.id.clone(), d.id.clone());+ let remove = (m.id.clone(), d.id.clone());+ let (from, to) = format::machine_tile(m);+ div()+ .id(SharedString::from(format!("side-v-{}-{}", m.id, d.id)))+ .group("monitor-row")+ .relative()+ .flex()+ .items_center()+ .gap(px(8.))+ .h(px(26.))+ .mx(px(10.))+ .pl(px(22.))+ .pr(px(8.))+ .rounded(px(7.))+ .cursor_pointer()+ .when(selected, |el| el.bg(theme.element_selected))+ .when(!selected, |el| el.hover(|st| st.bg(theme.ghost_hover)))+ .child(kit::tile("monitor", from, to, 16.))+ // An explicit width: GPUI 0.2 only ellipsizes text whose width it knows.+ .child(div().w(px((self.sidebar_width - 20. - 30. - 16. - 16. - 74. - 52.).max(40.))).truncate().text_size(px(12.5)).text_color(if selected { theme.text } else { theme.text_muted }).child(d.name.clone()))+ .child(div().flex_1())+ // Which ones Muxen added (and the × takes away).+ .child(kit::pill("virtual", theme.accent))+ .child(div().flex_none().font_family(mono_font()).text_size(px(10.5)).text_color(theme.text_placeholder).group_hover("monitor-row", |st| st.invisible()).child(format!("{}×{}", d.width as u32, d.height as u32)))+ // On hover, in place of the size: unplug it.+ .child(+ div()+ .id(SharedString::from(format!("side-v-x-{}-{}", m.id, d.id)))+ .absolute()+ .right(px(8.))+ .invisible()+ .group_hover("monitor-row", |st| st.visible())+ .tooltip(|window, cx| kit::Tooltip::view("Remove this virtual monitor".into(), window, cx))+ .child(icon("x", 12., theme.text_placeholder))+ .on_click(cx.listener(move |this, _, window, cx| {+ cx.stop_propagation();+ this.remove_display(remove.0.clone(), remove.1.clone(), window, cx)+ })),+ )+ .on_mouse_down(MouseButton::Right, {+ let (machine, display) = (m.id.clone(), d.id.clone());+ super::menu::on_right_click(move || super::menu::MenuTarget::Display { machine: machine.clone(), display: display.clone() }, cx)+ })+ .on_click(cx.listener(move |this, _, window, cx| this.show_display(machine.clone(), Some(display.clone()), window, cx)))}/// Moves a machine's desktop into a window of its own (and out of this one).pub(super) fn pop_out_desktop(&mut self, machine_id: &str, window: &mut Window, cx: &mut Context<Self>) {+ let display = self.desktops.get(machine_id).and_then(|v| v.read(cx).display().map(str::to_string));let id = machine_id.to_string();super::theme::remember(cx, |a| a.desktops.retain(|d| *d != id));self.desktops.remove(machine_id);let name = self.snapshot.machines.iter().find(|m| m.id == machine_id).map(|m| m.name.clone()).unwrap_or_else(|| machine_id.to_string());- super::desktop::open_window(self.engine.clone(), machine_id.to_string(), name, cx);+ super::desktop::open_window(self.engine.clone(), machine_id.to_string(), display, name, cx);match self.route.clone() {Route::Desktop(_) => self.navigate(Route::Machine(machine_id.to_string()), window, cx),Route::Session(sid) => {- self.split.remove(&sid);+ if let Some(key) = self.page_split(&sid) {+ self.split.remove(&key);+ }self.on_route_changed(window, cx);}_ => {}@@ -2198,17 +2433,20 @@ impl Root {/// Shows or hides a machine's desktop next to a session's terminal.pub(super) fn toggle_split(&mut self, session_id: &str, window: &mut Window, cx: &mut Context<Self>) {- if !self.split.remove(session_id) {- self.split.insert(session_id.to_string());+ match self.page_split(session_id) {+ Some(key) => {+ self.split.remove(&key);+ }+ None => {+ self.split.insert(session_id.to_string());+ }}self.on_route_changed(window, cx);}/// The desktop shown next to a session's terminal, if it's split.pub(super) fn split_desktop(&self, session_id: &str) -> Option<Entity<super::desktop::DesktopView>> {- if !self.split.contains(session_id) {- return None;- }+ self.page_split(session_id)?;self.desktops.get(session_id.split('/').next().unwrap_or_default()).cloned()}@@ -2254,7 +2492,11 @@ impl Render for Root {self.keys_soon = None;}if std::mem::take(&mut self.refocus) {- window.focus(&self.focus);+ // Moved to another pane of a split: its terminal; else the page.+ match &self.route {+ Route::Session(id) if self.terminals.contains_key(id) => window.focus(&self.terminals[id].focus_handle(cx)),+ _ => window.focus(&self.focus),+ }}let window_height = f32::from(window.viewport_size().height);// Dialogs sit lower on tall windows and scroll when they don't fit.@@ -2270,6 +2512,8 @@ impl Render for Root {Modal::Copy(d) => d.clone().into_any_element(),Modal::Cloud(d) => d.clone().into_any_element(),Modal::Rename(d) => d.clone().into_any_element(),+ Modal::AddDisplay(d) => d.clone().into_any_element(),+ Modal::MonitorPassword(d) => d.clone().into_any_element(),Modal::Licenses(d) => d.clone().into_any_element(),});let notice = self.render_notice(&theme);@@ -2303,6 +2547,10 @@ impl Render for Root {.on_action(cx.listener(Self::toggle_activity)).on_action(cx.listener(Self::add_machine)).on_action(cx.listener(Self::new_session))+ .on_action(cx.listener(|this, _: &SplitRight, window, cx| this.split_session(false, window, cx)))+ .on_action(cx.listener(|this, _: &SplitDown, window, cx| this.split_session(true, window, cx)))+ .on_action(cx.listener(|this, _: &NextPane, window, cx| this.step_pane(1, window, cx)))+ .on_action(cx.listener(|this, _: &PreviousPane, window, cx| this.step_pane(-1, window, cx))).on_action(cx.listener(|this, _: &QuickOpen, window, cx| this.open_palette(false, window, cx))).on_action(cx.listener(|this, _: &CommandPalette, window, cx| this.open_palette(true, window, cx))).on_action(cx.listener(|this, _: &ShowAbout, window, cx| this.navigate(Route::About, window, cx)))diff --git a/src/ui/sessions.rs b/src/ui/sessions.rsindex 3d376de..4d20867 100644--- a/src/ui/sessions.rs+++ b/src/ui/sessions.rs@@ -10,6 +10,7 @@ use gpui::{AnyElement, ClipboardItem, Context, Focusable, FontWeight, SharedStriuse super::dialogs::{ConfirmDialog, NewSessionDialog};use super::format;use super::kit::{self, Button, ButtonStyle, card, icon, section_title, spinner};+use super::panes::Panes;use super::root::{Modal, Root, Route};use super::terminal::{TerminalEvent, TerminalView};use super::theme::{ActiveTheme, Theme, mono_font};@@ -84,13 +85,28 @@ impl Root {/// Columns and rows a session's terminal gets in this window (its share of/// the width when the desktop is beside it).fn terminal_fit(&self, id: &str, window: &mut Window, cx: &mut Context<Self>) -> (u16, u16) {+ match self.pane_layout(id).and_then(|p| p.share(id)) {+ Some(share) => self.fit_share(id, share, window, cx),+ None => self.fit_area(id, 1., 1., window, cx),+ }+ }++ /// The size of a pane with this share of the page (under its title bar).+ fn fit_share(&self, id: &str, (w, h): (f32, f32), window: &mut Window, cx: &mut Context<Self>) -> (u16, u16) {+ self.fit_area(id, w, h, window, cx)+ }++ fn fit_area(&self, id: &str, w: f32, h: f32, window: &mut Window, cx: &mut Context<Self>) -> (u16, u16) {let viewport = window.viewport_size();let sidebar = if self.sidebar_hidden { 0. } else { self.sidebar_width };let mut width = f32::from(viewport.width) - sidebar;- if self.split.contains(id) {+ if self.page_split(id).is_some() {width *= self.split_ratio;}- TerminalView::fit(width, f32::from(viewport.height) - CHROME_HEIGHT, window, cx)+ let height = f32::from(viewport.height) - CHROME_HEIGHT;+ // A pane: its share, less its border and title bar.+ let (width, height) = if (w, h) == (1., 1.) && self.pane_layout(id).is_none() { (width, height) } else { (width * w - 2., height * h - 26.) };+ TerminalView::fit(width, height, window, cx)}pub(super) fn start_session(&mut self, req: StartSession, window: &mut Window, cx: &mut Context<Self>) {@@ -129,9 +145,13 @@ impl Root {/// Attaches a terminal to the session, unless one is already attached.pub(super) fn open_terminal(&mut self, id: &str, window: &mut Window, cx: &mut Context<Self>) {+ // Keys go to the session the page is on (the focused pane of a split).+ let shown = self.route == Route::Session(id.to_string());if let Some(t) = self.terminals.get(id) {if !t.read(cx).exited() {- window.focus(&t.focus_handle(cx));+ if shown {+ window.focus(&t.focus_handle(cx));+ }return;}}@@ -184,11 +204,137 @@ impl Root {cx.notify();}}));- window.focus(&view.focus_handle(cx));+ if shown {+ window.focus(&view.focus_handle(cx));+ }self.terminals.insert(id.to_string(), view);self.refresh_machine_sessions(id.split('/').next().unwrap_or_default());}+ // -----------------------------------------------------------------------+ // Panes: terminals split side by side or one above the other (panes.rs).++ /// The layout a session is in, if it's split.+ pub(super) fn pane_layout(&self, id: &str) -> Option<&Panes> {+ self.panes.iter().find(|p| p.contains(id))+ }++ /// The session of a page whose desktop is shown beside it: `id`, or+ /// another pane of its layout.+ pub(super) fn page_split(&self, id: &str) -> Option<String> {+ match self.pane_layout(id) {+ Some(p) => p.ids().into_iter().find(|x| self.split.contains(*x)).map(str::to_string),+ None => self.split.contains(id).then(|| id.to_string()),+ }+ }++ fn save_panes(&self, cx: &mut Context<Self>) {+ let saved: Vec<String> = self.panes.iter().map(Panes::encode).collect();+ super::theme::remember(cx, |a| a.panes = saved);+ }++ /// Splits the shown session's pane: a new shell on its machine, in its+ /// folder, to its right or below it.+ pub(super) fn split_session(&mut self, down: bool, window: &mut Window, cx: &mut Context<Self>) {+ let Route::Session(id) = self.route.clone() else { return };+ let Some(info) = self.snapshot.sessions.iter().find(|s| s.id == id).cloned() else { return };+ if !info.persistent || self.engine.is_demo() {+ self.notify_user("This session can't be split.", true, cx);+ return;+ }+ // Exactly the size its pane will have (half of this one), so the shell+ // isn't resized while it starts (zsh would mark its prompts with a stray %).+ let (w, h) = self.pane_layout(&id).and_then(|p| p.share(&id)).unwrap_or((1., 1.));+ let share = if down { (w, h / 2.) } else { (w / 2., h) };+ let (cols, rows) = self.fit_share(&id, share, window, cx);+ let req = StartSession { machine_id: info.machine_id.clone(), agent: "shell".into(), cwd: info.cwd.clone(), cols, rows, ..Default::default() };+ let engine = self.engine.clone();+ let job = engine.runtime().spawn({+ let engine = engine.clone();+ async move { engine.start_session(req).await }+ });+ let task = cx.spawn_in(window, async move |this, cx| {+ let result = job.await.unwrap_or_else(|e| Err(e.to_string()));+ let _ = this.update_in(cx, |this, window, cx| match result {+ Ok(s) => {+ match this.panes.iter_mut().find(|p| p.contains(&id)) {+ Some(p) => {+ p.split(&id, s.id.clone(), down);+ }+ None => {+ let mut p = Panes::One(id.clone());+ p.split(&id, s.id.clone(), down);+ this.panes.push(p);+ }+ }+ this.save_panes(cx);+ this.focus_pane(&s.id, window, cx);+ }+ Err(e) => this.notify_user(e, true, cx),+ });+ });+ self.track(task);+ }++ /// Shows another pane of the layout: keys go there.+ pub(super) fn focus_pane(&mut self, id: &str, window: &mut Window, cx: &mut Context<Self>) {+ let route = Route::Session(id.to_string());+ if self.route != route {+ // The same page: no step in Back.+ self.route = route;+ self.on_route_changed(window, cx);+ }+ }++ /// The next (or previous) pane of the shown layout.+ pub(super) fn step_pane(&mut self, step: isize, window: &mut Window, cx: &mut Context<Self>) {+ let Route::Session(id) = self.route.clone() else { return };+ let Some(ids) = self.pane_layout(&id).map(|p| p.ids().into_iter().map(str::to_string).collect::<Vec<_>>()) else { return };+ let at = ids.iter().position(|x| *x == id).unwrap_or(0) as isize;+ let next = ids[(at + step).rem_euclid(ids.len() as isize) as usize].clone();+ self.focus_pane(&next, window, cx);+ }++ /// Takes a pane out of its layout; the session goes on (in the sidebar).+ fn close_pane(&mut self, id: &str, window: &mut Window, cx: &mut Context<Self>) {+ let Some(i) = self.panes.iter().position(|p| p.contains(id)) else { return };+ let layout = self.panes.remove(i);+ let rest = layout.without(id);+ let next = rest.as_ref().and_then(|p| p.ids().first().map(|x| x.to_string()));+ if let Some(rest) = rest.filter(|p| p.ids().len() > 1) {+ self.panes.insert(i, rest);+ }+ self.save_panes(cx);+ if self.route == Route::Session(id.to_string())+ && let Some(next) = next+ {+ self.focus_pane(&next, window, cx);+ }+ cx.notify();+ }++ /// Sessions that ended leave their layouts (once their machine has been+ /// asked, so nothing goes while sessions are still being found).+ pub(super) fn prune_panes(&mut self, snapshot: &Snapshot, cx: &mut Context<Self>) {+ let engine = self.engine.clone();+ let gone = |id: &str| {+ let machine = id.split('/').next().unwrap_or_default();+ !snapshot.sessions.iter().any(|s| s.id == id) && engine.sessions_of(machine).is_some_and(|f| f.checked_at.is_some())+ };+ let before = self.panes.clone();+ self.panes = std::mem::take(&mut self.panes)+ .into_iter()+ .filter_map(|p| {+ let ids: Vec<String> = p.ids().into_iter().map(str::to_string).collect();+ ids.iter().filter(|id| gone(id)).try_fold(p, |p, id| p.without(id))+ })+ .filter(|p| p.ids().len() > 1)+ .collect();+ if self.panes != before {+ self.save_panes(cx);+ }+ }+/// Re-attaches a terminal whose connection dropped, a few times over about/// ten seconds. True while it's still trying.fn resume_terminal(&mut self, id: &str, window: &mut Window, cx: &mut Context<Self>) -> bool {@@ -325,9 +471,7 @@ impl Root {let machine_id = info.machine_id.clone();// Desktops: Linux (X11) machines so far.let desktop_capable = info.persistent && s.machines.iter().any(|m| m.id == info.machine_id && format::has_desktop(m) && !m.local);- let split = self.split.contains(&info.id);- let terminal = self.terminals.get(id).cloned();- let detached = terminal.as_ref().is_some_and(|t| t.read(cx).exited());+ let split = self.page_split(&info.id).is_some();let (icon_name, (from, to)) = kit::agent_look(&info.agent);let exited = info.status == "exited";@@ -396,6 +540,19 @@ impl Root {})),)})+ // Another shell beside it or below it, like splitting a terminal.+ .when(info.persistent && offline.is_none() && !self.engine.is_demo(), |d| {+ d.child(+ Button::icon_only("session-split-right", "columns-2")+ .tooltip("Split right (⌘D)")+ .on_click(cx.listener(|this, _, window, cx| this.split_session(false, window, cx))),+ )+ .child(+ Button::icon_only("session-split-down", "rows-2")+ .tooltip("Split down (⇧⌘D)")+ .on_click(cx.listener(|this, _, window, cx| this.split_session(true, window, cx))),+ )+ }).when(exited, |d| {d.child(Button::new("session-restart", "Restart")@@ -420,6 +577,96 @@ impl Root {}})));+ // The terminal, or the panes of its split.+ let body = match self.pane_layout(id).cloned() {+ Some(layout) => self.render_panes(&layout, id, window, cx),+ None => self.session_body(&info, window, cx).into_any_element(),+ };+ let body = div().relative().flex_1().min_w(px(0.)).min_h(px(0.)).flex().child(body);+ let panel = self.split_desktop(&info.id).map(|view| {+ let (pop, close) = (machine_id.clone(), info.id.clone());+ let to_sidebar = info.id.clone();+ let extra = vec![+ Button::icon_only("split-sidebar", "panel-left")+ .tooltip("Move to the sidebar")+ .on_click(cx.listener(move |this, _, window, cx| this.desktop_to_sidebar(&to_sidebar, window, cx)))+ .into_any_element(),+ Button::icon_only("split-window", "external-link")+ .tooltip("Open in a window")+ .on_click(cx.listener(move |this, _, window, cx| this.pop_out_desktop(&pop, window, cx)))+ .into_any_element(),+ Button::icon_only("split-close", "x")+ .tooltip("Hide the desktop")+ .on_click(cx.listener(move |this, _, window, cx| this.toggle_split(&close, window, cx)))+ .into_any_element(),+ ];+ div()+ .flex_1()+ .min_w(px(0.))+ .h_full()+ .flex()+ .flex_col()+ .child(super::desktop::toolbar(&view, extra, cx))+ .child(div().flex_1().min_h(px(0.)).child(view))+ });+ let body = match panel {+ Some(panel) => {+ // Terminal | divider (drag to resize, double-click for half and half) | desktop+ let resizing = self.split_resizing;+ let hover = theme.border;+ let divider = div()+ .id("split-divider")+ .group("split-divider")+ .flex_none()+ .w(px(6.))+ .h_full()+ .flex()+ .justify_center()+ .cursor_col_resize()+ .child(+ div()+ .w(px(if resizing { 2. } else { 1. }))+ .h_full()+ .when(resizing, |d| d.bg(theme.accent))+ .when(!resizing, |d| d.bg(theme.border_variant).group_hover("split-divider", |st| st.bg(hover).w(px(2.)))),+ )+ .on_drag(super::root::DraggedSplit, |_, _, _, cx| cx.new(|_| super::root::DraggedSplit))+ .on_click(cx.listener(|this, e: &gpui::ClickEvent, _, cx| {+ if e.click_count() == 2 {+ this.split_ratio = 0.5;+ this.finish_split_resize(cx);+ }+ }));+ div()+ .flex_1()+ .min_h(px(0.))+ .flex()+ .on_drag_move(cx.listener(Self::resize_split))+ .on_drop(cx.listener(|this, _: &super::root::DraggedSplit, _, cx| this.finish_split_resize(cx)))+ // The terminal pane was made to fill the page (flex_1: a zero basis);+ // in a split its basis is its share of the width.+ .child(body.flex_none().flex_basis(gpui::relative(self.split_ratio)).min_w(px(0.)))+ .child(divider)+ .child(panel)+ .into_any_element()+ }+ None => body.into_any_element(),+ };+ div().size_full().flex().flex_col().child(header).child(body).into_any_element()+ }++ /// A session's terminal, under what covers it while it can't be used+ /// (its machine offline, reconnecting, disconnected).+ fn session_body(&mut self, info: &SessionInfo, window: &mut Window, cx: &mut Context<Self>) -> gpui::Div {+ let theme = cx.theme();+ let s = self.snapshot.clone();+ if !self.terminals.contains_key(&info.id) && s.machines.iter().any(|m| m.id == info.machine_id && m.status != "offline") {+ self.open_terminal(&info.id, window, cx);+ }+ let offline = s.machines.iter().find(|m| m.id == info.machine_id && m.status == "offline").cloned();+ let terminal = self.terminals.get(&info.id).cloned();+ let detached = terminal.as_ref().is_some_and(|t| t.read(cx).exited());+ let exited = info.status == "exited";// Cut off while the machine is up (another network, a hiccup): attach// again by itself for a while before calling it disconnected.let resuming = if detached && !exited && info.persistent && offline.is_none() {@@ -431,7 +678,7 @@ impl Root {false};let sid3 = info.id.clone();- let body = div()+ div().relative().flex_1().min_h(px(0.))@@ -506,78 +753,71 @@ impl Root {),),)- });+ })+ }- let panel = self.split_desktop(&info.id).map(|view| {- let (pop, close) = (machine_id.clone(), info.id.clone());- let to_sidebar = info.id.clone();- let extra = vec![- Button::icon_only("split-sidebar", "panel-left")- .tooltip("Move to the sidebar")- .on_click(cx.listener(move |this, _, window, cx| this.desktop_to_sidebar(&to_sidebar, window, cx)))- .into_any_element(),- Button::icon_only("split-window", "external-link")- .tooltip("Open in a window")- .on_click(cx.listener(move |this, _, window, cx| this.pop_out_desktop(&pop, window, cx)))- .into_any_element(),- Button::icon_only("split-close", "x")- .tooltip("Hide the desktop")- .on_click(cx.listener(move |this, _, window, cx| this.toggle_split(&close, window, cx)))- .into_any_element(),- ];- div()- .flex_1()- .min_w(px(0.))- .h_full()- .flex()- .flex_col()- .child(super::desktop::toolbar(&view, extra, cx))- .child(div().flex_1().min_h(px(0.)).child(view))- });- let body = match panel {- Some(panel) => {- // Terminal | divider (drag to resize, double-click for half and half) | desktop- let resizing = self.split_resizing;- let hover = theme.border;- let divider = div()- .id("split-divider")- .group("split-divider")+ /// A layout of panes: each session's terminal under a slim title bar, the+ /// one keys go to outlined. A click picks a pane.+ fn render_panes(&mut self, layout: &Panes, focused: &str, window: &mut Window, cx: &mut Context<Self>) -> AnyElement {+ let theme = cx.theme();+ match layout {+ Panes::One(id) => {+ let Some(info) = self.snapshot.sessions.iter().find(|s| &s.id == id).cloned() else {+ return div().flex_1().into_any_element();+ };+ let on = id == focused;+ let body = self.session_body(&info, window, cx);+ let (pick, close) = (id.clone(), id.clone());+ let bar = div().flex_none()- .w(px(6.))- .h_full()+ .h(px(24.))+ .pl(px(10.))+ .pr(px(6.)).flex()- .justify_center()- .cursor_col_resize()+ .items_center()+ .gap(px(6.))+ .bg(if on { theme.element } else { theme.surface })+ .border_b_1()+ .border_color(theme.border_variant)+ .text_size(px(11.5))+ .text_color(if on { theme.text } else { theme.text_placeholder })+ .child(div().flex_1().min_w(px(0.)).overflow_hidden().whitespace_nowrap().child(info.title.clone())).child(div()- .w(px(if resizing { 2. } else { 1. }))- .h_full()- .when(resizing, |d| d.bg(theme.accent))- .when(!resizing, |d| d.bg(theme.border_variant).group_hover("split-divider", |st| st.bg(hover).w(px(2.)))),- )- .on_drag(super::root::DraggedSplit, |_, _, _, cx| cx.new(|_| super::root::DraggedSplit))- .on_click(cx.listener(|this, e: &gpui::ClickEvent, _, cx| {- if e.click_count() == 2 {- this.split_ratio = 0.5;- this.finish_split_resize(cx);- }- }));+ .id(SharedString::from(format!("pane-close-{id}")))+ .flex_none()+ .p(px(3.))+ .rounded(px(4.))+ .cursor_pointer()+ .hover(|st| st.bg(theme.ghost_hover))+ .tooltip(|window, cx| kit::Tooltip::view("Close the pane (the session keeps running)".into(), window, cx))+ .child(icon("x", 11., theme.text_placeholder))+ .on_click(cx.listener(move |this, _, window, cx| {+ cx.stop_propagation();+ this.close_pane(&close, window, cx)+ })),+ );div().flex_1()+ .min_w(px(0.)).min_h(px(0.)).flex()- .on_drag_move(cx.listener(Self::resize_split))- .on_drop(cx.listener(|this, _: &super::root::DraggedSplit, _, cx| this.finish_split_resize(cx)))- // The terminal pane was made to fill the page (flex_1: a zero basis);- // in a split its basis is its share of the width.- .child(body.flex_none().flex_basis(gpui::relative(self.split_ratio)).min_w(px(0.)))- .child(divider)- .child(panel)+ .flex_col()+ .border_1()+ .border_color(if on { theme.accent.opacity(0.55) } else { gpui::transparent_black() })+ .on_mouse_down(gpui::MouseButton::Left, cx.listener(move |this, _, window, cx| this.focus_pane(&pick, window, cx)))+ .child(bar)+ .child(body).into_any_element()}- None => body.into_any_element(),- };- div().size_full().flex().flex_col().child(header).child(body).into_any_element()+ Panes::Split { down, a, b } => {+ let (a, b) = (self.render_panes(a, focused, window, cx), self.render_panes(b, focused, window, cx));+ let line = div().flex_none().bg(theme.border_variant);+ let line = if *down { line.h(px(1.)).w_full() } else { line.w(px(1.)).h_full() };+ let half = |el: AnyElement| div().flex_1().min_w(px(0.)).min_h(px(0.)).flex().child(el);+ div().flex_1().min_w(px(0.)).min_h(px(0.)).flex().when(*down, |d| d.flex_col()).child(half(a)).child(line).child(half(b)).into_any_element()+ }+ }}// -----------------------------------------------------------------------@@ -998,13 +1238,6 @@ impl Root {move |this, _, window, cx| this.setup_tailscale(&mid, window, cx)})))})- // Seeing the desktop: Linux (X11) and Macs.- .when(format::has_desktop(m), |d| {- d.child(Button::new("m-desktop", "Show desktop").icon("monitor").on_click(cx.listener({- let mid = mid.clone();- move |this, _, window, cx| this.navigate(Route::Desktop(mid.clone()), window, cx)- })))- }).child(button),).into_any_element()diff --git a/src/ui/shortcuts.rs b/src/ui/shortcuts.rsindex 0e861f7..2269ef2 100644--- a/src/ui/shortcuts.rs+++ b/src/ui/shortcuts.rs@@ -6,8 +6,8 @@ use gpui::{App, KeyBinding, Keystroke};use super::root::{AddMachine, CheckNow, CommandPalette, FocusFilter, GoBack, GoForward, GoToMachine1, GoToMachine2, GoToMachine3, GoToMachine4, GoToMachine5, GoToMachine6,- GoToMachine7, GoToMachine8, GoToMachine9, NewSession, OpenSettings, ShowGithub, ShowJobs, ShowOverview, ShowWorkspaces, SyncGitHub,- QuickOpen, ToggleActivity, ToggleSidebar,+ GoToMachine7, GoToMachine8, GoToMachine9, NewSession, NextPane, OpenSettings, PreviousPane, ShowGithub, ShowJobs, ShowOverview, ShowWorkspaces,+ SplitDown, SplitRight, SyncGitHub, QuickOpen, ToggleActivity, ToggleSidebar,};use super::theme::Appearance;@@ -46,6 +46,10 @@ pub const ALL: &[Shortcut] = &[shortcut!("sync", "Sync GitHub", "secondary-shift-r", SyncGitHub),shortcut!("add-machine", "Add machine", "secondary-n", AddMachine),shortcut!("new-session", "New session", "secondary-t", NewSession),+ shortcut!("split-right", "Split the terminal right", "secondary-d", SplitRight),+ shortcut!("split-down", "Split the terminal down", "secondary-shift-d", SplitDown),+ shortcut!("next-pane", "Next pane", "secondary-alt-right", NextPane),+ shortcut!("previous-pane", "Previous pane", "secondary-alt-left", PreviousPane),shortcut!("filter", "Search machines and sessions", "secondary-f", FocusFilter),shortcut!("sidebar", "Hide or show the sidebar", "secondary-b", ToggleSidebar),shortcut!("back", "Back", "secondary-[", GoBack),diff --git a/src/ui/terminal/render.rs b/src/ui/terminal/render.rsindex 0739fd2..58bbc95 100644--- a/src/ui/terminal/render.rs+++ b/src/ui/terminal/render.rs@@ -103,6 +103,8 @@ fn base_font(window: &Window) -> Font {FALLBACKS.iter().find(|f| has(f)).map(|f| SharedString::from(*f)).unwrap_or_else(|| mono_font().into())};let mut font = gpui::font(family);+ // Icons the font lacks (Nerd Font glyphs): from the bundled symbols font.+ font.fallbacks = Some(gpui::FontFallbacks::from_fonts(crate::ui::assets::NERD_SYMBOLS_NAMES.iter().map(|n| n.to_string()).collect()));// Ligatures would merge cells and break the grid.font.features = FontFeatures(Arc::new(vec![("calt".into(), 0), ("liga".into(), 0)]));fontdiff --git a/src/ui/theme.rs b/src/ui/theme.rsindex 7c076ae..491752e 100644--- a/src/ui/theme.rs+++ b/src/ui/theme.rs@@ -141,6 +141,8 @@ pub struct Appearance {pub split_ratio: f32,/// Machines whose desktop is an item in the sidebar.pub desktops: Vec<String>,+ /// Terminals split into panes, each layout as text (see panes.rs).+ pub panes: Vec<String>,/// Favorite machines: first in the sidebar (so ⌘1, ⌘2, …), with a star.pub favorite_machines: Vec<String>,/// How icons look (see kit::IconStyle): "minimal", "tiles", "soft", ...@@ -168,6 +170,7 @@ impl Default for Appearance {github_folded_owners: Vec::new(),split_ratio: 0.5,desktops: Vec::new(),+ panes: Vec::new(),favorite_machines: Vec::new(),icon_style: super::kit::IconStyle::default().id().into(),shortcuts: Default::default(),