diff --git a/Cargo.lock b/Cargo.lock index 5c8bf76c6c..61228dc601 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2264,7 +2264,6 @@ version = "0.1.0" dependencies = [ "craft-behavior", "craft-cms", - "craft-drawingml", "craft-host", "craft-i18n", "craft-keymap", @@ -4527,7 +4526,6 @@ name = "craft-ui-canvas" version = "0.1.0" dependencies = [ "craft-behavior", - "craft-font-catalog", "craft-host", "craft-i18n", "craft-keymap", @@ -5727,6 +5725,7 @@ dependencies = [ [[package]] name = "ecolor" version = "0.37.0" +source = "git+https://github.com/storytold/egui.git?rev=14c39fed181756be6f357c284354e0ab55b64443#14c39fed181756be6f357c284354e0ab55b64443" dependencies = [ "bytemuck", "emath", @@ -5782,6 +5781,7 @@ dependencies = [ [[package]] name = "eframe" version = "0.37.0" +source = "git+https://github.com/storytold/egui.git?rev=14c39fed181756be6f357c284354e0ab55b64443#14c39fed181756be6f357c284354e0ab55b64443" dependencies = [ "ahash", "bytemuck", @@ -5816,6 +5816,7 @@ dependencies = [ [[package]] name = "egui" version = "0.37.0" +source = "git+https://github.com/storytold/egui.git?rev=14c39fed181756be6f357c284354e0ab55b64443#14c39fed181756be6f357c284354e0ab55b64443" dependencies = [ "accesskit", "ahash", @@ -5834,6 +5835,7 @@ dependencies = [ [[package]] name = "egui-wgpu" version = "0.37.0" +source = "git+https://github.com/storytold/egui.git?rev=14c39fed181756be6f357c284354e0ab55b64443#14c39fed181756be6f357c284354e0ab55b64443" dependencies = [ "ahash", "bytemuck", @@ -5852,6 +5854,7 @@ dependencies = [ [[package]] name = "egui-winit" version = "0.37.0" +source = "git+https://github.com/storytold/egui.git?rev=14c39fed181756be6f357c284354e0ab55b64443#14c39fed181756be6f357c284354e0ab55b64443" dependencies = [ "block2 0.6.2", "bytemuck", @@ -5871,6 +5874,7 @@ dependencies = [ [[package]] name = "egui_glow" version = "0.37.0" +source = "git+https://github.com/storytold/egui.git?rev=14c39fed181756be6f357c284354e0ab55b64443#14c39fed181756be6f357c284354e0ab55b64443" dependencies = [ "bytemuck", "egui", @@ -5883,6 +5887,7 @@ dependencies = [ [[package]] name = "egui_kittest" version = "0.37.0" +source = "git+https://github.com/storytold/egui.git?rev=14c39fed181756be6f357c284354e0ab55b64443#14c39fed181756be6f357c284354e0ab55b64443" dependencies = [ "eframe", "egui", @@ -5959,6 +5964,7 @@ dependencies = [ [[package]] name = "emath" version = "0.37.0" +source = "git+https://github.com/storytold/egui.git?rev=14c39fed181756be6f357c284354e0ab55b64443#14c39fed181756be6f357c284354e0ab55b64443" dependencies = [ "bytemuck", ] @@ -6031,6 +6037,7 @@ dependencies = [ [[package]] name = "epaint" version = "0.37.0" +source = "git+https://github.com/storytold/egui.git?rev=14c39fed181756be6f357c284354e0ab55b64443#14c39fed181756be6f357c284354e0ab55b64443" dependencies = [ "ahash", "bytemuck", @@ -6056,6 +6063,7 @@ dependencies = [ [[package]] name = "epaint_default_fonts" version = "0.37.0" +source = "git+https://github.com/storytold/egui.git?rev=14c39fed181756be6f357c284354e0ab55b64443#14c39fed181756be6f357c284354e0ab55b64443" [[package]] name = "equator" @@ -15403,15 +15411,19 @@ dependencies = [ [[patch.unused]] name = "egui_demo_lib" version = "0.37.0" +source = "git+https://github.com/storytold/egui.git?rev=14c39fed181756be6f357c284354e0ab55b64443#14c39fed181756be6f357c284354e0ab55b64443" [[patch.unused]] name = "egui_extras" version = "0.37.0" +source = "git+https://github.com/storytold/egui.git?rev=14c39fed181756be6f357c284354e0ab55b64443#14c39fed181756be6f357c284354e0ab55b64443" [[patch.unused]] name = "egui_inspection" version = "0.37.0" +source = "git+https://github.com/storytold/egui.git?rev=14c39fed181756be6f357c284354e0ab55b64443#14c39fed181756be6f357c284354e0ab55b64443" [[patch.unused]] name = "egui_system_font_provider" version = "0.37.0" +source = "git+https://github.com/storytold/egui.git?rev=14c39fed181756be6f357c284354e0ab55b64443#14c39fed181756be6f357c284354e0ab55b64443" diff --git a/Cargo.toml b/Cargo.toml index 136df2be6f..015b02802b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -326,20 +326,20 @@ linesweeper = { path = "vendor/linesweeper" } vello_common = { path = "vendor/vello_common" } vello_cpu = { path = "vendor/vello_cpu" } kurbo = { path = "vendor/kurbo" } -ecolor = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" } -emath = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" } -epaint = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" } -epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" } -egui = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" } -egui-winit = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" } -egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" } -egui_glow = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" } -egui_extras = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" } -egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" } -egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" } -eframe = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" } -egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" } -egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" } +ecolor = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" } +emath = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" } +epaint = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" } +epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" } +egui = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" } +egui-winit = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" } +egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" } +egui_glow = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" } +egui_extras = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" } +egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" } +egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" } +eframe = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" } +egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" } +egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" } winit = { git = "https://github.com/storytold/winit.git", rev = "a517b3846ee8457d84ee4975110bfda6797c44dc" } # symphonia's FLAC decoder restores LPC samples as `residual + (prediction as i32)`. In a valid diff --git a/crates/automation/src/client_tests.rs b/crates/automation/src/client_tests.rs index cd14eac5d6..83f065ee59 100644 --- a/crates/automation/src/client_tests.rs +++ b/crates/automation/src/client_tests.rs @@ -128,7 +128,9 @@ fn a_refusal_waiting_at_sign_in_is_the_reason_connect_gives() { reader.read_line(&mut line).ok().filter(|&read| read > 0).map(|_| line) }); let stream = std::net::TcpStream::connect(addr).unwrap(); - stream.set_read_timeout(Some(std::time::Duration::from_secs(5))).unwrap(); + // A hang guard only: the server thread writes the refusal without waiting on a timer, so a run that works never + // reaches the limit. + stream.set_read_timeout(Some(std::time::Duration::from_secs(60))).unwrap(); assert!(stream.peek(&mut [0]).unwrap() > 0, "the refusal is waiting before the sign-in"); let signed = ControlClient::over(stream).unwrap().sign_in(TOKEN); assert_eq!(signed.err(), Some(ConnectError::Refused("connection limit reached".into()))); diff --git a/crates/automation/src/control.rs b/crates/automation/src/control.rs index b12ec5fcea..0950de678f 100644 --- a/crates/automation/src/control.rs +++ b/crates/automation/src/control.rs @@ -141,8 +141,8 @@ pub enum Reply { AfterHeldOk { /// The dialog whose OK is held. dialog: DialogId, - /// Which open of the dialog ([`DialogHost::open_serial`]): a later open of the same dialog - /// is not the one the request confirmed. + /// Which open of the dialog the request confirmed ([`DialogHost::held_state_with_open_serial`]): + /// a later open of the same dialog, or another dialog with its ID, is not that one. open: u64, /// The app's refusal of the dialog's previous OK, when this confirm filed OK again after it: /// the earlier confirms still held for this open are answered with it. @@ -356,13 +356,12 @@ impl ControlChannel { /// dialog the app accepted; calling it more than once in a pass is harmless. pub fn poll_held(&mut self, host: &DialogHost) { self.held_waiters.retain(|(dialog, open, reply)| { - let answer = match host.held_state(*dialog) { - _ if host.open_serial(*dialog) != Some(*open) => { - json!({"ok": false, "error": "the dialog closed while its OK waited for the app's answer"}) - } - Some(HeldOk::Waiting) => return true, - Some(HeldOk::Accepted) => json!({"ok": true, "result": null}), - Some(HeldOk::Refused(reason)) => json!({"ok": false, "error": reason.as_str()}), + let current = host.held_state_with_open_serial(*dialog).filter(|(serial, _)| serial == open); + let answer = match current { + None => json!({"ok": false, "error": "the dialog closed while its OK waited for the app's answer"}), + Some((_, Some(HeldOk::Waiting))) => return true, + Some((_, Some(HeldOk::Accepted))) => json!({"ok": true, "result": null}), + Some((_, Some(HeldOk::Refused(reason)))) => json!({"ok": false, "error": reason.as_str()}), _ => json!({"ok": false, "error": "the app refused OK"}), }; let _ = reply.send(answer); diff --git a/crates/automation/src/dialogs.rs b/crates/automation/src/dialogs.rs index 749626cc61..7e8a544f88 100644 --- a/crates/automation/src/dialogs.rs +++ b/crates/automation/src/dialogs.rs @@ -65,8 +65,11 @@ pub fn dialog_reply(host: &mut DialogHost, ctx: &Context, method: &str, params: _ => None, }; let result = dialog_method(host, ctx, method, params)?; - let held = named.filter(|&id| method == "ui.dialog.confirm" && result.is_ok() && host.held_state(id) == Some(HeldOk::Waiting)); - Some(match held.and_then(|id| Some((id, host.open_serial(id)?))) { + let held = named.filter(|_| method == "ui.dialog.confirm" && result.is_ok()).and_then(|id| { + let (open, state) = host.held_state_with_open_serial(id)?; + matches!(state, Some(HeldOk::Waiting)).then_some((id, open)) + }); + Some(match held { Some((dialog, open)) => Reply::AfterHeldOk { dialog, open, refused }, None => Reply::from_result(result), }) diff --git a/crates/automation/tests/it/control.rs b/crates/automation/tests/it/control.rs index 7d6a31c6a1..25e1a3a2e7 100644 --- a/crates/automation/tests/it/control.rs +++ b/crates/automation/tests/it/control.rs @@ -118,6 +118,10 @@ fn a_finished_job_answers_only_its_own_waiters() { const TOKEN: &str = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"; +/// How long a test waits for a reply, a close or a request before it fails as hung. A server that works sends each +/// one without waiting on a timer, so the result does not depend on this limit or on how fast the machine runs. +const HANG: Duration = Duration::from_secs(60); + fn read_json(reader: &mut impl BufRead) -> Option { let mut line = String::new(); (reader.read_line(&mut line).ok()? > 0).then(|| serde_json::from_str(&line).expect("a JSON line")) @@ -145,9 +149,9 @@ fn an_unauthenticated_connection_is_closed_at_the_deadline_whatever_it_sends() { let options = ServeOptions { limits: ServerLimits::default().auth_deadline(Duration::from_secs(10)), clock, ended: Some(ended) }; let (rx, server) = server::serve_with(TcpListener::bind("127.0.0.1:0").expect("bound"), TOKEN.into(), host(), options).expect("started"); let mut stream = TcpStream::connect(server.addr).expect("connected"); - stream.set_read_timeout(Some(Duration::from_secs(5))).expect("timeout"); + stream.set_read_timeout(Some(HANG)).expect("timeout"); let mut reader = BufReader::new(stream.try_clone().expect("cloned")); - clock_read.recv_timeout(Duration::from_secs(5)).expect("the connection set its deadline"); + clock_read.recv_timeout(HANG).expect("the connection set its deadline"); // Blank lines and the start of a line, sent while the deadline is ahead: none is a frame the handshake refuses. stream.write_all(b"\n \n ").expect("written"); *at.lock().expect("the clock") = start + Duration::from_secs(10); @@ -206,9 +210,9 @@ fn serve_counting_ends() -> (Receiver, server::Listening, Receiv fn nothing_more_dispatched(rx: &Receiver, server: server::Listening, ended: &Receiver<()>, connections: usize) -> bool { drop(server); for _ in 0..connections { - ended.recv_timeout(Duration::from_secs(5)).expect("a connection ended"); + ended.recv_timeout(HANG).expect("a connection ended"); } - rx.recv_timeout(Duration::from_secs(5)).err() == Some(RecvTimeoutError::Disconnected) + rx.recv_timeout(HANG).err() == Some(RecvTimeoutError::Disconnected) } /// With `MAX_CONNECTIONS` connections open, the next one is told `connection limit reached` and closed; once one of @@ -218,7 +222,7 @@ fn connections_past_the_limit_are_refused_with_the_reason() { let (rx, server, ended) = serve_counting_ends(); let connect = || { let stream = TcpStream::connect(server.addr).expect("connected"); - stream.set_read_timeout(Some(Duration::from_secs(5))).expect("timeout"); + stream.set_read_timeout(Some(HANG)).expect("timeout"); let reader = BufReader::new(stream.try_clone().expect("cloned")); (stream, reader) }; @@ -234,7 +238,7 @@ fn connections_past_the_limit_are_refused_with_the_reason() { drop(open.pop()); // The server frees the place when it reads the close; a new connection is served once it has. - ended.recv_timeout(Duration::from_secs(5)).expect("the closed connection ended"); + ended.recv_timeout(HANG).expect("the closed connection ended"); let (mut stream, mut reader) = connect(); writeln!(stream, "{}", json!({"id": 1, "method": "auth", "params": {"token": TOKEN}})).expect("written"); let served = read_json(&mut reader).expect("a reply"); @@ -281,7 +285,7 @@ fn a_refused_first_frame_closes_the_connection() { for (first, id) in [("not json".to_owned(), Value::Null), (json!({"id": 4, "method": "auth", "params": {"token": wrong}}).to_string(), json!(4))] { let mut stream = TcpStream::connect(server.addr).expect("connected"); - stream.set_read_timeout(Some(Duration::from_secs(5))).expect("timeout"); + stream.set_read_timeout(Some(HANG)).expect("timeout"); let mut reader = BufReader::new(stream.try_clone().expect("cloned")); let second = json!({"id": 5, "method": "test.after"}); stream.write_all(format!("{first}\n{second}\n").as_bytes()).expect("both lines written before reading"); @@ -298,7 +302,7 @@ fn a_browser_post_never_reaches_the_app() { // The server's clock stands still, so the close comes from the refusal, not the deadline. let (rx, server, ended) = serve_counting_ends(); let mut stream = TcpStream::connect(server.addr).expect("connected"); - stream.set_read_timeout(Some(Duration::from_secs(5))).expect("timeout"); + stream.set_read_timeout(Some(HANG)).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"); @@ -323,7 +327,7 @@ fn a_browser_post_never_reaches_the_app() { fn an_over_long_request_is_refused_and_closes_the_connection() { let (rx, server) = server::listen(0, TOKEN.into(), host()).expect("started"); let mut stream = TcpStream::connect(server.addr).expect("connected"); - stream.set_read_timeout(Some(Duration::from_secs(5))).expect("timeout"); + stream.set_read_timeout(Some(HANG)).expect("timeout"); let mut reader = BufReader::new(stream.try_clone().expect("cloned")); writeln!(stream, "{}", json!({"id": 1, "method": "auth", "params": {"token": TOKEN}})).expect("written"); assert_eq!(read_json(&mut reader).expect("a reply")["ok"], true); @@ -425,7 +429,7 @@ fn reply_caps_bound_errors_and_reserve_the_newline_before_writing() { /// Answers the next request, which must be `test.ping`, with `pong`. fn answer_one_ping(rx: Receiver) -> std::thread::JoinHandle<()> { std::thread::spawn(move || { - let req = rx.recv_timeout(Duration::from_secs(5)).expect("a request"); + let req = rx.recv_timeout(HANG).expect("a request"); assert_eq!(req.method, "test.ping"); let pong: ControlResponse = json!({"ok": true, "result": "pong"}); req.reply.send(pong).expect("replied"); @@ -435,7 +439,7 @@ fn answer_one_ping(rx: Receiver) -> std::thread::JoinHandle<()> /// Authenticates with the one-frame token, sends `test.ping` and returns its reply. fn ping(addr: SocketAddr) -> Value { let mut stream = TcpStream::connect(addr).expect("connected"); - stream.set_read_timeout(Some(Duration::from_secs(5))).expect("timeout"); + stream.set_read_timeout(Some(HANG)).expect("timeout"); let mut reader = BufReader::new(stream.try_clone().expect("cloned")); writeln!(stream, "{}", json!({"id": 1, "method": "auth", "params": {"token": TOKEN}})).expect("written"); assert_eq!(read_json(&mut reader).expect("a reply")["ok"], true); @@ -470,7 +474,7 @@ fn a_challenge_authenticated_connection_is_served() { let (rx, server) = server::listen(0, TOKEN.into(), host()).expect("started"); let handler = answer_one_ping(rx); let mut stream = TcpStream::connect(server.addr).expect("connected"); - stream.set_read_timeout(Some(Duration::from_secs(5))).expect("timeout"); + stream.set_read_timeout(Some(HANG)).expect("timeout"); let mut reader = BufReader::new(stream.try_clone().expect("cloned")); let client_nonce = generate_nonce().expect("a nonce"); writeln!(stream, "{}", json!({"id": 1, "method": CHALLENGE_METHOD, "params": {"clientNonce": client_nonce}})).expect("written"); @@ -520,7 +524,7 @@ fn the_documented_capture_client_sends_setup_steps_and_capture() { let mut channel = ControlChannel::new(forwarded); let mut seen: Vec = Vec::new(); while seen.len() < 4 { - forward.send(requests.recv_timeout(Duration::from_secs(10)).expect("a request")).expect("forwarded"); + forward.send(requests.recv_timeout(HANG).expect("a request")).expect("forwarded"); let req = channel.next_request().expect("the forwarded request is dispatched"); seen.push(format!("{} {}", req.method, req.params)); let reply = match req.method.as_str() { @@ -545,7 +549,7 @@ fn the_documented_capture_client_sends_setup_steps_and_capture() { /// Connects and authenticates with the one-frame token. fn authenticated(addr: SocketAddr) -> (TcpStream, BufReader) { let mut stream = TcpStream::connect(addr).expect("connected"); - stream.set_read_timeout(Some(Duration::from_secs(5))).expect("timeout"); + stream.set_read_timeout(Some(HANG)).expect("timeout"); let mut reader = BufReader::new(stream.try_clone().expect("cloned")); writeln!(stream, "{}", json!({"id": "auth", "method": "auth", "params": {"token": TOKEN}})).expect("written"); assert_eq!(read_json(&mut reader).expect("a reply")["ok"], true); @@ -558,11 +562,11 @@ fn authenticated(addr: SocketAddr) -> (TcpStream, BufReader) { fn an_oversized_reply_keeps_its_framing_and_id_and_the_connection_serves_on() { let (rx, server) = server::listen(0, TOKEN.into(), host()).expect("started"); let handler = std::thread::spawn(move || { - let first = rx.recv_timeout(Duration::from_secs(5)).expect("a request"); + let first = rx.recv_timeout(HANG).expect("a request"); assert_eq!(first.method, "test.large"); assert!(first.deadline.is_some_and(|d| d > motion::now()), "native requests carry their reply deadline"); first.reply.send(json!({"ok": true, "result": "x".repeat(MAX_RESPONSE_BYTES)})).expect("replied"); - let second = rx.recv_timeout(Duration::from_secs(5)).expect("a request"); + let second = rx.recv_timeout(HANG).expect("a request"); assert_eq!(second.method, "test.small"); second.reply.send(json!({"ok": true, "result": "still serving"})).expect("replied"); }); @@ -585,7 +589,7 @@ fn an_oversized_reply_keeps_its_framing_and_id_and_the_connection_serves_on() { fn a_bad_json_request_gets_a_null_id_and_the_connection_serves_on() { let (rx, server) = server::listen(0, TOKEN.into(), host()).expect("started"); let handler = std::thread::spawn(move || { - let req = rx.recv_timeout(Duration::from_secs(5)).expect("a request"); + let req = rx.recv_timeout(HANG).expect("a request"); assert_eq!(req.method, "test.after"); req.reply.send(json!({"ok": true, "result": "still serving"})).expect("replied"); }); @@ -609,7 +613,7 @@ fn a_bad_json_request_gets_a_null_id_and_the_connection_serves_on() { fn a_repeated_auth_is_answered_already_authenticated_without_dispatching() { let (rx, server) = server::listen(0, TOKEN.into(), host()).expect("started"); let handler = std::thread::spawn(move || { - let req = rx.recv_timeout(Duration::from_secs(5)).expect("a request"); + let req = rx.recv_timeout(HANG).expect("a request"); assert_eq!(req.method, "test.after", "a repeated auth must not reach the app"); req.reply.send(json!({"ok": true, "result": "still serving"})).expect("replied"); }); @@ -632,7 +636,7 @@ fn a_repeated_auth_is_answered_already_authenticated_without_dispatching() { fn a_complete_json_request_at_eof_can_reach_the_app() { let (rx, server, ended) = serve_counting_ends(); let handler = std::thread::spawn(move || { - let req = rx.recv_timeout(Duration::from_secs(5)).expect("the request reached the app"); + let req = rx.recv_timeout(HANG).expect("the request reached the app"); assert_eq!(req.method, "test.once"); req.reply.send(json!({"ok": true, "result": "once"})).expect("replied"); rx @@ -659,7 +663,7 @@ fn idle_unauthenticated_connections_are_limited() { // Admission is counted by the accept thread: it is done once the next connection is answered. let refused = |addr| { let stream = TcpStream::connect(addr).expect("connected"); - stream.set_read_timeout(Some(Duration::from_secs(5))).expect("timeout"); + stream.set_read_timeout(Some(HANG)).expect("timeout"); read_json(&mut BufReader::new(stream)) }; let reply = refused(server.addr).expect("a refusal"); @@ -668,10 +672,10 @@ fn idle_unauthenticated_connections_are_limited() { drop(idle); // The freed slots go back as the closed connections are noticed. for _ in 0..MAX_CONNECTIONS { - ended.recv_timeout(Duration::from_secs(5)).expect("a closed connection ended"); + ended.recv_timeout(HANG).expect("a closed connection ended"); } let mut stream = TcpStream::connect(server.addr).expect("connected"); - stream.set_read_timeout(Some(Duration::from_secs(5))).expect("timeout"); + stream.set_read_timeout(Some(HANG)).expect("timeout"); let mut reader = BufReader::new(stream.try_clone().expect("cloned")); writeln!(stream, "{}", json!({"id": "auth", "method": "auth", "params": {"token": TOKEN}})).expect("written"); assert_eq!(read_json(&mut reader).expect("a reply")["ok"], true, "a freed slot is admitted again"); diff --git a/crates/automation/tests/it/dialogs.rs b/crates/automation/tests/it/dialogs.rs index b15b926dcd..374d2b4446 100644 --- a/crates/automation/tests/it/dialogs.rs +++ b/crates/automation/tests/it/dialogs.rs @@ -5,11 +5,11 @@ use std::sync::mpsc::{Receiver, channel}; use craft_automation::control::{ControlChannel, ControlRequest, ControlResponse}; use craft_automation::dialogs::{MAX_DIALOG_FIELDS, dialog_method, dialog_reply, inspect}; use craft_ui::contract::{Bind, SaveKey}; -use craft_ui::dialog::{DialogHost, DialogId, DialogResult, PromptChoice, PromptKind, StandardPrompt}; +use craft_ui::dialog::{DialogHost, DialogId, DialogResult, DialogStack, PromptChoice, PromptKind, StackDialog, StandardPrompt}; use craft_ui::patterns::form_dialogs::{DialogFields, HostedParamDialog, Param, ParamDialog, ParamKind}; use craft_ui::runtime::env::{Label, Word}; use craft_ui::testing::trial; -use egui::Context; +use egui::{Context, Ui}; use serde_json::{Value, json}; fn call(host: &mut DialogHost, ctx: &Context, method: &str, params: Value) -> Result { @@ -130,6 +130,56 @@ fn param_dialog_automation_follows_its_rows() { const TAKEN: Word = Word::keyed("craft_automation.nameTaken", "A preset with that name exists"); +struct OtherDialog(DialogId); + +impl StackDialog for OtherDialog { + type Result = (); + + fn id(&self) -> DialogId { + self.0 + } + + fn show(&mut self, _: &mut Ui, _: &DialogStack) -> Option> { + None + } +} + +/// Another type open under the same stable ID, before or after the confirm, doesn't answer the confirm whose OK +/// is waiting. +#[trial] +fn a_new_dialog_with_the_same_id_does_not_answer_a_pending_confirm() { + let ctx = Context::default(); + for other_was_open in [false, true] { + let mut host = DialogHost::new(); + let (_requests, rx) = channel(); + let mut control = ControlChannel::new(rx); + let id = host.open( + HostedParamDialog::new(&ctx, "blur", DialogFields::new(), |fields| { + ParamDialog::new("blur", "Blur", Param::parse_list(r#"{"radius":0.1..1000=1}"#)).values(Bind::bound(fields)) + }) + .held_ok(), + ); + if other_was_open { + host.open(OtherDialog(id)); + } + let (request, reply) = ControlRequest::new("ui.dialog.confirm", json!({"dialog": id.value()})); + let outcome = dialog_reply(&mut host, &ctx, &request.method, &request.params).expect("the confirm command"); + control.settle(request, outcome, None, 0.0); + if !other_was_open { + host.open(OtherDialog(id)); + } + assert_eq!(host.open_dialogs().len(), 2); + control.poll_held(&host); + assert_eq!(control.waiting(), 1, "the dialog that got the confirm is still waiting for the app (other open first: {other_was_open})"); + assert_eq!(reply.try_recv(), Err(std::sync::mpsc::TryRecvError::Empty)); + + assert!(held(&mut host, id).take_ok().is_some()); + held(&mut host, id).answer_ok(Ok(())); + control.poll_held(&host); + assert_eq!(reply.try_recv(), Ok(json!({"ok": true, "result": null}))); + } +} + /// The open parameter dialog `id` names. fn held(host: &mut DialogHost, id: DialogId) -> &mut HostedParamDialog { host.get_dyn_mut(id).and_then(|dialog| dialog.downcast_mut::()).expect("the held dialog is open") diff --git a/crates/behavior/src/wheel.rs b/crates/behavior/src/wheel.rs index 3f75b029e8..2e860a6d26 100644 --- a/crates/behavior/src/wheel.rs +++ b/crates/behavior/src/wheel.rs @@ -101,6 +101,13 @@ pub struct Wheel { pub gathered: Vec2, /// Whether the owner marked the running gesture moved (`Pointer::mark_wheel_moved`). pub moved: bool, + /// The modifiers held at any point of the running gesture so far, this share's included: those of its wheel events + /// and of the key events between them, so a key tapped between two events counts until the gesture ends. For the + /// taker that owns the gesture; another taker's share holds its own `mods`. + pub held: Mods, + /// A wheel event of the running gesture, or one less than [`GESTURE_GAP`] seconds before it began, arrived while a + /// modal layer held the wheel: the turn began or went on under the modal, and it stays marked until it ends. + pub modal: bool, } /// The eased motion of a canvas's line wheel: notches gather into owed motion that later passes pay out. @@ -247,6 +254,8 @@ impl Wheel { touch_pan: Vec2::ZERO, gathered: Vec2::ZERO, moved: false, + held: mods, + modal: false, } } diff --git a/crates/color-ui/README.md b/crates/color-ui/README.md index a38b1f9827..1e05047576 100644 --- a/crates/color-ui/README.md +++ b/crates/color-ui/README.md @@ -10,5 +10,7 @@ The colour model and conversions are in `craft-theme`; profiles and transforms i `ColorPanel::edited` can supply a colour's native components. Editing one channel preserves the other components, even when the host renders the colour through a different working-space transform. Current host components take -precedence over the panel's remembered values. Canceling a channel gesture restores the host's complete opening -colour, including its display colour, alpha and native components. +precedence over the panel's remembered values. Canceling a channel or ramp gesture restores the host's complete opening +color, including its display color, alpha and native components. The `before` of an edit from the channels, the ramp, +a hex field, the readout, the out-of-gamut chip, the Black and White wells or a Recent Colors chip is that complete +color, so Undo returns to it. diff --git a/crates/color-ui/src/ui/panel.rs b/crates/color-ui/src/ui/panel.rs index d2548b1045..db257c06b0 100644 --- a/crates/color-ui/src/ui/panel.rs +++ b/crates/color-ui/src/ui/panel.rs @@ -417,6 +417,8 @@ struct Kept { dragging: bool, /// The host's complete colour before a model gesture, independent of the panel's transform. opening: Option<(GestureId, PanelTarget, PickedColor)>, + /// Both colors, complete, before a gesture of the ramp, a hex field or the readout. + colors_opening: Option<(GestureId, [PickedColor; 2])>, /// The ramp gesture in progress picks for the colour not edited. other: bool, } @@ -977,6 +979,42 @@ impl Body<'_> { self.inputs.edited.and_then(Option::as_ref) } + /// The complete color of `target`: the host's `edited` color with its model values for the edited well, else + /// the well's color. + fn complete(&self, target: PanelTarget) -> PickedColor { + match self.picked() { + Some(picked) if target == self.target => *picked, + _ => PickedColor { color: self.colors[target.index()], model: None }, + } + } + + /// Pushes `event` for `target` with the complete color it started from as its `before`: the color when its + /// gesture began, kept through the host's live updates, or the current color for a `Set`. + fn push_from_complete(&mut self, target: PanelTarget, mut event: EditEvent) { + if let EditEvent::Begin { id, .. } = &event { + self.kept.colors_opening = Some((*id, [self.complete(PanelTarget::Foreground), self.complete(PanelTarget::Background)])); + } + let opening = self.kept.colors_opening.filter(|(id, _)| Some(*id) == event.id()).map(|(_, colors)| colors[target.index()]); + match &mut event { + EditEvent::Begin { before, .. } | EditEvent::Commit { before, .. } => { + if let Some(picked) = opening { + *before = Mixed::Same(picked); + } + } + EditEvent::Cancel { before, .. } => { + if let Some(picked) = opening { + *before = Some(Mixed::Same(picked)); + } + } + EditEvent::Set { before, .. } => *before = Mixed::Same(self.complete(target)), + _ => {} + } + if matches!(event.phase(), Some(GesturePhase::Commit | GesturePhase::Cancel) | None) { + self.kept.colors_opening = None; + } + self.push(target, event); + } + /// Whether the rows edit anything: the host gave no `edited(None)`. fn enabled(&self) -> bool { self.inputs.edited.is_none_or(Option::is_some) @@ -1090,7 +1128,7 @@ impl Body<'_> { if ColorWarningChip::new(&warning).arrangement(ColorWarningArrangement::Beside).show(ui).clicked { let picked = PickedColor { color: warning.nearest().with_alpha(color.a), model: None }; let name = self.words.title.as_str(); - self.push(self.target, EditEvent::set(Mixed::Same(PickedColor { color, model: None }), picked, name.into(), None)); + self.push_from_complete(self.target, EditEvent::set(Mixed::Same(PickedColor { color, model: None }), picked, name.into(), None)); } } }); @@ -1271,7 +1309,7 @@ impl Body<'_> { let color = self.color(); let edit = ColorReadout::new(self.words.hex_color.clone(), Bind::given(color.to_rgba())).show(ui); for event in edit.events { - self.push(self.target, event.map(|rgba| PickedColor { color: Srgba::from(rgba).with_alpha(color.a), model: None })); + self.push_from_complete(self.target, event.map(|rgba| PickedColor { color: Srgba::from(rgba).with_alpha(color.a), model: None })); } } @@ -1309,7 +1347,7 @@ impl Body<'_> { } let target = if self.kept.other { self.target.other() } else { self.target }; let alpha = self.colors[target.index()].a; - self.push(target, event.map(|pick| PickedColor { color: pick.color.with_alpha(alpha), model: None })); + self.push_from_complete(target, event.map(|pick| PickedColor { color: pick.color.with_alpha(alpha), model: None })); } } diff --git a/crates/color-ui/src/ui/panel/fill_stroke.rs b/crates/color-ui/src/ui/panel/fill_stroke.rs index 1e6dd88dd9..59c12cb674 100644 --- a/crates/color-ui/src/ui/panel/fill_stroke.rs +++ b/crates/color-ui/src/ui/panel/fill_stroke.rs @@ -128,7 +128,7 @@ impl Body<'_> { .show(ui, |ui, _| TextField::hex(words.hex_color.clone(), Bind::given(color.to_rgba())).show(ui)) .inner; for event in edit.into_iter().flat_map(|edit| edit.events) { - self.push(self.target, event.map(|rgba| PickedColor::rgb(Srgba::from(rgba).with_alpha(color.a)))); + self.push_from_complete(self.target, event.map(|rgba| PickedColor::rgb(Srgba::from(rgba).with_alpha(color.a)))); } } @@ -206,6 +206,9 @@ impl Body<'_> { fn set_color(&mut self, target: PanelTarget, color: Srgba) { let before = self.colors[target.index()]; let name = self.words.title.as_str(); - self.push(target, EditEvent::set(Mixed::Same(PickedColor::rgb(before)), PickedColor::rgb(color.with_alpha(before.a)), name.into(), None)); + self.push_from_complete( + target, + EditEvent::set(Mixed::Same(PickedColor::rgb(before)), PickedColor::rgb(color.with_alpha(before.a)), name.into(), None), + ); } } diff --git a/crates/color-ui/tests/it/panels.rs b/crates/color-ui/tests/it/panels.rs index 7ebaeb89d1..91d7c1dee5 100644 --- a/crates/color-ui/tests/it/panels.rs +++ b/crates/color-ui/tests/it/panels.rs @@ -343,16 +343,21 @@ fn a_disabled_fill_stroke_rgb_row_does_not_switch_its_units() { /// A Color panel whose host supplies authoritative native CMYK components. fn native_cmyk_panel(picked: PickedColor) -> (Fixture, Rc>, Edits) { + native_panel_in(picked, ColorPanelLayout::FillStroke, ColorPanelMode::CmykSliders) +} + +/// A Color panel in `layout` and `mode` whose host supplies authoritative native CMYK components. +fn native_panel_in(picked: PickedColor, layout: ColorPanelLayout, mode: ColorPanelMode) -> (Fixture, Rc>, Edits) { let host = Rc::new(RefCell::new(picked)); let edits: Edits = Default::default(); let (color, output) = (host.clone(), edits.clone()); let mut fixture = Fixture::new(move |ui| { let picked = *color.borrow(); - let mut state = ColorPanelState { mode: ColorPanelMode::CmykSliders, ..Default::default() }; + let mut state = ColorPanelState { mode, ..Default::default() }; let shown = ColorPanel::new(Bind::bound(&mut state), [picked.color; 2]) - .layout(ColorPanelLayout::FillStroke) + .layout(layout) .edited(Some(picked)) - .shown(ColorPanelShown::Mode(ColorPanelMode::CmykSliders)) + .shown(ColorPanelShown::Mode(mode)) .show(ui); for (_, event) in &shown.edits { if let Some(picked) = event.landed() { @@ -433,6 +438,127 @@ fn a_canceled_native_channel_drag_restores_the_hosts_original_color() { assert_eq!(*host.borrow(), picked, "release after Cancel cannot reapply the preview"); } +/// The color the last finished edit reports it started from: the `before` of its Commit or Set. +fn last_before(edits: &Edits) -> PickedColor { + edits + .borrow() + .iter() + .rev() + .find_map(|(_, event)| match event { + EditEvent::Commit { before: Mixed::Same(before), .. } | EditEvent::Set { before: Mixed::Same(before), .. } => Some(*before), + _ => None, + }) + .expect("a finished edit") +} + +/// A ramp drag starts from the host's complete color: Cancel restores the native inks and Undo of a committed drag +/// returns to them, even after the host applies the drag's live updates. +#[trial] +fn a_ramp_drag_restores_and_undoes_to_the_hosts_native_color() { + let native = ModelValues::new("cmyk", &[12.345, 45.678, 78.912, 23.456]); + let picked = PickedColor::in_model(Srgba::new(0.2, 0.4, 0.6, 0.7), native); + let (mut fixture, host, edits) = native_cmyk_panel(picked); + let ramp = fixture.by_label("Color Ramp").expect("the ramp"); + let from = ramp.rect.left_center() + Vec2::new(10.0, 0.0); + fixture.drag_hold_at(from, Vec2::new(60.0, 0.0)).settle(); + assert_ne!(*host.borrow(), picked, "the host applies the live ramp preview"); + fixture.key(Key::Escape, Modifiers::NONE).settle(); + let canceled = edits + .borrow() + .iter() + .rev() + .find_map(|(_, event)| match event { + EditEvent::Cancel { before: Some(Mixed::Same(before)), .. } => Some(*before), + _ => None, + }) + .expect("the ramp drag cancels"); + assert_eq!(canceled, picked, "Cancel carries the host's exact opening color and model"); + assert_eq!(*host.borrow(), picked, "the host restores the complete opening color"); + fixture.release_at(from + Vec2::new(60.0, 0.0)).settle(); + fixture.drag_at(from, Vec2::new(60.0, 0.0)).settle(); + assert_ne!(*host.borrow(), picked, "the ramp drag lands a new color"); + assert_eq!(last_before(&edits), picked, "the committed drag undoes to the host's color and model"); +} + +/// Without an `edited` color, a canceled ramp drag restores the well's color from before the drag, after the host +/// applies the drag's live updates to its wells. +#[trial] +fn a_canceled_ramp_drag_restores_the_wells_color() { + let start = Srgba::new(0.2, 0.4, 0.6, 0.7); + let wells = Rc::new(Cell::new([start, BLUE])); + let edits: Edits = Default::default(); + let (colors, output) = (wells.clone(), edits.clone()); + let mut fixture = Fixture::new(move |ui| { + let mut state = ColorPanelState { mode: ColorPanelMode::CmykSliders, ..Default::default() }; + let shown = ColorPanel::new(Bind::bound(&mut state), colors.get()).show(ui); + for (target, event) in &shown.edits { + if let Some(picked) = event.landed() { + let mut now = colors.get(); + now[usize::from(*target == PanelTarget::Background)] = picked.color; + colors.set(now); + } + } + output.borrow_mut().extend(shown.edits); + }); + fixture.room(COLOR_ROOM).settle(); + let ramp = fixture.by_label("Color Ramp").expect("the ramp"); + let from = ramp.rect.left_center() + Vec2::new(10.0, 0.0); + fixture.drag_hold_at(from, Vec2::new(60.0, 0.0)).settle(); + assert_ne!(wells.get()[0], start, "the host applies the live ramp preview"); + fixture.key(Key::Escape, Modifiers::NONE).settle(); + let canceled = edits.borrow().iter().rev().find_map(|(_, event)| match event { + EditEvent::Cancel { before, .. } => Some(*before), + _ => None, + }); + assert_eq!(canceled, Some(Some(Mixed::Same(PickedColor { color: start, model: None }))), "Cancel carries the well's color"); + assert_eq!(wells.get(), [start, BLUE], "the host restores the well's color"); +} + +/// A hex entry, in the cubes' readout and in the FillStroke layout's hex field, undoes to the host's complete color, +/// its native inks included. +#[trial] +fn a_hex_entry_undoes_to_the_hosts_native_color() { + let native = ModelValues::new("cmyk", &[12.345, 45.678, 78.912, 23.456]); + let picked = PickedColor::in_model(Srgba::new(0.2, 0.4, 0.6, 0.7), native); + for (layout, mode) in + [(ColorPanelLayout::ForegroundBackground, ColorPanelMode::HueCube), (ColorPanelLayout::FillStroke, ColorPanelMode::CmykSliders)] + { + let (mut fixture, host, edits) = native_panel_in(picked, layout, mode); + let hex = fixture.by_label("Hex color").expect("the hex field"); + fixture.click(&hex); + fixture.key(Key::A, Modifiers::COMMAND); + fixture.type_text("996633"); + fixture.key(Key::Enter, Modifiers::NONE); + fixture.settle(); + assert_ne!(*host.borrow(), picked, "{layout:?}: the hex entry lands a new color"); + assert_eq!(last_before(&edits), picked, "{layout:?}: the hex entry undoes to the host's color and model"); + } +} + +/// A click on the FillStroke layout's White well undoes to the host's complete color, its native inks included. +#[trial] +fn a_white_well_pick_undoes_to_the_hosts_native_color() { + let native = ModelValues::new("cmyk", &[12.345, 45.678, 78.912, 23.456]); + let picked = PickedColor::in_model(Srgba::new(0.2, 0.4, 0.6, 0.7), native); + let (mut fixture, host, edits) = native_cmyk_panel(picked); + let white = fixture.by_label("White").expect("the White well"); + fixture.click(&white).settle(); + assert_ne!(*host.borrow(), picked, "the White well lands white"); + assert_eq!(last_before(&edits), picked, "the White well's pick undoes to the host's color and model"); +} + +/// A click on the out-of-gamut chip undoes to the host's complete color, its native inks included. +#[trial] +fn a_gamut_chip_pick_undoes_to_the_hosts_native_color() { + let native = ModelValues::new("cmyk", &[12.345, 45.678, 78.912, 23.456]); + let picked = PickedColor::in_model(Srgba::rgb(0.0, 0.0, 1.0), native); + let (mut fixture, host, edits) = native_cmyk_panel(picked); + let chip = fixture.by_label("Out of gamut for printing: click for the nearest printable color").expect("the out-of-gamut chip"); + fixture.click(&chip).settle(); + assert_ne!(*host.borrow(), picked, "the chip lands the nearest printable color"); + assert_eq!(last_before(&edits), picked, "the chip's pick undoes to the host's color and model"); +} + /// The rect of the FillStroke spectrum in Web Color for a foreground of `color`. fn spectrum_rect(color: Srgba) -> egui::Rect { let mut fixture = Fixture::new(move |ui| { diff --git a/crates/craft/src/egui_fork.rs b/crates/craft/src/egui_fork.rs index e10d75f9e0..bae49f9ad9 100644 --- a/crates/craft/src/egui_fork.rs +++ b/crates/craft/src/egui_fork.rs @@ -3,7 +3,7 @@ /// The egui fork the library is built and tested with. Apps patch egui to exactly this. pub const GIT: &str = "https://github.com/storytold/egui.git"; /// The commit of [`GIT`]. -pub const REV: &str = "932a73b28560acb1a695533307b2cd0d66a42081"; +pub const REV: &str = "14c39fed181756be6f357c284354e0ab55b64443"; /// The packages the workspace patches to the fork (the `[patch.crates-io]` entries that name [`GIT`]). pub const PACKAGES: &[&str] = &[ diff --git a/crates/draw/src/ui/stroke/editor.rs b/crates/draw/src/ui/stroke/editor.rs index 2a802a2281..e43cb82827 100644 --- a/crates/draw/src/ui/stroke/editor.rs +++ b/crates/draw/src/ui/stroke/editor.rs @@ -85,6 +85,8 @@ impl Outcome for StrokeEditorOutput { /// - While the style fails [`StrokeStyle::validate`], the invalid word shows at the end and nothing is reported. /// - [`mixed`](Self::mixed): a mixed field shows the mixed state and lights no button or preset; the first edit sets it /// for all. +/// - [`host_labels`](Self::host_labels): shown in a host's [`FieldGroup`], the labeled rows read that group's label +/// column, so their controls start where the controls of the host's rows start. /// /// ```ignore /// let out = StrokeEditor::new("Stroke", Bind::bound(&mut style)).sections(StrokeSections::PANEL).show(ui); @@ -100,6 +102,7 @@ pub struct StrokeEditor<'a> { corners: bool, mixed: StrokeMixed, rows: &'a [StrokeChoiceRow<'a>], + host_labels: bool, } impl<'a> StrokeEditor<'a> { @@ -114,6 +117,7 @@ impl<'a> StrokeEditor<'a> { corners: true, mixed: StrokeMixed::default(), rows: &[], + host_labels: false, } } @@ -155,9 +159,17 @@ impl<'a> StrokeEditor<'a> { self } + /// Whether the editor's labeled rows read the label column of the [`FieldGroup`] the host shows the editor in, so + /// their controls start where the controls of the host's rows in that group start. False by default: the rows + /// then share a label column of their own. + pub fn host_labels(mut self, on: bool) -> Self { + self.host_labels = on; + self + } + /// Shows the editor. pub fn show(self, ui: &mut Ui) -> StrokeEditorOutput { - let StrokeEditor { label, mut value, sections, closed, caps_on_closed, corners, mixed, rows } = self; + let StrokeEditor { label, mut value, sections, closed, caps_on_closed, corners, mixed, rows, host_labels } = self; let env = Env::of(ui); let words = env.words::(); let name: Arc = label.as_str().into(); @@ -173,7 +185,7 @@ impl<'a> StrokeEditor<'a> { Some((base, draft)) if base == held => draft, _ => held.clone(), }; - let body = Body { words: &words, style: &style, sections, closed, caps_on_closed, corners, mixed, rows, name: name.clone() }; + let body = Body { words: &words, style: &style, sections, closed, caps_on_closed, corners, mixed, rows, host_labels, name: name.clone() }; body.show(ui, &mut found); if !found.events.is_empty() { for event in &found.events { @@ -264,11 +276,33 @@ struct Body<'a> { corners: bool, mixed: StrokeMixed, rows: &'a [StrokeChoiceRow<'a>], + /// The labeled rows read the label column of the group around the editor. + host_labels: bool, /// The name of the edits, for the host's undo. name: Arc, } impl Body<'_> { + /// Shows `body`'s labeled rows as a group named `label`: a [`FieldGroup`] with a label column of its own, or with + /// `host_labels` a stack as wide, whose rows read the label column of the group around the editor. + fn group(&self, ui: &mut Ui, label: &Label, salt: Option<&'static str>, mut body: impl FnMut(&mut Ui)) { + if self.host_labels { + let stack = Stack::new().label(label.clone()).sizing(Sizing::FillWidth); + match salt { + Some(salt) => stack.id_salt(salt), + None => stack, + } + .show(ui, |ui, _| body(ui)); + } else { + let group = FieldGroup::new(label.clone()); + match salt { + Some(salt) => group.id_salt(salt), + None => group, + } + .show(ui, |ui, _| body(ui)); + } + } + /// Reports the one-step change to `next`. fn set(&self, found: &mut Found, field: StrokeField, next: StrokeStyle) { let event = EditEvent::set(Mixed::Same(self.style.clone()), next, self.name.clone(), None); @@ -337,7 +371,7 @@ impl Body<'_> { let (style, mixed, words) = (self.style, self.mixed, self.words); let solid_closed = self.closed && !self.caps_on_closed && style.dashes.is_empty() && !mixed.dashes; let icons = self.sections.contains(StrokeSections::ICONS); - FieldGroup::new(words.title.clone()).show(ui, |ui, _| { + self.group(ui, &words.title, None, |ui| { let align = [ (StrokeAlign::Inside, "stroke_align_inside", &words.inside), (StrokeAlign::Center, "stroke_align_center", &words.center), @@ -453,7 +487,7 @@ impl Body<'_> { } }); } - FieldGroup::new(words.dash_offset.clone()).id_salt("offset").show(ui, |ui, _| { + self.group(ui, &words.dash_offset, Some("offset"), |ui| { let range = -f64::from(StrokeStyle::DASH_OFFSET_MAX)..=f64::from(StrokeStyle::DASH_OFFSET_MAX); let event = number(ui, &words.dash_offset, "dash-offset", f64::from(style.dash_offset), self.mixed.dash_offset, range, self.dash_unit(), true); diff --git a/crates/draw/tests/it/stroke_editor.rs b/crates/draw/tests/it/stroke_editor.rs index acf4e9d3e9..838a694d0a 100644 --- a/crates/draw/tests/it/stroke_editor.rs +++ b/crates/draw/tests/it/stroke_editor.rs @@ -1,10 +1,13 @@ //! The stroke editor's dash fields: typing in the blank after the pattern adds an entry, clearing a later field ends //! the pattern there, and the first field never clears. Its Caps row on a solid closed path: disabled by default, -//! enabled with `caps_on_closed`. +//! enabled with `caps_on_closed`. Its labeled rows in a host's group: a label column of their own by default, the +//! host group's with `host_labels`. use craft_draw::ui::stroke::{LineCap, StrokeEditor, StrokeSections, StrokeStyle}; -use craft_ui::contract::Bind; +use craft_ui::contract::{Bind, Show as _, ShowContainer as _}; +use craft_ui::form::{Field, FieldGroup}; use craft_ui::testing::{Fixture, trial}; +use craft_ui::text::NumberField; use egui::{Key, Modifiers}; use std::cell::RefCell; use std::rc::Rc; @@ -68,6 +71,58 @@ fn caps_on_closed_keeps_the_cap_buttons_enabled_on_a_solid_closed_path() { assert_eq!(style.borrow().cap, LineCap::Square, "the cap button sets the cap"); } +/// The label of the host group's own row: longer than every label of the editor. +const HOST_ROW: &str = "Arrowheads and profile"; + +/// A host group with one long-labeled row, [`HOST_ROW`], over the editor with `sections` and `host_labels` as given, +/// on a dashed path. +fn hosted_editor(sections: StrokeSections, host_labels: bool) -> Fixture { + let style = Rc::new(RefCell::new(StrokeStyle { dashes: vec![4.0, 2.0], ..StrokeStyle::default() })); + let mut fixture = Fixture::new(move |ui| { + let mut style = style.borrow_mut(); + FieldGroup::new("Host").show(ui, |ui, _| { + Field::new(HOST_ROW).show(ui, |ui, _| { + NumberField::new(HOST_ROW, Bind::given(Some(1.0))).show(ui); + }); + let _ = StrokeEditor::new("Stroke", Bind::bound(&mut *style)).sections(sections).host_labels(host_labels).show(ui); + }); + }); + fixture.settle(); + fixture +} + +/// The x where the control named `label` starts. +fn control_start(fixture: &Fixture, label: &str) -> f32 { + fixture.by_label(label).unwrap_or_else(|| panic!("{label:?} names its control")).rect.min.x +} + +#[trial] +fn host_labels_start_the_editor_rows_at_the_host_groups_control_edge() { + /// How far two edges may differ and still line up, in points. + const SLACK: f32 = 0.5; + let selects = StrokeSections::DASHES | StrokeSections::DASH_ALIGN | StrokeSections::OPACITY; + let fixture = hosted_editor(selects, true); + let edge = control_start(&fixture, HOST_ROW); + for name in ["Alignment", "Caps", "Corners", "Miter limit", "Opacity", "Dash offset", "Align dashes"] { + let at = control_start(&fixture, name); + assert!((at - edge).abs() <= SLACK, "{name:?} starts at the host group's control edge: {at} {edge}"); + } + + let fixture = hosted_editor(StrokeSections::PANEL, true); + let edge = control_start(&fixture, HOST_ROW); + for name in ["Miter limit", "Dash offset"] { + let at = control_start(&fixture, name); + assert!((at - edge).abs() <= SLACK, "{name:?} starts at the host group's control edge with icon rows: {at} {edge}"); + } + + let fixture = hosted_editor(selects, false); + let edge = control_start(&fixture, HOST_ROW); + for name in ["Alignment", "Caps", "Corners", "Miter limit", "Opacity", "Dash offset"] { + let at = control_start(&fixture, name); + assert!(at < edge - SLACK, "by default {name:?} keeps the editor's own label column: {at} {edge}"); + } +} + #[trial] fn dash_fields_add_after_the_pattern_and_a_cleared_field_ends_it() { let (mut fixture, style) = editor(vec![4.0, 2.0]); diff --git a/crates/imaging/src/layer_style/spec.rs b/crates/imaging/src/layer_style/spec.rs index b5c4670222..b55f01b12d 100644 --- a/crates/imaging/src/layer_style/spec.rs +++ b/crates/imaging/src/layer_style/spec.rs @@ -141,8 +141,8 @@ impl EffectSpec { /// field that the drag on the image moves. /// - Pattern Overlay: blend; opacity; pattern Pattern; angle; scale Scale 1..1000 %; link Link /// with Layer. Defaults: Normal, 100, "", 0, 100, true. - /// - Bevel & Emboss: style Style (inner Inner Bevel, outer Outer Bevel, emboss Emboss, pillow - /// Pillow Emboss); technique Technique (smooth Smooth, chiselHard Chisel Hard, chiselSoft + /// - Bevel & Emboss: style Style (outer Outer Bevel, inner Inner Bevel, emboss Emboss, pillow + /// Pillow Emboss, stroke Stroke Emboss); technique Technique (smooth Smooth, chiselHard Chisel Hard, chiselSoft /// Chisel Soft); depth Depth 1..1000 %; direction Direction (up Up, down Down); size 0..250 /// px; soften Soften 0..16 px; angle; useGlobalLight; altitude Altitude 0..90 °; /// glossContour Gloss Contour (anti-alias `glossAntiAlias`); highlightBlend Highlight Mode; @@ -360,7 +360,13 @@ impl EffectSpec { field( "style", "Style", - choice(&[("inner", "Inner Bevel"), ("outer", "Outer Bevel"), ("emboss", "Emboss"), ("pillow", "Pillow Emboss")]), + choice(&[ + ("outer", "Outer Bevel"), + ("inner", "Inner Bevel"), + ("emboss", "Emboss"), + ("pillow", "Pillow Emboss"), + ("stroke", "Stroke Emboss"), + ]), ), field("technique", "Technique", choice(&[("smooth", "Smooth"), ("chiselHard", "Chisel Hard"), ("chiselSoft", "Chisel Soft")])), field("depth", "Depth", slider(1.0, 1000.0, Percent)), diff --git a/crates/imaging/src/ui/layer_style/labels.rs b/crates/imaging/src/ui/layer_style/labels.rs index ecb0cdc591..88fcfa5660 100644 --- a/crates/imaging/src/ui/layer_style/labels.rs +++ b/crates/imaging/src/ui/layer_style/labels.rs @@ -90,6 +90,7 @@ craft_ui::words! { outer_bevel: "layerStyle.choiceOuter" = "Outer Bevel"; emboss: "layerStyle.choiceEmboss" = "Emboss"; pillow_emboss: "layerStyle.choicePillow" = "Pillow Emboss"; + stroke_emboss: "layerStyle.choiceStrokeEmboss" = "Stroke Emboss"; smooth: "layerStyle.choiceSmooth" = "Smooth"; chisel_hard: "layerStyle.choiceChiselHard" = "Chisel Hard"; chisel_soft: "layerStyle.choiceChiselSoft" = "Chisel Soft"; @@ -202,6 +203,7 @@ impl LayerStyleWords { "outer" => &self.outer_bevel, "emboss" => &self.emboss, "pillow" => &self.pillow_emboss, + "stroke" => &self.stroke_emboss, "smooth" => &self.smooth, "chiselHard" => &self.chisel_hard, "chiselSoft" => &self.chisel_soft, diff --git a/crates/imaging/tests/it/layer_style.rs b/crates/imaging/tests/it/layer_style.rs index 2668b1e5ad..20f67f5f17 100644 --- a/crates/imaging/tests/it/layer_style.rs +++ b/crates/imaging/tests/it/layer_style.rs @@ -161,6 +161,25 @@ fn page_rig(kind: EffectKind, params: Option) -> (Fixture, Rc = choices.iter().map(|choice| choice.value.as_ref()).collect(); + assert_eq!(values, ["outer", "inner", "emboss", "pillow", "stroke"]); + assert_eq!(spec.defaults.get("style"), Some(&StyleValue::Text("inner".into())), "Inner Bevel stays the default"); + + let mut params = spec.defaults.clone(); + params.set("style", StyleValue::Text("stroke".into())); + let (fixture, _host) = page_rig(EffectKind::BevelEmboss, Some(params)); + let style = one(&fixture, Role::COMBO_BOX, "Style"); + assert_eq!(fixture.tree().value_of(style.node), Some("Stroke Emboss")); +} + /// A page shows the spec's defaults for keys the instance lacks without writing them; editing one field writes only /// that key. #[trial] diff --git a/crates/menu/src/shortcuts/mod.rs b/crates/menu/src/shortcuts/mod.rs index 2b2165d4f9..5ae8ef362d 100644 --- a/crates/menu/src/shortcuts/mod.rs +++ b/crates/menu/src/shortcuts/mod.rs @@ -73,8 +73,10 @@ //! //! [`Options`] sets the conflict mode, double-press recording, area tabs, the on-screen keyboard, //! read-only rows for keys outside the catalog, the app's import and export formats, an `accept` -//! rule for which keys a command may get, and a `visible` rule for which catalog entries the table -//! lists (hidden entries keep their keys and still count in conflicts). +//! rule for which keys a command may get, a `visible` rule for which catalog entries the table +//! lists (hidden entries keep their keys and still count in conflicts), and whether the footer +//! offers Undo and Redo over the dialog's history or one button that steps the last change +//! ([`UndoButtons`]). use std::cell::RefCell; use std::collections::BTreeMap; @@ -199,6 +201,19 @@ pub enum ConflictMode { Keep, } +/// How the footer offers undo in [`Layout::Table`]. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +#[non_exhaustive] +pub enum UndoButtons { + /// Undo and Redo, side by side, over the whole history of the dialog's edits. + #[default] + History, + /// One button that steps the last change only: Undo reverts it and the button becomes Redo, which applies it + /// again and turns back into Undo. Starting to record a shortcut disables it until the next change. The undo + /// and redo keys step the same change. + Toggle, +} + /// An app's own Show entry. #[derive(Clone, Copy, Debug)] #[non_exhaustive] @@ -335,6 +350,8 @@ pub struct Options { /// [`Layout::Table`]: how the body is arranged. The keymap, the `accept` rule, the conflict mode /// and undo are the same in every layout. pub layout: Layout, + /// [`UndoButtons::History`]: how the footer offers undo. + pub undo: UndoButtons, } impl Default for Options { @@ -361,6 +378,7 @@ impl Default for Options { summary: true, accept: None, layout: Layout::Table, + undo: UndoButtons::History, } } } @@ -451,7 +469,9 @@ impl<'a> ShortcutsDialog<'a> { /// hold shortcuts in the Hold column. In [`ConflictMode::Ask`], a conflict leaves the old binding in place /// until the user confirms. Hosts can use [`ConflictMode::Steal`] or [`ConflictMode::Keep`] for immediate /// handling. Replacing a shortcut with an equivalent trigger leaves it alone. A replacement that changes - /// the shortcut can be undone in one step. `Err` says why the field was refused. + /// the shortcut can be undone in one step. `pressed`, `assign`, `remove` and `replace` are refused when the + /// user could not edit a shortcut: in a read-only dialog, while a prompt, review or recording is open, or on an + /// app tab. `Err` says why the field was refused. pub fn set_json_field(self, ui: &Ui, state: &mut DialogState, field: &str, value: &serde_json::Value) -> Result<(), String> { use craft_ui::dialog::FieldRefusal; let rejects = || FieldRefusal::Rejects(value).message(field); @@ -470,13 +490,16 @@ impl<'a> ShortcutsDialog<'a> { state.select_row(&command.ok_or_else(rejects)?); } "pressed" => { + if !state.can_edit(env) { + return Err(inactive()); + } let trigger = Trigger::parse(value.as_str().ok_or_else(rejects)?).map_err(|_| rejects())?; let command = state.selected.clone().ok_or_else(inactive)?; state.set_field(env, command, trigger); } "assign" => match value { serde_json::Value::Bool(true) => { - if state.field.is_none() { + if !state.can_edit(env) || state.field.is_none() { return Err(inactive()); } state.assign_field(env); @@ -486,6 +509,9 @@ impl<'a> ShortcutsDialog<'a> { _ => return Err(rejects()), }, "remove" => { + if !state.can_edit(env) { + return Err(inactive()); + } let wanted = Binding::parse(value.as_str().ok_or_else(rejects)?).map_err(|_| rejects())?; let command = state.selected.clone().ok_or_else(inactive)?; if !env.keymap.bindings(&command).contains(&wanted) { @@ -495,7 +521,7 @@ impl<'a> ShortcutsDialog<'a> { state.edit_result()?; } "replace" => { - if !env.options.editable || !state.is_showing() || state.modal() || state.is_recording() || env.has_app_tab(state.tab) { + if !state.can_edit(env) { return Err(inactive()); } let command = state.selected.clone().ok_or_else(inactive)?; @@ -598,6 +624,11 @@ const READ_ONLY_HEIGHT: f32 = 480.0; enum Act { Undo, Redo, + /// [`UndoButtons::Toggle`]'s one button, reading Redo when `redoes`, else Undo. A footer label is fixed for its + /// pass, so the button acts only while the last change still steps the way it reads. + Toggle { + redoes: bool, + }, ResetAll, Summarize, Ok, @@ -607,7 +638,7 @@ enum Act { } /// The footer's buttons and what each one does. Their enabled state is set after the body has run. -fn footer(env: &Env<'_>) -> (Vec, Vec) { +fn footer(env: &Env<'_>, state: &DialogState) -> (Vec, Vec) { let mut buttons = Vec::new(); let mut acts = Vec::new(); let mut add = |act: Act, label: String, role: DialogRole, stays_open: bool| { @@ -623,8 +654,14 @@ fn footer(env: &Env<'_>) -> (Vec, Vec) { return (buttons, acts); } if editable { - add(Act::Undo, word!(env, undo), DialogRole::Other, true); - add(Act::Redo, word!(env, redo), DialogRole::Other, true); + match env.options.undo { + UndoButtons::Toggle if state.toggle_redoes() => add(Act::Toggle { redoes: true }, word!(env, redo), DialogRole::Other, true), + UndoButtons::Toggle => add(Act::Toggle { redoes: false }, word!(env, undo), DialogRole::Other, true), + UndoButtons::History => { + add(Act::Undo, word!(env, undo), DialogRole::Other, true); + add(Act::Redo, word!(env, redo), DialogRole::Other, true); + } + } add(Act::ResetAll, word!(env, reset_all_more), DialogRole::Other, true); } // With sets, Summarize… is in the set row, which a read-only dialog does not show. @@ -652,7 +689,7 @@ fn frame(ui: &mut Ui, env: &mut Env<'_>, state: &mut DialogState) -> ShortcutsOu if !state.is_showing() { return ShortcutsOutput { response: ui.response(), outcome: state.finish() }; } - let (buttons, acts) = footer(env); + let (buttons, acts) = footer(env, state); let enter = env.options.enter_is_ok && !state.modal() && !state.is_recording(); let title = env.title(); let mut open = true; @@ -681,6 +718,7 @@ fn frame(ui: &mut Ui, env: &mut Env<'_>, state: &mut DialogState) -> ShortcutsOu button.set_enabled(match act { Act::Undo => idle && state.can_undo(), Act::Redo => idle && state.can_redo(), + Act::Toggle { redoes } => idle && state.can_toggle() && state.toggle_redoes() == *redoes, Act::ResetAll => idle && !env.keymap.overrides().is_empty(), Act::Ok | Act::Close => idle, Act::Cancel => idle, @@ -696,13 +734,26 @@ fn frame(ui: &mut Ui, env: &mut Env<'_>, state: &mut DialogState) -> ShortcutsOu .show(ui, |ui, cx| { let mut guard = session.borrow_mut(); let Session { env, state } = &mut *guard; - while let Some(step) = cx.take_step(!state.modal() && state.can_undo(), !state.modal() && state.can_redo()) { + let redoes = state.toggle_redoes(); + loop { + // Each step can change what the next may do: in Toggle mode an undo turns the next step into a redo. + let (undo, redo) = match env.options.undo { + UndoButtons::Toggle => (state.can_toggle() && !state.toggle_redoes(), state.can_toggle() && state.toggle_redoes()), + UndoButtons::History => (state.can_undo(), state.can_redo()), + }; + let (undo, redo) = (!state.modal() && undo, !state.modal() && redo); + let Some(step) = cx.take_step(undo, redo) else { break }; + // A step queued before the last one ran is still handed over: drop it when it is no longer allowed. match step { - Step::Undo => state.undo(env), - Step::Redo => state.redo(env), + Step::Undo if undo => state.undo(env), + Step::Redo if redo => state.redo(env), _ => {} } } + // The toggling button's label was fixed before the keys flipped it: show the new one on the next pass. + if state.toggle_redoes() != redoes { + cx.wake_at(cx.now()); + } view::body(ui, cx, env, state); if state.change_pending() { cx.wake_at(cx.now()); @@ -713,6 +764,8 @@ fn frame(ui: &mut Ui, env: &mut Env<'_>, state: &mut DialogState) -> ShortcutsOu match picked.and_then(|at| acts.get(at)) { Some(Act::Undo) => state.undo(env), Some(Act::Redo) => state.redo(env), + Some(Act::Toggle { redoes }) if state.toggle_redoes() == *redoes => state.toggle(env), + Some(Act::Toggle { .. }) => {} Some(Act::ResetAll) => state.ask_reset_all(), Some(Act::Summarize) => state.summarize(env), Some(Act::Ok | Act::Close) => state.ok(env), diff --git a/crates/menu/src/shortcuts/state.rs b/crates/menu/src/shortcuts/state.rs index 9f67d256b8..88d11930bf 100644 --- a/crates/menu/src/shortcuts/state.rs +++ b/crates/menu/src/shortcuts/state.rs @@ -277,6 +277,13 @@ struct Opened { holds: Option, } +/// Which way [`UndoButtons::Toggle`](super::UndoButtons::Toggle)'s button steps the last change. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Toggle { + Undo, + Redo, +} + #[derive(Clone, Copy, Debug, PartialEq, Eq)] enum Phase { New, @@ -311,6 +318,9 @@ pub struct DialogState { rows: RowCache, changed: bool, outcome: Option, + /// [`UndoButtons::Toggle`](super::UndoButtons::Toggle): which way its button steps the last change, `None` while + /// there is no change it may step. + last_change: Option, // ---- The view's own state ---- /// The chip of the selected row that Enter and Delete act on. pub(crate) chip: usize, @@ -363,6 +373,7 @@ impl DialogState { rows: RowCache::default(), changed: false, outcome: None, + last_change: None, chip: 0, keys_pick: None, typing: None, @@ -567,6 +578,8 @@ impl DialogState { self.message = None; self.recorder.reset(); if let Some(command) = target.command() { + // A new edit begins: the toggling undo button no longer reaches the change before it. + self.last_change = None; self.select_row(command); } self.recording = Some(Recording { target, waiting: None, started: false }); @@ -925,6 +938,7 @@ impl DialogState { /// After any edit: drop the conflict bar, refresh the field's holders, report Changed. fn edited(&mut self, env: &Env) { self.changed = true; + self.last_change = Some(Toggle::Undo); // The picked row is a position among the command's keys, which the edit may have moved. self.keys_pick = None; self.conflict = None; @@ -993,11 +1007,38 @@ impl DialogState { } pub(crate) fn undo(&mut self, env: &mut Env) { - self.edit(env, |s, km| s.undo(km)); + if self.edit(env, |s, km| s.undo(km)) { + self.last_change = Some(Toggle::Redo); + } } pub(crate) fn redo(&mut self, env: &mut Env) { - self.edit(env, |s, km| s.redo(km)); + if self.edit(env, |s, km| s.redo(km)) { + self.last_change = Some(Toggle::Undo); + } + } + + /// [`UndoButtons::Toggle`](super::UndoButtons::Toggle)'s button: undoes the last change, or redoes it after that. + pub(crate) fn toggle(&mut self, env: &mut Env) { + match self.last_change { + Some(Toggle::Undo) => self.undo(env), + Some(Toggle::Redo) => self.redo(env), + None => {} + } + } + + /// Whether the toggling button has a change to step. + pub(crate) fn can_toggle(&self) -> bool { + match self.last_change { + Some(Toggle::Undo) => self.can_undo(), + Some(Toggle::Redo) => self.can_redo(), + None => false, + } + } + + /// Whether the toggling button reads Redo: its last step undid the change. + pub(crate) fn toggle_redoes(&self) -> bool { + self.last_change == Some(Toggle::Redo) } pub(crate) fn can_undo(&self) -> bool { @@ -1153,6 +1194,7 @@ impl DialogState { env.keymap.set_overrides(p.active_overrides(b).clone()); } self.session = Some(EditSession::begin(env.keymap)); + self.last_change = None; self.recording = None; self.conflict = None; self.field = None; @@ -1165,6 +1207,12 @@ impl DialogState { self.prompt.is_some() || self.review.is_some() } + /// Whether the user could edit a shortcut now: the dialog is editable and shown, no prompt, review or + /// recording is open, and the shortcuts page is on screen rather than an app tab. + pub(crate) fn can_edit(&self, env: &Env) -> bool { + env.options.editable && self.is_showing() && !self.modal() && !self.is_recording() && !env.has_app_tab(self.tab) + } + fn report(&mut self, env: &Env, result: Result<(), ProfileError>) { match result { Ok(()) => self.message = None, diff --git a/crates/menu/tests/it/shortcuts/mod.rs b/crates/menu/tests/it/shortcuts/mod.rs index c796c17854..c2b9f79c82 100644 --- a/crates/menu/tests/it/shortcuts/mod.rs +++ b/crates/menu/tests/it/shortcuts/mod.rs @@ -9,6 +9,7 @@ pub(crate) mod review; pub(crate) mod rows; pub(crate) mod sets; pub(crate) mod tabs; +pub(crate) mod undo_toggle; use std::cell::Cell; use std::rc::Rc; @@ -247,6 +248,49 @@ fn automation_does_not_replace_a_binding_while_the_recorder_owns_it() { assert!(!rig.shared.borrow().state.is_recording()); } +#[trial] +fn automation_cannot_edit_shortcuts_in_a_read_only_dialog() { + let mut rig = Rig::mac(); + rig.set_json_field("command", json!("file.save")).unwrap(); + rig.set_json_field("pressed", json!("Cmd+K")).unwrap(); + rig.shared.borrow_mut().options.editable = false; + rig.pass(); + + assert!(rig.set_json_field("assign", json!(true)).is_err(), "assign"); + assert!(rig.set_json_field("remove", json!("Cmd+S")).is_err(), "remove"); + assert!(rig.set_json_field("pressed", json!("Cmd+J")).is_err(), "pressed"); + assert_eq!(rig.bindings("file.save"), ["Cmd+S"]); + let shared = rig.shared.borrow(); + assert!(!shared.state.snapshot(&shared.km).unwrap().can_undo); +} + +#[trial] +fn automation_cannot_edit_shortcuts_while_reset_confirmation_is_open() { + let mut rig = Rig::mac(); + rig.set_json_field("command", json!("file.save")).unwrap(); + rig.set_json_field("replace", json!({"old": "Cmd+S", "new": "Cmd+K"})).unwrap(); + rig.set_json_field("pressed", json!("Cmd+J")).unwrap(); + rig.click("Reset All…"); + + assert!(rig.set_json_field("assign", json!(true)).is_err(), "assign"); + assert!(rig.set_json_field("remove", json!("Cmd+K")).is_err(), "remove"); + assert!(rig.set_json_field("pressed", json!("Cmd+L")).is_err(), "pressed"); + assert_eq!(rig.bindings("file.save"), ["Cmd+K"]); +} + +#[trial] +fn automation_cannot_edit_a_shortcut_while_the_recorder_owns_it() { + let mut rig = Rig::mac(); + rig.set_json_field("command", json!("file.save")).unwrap(); + rig.click("Save: ⌘S"); + assert!(rig.shared.borrow().state.is_recording()); + + assert!(rig.set_json_field("remove", json!("Cmd+S")).is_err(), "remove"); + assert!(rig.set_json_field("pressed", json!("Cmd+J")).is_err(), "pressed"); + assert_eq!(rig.bindings("file.save"), ["Cmd+S"]); + assert!(rig.shared.borrow().state.is_recording()); +} + #[trial] fn automation_rejects_oversize_replacements_but_can_replace_an_oversize_default() { let scope = "Text".repeat(16); diff --git a/crates/menu/tests/it/shortcuts/tabs.rs b/crates/menu/tests/it/shortcuts/tabs.rs index 2f3dcea838..0908132a3c 100644 --- a/crates/menu/tests/it/shortcuts/tabs.rs +++ b/crates/menu/tests/it/shortcuts/tabs.rs @@ -17,7 +17,22 @@ use super::fixture; #[trial] fn shortcut_replacement_is_unavailable_on_an_app_tab() { + shortcut_edit_is_unavailable_on_an_app_tab("replace", json!({"old": "Cmd+S", "new": "Cmd+E"})); +} + +#[trial] +fn shortcut_removal_is_unavailable_on_an_app_tab() { + shortcut_edit_is_unavailable_on_an_app_tab("remove", json!("Cmd+S")); +} + +#[trial] +fn a_new_shortcut_cannot_be_pressed_on_an_app_tab() { + shortcut_edit_is_unavailable_on_an_app_tab("pressed", json!("Cmd+E")); +} + +fn shortcut_edit_is_unavailable_on_an_app_tab(field: &'static str, value: serde_json::Value) { for (tab, app_tab) in [("menus", true), ("unknown", false)] { + let value = value.clone(); let result = Rc::new(RefCell::new(None)); let observed = result.clone(); let drawn = Rc::new(Cell::new(false)); @@ -31,19 +46,14 @@ fn shortcut_replacement_is_unavailable_on_an_app_tab() { })]; if observed.borrow().is_none() { ShortcutsDialog::new(&mut keys).tabs(&mut tabs).set_json_field(ui, &mut state, "command", &json!("file.save")).unwrap(); - let answer = ShortcutsDialog::new(&mut keys).tabs(&mut tabs).set_json_field( - ui, - &mut state, - "replace", - &json!({"old": "Cmd+S", "new": "Cmd+E"}), - ); + let answer = ShortcutsDialog::new(&mut keys).tabs(&mut tabs).set_json_field(ui, &mut state, field, &value); *observed.borrow_mut() = Some(answer); } ShortcutsDialog::new(&mut keys).tabs(&mut tabs).show(ui, &mut state); }); fixture.settle(); assert_eq!(drawn.get(), app_tab); - assert_eq!(result.borrow().as_ref().unwrap().is_err(), app_tab); + assert_eq!(result.borrow().as_ref().unwrap().is_err(), app_tab, "{field} on {tab}"); } } diff --git a/crates/menu/tests/it/shortcuts/undo_toggle.rs b/crates/menu/tests/it/shortcuts/undo_toggle.rs new file mode 100644 index 0000000000..f25a29eabd --- /dev/null +++ b/crates/menu/tests/it/shortcuts/undo_toggle.rs @@ -0,0 +1,73 @@ +//! `UndoButtons::Toggle`: one footer button that steps the last change back and forth. + +use craft_keymap::{CommandRef, Platform}; +use craft_menu::shortcuts::UndoButtons; +use craft_ui::contract::Role; +use craft_ui::testing::trial; +use egui::{Key, Modifiers}; + +use super::fixture::Rig; + +fn rig() -> Rig { + Rig::tuned(Platform::Windows, |options| options.undo = UndoButtons::Toggle) +} + +/// Whether the footer button `label` can be clicked. +fn enabled(rig: &Rig, label: &str) -> bool { + let button = rig.named(label, Role::BUTTON); + !rig.fixture.tree().is_disabled_key(button.node) +} + +/// Records `key` over the selected command's `old` key in the detail pane. +fn replace(rig: &mut Rig, id: &str, control: &str, key: Key) { + rig.shared.borrow_mut().state.select(&CommandRef::from(id)); + rig.pass(); + rig.click(control); + rig.press(Modifiers::NONE, key); +} + +#[trial] +fn the_button_undoes_the_last_change_then_redoes_it() { + let mut rig = rig(); + assert!(!rig.has("Redo"), "one button, not Undo and Redo side by side"); + assert!(!enabled(&rig, "Undo"), "nothing to undo when the dialog opens"); + let original = rig.bindings("file.save"); + + replace(&mut rig, "file.save", "Replace Ctrl+S for Save", Key::F11); + assert_eq!(rig.bindings("file.save"), ["F11"]); + assert!(enabled(&rig, "Undo")); + + rig.click("Undo"); + assert_eq!(rig.bindings("file.save"), original); + assert!(!rig.has("Undo") && enabled(&rig, "Redo"), "after Undo the button reads Redo"); + + rig.click("Redo"); + assert_eq!(rig.bindings("file.save"), ["F11"]); + assert!(!rig.has("Redo") && enabled(&rig, "Undo"), "after Redo the button reads Undo again"); +} + +#[trial] +fn the_button_reaches_only_the_last_change() { + let mut rig = rig(); + let export = rig.bindings("file.export"); + replace(&mut rig, "file.save", "Replace Ctrl+S for Save", Key::F11); + replace(&mut rig, "file.export", "Replace Ctrl+E for Export…", Key::F9); + + rig.click("Undo"); + assert_eq!(rig.bindings("file.export"), export); + assert_eq!(rig.bindings("file.save"), ["F11"], "the change before the last one stays"); + assert!(!rig.has("Undo"), "a second Undo is not offered"); +} + +#[trial] +fn starting_to_record_disables_the_button() { + let mut rig = rig(); + replace(&mut rig, "file.save", "Replace Ctrl+S for Save", Key::F11); + assert!(enabled(&rig, "Undo")); + + rig.click("Replace F11 for Save"); + assert!(!enabled(&rig, "Undo"), "a new edit has begun"); + rig.press(Modifiers::NONE, Key::Escape); + assert_eq!(rig.bindings("file.save"), ["F11"]); + assert!(!enabled(&rig, "Undo"), "a cancelled recording does not bring the earlier change back"); +} diff --git a/crates/suite-account/src/lock.rs b/crates/suite-account/src/lock.rs index 74906014b6..7ea21ce89a 100644 --- a/crates/suite-account/src/lock.rs +++ b/crates/suite-account/src/lock.rs @@ -63,6 +63,14 @@ fn hold_mark(lock: &File) -> Option { lock.metadata().ok().map(|m| (m.len(), m.modified().ok())) } +/// Moves the held lock file's length to the next value in `1..=HOLDS`. +fn mark_hold(lock: &File) { + // A failure here only costs waiters the restart of their timeout for this hold. + if let Some((n, _)) = hold_mark(lock) { + let _ = lock.set_len(n % HOLDS + 1); + } +} + fn lock_path(path: &Path) -> PathBuf { let name = path.file_name().and_then(|n| n.to_str()).unwrap_or("accounts.json"); path.with_file_name(format!("{name}.lock")) @@ -102,10 +110,7 @@ pub(crate) fn with_lock(path: &Path, f: impl FnOnce() -> Result) -> } } } - // A failure here only costs waiters the restart of their timeout for this hold. - if let Some((n, _)) = hold_mark(&lock) { - let _ = lock.set_len(n % HOLDS + 1); - } + mark_hold(&lock); let result = f(); let _ = lock.unlock(); result @@ -156,13 +161,26 @@ mod tests { let dir = tempfile::tempdir().unwrap(); let path = dir.path().join("accounts.json"); with_lock(&path, || Ok(())).unwrap(); - let lock = open_lock_file(&path).unwrap(); - let before = hold_mark(&lock).unwrap(); - let Some(modified) = before.1 else { return }; - lock.set_modified(modified + Duration::from_secs(1)).unwrap(); - let after = hold_mark(&lock).unwrap(); - assert_eq!(before.0, after.0); - assert_ne!(before, after, "a new hold that leaves the same length must still change the mark"); + let before = { + // On Windows, a handle that set the time explicitly keeps it, so this one is closed first. + let lock = open_lock_file(&path).unwrap(); + hold_mark(&lock).and_then(|m| m.1).expect("the lock file must report a modification time on every platform CI runs"); + // 2000-01-01T00:00:00Z, a time FAT volumes can store. + lock.set_modified(SystemTime::UNIX_EPOCH + Duration::new(946_684_800, 0)).unwrap(); + hold_mark(&lock).unwrap() + }; + // Each hold opens and locks its own handle, as `with_lock` does, without its account-file preparation. + for _ in 0..HOLDS { + let lock = open_lock_file(&path).unwrap(); + lock.lock().unwrap(); + mark_hold(&lock); + } + let after = hold_mark(&open_lock_file(&path).unwrap()).unwrap(); + assert_eq!(before.0, after.0, "a full cycle of holds returns the lock file to the same length"); + let (Some(before_time), Some(after_time)) = (before.1, after.1) else { + panic!("the lock file must report a modification time before and after the holds"); + }; + assert_ne!(before_time, after_time, "a full cycle of holds must still change the modification time"); } #[test] diff --git a/crates/text/src/ui/character/paragraph.rs b/crates/text/src/ui/character/paragraph.rs index ca8ad2fd64..a94e964c1f 100644 --- a/crates/text/src/ui/character/paragraph.rs +++ b/crates/text/src/ui/character/paragraph.rs @@ -229,9 +229,9 @@ impl<'a> ParagraphControls<'a> { } /// As [`show`](Self::show), with the host's rows drawn by `between` after the alignment and direction rows and - /// before the indents. - pub fn show_with(self, ui: &mut Ui, between: impl FnOnce(&mut Ui)) -> ParagraphControlsOutput { - let mut between = Some(between); + /// before the indents. `between` runs in every run of the controls' body, its measuring runs included, so its rows + /// count in the height the controls measure. + pub fn show_with(self, ui: &mut Ui, mut between: impl FnMut(&mut Ui)) -> ParagraphControlsOutput { let direction_row = self.direction_row; let values = self.values; let point_text = self.point_text; @@ -256,9 +256,7 @@ impl<'a> ParagraphControls<'a> { if direction_row != DirectionRow::Hidden { edits.extend(toggle_row(ui, Some(&words.direction), &directions)); } - if let Some(between) = between.take() { - between(ui); - } + between(ui); Grid::new(&TWO_COLUMNS).fill_width().show(ui, |ui, _| { let start = LengthRow { diff --git a/crates/text/tests/it/paragraph.rs b/crates/text/tests/it/paragraph.rs index 65cf771338..4e03a582fc 100644 --- a/crates/text/tests/it/paragraph.rs +++ b/crates/text/tests/it/paragraph.rs @@ -1,11 +1,17 @@ //! The Word Paragraph dialog's pages: a check box whose paragraphs differ stays mixed across page switches until clicked; //! the contextual spacing box. -use craft_behavior::Mixed; -use craft_text::ui::character::{AsianTypography, LineBreakOptions, ParagraphDialog, ParagraphFormat, ParagraphTab}; +use craft_behavior::{Mixed, Proposal}; +use craft_text::ui::character::{ + AsianTypography, LineBreakOptions, ParagraphControls, ParagraphDialog, ParagraphFormat, ParagraphTab, ParagraphValues, +}; +use craft_ui::buttons::Button; +use craft_ui::contract::{Props as _, Show as _, ShowContainer as _}; use craft_ui::dialog::{DialogStack, StackDialog as _}; +use craft_ui::layout_components::Stack; use craft_ui::testing::{Fixture, trial}; -use std::cell::RefCell; +use egui::{Rect, Ui, Vec2}; +use std::cell::{Cell, RefCell}; use std::rc::Rc; fn toggled(fixture: &Fixture, label: &str) -> Option> { @@ -107,3 +113,31 @@ fn text_dialog_results_keep_the_opt_in_command_key_on_cancel_and_accept() { assert!(matches!(result, DialogResult::Ok(_))); assert_eq!(accepted_key.as_deref(), Some(key.as_str())); } + +/// The host's rows between the alignment rows and the indents count in the controls' measured height: a container +/// measured around the controls is as tall as it shows, so a flyout sized by that measure reaches Hyphenate. +#[trial] +fn the_rows_between_count_in_the_measured_height_of_the_paragraph_controls() { + const WIDTH: f32 = 290.0; + let values = ParagraphValues::default(); + let seen = Rc::new(Cell::new((Vec2::ZERO, Rect::NOTHING))); + let out = Rc::clone(&seen); + let mut fixture = Fixture::new(move |ui| { + let controls = |ui: &mut Ui| { + ParagraphControls::new("Paragraph", &values).show_with(ui, |ui| { + Button::new("Host row").show(ui); + }); + }; + let measured = Stack::new().id_salt("measured").measure_in(ui, Proposal::Width(WIDTH), |ui, _| controls(ui)); + let room = Rect::from_min_size(ui.max_rect().min, Vec2::new(WIDTH, 2000.0)); + let shown = Stack::new().id_salt("measured").show_at(ui, room, |ui, _| controls(ui)); + out.set((measured, shown.output.rect)); + }); + fixture.room(Vec2::new(800.0, 2000.0)).settle(); + let (measured, shown) = seen.get(); + let host = fixture.by_label("Host row").expect("the host's row is shown"); + let hyphenate = fixture.by_label("Hyphenate").expect("Hyphenate is shown"); + assert!(host.rect.bottom() < hyphenate.rect.top(), "the host's row is above Hyphenate: {host:?}, {hyphenate:?}"); + let reach = hyphenate.rect.bottom() - shown.top(); + assert!(measured.y >= reach - 0.5, "the measure ({}) reaches Hyphenate's foot ({reach}) in {shown:?}", measured.y); +} diff --git a/crates/ui-bench/src/bin/foundation/main.rs b/crates/ui-bench/src/bin/foundation/main.rs index 5a3e22ca8f..0404cd8844 100644 --- a/crates/ui-bench/src/bin/foundation/main.rs +++ b/crates/ui-bench/src/bin/foundation/main.rs @@ -11,6 +11,7 @@ use std::sync::Arc; use craft_behavior::kurbo::Point; use craft_behavior::{Axis, CanvasView, ColumnKey, ColumnWidth, DisplayOrder, ItemSource, PixelSize, RulerUnits, Selection}; use craft_host::target::ShellInfo; +use craft_ui::buttons::Button; use craft_ui::canvas::{ Canvas, Guide, GuideKey, HandTool, NavigationOptions, PixelRect, RasterDisplay, RasterSource, RulerText, Rulers, ToolHost, pan, tool_pass, }; @@ -19,6 +20,7 @@ use craft_ui::contract::ColumnSpec; use craft_ui::contract::{ Bind, Collapse, ContainerProps, Mount, Overlay, Props as _, SelectMode, Show as _, ShowCollection as _, ShowContainer as _, Sizing, }; +use craft_ui::contract::{MemoProps, MemoView}; use craft_ui::dialog::Dialog; use craft_ui::layout::ColumnGroup; use craft_ui::list::{List, ListRow}; @@ -66,6 +68,10 @@ impl Library for Foundation { fn build(&self, name: &str) -> SceneBuild { let (scene, equivalent): (Box, &'static str) = match name { + "memo-regions-stationary" | "memo-regions-changing" => ( + Box::new(MemoRegions { changing: name == "memo-regions-changing" }), + "20 fixed memo regions containing 20 buttons each; unchanged or one region invalidated per frame", + ), "inspector-500-fields" | "inspector-1000-fields" => ( Box::new(InspectorScene::new(if name == "inspector-500-fields" { 500 } else { 1000 })), // F8-MERGE: family (Field row): the field's own side label stands in for the `Field` row. @@ -109,6 +115,40 @@ impl Library for Foundation { } } +/// Fixed regions isolate registration replay from layout motion. The changing case +/// rebuilds one region per frame to exercise transitions back to real registration. +struct MemoRegions { + changing: bool, +} + +#[derive(MemoProps)] +struct MemoButtons { + revision: u64, +} + +fn memo_buttons(props: &mut MemoButtons, ui: &mut Ui) { + for index in 0..20 { + Button::new(format!("Action {index}: {}", props.revision)).id_salt(index).show(ui); + } +} + +impl Scene for MemoRegions { + fn size(&self) -> Vec2 { + vec2(1800.0, 1200.0) + } + + fn show(&mut self, ui: &mut Ui, frame: u64) { + for region in 0..20_u64 { + let min = Pos2::new(10.0 + (region % 10) as f32 * 175.0, 10.0 + (region / 10) as f32 * 580.0); + let rect = egui::Rect::from_min_size(min, vec2(165.0, 570.0)); + let revision = if self.changing { (frame + 19 - region) / 20 } else { 0 }; + ui.scope_builder(egui::UiBuilder::new().id_salt(region).max_rect(rect), |ui| { + MemoView::new("buttons", MemoButtons { revision }, memo_buttons).show(ui); + }); + } + } +} + struct InspectorScene { values: Vec>, texts: Vec, diff --git a/crates/ui-bench/src/harness.rs b/crates/ui-bench/src/harness.rs index 44c37d6e6f..9b778d3e8d 100644 --- a/crates/ui-bench/src/harness.rs +++ b/crates/ui-bench/src/harness.rs @@ -89,8 +89,10 @@ fn run_frame(library: &dyn Library, ctx: &Context, scene: &mut dyn Scene, frame: library.before_frame(ctx); let (count, bytes) = allocations(); let start = Instant::now(); - let output = ctx.run_ui(raw, |ui| scene.show(ui, frame)); + let mut output = ctx.run_ui(raw, |ui| scene.show(ui, frame)); let passes = output.platform_output.num_completed_passes; + // This headless benchmark has no renderer to consume texture updates. + output.textures_delta.clear(); drop(output); let seconds = start.elapsed().as_secs_f64(); let (count_after, bytes_after) = allocations(); diff --git a/crates/ui-bench/src/scenario.rs b/crates/ui-bench/src/scenario.rs index 2357327640..faf38f616b 100644 --- a/crates/ui-bench/src/scenario.rs +++ b/crates/ui-bench/src/scenario.rs @@ -14,6 +14,8 @@ pub struct Scenario { /// Every scenario, in report order. pub const SCENARIOS: &[Scenario] = &[ + Scenario { name: "memo-regions-stationary", description: "400 buttons in 20 stationary memo regions", no_discard: false }, + Scenario { name: "memo-regions-changing", description: "400 buttons in 20 memo regions, one rebuilt each frame", no_discard: false }, Scenario { name: "inspector-500-fields", description: "an inspector of 500 Field rows", no_discard: false }, Scenario { name: "inspector-1000-fields", description: "an inspector of 1,000 Field rows", no_discard: false }, Scenario { name: "virtual-list-10000", description: "a 10,000-item virtual list", no_discard: false }, diff --git a/crates/ui-canvas/src/canvas/tool_host.rs b/crates/ui-canvas/src/canvas/tool_host.rs index 0af687f764..f1df3b62f7 100644 --- a/crates/ui-canvas/src/canvas/tool_host.rs +++ b/crates/ui-canvas/src/canvas/tool_host.rs @@ -1303,13 +1303,14 @@ impl<'a, 't: 'a> Run<'a, 't> { if self.state.gesture.is_none() { return; } - // A pass delivers only the moves it was handed: a rerun pass has none. A held pointer resting in the edge band - // or past it keeps one drag per pass, since the view scrolls under it. - let stirred = pointer::with_pass_pointer(self.ctx, |pass| pass.stirred); - if !stirred && self.edge_depth(pos).is_none() { + // A tool that takes every move gets each move of the pass, a move to the last move's position included. A pass + // delivers only the moves it was handed: a rerun pass has none. A held pointer resting in the edge band or past + // it keeps one drag per pass, since the view scrolls under it. + if self.every_move(start, press) { return; } - if !self.every_move(start, press) { + let stirred = pointer::with_pass_pointer(self.ctx, |pass| pass.stirred); + if stirred || self.edge_depth(pos).is_some() { self.drag(press_pointer(start, pos, self.time, press, self.kind)); } } diff --git a/crates/ui-canvas/src/canvas_controls/task_bar.rs b/crates/ui-canvas/src/canvas_controls/task_bar.rs index 610125e491..84c360686b 100644 --- a/crates/ui-canvas/src/canvas_controls/task_bar.rs +++ b/crates/ui-canvas/src/canvas_controls/task_bar.rs @@ -76,7 +76,8 @@ impl TaskBarPlace { /// - Area: the bar shows inside `area` (the canvas rect): a move stays inside it, and a stored place outside it comes /// back inside, its left and top edges winning where the bar does not fit. An anchor that leaves no room on either /// side (a crop frame larger than the view) has the bar over it, on its side's edge of the area, with all its -/// members. Its members continue on a new line when the area is too narrow for them. +/// members. In an area too narrow for its members, its selects narrow to fit one line first, and the members +/// continue on a new line only when they do not fit it even at their least. /// - Menu: Hide bar reports `hide`; Reset bar position clears the place, so the bar follows its anchor again; Pin bar /// position keeps it where it shows and, picked again, lets it follow its anchor from where it shows. /// - `place` is the caller's value (`Bind::bound`): the bar reads it before it shows and writes the pass's change diff --git a/crates/ui-canvas/tests/it/canvas/tool.rs b/crates/ui-canvas/tests/it/canvas/tool.rs index faabe7dd76..52b929dba4 100644 --- a/crates/ui-canvas/tests/it/canvas/tool.rs +++ b/crates/ui-canvas/tests/it/canvas/tool.rs @@ -1074,6 +1074,31 @@ fn a_pass_with_only_a_key_or_modifier_change_re_hovers_a_still_pointer_and_re_dr rig.fixture.frame(vec![pointer::release(at + BY)]); } +/// A pointer move to the position of the last move does not hover the still pointer again, in any number of passes. A +/// move somewhere else hovers once, and so does a move back in after the pointer left the window. +#[trial] +fn a_move_to_the_same_position_does_not_re_hover_a_still_pointer() { + let log = Log::default(); + let mut rig = Rig::with(Probe::new("main", &log), &log, None, Setup::default()); + let at = rig.centre(); + let count = |rig: &Rig| rig.calls().iter().filter(|logged| logged.as_str() == "main hover").count(); + + rig.fixture.frame(vec![pointer::moved(at)]).idle(2); + rig.log.borrow_mut().clear(); + for _ in 0..3 { + rig.fixture.frame(vec![pointer::moved(at)]); + } + rig.fixture.frame(vec![pointer::moved(at), pointer::moved(at)]); + assert_eq!(count(&rig), 0, "moves to the same position hover nothing: {:?}", rig.calls()); + + rig.fixture.frame(vec![pointer::moved(at + BY)]); + assert_eq!(count(&rig), 1, "a move somewhere else hovers once: {:?}", rig.calls()); + + rig.log.borrow_mut().clear(); + rig.fixture.frame(vec![pointer::gone()]).frame(vec![pointer::moved(at + BY)]); + assert_eq!(count(&rig), 1, "a move back in at the same position hovers once: {:?}", rig.calls()); +} + /// What the drag session of `DropperTool` carries. #[derive(Clone, Debug, PartialEq)] struct Parcel(u32); @@ -1667,6 +1692,30 @@ fn moves_inside_the_click_distance_reach_a_tool_that_takes_every_move() { } } +/// During a drag past the click distance, a move to the position of the last move still reaches a tool that takes every +/// move, one drag call per move. Any other tool gets no drag for it. +#[trial] +fn a_move_to_the_same_position_reaches_a_tool_that_takes_every_move() { + for every in [true, false] { + let log = Log::default(); + let mut main = Probe::new("main", &log); + main.every_move = every; + let mut rig = Rig::with(main, &log, None, Setup::default()); + let at = rig.centre(); + let to = at + Vec2::new(40.0, 0.0); + rig.fixture.frame(vec![pointer::press(at)]).frame(vec![pointer::moved(to)]); + let before = rig.main.borrow().drags.len(); + rig.fixture.frame(vec![pointer::moved(to), pointer::moved(to)]); + let seen: Vec = rig.main.borrow().drags[before..].iter().map(|(pos, _)| *pos).collect(); + if every { + assert_eq!(seen, [to, to], "each move to the same position reaches the tool"); + } else { + assert!(seen.is_empty(), "a tool that does not take every move gets no drag for a still pointer: {seen:?}"); + } + rig.fixture.frame(vec![pointer::release(to)]); + } +} + /// A right-click during a drag asks for the menu where it came up and leaves the drag to the tool: no release and no /// cancel until the primary button comes up (a dragged comment keeps moving while its page menu opens). #[trial] diff --git a/crates/ui-canvas/tests/it/canvas_controls/task_bar.rs b/crates/ui-canvas/tests/it/canvas_controls/task_bar.rs index 23a1ca6531..40abee2034 100644 --- a/crates/ui-canvas/tests/it/canvas_controls/task_bar.rs +++ b/crates/ui-canvas/tests/it/canvas_controls/task_bar.rs @@ -605,3 +605,51 @@ fn a_bar_clear_of_the_handles_hangs_farther_below_its_anchor() { assert!(default > 0.0, "the bar hangs below its anchor: {default}"); assert!(clear > default + 2.0 * SLACK, "the bar clear of the handles hangs farther below: {clear} against {default}"); } + +/// What a task bar of three buttons and a select showing its short entry beside a long one shows in an area cut to +/// `width` (the whole canvas when `None`): the bar's rect, then the rects of the first button, the select and the More +/// button. +fn type_bar(width: Option) -> (Rect, [Rect; 3]) { + use craft_ui::contract::{Entry, Props as _}; + use craft_ui::pickers::Select; + let scene = scene(); + let shared = Rc::clone(&scene); + let mut fixture = Fixture::new(move |ui| { + let _ = on_canvas(ui, |ui, area, view| { + let mut held = shared.borrow_mut(); + let scene = &mut *held; + let area = width.map_or(area, |width| Rect::from_min_size(area.min, Vec2::new(width, area.height()))); + scene.bounds = Rect::from_points(&scene.anchor.iter().map(|point| view.to_screen(*point)).collect::>()); + scene.area = area; + let entries = [Entry::new(0u8, "Source Sans 3"), Entry::new(1, "Source Sans 3 Semibold Condensed")]; + let shown = TaskBar::new("Type", &scene.anchor, Bind::bound(&mut scene.place)).show(ui, area, |ui, _| { + let _ = Button::new("Create Outlines").show(ui); + let _ = Button::new("Convert To Area Type").show(ui); + let _ = Button::new("Duplicate").show(ui); + let _ = Select::new("Font family", Bind::given(0u8), &entries).label("Font family").show(ui); + }); + scene.rect = shown.output.rect; + shown.output + }); + }); + fixture.room(Vec2::new(1120.0, 720.0)); + fixture.settle(); + let rect = |label: &str| fixture.by_label(label).unwrap_or_else(|| panic!("the bar shows {label}")).rect; + let members = [rect("Create Outlines"), rect("Font family"), rect("More options")]; + (seen(&scene).rect, members) +} + +/// A task bar a little too wide for its area narrows its select to fit one line before any member goes on a new line: +/// More stays on the members' line, and the bar is no wider than the area. +#[trial] +fn a_task_bar_a_little_too_wide_narrows_its_select_and_keeps_more_on_its_line() { + let (natural, [_, select, _]) = type_bar(None); + let width = natural.width() - select.width() / 4.0; + let (bar, [first, narrowed, more]) = type_bar(Some(width)); + assert!(bar.width() <= width + SLACK, "the bar {bar:?} fits the area {width} wide"); + for (name, member) in [("the select", narrowed), ("More", more)] { + assert!((member.center().y - first.center().y).abs() < SLACK, "{name} {member:?} sits on the first member's line {first:?}"); + } + assert!(narrowed.width() + SLACK < select.width(), "the select narrows: {narrowed:?} against {select:?}"); + assert!(more.max.x <= bar.max.x + SLACK, "More {more:?} lies inside the bar {bar:?}"); +} diff --git a/crates/ui-contract/src/contract/body/placement.rs b/crates/ui-contract/src/contract/body/placement.rs index cbecaae81d..95a1ec9c4b 100644 --- a/crates/ui-contract/src/contract/body/placement.rs +++ b/crates/ui-contract/src/contract/body/placement.rs @@ -148,11 +148,12 @@ fn resting_placement( let (Some(default), Place::Float(float), true) = (overlay.size, &overlay.place, overlay.fit == OverlayFit::Resizable) else { return placement; }; - let room = (screen.size() - Vec2::splat(2.0 * tokens.space.inset.screen)).max(Vec2::ZERO); + // A float placed by its top share has only the room below that top, so its default size is held to it as well. + let room = float.room_in(region, (screen.size() - Vec2::splat(2.0 * tokens.space.inset.screen)).max(Vec2::ZERO)); let least = overlay.size_limits.min.min(room); let size = default.max(least).min(overlay.size_limits.max.unwrap_or(Vec2::INFINITY)).min(room); // The saved position is the layer's top left; the float's is where its corner sits. - let pos = placement.pos.map(Pos2::from).or_else(|| float.top_left(size)).unwrap_or_else(|| region.center() - size / 2.0); + let pos = placement.pos.map(Pos2::from).unwrap_or_else(|| float.top_left_in(region, size)); let pos = overlay.drag_bounds.keep(Rect::from_min_size(pos, size), region, tokens).min; placement.pos = Some(pos.into()); placement.size = Some(size.into()); diff --git a/crates/ui-contract/src/contract/body/size.rs b/crates/ui-contract/src/contract/body/size.rs index 6116d8e383..af40fb28f1 100644 --- a/crates/ui-contract/src/contract/body/size.rs +++ b/crates/ui-contract/src/contract/body/size.rs @@ -387,15 +387,15 @@ impl<'b> BodyHooks<'b> { } } - /// The room a layer offers its content: the safe rect (the region of a contained layer), or the share of it the overlay caps its content at. + /// The room a layer offers its content: the safe rect (the region of a contained layer), or the share of it the overlay caps its content at; + /// for a float placed by its top share, no taller than the room below its top. fn layer_room(ctx: &Context, env: &Env, overlay: &crate::contract::Overlay) -> Rect { let bounds = crate::contract::overlay::screen_for(ctx, env, overlay); - match overlay.fit { - crate::contract::overlay::OverlayFit::ContentCapped(share) => { - Rect::from_min_size(bounds.min, Vec2::new(bounds.width() * share.x, bounds.height() * share.y)) - } - _ => bounds, - } + let room = match overlay.fit { + crate::contract::overlay::OverlayFit::ContentCapped(share) => Vec2::new(bounds.width() * share.x, bounds.height() * share.y), + _ => bounds.size(), + }; + Rect::from_min_size(bounds.min, overlay.room_in(bounds, room)) } } diff --git a/crates/ui-contract/src/contract/label/place.rs b/crates/ui-contract/src/contract/label/place.rs index 20b6169e14..7b972ba76d 100644 --- a/crates/ui-contract/src/contract/label/place.rs +++ b/crates/ui-contract/src/contract/label/place.rs @@ -60,10 +60,21 @@ pub(super) fn hidden_control(ctx: &egui::Context, input: &LabelIn<'_>, flow: Flo match crate::layout::ambient_width(ctx, &crate::layout::LABELS, 0.0).filter(|column| *column > 0.0) { Some(column) if input.room >= column + gap + input.control_min => { crate::layout::note_beside(ctx, &crate::layout::LABELS, input.room - gap - input.control_min); + // The help line under the control wraps in the control column, so its measure holds only at the column read. + if input.help.is_some() { + crate::layout::note_beside(ctx, &crate::layout::LABELS, column); + } let (_, rest) = flow.take_start(column); rest.take_start(gap).1.rect() } - _ => input.row, + Some(_) => input.row, + None => { + // No row has reported the column yet: the control takes the row only until one does. + if input.help.is_some() { + crate::layout::note_beside(ctx, &crate::layout::LABELS, 0.0); + } + input.row + } } } @@ -99,10 +110,12 @@ pub(super) fn decide(ctx: &egui::Context, env: &Env, input: &LabelIn<'_>, kids: let room = (input.row.width() - indent - input.control_min - gap).max(0.0); let wraps = natural.x > room; // A wider label column leaves the label less room: the row's measure holds while the group's column stays - // within the column it read, or for a label on one line, within the widest column that keeps it there. + // within the column it read, or for a label on one line, within the widest column that keeps it there. A help + // line under the control wraps in the control column, so with one the measure holds only at the column read. if let Some(column) = after_column { let one_line = input.row.width() - input.control_min - gap - natural.x - gap; - crate::layout::note_beside(ctx, &crate::layout::LABELS, if wraps { column } else { one_line }); + let holds = if wraps || input.help.is_some() { column } else { one_line }; + crate::layout::note_beside(ctx, &crate::layout::LABELS, holds); } if wraps { natural = leaf.measure_in(kids, craft_behavior::Proposal::Width(room)); @@ -113,11 +126,14 @@ pub(super) fn decide(ctx: &egui::Context, env: &Env, input: &LabelIn<'_>, kids: // row grows at its end edge. let grows = if input.egui_cell { Grows::Cell } else { Grows::End }; if input.side.layout == FieldLayout::Line { - let number = env.control(input.size).number; + let metrics = env.control(input.size); + let number = metrics.number; let flow = if input.egui_cell { widened(flow, natural.x + gap + number, grows) } else { flow }; let (cell, rest) = flow.take_end(number); let width = natural.x.min((rest.rect().width() - gap).max(0.0)); - let drop = (cell.height() - natural.y).max(0.0) / 2.0; + // The label is centered on the control's line at the top of the cell, which in a row is as tall as the row's + // room. + let drop = (metrics.height.min(cell.height()) - natural.y).max(0.0) / 2.0; let label = Flow::new(rest.rect(), rtl).align(Vec2::new(width, natural.y), Align::Min, Align::Min).translate(Vec2::new(0.0, drop)); return Placed { label, control: cell, trailing: Rect::NOTHING, caption: 0.0 }; } @@ -153,6 +169,10 @@ pub(super) fn decide(ctx: &egui::Context, env: &Env, input: &LabelIn<'_>, kids: // A label that sits beside the group's column measured so far stacks once the column passes this. if read && !stacks && !pinned { crate::layout::note_beside(ctx, &key, input.room - gap - input.control_min); + // The help line under the control wraps in the control column, so its measure holds only at the column read. + if input.help.is_some() { + crate::layout::note_beside(ctx, &key, column); + } } // A stacked label has the row's width at most, where its name elides; in an egui grid's cell it keeps its own. let column = if stacks && !input.egui_cell { column.min(input.row.width()) } else { column }; diff --git a/crates/ui-contract/src/contract/overlay/place.rs b/crates/ui-contract/src/contract/overlay/place.rs index 6b939084c5..afd949f960 100644 --- a/crates/ui-contract/src/contract/overlay/place.rs +++ b/crates/ui-contract/src/contract/overlay/place.rs @@ -31,6 +31,9 @@ pub struct FloatPlace { pub pos: Option, /// The corner of the layer that sits at `pos`. pub corner: Align2, + /// Without `pos`, the share of the viewport's height above the layer's top: the layer is centered across and its + /// top stays put as its height changes. `None` centers it on both axes. + pub top: Option, } impl Default for FloatPlace { @@ -42,23 +45,60 @@ impl Default for FloatPlace { impl FloatPlace { /// Centred in the viewport. pub const fn centred() -> Self { - FloatPlace { pos: None, corner: Align2::LEFT_TOP } + FloatPlace { pos: None, corner: Align2::LEFT_TOP, top: None } + } + + /// Centered across the viewport, with its top `share` of the viewport's height down from the viewport's top, so a + /// layer whose content grows or shrinks keeps its top edge where it is. The layer grows no taller than leaves the + /// same share below it. `share` is clamped to 0 to 0.5; a share that is not a number centers the layer. + pub const fn top_centered(share: f32) -> Self { + let top = if share.is_nan() { None } else { Some(share.clamp(0.0, 0.5)) }; + FloatPlace { pos: None, corner: Align2::LEFT_TOP, top } } /// With its left-top at `pos`. pub const fn at(pos: Pos2) -> Self { - FloatPlace { pos: Some(pos), corner: Align2::LEFT_TOP } + FloatPlace { pos: Some(pos), corner: Align2::LEFT_TOP, top: None } } /// With its `corner` at `pos`. pub const fn corner_at(pos: Pos2, corner: Align2) -> Self { - FloatPlace { pos: Some(pos), corner } + FloatPlace { pos: Some(pos), corner, top: None } } /// The top left of a layer `size` large whose `corner` sits at `pos`; `None` for a centred layer. pub(crate) fn top_left(&self, size: Vec2) -> Option { self.pos.map(|pos| pos - self.corner.pos_in_rect(&Rect::from_min_size(Pos2::ZERO, size)).to_vec2()) } + + /// The top left of a layer `size` large placed in `region`: at its position, else centered across with its top at + /// its share of the region's height, else centered. + pub(crate) fn top_left_in(&self, region: Rect, size: Vec2) -> Pos2 { + self.top_left(size).unwrap_or_else(|| { + let centered = region.center() - size / 2.0; + self.top.map_or(centered, |share| Pos2::new(centered.x, region.min.y + region.height() * share)) + }) + } + + /// `room` no taller than a layer placed by its top share may grow while the same share of `region` stays below it, + /// which holds the layer's frame: a layer as tall as it may grow keeps its top where the share puts it. `room` + /// unchanged for every other float. + pub(crate) fn room_in(&self, region: Rect, room: Vec2) -> Vec2 { + match (self.pos, self.top) { + (None, Some(share)) => Vec2::new(room.x, room.y.min(region.height() * (1.0 - 2.0 * share).max(0.0))), + _ => room, + } + } +} + +impl Place { + /// `room` within what `region` leaves a layer at this place ([`FloatPlace::room_in`]); unchanged when anchored. + pub(crate) fn room_in(&self, region: Rect, room: Vec2) -> Vec2 { + match self { + Place::Float(float) => float.room_in(region, room), + Place::Anchored { .. } => room, + } + } } /// How much of a floating layer stays inside the window: the whole layer (`Inside`, the default) or a strip of its title. diff --git a/crates/ui-contract/src/contract/overlay/placement.rs b/crates/ui-contract/src/contract/overlay/placement.rs index 896ec8d3a7..7b845aa041 100644 --- a/crates/ui-contract/src/contract/overlay/placement.rs +++ b/crates/ui-contract/src/contract/overlay/placement.rs @@ -149,6 +149,12 @@ impl Overlay { } overlay } + + /// `room` within what the safe rect `bounds`, cut to the overlay's own bounds (`within_bounds`) as the layer is + /// placed in them, leaves a float placed by its top share ([`FloatPlace::room_in`](super::FloatPlace)). + pub(crate) fn room_in(&self, bounds: Rect, room: egui::Vec2) -> egui::Vec2 { + self.place.room_in(within_bounds(self, bounds), room) + } } pub(super) fn anchor_rect(ctx: &Context, layer: &Layer<'_>, bounds: Rect, memory: &mut LayerMemory) -> Rect { @@ -240,14 +246,15 @@ fn off_edge(overlay: &Overlay, bounds: Rect, anchor: Rect, inset: f32) -> Rect { } /// The most a layer's body may take: the fit's share of the safe rect `bounds`, at least as wide as the layer's -/// least width, or the whole safe rect. +/// least width, or the whole safe rect; for a float placed by its top share, no taller than the room below its top. fn cap(overlay: &Overlay, bounds: Rect, anchor: Rect) -> egui::Vec2 { - match overlay.fit { + let cap = match overlay.fit { OverlayFit::ContentCapped(share) => { egui::Vec2::new((bounds.width() * share.x).max(overlay.least_width(anchor.width())), bounds.height() * share.y) } _ => bounds.size(), - } + }; + overlay.room_in(bounds, cap) } /// The room a layer offers its content before it is placed: the cap (a share of the safe rect `bounds`), and for an @@ -321,7 +328,7 @@ pub(super) fn placement(ctx: &Context, layer: &Layer<'_>, covers: bool, size: Op Place::Float(float) => { let kept = within_bounds(layer.overlay, bounds); let size = size.unwrap_or(egui::Vec2::ZERO); - let min = float.top_left(size).unwrap_or_else(|| kept.center() - size / 2.0); + let min = float.top_left_in(kept, size); let rect = Rect::from_min_size(min, size); let at = layer.overlay.drag_bounds.keep(rect, kept, &layer.env.tokens).min; let inside = crate::contract::body::keep_inside(rect, kept).min; diff --git a/crates/ui-contract/src/contract/run.rs b/crates/ui-contract/src/contract/run.rs index d622cbca60..66ca1003c5 100644 --- a/crates/ui-contract/src/contract/run.rs +++ b/crates/ui-contract/src/contract/run.rs @@ -873,7 +873,9 @@ fn place_root(p: &Pass<'_, '_, '_>, ui: &mut Ui, (at, place): (ShowAt, &Env), en if rtl { Rect::from_min_size(Pos2::new(flowed.max.x - across.x, flowed.min.y), across) } else { Rect::from_min_size(flowed.min, across) } } else { let fill = p.p.fills_width() && !p.p.fills_width_only(); - let size = if inert { Vec2::ZERO } else { size }; + // An inert leaf that measured zero on one side still takes its other side, so the body it sits in counts it + // as well as the gap before it. A size the guard rejects for any shape takes no room. + let size = if inert && !steps::guard(size, ShapeKind::Body) { Vec2::ZERO } else { size }; let placed = steps::place(ui, place, at, size, InFlow { fill, first: first(size.y), line: p.p.first_is_row_line() }); // A picture its measure held (`MeasureCx::picture_size`) reports its placed width, padding included. if let Some(ColumnSweep::Count(column)) = env.column diff --git a/crates/ui-contract/src/fonts/on_demand.rs b/crates/ui-contract/src/fonts/on_demand.rs index 8e2c5821a4..09882e40e1 100644 --- a/crates/ui-contract/src/fonts/on_demand.rs +++ b/crates/ui-contract/src/fonts/on_demand.rs @@ -193,6 +193,7 @@ impl OnDemandFonts { } } Shape::Vec(shapes) => shapes.iter().for_each(|s| collect(s, out, wanted)), + Shape::PaintChunk(shapes) => shapes.iter().for_each(|clipped| collect(&clipped.shape, out, wanted)), _ => {} } } diff --git a/crates/ui-contract/src/layout/body.rs b/crates/ui-contract/src/layout/body.rs index f090c7586f..a98971add0 100644 --- a/crates/ui-contract/src/layout/body.rs +++ b/crates/ui-contract/src/layout/body.rs @@ -118,7 +118,9 @@ impl BodyLayout { } } - /// A `Row` that wraps; any other layout is unchanged. + /// A `Row` that wraps; any other layout is unchanged. In a bar, a row placed from its start that is too long for one + /// line first narrows its selects and elidable text to fit it, from the end, as a bar's row that does not wrap does, + /// and continues on a new line only when they do not fit it even at their least. pub fn wrap(self, on: bool) -> Self { match self { BodyLayout::Row { align, .. } => BodyLayout::Row { wrap: on, align }, @@ -980,50 +982,7 @@ fn run_shrinking(ui: &mut Ui, place: &Env, id: Id, mut body: impl FnMut(&mut let room = shrink_room(ui, place); let order = if place.values.get::().0 { ShrinkOrder::FromEnd } else { ShrinkOrder::Even }; let (drops, gap) = (view_room(ui, place, Axis::X).is_none(), ui.spacing().item_spacing.x); - // Records the width each unit gets, and returns whether one took another width in the first sweep. The levelled - // units take their levels first, in the room the continuous units leave at their least; the continuous units then - // narrow by their own rule with the levelled units' widths held. A row without levelled units holds nothing more. - let settle = |leaves: &[Reported], fixed: f32| { - let (levelled, continuous): (Vec<&Reported>, Vec<&Reported>) = leaves.iter().partition(|leaf| !leaf.levels.is_empty()); - let units: Vec = continuous.iter().map(|leaf| leaf.widths).collect(); - let whole: Vec = continuous.iter().map(|leaf| leaf.whole).collect(); - let first: Vec = continuous.iter().map(|leaf| leaf.cut_first).collect(); - let ranks: Vec> = continuous.iter().map(|leaf| leaf.rank).collect(); - let level_widths: Vec> = levelled.iter().map(|leaf| leaf.levels.clone()).collect(); - let levels = if room.is_finite() { - plan_levels(&level_widths, room - fixed - units.iter().map(|unit| unit.least).sum::()) - } else { - vec![0; levelled.len()] - }; - let width_at = |leaf: &Reported, level: usize| leaf.levels.get(level).copied().unwrap_or_default(); - let held: f32 = levelled.iter().zip(&levels).map(|(leaf, level)| width_at(leaf, *level)).sum(); - // The ranked units give up `rank_short` of the row's ideal width; a row offered no bound (a content-sized row's - // measuring run) still drops them for it. - let ideal = fixed + held + units.iter().map(|unit| unit.ideal).sum::(); - let rank_room = rank_short.map_or(f32::INFINITY, |short| ideal - short); - let widths = if room.is_finite() || rank_room.is_finite() { - shrink_or_drop(&units, &whole, (&first, &ranks), (fixed + held, gap), (room, rank_room), order, drops) - } else { - units.iter().map(|unit| ShrinkCap { width: unit.ideal, dropped: false, narrowed: false }).collect() - }; - // A levelled unit took no place of its own content in the first sweep (it measured each level apart), so the - // records its content's run leaves for the real run come from a sweep at the levels given. - let mut again = !levelled.is_empty(); - for (leaf, cap) in continuous.iter().zip(widths) { - let measured = layout_memory::Measured::new(Vec2::new(room, 0.0), Vec2::new(cap.width, 0.0)); - let given = layout_memory::ShrinkGiven { dropped: cap.dropped, narrowed: cap.narrowed }; - layout_memory::emit_shrink(&ctx, shrink_key(id, leaf.leaf), measured, given); - // Half a point: less than a pixel shows at any scale the box runs. - again |= (leaf.took - cap.width).abs() >= 0.5; - } - for (leaf, level) in levelled.iter().zip(levels) { - // The level travels as the record's height (`level_of`). - let measured = layout_memory::Measured::new(Vec2::new(room, 0.0), Vec2::new(width_at(leaf, level), level as f32)); - let given = layout_memory::ShrinkGiven { dropped: false, narrowed: level > 0 }; - layout_memory::emit_shrink(&ctx, shrink_key(id, leaf.leaf), measured, given); - } - again - }; + let settle = |leaves: &[Reported], fixed: f32| settle_shrink(&ctx, id, (leaves, fixed), (room, gap), (rank_short, order, drops)); // A row that is the first control under a label holds every control the label's placement must leave room for. let labelled = scope::label_awaiting_min(&ctx); let (inner, rect, mut leaves, fixed, fills, probe, again) = crate::contract::keeping_ids(&ctx, || { @@ -1078,6 +1037,59 @@ fn run_shrinking(ui: &mut Ui, place: &Env, id: Id, mut body: impl FnMut(&mut } } +/// Records the width each unit of the row `id` gets from the shrink step, for `leaves` with `fixed` (the row's other +/// children and gaps) in `room` with `gap` between units, and returns whether one took another width in the first +/// sweep. The levelled units take their levels first, in the room the continuous units leave at their least; the +/// continuous units then narrow by their own rule with the levelled units' widths held. A row without levelled units +/// holds nothing more. `rank_short`, `order` and `drops` are as `run_shrinking` gives them. +fn settle_shrink( + ctx: &egui::Context, + id: Id, + (leaves, fixed): (&[Reported], f32), + (room, gap): (f32, f32), + (rank_short, order, drops): (Option, ShrinkOrder, bool), +) -> bool { + let (levelled, continuous): (Vec<&Reported>, Vec<&Reported>) = leaves.iter().partition(|leaf| !leaf.levels.is_empty()); + let units: Vec = continuous.iter().map(|leaf| leaf.widths).collect(); + let whole: Vec = continuous.iter().map(|leaf| leaf.whole).collect(); + let first: Vec = continuous.iter().map(|leaf| leaf.cut_first).collect(); + let ranks: Vec> = continuous.iter().map(|leaf| leaf.rank).collect(); + let level_widths: Vec> = levelled.iter().map(|leaf| leaf.levels.clone()).collect(); + let levels = if room.is_finite() { + plan_levels(&level_widths, room - fixed - units.iter().map(|unit| unit.least).sum::()) + } else { + vec![0; levelled.len()] + }; + let width_at = |leaf: &Reported, level: usize| leaf.levels.get(level).copied().unwrap_or_default(); + let held: f32 = levelled.iter().zip(&levels).map(|(leaf, level)| width_at(leaf, *level)).sum(); + // The ranked units give up `rank_short` of the row's ideal width; a row offered no bound (a content-sized row's + // measuring run) still drops them for it. + let ideal = fixed + held + units.iter().map(|unit| unit.ideal).sum::(); + let rank_room = rank_short.map_or(f32::INFINITY, |short| ideal - short); + let widths = if room.is_finite() || rank_room.is_finite() { + shrink_or_drop(&units, &whole, (&first, &ranks), (fixed + held, gap), (room, rank_room), order, drops) + } else { + units.iter().map(|unit| ShrinkCap { width: unit.ideal, dropped: false, narrowed: false }).collect() + }; + // A levelled unit took no place of its own content in the first sweep (it measured each level apart), so the + // records its content's run leaves for the real run come from a sweep at the levels given. + let mut again = !levelled.is_empty(); + for (leaf, cap) in continuous.iter().zip(widths) { + let measured = layout_memory::Measured::new(Vec2::new(room, 0.0), Vec2::new(cap.width, 0.0)); + let given = layout_memory::ShrinkGiven { dropped: cap.dropped, narrowed: cap.narrowed }; + layout_memory::emit_shrink(ctx, shrink_key(id, leaf.leaf), measured, given); + // Half a point: less than a pixel shows at any scale the box runs. + again |= (leaf.took - cap.width).abs() >= 0.5; + } + for (leaf, level) in levelled.iter().zip(levels) { + // The level travels as the record's height (`level_of`). + let measured = layout_memory::Measured::new(Vec2::new(room, 0.0), Vec2::new(width_at(leaf, level), level as f32)); + let given = layout_memory::ShrinkGiven { dropped: false, narrowed: level > 0 }; + layout_memory::emit_shrink(ctx, shrink_key(id, leaf.leaf), measured, given); + } + again +} + /// In a body that scrolls along `axis`, what its view shows along it from the start of the rest of `ui`'s layout: along /// x the width a row there shrinks to fit and a child that fills its width fills, along y the height the children that /// fill a `Stack` there share. `None` outside such a body. @@ -2212,6 +2224,8 @@ fn run_row(ui: &mut Ui, env: &Env, at: &RowIn, (wrap, align): (bool, RowAlign inner }) .0 + } else if lines && align == RowAlign::Start && row.values.get::().0 { + run_wrap_start(ui, &row, (id, sizing, rtl), &mut body) } else if wrap { body(ui) } else { @@ -2260,6 +2274,70 @@ fn run_row(ui: &mut Ui, env: &Env, at: &RowIn, (wrap, align): (bool, RowAlign (inner, (align != RowAlign::Start).then(|| took.width())) } +/// Runs `body`, the children of the wrapping `Row` body `id` of a bar placed from its start, in `ui`, the block they +/// wrap in, under `row`. Children too wide for one line first narrow to fit it by the shrink step of an unwrapped bar +/// row (`settle_shrink`, from the end); they go on new lines only when they do not fit it even at their least. A measuring run decides +/// which from a counting sweep it takes back (`narrows_to_line`) and records the widths, and the real run reads its +/// decision. Either way the children run in a child of `ui` with its wrapping layout, so they keep their ids and +/// their lines' alignment. +fn run_wrap_start(ui: &mut Ui, row: &Env, (id, sizing, rtl): (Id, bool, bool), body: &mut impl FnMut(&mut Ui) -> R) -> R { + let ctx = ui.ctx().clone(); + let key = sub(id, "narrows"); + let room = ui.available_rect_before_wrap().width(); + let narrows = if sizing { + let counted = if room.is_finite() { narrows_to_line(ui, row, id, (child::row_layout(rtl, false), room), body) } else { None }; + if let Some((leaves, fixed)) = &counted { + settle_shrink(&ctx, id, (leaves, *fixed), (room, ui.spacing().item_spacing.x), (None, ShrinkOrder::FromEnd, false)); + } + found(&ctx, true, key, Vec2::new(room, 0.0), Vec2::new(if counted.is_some() { 1.0 } else { 0.0 }, 0.0)); + counted.is_some() + } else { + this_pass(&ctx, false, key).is_some_and(|took| took.x > 0.5) + }; + // In a child with the block's layout, as the counting sweep runs in one: the children take the same ids in the + // counting sweep and here, whether they narrow or wrap. + let shown = if narrows { row.derive_local(|scoped| scoped.shrink = Some(Shrink::Apply(id))) } else { row.clone() }; + let layout = *ui.layout(); + child::block(ui, None, layout, |ui| Env::run_in(ui, shown, &mut *body)).0 +} + +/// The units of the row `id`, counted in a sweep of `body` laid out on one `line` and taken back, with the width its +/// other children and gaps take, when they are too wide for `room` at their natural widths and fit it at their least; +/// `None` otherwise. A body among them counts at its natural width, and no unit carries a rank. +fn narrows_to_line( + ui: &mut Ui, + row: &Env, + id: Id, + (line, room): (egui::Layout, f32), + body: &mut impl FnMut(&mut Ui) -> R, +) -> Option<(Vec, f32)> { + let ctx = ui.ctx().clone(); + let count = row.derive_local(|scoped| { + scoped.rank_short = None; + scoped.shrink = Some(Shrink::Count(id)); + }); + let (counted, _) = crate::contract::draft( + &ctx, + || { + pass_state::with::(&ctx, |reports| reports.0.insert(id, Vec::new())); + let mut sweep = laid_out_child(ui, line); + let _ = Env::run_in(&mut sweep, count.clone(), &mut *body); + let mut leaves = pass_state::with::(&ctx, |reports| reports.0.remove(&id)).unwrap_or_default(); + // A wrapping row keeps every member: none leaves by rank, which would bring it back on a new line once + // the row is too narrow to narrow. + for leaf in &mut leaves { + leaf.rank = None; + } + let fixed = sweep.min_rect().width() - leaves.iter().map(|leaf| leaf.took).sum::(); + let short = |width: fn(&Reported) -> f32| fixed + leaves.iter().map(width).sum::() - room; + // Half a point: less than a pixel shows at any scale the box runs. + (short(|leaf| leaf.widths.ideal) >= 0.5 && short(|leaf| leaf.widths.least) < 0.5).then_some((leaves, fixed)) + }, + |_| false, + ); + counted +} + /// The line the children of the wrapping `SpaceBetween` row `id` sit on when they `took` one line, with the line /// `shared` it shares with its container's inline header or end region: how far below the row's top the line's centre /// lies, and the row's height once every child sits on it, as `record_line` finds an unwrapped row's. `None` when the diff --git a/crates/ui-contract/src/primitives/sensing.rs b/crates/ui-contract/src/primitives/sensing.rs index 849167f68b..9997d93520 100644 --- a/crates/ui-contract/src/primitives/sensing.rs +++ b/crates/ui-contract/src/primitives/sensing.rs @@ -267,14 +267,55 @@ pub(crate) struct Outcome { xf: Option, } +/// A real run reuses its buffer; a replay borrows the immutable registration it +/// recorded. Swapping current and previous lists keeps the same lifecycle as an +/// ordinary registration without copying each part on every stationary replay. +struct Registrations { + owned: Vec, + retained: Option>, +} + +impl Default for Registrations { + fn default() -> Self { + Self { owned: Vec::new(), retained: None } + } +} + +impl std::ops::Deref for Registrations { + type Target = [T]; + + fn deref(&self) -> &Self::Target { + self.retained.as_deref().unwrap_or(&self.owned) + } +} + +impl Registrations { + fn clear(&mut self) { + self.retained = None; + self.owned.clear(); + } + + fn retain(&mut self, values: &Arc<[T]>) { + self.owned.clear(); + self.retained = Some(Arc::clone(values)); + } +} + +impl Registrations { + fn copy_from(&mut self, values: &[T]) { + self.clear(); + self.owned.extend_from_slice(values); + } +} + #[derive(Default)] struct ArenaState { /// The pass the registration lists below belong to. pass: u64, members: Vec, previous: Vec, - own: Vec, - previous_own: Vec, + own: Registrations, + previous_own: Registrations, /// The stack position of the root's own `over` parts: above the members its body showed and below the ones /// `paint_over` shows (`place_over_widgets`). Above everything until the owner has placed them. own_over_at: u32, @@ -289,8 +330,6 @@ struct ArenaState { /// The pass whose outcome `sense_early` stepped before the root's step 8. early: u64, root: Option, - /// The egui widgets of the root: the root's, the transform forwarder and the edge widgets. - widgets: Vec, machine: PressMachine, outcome: Option, /// The host asked to end the open press (`cancel_press_of`): the arena's next lifecycle run ends it. @@ -553,29 +592,27 @@ impl crate::runtime::Shift for RootRegistration { #[derive(Clone, Debug, PartialEq)] struct RootRegistration { info: RootInfo, - own: Vec, - widgets: Vec, + own: Arc<[PartDecl]>, layer: Layer, } /// Notes a root's step-8 registration in the open records. -fn journal_root(ctx: &Context, arena: ArenaId, info: RootInfo, own: &[PartDecl], widgets: &[Id], layer: Layer) { +fn journal_root(ctx: &Context, arena: ArenaId, info: RootInfo, own: &[PartDecl], layer: Layer) { crate::runtime::replay::journal( ctx, - || (arena, RootRegistration { info, own: own.to_vec(), widgets: widgets.to_vec(), layer }), - |ctx, (arena, registration)| register_root_again(ctx, *arena, registration.clone()), + || (arena, RootRegistration { info, own: Arc::from(own), layer }), + |ctx, (arena, registration)| register_root_again(ctx, *arena, registration), ); } /// A replayed root's step-8 registration: its own parts, rect, widgets and layer, with no press run. -fn register_root_again(ctx: &Context, arena: ArenaId, registration: RootRegistration) { - journal_root(ctx, arena, registration.info, ®istration.own, ®istration.widgets, registration.layer); +fn register_root_again(ctx: &Context, arena: ArenaId, registration: &RootRegistration) { + journal_root(ctx, arena, registration.info, ®istration.own, registration.layer); let pass_nr = pass::pass_nr(ctx, pass::current_viewport(ctx)); with_arena(ctx, arena, pass_nr, |state| { rotate(state, pass_nr); - state.own = registration.own; + state.own.retain(®istration.own); state.root = Some(registration.info); - state.widgets = registration.widgets; state.last_layer = Some(registration.layer); }); } @@ -777,15 +814,13 @@ pub(crate) fn sense_root(ui: &Ui, spec: RootSpec<'_>) -> RootResult { let background = background_shape(spec.id, spec.rect, spec.own_sense | Sense::HOVER); pointer::record_widgets_in(ctx, read.viewport, layer, spec.id, &widgets, sense.contains(Sense::CLICK)); let info = RootInfo { id: spec.id, rect: spec.rect }; - journal_root(ctx, arena, info, spec.own, &widgets, layer); + journal_root(ctx, arena, info, spec.own, layer); // The parts last pass registered, which this pass's results read. let known = with_arena_in(ctx, read.viewport, arena, read.pass_nr, |state| { rotate(state, read.pass_nr); state.widens = spec.enabled; - state.own.clear(); - state.own.extend_from_slice(spec.own); + state.own.copy_from(spec.own); state.root = Some(info); - state.widgets = widgets; state.last_layer = Some(layer); // A root that stepped early while it was not yet known to be inert: an open press ends as the disabled root's // would, by stepping again with the cancel. diff --git a/crates/ui-contract/src/runtime/egui/fixture.rs b/crates/ui-contract/src/runtime/egui/fixture.rs index 1202576a3c..c41f3cf1be 100644 --- a/crates/ui-contract/src/runtime/egui/fixture.rs +++ b/crates/ui-contract/src/runtime/egui/fixture.rs @@ -491,6 +491,7 @@ fn stroke_width(shape: &Shape) -> f32 { fn flatten_ref<'a>(shape: &'a Shape, out: &mut Vec<&'a Shape>) { match shape { Shape::Vec(shapes) => shapes.iter().for_each(|shape| flatten_ref(shape, out)), + Shape::PaintChunk(shapes) => shapes.iter().for_each(|clipped| flatten_ref(&clipped.shape, out)), other => out.push(other), } } @@ -498,6 +499,7 @@ fn flatten_ref<'a>(shape: &'a Shape, out: &mut Vec<&'a Shape>) { pub(crate) fn flatten(shape: Shape, out: &mut Vec) { match shape { Shape::Vec(shapes) => shapes.into_iter().for_each(|shape| flatten(shape, out)), + Shape::PaintChunk(shapes) => shapes.iter().for_each(|clipped| flatten(clipped.shape.clone(), out)), other => out.push(other), } } diff --git a/crates/ui-contract/src/runtime/egui/input.rs b/crates/ui-contract/src/runtime/egui/input.rs index 049701d614..b427d3c792 100644 --- a/crates/ui-contract/src/runtime/egui/input.rs +++ b/crates/ui-contract/src/runtime/egui/input.rs @@ -338,7 +338,7 @@ pub(crate) struct PointerRead { pub sample: Option, /// The window lost focus in this pass. pub focus_lost: bool, - /// Whether the real pointer moved or entered, or a held modifier or key changed, in this pass. + /// Whether a held modifier or key changed in this pass. The begin hook adds the pass's moves to a new position. pub stirred: bool, /// The pass's finger events, in arrival order. pub touches: Vec, @@ -432,7 +432,6 @@ pub(crate) fn pointer_read(ctx: &Context) -> PointerRead { } } Event::PointerMoved(pos) => { - stirred = true; moves.push(events.len()); events.push(PointerEvent::moved(*pos, None)); } @@ -546,6 +545,88 @@ pub(crate) fn hit_targets(ctx: &Context) -> (Option, Option) { ctx.viewport(|viewport| (viewport.hits.click.map(|widget| widget.id), viewport.hits.drag.map(|widget| widget.id))) } +/// The events of a pass that `pass_held_mods` reads. +#[derive(Clone, Copy, PartialEq, Eq)] +pub(crate) enum HeldSpan { + /// Every event, and the modifiers held at the pass's end. + Pass, + /// The events from the first wheel, zoom, rotation or touch onward, and the modifiers held at the pass's end. + FromWheel, + /// The events up to and including the first primary press, with the modifiers of a Ctrl+wheel folded into a pinch + /// step before it; no modifiers when the pass has no such press. + ToPress, +} + +/// The position of the pass's first primary press in `events`. +fn first_primary_press(events: &[Event]) -> Option { + events.iter().position(|event| matches!(event, Event::PointerButton { button: egui::PointerButton::Primary, pressed: true, .. })) +} + +/// Whether a wheel or zoom event of the pass arrived before its first primary press; `false` when the pass has no +/// such press. +pub(crate) fn wheel_before_press(ctx: &Context) -> bool { + ctx.input(|input| { + let all = input.raw.events.as_slice(); + first_primary_press(all).is_some_and(|press| all[..press].iter().any(|event| matches!(event, Event::MouseWheel { .. } | Event::Zoom(_)))) + }) +} + +/// The modifiers held at any point of the pass: those held at its end and those each key, button, wheel and +/// modifier event of the pass carries, so a key pressed and released within the pass counts, and an Alt key's press. +/// `span` narrows the events that count. +pub(crate) fn pass_held_mods(ctx: &Context, span: HeldSpan) -> Mods { + let os = crate::runtime::windows::os_of(ctx); + let folded = PerViewport::::with(ctx, super::pass::current_viewport(ctx), |state| state.folded_mods); + ctx.input(|input| { + let all = input.raw.events.as_slice(); + let (events, mut held) = match span { + HeldSpan::Pass => (all, Mods::from_egui(&(input.modifiers | folded), os)), + HeldSpan::FromWheel => { + // Every event form that moves a wheel share begins a gesture. + let from = all + .iter() + .position(|event| matches!(event, Event::MouseWheel { .. } | Event::Zoom(_) | Event::Rotate(_) | Event::Touch { .. })) + .unwrap_or(all.len()); + (&all[from..], Mods::from_egui(&(input.modifiers | folded), os)) + } + HeldSpan::ToPress => { + let Some(press) = first_primary_press(all) else { + return Mods::NONE; + }; + // A folded Ctrl+wheel is an `Event::Zoom` now, which carries no modifiers. An input with a native zoom + // folds none, so a zoom of a pass with folded modifiers is a folded step. + let folded_before = all[..press].iter().any(|event| matches!(event, Event::Zoom(_))); + (&all[..=press], if folded_before { Mods::from_egui(&folded, os) } else { Mods::NONE }) + } + }; + // The first Alt event from the span's start onward tells whether Alt was down there. + let rest = if span == HeldSpan::ToPress { all } else { events }; + held.alt |= rest + .iter() + .find_map(|event| match event { + Event::Key { key: Key::AltLeft | Key::AltRight, pressed, repeat, .. } => Some(!*pressed || *repeat), + _ => None, + }) + .unwrap_or_else(|| input.key_down(Key::AltLeft) || input.key_down(Key::AltRight)); + for event in events { + // On Windows an Alt key's own events can arrive while the modifier flags miss it, as in `wheel_read`. + if let Event::Key { key: Key::AltLeft | Key::AltRight, pressed: true, .. } = event { + held.alt = true; + } + let modifiers = match event { + Event::Key { modifiers, .. } + | Event::PointerButton { modifiers, .. } + | Event::MouseWheel { modifiers, .. } + | Event::ModifiersChanged(modifiers) => modifiers, + _ => continue, + }; + let mods = Mods::from_egui(modifiers, os); + held = Mods { cmd: held.cmd || mods.cmd, ctrl: held.ctrl || mods.ctrl, alt: held.alt || mods.alt, shift: held.shift || mods.shift }; + } + held + }) +} + /// The wheel input of the pass: the summed scroll in points (`line` and `page` points per line and page), the /// last event's unit, phase and modifiers, and the device: fingers when any event of the pass came from them. `None` /// when no wheel event arrived. @@ -656,10 +737,12 @@ fn wheel_lines(unit: MouseWheelUnit, delta: Vec2, line: f32, page: f32) -> Vec2 /// Removes the events a modal layer in another viewport blocks: button and key presses, wheel, text, clipboard and /// touch. Pointer moves and releases stay, so the pointer position stays right and no press or key sticks down. The /// events `keep` admits stay too (the canvas the modal leaves open, `runtime::sampler`); `pointer` is where the pointer -/// stood before `events`. Returns whether anything went and whether a pointer press did or was kept. -pub(crate) fn drop_under_modal(events: &mut Vec, keep: Option<&crate::runtime::sampler::Hole>, pointer: Option) -> (bool, bool) { +/// stood before `events`. Returns whether anything went, whether a pointer press did or was kept, and whether a wheel +/// event went. +pub(crate) fn drop_under_modal(events: &mut Vec, keep: Option<&crate::runtime::sampler::Hole>, pointer: Option) -> (bool, bool, bool) { let before = events.len(); let mut press = false; + let mut wheel = false; let mut at = pointer; events.retain(|Arrived { event, .. }| { match event { @@ -678,9 +761,11 @@ pub(crate) fn drop_under_modal(events: &mut Vec, keep: Option<&crate::r | Event::Touch { .. } ); press |= matches!(event, Event::PointerButton { pressed: true, .. }); - !blocked || keep.is_some_and(|hole| hole.admits(event, at)) + let admitted = !blocked || keep.is_some_and(|hole| hole.admits(event, at)); + wheel |= !admitted && matches!(event, Event::MouseWheel { .. }); + admitted }); - (events.len() != before, press) + (events.len() != before, press, wheel) } /// Adds a release of `button` at `pos` after the events of `input`; it carries no modifiers. @@ -799,6 +884,7 @@ pub(crate) fn fold_legacy_pinch(ctx: &Context, input: &mut RawInput) { let points = if unit == MouseWheelUnit::Line { delta * line } else { delta }; *event = Event::Zoom((speed * (points.x + points.y)).exp()); state.folded_lines += wheel_lines(unit, delta, line, 0.0); + state.folded_mods |= modifiers; state.last_pinch = now.or(state.last_pinch); } }); @@ -811,6 +897,8 @@ pub(crate) struct RawState { last_pinch: Option, /// The wheel lines of the Ctrl+wheel events folded into pinch steps in the running pass's input (`zoom_wheel_lines`). folded_lines: Vec2, + /// The modifiers of the Ctrl+wheel events folded into pinch steps in the running pass's input (`pass_held_mods`). + folded_mods: egui::Modifiers, control_click: ControlClick, /// The Alt+numpad entry in progress. alt_code: super::alt_code::AltCodeEntry, @@ -830,7 +918,7 @@ pub(crate) fn prepare(ctx: &Context, input: &mut RawInput) { // This frame's `RootEnv`, which `set_input` stored before egui ran the input hook. let root = crate::runtime::frame::root_input(ctx); // Each pass's input folds its own steps: a later pass of the frame, whose input holds no events, reads none. - PerViewport::::with(ctx, input.viewport_id, |state| state.folded_lines = Vec2::ZERO); + PerViewport::::with(ctx, input.viewport_id, |state| (state.folded_lines, state.folded_mods) = (Vec2::ZERO, egui::Modifiers::NONE)); if root.ctrl_wheel_pinch { fold_legacy_pinch(ctx, input); } diff --git a/crates/ui-contract/src/runtime/egui/repaint.rs b/crates/ui-contract/src/runtime/egui/repaint.rs index 7eba495107..239ca2d1df 100644 --- a/crates/ui-contract/src/runtime/egui/repaint.rs +++ b/crates/ui-contract/src/runtime/egui/repaint.rs @@ -5,14 +5,20 @@ use egui::Context; /// Asks for one more pass after this one. The repaint cause names the caller. #[track_caller] pub(crate) fn request(ctx: &Context) { - crate::runtime::replay::note_unsettled(ctx); + // A transport or worker may wake this context while its UI thread owns the pass state. + if crate::runtime::frame::running(ctx).is_some() { + crate::runtime::replay::note_unsettled(ctx); + } ctx.request_repaint(); } /// Asks for a pass of `viewport` at once. The repaint cause names the caller. #[track_caller] pub(crate) fn request_of(ctx: &Context, viewport: egui::ViewportId) { - crate::runtime::replay::note_unsettled(ctx); + // A transport or worker may wake this context while its UI thread owns the pass state. + if crate::runtime::frame::running(ctx).is_some() { + crate::runtime::replay::note_unsettled(ctx); + } ctx.request_repaint_of(viewport); } diff --git a/crates/ui-contract/src/runtime/env/shell.rs b/crates/ui-contract/src/runtime/env/shell.rs index 3d0b70fa5f..411a22787d 100644 --- a/crates/ui-contract/src/runtime/env/shell.rs +++ b/crates/ui-contract/src/runtime/env/shell.rs @@ -122,6 +122,9 @@ struct Inner { edges: [bool; 3], tabs: bool, panels_hidden: bool, + /// In standard screen mode the user hid the editor's chrome with Tab: the docks, rails and floating panels of the + /// body hide with the shell's bars, while the body itself and the document tabs stay. + chrome_hidden: bool, regions: ShellRegions, float_bounds: Rect, region: Option, @@ -197,6 +200,7 @@ impl ShellCx { edges: [false; 3], tabs: true, panels_hidden: false, + chrome_hidden: false, regions, float_bounds, region: None, @@ -224,6 +228,13 @@ impl ShellCx { self } + /// The editor's chrome is hidden: the user pressed Tab in standard screen mode, so the shell's bars and rails are + /// gone and the body's docks, rails and floating panels go with them, while the body and the document tabs stay. + pub fn with_chrome_hidden(mut self, hidden: bool) -> Self { + Arc::make_mut(&mut self.inner).chrome_hidden = hidden; + self + } + /// The Tab reveal is on or off. pub fn with_tab_reveal(mut self, on: bool) -> Self { Arc::make_mut(&mut self.inner).tab_reveal = on; @@ -280,11 +291,18 @@ impl ShellCx { self.inner.panels_hidden } - /// Whether the dock at `edge` shows: in normal mode and during the Tab reveal unless the panels are hidden, and the - /// `Start` and `End` docks also while that edge's reveal is on, in body-only mode or while the panels are hidden. + /// Whether the user hid the editor's chrome with Tab in standard screen mode: the shell's bars are gone and the + /// body's docks and floating panels hide with them, while the body and the document tabs stay. + pub fn chrome_hidden(&self) -> bool { + self.inner.chrome_hidden + } + + /// Whether the dock at `edge` shows: in normal mode and during the Tab reveal unless the panels are hidden or the + /// editor's chrome is, and the `Start` and `End` docks also while that edge's reveal is on, in body-only mode or + /// while the panels are hidden. pub fn dock_visible(&self, edge: super::PaneEdge) -> bool { let inner = &*self.inner; - let base = !inner.panels_hidden && (inner.mode == BodyMode::Normal || inner.tab_reveal); + let base = !inner.panels_hidden && !inner.chrome_hidden && (inner.mode == BodyMode::Normal || inner.tab_reveal); base || match edge { super::PaneEdge::Start => self.edge_revealed(RevealEdge::Start), super::PaneEdge::End => self.edge_revealed(RevealEdge::End), @@ -293,9 +311,9 @@ impl ShellCx { } /// Whether floating frames show: in normal mode; in body-only mode only during the Tab reveal; never while the - /// panels are hidden. + /// panels are hidden or the editor's chrome is. pub fn floating_visible(&self) -> bool { - !self.inner.panels_hidden && (self.inner.mode == BodyMode::Normal || self.inner.tab_reveal) + !self.inner.panels_hidden && !self.inner.chrome_hidden && (self.inner.mode == BodyMode::Normal || self.inner.tab_reveal) } /// The same skeleton with its revealed rects registered under `id`, which stays the same across passes. Without @@ -344,17 +362,19 @@ impl ShellCx { } /// Are slots shown by a reveal (Tab or edge) on this pass? Only body-only mode reveals with Tab; an edge reveals in - /// body-only mode and while the panels are hidden. + /// body-only mode, while the panels are hidden, and while the editor's chrome is. pub fn revealed(&self) -> bool { let inner = &*self.inner; let body_only = inner.mode == BodyMode::Only; - (body_only && inner.tab_reveal) || ((body_only || inner.panels_hidden) && inner.edges.iter().any(|on| *on)) + let hides_docks = body_only || inner.panels_hidden || inner.chrome_hidden; + (body_only && inner.tab_reveal) || (hides_docks && inner.edges.iter().any(|on| *on)) } - /// Is the edge reveal on for `edge`? False while the panels show in normal mode, and during the Tab reveal. + /// Is the edge reveal on for `edge`? False while the panels show in normal mode with the editor's chrome shown, + /// and during the Tab reveal. pub fn edge_revealed(&self, edge: RevealEdge) -> bool { let inner = &*self.inner; - (inner.mode == BodyMode::Only || inner.panels_hidden) && !inner.tab_reveal && inner.edges[edge.index()] + (inner.mode == BodyMode::Only || inner.panels_hidden || inner.chrome_hidden) && !inner.tab_reveal && inner.edges[edge.index()] } /// The body rect and the shown slots of this pass. @@ -390,12 +410,25 @@ pub struct ShellEntry(#[doc(hidden)] pub Option); impl crate::contract::MemoProps for ShellEntry { fn key(&self, key: &mut crate::contract::MemoKey) { let Some(shell) = &self.0 else { return key.write_u32(0) }; - let Inner { window, mode, tab_reveal, edges, tabs, panels_hidden, regions, float_bounds, region, page_band, reveals: _, dialog: _ } = - &*shell.inner; + let Inner { + window, + mode, + tab_reveal, + edges, + tabs, + panels_hidden, + chrome_hidden, + regions, + float_bounds, + region, + page_band, + reveals: _, + dialog: _, + } = &*shell.inner; key.write_u32(1); key.feed_hash(window); key.feed_hash(&std::mem::discriminant(mode)); - (*tab_reveal, *edges, *tabs, *panels_hidden).key(key); + (*tab_reveal, *edges, *tabs, *panels_hidden, *chrome_hidden).key(key); regions.body.key(key); key.write_u32(regions.slots.len() as u32); for (slot, rect) in ®ions.slots { diff --git a/crates/ui-contract/src/runtime/frame.rs b/crates/ui-contract/src/runtime/frame.rs index bcb8b6947c..10d75c74da 100644 --- a/crates/ui-contract/src/runtime/frame.rs +++ b/crates/ui-contract/src/runtime/frame.rs @@ -193,6 +193,8 @@ pub(crate) struct FrameState { root_passes_hooked: u64, /// What drops the records of closed viewports as a frame begins. prunes: HashMap, + /// What drops the pass-stamped records of a viewport whose pass count egui started again. + restarts: HashMap, sweeps: HashMap, /// What a layer above the runtime reads at the begin hook, after the pointer snapshot and before any component runs. begins: HashMap, @@ -286,12 +288,20 @@ pub trait Stored: Default + Send + 'static { fn stamped(ctx: &Context, f: impl FnOnce(&mut PerViewport>) -> R) -> R { pass_state::with_records::, R>(ctx, f) } + + /// Drops the record of `viewport` when this type's records carry the viewport's pass number ([`Stamped`]): egui + /// counts the passes of that viewport from zero again, which the begin hook finds. Other records stay. + fn forget_restarted(_ctx: &Context, _viewport: ViewportId) {} } impl Stored for Stamped { fn records(ctx: &Context, f: impl FnOnce(&mut PerViewport) -> R) -> R { T::stamped(ctx, f) } + + fn forget_restarted(ctx: &Context, viewport: ViewportId) { + Self::records(ctx, |records| records.records.retain(|(id, _)| *id != viewport)); + } } impl PerViewport { @@ -335,6 +345,9 @@ impl PerViewport { T::records(ctx, |records| records.records.retain(|(viewport, _)| live.contains(viewport))); } register_prune(ctx, TypeId::of::(), prune::); + pass_state::with::(ctx, |state| { + state.restarts.entry(TypeId::of::()).or_insert(T::forget_restarted); + }); } } @@ -395,6 +408,14 @@ fn prune_closed(ctx: &Context) { } } +/// Drops the pass-stamped records of `viewport`, whose passes egui counts from zero again. +fn forget_restarted(ctx: &Context, viewport: ViewportId) { + let restarts: Vec = pass_state::with::(ctx, |state| state.restarts.values().copied().collect()); + for restart in restarts { + restart(ctx, viewport); + } +} + /// Registers a sweep the end hook runs for the running viewport's pass, once per service type. pub(crate) fn register_end_sweep(ctx: &Context, key: TypeId, sweep: fn(&Context)) { pass_state::with::(ctx, |state| { @@ -675,6 +696,8 @@ struct ViewportRecord { press_cancelled: bool, /// `None` until the viewport's first pass begins. now: Option, + /// The pass number of the viewport's latest pass the begin hook ran for. + began: Option, } impl Stored for ViewportRecord {} @@ -820,6 +843,13 @@ pub(crate) fn begin_pass(ui: &mut Ui) { // H5: read the clock once; the runtime cancelled a captured press since this viewport's last pass. let now = pass::now(&ctx); let (pass_nr, frame_nr) = (pass::pass_nr(&ctx, viewport), ctx.cumulative_frame_nr_for(viewport)); + // egui drops a child viewport that a pass of its parent leaves out, and counts the passes of the viewport it opens + // again under that id from zero. Its window stays open, and so do its records: a stamp from before the restart can + // equal the number of a later pass. + let restarted = PerViewport::::with(&ctx, viewport, |record| record.began.replace(pass_nr).is_some_and(|began| pass_nr <= began)); + if restarted { + forget_restarted(&ctx, viewport); + } let (elapsed, cancelled) = PerViewport::::with(&ctx, viewport, |record| { // The events this frame's input hook held arrived at the frame's input time. record.held.stamp(now); diff --git a/crates/ui-contract/src/runtime/keys/input.rs b/crates/ui-contract/src/runtime/keys/input.rs index bd273edf09..ed06346dab 100644 --- a/crates/ui-contract/src/runtime/keys/input.rs +++ b/crates/ui-contract/src/runtime/keys/input.rs @@ -654,8 +654,13 @@ pub(crate) fn input_hook(ctx: &Context, input: &RawInput, events: &mut Vec, } +struct OwnerRecord { + stamp: OwnerStamp, + batch: Option, +} + +struct RetainedOwners { + stamp: OwnerStamp, + members: usize, + valid: bool, +} + +/// One immutable region's owner-registration identity. A rebuilt record gets a new identity. +pub(crate) struct OwnerBatch(u64); + +impl Default for OwnerBatch { + fn default() -> Self { + static NEXT: AtomicU64 = AtomicU64::new(1); + Self(NEXT.fetch_add(1, Ordering::Relaxed)) + } +} + +fn owner_stamp(reg: &Registry, record: &OwnerRecord) -> OwnerStamp { + record.batch.and_then(|id| reg.owner_batches.get(&id)).map_or(record.stamp, |batch| batch.stamp) +} + +fn next_owner_stamp(last: Option, viewport: ViewportId, pass: u64, at: f64) -> OwnerStamp { + let before = match last { + Some(last) if last.viewport == viewport && last.pass == pass => last.before, + Some(last) if last.viewport == viewport => Some(last.pass), + _ => None, + }; + OwnerStamp { viewport, pass, at, before } +} + +/// A real registration, transfer or removal invalidates the old region's fast path. +/// The batch stays until its last owner leaves, preserving its stamp during eviction grace. +fn detach_owner(reg: &mut Registry, record: &OwnerRecord) { + let Some(id) = record.batch else { return }; + if let Some(batch) = reg.owner_batches.get_mut(&id) { + batch.valid = false; + batch.members -= 1; + if batch.members == 0 { + reg.owner_batches.remove(&id); + } + } +} + /// One entry the runtime keeps for a component, and the owner that is tested for its eviction. struct SlotRecord { owner: Id, @@ -216,6 +263,7 @@ struct SlotRecord { #[derive(Default)] pub(crate) struct Registry { owners: FastMap, + owner_batches: FastMap, /// Keyed by `(slot id, tier, type)`. slots: FastMap<(Id, u8, TypeId), SlotRecord>, /// Evicted slots, moved out inside the end hook; the first pipeline run of the next pass drops them. @@ -268,26 +316,74 @@ impl Seen { /// Registers `owner`'s pass, at step 3: eviction tests only owners. Shown entries of an owner not registered /// for 3 passes of the viewport that last showed it and 0.5 s are evicted by `evict`. pub(crate) fn register_owner(ctx: &Context, owner: Id) { - crate::runtime::replay::journal(ctx, || owner, |ctx, &owner| register_owner(ctx, owner)); crate::runtime::replay::note_owner(ctx, owner); + register_owners(ctx, &[owner]); +} + +/// Registers a cached region's owners together, with one pass-state borrow. +/// Owner registration has no ordering effect: repeated registrations in a pass +/// keep the same previous-pass stamp. +pub(crate) fn register_owners(ctx: &Context, owners: &[Id]) { let facts = frame::facts(ctx); pass_state::with::(ctx, |reg| { - let before = match reg.owners.get(&owner) { - Some(last) if last.viewport == facts.viewport && last.pass == facts.pass_nr => last.before, - Some(last) if last.viewport == facts.viewport => Some(last.pass), - _ => None, - }; - reg.owners.insert(owner, OwnerRecord { viewport: facts.viewport, pass: facts.pass_nr, at: facts.now, before }); - reg.ended.remove(&owner); + for &owner in owners { + let last = reg.owners.remove(&owner); + let stamp = next_owner_stamp(last.as_ref().map(|last| owner_stamp(reg, last)), facts.viewport, facts.pass_nr, facts.now); + if let Some(last) = last { + detach_owner(reg, &last); + } + reg.owners.insert(owner, OwnerRecord { stamp, batch: None }); + reg.ended.remove(&owner); + } }); } +/// Keeps a stationary region's owners with one stamp update. Mixed previous-pass histories +/// fall back to individual records; they must not change another owner's appearance state. +pub(crate) fn retain_owners(ctx: &Context, key: &OwnerBatch, owners: &[Id]) { + if owners.is_empty() { + return; + } + let facts = frame::facts(ctx); + let retained = pass_state::with::(ctx, |reg| { + if let Some(batch) = reg.owner_batches.get_mut(&key.0) + && batch.valid + && batch.members == owners.len() + && batch.stamp.viewport == facts.viewport + { + batch.stamp = next_owner_stamp(Some(batch.stamp), facts.viewport, facts.pass_nr, facts.now); + return true; + } + let next = |reg: &Registry, owner| { + next_owner_stamp(reg.owners.get(&owner).map(|last| owner_stamp(reg, last)), facts.viewport, facts.pass_nr, facts.now) + }; + let stamp = next(reg, owners[0]); + if owners.iter().any(|&owner| next(reg, owner) != stamp) { + return false; + } + for &owner in owners { + if let Some(last) = reg.owners.remove(&owner) { + detach_owner(reg, &last); + } + } + reg.owner_batches.insert(key.0, RetainedOwners { stamp, members: owners.len(), valid: true }); + for &owner in owners { + reg.owners.insert(owner, OwnerRecord { stamp, batch: Some(key.0) }); + reg.ended.remove(&owner); + } + true + }); + if !retained { + register_owners(ctx, owners); + } +} + /// Whether `owner` was registered in the pass before the running one of its viewport, by a run or a replay: its /// component was shown there. pub(crate) fn shown_last_pass(ctx: &Context, owner: Id) -> bool { let facts = frame::facts(ctx); pass_state::with::(ctx, |reg| { - reg.owners.get(&owner).filter(|last| last.viewport == facts.viewport).is_some_and(|last| { + reg.owners.get(&owner).map(|last| owner_stamp(reg, last)).filter(|last| last.viewport == facts.viewport).is_some_and(|last| { let shown = if last.pass == facts.pass_nr { last.before } else { Some(last.pass) }; shown.is_some_and(|shown| shown + 1 >= facts.pass_nr) }) @@ -328,12 +424,19 @@ pub(crate) fn evict(ctx: &Context) { let live = pass::live_viewports(ctx); let running = frame::running(ctx); pass_state::with::(ctx, |reg| { - let due = |r: &OwnerRecord| owner_due(r.pass, r.at, pass::pass_nr_beside(ctx, running, r.viewport), now, live.contains(&r.viewport)); + let due = |record: &OwnerRecord| { + let r = owner_stamp(reg, record); + owner_due(r.pass, r.at, pass::pass_nr_beside(ctx, running, r.viewport), now, live.contains(&r.viewport)) + }; let dead: IdSet = reg.owners.iter().filter(|(_, r)| due(r)).map(|(id, _)| *id).collect(); if dead.is_empty() { return; } - reg.owners.retain(|id, _| !dead.contains(id)); + for id in &dead { + if let Some(record) = reg.owners.remove(id) { + detach_owner(reg, &record); + } + } end_lives(reg, dead.iter().copied()); let moved = take_shown(ctx, reg, |owner| dead.contains(&owner)); QUEUED.fetch_add(moved.len(), Ordering::Release); @@ -348,7 +451,8 @@ pub(crate) fn evict(ctx: &Context) { /// `owner` has no record: its life ended already, or it never ran. pub(crate) fn end_shown(ctx: &Context, owner: Id) -> bool { let moved = pass_state::with::(ctx, |reg| { - reg.owners.remove(&owner).map(|_| { + reg.owners.remove(&owner).map(|record| { + detach_owner(reg, &record); end_lives(reg, [owner]); take_shown(ctx, reg, |of| of == owner) }) @@ -483,7 +587,7 @@ pub(crate) fn records_written(ctx: &Context) -> usize { /// The pass of the viewport that last registered `owner` at step 3, `None` once the owner is evicted. pub(crate) fn owner_pass(ctx: &Context, owner: Id) -> Option { - pass_state::with::(ctx, |reg| reg.owners.get(&owner).map(|record| record.pass)) + pass_state::with::(ctx, |reg| reg.owners.get(&owner).map(|record| owner_stamp(reg, record).pass)) } /// Drops the evicted slots, outside every lock and hook, so a slot's `Drop` may touch the `Context`. diff --git a/crates/ui-contract/src/runtime/pass_state.rs b/crates/ui-contract/src/runtime/pass_state.rs index 9512176ff5..637f880f36 100644 --- a/crates/ui-contract/src/runtime/pass_state.rs +++ b/crates/ui-contract/src/runtime/pass_state.rs @@ -434,6 +434,40 @@ pub(crate) mod binding_tests { with_state(ctx, std::ptr::from_ref) } + #[cfg(not(target_arch = "wasm32"))] + #[trial] + fn worker_repaints_leave_the_ui_threads_pass_state_owned_by_its_pass() { + use crate::runtime::egui::memory::Service; + use crate::runtime::egui::repaint; + use crate::runtime::windows::WindowHost; + use std::sync::{ + Arc, + atomic::{AtomicUsize, Ordering}, + }; + + let wakes: [fn(&Context); 3] = + [repaint::request, |ctx| repaint::request_of(ctx, ViewportId::ROOT), |ctx| WindowHost::of(ctx).repaint_in(ViewportId::ROOT, -1.0)]; + for wake in wakes { + let ctx = Context::default(); + let calls = Arc::new(AtomicUsize::new(0)); + let observed = Arc::clone(&calls); + ctx.set_request_repaint_callback(move |_| { + observed.fetch_add(1, Ordering::Relaxed); + }); + hold(&ctx); + begin_running(&ctx, PassFacts { viewport: ViewportId::ROOT, pass_nr: 7, frame_nr: 7, now: 1.0, elapsed: 0.0 }); + let original = address(&ctx); + let worker_ctx = ctx.clone(); + let result = std::thread::spawn(move || wake(&worker_ctx)).join(); + let remained_owned = Service::::run(&ctx, |parked| parked.0.is_none()); + end_running(&ctx); + release(&ctx); + assert!(result.is_ok(), "a transport worker may wake an active UI pass"); + assert!(remained_owned, "a worker must not park a replacement for the UI thread's state"); + assert_eq!(address(&ctx), original, "the installed state survives the wake"); + assert!(calls.load(Ordering::Relaxed) > 0, "the native event loop is still woken"); + } + } #[trial] fn component_tree_restores_its_state_after_nested_context_access_and_unwind() { let outer = Context::default(); diff --git a/crates/ui-contract/src/runtime/pointer.rs b/crates/ui-contract/src/runtime/pointer.rs index 5b8463f6c5..113ef7643b 100644 --- a/crates/ui-contract/src/runtime/pointer.rs +++ b/crates/ui-contract/src/runtime/pointer.rs @@ -102,7 +102,8 @@ pub struct PassPointer { pub primary_down: bool, pub press_targets: PressTargets, pub focus_lost: bool, - /// Whether the real pointer moved or entered, or a held modifier or key changed, in the pass. + /// Whether the real pointer moved to a new position or entered, a pen or touch reading arrived with a move, or a + /// held modifier or key changed, in the pass. pub stirred: bool, /// A pointer move or entry in this pass's events; false on a rerun even while a position is held. pub moved: bool, @@ -129,6 +130,8 @@ pub(crate) struct Memory { withheld: IdMap, /// The touch under way, for the multi-finger tap. taps: Taps, + /// Where the pointer's last move went, until the pointer leaves the window. + last_move: Option, } /// What one pass's finger events made of the touch. @@ -229,6 +232,8 @@ type BodyRecord = HashMap; pub(crate) struct Shapes { this: LayerRecord, last: LayerRecord, + // One older pass supplies buffers only: never hit-tested, replaced at every begin. + spare: LayerRecord, this_bodies: BodyRecord, last_bodies: BodyRecord, /// The egui widgets components made for their own text (a field's text, a selection part) in the running pass and @@ -270,6 +275,30 @@ pub(crate) struct Shapes { made_lookups: u32, } +impl Shapes { + /// Reuse only this root's old buffers. Unused records leave with the spare pass, + /// and clearing before insertion keeps a disappeared shape or widget out of hit testing. + fn root(&mut self, layer: Layer, root: Id) -> &mut RootRecord { + let spare = &mut self.spare; + self.this.entry(layer).or_default().entry(root).or_insert_with(|| { + let mut entry = spare.get_mut(&layer).and_then(|roots| roots.remove(&root)).unwrap_or_default(); + // A root that becomes small must not retain an old large allocation forever. + fn clear(items: &mut Vec) { + let keep = items.len().max(8).saturating_mul(2); + if items.capacity() > keep { + items.shrink_to(keep); + } + items.clear(); + } + clear(&mut entry.shapes); + clear(&mut entry.placed); + clear(&mut entry.widgets); + entry.click = false; + entry + }) + } +} + /// The begin hook (H5): converts the pass's pointer input. pub(crate) fn begin(ctx: &Context, hit: HitSizes, latched: craft_keymap::Mods) { let viewport = pass::current_viewport(ctx); @@ -288,7 +317,20 @@ pub(crate) fn begin(ctx: &Context, hit: HitSizes, latched: craft_keymap::Mods) { let hits = input::hit_targets(ctx); let other_pressed = read.events.iter().any(|event| matches!(event, PointerEvent::Pressed { button: PointerButton::Middle | PointerButton::Secondary, .. })); - let (events, targets, touched) = PerViewport::::with(ctx, viewport, |memory| { + let (events, targets, touched, moved) = PerViewport::::with(ctx, viewport, |memory| { + // A move stirs the pass when it goes somewhere other than the last move, or carries a pen or touch reading. A + // move that repeats the pointer's position does not. + let mut moved = false; + for event in &read.events { + match event { + PointerEvent::Moved { at, sample, .. } => { + moved |= memory.last_move != Some(*at) || sample.is_some(); + memory.last_move = Some(*at); + } + PointerEvent::Gone => memory.last_move = None, + _ => {} + } + } let mut events = read.events.clone(); // Every button's press runs on the click run, as a click of any button did in the old apps: a middle-button pan // click between two clicks makes the second a triple click. Only a primary press carries its count. @@ -315,7 +357,7 @@ pub(crate) fn begin(ctx: &Context, hit: HitSizes, latched: craft_keymap::Mods) { if read.primary_pressed || other_pressed { memory.press_targets = PressTargets { click: hits.0, drag: hits.1 }; } - (events, memory.press_targets, memory.taps.feed(&read.touches, read.time)) + (events, memory.press_targets, memory.taps.feed(&read.touches, read.time), moved) }); // Where a modal holds the wheel off the canvas, a tap is not reported and a touch under way is dropped, by the // wheel's own rule. @@ -352,7 +394,7 @@ pub(crate) fn begin(ctx: &Context, hit: HitSizes, latched: craft_keymap::Mods) { }; // input::pointer_read emits Moved for Event::PointerMoved, including entry into the window. Its event // list is empty on a rerun; a button or modifier at a held position cannot become movement. - let moved = read.events.iter().any(|event| matches!(event, PointerEvent::Moved { .. })); + let move_event = read.events.iter().any(|event| matches!(event, PointerEvent::Moved { .. })); let pass_pointer = PassPointer { frame: Some(frame), events, @@ -360,8 +402,8 @@ pub(crate) fn begin(ctx: &Context, hit: HitSizes, latched: craft_keymap::Mods) { primary_down: read.primary_down, press_targets: targets, focus_lost: read.focus_lost, - stirred: read.stirred, - moved, + stirred: read.stirred || moved, + moved: move_event, gesture: touched.landed, }; let hover_at = pass_pointer.hover; @@ -394,7 +436,8 @@ pub(crate) fn begin(ctx: &Context, hit: HitSizes, latched: craft_keymap::Mods) { } PerViewport::>>::with_pass(ctx, viewport, pass_nr, |_, _| {}, |record| *record = Arc::new(pass_pointer)); PerViewport::::with(ctx, viewport, |shapes| { - shapes.last = std::mem::take(&mut shapes.this); + let finished = std::mem::take(&mut shapes.this); + shapes.spare = std::mem::replace(&mut shapes.last, finished); shapes.last_bodies = std::mem::take(&mut shapes.this_bodies); shapes.last_texts = std::mem::take(&mut shapes.this_texts); shapes.this_made.clear(); @@ -659,6 +702,7 @@ pub(crate) fn take_multi_tap(ctx: &Context, id: Id, accepts: impl FnOnce(Pos2) - /// Writes `shapes` of the arena rooted at `root`, shown through `clip` (layer space), into the running pass's shape /// record under `layer`, above every shape recorded before them in the pass. Stack positions are per arena, so each /// root's shapes stay apart. +#[cfg(feature = "testing")] pub(crate) fn record_shapes(ctx: &Context, layer: Layer, root: Id, clip: Rect, shapes: impl IntoIterator>) { record_shapes_in(ctx, pass::current_viewport(ctx), layer, root, clip, shapes); } @@ -669,7 +713,7 @@ pub(crate) fn record_shapes_in(ctx: &Context, viewport: ViewportId, layer: Layer crate::runtime::replay::journal( ctx, || (layer, root, crate::runtime::Clip::new(clip), shapes.clone()), - |ctx, (layer, root, clip, shapes)| record_shapes(ctx, *layer, *root, clip.rect(), shapes.iter().cloned()), + |ctx, (layer, root, clip, shapes)| replay_shapes(ctx, *layer, *root, clip.rect(), shapes), ); add_shapes_in(ctx, viewport, layer, root, clip, shapes); } @@ -678,11 +722,22 @@ pub(crate) fn record_shapes_in(ctx: &Context, viewport: ViewportId, layer: Layer /// stack positions a replay takes from the arena it joins (`sensing`), not from the recorded run. pub(crate) fn add_shapes_in(ctx: &Context, viewport: ViewportId, layer: Layer, root: Id, clip: Rect, shapes: Vec>) { crate::runtime::replay::note_sensors(ctx, shapes.iter().map(|shape| shape.owner)); + extend_shapes_in(ctx, viewport, layer, root, clip, shapes); +} + +/// Replay already holds an immutable journal: copy directly into this pass's root +/// instead of collecting another temporary vector or journaling the replay again. +fn replay_shapes(ctx: &Context, layer: Layer, root: Id, clip: Rect, shapes: &[Shape]) { + crate::runtime::replay::note_sensors(ctx, shapes.iter().map(|shape| shape.owner)); + extend_shapes_in(ctx, pass::current_viewport(ctx), layer, root, clip, shapes.iter().cloned()); +} + +fn extend_shapes_in(ctx: &Context, viewport: ViewportId, layer: Layer, root: Id, clip: Rect, shapes: impl IntoIterator>) { PerViewport::::with(ctx, viewport, |record| { let order = record.next; record.next += 1; record.this_made.insert(root); - let entry = record.this.entry(layer).or_default().entry(root).or_default(); + let entry = record.root(layer, root); entry.shapes.extend(shapes); entry.placed.resize(entry.shapes.len(), Placed { order, clip }); }); @@ -820,7 +875,7 @@ pub(crate) fn record_widgets_in(ctx: &Context, viewport: ViewportId, layer: Laye PerViewport::::with(ctx, viewport, |record| { record.this_made.insert(root); record.this_made.extend(widgets.iter().copied()); - let entry = record.this.entry(layer).or_default().entry(root).or_default(); + let entry = record.root(layer, root); entry.widgets.extend_from_slice(widgets); entry.click |= click; }); diff --git a/crates/ui-contract/src/runtime/replay.rs b/crates/ui-contract/src/runtime/replay.rs index 7ce6d27376..aeda33820b 100644 --- a/crates/ui-contract/src/runtime/replay.rs +++ b/crates/ui-contract/src/runtime/replay.rs @@ -176,6 +176,8 @@ pub(crate) struct Facts { /// The components whose memory owners registered in the run (`memory::register_owner`): a replay needs their /// shown-tier state still kept (`memory::ended_since`). pub(crate) owners: Vec, + /// Owners registered by a shown run, excluding measurement-only registrations. + pub(crate) owner_registrations: Vec, /// The components that take the AccessKit requests on the nodes the run registered (`note_node_owner`): a request /// routed to one of them is routed into the run, though the component is no egui widget (a collection's row). pub(crate) node_owners: Vec, @@ -237,6 +239,7 @@ impl Held { /// What one real run of a region added to its pass. pub(crate) struct Record { pub(crate) focus: Transcript, + owner_batch: crate::runtime::memory::OwnerBatch, pub(crate) journal: Vec, egui: egui::PassRecords, /// The egui widgets of the run. @@ -320,6 +323,7 @@ pub(crate) fn close(ctx: &Context, layer: Layer) -> Record { outer.facts.blocked |= open.facts.blocked; outer.facts.discards |= open.facts.discards; outer.facts.owners.extend(open.facts.owners.iter().copied()); + outer.facts.owner_registrations.extend(open.facts.owner_registrations.iter().copied()); outer.facts.node_owners.extend(open.facts.node_owners.iter().copied()); outer.facts.layout_keeps.extend(open.facts.layout_keeps.iter().copied()); outer.facts.derived_keeps.extend(open.facts.derived_keeps.iter().copied()); @@ -341,6 +345,10 @@ pub(crate) fn close(ctx: &Context, layer: Layer) -> Record { let egui = ctx.pass_records_since(&open.egui); let mut facts = open.facts; // Every measure of an entry keeps it again: the record keeps each one once. + facts.owners.sort_unstable_by_key(|id| id.value()); + facts.owners.dedup(); + facts.owner_registrations.sort_unstable_by_key(|id| id.value()); + facts.owner_registrations.dedup(); facts.layout_keeps.sort_unstable_by_key(|id| id.value()); facts.layout_keeps.dedup(); facts.derived_keeps.sort_unstable_by_key(|id| id.value()); @@ -361,7 +369,7 @@ pub(crate) fn close(ctx: &Context, layer: Layer) -> Record { facts.inputs.insert(Input::Focus); facts.inputs.insert(Input::Sent); } - Record { focus, journal, widgets, held, egui, facts } + Record { focus, journal, widgets, held, egui, facts, owner_batch: Default::default() } } #[cfg(feature = "testing")] @@ -418,6 +426,9 @@ impl Record { only(&run.facts.reads, &self.facts.reads) )); } + if self.facts.owner_registrations != run.facts.owner_registrations { + found.push(format!("memory owners: left {:?} / right {:?}", self.facts.owner_registrations, run.facts.owner_registrations)); + } if self.facts.inputs != run.facts.inputs { let list = |inputs: Inputs| Input::ALL.into_iter().filter(|input| inputs.contains(*input)).collect::>(); found.push(format!("inputs: left {:?} / right {:?}", list(self.facts.inputs), list(run.facts.inputs))); @@ -453,6 +464,12 @@ fn min_wake(a: Option, b: Option) -> Option { /// every journal entry move by the one shift (`Shift`). The focus transcript holds no place: a stop's place is its /// root widget's rect, which egui's records move. pub(crate) fn replay(ctx: &Context, record: &Record, shift: &RecordShift) { + let owner_recording = journaling(ctx); + if shift.is_none() { + crate::runtime::memory::retain_owners(ctx, &record.owner_batch, &record.facts.owner_registrations); + } else { + crate::runtime::memory::register_owners(ctx, &record.facts.owner_registrations); + } ctx.replay_pass_records(&record.egui, shift); focus::replay(ctx, &record.focus); // The records open around the replay hold its journal at the place it replays at, as a run there would have noted @@ -476,6 +493,10 @@ pub(crate) fn replay(ctx: &Context, record: &Record, shift: &RecordShift) { crate::runtime::egui::repaint::request_after(ctx, crate::runtime::egui::pass::current_viewport(ctx), at - frame::clock(ctx)); } with_open(ctx, |facts| { + facts.owners.extend(record.facts.owners.iter().copied()); + if owner_recording { + facts.owner_registrations.extend(record.facts.owner_registrations.iter().copied()); + } facts.layout_keeps.extend(record.facts.layout_keeps.iter().copied()); facts.derived_keeps.extend(record.facts.derived_keeps.iter().copied()); facts.reads.extend(record.facts.reads.iter().copied()); @@ -640,7 +661,13 @@ pub(crate) fn note_node_owner(ctx: &Context, owner: egui::Id) { /// Notes that the memory owner `owner` registered in the running code. pub(crate) fn note_owner(ctx: &Context, owner: egui::Id) { - with_open(ctx, |facts| facts.owners.push(owner)); + let registered = journaling(ctx); + with_open(ctx, |facts| { + facts.owners.push(owner); + if registered { + facts.owner_registrations.push(owner); + } + }); } /// How many discard requests the running pass's output holds. diff --git a/crates/ui-contract/src/runtime/shift.rs b/crates/ui-contract/src/runtime/shift.rs index b5cb2ad2e0..e15c7112b3 100644 --- a/crates/ui-contract/src/runtime/shift.rs +++ b/crates/ui-contract/src/runtime/shift.rs @@ -131,6 +131,16 @@ impl Shift for [T; N] { } } +impl Shift for Arc<[T]> { + fn shifted(&self, by: &RecordShift) -> Self { + if by.is_none() { Arc::clone(self) } else { self.iter().map(|value| value.shifted(by)).collect() } + } + + fn snapped(&self, to: &Self, within: f32) -> Self { + snapped_items(self.iter(), to.iter(), within).into() + } +} + impl Shift for Vec { fn shifted(&self, by: &RecordShift) -> Self { self.iter().map(|value| value.shifted(by)).collect() diff --git a/crates/ui-contract/src/runtime/wheel.rs b/crates/ui-contract/src/runtime/wheel.rs index b3815c4bc9..5563d9a6c9 100644 --- a/crates/ui-contract/src/runtime/wheel.rs +++ b/crates/ui-contract/src/runtime/wheel.rs @@ -14,7 +14,6 @@ use craft_behavior::{ use craft_keymap::Mods; use egui::{Context, Id, IdMap, Pos2, Vec2}; -#[derive(Default)] pub(crate) struct State { this: Vec>, last: Vec>, @@ -32,12 +31,40 @@ pub(crate) struct State { zoom_gathered: Vec2, /// Whether the owner marked the running gesture moved, reset when the gesture closes. moved: bool, + /// The modifiers held at any point of the running gesture, reset when the gesture closes. + held: Mods, + /// Whether a wheel event of the running gesture, or one just before it began, arrived while a modal held the wheel. + modal: bool, + /// The time of the last wheel event a modal held; −∞ before the first. + modal_last: f64, /// The last gesture the device ended, which a momentum run of the same owner within `GESTURE_GAP` resumes. device_ended: Option, /// The wheel ease each owner holds. eases: egui::IdMap, } +impl Default for State { + fn default() -> Self { + State { + this: Vec::new(), + last: Vec::new(), + this_layers: IdMap::default(), + last_layers: IdMap::default(), + armed: None, + shares: Vec::new(), + gesture: WheelGesture::default(), + gathered: Vec2::ZERO, + zoom_gathered: Vec2::ZERO, + moved: false, + held: Mods::NONE, + modal: false, + modal_last: f64::NEG_INFINITY, + device_ended: None, + eases: IdMap::default(), + } + } +} + /// A gesture the device ended (fingers lifted), as a momentum run that follows it continues it. #[derive(Clone, Copy)] struct Ended { @@ -46,6 +73,13 @@ struct Ended { gathered: Vec2, zoom_gathered: Vec2, moved: bool, + held: Mods, + modal: bool, +} + +/// The modifiers held in `a` or in `b`. +const fn either(a: Mods, b: Mods) -> Mods { + Mods { cmd: a.cmd || b.cmd, ctrl: a.ctrl || b.ctrl, alt: a.alt || b.alt, shift: a.shift || b.shift } } /// Marks the wheel gesture `id` owns, while it runs, as moved. @@ -88,6 +122,15 @@ pub(crate) fn stop_ease(ctx: &Context, id: Id) { }); } +/// Notes that a modal layer held this pass's wheel in `viewport` before the begin hook saw it (a modal in another +/// viewport): the running gesture, and one that begins within `GESTURE_GAP`, began or went on under a modal. +pub(crate) fn note_held_by_modal(ctx: &Context, viewport: egui::ViewportId, now: f64) { + PerViewport::::with(ctx, viewport, |state| { + state.modal_last = now; + state.modal = state.modal || state.gesture.runs(now); + }); +} + impl State { /// Closes the gesture a press (`pressed`) or the gap at `now` ended, and returns the owner `WheelGesture::end` /// gave. A closed gesture's gathered scroll and mark go; a press also drops every ease and the ended swipe a @@ -105,6 +148,8 @@ impl State { self.gathered = Vec2::ZERO; self.zoom_gathered = Vec2::ZERO; self.moved = false; + self.held = Mods::NONE; + self.modal = false; } ended } @@ -117,13 +162,16 @@ impl State { return None; } let swipe = self.device_ended.filter(|ended| source == WheelSource::Momentum && now - ended.at < GESTURE_GAP); - (self.gathered, self.zoom_gathered, self.moved) = - swipe.map_or((Vec2::ZERO, Vec2::ZERO, false), |ended| (ended.gathered, ended.zoom_gathered, ended.moved)); + (self.gathered, self.zoom_gathered, self.moved, self.held) = + swipe.map_or((Vec2::ZERO, Vec2::ZERO, false, Mods::NONE), |ended| (ended.gathered, ended.zoom_gathered, ended.moved, ended.held)); + // A turn that went on under a modal until just now goes on under it after the modal closes. + self.modal = swipe.is_some_and(|ended| ended.modal) || now - self.modal_last < GESTURE_GAP; swipe.map(|ended| ended.owner) } - /// Adds `share`, in its owner's points, to the gesture it belongs to and gives it the gesture's gathered scroll - /// and mark; a share of another owner than the gesture's gathers only itself. A point share cancels its owner's + /// Adds `share`, in its owner's points, to the gesture it belongs to and gives it the gesture's gathered scroll, + /// mark and held modifiers; a share of another owner than the gesture's gathers only itself. Every share carries + /// whether the gesture went on under a modal. A point share cancels its owner's /// owed ease on each axis it moves: direct input wins over an older line tail, and only on its own axis. fn gather(&mut self, owner: Id, share: &mut Wheel) { if share.unit == WheelUnit::Point @@ -131,12 +179,14 @@ impl State { { ease.cancel_axis(share.scroll.x != 0.0, share.scroll.y != 0.0); } + share.modal = self.modal; if self.gesture.owner == Some(owner) { self.gathered += share.scroll; self.zoom_gathered += share.zoom_lines; share.gathered = self.gathered; share.zoom_gathered = self.zoom_gathered; share.moved = self.moved; + share.held = self.held; } else { share.gathered = share.scroll; share.zoom_gathered = share.zoom_lines; @@ -199,6 +249,12 @@ pub(crate) fn begin(ctx: &Context, pointer_scoped_field_wheel: bool) { let pass_pointer = pointer::pass_pointer(ctx); let frame = pass_pointer.frame.clone(); let wheel_in = input::wheel_read(ctx, 1.0, 1.0); + let pass_mods = input::pass_held_mods(ctx, input::HeldSpan::Pass); + let wheel_mods = input::pass_held_mods(ctx, input::HeldSpan::FromWheel); + let press_mods = input::pass_held_mods(ctx, input::HeldSpan::ToPress); + let wheel_before_press = input::wheel_before_press(ctx); + // A Ctrl+wheel the input layer folded into a pinch is wheel input too, for a modal's hold on the turn. + let pinched = ctx.input(|input| input.raw.events.iter().any(|event| matches!(event, egui::Event::Zoom(_)))); let zoom_lines = input::zoom_wheel_lines(ctx); let now = crate::runtime::frame::clock(ctx); let focused = focus::focused_stop(ctx).map(|(owner, _)| owner); @@ -245,11 +301,31 @@ pub(crate) fn begin(ctx: &Context, pointer_scoped_field_wheel: bool) { } // A press ends the gesture at once, the gap after its last event otherwise. A value control that owned it // hears the end as a zero-scroll `End` share; a scroll region and a canvas hear only the device's phases. + // A key tapped in the pass before the press that ends a running gesture was held during that gesture. + let closing_press = pressed_on.is_some() && state.gesture.runs(now); + let held_before = if closing_press { either(state.held, press_mods) } else { state.held }; + // A wheel a modal held in the pass before that press arrived during the gesture too. + let modal_before = state.modal || (closing_press && wheel_before_press && (blocked || modal_family.is_some())); let ended = state.close_gesture(pressed_on.is_some(), now); let ended = ended.filter(|owner| state.last.iter().any(|taker| taker.owner == *owner && taker.value)); + // A key tapped between the running gesture's wheel events counts as held for the rest of it, and one tapped + // between a swipe's device end and its momentum run counts for the run that resumes it. + if state.gesture.runs(now) { + state.held = either(state.held, pass_mods); + } else if let Some(swipe) = state.device_ended.as_mut().filter(|swipe| now - swipe.at < GESTURE_GAP) { + swipe.held = either(swipe.held, pass_mods); + } + // A wheel a modal holds marks the running gesture, and the one that follows within the gap. + if (wheel_in.is_some() || pinched) && (blocked || modal_family.is_some()) { + state.modal_last = now; + state.modal = state.modal || state.gesture.runs(now); + } if let Some(owner) = ended { let mods = frame.as_ref().map_or(Mods::NONE, |frame| frame.mods); - state.shares.push((owner, Wheel::new(Vec2::ZERO, mods, WheelUnit::Point, WheelPhase::End))); + // The end carries the metadata of the gesture it ends. + let mut end = Wheel::new(Vec2::ZERO, mods, WheelUnit::Point, WheelPhase::End); + (end.held, end.modal) = (held_before, modal_before); + state.shares.push((owner, end)); } if let (Some(frame), Some(at)) = (&frame, hover) && !blocked @@ -283,6 +359,7 @@ pub(crate) fn begin(ctx: &Context, pointer_scoped_field_wheel: bool) { .touch_pan(touch_pan) .at(at); let focus = WheelFocus::new(focused).app_field(app_field).by_position(by_position); + let held_mods = if state.gesture.runs(now) { pass_mods } else { wheel_mods }; let swipe = state.open_gesture(source, now); // A point over a modal admits its own wheel takers, not a canvas below the modal. let eligible: Vec<_> = state @@ -295,11 +372,14 @@ pub(crate) fn begin(ctx: &Context, pointer_scoped_field_wheel: bool) { }) }) .collect(); + let (previous_owner, held, modal) = (state.gesture.owner, state.held, state.modal); let shares = split(&eligible, at, share, focus, state.armed, &mut state.gesture, now); // A momentum run resumes its swipe only on the swipe's owner; any split drops the ended swipe. if swipe.is_some() && state.gesture.owner != swipe { - (state.gathered, state.zoom_gathered, state.moved) = (Vec2::ZERO, Vec2::ZERO, false); + (state.gathered, state.zoom_gathered, state.moved, state.held) = (Vec2::ZERO, Vec2::ZERO, false, Mods::NONE); + state.modal = now - state.modal_last < GESTURE_GAP; } + state.held = either(state.held, either(mods, held_mods)); state.device_ended = None; // The device's lines and pages become points of each taker: the notch is the scroll owner's to choose. for (owner, mut share) in shares { @@ -311,11 +391,14 @@ pub(crate) fn begin(ctx: &Context, pointer_scoped_field_wheel: bool) { share.scroll = taker.points(share.scroll, unit); } state.gather(owner, &mut share); + if share.phase == WheelPhase::End && Some(owner) == previous_owner && state.gesture.owner != previous_owner { + (share.held, share.modal) = (held, modal); + } state.shares.push((owner, share)); } if device_end { - let (gathered, zoom_gathered, moved) = (state.gathered, state.zoom_gathered, state.moved); - state.device_ended = state.gesture.owner.map(|owner| Ended { owner, at: now, gathered, zoom_gathered, moved }); + let (gathered, zoom_gathered, moved, held, modal) = (state.gathered, state.zoom_gathered, state.moved, state.held, state.modal); + state.device_ended = state.gesture.owner.map(|owner| Ended { owner, at: now, gathered, zoom_gathered, moved, held, modal }); } } } diff --git a/crates/ui-contract/tests/it/body/placement.rs b/crates/ui-contract/tests/it/body/placement.rs index 744e341fab..29a635612e 100644 --- a/crates/ui-contract/tests/it/body/placement.rs +++ b/crates/ui-contract/tests/it/body/placement.rs @@ -5,9 +5,9 @@ use craft_behavior::overlay::{Align, Side}; use craft_behavior::{GesturePhase, Sense}; use craft_theme::{Contrast, Mode}; -use craft_ui::contract::overlay::{Anchor, DragBounds, FloatPlace, Place, PlacementChange, PlacementKind}; +use craft_ui::contract::overlay::{Anchor, DragBounds, FloatPlace, OverlayFit, Place, PlacementChange, PlacementKind}; use craft_ui::contract::{ - BodyCx, Common, Component, Container, ContainerProps, Cx, DragBand, HeaderRegion, MemoProps, MemoView, Mount, Overlay, Props as _, Role, + BodyCx, Common, Component, Container, ContainerProps, Cx, DragBand, HeaderRegion, MemoProps, MemoView, Mount, Overlay, Props as _, Role, Scroll, Show as _, ShowContainer as _, Sizing, }; use craft_ui::layout::BodyLayout; @@ -334,6 +334,60 @@ fn a_layer_with_bounds_shows_inside_them_hung_or_placed() { } } +/// A float placed by its top share within bounds keeps its top at that share of the bounds' height, centered across +/// them, whether its scrolling body is short or taller than the bounds: the tall one is held to the room below the top +/// and scrolls. Guards against a room measured on the whole screen, where a tall body outgrew the bounds and the keep +/// rule pushed the layer's top up. +#[trial] +fn a_float_placed_by_its_top_share_keeps_its_top_within_bounds_as_its_body_grows() { + let top = BOUNDS.top() + BOUNDS.height() * 0.2; + for height in [40.0, BOUNDS.height() * 2.0] { + let (shown, log, seen) = (Cell::new(Rect::NOTHING), RefCell::new(Vec::new()), RefCell::new(Seen::default())); + let mut show = |ui: &mut Ui| { + let overlay = Overlay::floating().place(Place::Float(FloatPlace::top_centered(0.2))).bounds(BOUNDS); + let props = ContainerProps::new().mount(Mount::Layer(overlay)).sizing(Sizing::Content).scroll(Scroll::vertical()); + let out = Pane { common: Common::new(), props, log: &log }.id_salt("top-share").show(ui, |ui, _| { + Probe::new(&seen).size(Vec2::new(BODY.x, height)).show(ui); + }); + shown.set(out.output.rect); + }; + let mut frames = Frames::new(); + frames.idle(4, &mut show); + let rect = shown.get(); + assert!(rect.is_positive(), "body {height}: the layer shows: {rect:?}"); + assert!((rect.top() - top).abs() < SLACK, "body {height}: the top is 20% of the bounds' height down, at {top}: {rect:?}"); + assert!((rect.center().x - BOUNDS.center().x).abs() < SLACK, "body {height}: the layer is centered across {BOUNDS:?}: {rect:?}"); + assert!(rect.bottom() <= BOUNDS.bottom() + SLACK, "body {height}: the layer stays inside {BOUNDS:?}: {rect:?}"); + } +} + +/// A resizable float placed by its top share within bounds, with a default size taller than the bounds, takes at most +/// the room below its top: its top stays at the share and it ends inside the bounds. Guards against a default size +/// held only to the screen, which the keep rule then pushed up past the share. +#[trial] +fn a_resizable_float_placed_by_its_top_share_holds_its_default_size_to_the_room_below_its_top() { + let top = BOUNDS.top() + BOUNDS.height() * 0.2; + let (shown, log, seen) = (Cell::new(Rect::NOTHING), RefCell::new(Vec::new()), RefCell::new(Seen::default())); + let mut show = |ui: &mut Ui| { + let overlay = Overlay::floating() + .place(Place::Float(FloatPlace::top_centered(0.2))) + .bounds(BOUNDS) + .fit(OverlayFit::Resizable) + .size(Vec2::new(BODY.x, BOUNDS.height() * 2.0)); + let props = ContainerProps::new().mount(Mount::Layer(overlay)).sizing(Sizing::Content).scroll(Scroll::vertical()); + let out = Pane { common: Common::new(), props, log: &log }.id_salt("top-share-sized").show(ui, |ui, _| { + Probe::new(&seen).size(BODY).show(ui); + }); + shown.set(out.output.rect); + }; + let mut frames = Frames::new(); + frames.idle(4, &mut show); + let rect = shown.get(); + assert!(rect.is_positive(), "the layer shows: {rect:?}"); + assert!((rect.top() - top).abs() < SLACK, "the top is 20% of the bounds' height down, at {top}: {rect:?}"); + assert!(rect.bottom() <= BOUNDS.bottom() + SLACK, "the layer stays inside {BOUNDS:?}: {rect:?}"); +} + /// A layer anchored `Parent` hangs from the placed panel of the layer whose body opened it, not from its own cursor. #[trial] fn a_layer_anchored_parent_hangs_on_the_parent_panel() { diff --git a/crates/ui-contract/tests/it/fonts/on_demand.rs b/crates/ui-contract/tests/it/fonts/on_demand.rs index 869003f92b..1c53f13fd9 100644 --- a/crates/ui-contract/tests/it/fonts/on_demand.rs +++ b/crates/ui-contract/tests/it/fonts/on_demand.rs @@ -348,3 +348,24 @@ fn the_deflated_defaults_are_eguis_default_faces_and_draw_its_icons() { } } } + +/// A kept region still contributes missing glyphs to the on-demand font scan. +#[trial] +fn retained_paint_loads_a_missing_script_face() { + let arabic = write("retained-arabic.ttf", ARABIC); + let files = Files::new(vec![("Arab", vec![arabic.clone()])]); + let mut frames = Frames::new(); + install(&frames, &files); + for _ in 0..10 { + frames.frame(vec![], |ui| { + let color = egui::Color32::WHITE; + let galley = ui.painter().layout_no_wrap("\u{639}".to_owned(), FontId::proportional(14.0), color); + let text = egui::epaint::TextShape::new(ui.cursor().min, galley, color); + let clipped = egui::epaint::ClippedShape::new(ui.clip_rect(), egui::Shape::Text(text)); + ui.painter().add(egui::Shape::PaintChunk(Arc::from([clipped]))); + }); + } + assert_eq!(registered(&frames), [(arabic, 0)]); + assert!(draws(&frames, '\u{639}')); + assert_eq!(files.checks(), 1, "later retained frames reuse the registered face"); +} diff --git a/crates/ui-contract/tests/it/layout/body.rs b/crates/ui-contract/tests/it/layout/body.rs index 97c842f2e2..a86097ee5b 100644 --- a/crates/ui-contract/tests/it/layout/body.rs +++ b/crates/ui-contract/tests/it/layout/body.rs @@ -789,3 +789,29 @@ fn a_labelled_container_narrower_than_its_padding_places_its_footer() { assert!(rects[0].min.is_finite() && rects[0].max.is_finite(), "{direction:?}: the container shows at {:?}", rects[0]); } } + +/// A content-sized Row holding a leaf 8 wide and 0 tall after a 40-wide one is as wide as the same Row with that leaf +/// 1 tall, and a content-sized Stack holding a leaf 0 wide and 8 tall below a 10-tall one is as tall as the same Stack +/// with that leaf 1 wide: the leaf's other side and the gap before it both count. +#[trial] +fn a_leaf_that_measures_zero_on_one_side_keeps_its_other_side_in_the_body() { + let measured = |layout: &BodyLayout, edge: Vec2| { + lay_out(None, |ui| { + let (first, last) = (RefCell::new(Seen::default()), RefCell::new(Seen::default())); + let panel = Panel::new().layout(layout.clone()).sizing(Sizing::Content).id_salt("body").show(ui, |ui, _| { + Probe::new(&first).size(ITEM).id_salt("first").show(ui); + Probe::new(&last).size(edge).id_salt("edge").show(ui); + }); + vec![panel.output.rect] + }) + .1[0] + }; + for (layout, edge, along) in [(BodyLayout::row(), Vec2::new(8.0, 0.0), 0), (BodyLayout::stack(), Vec2::new(0.0, 8.0), 1)] { + let (zero, shown) = (measured(&layout, edge), measured(&layout, edge.max(Vec2::splat(1.0)))); + assert!(shown.size()[along] > ITEM[along] + edge[along], "{layout:?}: the body with a shown leaf counts a gap: {shown:?}"); + assert!( + (zero.size()[along] - shown.size()[along]).abs() < SLACK, + "{layout:?}: the body takes the {edge:?} leaf's extent and the gap before it, as for a shown leaf {shown:?}: {zero:?}" + ); + } +} diff --git a/crates/ui-contract/tests/it/runtime/wheel.rs b/crates/ui-contract/tests/it/runtime/wheel.rs index 08e005bce6..642847972f 100644 --- a/crates/ui-contract/tests/it/runtime/wheel.rs +++ b/crates/ui-contract/tests/it/runtime/wheel.rs @@ -369,6 +369,233 @@ fn a_wheel_over_an_open_popup_goes_to_the_popup_and_not_to_the_region_under_it() ); } +/// A modal layer with an empty body. +#[derive(craft_ui::contract::Component)] +#[component(container, unregistered)] +struct WheelModal { + #[common] + common: Common, + #[container] + props: ContainerProps, +} + +impl Component for WheelModal { + const ROLE: Role = Role::GROUP; + type Style = PlainStyle; + type Output = Response; + + fn style(_: &StyleCx<'_>, _: WheelModalStyleKey) -> PlainStyle { + PlainStyle::min(Vec2::new(120.0, 60.0)) + } + + fn finish(self, cx: Cx<'_, Self>) -> Response { + cx.response.clone() + } +} + +impl Container for WheelModal {} + +#[trial] +fn a_wheel_gesture_carries_the_keys_held_during_it_and_whether_it_began_under_a_modal() { + let canvas = Id::unique("held_canvas"); + let rect = Rect::from_min_size(Pos2::ZERO, Vec2::splat(400.0)); + let open = Cell::new(false); + let last: Cell> = Cell::new(None); + let mut show_frame = |ui: &mut Ui| { + if open.get() { + let props = ContainerProps::new().mount(Mount::Layer(Overlay::modal())); + WheelModal { common: Common::new(), props }.id_salt("wheel_modal").show(ui, |_, _| {}); + } + register(ui.ctx(), WheelTaker::new(canvas, rect).vertical(true).scrolls(true)); + if let Some(share) = take_share(ui.ctx(), canvas) { + last.set(Some(share)); + } + }; + let mut frames = Frames::new(); + frames.idle(2, &mut show_frame); + frames.frame(vec![pointer::moved(Pos2::new(390.0, 390.0))], &mut show_frame); + let turn = |frames: &mut Frames, show_frame: &mut dyn FnMut(&mut Ui)| { + last.set(None); + frames.frame(vec![pointer::wheel(-30.0)], &mut *show_frame); + last.take() + }; + + let first = turn(&mut frames, &mut show_frame).expect("the canvas takes the wheel"); + assert_eq!((first.held, first.modal), (craft_keymap::Mods::NONE, false), "a plain turn: {first:?}"); + // Shift tapped between two events of the turn counts for the rest of it. + frames.hold(Modifiers::SHIFT); + frames.frame(Vec::new(), &mut show_frame); + frames.hold(Modifiers::NONE); + let after = turn(&mut frames, &mut show_frame).expect("the turn goes on"); + assert!(after.held.shift && !after.mods.shift, "the tapped key is held for the turn, not in this event: {after:?}"); + frames.advance(GESTURE_GAP); + frames.idle(2, &mut show_frame); + let next = turn(&mut frames, &mut show_frame).expect("a new turn"); + assert!(!next.held.shift, "a new turn starts with no keys held: {next:?}"); + + // A turn that begins under a modal stays marked once the modal closes, until the gap ends it. + frames.advance(GESTURE_GAP); + open.set(true); + frames.idle(2, &mut show_frame); + assert!(turn(&mut frames, &mut show_frame).is_none(), "the modal holds the wheel"); + open.set(false); + frames.frame(Vec::new(), &mut show_frame); + let under = turn(&mut frames, &mut show_frame).expect("the canvas takes the rest of the turn"); + assert!(under.modal, "the rest of a turn begun under the modal: {under:?}"); + frames.advance(GESTURE_GAP); + frames.idle(2, &mut show_frame); + let fresh = turn(&mut frames, &mut show_frame).expect("a new turn"); + assert!(!fresh.modal, "a turn begun after the gap: {fresh:?}"); +} + +#[trial] +fn the_end_share_of_a_pressed_wheel_gesture_carries_a_key_tapped_before_the_press_in_its_pass() { + let slider = Id::unique("press_held_slider"); + let rect = Rect::from_min_size(Pos2::new(50.0, 50.0), Vec2::new(100.0, 20.0)); + let end: Cell> = Cell::new(None); + let mut show_frame = |ui: &mut Ui| { + register(ui.ctx(), WheelTaker::new(slider, rect).vertical(true).value(true)); + if let Some(share) = take_share(ui.ctx(), slider).filter(|share| share.phase == WheelPhase::End) { + end.set(Some(share)); + } + }; + let (on_slider, beside) = (Pos2::new(70.0, 60.0), Pos2::new(300.0, 300.0)); + let mut frames = Frames::new(); + frames.idle(2, &mut show_frame); + // Turns the wheel on the slider, then ends the gesture with a pass of `events` that holds a press. + let pressed = |frames: &mut Frames, show_frame: &mut dyn FnMut(&mut Ui), events: Vec| { + frames.frame(vec![pointer::moved(on_slider)], &mut *show_frame); + frames.frame(vec![pointer::wheel(-30.0)], &mut *show_frame); + end.set(None); + frames.frame(events, &mut *show_frame); + let share = end.take().expect("the press ends the slider's gesture in its pass"); + frames.frame(vec![pointer::release(beside)], &mut *show_frame); + frames.advance(GESTURE_GAP); + frames.idle(2, &mut *show_frame); + share + }; + let tap = || [Event::ModifiersChanged(Modifiers::SHIFT), Event::ModifiersChanged(Modifiers::NONE)]; + + let plain = pressed(&mut frames, &mut show_frame, vec![pointer::press(beside)]); + assert_eq!(plain.held, craft_keymap::Mods::NONE, "a plain press: {plain:?}"); + let before = pressed(&mut frames, &mut show_frame, tap().into_iter().chain([pointer::press(beside)]).collect()); + assert!(before.held.shift, "Shift tapped before the press was held during the gesture: {before:?}"); + let after = pressed(&mut frames, &mut show_frame, [pointer::press(beside)].into_iter().chain(tap()).collect()); + assert_eq!(after.held, craft_keymap::Mods::NONE, "Shift tapped after the press came after the gesture: {after:?}"); +} + +#[trial] +fn a_key_tapped_after_the_rotation_that_begins_a_gesture_is_held_during_it() { + let canvas = Id::unique("rotate_held_canvas"); + let rect = Rect::from_min_size(Pos2::ZERO, Vec2::splat(400.0)); + let last: Cell> = Cell::new(None); + let mut show_frame = |ui: &mut Ui| { + register(ui.ctx(), WheelTaker::new(canvas, rect).vertical(true).zoom(true)); + if let Some(share) = take_share(ui.ctx(), canvas) { + last.set(Some(share)); + } + }; + let mut frames = Frames::new(); + frames.idle(2, &mut show_frame); + frames.frame(vec![pointer::moved(Pos2::new(200.0, 200.0))], &mut show_frame); + // A pass of `events` begins a gesture; the gap then ends it. + let begun = |frames: &mut Frames, show_frame: &mut dyn FnMut(&mut Ui), events: Vec| { + last.set(None); + frames.frame(events, &mut *show_frame); + let share = last.take().expect("the canvas takes the rotation"); + frames.advance(GESTURE_GAP); + frames.idle(2, &mut *show_frame); + share + }; + let tap = || [Event::ModifiersChanged(Modifiers::SHIFT), Event::ModifiersChanged(Modifiers::NONE)]; + + let after = begun(&mut frames, &mut show_frame, [Event::Rotate(0.25)].into_iter().chain(tap()).collect()); + assert!(after.rotation != 0.0 && after.held.shift, "Shift tapped after the rotation was held during its gesture: {after:?}"); + let before = begun(&mut frames, &mut show_frame, tap().into_iter().chain([Event::Rotate(0.25)]).collect()); + assert!(before.rotation != 0.0 && !before.held.shift, "Shift tapped before the rotation came before the gesture: {before:?}"); +} + +#[trial] +fn the_end_share_of_a_pressed_wheel_gesture_carries_the_ctrl_of_a_folded_pinch_step_before_the_press() { + // egui reports the Ctrl key as `ctrl` and `command` off macOS. + let ctrl = Modifiers { ctrl: true, command: true, ..Modifiers::NONE }; + let pinch_step = || wheel_event(MouseWheelUnit::Line, Vec2::new(0.0, 0.4), TouchPhase::Move, ctrl); + let slider = Id::unique("folded_press_slider"); + let rect = Rect::from_min_size(Pos2::new(50.0, 50.0), Vec2::new(100.0, 20.0)); + let seen: Rc>> = Rc::new(Cell::new(None)); + let end = Rc::clone(&seen); + let mut fixture = Fixture::new(move |ui| { + register(ui.ctx(), WheelTaker::new(slider, rect).vertical(true).value(true)); + if let Some(share) = take_share(ui.ctx(), slider).filter(|share| share.phase == WheelPhase::End) { + end.set(Some(share)); + } + }); + fixture.os(Os::Windows); + fixture.settle(); + let (on_slider, beside) = (Pos2::new(70.0, 60.0), Pos2::new(300.0, 300.0)); + // Turns the wheel on the slider, then ends the gesture with a pass of `events` that holds a press. + let pressed = |fixture: &mut Fixture, events: Vec| { + fixture.frame(vec![pointer::moved(on_slider)]); + fixture.frame(vec![pointer::wheel(-30.0)]); + seen.set(None); + fixture.frame(events); + let share = seen.take().expect("the press ends the slider's gesture in its pass"); + fixture.frame(vec![pointer::release(beside)]); + fixture.advance(1.0); + fixture.idle(2); + share + }; + + let before = pressed(&mut fixture, vec![pinch_step(), pointer::press(beside)]); + assert!(before.held.cmd || before.held.ctrl, "the Ctrl of a pinch step before the press was held during the gesture: {before:?}"); + let after = pressed(&mut fixture, vec![pointer::press(beside), pinch_step()]); + assert_eq!(after.held, craft_keymap::Mods::NONE, "a pinch step after the press came after the gesture: {after:?}"); +} + +#[trial] +fn the_end_share_of_a_pressed_wheel_gesture_is_marked_by_a_wheel_a_modal_held_before_the_press() { + let slider = Id::unique("modal_press_slider"); + let rect = Rect::from_min_size(Pos2::new(50.0, 50.0), Vec2::new(100.0, 20.0)); + let open = Cell::new(false); + let end: Cell> = Cell::new(None); + let mut show_frame = |ui: &mut Ui| { + if open.get() { + let props = ContainerProps::new().mount(Mount::Layer(Overlay::modal())); + WheelModal { common: Common::new(), props }.id_salt("press_wheel_modal").show(ui, |_, _| {}); + } + register(ui.ctx(), WheelTaker::new(slider, rect).vertical(true).value(true)); + if let Some(share) = take_share(ui.ctx(), slider).filter(|share| share.phase == WheelPhase::End) { + end.set(Some(share)); + } + }; + let (on_slider, beside) = (Pos2::new(70.0, 60.0), Pos2::new(300.0, 300.0)); + let mut frames = Frames::new(); + frames.idle(2, &mut show_frame); + // Turns the wheel on the slider, opens a modal during the gesture, then ends the gesture with a pass of `events` + // that holds a press. + let pressed = |frames: &mut Frames, show_frame: &mut dyn FnMut(&mut Ui), events: Vec| { + frames.frame(vec![pointer::moved(on_slider)], &mut *show_frame); + frames.frame(vec![pointer::wheel(-30.0)], &mut *show_frame); + open.set(true); + frames.idle(2, &mut *show_frame); + end.set(None); + frames.frame(events, &mut *show_frame); + let share = end.take().expect("the press ends the slider's gesture in its pass"); + frames.frame(vec![pointer::release(beside)], &mut *show_frame); + open.set(false); + frames.advance(2.0 * GESTURE_GAP); + frames.idle(2, &mut *show_frame); + share + }; + + let plain = pressed(&mut frames, &mut show_frame, vec![pointer::press(beside)]); + assert!(!plain.modal, "a press with no wheel in its pass: {plain:?}"); + let before = pressed(&mut frames, &mut show_frame, vec![pointer::wheel(-30.0), pointer::press(beside)]); + assert!(before.modal, "a wheel the modal held before the press arrived during the gesture: {before:?}"); + let after = pressed(&mut frames, &mut show_frame, vec![pointer::press(beside), pointer::wheel(-30.0)]); + assert!(!after.modal, "a wheel the modal held after the press came after the gesture: {after:?}"); +} + /// What the view under the pointer took over one step: the summed scroll, the product of the zooms and the number of /// shares. #[derive(Clone, Copy, Debug, PartialEq)] diff --git a/crates/ui-contract/tests/it/runtime/windows.rs b/crates/ui-contract/tests/it/runtime/windows.rs index 494a6fd090..49153a2259 100644 --- a/crates/ui-contract/tests/it/runtime/windows.rs +++ b/crates/ui-contract/tests/it/runtime/windows.rs @@ -1889,3 +1889,33 @@ fn dropped_window_input_leaves_a_hosted_window_only_injected_input() { assert!(seen.get().primary, "{policy:?}: the injected click reaches the window: {:?}", seen.get()); } } + +/// A child window that one pass of a frame leaves out and the next shows again, as a popup that closes and opens +/// again within a frame, while its OS window stays open: egui drops the viewport and counts its passes from zero again. +/// A component that the window shows before it closes, and again from its third pass after it opens, runs once in +/// each of its passes, as it would in a window opened for the first time. +#[trial] +fn a_child_window_shown_again_in_a_later_pass_of_its_frame_runs_its_component_once_a_pass() { + let windows = Windows::new(); + let seen = RefCell::new(Seen::default()); + // The window's passes in each frame: 0, 1 and 2 with the component; it opens again as pass 0 in the second pass + // of frame 3, then 1 without the component and 2 and 3 with it. + let frames = [(false, true), (false, true), (false, true), (true, false), (false, false), (false, true), (false, true)]; + for (frame, (reopens, shows)) in frames.into_iter().enumerate() { + let mut passes = 0; + windows.frame(vec![], vec![], |ui| { + passes += 1; + if reopens && passes == 1 { + ui.ctx().request_discard("the child window opens again in the next pass"); + return; + } + ui.ctx().show_viewport_immediate(child(), ViewportBuilder::default(), |cui, _| { + if shows { + Probe::new(&seen).label("Kid").id_salt("kid").show(cui); + } + }); + }); + assert_eq!(passes, if reopens { 2 } else { 1 }, "frame {frame}"); + } + assert!(seen.borrow().id.is_some(), "the child window ran its component"); +} diff --git a/crates/ui-panels/src/dialog/host.rs b/crates/ui-panels/src/dialog/host.rs index 4c4dd996f3..e2bb1d7c8c 100644 --- a/crates/ui-panels/src/dialog/host.rs +++ b/crates/ui-panels/src/dialog/host.rs @@ -649,7 +649,15 @@ impl DialogHost { /// Where the held OK of the open dialog `id` names stands ([`StackDialog::held_state`]); `None` when no such dialog /// is open or its OK holds nothing now. pub fn held_state(&self, id: DialogId) -> Option { - self.open.iter().find(|dialog| dialog.id() == id)?.held_state() + self.held_state_with_open_serial(id)?.1 + } + + /// The opening serial and held OK state for the dialog [`confirm_by_id`](Self::confirm_by_id) addresses. + /// If dialogs share the ID, this follows that action's first match. The outer `None` means no such dialog is + /// open. An opening with no held OK has a serial and a `None` state. + pub fn held_state_with_open_serial(&self, id: DialogId) -> Option<(u64, Option)> { + let dialog = &self.open[self.position_by_id(id)?]; + Some((dialog.serial, dialog.held_state())) } /// The canvas of the most recently opened dialog that shows the document on one ([`StackDialog::canvas`]): where diff --git a/crates/ui-panels/src/rails/tool.rs b/crates/ui-panels/src/rails/tool.rs index c18ff08aa9..134873e659 100644 --- a/crates/ui-panels/src/rails/tool.rs +++ b/crates/ui-panels/src/rails/tool.rs @@ -46,7 +46,8 @@ pub use drag::{DropAt, ToolDrag, ToolDropped, drop_in_slot}; #[env(style)] #[non_exhaustive] pub enum RailDensity { - /// Buttons `size.rail.button` square. + /// Buttons `size.rail.button` apart: `size.rail.button` less `space.gap.tight` square, so a button and the tight + /// gap after it take `size.rail.button`. #[default] Regular, /// Buttons a control high (`size.control.md`) square: a denser step than the scope's density gives, for an app @@ -58,7 +59,7 @@ impl RailDensity { /// The side of a rail button at this density. pub fn button(self, tokens: &UiTokens) -> f32 { match self { - RailDensity::Regular => tokens.size.rail.button, + RailDensity::Regular => tokens.size.rail.button - tokens.space.gap.tight, RailDensity::Dense => tokens.size.control.md, } } @@ -132,7 +133,8 @@ type FooterFn<'a> = Box; /// and the slots fill the rows in reading order. The control padding surrounds the buttons; a slot that ends a group /// leaves `space.gap.inline` after its row; slots within a group sit `space.gap.tight` apart. The Edit Toolbar button /// follows the last slot; the host's footer stays in view under the slots, a divider rule and `space.gap.inline` below -/// them when that footer draws content, and the slots scroll when the room is short under +/// them when that footer draws content (with [`footer_scrolls`](ToolRail::footer_scrolls) it scrolls with the slots +/// instead), and the slots scroll when the room is short under /// an overlay bar in the end padding that shows only under the pointer (`Scroll::overlay`), or at rest too with /// [`bar_at_rest`](ToolRail::bar_at_rest), and its /// buttons show the rail's glyphs. The rail is exactly as tall as its rows and footer at the width it gets @@ -192,6 +194,10 @@ pub struct ToolRail<'a, T: Value + MemoProps + PlainData + 'static> { /// How the button of the current tool shows it is on. #[prop] active_look: ActiveLook, + /// The host's footer stands under the slots inside the scroll region, so in a rail too short for its rows and + /// footer it scrolls with the slots instead of staying in view. + #[prop(flag)] + footer_scrolls: bool, footer: Option>, /// The columns the rail lays out in this pass. columns: usize, @@ -230,6 +236,7 @@ impl<'a, T: Value + MemoProps + PlainData + 'static> ToolRail<'a, T> { tips: None, density: RailDensity::Regular, active_look: ActiveLook::Accent, + footer_scrolls: false, footer: None, columns: 1, shown: Rc::default(), @@ -277,7 +284,15 @@ impl<'a, T: Value + MemoProps + PlainData + 'static> ToolRail<'a, T> { fn prepare(&mut self, ui: &Ui, width: f32, footer: impl FnMut(&mut Ui, RailFooter) + 'a) -> Draw<'a, T> { self.columns = usize::from(self.grid(ui, self.cells()).steps_within(width)); self.props = std::mem::take(&mut self.props).roving(Roving::new(NavShape::wrapped_grid(self.columns))); - self.footer = Some(Box::new(footer)); + let footer: FooterFn<'a> = Box::new(footer); + // A footer that scrolls stands in the body, under the slots; one that stays in view is the rail's footer region. + let scrolled = if self.footer_scrolls { + self.props.footer = None; + Some(footer) + } else { + self.footer = Some(footer); + None + }; Draw { slots: self.slots, current: self.current, @@ -293,6 +308,7 @@ impl<'a, T: Value + MemoProps + PlainData + 'static> ToolRail<'a, T> { tips: self.tips, mark: self.mark, reveal: self.reveal, + footer: scrolled, } } } @@ -361,9 +377,26 @@ struct Draw<'a, T: PlainData> { tips: Option<&'a dyn ToolTips>, mark: Option<&'a T>, reveal: Option<&'a T>, + /// The host's footer when it scrolls with the slots ([`ToolRail::footer_scrolls`]). + footer: Option>, } impl Draw<'_, T> { + /// The rail's body: the grid, and under it the host's footer when it scrolls with the slots, after a divider rule + /// and `space.gap.inline` when that footer draws content, as the footer region shows it. + fn body(&mut self, ui: &mut Ui, events: &mut Vec>) -> (Option, Vec<(usize, Rect)>) { + let Some(mut footer) = self.footer.take() else { return self.run(ui, events) }; + let (columns, mut ran) = (self.columns, None); + Stack::new() + .fill_width() + .footer(|ui, _| footer(ui, RailFooter { columns })) + .footer_rule() + .footer_gap(Gap::Inline) + .show(ui, |ui, _| ran = Some(self.run(ui, events))); + self.footer = Some(footer); + ran.unwrap_or_default() + } + /// Shows the grid as a memoized view; what the buttons report goes into `events` (nothing on a replay). Returns the /// Edit Toolbar button's id while the rail shows it, and the host's index and rect of each slot button. fn run(&self, ui: &mut Ui, events: &mut Vec>) -> (Option, Vec<(usize, Rect)>) { @@ -504,7 +537,8 @@ fn grid(props: &mut GridProps<'_, T>, ui: &mut impl<'a, T: Value + MemoProps + PlainData + 'static> ToolRail<'a, T> { /// Shows the rail in the width `ui` has left. `footer` draws under the last slot (colour chips, Quick Mask, - /// Screen Mode); it stays in view when the room is short. + /// Screen Mode); it stays in view when the room is short, unless it scrolls with the slots + /// ([`footer_scrolls`](ToolRail::footer_scrolls)). pub fn show_rail(self, ui: &mut Ui, footer: impl FnMut(&mut Ui, RailFooter) + 'a) -> ToolRailOutput { let room = ui.available_width(); self.show_within(ui, room, footer) @@ -519,7 +553,7 @@ impl<'a, T: Value + MemoProps + PlainData + 'static> ToolRail<'a, T> { /// Shows the rail laid out `width` wide. fn show_within(mut self, ui: &mut Ui, width: f32, footer: impl FnMut(&mut Ui, RailFooter) + 'a) -> ToolRailOutput { - let draw = self.prepare(ui, width, footer); + let mut draw = self.prepare(ui, width, footer); // The last-used tools after this pass: derived while the slots, the remembered and hidden tools and the current tool are as they were. let key = (draw.slots.revision(), draw.last_used.revision(), draw.hidden.map(Tracked::revision), draw.current); let last = crate::runtime::derived::derived(ui.ctx(), ui.scope_id().with("remembered"), &key, || { @@ -528,7 +562,7 @@ impl<'a, T: Value + MemoProps + PlainData + 'static> ToolRail<'a, T> { let last = last.as_ref().clone(); let (mut events, mut edit_toolbar, laid) = (Vec::new(), None, Rc::clone(&self.shown)); let shown = self.show(ui, |ui, _| { - let (edit, slots) = draw.run(ui, &mut events); + let (edit, slots) = draw.body(ui, &mut events); edit_toolbar = edit; *laid.borrow_mut() = slots; }); @@ -559,9 +593,9 @@ impl<'a, T: Value + MemoProps + PlainData + 'static> ToolRail<'a, T> { /// The size of the rail laid out `width` wide, with `footer` under its rows: as many columns as `width` holds, /// as tall as its rows and footer (at most the room along the axis it scrolls on). pub fn measure_rail(mut self, ui: &Ui, width: f32, footer: impl FnMut(&mut Ui, RailFooter) + 'a) -> Vec2 { - let draw = self.prepare(ui, width, footer); + let mut draw = self.prepare(ui, width, footer); self.measure_in(ui, Proposal::Width(width), |ui, _| { - draw.run(ui, &mut Vec::new()); + draw.body(ui, &mut Vec::new()); }) } } diff --git a/crates/ui-panels/src/rails/tool/trials.rs b/crates/ui-panels/src/rails/tool/trials.rs index b252d8373e..655a7aa898 100644 --- a/crates/ui-panels/src/rails/tool/trials.rs +++ b/crates/ui-panels/src/rails/tool/trials.rs @@ -16,7 +16,7 @@ use crate::runtime::env::ThemeScope; use crate::style::StyleCx; use crate::testing::pointer::secondary; use crate::testing::pointer::{moved, wheel}; -use crate::testing::relations::{above, grows_with}; +use crate::testing::relations::{above, equals_token, grows_with}; use crate::testing::{Fixture, MemoRun, last_frame_derived_builds, last_frame_memo_runs, last_pass_memo_key_bytes, trial}; use craft_theme::Size; use egui::{Rect, Vec2}; @@ -156,6 +156,79 @@ fn in_a_short_room_the_rows_scroll_above_the_footer_that_stays_in_view() { } } +/// A regular rail's buttons stand `size.rail.button` apart down a column: a button and the tight gap after it take +/// that step, so a column of a given height holds as many buttons as the step divides into it. +#[trial] +fn a_regular_rails_buttons_stand_a_rail_button_apart() { + let grid = DockGrid::rail(LABELS.len()).resolved(&DockSizes::of(Fixture::new(|_| {}).ctx())); + let (fixture, _) = rail_in(grid.width(1), 800.0); + let step = StyleCx::with_root(fixture.ctx(), |cx| cx.tokens.size.rail.button); + let tops: Vec = LABELS.iter().map(|label| rect(&fixture, label).top()).collect(); + for pair in tops.windows(2) { + assert!(equals_token(pair[1] - pair[0], step), "the buttons stand {step} apart: {tops:?}"); + } +} + +/// A one-column rail in a room `height` high, with `footer_scrolls` when `scrolls`, and the size `measure_rail` gives +/// it. +fn scrolling_rail_in(width: f32, height: f32, scrolls: bool) -> (Fixture, Rc>) { + let measured = Rc::new(Cell::new(Vec2::ZERO)); + let report = Rc::clone(&measured); + let (slots, last) = (Tracked::new(slots()), Tracked::new(LastUsed::default())); + let mut fixture = Fixture::new(move |ui| { + let rail = || { + let rail = ToolRail::new("Tools", &slots, &0, &last); + if scrolls { rail.footer_scrolls() } else { rail } + }; + report.set(rail().measure_rail(ui, width, |ui, _| { + Button::new("Foot").show(ui); + })); + rail().show_rail(ui, |ui, _| { + Button::new("Foot").show(ui); + }); + }); + fixture.room(Vec2::new(width, height)).settle(); + (fixture, measured) +} + +/// With `footer_scrolls` the footer stands under the last row inside the scroll region. In a tall room the rail lays +/// out and measures as one whose footer stays in view; in a short room it shows more buttons than that rail, the +/// footer starts out of view, and scrolling brings it in under the last button. +#[trial] +fn with_footer_scrolls_the_footer_scrolls_with_the_rows() { + let grid = DockGrid::rail(LABELS.len()).resolved(&DockSizes::of(Fixture::new(|_| {}).ctx())); + let width = grid.width(1); + let ((pinned, pinned_size), (scrolled, scrolled_size)) = (scrolling_rail_in(width, 800.0, false), scrolling_rail_in(width, 800.0, true)); + let (pinned_size, scrolled_size) = (pinned_size.get(), scrolled_size.get()); + assert!(near(scrolled_size.y, pinned_size.y), "in a tall room the measures match: {scrolled_size:?} against {pinned_size:?}"); + for label in LABELS.iter().copied().chain(["Foot"]) { + let (at, pinned_at) = (rect(&scrolled, label), rect(&pinned, label)); + assert!(near(at.top(), pinned_at.top()), "{label} stands where it does under a footer that stays in view: {at:?} against {pinned_at:?}"); + } + + let height = 100.0; + // A button is in view above the footer and inside the rail. + let in_view = |fixture: &Fixture| { + let bottom = rect(fixture, "Tools").bottom().min(rect(fixture, "Foot").top()); + LABELS.iter().filter(|label| rect(fixture, label).bottom() <= bottom).count() + }; + let ((pinned, _), (mut scrolled, measured)) = (scrolling_rail_in(width, height, false), scrolling_rail_in(width, height, true)); + assert!(measured.get().y > height, "the rows and the footer do not fit the room"); + let (pinned_count, scrolled_count) = (in_view(&pinned), in_view(&scrolled)); + assert!(scrolled_count > pinned_count, "more buttons are in view: {scrolled_count} against {pinned_count}"); + let rail = rect(&scrolled, "Tools"); + assert!(rect(&scrolled, "Foot").top() >= rail.bottom(), "the footer starts out of view"); + + scrolled.frame(vec![moved(rect(&scrolled, "Move").center())]); + for _ in 0..10 { + scrolled.frame(vec![wheel(-120.0)]); + } + scrolled.settle(); + let (last, foot) = (rect(&scrolled, "Clone Stamp"), rect(&scrolled, "Foot")); + assert!(grows_with(foot.bottom(), rail.bottom()), "the footer is in view after scrolling: {foot:?} in {rail:?}"); + assert!(above(last, foot), "the last button is above the footer: {last:?} over {foot:?}"); +} + /// A rail too short for its rows shows its bar in the end padding beside the buttons while the pointer is away only /// with `bar_at_rest`. #[trial] diff --git a/crates/ui-panels/tests/it/rails/drawer.rs b/crates/ui-panels/tests/it/rails/drawer.rs index 57b2fa76f4..4d4f315f40 100644 --- a/crates/ui-panels/tests/it/rails/drawer.rs +++ b/crates/ui-panels/tests/it/rails/drawer.rs @@ -319,6 +319,9 @@ fn the_drawer_title_and_hint_line_up_with_the_headings() { fn a_rule_parts_the_drawers_list_from_its_footer_at_the_drawers_foot() { use craft_ui::contract::Role; let mut fixture = drawer_fixture(40); + // The width check measures against the Cut row, whose shortcut text follows the OS (Ctrl+X, or the shorter ⌘X on + // a Mac host). Pin one OS so the yardstick is the same on every runner. + fixture.os(craft_host::target::Os::Linux); fixture.room(Vec2::new(480.0, 240.0)).idle(30); let drawer = fixture.by_role(Role::DIALOG).first().expect("the drawer is open").rect; let restore = fixture.by_label("Restore Defaults").expect("the Restore Defaults button").rect; diff --git a/crates/ui-patterns/src/patterns/form_dialogs/new_document.rs b/crates/ui-patterns/src/patterns/form_dialogs/new_document.rs index 8c256f5b1c..72cd2425ed 100644 --- a/crates/ui-patterns/src/patterns/form_dialogs/new_document.rs +++ b/crates/ui-patterns/src/patterns/form_dialogs/new_document.rs @@ -88,6 +88,8 @@ craft_ui::words! { /// The Color Profile entry of [`NewDocumentDialog::unmanaged_profile`]: no profile is embedded. dont_color_manage: "newDocument.dontColorManage" = "Don't Color Manage"; background: "newDocument.background" = "Background Contents"; + /// The disclosure under Background Contents that holds Color Profile and Pixel Aspect Ratio. + advanced_options: "newDocument.advancedOptions" = "Advanced Options"; white: "newDocument.white" = "White"; black: "newDocument.black" = "Black"; background_color: "newDocument.backgroundColor" = "Background Color"; @@ -111,7 +113,7 @@ craft_ui::words! { depth_1: "newDocument.depth1" = "1 bit"; depth_8: "newDocument.depth8" = "8 bit"; depth_16: "newDocument.depth16" = "16 bit"; - depth_32: "newDocument.depth32" = "32 bit (float)"; + depth_32: "newDocument.depth32" = "32 bit"; orientation: "newDocument.orientation" = "Orientation"; pixel_aspect: "newDocument.pixelAspect" = "Pixel Aspect Ratio"; square_pixels: "newDocument.pixelAspectSquare" = "Square Pixels"; @@ -468,9 +470,10 @@ fn body(ui: &mut Ui, form: &mut FormCx<'_, '_>, values: &mu /// the orientation control. Saved and recent cards restore every setting but the name. A Web or Mobile card turns /// Artboards on; a card of another category turns it off again only when such a card turned it on. /// - Details: Name with the Save Document Preset icon, Width and Height with their units, Orientation, Artboards, -/// Resolution, Color Mode, Depth, Color Profile, Pixel Aspect Ratio (the built-in ratios, then the app's -/// [`custom_pixel_aspects`](NewDocumentDialog::custom_pixel_aspects)) and Background Contents. Bitmap takes only 1 -/// bit and offers no Transparent background ([`DocumentOptions::fitted`]). +/// Resolution, Color Mode, Depth, Background Contents, then an Advanced Options disclosure (open by default) +/// holding Color Profile and Pixel Aspect Ratio (the built-in ratios, then the app's +/// [`custom_pixel_aspects`](NewDocumentDialog::custom_pixel_aspects)). Bitmap takes only 1 bit and offers no +/// Transparent background ([`DocumentOptions::fitted`]). /// - Save Document Preset: the icon opens a pane in place of the details with the first free `Saved N` selected; /// Save Preset or Enter saves the preset and does not create the document, Cancel goes back. The name is checked by /// the preset library (not blank, different from the saved names ignoring case), and at most 256 presets are kept. diff --git a/crates/ui-patterns/src/patterns/form_dialogs/new_document/details.rs b/crates/ui-patterns/src/patterns/form_dialogs/new_document/details.rs index 2490ac4d1b..e2c655c68d 100644 --- a/crates/ui-patterns/src/patterns/form_dialogs/new_document/details.rs +++ b/crates/ui-patterns/src/patterns/form_dialogs/new_document/details.rs @@ -19,6 +19,7 @@ use crate::runtime::env::{Env, Label, Message, UnitKind, Units}; use crate::runtime::focus::{self, FocusTarget}; use crate::runtime::requests::{ColorRequest, HostAnswer}; use crate::runtime::words::CommonWords; +use crate::sections::{HeaderStrength, Section}; use crate::style::TypeRole; use crate::text::{NumberField, TextField}; use craft_behavior::{ColumnWidth, EditEvent, EditEvents, IconId, NumberCodec, PixelSize}; @@ -312,20 +313,23 @@ fn raster_rows(ui: &mut Ui, values: &mut DocumentOptions, memory: &mut RasterMem } }); }); - Field::new(words.profile.clone()).layout(FieldLayout::Above).id_salt("profile").show(ui, |ui, _| { - let current = values.profile.clone().filter(|profile| others.contains(&profile) || Some(profile) == unmanaged); - let shown = Select::new(words.profile.clone(), Bind::given(current), &profiles).sizing(Sizing::FillWidth).show(ui); - if let Some(profile) = shown.value().cloned() { - values.profile = profile; - } - }); - Field::new(words.pixel_aspect.clone()).layout(FieldLayout::Above).id_salt("pixel-aspect").show(ui, |ui, _| { - let listed = pixel_aspects.iter().any(|entry| entry.value() == Some(&values.pixel_aspect)); - let current = if listed { values.pixel_aspect.clone() } else { SQUARE_PIXELS.to_owned() }; - let shown = Select::new(words.pixel_aspect.clone(), Bind::given(current), &pixel_aspects).sizing(Sizing::FillWidth).show(ui); - if let Some(id) = shown.value().cloned() { - values.pixel_aspect = id; - } + // Color Profile and Pixel Aspect Ratio stand under Advanced Options, open by default; collapsing it keeps their values. + Section::new(words.advanced_options.clone()).strength(HeaderStrength::Subheading).id_salt("advanced").show(ui, |ui, _| { + Field::new(words.profile.clone()).layout(FieldLayout::Above).id_salt("profile").show(ui, |ui, _| { + let current = values.profile.clone().filter(|profile| others.contains(&profile) || Some(profile) == unmanaged); + let shown = Select::new(words.profile.clone(), Bind::given(current), &profiles).sizing(Sizing::FillWidth).show(ui); + if let Some(profile) = shown.value().cloned() { + values.profile = profile; + } + }); + Field::new(words.pixel_aspect.clone()).layout(FieldLayout::Above).id_salt("pixel-aspect").show(ui, |ui, _| { + let listed = pixel_aspects.iter().any(|entry| entry.value() == Some(&values.pixel_aspect)); + let current = if listed { values.pixel_aspect.clone() } else { SQUARE_PIXELS.to_owned() }; + let shown = Select::new(words.pixel_aspect.clone(), Bind::given(current), &pixel_aspects).sizing(Sizing::FillWidth).show(ui); + if let Some(id) = shown.value().cloned() { + values.pixel_aspect = id; + } + }); }); if ask_color { diff --git a/crates/ui-patterns/src/patterns/form_dialogs/param.rs b/crates/ui-patterns/src/patterns/form_dialogs/param.rs index 6686a70757..e50249da44 100644 --- a/crates/ui-patterns/src/patterns/form_dialogs/param.rs +++ b/crates/ui-patterns/src/patterns/form_dialogs/param.rs @@ -648,7 +648,7 @@ pub(crate) struct RowOptions { resettable: bool, /// The label a footer row shows while on ([`Param::in_footer`]). footer_on: Option