Your own team of AI bots in one self-hosted binary: spaces, every account you have, handoffs, approvals and routines. Open-source, self-hosted alternative to Grok Bot, Claude Duet and OpenAI dots. Rust + React.
Rust ai-agentsai-assistantai-botautomationbotbots-teamchatbotclaude-duetgrokgrok-botgrok-bot-alternativeharnessllmmulti-agentopenai-dotsopenbotpersonal-agentrustself-hostedselfhosted-ai
Desktop: place picker and switch in place (0.9.13) (#650)
Oleksandr Ivanchenkof9766b9551bf
diff --git a/apps/mac/loading/pixelify-sans.woff2 b/apps/mac/loading/pixelify-sans.woff2new file mode 100644index 00000000..1fa11166Binary files /dev/null and b/apps/mac/loading/pixelify-sans.woff2 differdiff --git a/apps/mac/loading/places.html b/apps/mac/loading/places.htmlnew file mode 100644index 00000000..69a86415--- /dev/null+++ b/apps/mac/loading/places.html@@ -0,0 +1,233 @@+<!doctype html>+<!-- The place picker (design: /home/maus/shared/ship-software-safely/autonomy/desktop-island/design.md 9.2,+ mockups/src/places.css). A bundled page in its own small window ("places"), with no command+ capability. Rust gives it the rows with window.eval("kwantPlaces.show({...})"); it answers only by+ navigating to kwant-places://… (ready, switch?i=N&side=0|1, add, run-here, close, size?h=N), which+ on_navigation catches and refuses (src/picker.rs, rules in src/switcher.rs). A row is named by its+ index in the rows Rust gave, never by a name or an address. Every name and status goes in with+ textContent; only our own glyphs and icons are built as SVG elements. -->+<html><head><meta charset="utf-8"><meta name="color-scheme" content="dark">+<title>Places</title>+<style>+@font-face { font-family: "Pixelify Sans"; src: url("pixelify-sans.woff2") format("woff2"); font-weight: 400 700; font-display: block; }+html, body { margin: 0; background: transparent; overflow: hidden; user-select: none; -webkit-user-select: none; cursor: default; }+/* 16 px of transparent margin around the card for its shadow (switcher.rs PICKER_MARGIN) */+#root { padding: 16px; width: 300px; }+.kw-picker { box-sizing: border-box; width: 300px; padding: 6px; border-radius: 12px; background: #1a1538;+ box-shadow: inset 0 0 0 1px rgb(255 255 255 / .10), 0 18px 48px rgb(0 0 0 / .55), 0 2px 6px rgb(0 0 0 / .4);+ color: #f7f6ff; font: 400 13px/16px -apple-system, BlinkMacSystemFont, "SF Pro Text", "Segoe UI", Inter, Roboto, sans-serif;+ animation: kw-pick-in 120ms cubic-bezier(.2, .8, .2, 1) backwards; }+@keyframes kw-pick-in { from { opacity: 0; transform: translateY(-4px); } }+@media (prefers-reduced-motion: reduce) { .kw-picker { animation: none; } }+.kw-picker h1 { margin: 4px 8px 6px; font: 500 12px/20px "Pixelify Sans", monospace; letter-spacing: .06em; text-transform: uppercase; color: #bcb7de; }+.kw-pick { display: grid; grid-template-columns: 28px minmax(0, 1fr) auto 18px; align-items: center; column-gap: 10px; height: 44px; padding: 0 8px; border-radius: 8px; cursor: pointer; outline: none; }+.kw-pick.is-sel { background: #231d4b; box-shadow: inset 0 0 0 1px rgb(184 173 255 / .45); }+.kw-pick .tile { width: 28px; height: 28px; border-radius: 7px; background: #231d4b; display: grid; place-items: center; color: #b8adff; }+.kw-pick.is-sel .tile { background: #2c2552; }+.kw-pick .tile .glyph { width: 14px; height: 14px; }+.kw-pick .tx { min-width: 0; }+.kw-pick .nm { display: block; font-weight: 600; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }+.kw-pick .sub { display: block; font-size: 12px; color: #9a94c4; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }+.kw-pick .sub.bad { color: #fda4af; }+.kw-pick .n { min-width: 20px; height: 20px; padding: 0 5px; box-sizing: border-box; border-radius: 5px; background: #ffb020; color: #1b1033; font: 700 12px/20px -apple-system, "Segoe UI", Inter, sans-serif; text-align: center; font-variant-numeric: tabular-nums; }+.kw-pick .cur { color: #b8adff; display: inline-flex; } .kw-pick .cur svg { width: 16px; height: 16px; }+.kw-pick kbd { width: 18px; height: 18px; border-radius: 4px; box-shadow: inset 0 0 0 1px rgb(255 255 255 / .14); color: #9a94c4; font: 500 11px/18px -apple-system, "Segoe UI", Inter, sans-serif; text-align: center; }+.kw-pick.act { grid-template-columns: 28px 1fr; height: 40px; color: #d9d6f0; }+.kw-pick.act .nm { font-weight: 500; }+.kw-pick.act .tile { background: transparent; box-shadow: inset 0 0 0 1px rgb(255 255 255 / .14); color: #bcb7de; }+.kw-pick.act .tile svg { width: 15px; height: 15px; }+.kw-picker hr { border: 0; height: 1px; background: rgb(255 255 255 / .07); margin: 6px 4px; }+.kw-picker .hint { display: flex; gap: 12px; padding: 6px 8px 2px; font-size: 11px; line-height: 17px; color: #9a94c4; }+.kw-picker .hint kbd { font: inherit; color: #bcb7de; }+</style></head>+<body>+<div id="root"><div class="kw-picker" role="dialog" aria-label="Places">+ <h1>Places</h1>+ <div id="rows" role="listbox" aria-label="Places"></div>+ <hr>+ <div id="acts"></div>+ <div class="hint"><span><kbd>↑↓</kbd> move</span><span><kbd>↩</kbd> switch</span><span><kbd id="side-key">⌥↩</kbd> open side by side</span></div>+</div></div>+<script>+(function () {+ 'use strict';+ var SVG = 'http://www.w3.org/2000/svg';+ // 7x7 pixel glyphs (mockups/src/perch.js)+ var GLYPHS = {+ mac: ['.......', '.#####.', '.#...#.', '.#...#.', '.#####.', '#######', '.......'],+ server: ['.#####.', '.#..#..', '.#####.', '.......', '.#####.', '.#..#..', '.#####.']+ };+ var ICONS = { check: 'M20 6 9 17l-5-5', plus: 'M12 5v14M5 12h14', play: 'M8 5.5v13l10-6.5z' };++ function glyph(kind) {+ var svg = document.createElementNS(SVG, 'svg');+ svg.setAttribute('class', 'glyph');+ svg.setAttribute('viewBox', '0 0 7 7');+ svg.setAttribute('shape-rendering', 'crispEdges');+ svg.setAttribute('aria-hidden', 'true');+ (GLYPHS[kind] || GLYPHS.server).forEach(function (line, y) {+ for (var x = 0; x < line.length; x++) {+ if (line[x] !== '#') continue;+ var r = document.createElementNS(SVG, 'rect');+ r.setAttribute('x', x); r.setAttribute('y', y); r.setAttribute('width', 1); r.setAttribute('height', 1);+ r.setAttribute('fill', 'currentColor');+ svg.appendChild(r);+ }+ });+ return svg;+ }+ function icon(name) {+ var svg = document.createElementNS(SVG, 'svg');+ svg.setAttribute('viewBox', '0 0 24 24');+ svg.setAttribute('fill', 'none');+ svg.setAttribute('stroke', 'currentColor');+ svg.setAttribute('stroke-width', '2.25');+ svg.setAttribute('stroke-linecap', 'round');+ svg.setAttribute('stroke-linejoin', 'round');+ svg.setAttribute('aria-hidden', 'true');+ var p = document.createElementNS(SVG, 'path');+ p.setAttribute('d', ICONS[name] || ICONS.plus);+ svg.appendChild(p);+ return svg;+ }+ function el(tag, cls, text) {+ var e = document.createElement(tag);+ if (cls) e.className = cls;+ if (text != null) e.textContent = String(text);+ return e;+ }+ // a long host is cut in the middle (design.md 9.2: at 30), then tighter until it fits its column+ // (design-check-switcher F3: the end of a host is what tells two servers apart, so CSS must never+ // add an end ellipsis). Same loop as PlaceChipRow; it stops at 12.+ function midcut(s, max) {+ var a = Array.from(s);+ if (a.length <= max) return s;+ var keep = max - 1, h = Math.ceil(keep / 2);+ return a.slice(0, h).join('') + '…' + a.slice(a.length - (keep - h)).join('');+ }+ function fitHost(nm, name) {+ var cut = Math.min(30, Array.from(name).length);+ nm.textContent = midcut(name, cut);+ while (nm.scrollWidth > nm.clientWidth && cut > 12) {+ cut -= 1;+ nm.textContent = midcut(name, cut);+ }+ }++ // One navigation at a time: two in the same moment may lose the first.+ var queue = [], busy = false;+ function send(what) {+ queue.push(what);+ if (!busy) pump();+ }+ function pump() {+ var next = queue.shift();+ if (next === undefined) { busy = false; return; }+ busy = true;+ location.href = 'kwant-places://' + next;+ setTimeout(pump, 40);+ }++ var items = []; // [{el, go(side)}]: the rows, then the actions+ var nRows = 0, sel = 0;+ var shown = 0; // which show() a pending fit belongs to++ function select(i) {+ if (!items.length) return;+ sel = Math.max(0, Math.min(items.length - 1, i));+ items.forEach(function (it, j) {+ it.el.classList.toggle('is-sel', j === sel);+ if (it.row) it.el.setAttribute('aria-selected', j === sel ? 'true' : 'false');+ });+ }++ function show(data) {+ data = data || {};+ var rows = Array.isArray(data.rows) ? data.rows : [];+ var acts = Array.isArray(data.actions) ? data.actions : [];+ document.getElementById('side-key').textContent = data.mac ? '⌥↩' : 'Alt+↩';+ var list = document.getElementById('rows'), actList = document.getElementById('acts');+ list.replaceChildren(); actList.replaceChildren();+ items = [];+ nRows = rows.length;+ var current = -1;+ var hosts = []; // [{nm, name}] server names to fit once the font is in+ rows.forEach(function (r, i) {+ var row = el('div', 'kw-pick');+ row.setAttribute('role', 'option');+ var tile = el('span', 'tile'); tile.appendChild(glyph(r.kind === 'mac' ? 'mac' : 'server'));+ var tx = el('span', 'tx');+ var name = String(r.name || '');+ var nm = el('span', 'nm', r.kind === 'server' ? midcut(name, 30) : name);+ if (r.kind === 'server') {+ nm.title = name;+ hosts.push({ nm: nm, name: name });+ }+ tx.appendChild(nm);+ tx.appendChild(el('span', 'sub' + (r.bad ? ' bad' : ''), r.sub || ''));+ var n = Math.max(0, Math.floor(Number(r.n) || 0));+ var right;+ if (n > 0) {+ right = el('span', 'n', n > 9 ? '9+' : String(n));+ right.setAttribute('aria-label', n + ' waiting');+ } else if (r.cur) {+ right = el('span', 'cur'); right.appendChild(icon('check'));+ right.setAttribute('aria-label', 'You are here');+ } else {+ right = el('span');+ }+ // F10, and Rigel's fix 3 for This Mac rows: every row's label replaces its whole name, so it+ // carries the status, count and ✓ too, and never the keycap digit. The status is often the+ // count already ("2 waiting"): then it is said once. "You are here" is said even when the+ // count takes the ✓'s place.+ var sub = String(r.sub || ''), count = n > 0 ? n + ' waiting' : '';+ row.setAttribute('aria-label', [name, sub, count === sub ? '' : count, r.cur ? 'You are here' : ''].filter(Boolean).join(', '));+ if (r.cur) current = i;+ row.append(tile, tx, right, el('kbd', '', i < 9 ? i + 1 : ''));+ var go = function (side) { send('switch?i=' + i + '&side=' + (side ? 1 : 0)); };+ items.push({ el: row, go: go, row: true });+ list.appendChild(row);+ });+ acts.forEach(function (a) {+ var id = a.id === 'run-here' ? 'run-here' : 'add';+ var row = el('div', 'kw-pick act');+ row.setAttribute('role', 'button');+ var tile = el('span', 'tile'); tile.appendChild(icon(a.icon === 'play' ? 'play' : 'plus'));+ row.append(tile, el('span', 'nm', a.label || ''));+ items.push({ el: row, go: function () { send(id); } });+ actList.appendChild(row);+ });+ items.forEach(function (it, j) {+ it.el.addEventListener('mousemove', function () { if (sel !== j) select(j); });+ it.el.addEventListener('click', function (e) { it.go(e.altKey); });+ });+ // Enter goes to the next place by default, like switching apps+ select(nRows > 1 ? (current === 0 ? 1 : 0) : 0);+ var me = ++shown;+ var fonts = document.fonts && document.fonts.ready ? document.fonts.ready : Promise.resolve();+ fonts.then(function () {+ requestAnimationFrame(function () {+ if (me !== shown) return; // a newer show() fits its own rows+ hosts.forEach(function (x) { fitHost(x.nm, x.name); });+ var h = Math.ceil(document.querySelector('.kw-picker').getBoundingClientRect().height);+ send('size?h=' + Math.min(9999, h));+ });+ });+ }++ document.addEventListener('keydown', function (e) {+ if (e.key === 'Escape') { e.preventDefault(); send('close'); return; }+ if (e.key === 'ArrowDown') { e.preventDefault(); select(sel + 1); return; }+ if (e.key === 'ArrowUp') { e.preventDefault(); select(sel - 1); return; }+ if (e.key === 'Enter') { e.preventDefault(); if (items[sel]) items[sel].go(e.altKey); return; }+ if (!e.metaKey && !e.ctrlKey && /^Digit[1-9]$/.test(e.code)) {+ var i = Number(e.code.slice(5)) - 1;+ if (i < nRows) { e.preventDefault(); items[i].go(e.altKey); }+ }+ });++ window.kwantPlaces = { show: show };+ send('ready');+})();+</script>+</body></html>diff --git a/apps/mac/src/main.rs b/apps/mac/src/main.rsindex 9458c025..de716d74 100644--- a/apps/mac/src/main.rs+++ b/apps/mac/src/main.rs@@ -17,10 +17,12 @@ mod nudge_linux;mod nudge_mac;#[cfg(windows)]mod nudge_windows;+mod picker;mod places;mod redact;mod remote;mod startup;+mod switcher;mod target;mod update;@@ -242,6 +244,14 @@ struct Shared {last_focused: Mutex<Option<String>>,/// Wakes the menu's poll after a change.wake: Mutex<Option<mpsc::Sender<()>>>,+ /// What the menu's last poll said of each place (by key), for the place picker.+ status: Mutex<HashMap<String, menu::Status>>,+ /// What waits in the places other than This Mac, as This Mac's page was told last.+ elsewhere: Mutex<Option<usize>>,+ /// The place picker's rows and state (`picker.rs`).+ picker: Mutex<picker::PickerState>,+ /// The pages' picker asks, at most one a second per window.+ asks: Mutex<switcher::RateLimit>,}impl Shared {@@ -259,6 +269,10 @@ impl Shared {unreachable: Mutex::new(Default::default()),last_focused: Mutex::new(None),wake: Mutex::new(None),+ status: Mutex::new(HashMap::new()),+ elsewhere: Mutex::new(None),+ picker: Mutex::new(picker::PickerState::default()),+ asks: Mutex::new(switcher::RateLimit::default()),}}}@@ -365,6 +379,10 @@ fn main() {WindowEvent::Focused(true) if is_place_window(window.label()) => {*window.state::<Shared>().last_focused.lock().unwrap() = Some(window.label().to_string());}+ // a click outside the place picker closes it+ WindowEvent::Focused(false) if window.label() == switcher::PICKER_WINDOW => {+ picker::blurred(window.app_handle());+ }_ => {}}).build(tauri::generate_context!())@@ -696,6 +714,11 @@ fn save_open<R: Runtime>(app: &AppHandle<R>) {/// What a link in a place's window does (`popup`: it asked for a new window). A link to another/// place opens that place's window; a page off every place goes to the browser.fn route<R: Runtime>(app: &AppHandle<R>, me: &Place, url: &Url, popup: bool) -> bool {+ // the place chip (and Ctrl+Shift+O) asking for the place picker: handled, never loaded+ if url.scheme() == "kwant-app" {+ picker::on_app_url(app, &me.window_label(), url);+ return false;+ }// port 0 never matches a link: This Mac's window before its kwant runslet mine = home(app, me).unwrap_or(Home::Local { port: 0 });let others: Vec<(Place, Home)> = current(app)@@ -732,7 +755,11 @@ fn make_window<R: Runtime>(app: &AppHandle<R>, place: &Place, goto: Goto, visibllet title = places::window_title(place, ¤t(app));let (nav_app, nav_place) = (app.clone(), place.clone());let (pop_app, pop_place) = (app.clone(), place.clone());- let window = match WebviewWindowBuilder::new(app, place.window_label(), WebviewUrl::App("index.html".into()))+ let builder = WebviewWindowBuilder::new(app, place.window_label(), WebviewUrl::App("index.html".into()));+ // Ctrl+Shift+O opens the place picker (macOS has the Window menu's ⌘⇧O)+ #[cfg(not(target_os = "macos"))]+ let builder = builder.initialization_script(switcher::SHORTCUT_SCRIPT);+ let window = match builder.title(title).visible(visible).inner_size(1280.0, 820.0)@@ -750,6 +777,8 @@ fn make_window<R: Runtime>(app: &AppHandle<R>, place: &Place, goto: Goto, visiblroute(&pop_app, &pop_place, &url, true);NewWindowResponse::Deny})+ // This Mac's page learns what waits elsewhere (no other window does)+ .on_page_load(|window, payload| picker::page_loaded(&window, payload.url(), payload.event())).build(){Ok(w) => w,@@ -1175,6 +1204,7 @@ fn set_window_menu(app: &AppHandle, places: &[Place]) {let bar = Menu::default(app)?;if let Some(window) = bar.get(tauri::menu::WINDOW_SUBMENU_ID).and_then(|k| k.as_submenu().cloned()) {window.append(&PredefinedMenuItem::separator(app)?)?;+ window.append(&MenuItem::with_id(app, "switch_place", "Switch place…", true, Some("CmdOrCtrl+Shift+O"))?)?;for (i, place) in places.iter().enumerate() {let accel = (i < 9).then(|| format!("CmdOrCtrl+{}", i + 1));let text = match place {@@ -1195,7 +1225,11 @@ fn set_window_menu(app: &AppHandle, places: &[Place]) {/// Every menu click: the tray's and the Window menu's.fn on_menu(app: &AppHandle, id: &str) {match id {- "open" => open_place(app, &Place::ThisMac, Goto::Stay),+ "open" => picker::switch_from_last(app, &Place::ThisMac),+ "switch_place" => {+ let (app, from) = (app.clone(), picker::last_place_window(app));+ std::thread::spawn(move || picker::open(&app, from, None));+ }"update" => {// The window shows the download and the relaunchif let Err(e) = kwnt::app_update::UpdateHub::shared().install() {@@ -1226,8 +1260,9 @@ fn on_menu(app: &AppHandle, id: &str) {}_ => {if let Some(key) = id.strip_prefix("place:").or_else(|| id.strip_prefix("win:")) {+ // the tray's rows and ⌘1/⌘2 switch in placeif let Some(place) = place_by_key(app, key) {- open_place(app, &place, Goto::Stay);+ picker::switch_from_last(app, &place);}} else if let Some(origin) = id.strip_prefix("remove:") {confirm_remove(app, origin);@@ -1339,6 +1374,9 @@ fn build_tray(handle: &AppHandle) -> tauri::Result<()> {menu::Status::Connecting})};+ *shared.status.lock().unwrap() = status.clone();+ let counts: Vec<(bool, usize)> = all.iter().map(|p| (*p == Place::ThisMac, status_of(p).count())).collect();+ picker::set_elsewhere(&app, switcher::waiting_elsewhere(&counts));*shared.unreachable.lock().unwrap() = all.iter().filter(|p| status_of(p) == menu::Status::Unreachable)@@ -1754,6 +1792,82 @@ mod tests {let _ = std::fs::remove_dir_all(data_dir);}+ /// The place picker is a bundled page in its own window (`places`), which no capability+ /// lists: it reaches Rust only through `kwant-places://` navigations, never a command.+ #[test]+ fn the_place_picker_can_call_no_command() {+ let (_app, window, data_dir) = app_with("picker-window", switcher::PICKER_WINDOW, Places::default());+ for from in ["tauri://localhost/places.html", "http://tauri.localhost/places.html"] {+ for cmd in COMMANDS {+ let refused = invoke(&window, cmd, from, args());+ assert!(matches!(&refused, Err(serde_json::Value::String(_))), "{cmd} from {from}: {refused:?}");+ }+ }+ nothing_saved(&data_dir);+ let _ = std::fs::remove_dir_all(data_dir);+ }++ fn server_place() -> (Places, Place) {+ let origin = target::parse_address("kwant.example.com").unwrap().origin;+ let mut places = Places::default();+ places.add_server(origin.clone());+ (places, Place::Server(origin))+ }++ /// A server's page may open the picker (it shows only our own page), but at most once a+ /// second, and the address is never loaded. An unknown kwant-app ask is refused and doesn't+ /// use up the second.+ #[test]+ fn a_page_opens_the_picker_at_most_once_a_second_and_never_loads_the_address() {+ let (places, server) = server_place();+ let label = server.window_label();+ let (app, _window, data_dir) = app_with("picker-asks", &label, places);+ let handle = app.handle();+ let island: Url = "kwant-app://island?mode=off&shortcut=off".parse().unwrap();+ assert!(!route(handle, &server, &island, false), "never loaded");+ assert_eq!(picker::on_app_url(handle, &label, &island), None, "not a picker ask");+ let ask: Url = "kwant-app://places?at=76,44".parse().unwrap();+ assert_eq!(+ picker::on_app_url(handle, &label, &ask),+ Some(switcher::AppAsk::Places { at: Some((76.0, 44.0)) }),+ "the first ask opens it"+ );+ for _ in 0..50 {+ assert_eq!(picker::on_app_url(handle, &label, &ask), None, "again within a second: ignored");+ assert!(!route(handle, &server, &ask, false), "and never loaded");+ assert!(!route(handle, &server, &ask, true), "nor as a popup");+ }+ assert!(picker::on_app_url(handle, MAIN, &ask).is_some(), "another window has its own second");+ nothing_saved(&data_dir);+ let _ = std::fs::remove_dir_all(data_dir);+ }++ /// Only This Mac's window showing This Mac's kwant learns what waits elsewhere; a server's+ /// window, the picker and This Mac's loading page never do.+ #[test]+ fn only_this_mac_s_page_hears_what_waits_elsewhere() {+ let (places, server) = server_place();+ let (app, _window, data_dir) = app_with("elsewhere", MAIN, places);+ let handle = app.handle();+ *handle.state::<Shared>().elsewhere.lock().unwrap() = Some(3);+ let local: Url = "http://127.0.0.1:1/spaces/spc_default".parse().unwrap();+ let remote: Url = "https://kwant.example.com/".parse().unwrap();+ let loading: Url = "tauri://localhost/index.html".parse().unwrap();+ let js = picker::elsewhere_for(handle, MAIN, &local).expect("This Mac's page");+ assert!(js.contains("__KWANT_ELSEWHERE__=3"), "{js}");+ for (label, url) in [+ (server.window_label(), &remote),+ (server.window_label(), &local),+ (switcher::PICKER_WINDOW.to_string(), &local),+ (CONNECT.to_string(), &local),+ (MAIN.to_string(), &remote),+ (MAIN.to_string(), &loading),+ ] {+ assert_eq!(picker::elsewhere_for(handle, &label, url), None, "{label} at {url}");+ }+ let _ = std::fs::remove_dir_all(data_dir);+ }+/// Rigel's F7: Tauri's access check compares only the scheme and the host, so a page at the/// bundled host with a port or a user name gets past it. The command's own check then/// refuses it, and nothing is saved.diff --git a/apps/mac/src/picker.rs b/apps/mac/src/picker.rsnew file mode 100644index 00000000..0c0bade7--- /dev/null+++ b/apps/mac/src/picker.rs@@ -0,0 +1,393 @@+//! The place picker (bundled `loading/places.html`, design.md 9.2) and switching in place+//! (desktop-island/build-brief.md, Part 1). The rules are in `switcher.rs`; this is the Tauri+//! side.+//!+//! - A place's page asks for the picker with `kwant-app://places?at=x,y` (`route` hands it here):+//! at most once a second per window, x,y clamped to the window, never loaded.+//! - The picker page talks back only with `kwant-places://…` navigations, naming a row by its+//! index in the rows Rust gave it. It has no command capability (its label is in no+//! capability file).+//! - Switching moves the target into the window you were in (its frame, maximized and+//! full-screen state) and hides the one you left, which stays connected. ⌥↩ opens side by side.+//! - Only This Mac's window, showing This Mac's kwant, learns how much waits elsewhere.++use crate::places::{self, Place};+use crate::switcher::{self, AppAsk, PickerAsk, Plan, Rect};+use crate::{current, is_place_window, menu, open_place, set_local, show, show_connect, wake, Goto, Shared, MAIN};+use std::time::{Duration, Instant};+use tauri::webview::{NewWindowResponse, PageLoadEvent};+use tauri::{AppHandle, LogicalSize, Manager, Runtime, Url, WebviewUrl, WebviewWindow, WebviewWindowBuilder};++/// A focus change this soon after the picker showed doesn't close it (showing it moves focus).+const BLUR_GRACE: Duration = Duration::from_millis(300);++/// What the picker shows now.+#[derive(Default)]+pub struct PickerState {+ /// The window it was opened from: the "from" of a switch.+ from: Option<String>,+ /// The rows as given to the page, in the page's order.+ rows: Vec<Place>,+ /// The page has loaded and said `ready`.+ ready: bool,+ /// Rows waiting for `ready`.+ pending: Option<String>,+ /// When it last showed; `None` while hidden.+ shown_at: Option<Instant>,+}++/// A place's page navigated to `kwant-app://…` (never loaded). `label`: that page's window.+/// Returns what was accepted (`None`: unknown, or asked again within a second).+pub fn on_app_url<R: Runtime>(app: &AppHandle<R>, label: &str, url: &Url) -> Option<AppAsk> {+ let Some(ask) = switcher::parse_app(url.as_str()) else {+ tracing::info!("ignored a kwant-app address the app doesn't know");+ return None;+ };+ if !app.state::<Shared>().asks.lock().unwrap().allow(label, Instant::now(), switcher::ASK_EVERY) {+ tracing::debug!(window = label, "ignored a second picker ask within a second");+ return None;+ }+ match &ask {+ AppAsk::Places { at } => {+ let (app, label, at) = (app.clone(), label.to_string(), *at);+ // never build or show a window inside the webview's own callback+ std::thread::spawn(move || open(&app, Some(label), at));+ }+ }+ Some(ask)+}++/// The window the person is in: the one that had the keyboard last, while it shows.+pub fn last_place_window<R: Runtime>(app: &AppHandle<R>) -> Option<String> {+ let last = app.state::<Shared>().last_focused.lock().unwrap().clone();+ last.filter(|l| shows(app, l))+}++fn shows<R: Runtime>(app: &AppHandle<R>, label: &str) -> bool {+ is_place_window(label) && app.get_webview_window(label).and_then(|w| w.is_visible().ok()).unwrap_or(false)+}++/// The picker's rows and the page's JSON for them.+fn rows<R: Runtime>(app: &AppHandle<R>, from: Option<&str>) -> (Vec<Place>, usize, String) {+ let saved = current(app);+ let status = app.state::<Shared>().status.lock().unwrap().clone();+ let all = saved.all();+ let keys: Vec<String> = all.iter().map(Place::key).collect();+ let here = from.and_then(|l| saved.by_window(l)).map(|p| p.key());+ let mut shown: Vec<Place> = switcher::row_order(&keys, here.as_deref()).into_iter().map(|i| all[i].clone()).collect();+ let mut json: Vec<serde_json::Value> = shown+ .iter()+ .map(|p| {+ let said = status.get(&p.key()).copied().unwrap_or(if *p == Place::ThisMac {+ menu::Status::Starting+ } else {+ menu::Status::Connecting+ });+ let (kind, name) = match p {+ Place::ThisMac => ("mac", places::THIS_MAC_LABEL.to_string()),+ Place::Server(o) => ("server", o.host()),+ };+ serde_json::json!({+ "kind": kind,+ "name": name,+ "sub": said.text(),+ "bad": matches!(said, menu::Status::Unreachable | menu::Status::DidntStart),+ "n": said.count(),+ "cur": here.as_deref() == Some(p.key().as_str()),+ })+ })+ .collect();+ // This Mac's kwant off: its row says so, and picking it starts it (mockup rowsB)+ if !saved.this_mac {+ shown.push(Place::ThisMac);+ json.push(serde_json::json!({ "kind": "mac", "name": places::THIS_MAC_LABEL, "sub": "Not running", "bad": false, "n": 0, "cur": false }));+ }+ let mut actions = vec![serde_json::json!({ "id": "add", "label": "Add a server…", "icon": "plus" })];+ if !saved.this_mac {+ actions.push(serde_json::json!({ "id": "run-here", "label": places::RUN_HERE, "icon": "play" }));+ }+ let n_actions = actions.len();+ let page = serde_json::json!({ "rows": json, "actions": actions, "mac": cfg!(target_os = "macos") });+ (shown, n_actions, page.to_string())+}++/// Opens the picker: under the chip (`at`, in `from`'s CSS px), at `from`'s top centre without+/// one, or at the top centre of the screen when no place's window shows.+pub fn open<R: Runtime>(app: &AppHandle<R>, from: Option<String>, at: Option<(f64, f64)>) {+ let from = from.filter(|l| shows(app, l));+ let (rows, n_actions, page) = rows(app, from.as_deref());+ let Some(picker) = window(app) else {+ return;+ };+ let height = switcher::picker_height(switcher::card_height(rows.len(), n_actions));+ let spot = from.as_deref().and_then(|l| app.get_webview_window(l)).and_then(|w| frame_of(&w, at));+ let spot = spot.or_else(|| screen_of(&picker).map(|s| (s, None, picker.scale_factor().unwrap_or(1.0), s)));+ let ready = {+ let shared = app.state::<Shared>();+ let mut state = shared.picker.lock().unwrap();+ state.from = from;+ state.rows = rows;+ state.shown_at = Some(Instant::now());+ state.pending = (!state.ready).then(|| page.clone());+ state.ready+ };+ let _ = picker.set_size(LogicalSize::new(switcher::PICKER_W + 2.0 * switcher::PICKER_MARGIN, height));+ if let Some((window, at, scale, screen)) = spot {+ let (x, y) = switcher::picker_spot(window, at, scale, height, screen);+ let _ = picker.set_position(tauri::PhysicalPosition::new(x as i32, y as i32));+ }+ if ready {+ let _ = picker.eval(format!("window.kwantPlaces&&kwantPlaces.show({page})"));+ }+ show(&picker);+}++/// The asking window's content area, the chip's point clamped into it, its scale and its screen.+fn frame_of<R: Runtime>(w: &WebviewWindow<R>, at: Option<(f64, f64)>) -> Option<(Rect, Option<(f64, f64)>, f64, Rect)> {+ let pos = w.inner_position().ok()?;+ let size = w.inner_size().ok()?;+ let scale = w.scale_factor().unwrap_or(1.0);+ let window = Rect { x: pos.x as f64, y: pos.y as f64, w: size.width as f64, h: size.height as f64 };+ let css = (window.w / scale, window.h / scale);+ let screen = screen_of(w).unwrap_or(window);+ Some((window, at.map(|a| switcher::clamp_at(a, css)), scale, screen))+}++/// The work area (without the menu bar and the Dock or taskbar) of a window's screen.+fn screen_of<R: Runtime>(w: &WebviewWindow<R>) -> Option<Rect> {+ let monitor = w.current_monitor().ok().flatten().or_else(|| w.primary_monitor().ok().flatten())?;+ let area = monitor.work_area();+ Some(Rect {+ x: area.position.x as f64,+ y: area.position.y as f64,+ w: area.size.width as f64,+ h: area.size.height as f64,+ })+}++/// The picker's window (made hidden the first time).+fn window<R: Runtime>(app: &AppHandle<R>) -> Option<WebviewWindow<R>> {+ if let Some(w) = app.get_webview_window(switcher::PICKER_WINDOW) {+ return Some(w);+ }+ let nav_app = app.clone();+ let built = WebviewWindowBuilder::new(app, switcher::PICKER_WINDOW, WebviewUrl::App("places.html".into()))+ .title("Places")+ .inner_size(switcher::PICKER_W + 2.0 * switcher::PICKER_MARGIN, switcher::PICKER_MIN_H)+ .resizable(false)+ .decorations(false)+ .transparent(true)+ .shadow(false)+ .always_on_top(true)+ .skip_taskbar(true)+ .visible(false)+ .on_navigation(move |url| {+ if url.scheme() == "kwant-places" {+ on_picker_url(&nav_app, url);+ return false;+ }+ // only the bundled picker page itself+ crate::links::is_bundled(url)+ })+ .on_new_window(|_, _| NewWindowResponse::Deny)+ .build();+ match built {+ Ok(w) => Some(w),+ Err(e) => {+ tracing::error!(error = %e, "couldn't make the place picker");+ None+ }+ }+}++/// The picker page navigated to `kwant-places://…` (never loaded).+fn on_picker_url<R: Runtime>(app: &AppHandle<R>, url: &Url) {+ let Some(ask) = switcher::parse_picker(url.as_str()) else {+ tracing::info!("ignored a picker address the app doesn't know");+ return;+ };+ let app = app.clone();+ std::thread::spawn(move || act(&app, ask));+}++fn act<R: Runtime>(app: &AppHandle<R>, ask: PickerAsk) {+ let picker = app.get_webview_window(switcher::PICKER_WINDOW);+ match ask {+ PickerAsk::Ready => {+ let pending = {+ let shared = app.state::<Shared>();+ let mut state = shared.picker.lock().unwrap();+ state.ready = true;+ state.pending.take()+ };+ if let (Some(page), Some(w)) = (pending, picker) {+ let _ = w.eval(format!("window.kwantPlaces&&kwantPlaces.show({page})"));+ }+ }+ PickerAsk::Size { h } => {+ if let Some(w) = picker {+ let _ = w.set_size(LogicalSize::new(switcher::PICKER_W + 2.0 * switcher::PICKER_MARGIN, switcher::picker_height(h)));+ }+ }+ PickerAsk::Close => {+ let from = hide(app);+ if let Some(w) = from.and_then(|l| app.get_webview_window(&l)) {+ let _ = w.set_focus();+ }+ }+ PickerAsk::Add => {+ hide(app);+ show_connect(app);+ }+ PickerAsk::RunHere => {+ hide(app);+ run_here(app);+ }+ PickerAsk::Switch { index, side } => {+ let row = app.state::<Shared>().picker.lock().unwrap().rows.get(index).cloned();+ let Some(place) = row else {+ return;+ };+ let from = hide(app);+ if place == Place::ThisMac && !current(app).this_mac {+ run_here(app);+ } else {+ switch_to(app, from, &place, side);+ }+ }+ }+}++fn run_here<R: Runtime>(app: &AppHandle<R>) {+ if let Err(e) = set_local(app, true) {+ tracing::info!(?e, "Run kwant on this Mac from the picker unchanged");+ }+ wake(app);+}++/// Hides the picker; returns the window it was opened from.+fn hide<R: Runtime>(app: &AppHandle<R>) -> Option<String> {+ let from = {+ let shared = app.state::<Shared>();+ let mut state = shared.picker.lock().unwrap();+ state.shown_at = None;+ state.from.clone()+ };+ if let Some(w) = app.get_webview_window(switcher::PICKER_WINDOW) {+ let _ = w.hide();+ }+ from+}++/// The picker lost the keyboard (a click outside it): it closes, unless it only just showed.+pub fn blurred<R: Runtime>(app: &AppHandle<R>) {+ let shown_at = app.state::<Shared>().picker.lock().unwrap().shown_at;+ if shown_at.is_some_and(|t| t.elapsed() >= BLUR_GRACE) {+ hide(app);+ }+}++/// ⌘1/⌘2, the tray's rows: switch in place from the window the person is in.+pub fn switch_from_last<R: Runtime>(app: &AppHandle<R>, place: &Place) {+ let from = last_place_window(app);+ switch_to(app, from, place, false);+}++/// Goes to `place` from the window `from` (switcher::plan).+pub fn switch_to<R: Runtime>(app: &AppHandle<R>, from: Option<String>, place: &Place, side: bool) {+ let label = place.window_label();+ let from = from.filter(|l| shows(app, l));+ let target_shows = app.get_webview_window(&label).and_then(|w| w.is_visible().ok()).unwrap_or(false);+ match switcher::plan(from.as_deref(), &label, target_shows, side) {+ Plan::Show | Plan::SideBySide => open_place(app, place, Goto::Stay),+ Plan::TakeFrame { from } => take_frame(app, &from, place),+ }+}++/// `place`'s window takes `from`'s frame and shows; `from` hides (it stays connected and keeps+/// its nudges).+fn take_frame<R: Runtime>(app: &AppHandle<R>, from: &str, place: &Place) {+ let Some(old) = app.get_webview_window(from) else {+ open_place(app, place, Goto::Stay);+ return;+ };+ {+ let shared = app.state::<Shared>();+ let mut places = shared.places.lock().unwrap();+ if !places.has(place) {+ return;+ }+ places.set_open(place, true);+ }+ let label = place.window_label();+ if app.get_webview_window(&label).is_none() {+ // made hidden, so it appears straight in the old window's frame+ crate::make_window(app, place, Goto::Stay, false);+ }+ let Some(new) = app.get_webview_window(&label) else {+ return;+ };+ let full = old.is_fullscreen().unwrap_or(false);+ let maximized = old.is_maximized().unwrap_or(false);+ if new.is_fullscreen().unwrap_or(false) && !full {+ let _ = new.set_fullscreen(false);+ }+ if new.is_maximized().unwrap_or(false) && !maximized {+ let _ = new.unmaximize();+ }+ if let (Ok(pos), Ok(size)) = (old.outer_position(), old.inner_size()) {+ let _ = new.set_size(size);+ let _ = new.set_position(pos);+ }+ if maximized {+ let _ = new.maximize();+ }+ if full {+ let _ = new.set_fullscreen(true);+ }+ show(&new);+ *app.state::<Shared>().last_focused.lock().unwrap() = Some(label);+ if full {+ let _ = old.set_fullscreen(false);+ }+ let _ = old.hide();+}++/// The script for a page that just loaded in `label`'s window, if it may have one.+pub fn elsewhere_for<R: Runtime>(app: &AppHandle<R>, label: &str, url: &Url) -> Option<String> {+ let port = app.state::<Shared>().local.lock().unwrap().port;+ let n = app.state::<Shared>().elsewhere.lock().unwrap().unwrap_or(0);+ switcher::elsewhere_script(label, switcher::is_local_page(url.as_str(), port), n)+}++/// A page finished loading in a place's window: This Mac's page gets the count again.+pub fn page_loaded<R: Runtime>(window: &WebviewWindow<R>, url: &Url, event: PageLoadEvent) {+ if !matches!(event, PageLoadEvent::Finished) {+ return;+ }+ if let Some(js) = elsewhere_for(window.app_handle(), window.label(), url) {+ let _ = window.eval(js.as_str());+ }+}++/// The menu's poll counted what waits in the places other than This Mac: This Mac's page hears+/// of a change.+pub fn set_elsewhere<R: Runtime>(app: &AppHandle<R>, n: usize) {+ {+ let shared = app.state::<Shared>();+ let mut now = shared.elsewhere.lock().unwrap();+ if *now == Some(n) {+ return;+ }+ *now = Some(n);+ }+ let Some(main) = app.get_webview_window(MAIN) else {+ return;+ };+ let Ok(url) = main.url() else {+ return;+ };+ if let Some(js) = elsewhere_for(app, MAIN, &url) {+ let _ = main.eval(js.as_str());+ }+}diff --git a/apps/mac/src/switcher.rs b/apps/mac/src/switcher.rsnew file mode 100644index 00000000..ae5ecaa2--- /dev/null+++ b/apps/mac/src/switcher.rs@@ -0,0 +1,450 @@+//! Switching places from inside the window (desktop-island/build-brief.md, Part 1): what the+//! place chip and the picker may ask, and the rules Rust holds them to. Pure: no Tauri, no I/O,+//! so every rule here has a unit test (`rustc --test src/switcher.rs` runs them without WebKit).+//!+//! - A place's page asks for the picker by navigating to `kwant-app://places?at=x,y` (or with no+//! `at`: the window's top centre). Any place window may ask (it only opens our own bundled+//! page), at most once a second per window, and x,y are clamped to the window.+//! - The picker (bundled `loading/places.html`) answers with `kwant-places://…` navigations that+//! name a row by its index in the list Rust gave it, never by a key it made up.+//! - Only This Mac's window (`main`, showing the kwant on 127.0.0.1) learns how many things wait+//! in other places (`window.__KWANT_ELSEWHERE__`). A server's page never learns anything about+//! any other place.++use std::collections::HashMap;+use std::time::{Duration, Instant};++/// The label of This Mac's window (as `crate::MAIN`).+pub const MAIN_WINDOW: &str = "main";+/// The picker window's label.+pub const PICKER_WINDOW: &str = "places";+/// How often one window may open the picker.+pub const ASK_EVERY: Duration = Duration::from_secs(1);+/// Longest `kwant-app://` address read at all.+const MAX_URL: usize = 256;++/// The picker card's width (design.md 9.2) and the transparent margin around it for its shadow.+pub const PICKER_W: f64 = 300.0;+pub const PICKER_MARGIN: f64 = 16.0;+/// The heights the picker page may ask for (with its margins).+pub const PICKER_MIN_H: f64 = 120.0;+pub const PICKER_MAX_H: f64 = 560.0;+/// The gap between the chip's bottom edge and the picker card.+const UNDER_CHIP: f64 = 4.0;+/// From the window's top edge when opened by the shortcut.+const FROM_TOP: f64 = 8.0;++/// What a place's page asked for through `kwant-app://`.+#[derive(Debug, Clone, PartialEq)]+pub enum AppAsk {+ /// Open the picker; `at` is the chip's bottom-left in window (CSS) coordinates, unclamped.+ Places { at: Option<(f64, f64)> },+}++/// Reads a `kwant-app://` address. `None`: not one we know (it is refused and ignored).+pub fn parse_app(url: &str) -> Option<AppAsk> {+ if url.len() > MAX_URL {+ return None;+ }+ let rest = url.strip_prefix("kwant-app://")?;+ let (host, query) = split_query(rest);+ match host.trim_end_matches('/') {+ "places" => {+ let at = query.and_then(|q| param(q, "at")).and_then(parse_at);+ Some(AppAsk::Places { at })+ }+ _ => None,+ }+}++/// What the picker page asked for through `kwant-places://`.+#[derive(Debug, Clone, PartialEq)]+pub enum PickerAsk {+ /// The page loaded and can take its rows.+ Ready,+ /// Switch to row `index` of the list Rust gave it; `side`: open side by side instead.+ Switch { index: usize, side: bool },+ /// "Add a server…".+ Add,+ /// "Run kwant on this Mac".+ RunHere,+ /// Esc.+ Close,+ /// The card's height (CSS px, without the margins).+ Size { h: f64 },+}++/// Reads a `kwant-places://` address. `None`: not one we know.+pub fn parse_picker(url: &str) -> Option<PickerAsk> {+ if url.len() > MAX_URL {+ return None;+ }+ let rest = url.strip_prefix("kwant-places://")?;+ let (host, query) = split_query(rest);+ let q = query.unwrap_or("");+ match host.trim_end_matches('/') {+ "ready" => Some(PickerAsk::Ready),+ "switch" => {+ let index = param(q, "i")?;+ // digits only: no sign, no spaces, no hex; small enough for any list+ if index.is_empty() || index.len() > 2 || !index.bytes().all(|b| b.is_ascii_digit()) {+ return None;+ }+ let side = match param(q, "side") {+ None | Some("0") => false,+ Some("1") => true,+ Some(_) => return None,+ };+ Some(PickerAsk::Switch { index: index.parse().ok()?, side })+ }+ "add" => Some(PickerAsk::Add),+ "run-here" => Some(PickerAsk::RunHere),+ "close" => Some(PickerAsk::Close),+ "size" => {+ let h = param(q, "h")?;+ if h.is_empty() || h.len() > 4 || !h.bytes().all(|b| b.is_ascii_digit()) {+ return None;+ }+ Some(PickerAsk::Size { h: h.parse::<f64>().ok()? })+ }+ _ => None,+ }+}++fn split_query(rest: &str) -> (&str, Option<&str>) {+ let rest = rest.split('#').next().unwrap_or("");+ match rest.split_once('?') {+ Some((h, q)) => (h, Some(q)),+ None => (rest, None),+ }+}++/// The first value of `name` in a query (no percent-decoding: none of our values need it).+fn param<'a>(query: &'a str, name: &str) -> Option<&'a str> {+ query.split('&').find_map(|pair| {+ let (k, v) = pair.split_once('=').unwrap_or((pair, ""));+ (k == name).then_some(v)+ })+}++/// "x,y" as two finite numbers (a comma may come percent-encoded as %2C). `None` for anything else.+pub fn parse_at(text: &str) -> Option<(f64, f64)> {+ if text.len() > 40 {+ return None;+ }+ let text = text.replace("%2C", ",").replace("%2c", ",");+ let (x, y) = text.split_once(',')?;+ let num = |s: &str| -> Option<f64> {+ // plain decimals only: no "inf", "NaN", exponents or signs other than a leading minus+ let ok = !s.is_empty() && s.bytes().all(|b| b.is_ascii_digit() || b == b'.' || b == b'-');+ if !ok {+ return None;+ }+ s.parse::<f64>().ok().filter(|v| v.is_finite())+ };+ Some((num(x)?, num(y)?))+}++/// Keeps a point inside a window of `size` (CSS px).+pub fn clamp_at(at: (f64, f64), size: (f64, f64)) -> (f64, f64) {+ let (w, h) = (size.0.max(0.0), size.1.max(0.0));+ (at.0.clamp(0.0, w), at.1.clamp(0.0, h))+}++/// At most one ask per `every` per key (a window label). A refused ask doesn't restart the clock.+#[derive(Debug, Default)]+pub struct RateLimit {+ last: HashMap<String, Instant>,+}++impl RateLimit {+ pub fn allow(&mut self, key: &str, now: Instant, every: Duration) -> bool {+ match self.last.get(key) {+ Some(t) if now.saturating_duration_since(*t) < every => false,+ _ => {+ self.last.insert(key.to_string(), now);+ true+ }+ }+ }+}++/// A screen rectangle in physical pixels.+#[derive(Debug, Clone, Copy, PartialEq)]+pub struct Rect {+ pub x: f64,+ pub y: f64,+ pub w: f64,+ pub h: f64,+}++/// Where the picker window goes (physical px, top-left). `window`: the asking window's content+/// area; `at`: the chip's bottom-left in that window (CSS px, already clamped), or `None` for the+/// window's top centre; `scale`: the window's scale factor; `height`: the picker window's height+/// in CSS px with margins; `screen`: the work area of the window's monitor. The card's top-left+/// lands under the chip; the whole window stays on screen.+pub fn picker_spot(window: Rect, at: Option<(f64, f64)>, scale: f64, height: f64, screen: Rect) -> (f64, f64) {+ let scale = if scale.is_finite() && scale > 0.0 { scale } else { 1.0 };+ let (card_x, card_y) = match at {+ Some((x, y)) => (window.x + x * scale, window.y + (y + UNDER_CHIP) * scale),+ None => (window.x + window.w / 2.0 - PICKER_W / 2.0 * scale, window.y + FROM_TOP * scale),+ };+ let (x, y) = (card_x - PICKER_MARGIN * scale, card_y - PICKER_MARGIN * scale);+ let (w, h) = ((PICKER_W + 2.0 * PICKER_MARGIN) * scale, height * scale);+ let x = x.min(screen.x + screen.w - w).max(screen.x);+ let y = y.min(screen.y + screen.h - h).max(screen.y);+ (x.round(), y.round())+}++/// The picker window's height for the card height the page reported (CSS px).+pub fn picker_height(card_h: f64) -> f64 {+ (card_h + 2.0 * PICKER_MARGIN).clamp(PICKER_MIN_H, PICKER_MAX_H)+}++/// The picker's row order (design.md 9.2): the current place first, then the others in saved+/// order. `keys`: the places in saved order; returns indexes into it.+pub fn row_order(keys: &[String], current: Option<&str>) -> Vec<usize> {+ let cur = current.and_then(|c| keys.iter().position(|k| k == c));+ cur.into_iter().chain((0..keys.len()).filter(|i| Some(*i) != cur)).collect()+}++/// The card's height before the page measures itself (CSS px, without margins), from+/// places.html's CSS: padding 6+6, header 30, rows 44, divider 13, actions 40, hint 25.+pub fn card_height(rows: usize, actions: usize) -> f64 {+ 12.0 + 30.0 + 44.0 * rows as f64 + 13.0 + 40.0 * actions as f64 + 25.0+}++/// What a switch does.+#[derive(Debug, Clone, PartialEq, Eq)]+pub enum Plan {+ /// Show (and focus) the target; nothing else moves.+ Show,+ /// The target takes `from`'s frame and shows; `from` hides (and stays connected).+ TakeFrame { from: String },+ /// The target opens in its own window, as before (⌥↩).+ SideBySide,+}++/// How to get to `target` (a window label) from the window the person was in (`from`: its label+/// while it shows, else `None`). `target_shows`: the target's window is already on screen (a+/// side-by-side window stays where it is). `side`: ⌥↩.+pub fn plan(from: Option<&str>, target: &str, target_shows: bool, side: bool) -> Plan {+ if side {+ return Plan::SideBySide;+ }+ match from {+ Some(f) if f != target && !target_shows && f != PICKER_WINDOW => Plan::TakeFrame { from: f.to_string() },+ _ => Plan::Show,+ }+}++/// Whether `url` is the page of the kwant on this Mac (`port`): http on 127.0.0.1 or localhost.+pub fn is_local_page(url: &str, port: Option<u16>) -> bool {+ let Some(port) = port.filter(|p| *p != 0) else {+ return false;+ };+ let Some(rest) = url.strip_prefix("http://") else {+ return false;+ };+ let authority = rest.split(['/', '?', '#']).next().unwrap_or("");+ if authority.contains('@') {+ return false;+ }+ authority == format!("127.0.0.1:{port}") || authority == format!("localhost:{port}")+}++/// The script that tells This Mac's page how many things wait in other places, or `None` when+/// the window isn't This Mac's or doesn't show This Mac's kwant (a server window, the picker, the+/// loading page): nothing about other places is ever given to them.+pub fn elsewhere_script(label: &str, page_is_local: bool, waiting_elsewhere: usize) -> Option<String> {+ if label != MAIN_WINDOW || !page_is_local {+ return None;+ }+ let n = waiting_elsewhere.min(9999);+ Some(format!(+ "window.__KWANT_ELSEWHERE__={n};try{{window.dispatchEvent(new Event('kwant-elsewhere'))}}catch(e){{}}"+ ))+}++/// What waits in the places other than This Mac (`counts`: (is This Mac, count) per place).+pub fn waiting_elsewhere(counts: &[(bool, usize)]) -> usize {+ counts.iter().filter(|(this_mac, _)| !this_mac).map(|(_, n)| *n).sum()+}++/// Shortcut for Windows and Linux, where the app has no menu bar: Ctrl+Shift+O in a place's+/// window asks for the picker at the window's top centre. (macOS has the Window menu's+/// "Switch place…" ⌘⇧O instead.) Runs in the main frame of each place window.+pub const SHORTCUT_SCRIPT: &str = "window.addEventListener('keydown',function(e){if(e.ctrlKey&&e.shiftKey&&!e.altKey&&!e.metaKey&&(e.key==='O'||e.key==='o'||e.code==='KeyO')){e.preventDefault();e.stopPropagation();window.location.href='kwant-app://places';}},true);";++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn the_chip_s_ask_is_read_with_its_point() {+ assert_eq!(parse_app("kwant-app://places?at=76,44"), Some(AppAsk::Places { at: Some((76.0, 44.0)) }));+ assert_eq!(parse_app("kwant-app://places?at=76.5%2C44"), Some(AppAsk::Places { at: Some((76.5, 44.0)) }));+ assert_eq!(parse_app("kwant-app://places/?at=1,2"), Some(AppAsk::Places { at: Some((1.0, 2.0)) }));+ // the shortcut sends no point: the window's top centre+ assert_eq!(parse_app("kwant-app://places"), Some(AppAsk::Places { at: None }));+ }++ #[test]+ fn an_odd_point_is_dropped_not_trusted() {+ for at in ["NaN,1", "inf,2", "1e309,1", "1,", ",1", "a,b", "1;2", "1,2,3", "+1,2", " 1,2", "0x10,2"] {+ assert_eq!(parse_app(&format!("kwant-app://places?at={at}")), Some(AppAsk::Places { at: None }), "{at}");+ }+ let long = format!("kwant-app://places?at={},1", "9".repeat(300));+ assert_eq!(parse_app(&long), None, "an overlong address is ignored");+ }++ #[test]+ fn unknown_app_asks_are_ignored() {+ for url in ["kwant-app://island?mode=off", "kwant-app://", "kwant-app://placesx", "kwant-nudge://open", "https://kwant-app/places"] {+ assert_eq!(parse_app(url), None, "{url}");+ }+ }++ #[test]+ fn points_are_clamped_to_the_window() {+ assert_eq!(clamp_at((-50.0, -1.0), (1280.0, 820.0)), (0.0, 0.0));+ assert_eq!(clamp_at((99999.0, 99999.0), (1280.0, 820.0)), (1280.0, 820.0));+ assert_eq!(clamp_at((76.0, 44.0), (1280.0, 820.0)), (76.0, 44.0));+ assert_eq!(clamp_at((5.0, 5.0), (-3.0, f64::NAN.max(0.0))), (0.0, 0.0));+ }++ #[test]+ fn a_window_opens_the_picker_at_most_once_a_second() {+ let mut limit = RateLimit::default();+ let t0 = Instant::now();+ assert!(limit.allow("server-ab", t0, ASK_EVERY));+ assert!(!limit.allow("server-ab", t0 + Duration::from_millis(10), ASK_EVERY));+ assert!(!limit.allow("server-ab", t0 + Duration::from_millis(999), ASK_EVERY));+ // another window has its own allowance+ assert!(limit.allow("main", t0 + Duration::from_millis(10), ASK_EVERY));+ assert!(limit.allow("server-ab", t0 + Duration::from_millis(1000), ASK_EVERY));+ // 100 asks in a burst open it once+ let t1 = t0 + Duration::from_secs(10);+ let opened = (0..100).filter(|i| limit.allow("server-ab", t1 + Duration::from_millis(*i), ASK_EVERY)).count();+ assert_eq!(opened, 1);+ }++ #[test]+ fn the_picker_names_rows_by_index_only() {+ assert_eq!(parse_picker("kwant-places://switch?i=2"), Some(PickerAsk::Switch { index: 2, side: false }));+ assert_eq!(parse_picker("kwant-places://switch?i=0&side=1"), Some(PickerAsk::Switch { index: 0, side: true }));+ for url in [+ "kwant-places://switch",+ "kwant-places://switch?i=",+ "kwant-places://switch?i=-1",+ "kwant-places://switch?i=+1",+ "kwant-places://switch?i=999",+ "kwant-places://switch?i=1&side=yes",+ "kwant-places://switch?key=https://evil.example",+ "kwant-places://open?i=1",+ ] {+ assert_eq!(parse_picker(url), None, "{url}");+ }+ assert_eq!(parse_picker("kwant-places://ready"), Some(PickerAsk::Ready));+ assert_eq!(parse_picker("kwant-places://add"), Some(PickerAsk::Add));+ assert_eq!(parse_picker("kwant-places://run-here"), Some(PickerAsk::RunHere));+ assert_eq!(parse_picker("kwant-places://close"), Some(PickerAsk::Close));+ assert_eq!(parse_picker("kwant-places://size?h=244"), Some(PickerAsk::Size { h: 244.0 }));+ assert_eq!(parse_picker("kwant-places://size?h=1e9"), None);+ assert_eq!(parse_picker("kwant-places://size?h=99999"), None);+ }++ #[test]+ fn the_picker_height_is_clamped() {+ assert_eq!(picker_height(10.0), PICKER_MIN_H);+ assert_eq!(picker_height(9000.0), PICKER_MAX_H);+ assert_eq!(picker_height(244.0), 244.0 + 2.0 * PICKER_MARGIN);+ }++ #[test]+ fn the_picker_lands_under_the_chip_and_stays_on_screen() {+ let screen = Rect { x: 0.0, y: 0.0, w: 2880.0, h: 1800.0 };+ let window = Rect { x: 200.0, y: 100.0, w: 2560.0, h: 1640.0 };+ // chip bottom-left at 76,44 CSS px on a 2x screen: card at 200+152, 100+(48*2)+ let (x, y) = picker_spot(window, Some((76.0, 44.0)), 2.0, 300.0, screen);+ assert_eq!((x, y), (200.0 + 152.0 - 32.0, 100.0 + 96.0 - 32.0));+ // the shortcut: centred on the window, near its top+ let (x, _) = picker_spot(window, None, 2.0, 300.0, screen);+ assert_eq!(x, (200.0 + 1280.0 - 300.0 - 32.0_f64).round());+ // a window at the screen's right edge: the picker is pulled back on screen+ let edge = Rect { x: 2700.0, y: 1700.0, w: 900.0, h: 600.0 };+ let (x, y) = picker_spot(edge, Some((800.0, 500.0)), 1.0, 300.0, screen);+ assert_eq!((x, y), (2880.0 - 332.0, 1800.0 - 300.0));+ // a window off the left/top of a second screen+ let other = Rect { x: -1920.0, y: 0.0, w: 1920.0, h: 1080.0 };+ let left = Rect { x: -1950.0, y: -40.0, w: 800.0, h: 600.0 };+ let (x, y) = picker_spot(left, Some((0.0, 0.0)), 1.0, 300.0, other);+ assert_eq!((x, y), (-1920.0, 0.0));+ // a bad scale factor never yields NaN+ let (x, y) = picker_spot(window, Some((1.0, 1.0)), f64::NAN, 300.0, screen);+ assert!(x.is_finite() && y.is_finite());+ }++ #[test]+ fn the_current_place_comes_first_then_saved_order() {+ let keys: Vec<String> = ["this_mac", "https://a", "https://b"].iter().map(|s| s.to_string()).collect();+ assert_eq!(row_order(&keys, Some("https://b")), vec![2, 0, 1]);+ assert_eq!(row_order(&keys, Some("this_mac")), vec![0, 1, 2]);+ assert_eq!(row_order(&keys, None), vec![0, 1, 2]);+ assert_eq!(row_order(&keys, Some("https://gone")), vec![0, 1, 2]);+ assert_eq!(row_order(&[], Some("x")), Vec::<usize>::new());+ assert!(picker_height(card_height(3, 1)) < PICKER_MAX_H);+ }++ #[test]+ fn switching_takes_the_frame_unless_asked_otherwise() {+ let s1 = "server-6874";+ assert_eq!(plan(Some("main"), s1, false, false), Plan::TakeFrame { from: "main".into() });+ assert_eq!(plan(Some("main"), s1, false, true), Plan::SideBySide, "⌥↩ keeps today's side by side");+ assert_eq!(plan(Some("main"), "main", false, false), Plan::Show, "the current place just comes front");+ assert_eq!(plan(None, s1, false, false), Plan::Show, "no window showing: just show the target");+ assert_eq!(plan(Some("main"), s1, true, false), Plan::Show, "a window already beside it stays, nothing hides");+ assert_eq!(plan(Some(PICKER_WINDOW), s1, false, false), Plan::Show, "the picker is never a place to hide");+ }++ #[test]+ fn only_this_mac_s_page_is_local() {+ assert!(is_local_page("http://127.0.0.1:8799/", Some(8799)));+ assert!(is_local_page("http://localhost:8799/spaces/x?y#z", Some(8799)));+ assert!(!is_local_page("http://127.0.0.1:8799/", Some(8800)), "another port");+ assert!(!is_local_page("http://127.0.0.1:8799/", None), "This Mac's kwant isn't running");+ assert!(!is_local_page("http://127.0.0.1:0/", Some(0)));+ assert!(!is_local_page("https://kwant.jumpin.games/", Some(8799)));+ assert!(!is_local_page("http://127.0.0.1:[email protected]/", Some(8799)));+ assert!(!is_local_page("http://evil.example/?127.0.0.1:8799", Some(8799)));+ assert!(!is_local_page("http://127.0.0.1:87990/", Some(8799)));+ assert!(!is_local_page("tauri://localhost/index.html", Some(8799)), "the loading page");+ }++ #[test]+ fn a_server_window_never_learns_about_other_places() {+ for label in ["server-68747470733a2f2f6b77616e742e6a756d70696e2e67616d6573", "server-", "connect", PICKER_WINDOW, "kwant-nudge-pill", "perch"] {+ assert_eq!(elsewhere_script(label, true, 3), None, "{label}");+ assert_eq!(elsewhere_script(label, false, 3), None, "{label}");+ }+ assert_eq!(elsewhere_script(MAIN_WINDOW, false, 3), None, "This Mac's window off its own kwant (loading page)");+ let js = elsewhere_script(MAIN_WINDOW, true, 3).expect("This Mac's page gets it");+ assert!(js.starts_with("window.__KWANT_ELSEWHERE__=3;"));+ assert!(js.contains("new Event('kwant-elsewhere')"));+ assert!(elsewhere_script(MAIN_WINDOW, true, 0).unwrap().contains("=0;"), "0 hides the badge");+ }++ #[test]+ fn elsewhere_counts_only_the_other_places() {+ assert_eq!(waiting_elsewhere(&[(true, 5), (false, 2), (false, 1)]), 3);+ assert_eq!(waiting_elsewhere(&[(true, 5)]), 0);+ assert_eq!(waiting_elsewhere(&[]), 0);+ }++ #[test]+ fn the_shortcut_script_only_asks_for_the_picker() {+ assert!(SHORTCUT_SCRIPT.contains("'kwant-app://places'"));+ assert_eq!(parse_app("kwant-app://places"), Some(AppAsk::Places { at: None }));+ assert!(!SHORTCUT_SCRIPT.contains("__KWANT"), "it gives the page nothing");+ }+}diff --git a/frontend/tests/placesRowLabel.test.mjs b/frontend/tests/placesRowLabel.test.mjsnew file mode 100644index 00000000..c20813d8--- /dev/null+++ b/frontend/tests/placesRowLabel.test.mjs@@ -0,0 +1,62 @@+// The place picker (apps/mac/loading/places.html): what a screen reader hears for each row.+// design-check-switcher F10 (server rows) and Rigel's fix 3 in qa-switcher.md (This Mac rows): a+// row's aria-label is its whole name, so it says the place, its status, the count when that isn't+// the status already, and "You are here", and never the keycap digit.+import assert from 'node:assert/strict';+import test from 'node:test';+import { readFileSync } from 'node:fs';+import { JSDOM, VirtualConsole } from 'jsdom';++const html = readFileSync(new URL('../../apps/mac/loading/places.html', import.meta.url), 'utf8');++function picker(rows) {+ const vc = new VirtualConsole(); // the page answers Rust by navigating to kwant-places://, which jsdom can't+ const errors = [];+ vc.on('jsdomError', (e) => { if (!/navigation/i.test(String(e.message))) errors.push(e); });+ const dom = new JSDOM(html, { runScripts: 'dangerously', pretendToBeVisual: true, virtualConsole: vc });+ dom.window.kwantPlaces.show({ mac: true, rows, actions: [] });+ const opts = [...dom.window.document.querySelectorAll('#rows [role="option"]')];+ return { opts, labels: opts.map((o) => o.getAttribute('aria-label')), errors };+}++const mac = 'This Mac';++test('every row says its place, status, count once and "You are here", server or This Mac', () => {+ const { opts, labels, errors } = picker([+ { kind: 'mac', name: mac, sub: 'Nothing waiting', n: 0, cur: true },+ { kind: 'server', name: 'kwant.jumpin.games', sub: '2 waiting', n: 2, cur: false },+ { kind: 'server', name: 'vps2.example.com', sub: "Can't reach it", bad: true, n: 0, cur: false },+ { kind: 'server', name: 'kwant-on-a-very-long-host-name.example.com', sub: "Sign in to see what's waiting", n: 0, cur: false },+ ]);+ assert.deepEqual(errors, []);+ assert.equal(opts.length, 4);+ assert.deepEqual(labels, [+ `${mac}, Nothing waiting, You are here`,+ 'kwant.jumpin.games, 2 waiting',+ "vps2.example.com, Can't reach it",+ "kwant-on-a-very-long-host-name.example.com, Sign in to see what's waiting",+ ]);+});++test('a This Mac row keeps "You are here" when its count takes the ✓\'s place, and says the count once', () => {+ // Rigel's jsdom readings before the fix: "This Mac Running You are here 1" and+ // "This Mac 3 waiting 3 waiting 9" (keycap digit read, count twice, no "You are here").+ const { labels } = picker([+ { kind: 'server', name: 'kwant.jumpin.games', sub: 'Nothing waiting', n: 0, cur: false },+ { kind: 'mac', name: mac, sub: '3 waiting', n: 3, cur: true },+ { kind: 'mac', name: mac, sub: 'Not running', n: 0, cur: false },+ { kind: 'server', name: 'busy.example.com', sub: '12 waiting', n: 12, cur: true },+ ]);+ assert.deepEqual(labels, [+ 'kwant.jumpin.games, Nothing waiting',+ `${mac}, 3 waiting, You are here`,+ `${mac}, Not running`,+ 'busy.example.com, 12 waiting, You are here',+ ]);+ for (const l of labels) assert.doesNotMatch(l, /\d$/, `no keycap digit at the end: ${l}`);+});++test('a count that is not the status is still said', () => {+ const { labels } = picker([{ kind: 'mac', name: mac, sub: 'Starting…', n: 2, cur: true }]);+ assert.deepEqual(labels, [`${mac}, Starting…, 2 waiting, You are here`]);+});