diff --git a/Cargo.lock b/Cargo.lock index e951f6daf..49ce11865 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2071,6 +2071,7 @@ dependencies = [ "sha2 0.10.9", "tempfile", "thiserror 2.0.21", + "web-time", ] [[package]] @@ -2357,6 +2358,7 @@ dependencies = [ "block2 0.6.2", "craft-atomic", "craft-behavior", + "craft-browse", "craft-host", "craft-i18n", "craft-platform", @@ -2369,6 +2371,7 @@ dependencies = [ "objc2-foundation 0.3.2", "raw-window-handle", "rfd", + "serde_json", "zbus", ] @@ -2814,8 +2817,12 @@ dependencies = [ name = "craft-gpu" version = "0.1.0" dependencies = [ + "egui-wgpu", + "log", + "pollster 1.0.1", "serde", "serde_json", + "tempfile", "thiserror 2.0.21", ] @@ -3422,6 +3429,7 @@ version = "0.1.0" dependencies = [ "craft-behavior", "craft-i18n", + "craft-keymap", "craft-text", "craft-theme", "craft-ui", @@ -3598,11 +3606,13 @@ dependencies = [ "craft-docpath", "craft-host", "craft-theme", + "fmv-macos-events", "futures-lite", "js-sys", "log", "objc2-app-kit 0.3.2", "objc2-foundation 0.3.2", + "rfd", "serde", "serde_json", "sysinfo", @@ -3611,6 +3621,7 @@ dependencies = [ "wasm-bindgen-test", "web-sys", "web-time", + "windows", "wl-clipboard-rs", "x11rb", "xcap", @@ -3697,14 +3708,19 @@ name = "craft-print" version = "0.1.0" dependencies = [ "craft-behavior", + "craft-host", "craft-ui", "craft-winprint-gdi", "egui", + "js-sys", "log", "miniz_oxide 0.9.1", "roxmltree 0.21.2", + "serde", "serde_json", "tempfile", + "wasm-bindgen", + "web-sys", "winprint", "winsafe", ] @@ -3821,6 +3837,7 @@ dependencies = [ "craft-host", "craft-i18n", "craft-keymap", + "craft-pages", "craft-theme", "craft-ui", "egui", @@ -3873,11 +3890,15 @@ dependencies = [ "craft-host", "craft-settings", "dirs", + "log", "serde", "serde_json", "tempfile", "toml", "toml_edit", + "wasm-bindgen-test", + "web-sys", + "web-time", ] [[package]] @@ -4260,6 +4281,7 @@ version = "0.1.0" dependencies = [ "accesskit", "craft-behavior", + "craft-codepage", "craft-font-catalog", "craft-fonts-build", "craft-host", @@ -6052,6 +6074,17 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "fmv-macos-events" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "90642cf66dde7f205dc8b42dfe57b47d0f3a29f571b832742883ef512e23fe55" +dependencies = [ + "objc2 0.6.5", + "objc2-app-kit 0.3.2", + "objc2-foundation 0.3.2", +] + [[package]] name = "fnv" version = "1.0.7" diff --git a/crates/automation/Cargo.toml b/crates/automation/Cargo.toml index 9e4e079df..a9fcf894a 100644 --- a/crates/automation/Cargo.toml +++ b/crates/automation/Cargo.toml @@ -40,16 +40,18 @@ craft-ui = { workspace = true, optional = true } egui = { workspace = true, optional = true } serde = { workspace = true } serde_json = { workspace = true } - -# The control channel, its server and client, screenshots, the profiler and the trace. -[target.'cfg(not(target_arch = "wasm32"))'.dependencies] +web-time = "1.1" +# The screenshot queue encodes and inlines PNGs on every target the control channel builds for. base64 = "0.22" +png = "0.17" + +# The server, client, profiler and trace. +[target.'cfg(not(target_arch = "wasm32"))'.dependencies] craft-platform = { workspace = true } craft-host = { workspace = true, optional = true } getrandom = "0.3" hmac = "0.12" log = "0.4" -png = "0.17" sha2 = { version = "0.10", default-features = false, features = ["std"] } thiserror = { workspace = true } diff --git a/crates/automation/src/client.rs b/crates/automation/src/client.rs index b32b98d28..c199a14c6 100644 --- a/crates/automation/src/client.rs +++ b/crates/automation/src/client.rs @@ -12,6 +12,26 @@ use crate::security::{AUTH_METHOD, IO_TIMEOUT}; /// server's own timeout error arrives before the client gives up. pub const CALL_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(REPLY_DEADLINE.as_secs() + 5); +/// Why [`ControlClient::connect`] failed. +#[derive(Clone, Debug, PartialEq, Eq)] +#[non_exhaustive] +pub enum ConnectError { + /// A socket or read failure: the server was not reached. + Transport(String), + /// The server answered the `auth` request with an error. + Refused(String), +} + +impl std::fmt::Display for ConnectError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + ConnectError::Transport(why) | ConnectError::Refused(why) => f.write_str(why), + } + } +} + +impl std::error::Error for ConnectError {} + /// One authenticated connection. pub struct ControlClient { stream: std::net::TcpStream, @@ -21,16 +41,25 @@ pub struct ControlClient { } impl ControlClient { + /// True after a transport failure closed the connection; an error reply leaves it false. A + /// caller tells a lost connection from a refused request and never replays a mutation. + pub fn is_broken(&self) -> bool { + self.broken + } + /// Connect (read timeout [`CALL_TIMEOUT`]), send /// `{"id": 1, "method": "auth", "params": {"token": token}}` and read one reply line; `Err` with - /// the reply's `error` text when it isn't `ok`, or the I/O error's message. - pub fn connect(addr: SocketAddr, token: &str) -> Result { - let stream = std::net::TcpStream::connect(addr).map_err(|e| e.to_string())?; - stream.set_read_timeout(Some(CALL_TIMEOUT)).map_err(|e| e.to_string())?; - stream.set_write_timeout(Some(IO_TIMEOUT)).map_err(|e| e.to_string())?; - let reader = BufReader::new(stream.try_clone().map_err(|e| e.to_string())?); + /// the reply's `error` text as `Refused` when it isn't `ok`, or the I/O error's message as `Transport`. + pub fn connect(addr: SocketAddr, token: &str) -> Result { + let io = |e: std::io::Error| ConnectError::Transport(e.to_string()); + let stream = std::net::TcpStream::connect(addr).map_err(io)?; + stream.set_read_timeout(Some(CALL_TIMEOUT)).map_err(io)?; + stream.set_write_timeout(Some(IO_TIMEOUT)).map_err(io)?; + let reader = BufReader::new(stream.try_clone().map_err(io)?); let mut client = Self { stream, broken: false, reader, next_id: 2 }; - client.exchange(1, AUTH_METHOD, json!({"token": token}))?; + // `exchange` marks the client broken on a transport failure only, so an error reply is a refusal. + let auth = client.exchange(1, AUTH_METHOD, json!({"token": token})); + auth.map_err(|e| if client.broken { ConnectError::Transport(e) } else { ConnectError::Refused(e) })?; Ok(client) } diff --git a/crates/automation/src/control.rs b/crates/automation/src/control.rs index c0f594251..cc1e37c81 100644 --- a/crates/automation/src/control.rs +++ b/crates/automation/src/control.rs @@ -14,7 +14,7 @@ //! two happened, once, between the UI thread and the transport. use std::sync::mpsc::{Receiver, Sender}; -use std::time::Instant; +use web_time::Instant; use craft_ui::runtime::motion; use craft_ui::runtime::windows::WindowHost; @@ -127,9 +127,17 @@ pub enum Reply { /// A command started a background job and the caller waits: reply with its result when it /// has been applied, or with its error or `cancelled`. AfterJob(JobId), + /// A `ui.accessTree`: hold the reply until the window's settled access tree can be read + /// ([`ControlChannel::poll_access_trees`]). + AccessTree, } impl Reply { + /// A `ui.accessTree` reply: held until the window's settled access tree is available. + pub fn access_tree() -> Reply { + Reply::AccessTree + } + /// A `ui.screenshot` reply for `token` of `viewport`, writing the PNG to `path` or inlining it /// when `None`. pub fn screenshot(token: u64, path: Option, viewport: egui::ViewportId) -> Self { @@ -162,6 +170,7 @@ pub struct ControlChannel { rx: Receiver, input_waiters: Vec>, job_waiters: Vec<(JobId, Sender)>, + tree_waiters: Vec>, /// The screenshot queue; the app calls its `issue` and `drain` from its UI and logic phases. pub captures: Captures, } @@ -169,7 +178,7 @@ pub struct ControlChannel { impl ControlChannel { /// Attach a transport's receiver (TCP, stdin, tests). pub fn new(rx: Receiver) -> Self { - Self { rx, input_waiters: Vec::new(), job_waiters: Vec::new(), captures: Captures::default() } + Self { rx, input_waiters: Vec::new(), job_waiters: Vec::new(), tree_waiters: Vec::new(), captures: Captures::default() } } /// The next request to run, claimed through [`Dispatch::start`]. Expired or abandoned @@ -197,6 +206,7 @@ impl ControlChannel { } Reply::AfterInput => self.input_waiters.push(reply), Reply::AfterJob(job) => self.job_waiters.push((job, reply)), + Reply::AccessTree => self.tree_waiters.push(reply), Reply::Screenshot { token, path, viewport } => { if let Err((reply, e)) = self.captures.admit(ScreenshotRequest { token, path, viewport, reply, document, settle_ms }, motion::now()) { let _ = reply.send(json!({"ok": false, "error": e})); @@ -237,6 +247,43 @@ impl ControlChannel { } } + /// Answers the held `ui.accessTree` requests from the window host's settled access tree; a + /// request stays held while the host has none. Runs in the logic phase of every pass, as + /// [`poll_input`](Self::poll_input) does. + pub fn poll_access_trees(&mut self, ctx: &egui::Context) { + if self.tree_waiters.is_empty() { + return; + } + // `ui.accessTree` takes no window: it reads the main window's tree. + let Some(update) = WindowHost::of(ctx).access_tree(egui::ViewportId::ROOT) else { return }; + let nodes: Vec = update + .nodes + .iter() + .map(|(id, node)| { + let children: Vec = node.children().iter().map(|child| child.0).collect(); + let mut entry = json!({"id": id.0, "role": format!("{:?}", node.role()), "children": children}); + if let Some(name) = node.label() { + entry["name"] = json!(name); + } + if let Some(value) = node.value() { + entry["value"] = json!(value); + } + if let Some(selection) = node.text_selection() { + entry["textSelection"] = json!({ + "anchor": {"node": selection.anchor.node.0, "character": selection.anchor.character_index}, + "focus": {"node": selection.focus.node.0, "character": selection.focus.character_index}, + }); + } + entry + }) + .collect(); + let root = update.tree.as_ref().map(|tree| tree.root.0); + let reply = json!({"ok": true, "result": {"nodes": nodes, "focus": update.focus.0, "root": root}}); + for waiter in self.tree_waiters.drain(..) { + let _ = waiter.send(reply.clone()); + } + } + /// Drops the host's queued input and the step in flight, and fails every /// [`Reply::AfterInput`] waiter with `input cancelled: {reason}`, also when only waiters /// remain (their input was already consumed). True when anything was pending or waiting. @@ -277,6 +324,6 @@ impl ControlChannel { /// Waiters of every kind, for `ui.inspect`'s `pending` count and tests. pub fn waiting(&self) -> usize { - self.input_waiters.len() + self.job_waiters.len() + self.captures.pending() + self.input_waiters.len() + self.job_waiters.len() + self.tree_waiters.len() + self.captures.pending() } } diff --git a/crates/automation/src/lib.rs b/crates/automation/src/lib.rs index 52e967ead..d7bd2de74 100644 --- a/crates/automation/src/lib.rs +++ b/crates/automation/src/lib.rs @@ -23,19 +23,18 @@ pub mod ui; #[cfg(not(target_arch = "wasm32"))] pub mod args; -#[cfg(all(feature = "ui", not(target_arch = "wasm32")))] +#[cfg(feature = "ui")] pub mod control; #[cfg(all(feature = "ui", not(target_arch = "wasm32")))] pub mod dialogs; #[cfg(not(target_arch = "wasm32"))] pub mod profiler; -#[cfg(not(target_arch = "wasm32"))] pub mod protocol; -#[cfg(all(feature = "ui", not(target_arch = "wasm32")))] +#[cfg(feature = "ui")] pub mod screenshot; #[cfg(not(target_arch = "wasm32"))] pub mod security; -#[cfg(all(feature = "ui", not(target_arch = "wasm32")))] +#[cfg(feature = "ui")] pub mod synthetic; #[cfg(not(target_arch = "wasm32"))] pub mod trace; diff --git a/crates/automation/src/protocol.rs b/crates/automation/src/protocol.rs index 20b4357b5..8cf25e09c 100644 --- a/crates/automation/src/protocol.rs +++ b/crates/automation/src/protocol.rs @@ -104,6 +104,10 @@ pub fn write_reply(out: &mut impl Write, reply: &Value) -> std::io::Result<()> { /// The pointer buttons a request may name. pub const BUTTONS: [&str; 4] = ["left", "right", "secondary", "middle"]; +/// The method that reads the window's access tree. Params `{}`; the reply is +/// `{nodes: [{id, role, name?, value?, children, textSelection?}], focus, root}` with AccessKit +/// role names. +pub const ACCESS_TREE_METHOD: &str = "ui.accessTree"; /// The per-request reply deadline. pub const REPLY_DEADLINE: Duration = Duration::from_secs(60); diff --git a/crates/automation/src/screenshot.rs b/crates/automation/src/screenshot.rs index f3456c521..292ecab60 100644 --- a/crates/automation/src/screenshot.rs +++ b/crates/automation/src/screenshot.rs @@ -18,7 +18,7 @@ use std::collections::HashMap; use std::sync::Arc; use std::sync::mpsc::Sender; -use std::time::{Duration, Instant}; +use web_time::{Duration, Instant}; use base64::Engine as _; use craft_ui::runtime::windows::{ScreenshotFacts, ScreenshotSlot, WindowHost}; diff --git a/crates/automation/src/synthetic.rs b/crates/automation/src/synthetic.rs index 90e16fc1b..96024d958 100644 --- a/crates/automation/src/synthetic.rs +++ b/crates/automation/src/synthetic.rs @@ -49,9 +49,9 @@ pub const OFF_SCREEN: &str = "the document point is too far off the screen"; /// The error of a point that is not finite (NaN or infinite): refused at the request, never queued. pub const NOT_FINITE: &str = "the point must be finite"; -/// The application's map from a document point to the screen point its canvas shows it at; `None` when no canvas -/// shows a document. Applications without documents pass `&|_| None`. -pub type DocumentMap<'a> = &'a dyn Fn(Pos2) -> Option; +/// The application's map from a page and a document point on it to the screen point its canvas shows it at; `None` +/// when no canvas shows a document. Applications without documents pass `&|_, _| None`. +pub type DocumentMap<'a> = &'a dyn Fn(usize, Pos2) -> Option; /// A point of a request: screen points, or document points the application maps. #[derive(Clone, Copy, Debug, PartialEq)] @@ -59,8 +59,8 @@ pub type DocumentMap<'a> = &'a dyn Fn(Pos2) -> Option; pub enum At { /// Screen points. Screen(Pos2), - /// Document points. - Document(Pos2), + /// Document points on page `page` (0 when the request names none). + Document(Pos2, usize), } impl At { @@ -70,7 +70,7 @@ impl At { let x = p.number_in("x", "x", range)?.unwrap_or(0.0) as f32; let y = p.number_in("y", "y", range)?.unwrap_or(0.0) as f32; Ok(match p.choice("coordinates", "coordinates", &["screen", "document"])?.unwrap_or("screen") { - "document" => Self::Document(pos2(x, y)), + "document" => Self::Document(pos2(x, y), p.uint_field("page")?.map_or(0, |page| usize::try_from(page).unwrap_or(usize::MAX))), _ => Self::Screen(pos2(x, y)), }) } @@ -81,9 +81,9 @@ impl At { match self { Self::Screen(at) if at.x.is_finite() && at.y.is_finite() => Ok(at), Self::Screen(_) => Err(NOT_FINITE.to_owned()), - Self::Document(at) if !(at.x.is_finite() && at.y.is_finite()) => Err(NOT_FINITE.to_owned()), - Self::Document(at) => { - let on_screen = map(at).ok_or_else(|| NO_DOCUMENT.to_owned())?; + Self::Document(at, _) if !(at.x.is_finite() && at.y.is_finite()) => Err(NOT_FINITE.to_owned()), + Self::Document(at, page) => { + let on_screen = map(page, at).ok_or_else(|| NO_DOCUMENT.to_owned())?; let within = |v: f32| v.is_finite() && f64::from(v.abs()) <= MAX_SCREEN_POINT; if within(on_screen.x) && within(on_screen.y) { Ok(on_screen) } else { Err(OFF_SCREEN.to_owned()) } } @@ -92,7 +92,7 @@ impl At { } /// The point fields every pointer request takes. -const POINT: [&str; 3] = ["x", "y", "coordinates"]; +const POINT: [&str; 4] = ["x", "y", "coordinates", "page"]; /// The modifier fields ([`crate::protocol::KEY_MODIFIERS`], top-level or under `modifiers`). const MODIFIERS: [&str; 5] = ["modifiers", "shift", "alt", "command", "ctrl"]; @@ -263,7 +263,7 @@ impl Release { /// `{button?, key?, x?, y?, coordinates?}`, no other fields. With neither `button` nor `key` everything held is /// released, the modifiers too; both is ``"`button` and `key` exclude each other"``. pub fn from_params(params: &Value) -> Result { - let p = Params(params).only(None, &["button", "key", "x", "y", "coordinates"])?; + let p = Params(params).only(None, &["button", "key", "x", "y", "coordinates", "page"])?; let p = Params(&p); let released = match (button(&p)?, key(&p)?) { (Some(_), Some(_)) => return Err("`button` and `key` exclude each other".into()), diff --git a/crates/automation/tests/it/control.rs b/crates/automation/tests/it/control.rs index c6c963be2..5191dabc7 100644 --- a/crates/automation/tests/it/control.rs +++ b/crates/automation/tests/it/control.rs @@ -123,6 +123,33 @@ fn an_unauthenticated_connection_is_closed_at_the_deadline_whatever_it_sends() { assert!(rx.try_recv().is_err(), "nothing was dispatched"); } +/// A web page can reach loopback: a browser `POST` whose body is a valid `auth` line is refused at its request line +/// and the connection closed, so neither the body's `auth` nor a request after it reaches the app. +#[trial] +fn a_browser_post_never_reaches_the_app() { + // Far longer than the trial, so the close comes from the refusal, not the deadline. + let (rx, server) = server::serve_with_deadline(TcpListener::bind("127.0.0.1:0").expect("bound"), TOKEN.into(), host(), Duration::from_secs(60)) + .expect("started"); + let mut stream = TcpStream::connect(server.addr).expect("connected"); + stream.set_read_timeout(Some(Duration::from_secs(5))).expect("timeout"); + let mut reader = BufReader::new(stream.try_clone().expect("cloned")); + let body = format!("{}\n{}\n", json!({"id": 1, "method": "auth", "params": {"token": TOKEN}}), json!({"id": 2, "method": "test.ping"})); + write!(stream, "POST / HTTP/1.1\r\n").expect("written"); + let refused = read_json(&mut reader).expect("a reply to the request line"); + assert_eq!(refused["ok"], false, "{refused}"); + assert_eq!(refused["error"], "authentication required", "{refused}"); + // The rest of what the browser sends; the server may already have closed. + let _ = write!(stream, "Host: 127.0.0.1\r\nContent-Type: text/plain\r\nContent-Length: {}\r\n\r\n{body}", body.len()); + let _ = stream.flush(); + let mut rest = String::new(); + let closed = match reader.read_line(&mut rest) { + Ok(read) => read == 0, + Err(e) => !matches!(e.kind(), std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut), + }; + assert!(closed, "the connection closes after the refusal, answering nothing more: {rest:?}"); + assert!(rx.recv_timeout(Duration::from_millis(300)).is_err(), "nothing reached the app"); +} + /// A request line over `MAX_REQUEST_BYTES` without a newline gets an error reply and the connection is closed. #[trial] fn an_over_long_request_is_refused_and_closes_the_connection() { diff --git a/crates/automation/tests/it/synthetic.rs b/crates/automation/tests/it/synthetic.rs index 9452879ae..494cc848d 100644 --- a/crates/automation/tests/it/synthetic.rs +++ b/crates/automation/tests/it/synthetic.rs @@ -32,9 +32,14 @@ struct Rig { passes: Rc>>, } -/// Document points are screen points doubled, as a canvas at 50 % shows them. -fn map(at: Pos2) -> Option { - Some(pos2(at.x / 2.0, at.y / 2.0)) +/// Screen points between one page's top and the next's, in a canvas that stacks its pages down the screen. +const PAGE_STEP: f32 = 200.0; + +/// Document points are screen points doubled, as a canvas at 50 % shows them, with each page [`PAGE_STEP`] below +/// the one before. +fn map(page: usize, at: Pos2) -> Option { + let page = u16::try_from(page).ok()?; + Some(pos2(at.x / 2.0, at.y / 2.0 + f32::from(page) * PAGE_STEP)) } impl Rig { @@ -109,6 +114,8 @@ fn a_held_press_stays_down_until_its_release() { assert_eq!(rig.now().pos, Some(pos2(100.0, 50.0)), "the document point is mapped"); rig.send("ui.move", json!({"x": 300, "y": 100, "coordinates": "document"})); assert!(rig.now().primary_down && rig.now().pos == Some(pos2(150.0, 50.0)), "a move while held drags"); + rig.send("ui.move", json!({"x": 300, "y": 100, "coordinates": "document", "page": 1})); + assert_eq!(rig.now().pos, Some(pos2(150.0, 50.0 + PAGE_STEP)), "a document point is mapped on the page it names"); rig.send("ui.release", json!({})); assert!(!rig.now().primary_down, "the release lets it go"); rig.send("ui.click", json!({"x": 10, "y": 10})); @@ -276,7 +283,7 @@ fn injected_passes_are_the_passes_that_carry_a_step() { fn document_points_need_a_canvas() { let rig = Rig::new(); let host = rig.host(); - let none = |_: Pos2| None; + let none = |_: usize, _: Pos2| None; let refused = input_method("ui.move", &json!({"x": 1, "y": 1, "coordinates": "document"}), &host, ViewportId::ROOT, &none); assert_eq!(refused, Some(Err(NO_DOCUMENT.to_owned()))); assert!(host.injected_idle()); @@ -409,9 +416,9 @@ fn ui_ime_reaches_a_focused_text_field_as_a_preedit_then_a_commit_in_order() { #[trial] fn a_point_that_is_not_finite_is_refused() { for bad in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY] { - for at in [At::Screen(pos2(bad, 1.0)), At::Screen(pos2(1.0, bad)), At::Document(pos2(bad, 1.0))] { - assert_eq!(at.resolve(&|p| Some(p)), Err(NOT_FINITE.to_owned()), "{at:?}"); + for at in [At::Screen(pos2(bad, 1.0)), At::Screen(pos2(1.0, bad)), At::Document(pos2(bad, 1.0), 0)] { + assert_eq!(at.resolve(&|_, p| Some(p)), Err(NOT_FINITE.to_owned()), "{at:?}"); } } - assert_eq!(At::Screen(pos2(3.0, 4.0)).resolve(&|_| None), Ok(pos2(3.0, 4.0))); + assert_eq!(At::Screen(pos2(3.0, 4.0)).resolve(&|_, _| None), Ok(pos2(3.0, 4.0))); } diff --git a/crates/behavior/src/cursor.rs b/crates/behavior/src/cursor.rs index 32d35a918..4b0953fda 100644 --- a/crates/behavior/src/cursor.rs +++ b/crates/behavior/src/cursor.rs @@ -196,6 +196,8 @@ pub enum PaintedCursor { Arrow { /// The arrow is drawn hollow. hollow: bool, + /// The art turns about its hotspot to point along this direction; `None` is the base art. + toward: Option, }, /// An I-beam across a path with a filled triangle toward each grabbable side. #[non_exhaustive] @@ -216,6 +218,8 @@ pub enum PaintedCursor { }, /// No cursor at all. Hidden, + /// A plain I-beam, visible on light and dark. + IBeam, } impl PaintedCursor { @@ -275,7 +279,12 @@ impl PaintedCursor { /// An arrow with its tip on the hotspot, hollow when `hollow`. pub const fn arrow(hollow: bool) -> Self { - PaintedCursor::Arrow { hollow } + PaintedCursor::Arrow { hollow, toward: None } + } + + /// A solid arrow turned about its hotspot to point along `dir`. + pub const fn arrow_toward(dir: Vec2) -> Self { + PaintedCursor::Arrow { hollow: false, toward: Some(dir) } } /// An I-beam across the path with a triangle toward each grabbable side. diff --git a/crates/behavior/src/editor.rs b/crates/behavior/src/editor.rs index c05714195..7e9467f2c 100644 --- a/crates/behavior/src/editor.rs +++ b/crates/behavior/src/editor.rs @@ -52,6 +52,9 @@ pub enum EditorInput { forward: bool, /// How much to delete. by: Granularity, + /// Shift was held (`Intent::Delete::shift`): Shift+Delete is a word processor's Cut, which deletes nothing + /// without a selection, so an editor that gives it that meaning tells it from a plain Delete. + shift: bool, }, /// Text around the caret or the marked text, deleted for the IME. #[non_exhaustive] @@ -87,14 +90,21 @@ pub enum EditorInput { Newline, /// Tab. Tab, + /// Shift+Tab, which reaches only a document canvas's editor part that keeps Tab. + BackTab, /// Escape. Cancel, } impl EditorInput { - /// A `Delete` of `by`. + /// A `Delete` of `by`, without Shift. pub const fn delete(forward: bool, by: Granularity) -> Self { - EditorInput::Delete { forward, by } + EditorInput::Delete { forward, by, shift: false } + } + + /// A `Delete` of `by` with Shift held when `shift`. + pub const fn delete_with_shift(forward: bool, by: Granularity, shift: bool) -> Self { + EditorInput::Delete { forward, by, shift } } /// A `DeleteSurrounding` of `before` and `after` characters. diff --git a/crates/behavior/src/fit.rs b/crates/behavior/src/fit.rs index 0abbabacf..4814a0078 100644 --- a/crates/behavior/src/fit.rs +++ b/crates/behavior/src/fit.rs @@ -1,6 +1,6 @@ //! The fit rules: which tabs, bar items or titles stay in a strip and which go to an overflow menu. [`fit`] and -//! [`fit_whole`] assign tab widths (tabs shrink before they overflow, or keep their width); [`fit_items`] drops -//! command items and titles from the end. All of them read no egui types. +//! [`fit_whole`] assign tab widths (tabs shrink before they overflow, or keep their width); [`fit_items`] shortens +//! items that have a short form, then drops command items and titles from the end. All of them read no egui types. /// Tabs visible on a strip and tabs that need an overflow menu, all in original order. #[derive(Clone, Debug, Default, PartialEq)] @@ -122,9 +122,13 @@ fn fit_keeping_selected(natural: &[f32], selected: usize, available: f32, minimu /// gets less than its natural width; its painter elides the label. A lone tab never reserves a /// button. /// +/// The tabs marked in `kept` take the room after the selected tab before the others, in order while each fits; a +/// kept tab that does not fit overflows. The others then follow the rule above. A `kept` slice that is empty or +/// shorter than `natural` marks no tab past its end, so an empty slice gives the plain rule. +/// /// Dimensions are sanitized as in [`fit`], and the shown widths plus `overflow_width` never /// exceed the sanitized available width. Work and storage are linear in the input count. -pub fn fit_whole(natural: &[f32], selected: usize, available: f32, overflow_width: f32) -> TabFit { +pub fn fit_whole(natural: &[f32], selected: usize, kept: &[bool], available: f32, overflow_width: f32) -> TabFit { let available = tab_extent(available); let natural: Vec = natural.iter().map(|&w| tab_extent(w)).collect(); if natural.iter().map(|&w| f64::from(w)).sum::() <= f64::from(available) { @@ -138,17 +142,33 @@ pub fn fit_whole(natural: &[f32], selected: usize, available: f32, overflow_widt let selected = selected.min(natural.len().saturating_sub(1)); let active = natural.get(selected).copied().unwrap_or(0.0).min(budget); let mut room = f64::from(budget - active); + let mut keep = vec![false; natural.len()]; + if let Some(keep) = keep.get_mut(selected) { + *keep = true; + } + // The kept tabs take room first, then the others; each run stops at its first tab that does not fit. + for kept_run in [true, false] { + for (i, &width) in natural.iter().enumerate() { + if i == selected || kept.get(i).copied().unwrap_or(false) != kept_run { + continue; + } + if f64::from(width) > room { + break; + } + room -= f64::from(width); + if let Some(keep) = keep.get_mut(i) { + *keep = true; + } + } + } let mut shown = Vec::new(); let mut overflow = Vec::new(); - let mut full = false; for (i, &width) in natural.iter().enumerate() { if i == selected { shown.push((i, active)); - } else if !full && f64::from(width) <= room { - room -= f64::from(width); + } else if keep.get(i).copied().unwrap_or(false) { shown.push((i, width)); } else { - full = true; overflow.push(i); } } @@ -208,12 +228,20 @@ pub struct FitItem { pub section: u16, /// Whether the item may overflow. pub keep: FitKeep, + /// The extent of the item's shorter form, if it has one. + pub short: Option, } impl FitItem { /// An item `extent` long in `section`. pub const fn new(extent: f32, section: u16, keep: FitKeep) -> Self { - FitItem { extent, section, keep } + FitItem { extent, section, keep, short: None } + } + + /// The item with a shorter form `extent` long, which it takes before any free item leaves. + pub const fn short(mut self, extent: f32) -> Self { + self.short = Some(extent); + self } } @@ -225,6 +253,8 @@ pub struct Fit { pub shown: Vec, /// The items in the overflow menu; empty when everything fits. pub overflow: Vec, + /// The shown items that take their shorter form, as indexes into the input. + pub short: Vec, } fn item_extent(value: f32) -> f64 { @@ -247,24 +277,45 @@ pub fn run_extent(items: &[FitItem], shown: &[bool], gap: f64, section_gap: f64) } /// Decides which items stay in a strip `available` long. Everything fits and no item is `Menu`: all items show. -/// Otherwise the `Menu` items are in the menu, and the last `Free` item leaves first, one at a time, until the rest -/// and an overflow control `overflow_extent` long, set off by `gap`, fit; `Pinned` items stay even when they alone -/// are longer than `available`. Negative and non-finite lengths count as zero. +/// Otherwise the `Menu` items are in the menu, and the items with a [`FitItem::short`] form take it first, the last +/// one first, until the run fits (listed in [`Fit::short`]); a `Pinned` item shortens as a `Free` one does. Only then +/// does the last `Free` item leave, one at a time, until the rest and an overflow control `overflow_extent` long, +/// set off by `gap`, fit; `Pinned` items stay even when they alone are longer than `available`. Items that leave are +/// never listed as short. Negative and non-finite lengths count as zero. pub fn fit_items(items: &[FitItem], available: f32, gap: f32, section_gap: f32, overflow_extent: f32) -> Fit { let (available, gap, section_gap, overflow_extent) = (item_extent(available), item_extent(gap), item_extent(section_gap), item_extent(overflow_extent)); let mut shown: Vec = items.iter().map(|item| item.keep != FitKeep::Menu).collect(); if shown.iter().all(|shown| *shown) && run_extent(items, &shown, gap, section_gap) <= available { - return Fit { shown: (0..items.len()).collect(), overflow: Vec::new() }; + return Fit { shown: (0..items.len()).collect(), overflow: Vec::new(), short: Vec::new() }; } - let fits = |shown: &[bool]| { + // The overflow control takes room only while some item is in the menu; a run that every item is in, shortened, + // needs no control. + let fits = |run: &[FitItem], shown: &[bool]| { + let extent = run_extent(run, shown, gap, section_gap); + if shown.iter().all(|shown| *shown) { + return extent <= available; + } let before_control = if shown.iter().any(|shown| *shown) { gap } else { 0.0 }; - run_extent(items, shown, gap, section_gap) + before_control + overflow_extent <= available + extent + before_control + overflow_extent <= available }; - while !fits(&shown) { + // The shadow run holds each item at the extent it takes: shortened items at their `short` extent. + let mut run: Vec = items.to_vec(); + let mut short = vec![false; items.len()]; + while !fits(&run, &shown) { + let Some(last) = (0..items.len()).rev().find(|&at| shown[at] && !short[at] && items[at].short.is_some()) else { + break; + }; + short[last] = true; + if let (Some(item), Some(extent)) = (run.get_mut(last), items[last].short) { + item.extent = extent; + } + } + while !fits(&run, &shown) { let Some(last) = (0..items.len()).rev().find(|&at| shown[at] && items[at].keep == FitKeep::Free) else { break }; shown[last] = false; } let (kept, left): (Vec, Vec) = (0..items.len()).partition(|&at| shown[at]); - Fit { shown: kept, overflow: left } + let short = kept.iter().copied().filter(|&at| short[at]).collect(); + Fit { shown: kept, overflow: left, short } } diff --git a/crates/behavior/src/geometry/mod.rs b/crates/behavior/src/geometry/mod.rs index 24886f10d..434fd68df 100644 --- a/crates/behavior/src/geometry/mod.rs +++ b/crates/behavior/src/geometry/mod.rs @@ -27,5 +27,6 @@ pub use outside::outside_pieces; pub use quad::{BoxAllow, BoxDrag, BoxPart, BoxRules, BoxState, Homography, Parts, SKEW_LIMIT, ScaleRule, TransformMode, drag}; pub use selection_op::SelectionOperation; pub use snap::{ - SNAP_PX, SnapGesture, SnapKind, SnapKinds, SnapLine, SnapOptions, SnapTarget, SnapTargets, across_axis, coordinate_across, motion_across, + SNAP_PX, SnapGesture, SnapKind, SnapKinds, SnapLine, SnapOptions, SnapSuspend, SnapTarget, SnapTargets, across_axis, coordinate_across, + motion_across, }; diff --git a/crates/behavior/src/geometry/quad.rs b/crates/behavior/src/geometry/quad.rs index dcf053241..6b44078e0 100644 --- a/crates/behavior/src/geometry/quad.rs +++ b/crates/behavior/src/geometry/quad.rs @@ -100,6 +100,9 @@ pub enum ScaleRule { /// A shape or path bounds box: a corner scales by the projection of the drag on the anchor-corner diagonal, /// keeping the proportions; an edge stretches its one axis. Shape, + /// A corner keeps the proportions and ⇧ frees them, as [`ScaleRule::Proportional`]; an edge stretches its one + /// axis, as [`ScaleRule::Shape`]. The aspect link plays no part. + Corners, } /// What the box's content allows. PhotoCraft: editable type refuses distort and perspective @@ -271,8 +274,9 @@ impl BoxRules { /// The modifiers a drag of `part` acts on, from the keys held: ⌘ is dropped on a corner or /// edge the content refuses to distort or skew, the legacy scale rule ([`ScaleRule::Free`]) - /// or an unlinked aspect ratio turns ⇧ over on corners and edges, and the shape rule - /// ([`ScaleRule::Shape`]) sets ⇧ by the part alone. Mode keys ([`TransformMode::Distort`], + /// or an unlinked aspect ratio turns ⇧ over on corners and edges, the shape rule + /// ([`ScaleRule::Shape`]) sets ⇧ by the part alone, and the corners rule ([`ScaleRule::Corners`]) sets ⇧ on + /// edges only. Mode keys ([`TransformMode::Distort`], /// [`TransformMode::Perspective`]) are not added here: they are part of /// [`drag_kind`](Self::drag_kind). [`drag`] acts on these modifiers. fn drag_modifiers(&self, part: BoxPart, mods: Mods) -> Mods { @@ -285,6 +289,7 @@ impl BoxRules { } match self.scale { ScaleRule::Shape => shape_mods(part, mods), + ScaleRule::Corners => corners_mods(part, mods), scale => { let legacy = scale == ScaleRule::Free; legacy_mods(legacy, part, unlinked_mods(!self.aspect_linked, legacy, part, mods)) @@ -313,6 +318,15 @@ pub fn drag(start: &BoxState, last: &BoxState, part: BoxPart, from: Point, to: P apply_mode_drag(&g, to, rules, mods) } +/// The [`ScaleRule::Corners`] rule: a corner keeps the keys as given, so it keeps the proportions and ⇧ frees them; +/// an edge stretches its one axis whatever ⇧ and the aspect link say. ⌘ gestures are left alone. +fn corners_mods(part: BoxPart, mut mods: Mods) -> Mods { + if !mods.cmd && matches!(part, BoxPart::Edge(_)) { + mods.shift = true; + } + mods +} + /// The shape bounds box's rule: a corner keeps the proportions along the diagonal and an edge /// stretches its one axis, whatever ⇧ and the aspect link say. ⌘ gestures are left alone. fn shape_mods(part: BoxPart, mut mods: Mods) -> Mods { diff --git a/crates/behavior/src/geometry/snap.rs b/crates/behavior/src/geometry/snap.rs index 50889a4f2..b01e503a7 100644 --- a/crates/behavior/src/geometry/snap.rs +++ b/crates/behavior/src/geometry/snap.rs @@ -7,11 +7,13 @@ //! caller converts [`SNAP_PX`] screen points with the zoom. Results carry [`SnapLine`]s the //! caller draws. //! -//! Snapping is on when View › Snap is; holding Ctrl while dragging turns it off, except when Ctrl -//! is the tool's own modifier (the caller reads the keys). Smart guides follow View › Show › +//! Snapping is on when View › Snap is; holding the suspend key ([`SnapSuspend`], Ctrl by default) +//! while dragging turns it off, except when that key is the tool's own modifier (the caller reads +//! the keys). Smart guides follow View › Show › //! Smart Guides and also snap the Move tool to other layers' edges and centres. use crate::flow::Axis; +use craft_keymap::{Mods, Platform}; use kurbo::{Point, Rect, Vec2}; /// Screen points within which a position snaps (Photoshop). @@ -158,12 +160,51 @@ pub struct SnapOptions { pub selection: bool, /// View › Show › Smart Guides. pub smart_guides: bool, + /// The key that suspends snapping. + pub suspend: SnapSuspend, } impl Default for SnapOptions { /// Photoshop's defaults: everything on. fn default() -> Self { - Self { on: true, guides: true, grid: true, layers: true, document_bounds: true, selection: true, smart_guides: true } + Self { + on: true, + guides: true, + grid: true, + layers: true, + document_bounds: true, + selection: true, + smart_guides: true, + suspend: SnapSuspend::default(), + } + } +} + +/// The key that suspends snapping. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +#[non_exhaustive] +pub enum SnapSuspend { + /// The Control key. + #[default] + Control, + /// The Alt key. + Alt, +} + +impl SnapSuspend { + /// Whether this key is held in `mods` on `os`: Control is the Control key without ⌘ on macOS and Ctrl + /// elsewhere (where it is `Mods::cmd`); Alt is Alt (⌥). + pub fn is_held(self, mods: Mods, os: Platform) -> bool { + match self { + SnapSuspend::Control => { + if os.is_mac() { + mods.ctrl && !mods.cmd + } else { + mods.cmd + } + } + SnapSuspend::Alt => mods.alt, + } } } @@ -197,6 +238,15 @@ pub struct SnapTargets { /// Distances closer than this are equal. const TIE: f64 = 1e-9; +/// Whether `target` reaches a point or box spanning `across` on the other axis: a target with a span (a layer's +/// edge on its page) only where the two overlap; a target without a span, or a query without an extent, always. +fn reaches(target: &SnapTarget, across: Option<(f64, f64)>) -> bool { + match (target.span, across) { + (Some((a, b)), Some((lo, hi))) => lo <= b && a <= hi, + _ => true, + } +} + /// The line through `target` reaching the snapped object at `a..b` along the line; a target /// without a span stays full height. fn line(target: &SnapTarget, a: f64, b: f64) -> SnapLine { @@ -291,8 +341,15 @@ impl SnapTargets { /// The nearest target of a kind in `kinds` among the lines that run `along` an axis, within `tolerance` of /// `value` across them; [`SnapTargets::nearest`] is this with [`SnapKinds::ALL`]. pub fn nearest_of(&self, along: Axis, value: f64, tolerance: f64, kinds: SnapKinds) -> Option { + self.nearest_within(along, value, None, tolerance, kinds) + } + + /// [`nearest_of`](Self::nearest_of) that also takes the query's extent `across` the other axis: a target with a + /// span catches only a point or box overlapping that span there; without `across`, or for a target without a + /// span, it is `nearest_of`. + pub fn nearest_within(&self, along: Axis, value: f64, across: Option<(f64, f64)>, tolerance: f64, kinds: SnapKinds) -> Option { let mut best: Option<(f64, SnapTarget)> = None; - for target in self.targets.iter().filter(|t| t.along == along && kinds.contains(t.kind)) { + for target in self.targets.iter().filter(|t| t.along == along && kinds.contains(t.kind) && reaches(t, across)) { let distance = (target.position - value).abs(); if distance > tolerance { continue; @@ -325,11 +382,11 @@ impl SnapTargets { pub fn snap_point_of(&self, point: Point, tolerance: f64, kinds: SnapKinds) -> (Point, Vec) { let mut out = point; let mut lines = Vec::new(); - if let Some(t) = self.nearest_of(Axis::Y, point.x, tolerance, kinds) { + if let Some(t) = self.nearest_within(Axis::Y, point.x, Some((point.y, point.y)), tolerance, kinds) { out.x = t.position; lines.push(line(&t, point.y, point.y)); } - if let Some(t) = self.nearest_of(Axis::X, point.y, tolerance, kinds) { + if let Some(t) = self.nearest_within(Axis::X, point.y, Some((out.x, out.x)), tolerance, kinds) { out.y = t.position; lines.push(line(&t, out.x, out.x)); } @@ -359,7 +416,7 @@ impl SnapTargets { let anchors = [lo, hi, (lo + hi) / 2.0]; let mut best: Option = None; for anchor in anchors { - if let Some(t) = self.nearest_of(along, anchor, tolerance, kinds) { + if let Some(t) = self.nearest_within(along, anchor, Some(other), tolerance, kinds) { let d = t.position - anchor; if best.is_none_or(|b| d.abs() < b.abs() - TIE) { best = Some(d); @@ -376,7 +433,7 @@ impl SnapTargets { let hit = self .targets .iter() - .filter(|t| t.along == along && kinds.contains(t.kind) && (t.position - moved).abs() < 1e-6) + .filter(|t| t.along == along && kinds.contains(t.kind) && reaches(t, Some(other)) && (t.position - moved).abs() < 1e-6) .min_by_key(|t| u8::from(t.kind != SnapKind::Guide)); if let Some(t) = hit { lines.push(line(t, other.0, other.1)); diff --git a/crates/behavior/src/intent.rs b/crates/behavior/src/intent.rs index 6f9c6c5c3..ea406da38 100644 --- a/crates/behavior/src/intent.rs +++ b/crates/behavior/src/intent.rs @@ -177,6 +177,8 @@ pub enum Intent { Text(Arc), /// Tab in a component whose key filter keeps it. Tab, + /// Shift+Tab in a document canvas's editor part that keeps Tab. + BackTab, /// An edit command the focused component lists. Edit(EditCommand), /// Switch to the next or previous page. diff --git a/crates/behavior/src/item_layout.rs b/crates/behavior/src/item_layout.rs index 0332d57e8..9c26a1c0e 100644 --- a/crates/behavior/src/item_layout.rs +++ b/crates/behavior/src/item_layout.rs @@ -39,6 +39,12 @@ pub trait ItemLayout { None } + /// `NavShape::RaggedGrid`: the columns a vertical move from row `from` to row `to` shifts the column by, when the rows + /// are offset against each other; 0 when they line up. + fn column_shift(&self, _from: usize, _to: usize) -> isize { + 0 + } + /// Whether item `at` takes a place in the layout; a hidden item (in a closed group) cannot take the lead. fn shown(&self, _at: usize) -> bool { true diff --git a/crates/behavior/src/item_source.rs b/crates/behavior/src/item_source.rs index 9908e16f6..871e43d4c 100644 --- a/crates/behavior/src/item_source.rs +++ b/crates/behavior/src/item_source.rs @@ -178,6 +178,10 @@ impl NavOutline for Outline<'_, K> { self.layout.and_then(|layout| layout.row_len(row)) } + fn column_shift(&self, from: usize, to: usize) -> isize { + self.layout.map_or(0, |layout| layout.column_shift(from, to)) + } + fn columns(&self) -> usize { self.columns } diff --git a/crates/behavior/src/nav/step.rs b/crates/behavior/src/nav/step.rs index 8b20ca291..bb93f2df4 100644 --- a/crates/behavior/src/nav/step.rs +++ b/crates/behavior/src/nav/step.rs @@ -64,6 +64,12 @@ pub trait NavOutline { None } + /// `RaggedGrid`: how many columns a vertical move from row `from` to row `to` shifts the column by, for rows that are + /// offset against each other (a honeycomb's). 0 for rows that line up. + fn column_shift(&self, _from: usize, _to: usize) -> isize { + 0 + } + /// `Cell`: the cells of every position (a row of a sheet). fn columns(&self) -> usize { 1 @@ -325,8 +331,9 @@ fn ragged(outline: &dyn NavOutline, state: &NavState, lead: usize, mv: NavMove) let Some((row, column, _)) = locate(outline, lead) else { return NavStep::Unhandled }; let rows = (0..).take_while(|&r| outline.row_len(r).is_some()).count(); // A row without a position that takes the lead (a closed group's) is passed over in the move's direction. - let toward = |rows: Vec| moved(rows.into_iter().find_map(|row| ragged_at(outline, row, column))); - let vertical = |to: Option| moved(to.and_then(|row| ragged_at(outline, row, column))); + let shifted = |to: usize| column.saturating_add_signed(outline.column_shift(row, to)); + let toward = |rows: Vec| moved(rows.into_iter().find_map(|to| ragged_at(outline, to, shifted(to)))); + let vertical = |to: Option| moved(to.and_then(|to| ragged_at(outline, to, shifted(to)))); match mv { NavMove::Back => moved(neighbour(outline, state, lead, false)), NavMove::Forward => moved(neighbour(outline, state, lead, true)), diff --git a/crates/behavior/tests/fit.rs b/crates/behavior/tests/fit.rs index 7ec8b3f1b..08cd37712 100644 --- a/crates/behavior/tests/fit.rs +++ b/crates/behavior/tests/fit.rs @@ -1,6 +1,6 @@ -//! The fit rules: tab widths (`fit`). +//! The fit rules: tab widths (`fit`) and strip items (`fit_items`). -use craft_behavior::fit::{TabFit, fit}; +use craft_behavior::fit::{FitItem, FitKeep, TabFit, fit, fit_items}; fn total(fit: &TabFit) -> f32 { fit.shown.iter().map(|&(_, width)| width).sum::() + fit.overflow_width @@ -25,6 +25,45 @@ fn overflow_retains_selection_and_partitions_all_tabs() { } } +/// Guards the shortening stage of `fit_items`: short forms go last first, before any free item leaves, a leaving item +/// is not reported short, and items without a short form fit exactly as before (the menu bar, bar items and +/// breadcrumbs build no short forms). +#[test] +fn short_items_shorten_from_the_end_before_any_item_leaves() { + let item = |extent| FitItem::new(extent, 0, FitKeep::Free); + let shortening = [item(50.0).short(20.0), item(50.0), item(50.0).short(20.0)]; + let plain = [item(50.0), item(50.0), item(50.0)]; + let at = |items: &[FitItem], available| fit_items(items, available, 0.0, 0.0, 10.0); + + let wide = at(&shortening, 150.0); + assert!(wide.short.is_empty() && wide.overflow.is_empty(), "a run that fits keeps every full form: {wide:?}"); + + let narrower = at(&shortening, 120.0); + assert!(narrower.overflow.is_empty(), "shortening comes before any item leaves: {narrower:?}"); + assert!(narrower.short.contains(&2) && !narrower.short.contains(&0), "the last short item goes first: {narrower:?}"); + + let narrow = at(&shortening, 90.0); + assert!(narrow.overflow.is_empty(), "every short form is taken before an item leaves: {narrow:?}"); + assert!(narrow.short.contains(&0) && narrow.short.contains(&2), "then the earlier ones: {narrow:?}"); + + let narrowest = at(&shortening, 80.0); + assert!(narrowest.overflow.contains(&2) && narrowest.shown.contains(&0), "then the last free item leaves: {narrowest:?}"); + assert!(narrowest.short.iter().all(|i| narrowest.shown.contains(i)), "a leaving item is not short: {narrowest:?}"); + + for available in [0.0, 40.0, 80.0, 90.0, 120.0, 150.0] { + let fit = at(&plain, available); + assert!(fit.short.is_empty(), "no short form, no short item: {fit:?}"); + let shown = shortening.len() - fit.overflow.len(); + assert_eq!(fit.shown, (0..shown).collect::>(), "items without short forms leave from the end: {fit:?}"); + } + assert!(!at(&plain, 120.0).overflow.is_empty(), "without short forms the narrower run overflows"); + + let pinned = [FitItem::new(80.0, 0, FitKeep::Pinned).short(30.0), FitItem::new(90.0, 0, FitKeep::Pinned).short(30.0)]; + let squeezed = fit_items(&pinned, 40.0, 0.0, 0.0, 0.0); + assert!(squeezed.overflow.is_empty(), "pinned items never leave: {squeezed:?}"); + assert_eq!(squeezed.short.len(), 2, "pinned items shorten as free ones do: {squeezed:?}"); +} + #[test] fn kept_selection_keeps_its_width_and_overflow_starts_at_the_end() { let natural = [80.0, 90.0, 85.0, 95.0, 70.0]; diff --git a/crates/behavior/tests/geometry/quad.rs b/crates/behavior/tests/geometry/quad.rs index 2d8f74416..e716f2511 100644 --- a/crates/behavior/tests/geometry/quad.rs +++ b/crates/behavior/tests/geometry/quad.rs @@ -92,6 +92,29 @@ fn a_distort_corner_stops_before_the_box_folds() { assert_eq!(q, [p(5.0, 5.0), p(1.0, 0.0), p(2.0, 0.0), p(3.0, 0.0)]); } +#[test] +fn a_corners_box_keeps_a_corner_proportional_until_shift_and_stretches_an_edge_on_one_axis() { + let linked = BoxRules::default().with_scale(ScaleRule::Corners); + let unlinked = linked.with_aspect_linked(false); + for rules in [&linked, &unlinked] { + // A plain corner keeps the proportions along the diagonal, whatever the aspect link says. + let kept = dragged(p(100.0, 50.0), p(200.0, 60.0), Mods::NONE, rules); + assert!(corners_are(&kept, 0.0, 0.0, 184.0, 92.0), "{:?}", kept.quad); + // ⇧ frees them. + let freed = dragged(p(100.0, 50.0), p(200.0, 60.0), Mods::SHIFT, rules); + assert!(corners_are(&freed, 0.0, 0.0, 200.0, 60.0), "{:?}", freed.quad); + // The right edge's middle stretches only x, with ⇧ or without. + for mods in [Mods::NONE, Mods::SHIFT] { + let edge = dragged(p(100.0, 25.0), p(150.0, 40.0), mods, rules); + assert!(corners_are(&edge, 0.0, 0.0, 150.0, 50.0), "{mods:?}: {:?}", edge.quad); + } + } + // A ⌘ corner distorts as it does under the default rule: the gesture is left alone. + let distorted = dragged(p(100.0, 50.0), p(200.0, 60.0), Mods::CMD, &linked); + assert_eq!(distorted, dragged(p(100.0, 50.0), p(200.0, 60.0), Mods::CMD, &BoxRules::default())); + assert!(near(distorted.quad[2], p(200.0, 60.0)) && near(distorted.quad[0], p(0.0, 0.0)), "{:?}", distorted.quad); +} + #[test] fn a_shape_box_scales_corners_by_the_diagonal_and_edges_on_one_axis() { // The reference measurement: the bounds 100,98–723,451, the bottom-right handle dragged by diff --git a/crates/behavior/tests/geometry/snap.rs b/crates/behavior/tests/geometry/snap.rs index 3df1bcb57..0a8c44c09 100644 --- a/crates/behavior/tests/geometry/snap.rs +++ b/crates/behavior/tests/geometry/snap.rs @@ -2,7 +2,7 @@ use craft_behavior::Axis; use craft_behavior::geometry::{SnapKind, SnapKinds, SnapTarget, SnapTargets}; -use kurbo::{Rect, Vec2}; +use kurbo::{Point, Rect, Vec2}; fn guide(along: Axis, position: f64) -> SnapTarget { SnapTarget::new(along, position, SnapKind::Guide) @@ -31,3 +31,28 @@ fn a_moving_rect_skips_the_kinds_left_out() { let (offset, lines) = targets.snap_rect_of(rect, 4.0, SnapKinds::ALL.without(SnapKind::Selection)); assert_eq!((offset, lines.len()), (Vec2::ZERO, 0), "a moved selection ignores the selection's edges"); } + +#[test] +fn a_spanned_target_catches_only_a_box_that_overlaps_its_span_on_the_other_axis() { + let mut targets = SnapTargets::new(); + // A layer on page 2: its left edge at x 100 spans y 1200 to 1300. + targets.add_rect(Rect::new(100.0, 1200.0, 300.0, 1300.0), SnapKind::LayerEdge, SnapKind::LayerCenter); + targets.add(guide(Axis::Y, 400.0)); + + // Over page 1, 2 units right of the edge's line but far from its span: no snap. + let (offset, lines) = targets.snap_rect(Rect::new(102.0, 50.0, 150.0, 90.0), 4.0); + assert_eq!((offset, lines.len()), (Vec2::ZERO, 0), "a box over page 1 is not caught by page 2's layer"); + // Beside the layer on page 2: caught. + let (offset, _) = targets.snap_rect(Rect::new(102.0, 1210.0, 150.0, 1240.0), 4.0); + assert_eq!(offset.x, -2.0, "a box overlapping the span snaps to the edge"); + + // A point the same way. + let (at, lines) = targets.snap_point(Point::new(102.0, 60.0), 4.0); + assert_eq!((at, lines.len()), (Point::new(102.0, 60.0), 0)); + let (at, _) = targets.snap_point(Point::new(102.0, 1250.0), 4.0); + assert_eq!(at.x, 100.0); + + // A full-height guide catches a box anywhere along it. + let (offset, _) = targets.snap_rect(Rect::new(402.0, 50.0, 450.0, 90.0), 4.0); + assert_eq!(offset.x, -2.0, "an unspanned target is unchanged"); +} diff --git a/crates/browse/src/places/cache.rs b/crates/browse/src/places/cache.rs index 2a6da5e62..72a0b9d93 100644 --- a/crates/browse/src/places/cache.rs +++ b/crates/browse/src/places/cache.rs @@ -1,4 +1,4 @@ -//! `FolderCache`: roots and subfolder listings made in jobs, kept until they go stale. +//! `FolderCache`: roots, subfolder and entries listings made in jobs, kept until they go stale. use std::collections::{HashMap, HashSet}; use std::path::{Path, PathBuf}; @@ -7,7 +7,7 @@ use std::sync::Arc; use craft_host::queue::{JobQueue, Priority, QueueOptions}; use craft_host::{Jobs, Wake}; -use super::{Directories, Folder, StandardFolder, Volume}; +use super::{Directories, Entry, Folder, FolderEntries, StandardFolder, Volume}; /// The standard folders and volumes, from one job. #[derive(Clone, Debug, Default, PartialEq, Eq)] @@ -29,11 +29,28 @@ pub enum Listing<'a> { Failed(&'a str), } +/// One folder's files and folders as the cache has them. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Entries<'a> { + /// Not listed yet; a job is queued. + Loading, + /// The entries, and whether the listing stopped at its limit. + Ready { + /// The files and folders. + entries: &'a [Entry], + /// The listing stopped at the limit before the folder ended. + truncated: bool, + }, + /// The folder couldn't be listed; the system's message. + Failed(&'a str), +} + /// What a listing job returns. enum Found { Roots(Roots), Subfolders(Result, String>), Unlisted(Vec), + Entries(Result), } /// Which listing a job makes. @@ -42,6 +59,8 @@ enum Job { Roots, Subfolders(PathBuf), Unlisted(PathBuf), + /// A folder's files and folders, up to a limit of entries read. + Entries(PathBuf, usize), } /// Folder listings for a places tree, made in jobs on a [`JobQueue`] (lanes from @@ -62,6 +81,8 @@ pub struct FolderCache { roots: Option, listings: HashMap, String>, bool)>, unlisted: HashMap>, + /// Files and folders by (folder, limit), each with its stale flag like `listings`. + entries: HashMap<(PathBuf, usize), (Result, bool)>, stale_roots: bool, /// What this pass asked for, for [`finish_pass`](Self::finish_pass). asked: HashSet, @@ -82,6 +103,7 @@ impl FolderCache { roots: None, listings: HashMap::new(), unlisted: HashMap::new(), + entries: HashMap::new(), stale_roots: false, asked: HashSet::new(), generations: HashMap::new(), @@ -118,6 +140,31 @@ impl FolderCache { } } + /// `folder`'s files and folders up to `limit` entries, listed in a job like + /// [`subfolders`](Self::subfolders); the cache keys a listing by folder and limit. + pub fn entries(&mut self, folder: &Path, limit: usize) -> Entries<'_> { + // ui-egui: crates/ui-egui/src/file_browser.rs:58 (`list_dir`, read in the pass there; in a job here). + self.drain(); + let key = (folder.to_path_buf(), limit); + let job = Job::Entries(key.0.clone(), limit); + self.asked.insert(job.clone()); + match self.entries.get(&key).map(|(_, stale)| *stale) { + None => self.submit(job, Priority::VISIBLE), + Some(true) => self.submit(job, Priority::NEAR), + Some(false) => {} + } + self.held_entries(folder, limit).unwrap_or(Entries::Loading) + } + + /// The listing of `folder` at `limit` the cache holds now, without taking in finished jobs or queueing one: for a + /// reader that cannot borrow the cache mutably (automation). `None` when none is held. + pub fn held_entries(&self, folder: &Path, limit: usize) -> Option> { + self.entries.get(&(folder.to_path_buf(), limit)).map(|(result, _)| match result { + Ok(found) => Entries::Ready { entries: &found.entries, truncated: found.truncated }, + Err(message) => Entries::Failed(message), + }) + } + /// The hidden folders on the way to `path` ([`Directories::unlisted_ancestors`]); `None` until /// listed. pub fn unlisted(&mut self, path: &Path) -> Option<&[PathBuf]> { @@ -141,17 +188,31 @@ impl FolderCache { for (_, stale) in self.listings.values_mut() { *stale = true; } + for (_, stale) in self.entries.values_mut() { + *stale = true; + } } - /// Marks one folder's listing stale. + /// Marks one folder's listings stale: its subfolders and its entries at every limit. pub fn refresh_folder(&mut self, folder: &Path) { // new: the tree calls it when a row opens. - if let Some(generation) = self.generations.get_mut(&Job::Subfolders(folder.to_path_buf())) { - *generation += 1; + for (job, generation) in &mut self.generations { + let of_folder = match job { + Job::Subfolders(path) | Job::Entries(path, _) => path == folder, + Job::Roots | Job::Unlisted(_) => false, + }; + if of_folder { + *generation += 1; + } } if let Some((_, stale)) = self.listings.get_mut(folder) { *stale = true; } + for ((path, _), (_, stale)) in &mut self.entries { + if path == folder { + *stale = true; + } + } } /// Drops the listings of folders not asked for since the last call, and cancels their jobs @@ -161,6 +222,7 @@ impl FolderCache { let asked = std::mem::take(&mut self.asked); self.listings.retain(|path, _| asked.contains(&Job::Subfolders(path.clone()))); self.unlisted.retain(|path, _| asked.contains(&Job::Unlisted(path.clone()))); + self.entries.retain(|(path, limit), _| asked.contains(&Job::Entries(path.clone(), *limit))); self.queue.reprioritize(|job, priority| asked.contains(job).then_some(priority)); self.generations.retain(|job, _| *job == Job::Roots || asked.contains(job)); } @@ -178,6 +240,7 @@ impl FolderCache { Job::Roots => Found::Roots(Roots { standard: directories.standard(), volumes: directories.volumes() }), Job::Subfolders(folder) => Found::Subfolders(directories.subfolders(&folder, cancel).map_err(|e| e.to_string())), Job::Unlisted(path) => Found::Unlisted(directories.unlisted_ancestors(&path)), + Job::Entries(folder, limit) => Found::Entries(directories.entries(&folder, limit, cancel).map_err(|e| e.to_string())), }; (generation, found) }); @@ -203,6 +266,9 @@ impl FolderCache { (Job::Unlisted(path), Found::Unlisted(found)) => { self.unlisted.insert(path, found); } + (Job::Entries(folder, limit), Found::Entries(result)) => { + self.entries.insert((folder, limit), (result, !current)); + } _ => {} } } diff --git a/crates/browse/src/places/directories.rs b/crates/browse/src/places/directories.rs index 0db5c7d48..c458ea082 100644 --- a/crates/browse/src/places/directories.rs +++ b/crates/browse/src/places/directories.rs @@ -50,6 +50,26 @@ pub struct Folder { pub name: String, } +/// A file or folder in a [`FolderEntries`] listing. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Entry { + /// Its path. + pub path: PathBuf, + /// Its name. + pub name: String, + /// Whether it is a folder. + pub folder: bool, +} + +/// The files and folders of one folder, as [`Directories::entries`] lists them. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct FolderEntries { + /// The entries read, hidden ones left out, in `natural_cmp` order of their names. + pub entries: Vec, + /// The listing stopped at the limit before the folder ended. + pub truncated: bool, +} + /// The folder lookups a places tree needs (owner question 4: a small trait in this crate, with a /// system implementation and a fake). Every call can block on a slow or network disk: /// [`FolderCache`](super::FolderCache) calls them only in jobs. @@ -70,6 +90,11 @@ pub trait Directories: Send + Sync { /// The hidden folders among `path` and its ancestors, innermost first (LightCraft's /// `unlisted_ancestors`); a tree never opens through one. fn unlisted_ancestors(&self, path: &Path) -> Vec; + + /// The files and folders of `folder`, with the hidden rule and the `natural_cmp` order of + /// [`subfolders`](Self::subfolders). Stops after `limit` entries read and reports + /// `truncated`; checks `cancel` between entries. + fn entries(&self, folder: &Path, limit: usize, cancel: &Cancel) -> io::Result; } /// [`Directories`] over the file system. @@ -79,7 +104,7 @@ pub trait Directories: Send + Sync { /// - `volumes`: macOS the entries of `/Volumes`; Linux `/media/$USER/*`, `/run/media/$USER/*` and /// `/mnt/*`; Windows the drive letters `A:` to `Z:` whose root exists. `network` and `removable` /// stay false where `std` can't tell (a platform service may add them later). -/// - `subfolders`: `std::fs::read_dir`, as the trait says. +/// - `subfolders` and `entries`: `std::fs::read_dir`, as the trait says. #[cfg(not(target_arch = "wasm32"))] #[derive(Clone, Copy, Debug, Default)] pub struct SystemDirectories; @@ -162,6 +187,33 @@ impl Directories for SystemDirectories { Ok(out) } + fn entries(&self, folder: &Path, limit: usize, cancel: &Cancel) -> io::Result { + // ui-egui: crates/ui-egui/src/file_browser.rs:58 (`list_dir`: `MAX_SCANNED` entries read, hidden left out, links to folders are folders). + let mut out = FolderEntries::default(); + for (read, entry) in std::fs::read_dir(folder)?.enumerate() { + if cancel.is_cancelled() { + break; + } + // Hidden entries count as read too: the limit bounds the time a huge folder takes. + if read >= limit { + out.truncated = true; + break; + } + let Ok(entry) = entry else { continue }; + let path = entry.path(); + let folder = match entry.file_type() { + Ok(t) if t.is_symlink() => path.is_dir(), + Ok(t) => t.is_dir(), + Err(_) => continue, + }; + if !is_hidden(&path, || entry.metadata()) { + out.entries.push(Entry { name: entry.file_name().to_string_lossy().into_owned(), path, folder }); + } + } + out.entries.sort_by(|a, b| craft_platform::open::natural_cmp(&a.name, &b.name)); + Ok(out) + } + fn unlisted_ancestors(&self, path: &Path) -> Vec { // lightcraft: crates/ui-egui/src/panels/left/local.rs:201 (`unlisted_ancestors`). path.ancestors().filter(|p| is_hidden(p, || std::fs::symlink_metadata(p))).map(Path::to_path_buf).collect() @@ -177,7 +229,7 @@ fn home() -> Option { // lightcraft: crates/engine/src/walk.rs:56 (`hidden_with_metadata`). #[cfg(not(target_arch = "wasm32"))] fn is_hidden(path: &Path, metadata: impl FnOnce() -> io::Result) -> bool { - if path.file_name().is_some_and(|n| n.to_string_lossy().starts_with('.')) { + if dotted(path) { return true; } #[cfg(windows)] @@ -199,6 +251,12 @@ fn is_hidden(path: &Path, metadata: impl FnOnce() -> io::Result