Framework sync: merge craft-libs main (186a229c8, with the egui numpad rev)

Conflicts: the paragraph trials keep both sides' trials; the pass pointer keeps upstream's stirred (moved to a new position) and the port's moved (a move event this pass); the shell's slot visibility, overlay and covering tests combine the port's page rule with upstream's standard-mode bar reveal.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Dylan M. TaylorandClaude Opus 5.5 committed 2026-11-29 13:53:40 +00:00
commit c219d0c6fa
102 files changed
+3573 -369

No files matched your search

Generated
+14 -2
View File
@@ -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"
+14 -14
View File
@@ -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
+3 -1
View File
@@ -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())));
+8 -9
View File
@@ -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);
+5 -2
View File
@@ -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),
})
+26 -22
View File
@@ -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<Value> {
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<ControlRequest>, server::Listening, Receiv
fn nothing_more_dispatched(rx: &Receiver<ControlRequest>, 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<ControlRequest>) -> 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<ControlRequest>) -> 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<String> = 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<TcpStream>) {
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<TcpStream>) {
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");
+52 -2
View File
@@ -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<Value, String> {
@@ -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<DialogResult<Self::Result>> {
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::<HostedParamDialog>()).expect("the held dialog is open")
+9
View File
@@ -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,
}
}
+4 -2
View File
@@ -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.
+41 -3
View File
@@ -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<PickedColor>) {
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 }));
}
}
+5 -2
View File
@@ -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),
);
}
}
+129 -3
View File
@@ -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<RefCell<PickedColor>>, 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<RefCell<PickedColor>>, 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| {
+1 -1
View File
@@ -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] = &[
+38 -4
View File
@@ -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::<StrokeWords>();
let name: Arc<str> = 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<str>,
}
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);
+57 -2
View File
@@ -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]);
+9 -3
View File
@@ -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)),
@@ -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,
+19
View File
@@ -161,6 +161,25 @@ fn page_rig(kind: EffectKind, params: Option<StyleParams>) -> (Fixture, Rc<RefCe
rig_of(host(draft, vec![spec]))
}
/// Bevel & Emboss offers the five styles in the reference application's menu order, and a stored Stroke Emboss shows
/// by name rather than as a blank.
#[trial]
fn bevel_style_offers_stroke_emboss_in_menu_order() {
let spec = EffectSpec::photoshop(EffectKind::BevelEmboss);
let Some(FieldKind::Choice(choices)) = spec.fields.iter().find(|field| field.key == "style").map(|field| &field.kind) else {
panic!("Bevel & Emboss has a Style choice")
};
let values: Vec<&str> = 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]
+65 -12
View File
@@ -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<FooterButton>, Vec<Act>) {
fn footer(env: &Env<'_>, state: &DialogState) -> (Vec<FooterButton>, Vec<Act>) {
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<FooterButton>, Vec<Act>) {
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),
+50 -2
View File
@@ -277,6 +277,13 @@ struct Opened {
holds: Option<HoldSetting>,
}
/// 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<Outcome>,
/// [`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<Toggle>,
// ---- 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,
+44
View File
@@ -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);
+17 -7
View File
@@ -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}");
}
}
@@ -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");
}
+29 -11
View File
@@ -63,6 +63,14 @@ fn hold_mark(lock: &File) -> Option<HoldMark> {
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<T>(path: &Path, f: impl FnOnce() -> Result<T, Error>) ->
}
}
}
// 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]
+4 -6
View File
@@ -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 {
+37 -3
View File
@@ -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<Mixed<bool>> {
@@ -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);
}
@@ -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<dyn Scene>, &'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<Option<f64>>,
texts: Vec<String>,
+3 -1
View File
@@ -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();
+2
View File
@@ -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 },
+6 -5
View File
@@ -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));
}
}
@@ -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
+49
View File
@@ -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<Pos2> = 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]
@@ -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<f32>) -> (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::<Vec<_>>());
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:?}");
}
@@ -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());
+7 -7
View File
@@ -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))
}
}
+25 -5
View File
@@ -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 };
@@ -31,6 +31,9 @@ pub struct FloatPlace {
pub pos: Option<Pos2>,
/// 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<f32>,
}
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<Pos2> {
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.
@@ -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;
+3 -1
View File
@@ -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
@@ -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)),
_ => {}
}
}
+123 -45
View File
@@ -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<R>(ui: &mut Ui, place: &Env, id: Id, mut body: impl FnMut(&mut
let room = shrink_room(ui, place);
let order = if place.values.get::<InBar>().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<ShrinkUnit> = continuous.iter().map(|leaf| leaf.widths).collect();
let whole: Vec<f32> = continuous.iter().map(|leaf| leaf.whole).collect();
let first: Vec<bool> = continuous.iter().map(|leaf| leaf.cut_first).collect();
let ranks: Vec<Option<u8>> = continuous.iter().map(|leaf| leaf.rank).collect();
let level_widths: Vec<Vec<f32>> = 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::<f32>())
} 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::<f32>();
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<R>(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<f32>, ShrinkOrder, bool),
) -> bool {
let (levelled, continuous): (Vec<&Reported>, Vec<&Reported>) = leaves.iter().partition(|leaf| !leaf.levels.is_empty());
let units: Vec<ShrinkUnit> = continuous.iter().map(|leaf| leaf.widths).collect();
let whole: Vec<f32> = continuous.iter().map(|leaf| leaf.whole).collect();
let first: Vec<bool> = continuous.iter().map(|leaf| leaf.cut_first).collect();
let ranks: Vec<Option<u8>> = continuous.iter().map(|leaf| leaf.rank).collect();
let level_widths: Vec<Vec<f32>> = 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::<f32>())
} 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::<f32>();
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<R>(ui: &mut Ui, env: &Env, at: &RowIn, (wrap, align): (bool, RowAlign
inner
})
.0
} else if lines && align == RowAlign::Start && row.values.get::<InBar>().0 {
run_wrap_start(ui, &row, (id, sizing, rtl), &mut body)
} else if wrap {
body(ui)
} else {
@@ -2260,6 +2274,70 @@ fn run_row<R>(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<R>(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<R>(
ui: &mut Ui,
row: &Env,
id: Id,
(line, room): (egui::Layout, f32),
body: &mut impl FnMut(&mut Ui) -> R,
) -> Option<(Vec<Reported>, 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::<ShrinkReports, _>(&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::<ShrinkReports, _>(&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::<f32>();
let short = |width: fn(&Reported) -> f32| fixed + leaves.iter().map(width).sum::<f32>() - 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
+52 -17
View File
@@ -267,14 +267,55 @@ pub(crate) struct Outcome {
xf: Option<LayerMap>,
}
/// 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<T> {
owned: Vec<T>,
retained: Option<Arc<[T]>>,
}
impl<T> Default for Registrations<T> {
fn default() -> Self {
Self { owned: Vec::new(), retained: None }
}
}
impl<T> std::ops::Deref for Registrations<T> {
type Target = [T];
fn deref(&self) -> &Self::Target {
self.retained.as_deref().unwrap_or(&self.owned)
}
}
impl<T> Registrations<T> {
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<T: Clone> Registrations<T> {
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<MemberDecl>,
previous: Vec<MemberDecl>,
own: Vec<PartDecl>,
previous_own: Vec<PartDecl>,
own: Registrations<PartDecl>,
previous_own: Registrations<PartDecl>,
/// 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<RootInfo>,
/// The egui widgets of the root: the root's, the transform forwarder and the edge widgets.
widgets: Vec<Id>,
machine: PressMachine<Hit>,
outcome: Option<Outcome>,
/// 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<PartDecl>,
widgets: Vec<Id>,
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, &registration.own, &registration.widgets, registration.layer);
fn register_root_again(ctx: &Context, arena: ArenaId, registration: &RootRegistration) {
journal_root(ctx, arena, registration.info, &registration.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(&registration.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.
@@ -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<Shape>) {
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),
}
}
+95 -7
View File
@@ -338,7 +338,7 @@ pub(crate) struct PointerRead {
pub sample: Option<PointerSample>,
/// 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<Finger>,
@@ -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<Id>, Option<Id>) {
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<usize> {
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::<RawState>::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<Arrived>, keep: Option<&crate::runtime::sampler::Hole>, pointer: Option<Pos2>) -> (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<Arrived>, keep: Option<&crate::runtime::sampler::Hole>, pointer: Option<Pos2>) -> (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<Arrived>, 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<f64>,
/// 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::<RawState>::with(ctx, input.viewport_id, |state| state.folded_lines = Vec2::ZERO);
PerViewport::<RawState>::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);
}
@@ -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);
}
+45 -12
View File
@@ -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<Rect>,
@@ -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<ShellCx>);
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 &regions.slots {
+30
View File
@@ -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<TypeId, fn(&Context, &[ViewportId])>,
/// What drops the pass-stamped records of a viewport whose pass count egui started again.
restarts: HashMap<TypeId, fn(&Context, ViewportId)>,
sweeps: HashMap<TypeId, fn(&Context)>,
/// What a layer above the runtime reads at the begin hook, after the pointer snapshot and before any component runs.
begins: HashMap<TypeId, fn(&Context)>,
@@ -286,12 +288,20 @@ pub trait Stored: Default + Send + 'static {
fn stamped<R>(ctx: &Context, f: impl FnOnce(&mut PerViewport<Stamped<Self>>) -> R) -> R {
pass_state::with_records::<Stamped<Self>, 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<T: Stored> Stored for Stamped<T> {
fn records<R>(ctx: &Context, f: impl FnOnce(&mut PerViewport<Self>) -> R) -> R {
T::stamped(ctx, f)
}
fn forget_restarted(ctx: &Context, viewport: ViewportId) {
Self::records(ctx, |records| records.records.retain(|(id, _)| *id != viewport));
}
}
impl<T: Stored> PerViewport<T> {
@@ -335,6 +345,9 @@ impl<T: Stored> PerViewport<T> {
T::records(ctx, |records| records.records.retain(|(viewport, _)| live.contains(viewport)));
}
register_prune(ctx, TypeId::of::<T>(), prune::<T>);
pass_state::with::<FrameState, _>(ctx, |state| {
state.restarts.entry(TypeId::of::<T>()).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<fn(&Context, ViewportId)> = pass_state::with::<FrameState, _>(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::<FrameState, _>(ctx, |state| {
@@ -675,6 +696,8 @@ struct ViewportRecord {
press_cancelled: bool,
/// `None` until the viewport's first pass begins.
now: Option<f64>,
/// The pass number of the viewport's latest pass the begin hook ran for.
began: Option<u64>,
}
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::<ViewportRecord>::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::<ViewportRecord>::with(&ctx, viewport, |record| {
// The events this frame's input hook held arrived at the frame's input time.
record.held.stamp(now);
+7 -2
View File
@@ -654,8 +654,13 @@ pub(crate) fn input_hook(ctx: &Context, input: &RawInput, events: &mut Vec<Arriv
let (hole, trimmed) = sampler::hook(ctx, input, events);
// A modal layer in another viewport blocks this one (app-modal, 15.5): nothing below reaches the key stage.
if overlay::modal_elsewhere(ctx, viewport) {
let pointer = ctx.input(|state| state.pointer.latest_pos());
let (removed, press) = raw_input::drop_under_modal(events, hole.as_ref(), pointer);
let pointer = ctx.input_for(viewport, |state| state.pointer.latest_pos());
let (removed, press, wheel) = raw_input::drop_under_modal(events, hole.as_ref(), pointer);
// The wheel turn the modal holds here stays marked once it closes.
if wheel {
let now = input.time.unwrap_or_else(|| ctx.input_for(viewport, |state| state.time + f64::from(input.predicted_dt)));
crate::runtime::wheel::note_held_by_modal(ctx, viewport, now);
}
if press {
overlay::note_dropped_press(ctx, viewport);
}
+121 -17
View File
@@ -19,7 +19,7 @@ use std::fmt::Debug;
use std::hash::{Hash, Hasher};
use std::marker::PhantomData;
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
/// A value kept in memory. `Clone` is required because egui's temp store clones on insert; large caches hold `Arc`s.
pub trait Slot: Clone + Default + Send + Sync + 'static {}
@@ -198,15 +198,62 @@ fn persist_changed(entries: &[Entry]) {
}
}
/// The last registration of an owner: the component id registered at step 3 whose pipeline opened a stage.
struct OwnerRecord {
/// The last registration of one owner or a stationary retained batch.
#[derive(Clone, Copy, PartialEq)]
struct OwnerStamp {
viewport: ViewportId,
pass: u64,
at: f64,
/// The pass of the owner's registration before `pass`, in the same viewport.
before: Option<u64>,
}
struct OwnerRecord {
stamp: OwnerStamp,
batch: Option<u64>,
}
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<OwnerStamp>, 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<Id, OwnerRecord>,
owner_batches: FastMap<u64, RetainedOwners>,
/// 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::<Registry, _>(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::<Registry, _>(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::<Registry, _>(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::<Registry, _>(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::<Registry, _>(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<u64> {
pass_state::with::<Registry, _>(ctx, |reg| reg.owners.get(&owner).map(|record| record.pass))
pass_state::with::<Registry, _>(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`.
@@ -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::<super::Parked>::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();
+65 -10
View File
@@ -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<u64>,
/// 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<Pos2>,
}
/// What one pass's finger events made of the touch.
@@ -229,6 +232,8 @@ type BodyRecord = HashMap<Layer, (Id, Layer)>;
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<T>(items: &mut Vec<T>) {
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::<Memory>::with(ctx, viewport, |memory| {
let (events, targets, touched, moved) = PerViewport::<Memory>::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::<Stamped<Arc<PassPointer>>>::with_pass(ctx, viewport, pass_nr, |_, _| {}, |record| *record = Arc::new(pass_pointer));
PerViewport::<Shapes>::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<Item = Shape<Id>>) {
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<Shape<Id>>) {
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<Id>]) {
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<Item = Shape<Id>>) {
PerViewport::<Shapes>::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::<Shapes>::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;
});
+29 -2
View File
@@ -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<egui::Id>,
/// Owners registered by a shown run, excluding measurement-only registrations.
pub(crate) owner_registrations: Vec<egui::Id>,
/// 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<egui::Id>,
@@ -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<Entry>,
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::<Vec<_>>();
found.push(format!("inputs: left {:?} / right {:?}", list(self.facts.inputs), list(run.facts.inputs)));
@@ -453,6 +464,12 @@ fn min_wake(a: Option<f64>, b: Option<f64>) -> Option<f64> {
/// 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.
+10
View File
@@ -131,6 +131,16 @@ impl<T: Shift, const N: usize> Shift for [T; N] {
}
}
impl<T: Shift> 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<T: Shift> Shift for Vec<T> {
fn shifted(&self, by: &RecordShift) -> Self {
self.iter().map(|value| value.shifted(by)).collect()
+92 -9
View File
@@ -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<WheelTaker<Id>>,
last: Vec<WheelTaker<Id>>,
@@ -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<Ended>,
/// The wheel ease each owner holds.
eases: egui::IdMap<WheelEase>,
}
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::<State>::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 });
}
}
}
+56 -2
View File
@@ -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() {
@@ -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");
}
@@ -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:?}"
);
}
}
@@ -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<Option<Wheel>> = 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<Option<Wheel>> = 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<Event>| {
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<Option<Wheel>> = 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<Event>| {
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<Cell<Option<Wheel>>> = 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<Event>| {
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<Option<Wheel>> = 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<Event>| {
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)]
@@ -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");
}
+9 -1
View File
@@ -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<HeldOk> {
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<HeldOk>)> {
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
+43 -9
View File
@@ -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<dyn FnMut(&mut Ui, RailFooter) + 'a>;
/// 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<FooterFn<'a>>,
/// 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<T>>,
mark: Option<&'a T>,
reveal: Option<&'a T>,
/// The host's footer when it scrolls with the slots ([`ToolRail::footer_scrolls`]).
footer: Option<FooterFn<'a>>,
}
impl<T: Value + MemoProps + PlainData> 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<RailEvent<T>>) -> (Option<Id>, 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<RailEvent<T>>) -> (Option<Id>, Vec<(usize, Rect)>) {
@@ -504,7 +537,8 @@ fn grid<T: Value + MemoProps + PlainData>(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<T> {
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<T> {
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());
})
}
}
+74 -1
View File
@@ -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<f32> = 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<Cell<Vec2>>) {
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]
@@ -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;
@@ -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<S: DocumentSettings>(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.
@@ -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 {
@@ -648,7 +648,7 @@ pub(crate) struct RowOptions {
resettable: bool,
/// The label a footer row shows while on ([`Param::in_footer`]).
footer_on: Option<Label>,
/// The lengths a number row keeps and shows ([`Param::length`]).
/// The lengths a number or range row keeps and shows ([`Param::length`]).
length: Option<LengthUnits>,
/// The codec a number row reads and writes with ([`Param::codec`]).
codec: Option<NumberCodec>,
@@ -1156,7 +1156,8 @@ impl Param {
self
}
/// Draws a `Number` row as a length: the stored unit in the binding, the shown unit in the field.
/// Draws a `Number` or `Range` row as a length: the stored unit in the binding, the range and a range row's
/// slider, the shown unit in the field.
#[must_use]
pub fn length(mut self, lengths: LengthUnits) -> Self {
self.options.get_or_insert_default().length = Some(lengths);
@@ -380,7 +380,9 @@ impl<'a> PropertiesDialog<'a> {
dialog = dialog.preview(Some(preview));
}
let rows = RefCell::new(None::<ParamRowsOutput>);
let (shown_tab, mut latest) = (Cell::new(0), None::<DialogFields>);
// The tab the body showed; none when the body did not run (a closed dialog, or a measuring run that ends before
// the body), and then the bound tab keeps its value.
let (shown_tab, mut latest) = (Cell::new(None::<usize>), None::<DialogFields>);
let shown = dialog.show(ui, |ui, form, fields| {
if form.first() {
let all: Vec<Param> = per_tab.iter().flatten().cloned().collect();
@@ -429,7 +431,7 @@ impl<'a> PropertiesDialog<'a> {
Notice::new(Tone::Bad, reason.clone()).layout(NoticeLayout::Inline).show(ui);
}
form.memory::<OpenTab>().0 = current;
shown_tab.set(current);
shown_tab.set(Some(current));
resettable.set(tabs.get(current).is_some_and(|tab| tab.resettable));
if hold {
latest = Some(fields.clone());
@@ -437,14 +439,15 @@ impl<'a> PropertiesDialog<'a> {
true
});
if let Some(bind) = tab_bind.as_mut()
&& read_bind(bind) != Some(shown_tab.get())
&& let Some(at) = shown_tab.get()
&& read_bind(bind) != Some(at)
{
write_bind(bind, shown_tab.get());
write_bind(bind, at);
}
let tab_reset = pressed.get();
if tab_reset && let Some(tab) = tabs.get(shown_tab.get()) {
if tab_reset && let Some((at, tab)) = shown_tab.get().and_then(|at| tabs.get(at).map(|tab| (at, tab))) {
let mut fields = read_bind(&mut values).unwrap_or_default();
Self::reset_tab(tab, shown_tab.get(), &mut fields);
Self::reset_tab(tab, at, &mut fields);
write_bind(&mut values, fields);
}
let result = match shown.closed {
@@ -480,6 +480,24 @@ impl Line<'_> {
});
}
/// Shows `body` in a field named by the row with its caption hidden: where the rows of the form share a label
/// column, `body` starts past that column, where the controls of the captioned rows and the check boxes start. A
/// `bare` row and a row in a shared line show `body` where they stand.
fn show_uncaptioned(&self, ui: &mut Ui, mut body: impl FnMut(&mut Ui)) {
if self.bare || self.compact {
body(ui);
return;
}
let env = Env::of(ui);
let view = env.view();
let own_caption = view.get::<LabelScheme>() == LabelScheme::Inline && !view.get::<CaptionColumn>().shared();
let mut field = Field::new(self.name.clone()).id_salt(self.key).enabled(self.enabled).side(SideLabel::new().kind(LabelKind::Hidden));
if own_caption {
field = field.layout(FieldLayout::Above);
}
field.show(ui, |ui, _| body(ui));
}
/// The help button after a row's control: a press is noted for the pass, which reports the row's link.
fn help_button(&self, ui: &mut Ui) {
let help = Env::of(ui).words::<ParamWords>().help.clone();
@@ -890,6 +908,9 @@ impl<'p> Pass<'p> {
if let Some(kind) = line.param.unit {
slider = slider.unit_kind(kind);
}
if let Some(lengths) = option.length() {
slider = slider.lengths(lengths);
}
if let Some(text) = line.param.unit_label_text() {
slider = slider.unit(text.clone());
}
@@ -926,18 +947,30 @@ impl<'p> Pass<'p> {
// Match the ordinary range row's number field precision when the caller sets no step.
let default_step = if range.end() - range.start() <= 10.0 { 0.01 } else { 1.0 };
let step = set_step.unwrap_or(default_step);
let kind = line.param.unit;
let lengths = line.param.option().length();
let kind = lengths.map(|lengths| lengths.shown).or(line.param.unit);
let symbol: Option<Label> = line.param.unit_label_text().cloned().or_else(|| kind.map(|kind| self.units.symbol(kind).into()));
let default = line.param.default_value().and_then(number_of).map(Some);
line.show(ui, |ui| {
Row::new().show(ui, |ui, _| {
let mut field = NumberField::new(line.name.clone(), line.bind(Some(value), default))
.range(range.clone())
.popup_slider(range.clone())
.snap_popup_slider(set_step.is_some())
.commit_decimals(decimals_for_step(step))
.scrub_by_label();
if set_step.is_some() || default_step != 1.0 {
let bind = line.bind(Some(value), default);
let mut field = match lengths {
// A length field keeps the shown unit's decimals and, without a set step, its step; a set step is
// in the stored unit, so the field steps by it in the shown unit and snaps typed values to it.
Some(lengths) => {
let field = NumberField::length(line.name.clone(), bind, lengths);
match (set_step, self.units.length_scale(lengths)) {
(Some(step), Some(scale)) => field.step(step * scale).snap_typed(true),
_ => field,
}
}
None => NumberField::new(line.name.clone(), bind).commit_decimals(decimals_for_step(step)),
}
.range(range.clone())
.popup_slider(range.clone())
.snap_popup_slider(set_step.is_some())
.scrub_by_label();
if lengths.is_none() && (set_step.is_some() || default_step != 1.0) {
field = field.step(step).snap_typed(set_step.is_some());
}
if let Some(kind) = kind {
@@ -1203,15 +1236,16 @@ impl<'p> Pass<'p> {
}
/// A radio row is its own section: the title shows the row's name once, and the group it names follows. A row with
/// [`options_in_row`](Param::options_in_row) has no title and stands its options side by side.
/// [`options_in_row`](Param::options_in_row) has no title and stands its options side by side. In a form whose
/// rows share a label column, the options start in the control column ([`Line::show_uncaptioned`]).
fn radio_options(&mut self, ui: &mut Ui, line: &Line<'_>, options: &[(String, Label)], details: &[Label]) {
let inline = Env::of(ui).view().get::<LabelScheme>() == LabelScheme::Inline;
if line.param.option().options_in_row() {
self.radio_group(ui, line, options, details, true);
line.show_uncaptioned(ui, |ui| self.radio_group(ui, line, options, details, true));
return;
}
if line.param.option().stacked_options() {
self.radio_group(ui, line, options, details, false);
line.show_uncaptioned(ui, |ui| self.radio_group(ui, line, options, details, false));
return;
}
// A document dialog sets the caption and its options on one line, as production's do; the caption is left out
@@ -1227,7 +1261,7 @@ impl<'p> Pass<'p> {
return;
}
Section::fixed(line.name.clone()).strength(HeaderStrength::Caption).id_salt(line.key).show(ui, |ui, _| {
self.radio_group(ui, line, options, details, false);
line.show_uncaptioned(ui, |ui| self.radio_group(ui, line, options, details, false));
});
}
@@ -1,8 +1,9 @@
//! `CommandPalette` (24.4): a search over the app's commands, in one centred modal box or in place under a search box.
//! `CommandPalette` (24.4): a search over the app's commands, in one modal box near the window's top or in place under a
//! search box.
use super::words::PanelWords;
use crate::contract::overlay::{Dismiss, Outside, OverlayFit, ViewportShare};
use crate::contract::overlay::{Dismiss, FloatPlace, Outside, OverlayFit, Place, ViewportShare};
use crate::contract::{
Bind, BodyCx, CollectionEvent, LeastWidth, Overlay, Pattern, Politeness, Props, Show as _, ShowCollection as _, ShowContainer as _, Sizing,
announce, clicked,
@@ -140,6 +141,8 @@ impl crate::contract::Outcome for PaletteOutput {
/// `label`, closed and open; the dialog face's field, inside a box named `label`, keeps the generic search name.
/// - Width (dialog face): at least `least_width` ([`LeastWidth::Palette`] by default), so the box keeps its width as
/// the query changes its rows; at most 60% of the window's width, where a row wider than the box shortens its label.
/// - Place (dialog face): centered across the window, with its top 15% of the window's height down, so the field stays
/// put while the query changes the rows; the box grows and shrinks downward, at most 70% of the window's height.
/// - Empty query: with `suggested`, its heading and those commands; else the commands last run, newest first (the
/// `recents` binding), else the first entries.
/// - Fallback: with `fallback`, a last row follows the matches of a query, or stands alone when nothing matches. Picking
@@ -252,7 +255,11 @@ impl<'a> CommandPalette<'a> {
.collection_body()
.least_width(least_width)
.overlay(|_| {
let mut overlay = Overlay::modal().dismiss(Dismiss::new().outside(Outside::Close));
// The box's top stays where a box of its whole capped height would sit centered, so the field holds
// still while the rows under it come and go.
let mut overlay = Overlay::modal()
.dismiss(Dismiss::new().outside(Outside::Close))
.place(Place::Float(FloatPlace::top_centered((1.0 - SHARE.y) / 2.0)));
overlay.fit = OverlayFit::ContentCapped(SHARE);
overlay
})
@@ -93,6 +93,22 @@ fn shift_tab_keeps_the_panels_the_host_names_docked_and_floating_and_tab_hides_t
assert_eq!(shown_under(tab, true), BTreeSet::from([CANVAS]), "Tab keeps the canvas only, whatever the host names");
}
#[trial]
fn the_standard_chrome_hiding_hides_every_dock_panel_and_floating_window_yet_keeps_the_body() {
let room = Rect::from_min_size(Pos2::ZERO, Vec2::new(400.0, 300.0));
let chrome = ShellCx::detached(WindowKey::main(), BodyMode::Normal, room).with_chrome_hidden(true);
assert_eq!(
shown_under(chrome.clone(), true),
BTreeSet::from([CANVAS]),
"the standard Tab hides keeps the protected canvas alone, whatever the host names"
);
assert_eq!(
shown_under(chrome.with_edge_reveal(RevealEdge::Start, true), false),
BTreeSet::from([CANVAS, TOOLBAR]),
"the start edge's reveal shows the start dock alone, as under Tab"
);
}
#[trial]
fn a_revealed_edge_shows_its_dock_alone_under_tab_and_shift_tab() {
let room = Rect::from_min_size(Pos2::ZERO, Vec2::new(400.0, 300.0));
@@ -3,7 +3,7 @@
use craft_behavior::MotionMode;
use craft_ui::buttons::Button;
use craft_ui::contract::{Bind, SaveKey, Show as _, clicked};
use craft_ui::contract::{Bind, Role, SaveKey, Show as _, clicked};
use craft_ui::dialog::DialogHost;
use craft_ui::display::Text;
use craft_ui::patterns::form_dialogs::{
@@ -737,6 +737,46 @@ fn without_unmanaged_profile_there_is_no_dont_color_manage() {
assert!(!shows(&fixture, "Don't Color Manage"));
}
/// Advanced Options starts open under Background Contents; folding it hides Color Profile and Pixel Aspect Ratio and keeps
/// the profile picked under it, and unfolding shows them again.
#[trial]
fn advanced_options_folds_color_profile_and_pixel_aspect_and_keeps_the_profile() {
let mut picked = DocumentOptions::default();
picked.profile = Some("display-p3".to_owned());
let held = Rc::new(RefCell::new(picked));
let shared = held.clone();
let mut fixture = Fixture::new(move |ui| {
let mut options = shared.borrow().clone();
let _ = NewDocumentDialog::new(Bind::bound(&mut options)).profiles(two_mode_profiles()).show(ui);
*shared.borrow_mut() = options;
});
// Without motion the fold finishes at once, rather than mid-animation when the assertions run.
fixture.motion(MotionMode::Off).room(Vec2::new(1400.0, 1000.0)).settle();
let background = fixture.by_label("Background Contents").expect("the Background Contents field").rect;
let tree = fixture.tree();
let advanced =
fixture.by_role(Role::BUTTON).into_iter().find(|button| tree.name_of(button.node) == Some("Advanced Options")).expect("the disclosure");
assert_eq!(tree.expanded_of(advanced.node), Some(true), "Advanced Options starts open");
assert!(background.bottom() <= advanced.rect.top(), "Advanced Options follows Background Contents");
assert!(fixture.by_label("Color Profile").is_some() && fixture.by_label("Pixel Aspect Ratio").is_some(), "open, it shows its fields");
fixture.click(&advanced).settle();
assert_eq!(fixture.tree().expanded_of(advanced.node), Some(false), "a click folds it");
assert!(fixture.by_label("Color Profile").is_none() && fixture.by_label("Pixel Aspect Ratio").is_none(), "folded, its fields are hidden");
assert_eq!(held.borrow().profile.as_deref(), Some("display-p3"), "folding keeps the profile");
// Past the double-click time, so the second click is a click of its own; the header is found again in case the fold
// moved it.
fixture.advance(1.0).frame(Vec::new());
let tree = fixture.tree();
let advanced =
fixture.by_role(Role::BUTTON).into_iter().find(|button| tree.name_of(button.node) == Some("Advanced Options")).expect("the disclosure");
fixture.click(&advanced).settle();
assert_eq!(fixture.tree().expanded_of(advanced.node), Some(true), "a second click unfolds it");
assert!(fixture.by_label("Color Profile").is_some(), "unfolded, Color Profile shows again");
assert!(shows(&fixture, "display-p3"), "with the profile still picked");
}
/// The names of the standard category `id`, in card order.
fn standard_names(id: &str) -> Vec<&'static str> {
let categories = craft_ui::patterns::form_dialogs::PresetCategory::standard();
@@ -558,6 +558,30 @@ fn a_radio_row_in_a_row_stands_its_options_side_by_side_without_a_caption() {
assert_eq!(values.borrow().text("layout"), Some("horizontal"));
}
// In a form whose rows share a label column, the options of a radio row start where the label of a check box row
// starts, past the label column, in each of the row's layouts.
#[trial]
fn a_radio_rows_options_start_in_the_control_column() {
let pages = || ParamKind::radio(vec![("all".into(), "All".into()), ("range".into(), "Range".into())], Some("all".into()));
let layouts = [
("captioned", Param::new("pages", "Pages", pages())),
("stacked", Param::new("pages", "Pages", pages()).stacked_options()),
("in a row", Param::new("pages", "Pages", pages()).options_in_row()),
];
for (layout, radio) in layouts {
let values = Rc::new(RefCell::new(DialogFields::new()));
let params = vec![Param::new("title", "A long caption", ParamKind::text("")), Param::new("keep", "Keep", ParamKind::bool(false)), radio];
let fixture = rows(params, &values);
let left = |text: &str| {
let painted = fixture.texts().iter().find(|painted| painted.text == text).unwrap_or_else(|| panic!("{layout}: the text {text}"));
painted.rect.left()
};
let (caption, check, option) = (left("A long caption"), left("Keep"), left("All"));
assert!(check > caption + 1.0, "{layout}: the check box row starts past the label column: {check} against {caption}");
assert!((option - check).abs() < 0.5, "{layout}: the first option starts where the check box row starts: {option} against {check}");
}
}
// A text row with `field_chars` asks for that many characters instead of the field length: a wide row's field is wider
// than a plain row's, and `0` keeps the field length.
#[trial]
@@ -1427,6 +1451,63 @@ fn a_length_row_reads_with_its_codec() {
assert!(plain.zip(coded).is_some_and(|(plain, coded)| coded > plain), "the codec read the typed text: {plain:?} against {coded:?}");
}
/// A range row with lengths shows its value in the shown unit and keeps the stored one, with a permanent slider and
/// with a popup one; a bare typed number is in the shown unit.
#[trial]
fn a_range_row_shows_a_length_in_the_shown_unit() {
let lengths = craft_ui::runtime::env::LengthUnits::new(UnitKind::Points, UnitKind::Inches, 72.0);
let depth = Param::new("depth", "Depth", ParamKind::range(0.0, 720.0, 72.0, SliderScale::Linear)).length(lengths);
for popup in [false, true] {
let row = if popup { depth.clone().popup_slider() } else { depth.clone() };
let values = Rc::new(RefCell::new(DialogFields::new()));
values.borrow_mut().set("depth", FieldValue::Number(72.0));
let mut fixture = rows(vec![row], &values);
fixture.room(Vec2::new(1280.0, 800.0)).settle();
let texts = fixture.texts();
assert!(texts.iter().any(|run| run.text == "in"), "the shown unit's symbol, popup {popup}");
assert!(!texts.iter().any(|run| run.text == "pt" || run.text.starts_with("72")), "no stored-unit text, popup {popup}");
let tree = fixture.tree();
let field = fixture.by_role(Role::SPIN_BUTTON).into_iter().find(|target| tree.name_of(target.node) == Some("Depth")).expect("the field");
fixture.click(&field).settle();
fixture.key(Key::A, Modifiers::COMMAND).type_text("2").key(Key::Enter, Modifiers::NONE).settle();
let stored = values.borrow().number("depth");
assert!(stored.is_some_and(|points| (points - 144.0).abs() < 1e-6), "2 in is 144 pt, popup {popup}: {stored:?}");
}
// A set step is in the stored unit: Up on a popup row's field moves 72 pt, one inch.
let values = Rc::new(RefCell::new(DialogFields::new()));
values.borrow_mut().set("depth", FieldValue::Number(72.0));
let mut fixture = rows(vec![depth.popup_slider().step(72.0)], &values);
let field = fixture.by_role(Role::SPIN_BUTTON).into_iter().next().expect("the popup row's field");
fixture.click(&field).settle();
fixture.key(Key::ArrowUp, Modifiers::NONE).settle();
let stepped = values.borrow().number("depth");
assert!(stepped.is_some_and(|points| (points - 144.0).abs() < 1e-6), "one step of 72 pt: {stepped:?}");
}
/// A range row with lengths and a set step, with a permanent slider and with a popup one: the step is in the stored
/// unit, so Up on the field moves by it, and a typed value goes to its nearest multiple.
#[trial]
fn a_length_range_row_steps_and_snaps_its_field_by_the_set_step() {
let lengths = craft_ui::runtime::env::LengthUnits::new(UnitKind::Points, UnitKind::Inches, 72.0);
let depth = Param::new("depth", "Depth", ParamKind::range(0.0, 720.0, 144.0, SliderScale::Linear)).length(lengths).step(144.0);
for popup in [false, true] {
let row = if popup { depth.clone().popup_slider() } else { depth.clone() };
let values = Rc::new(RefCell::new(DialogFields::new()));
values.borrow_mut().set("depth", FieldValue::Number(144.0));
let mut fixture = rows(vec![row], &values);
fixture.room(Vec2::new(1280.0, 800.0)).settle();
let tree = fixture.tree();
let field = fixture.by_role(Role::SPIN_BUTTON).into_iter().find(|target| tree.name_of(target.node) == Some("Depth")).expect("the field");
fixture.click(&field).settle();
fixture.key(Key::ArrowUp, Modifiers::NONE).settle();
let stepped = values.borrow().number("depth");
assert!(stepped.is_some_and(|points| (points - 288.0).abs() < 1e-6), "one step of 144 pt, popup {popup}: {stepped:?}");
fixture.key(Key::A, Modifiers::COMMAND).type_text("1.4").key(Key::Enter, Modifiers::NONE).settle();
let typed = values.borrow().number("depth");
assert!(typed.is_some_and(|points| (points - 144.0).abs() < 1e-6), "1.4 in snaps to 2 in, 144 pt, popup {popup}: {typed:?}");
}
}
/// A row marked `beside_previous` stands on the line of the row before it, where an unmarked one stands below.
#[trial]
fn a_row_beside_the_previous_one_shares_its_line() {
@@ -20,13 +20,12 @@ fn row_in(width: f32) -> Fixture {
fn browse_shows_its_whole_label_inside_a_narrow_column() {
for width in [360.0, 260.0, 200.0] {
let fixture = row_in(width);
let shown = fixture.shown();
let label = fixture.texts().iter().find(|run| run.text == "Browse…").cloned();
let label = label
.unwrap_or_else(|| panic!("{width}: Browse… is painted: {:?}", fixture.texts().iter().map(|run| run.text.clone()).collect::<Vec<_>>()));
assert!(!label.elided, "{width}: the Browse label is not cut");
let button = fixture.by_label("Browse…").expect("the Browse button");
assert!(button.rect.right() <= shown.right() + 0.5, "{width}: the button {:?} ends inside the column {shown:?}", button.rect);
assert!(button.rect.right() <= width + 0.5, "{width}: the button {:?} ends inside the column of width {width}", button.rect);
assert!(
label.rect.left() >= button.rect.left() - 0.5 && label.rect.right() <= button.rect.right() + 0.5,
"{width}: the label {:?} lies inside the button {:?}",
@@ -114,3 +114,37 @@ fn the_shown_tab_and_the_values_are_json_fields() {
fixture.click(&preview).idle(4);
assert_eq!(listed(&host, id).get("preview"), Some(&json!(true)), "the check box writes the field the host lists");
}
#[trial]
fn a_measuring_run_keeps_the_hosted_dialogs_tab() {
let host = Rc::new(RefCell::new(DialogHost::new()));
let mut fixture = super::hosted::measured_fixture(&host);
let ctx = fixture.ctx().clone();
let dialog =
HostedPropertiesDialog::new("properties", DialogFields::new(), |values| PropertiesDialog::new("properties", "Properties", tabs(), values));
let id = host.borrow_mut().open(dialog);
assert_eq!(host.borrow_mut().set_json_field(&ctx, id, "tab", json!("paragraph")), Ok(()), "the dialog opens on its second tab");
fixture.frame(Vec::new());
assert_eq!(listed(&host, id).get("tab"), Some(&json!("paragraph")), "the first frame keeps the opening tab");
fixture.idle(4);
assert_eq!(listed(&host, id).get("tab"), Some(&json!("paragraph")), "later frames keep it too");
assert!(fixture.by_label("Indent").is_some(), "the dialog shows the second tab's rows");
}
#[trial]
fn a_closed_dialog_leaves_its_bound_tab_alone() {
let tab = Rc::new(Cell::new(1_usize));
let (held, values) = (Rc::clone(&tab), Rc::new(RefCell::new(DialogFields::new())));
let mut fixture = Fixture::new(move |ui| {
let mut at = held.get();
let mut open = false;
let _ = PropertiesDialog::new("properties", "Properties", tabs(), Bind::bound(&mut *values.borrow_mut()))
.opened(Bind::bound(&mut open))
.tab(Bind::bound(&mut at))
.show(ui);
held.set(at);
});
fixture.room(Vec2::new(900.0, 700.0));
fixture.idle(4);
assert_eq!(tab.get(), 1, "a dialog that shows no body writes no tab");
}
@@ -3,6 +3,7 @@
//! remembers what it ran.
use craft_ui::buttons::Button;
use craft_ui::contract::overlay::layer_room;
use craft_ui::contract::{Bind, CommandSet, LeastWidth, Overlay, Role, Show as _, ShowContainer as _, clicked};
use craft_ui::menu::search::{HelpEntry, SearchIndex, SearchWords, Synonyms};
use craft_ui::patterns::panels::{CommandPalette, PaletteFace, PaletteState};
@@ -825,3 +826,35 @@ fn the_dialog_face_keeps_a_readable_width_while_the_query_changes_its_rows() {
let kept = width(&wide.fixture);
assert!(kept <= window * 0.6 + 0.5, "a least width wider than the share gives way to it: {kept} in {window}");
}
/// The dialog face's top edge and its field hold still while a query changes how many rows it lists: the box is
/// centered across the window with its top 15% of the window's height down, and only its bottom edge moves. Guards
/// against a box centered on both axes, whose field jumped up and down with each query.
#[trial]
fn the_dialog_face_keeps_its_top_and_field_in_place_while_the_query_changes_its_rows() {
let entries = ["Cut", "Copy", "Paste", "Paste Inside", "Delete", "Duplicate", "Group", "Ungroup", "Lock", "Unlock", "Hide", "Show"]
.iter()
.map(|label| entry(&label.to_lowercase().replace(' ', ""), label))
.collect();
let (mut fixture, _open, _picked) = palette(entries, false);
fixture.room(Vec2::new(1400.0, 900.0)).settle();
let placed = |fixture: &Fixture| {
let frame = fixture.by_role(Role::DIALOG).first().expect("the palette's box shows").rect;
let field = fixture.by_role(Role::TEXT_INPUT).first().expect("the search field shows").rect;
(frame, field)
};
let (opened, opened_field) = placed(&fixture);
let window = layer_room(fixture.ctx());
assert!((opened.center().x - window.center().x).abs() <= 1.0, "the box is centered across the window: {opened:?} in {window:?}");
assert!(
(opened.top() - (window.top() + window.height() * 0.15)).abs() <= 1.0,
"the box's top is 15% of the window's height down: {opened:?} in {window:?}"
);
fixture.type_text("cut").settle();
assert_eq!(names(&fixture).len(), 1, "the query lists one row: {:?}", names(&fixture));
let (typed, typed_field) = placed(&fixture);
assert!(typed.height() < opened.height() - 1.0, "one row makes a shorter box: {typed:?} against {opened:?}");
assert!((typed.top() - opened.top()).abs() <= 0.5, "the box's top stays put: {typed:?} against {opened:?}");
assert!((typed_field.top() - opened_field.top()).abs() <= 0.5, "the field stays put: {typed_field:?} against {opened_field:?}");
}
@@ -0,0 +1,117 @@
//! A row's help line in the preferences window shows every line it wraps to. The rows above the first side-labelled
//! row read no label column while the window measures them, then start in the control column: their help lines wrap
//! there, under a check box with its label after it and under a control beside a label narrower than the widest.
use craft_ui::contract::Bind;
use craft_ui::patterns::preferences::{
GroupSpec, PageSpec, PrefValue, PreferencesDraft, PreferencesModel, PreferencesState, PreferencesWindow, RowKind, RowSpec,
};
use craft_ui::testing::{Fixture, trial};
use egui::{Rect, Ui, vec2};
/// Half a pixel at the scales the box runs.
const ROUNDING: f32 = 0.5;
const HELPS: [&str; 7] = [
"On the desktop, a save to a file is written in the background while you keep editing; off, you wait until it is written.",
"On the desktop, exports to files and packages are written in the background while you keep editing, except 3D exports; off, you wait for them.",
"Every few minutes, keeps a recovery copy of each document with unsaved changes made since its last copy; off, no timed copies are made.",
"On the desktop, the folder recovery copies are kept in; leave it blank for the app's own folder. The web version keeps them in the browser.",
"Open Recent Files and the Home screen list at most this many recent files; 0 lists none, and the app still remembers up to 30.",
"When a document opens, a linked EPS image that shows its saved preview keeps it instead of reading the EPS file again; changed files still follow Update Links.",
"In Pixel Preview, images are drawn smoothed; off, their pixels show with hard edges. Outside Pixel Preview, images are always smoothed.",
];
struct Model;
impl PreferencesModel for Model {
fn pages(&self) -> Vec<PageSpec<'_>> {
let mut page = PageSpec::new("files", "File Handling", Vec::new());
page.groups = vec![
GroupSpec::new(
Some("File Handling"),
vec![
RowSpec::new("save", "Enable Background Save", RowKind::Bool(true)).help(HELPS[0]),
RowSpec::new("export", "Enable Background Export", RowKind::Bool(true)).help(HELPS[1]),
],
),
GroupSpec::new(
Some("Data Recovery"),
vec![
RowSpec::new("recovery", "Automatically Save Recovery Data", RowKind::Bool(true)).help(HELPS[2]),
RowSpec::new("folder", "Folder", RowKind::Text("")).help(HELPS[3]),
RowSpec::new("recent", "Number of Recent Files to Display", RowKind::Text("20")).help(HELPS[4]),
RowSpec::new("proxy", "Use Low Resolution Proxy for Linked EPS", RowKind::Bool(false)).help(HELPS[5]),
RowSpec::new("bitmaps", "Display Bitmaps as Anti-aliased Images in Pixel Preview", RowKind::Bool(false)).help(HELPS[6]),
],
),
];
vec![PageSpec::new("general", "General", vec![RowSpec::new("general.snap", "Snap to grid", RowKind::Bool(false))]), page]
}
fn set(&mut self, _: &str, _: PrefValue) {}
fn custom_row(&mut self, _: &mut Ui, _: &str) -> bool {
false
}
fn custom_page(&mut self, _: &mut Ui, _: &str) -> bool {
false
}
fn reset_page(&mut self, _: &str) {}
}
impl PreferencesDraft for Model {
fn differs(&self) -> bool {
false
}
fn apply(&mut self) -> Result<(), String> {
Ok(())
}
fn cancel(&mut self) {}
}
/// A help line the window painted with part of it outside the clip it paints under.
#[derive(Debug)]
#[allow(dead_code, reason = "read through the failure message")]
struct Cut {
help: String,
rows: usize,
rect: Rect,
clip: Rect,
}
/// The File Handling page in a window `width` wide at `ppp` pixels per point: every help line it painted, and the ones
/// cut off.
fn painted(ppp: f32, width: f32) -> (usize, Vec<Cut>) {
let mut state = PreferencesState::default();
state.selected = "files".to_owned();
let mut fixture = Fixture::new(move |ui| {
let _ = PreferencesWindow::new(Bind::bound(&mut state)).size(vec2(width, 760.0)).show(ui, &mut Model);
});
fixture.pixels_per_point(ppp).room(vec2(1200.0, 900.0)).settle();
let mut seen = 0;
let mut cut = Vec::new();
for (clip, shape) in fixture.frame_clipped_shapes() {
let egui::Shape::Text(text) = shape else { continue };
if !HELPS.contains(&text.galley.text()) {
continue;
}
seen += 1;
let rect = text.galley.rect.translate(text.pos.to_vec2());
if rect.max.y > clip.max.y + ROUNDING || rect.max.x > clip.max.x + ROUNDING {
cut.push(Cut { help: text.galley.text().to_owned(), rows: text.galley.rows.len(), rect, clip });
}
}
(seen, cut)
}
/// At 900 and 960 points the second and third help lines wrap to two lines in the control column and fit on one at
/// the width the rows had before the column was known.
#[trial]
fn every_line_of_a_rows_help_shows() {
for ppp in [1.0, 2.0] {
for width in [900.0, 960.0, 1036.0] {
let (seen, cut) = painted(ppp, width);
assert_eq!(seen, HELPS.len(), "every help line painted at {width} points, {ppp} pixels per point");
assert!(cut.is_empty(), "help lines cut off at {width} points, {ppp} pixels per point: {cut:#?}");
}
}
}
@@ -2,6 +2,7 @@
//! window's answers and the hex codec.
pub(crate) mod classic;
pub(crate) mod help;
pub(crate) mod live;
pub(crate) mod model;
pub(crate) mod nested;
+40 -12
View File
@@ -337,6 +337,9 @@ struct Placed<'a, S> {
title: bool,
/// The options bar: it follows the place, and it is the options bar's height at every edge.
options: bool,
/// An editor bar or rail: the user's Tab in standard screen mode hides it, while the title and the status bar
/// stay.
bars: bool,
/// The slot's name in the shell's words, for a slot of the canvas preset.
named: Option<fn(&ShellWords) -> Label>,
version: VersionFn<'a, S>,
@@ -481,6 +484,8 @@ pub struct AppShellOutput {
pub struct ChromeState {
/// The user hid every panel, tool and bar.
pub hidden: bool,
/// In standard screen mode the user hid the editor's bars and rails with Tab; the title and status slots stay.
pub chrome_hidden: bool,
/// The panels are hidden while the tools and bars stay.
pub panels_hidden: bool,
/// The edge whose slots a reveal shows, when one is on.
@@ -500,7 +505,12 @@ pub fn chrome_state(ctx: &Context, viewport: ViewportId) -> ChromeState {
impl ChromeState {
/// What `reveal` says: the one source of a pass's output and of [`chrome_state`].
fn of(reveal: &Reveal) -> Self {
ChromeState { hidden: reveal.hidden(), panels_hidden: reveal.panels_hidden(), revealed: reveal.revealed_edge() }
ChromeState {
hidden: reveal.hidden(),
chrome_hidden: reveal.chrome_hidden(),
panels_hidden: reveal.panels_hidden(),
revealed: reveal.revealed_edge(),
}
}
}
@@ -529,7 +539,9 @@ impl Outcome for AppShellOutput {
/// Tab; the pointer at the top, start or end edge shows that edge's slots, unless a button is held or a popup is
/// open or `edge_reveal` is off. Revealed slots cover the body and leave its rect as it is. A screen-mode change ends
/// a reveal. The shell takes its own window's Tab toggles from the frame state in the pass that records them: in
/// normal mode Tab hides every slot and panel and shows them again.
/// standard screen mode Tab hides the editor's bars and rails (the [`options_bar`](Self::options_bar) and the slots
/// put by [`top`](Self::top), [`bottom`](Self::bottom), [`start`](Self::start) and [`end`](Self::end)) and shows them
/// again, while the title and status slots stay shown; in the other normal-mode screen it hides every slot and panel.
/// - **Canvas preset.** [`title_bar_if`](Self::title_bar_if), [`options_bar`](Self::options_bar),
/// and [`status`](Self::status) add the slots of a document editor under the keys of [`slots`](super::slots),
/// named by `ShellWords`; the toolbar is a panel of the dock, not a slot; each takes the host's `visible` flag, passed every frame.
@@ -659,8 +671,16 @@ impl<'a, S> AppShell<'a, S> {
/// The title slot with a slot of your own, for a title that follows the host's menu bar flag.
pub fn title(mut self, slot: Slot, version: impl Fn(&S) -> Option<u64> + 'a, add: impl FnMut(&mut Ui, &mut BodyCx<'_>, &mut S) + 'a) -> Self {
self.title =
Some(Placed { slot, edge: PaneEdge::Top, title: true, options: false, named: None, version: Box::new(version), add: Box::new(add) });
self.title = Some(Placed {
slot,
edge: PaneEdge::Top,
title: true,
options: false,
bars: false,
named: None,
version: Box::new(version),
add: Box::new(add),
});
self
}
@@ -675,7 +695,8 @@ impl<'a, S> AppShell<'a, S> {
self.title(Slot::new(keys::TITLE).visible(visible).reveal_if(visible), version, add)
}
/// The options bar, a top slot keyed `"options"` that reveals in body-only mode.
/// The options bar, a top slot keyed `"options"` that reveals in body-only mode and hides when the user hides the
/// editor's chrome in standard screen mode.
pub fn options_bar(
mut self,
visible: bool,
@@ -688,6 +709,7 @@ impl<'a, S> AppShell<'a, S> {
edge: PaneEdge::Top,
title: false,
options: true,
bars: true,
named: Some(|words| words.options.clone()),
version: Box::new(version),
add: Box::new(add),
@@ -695,7 +717,8 @@ impl<'a, S> AppShell<'a, S> {
self
}
/// The status bar, a bottom slot keyed `"status"` that never reveals.
/// The status bar, a bottom slot keyed `"status"` that never reveals and stays shown while the user hides the
/// editor's chrome in standard screen mode.
pub fn status(mut self, visible: bool, version: impl Fn(&S) -> Option<u64> + 'a, add: impl FnMut(&mut Ui, &mut BodyCx<'_>, &mut S) + 'a) -> Self {
let slot = Slot::new(keys::STATUS).visible(visible);
self.slots.push(Placed {
@@ -703,6 +726,7 @@ impl<'a, S> AppShell<'a, S> {
edge: PaneEdge::Bottom,
title: false,
options: false,
bars: false,
named: Some(|words| words.status.clone()),
version: Box::new(version),
add: Box::new(add),
@@ -759,7 +783,7 @@ impl<'a, S> AppShell<'a, S> {
version: impl Fn(&S) -> Option<u64> + 'a,
add: impl FnMut(&mut Ui, &mut BodyCx<'_>, &mut S) + 'a,
) -> Self {
self.slots.push(Placed { slot, edge, title: false, options: false, named: None, version: Box::new(version), add: Box::new(add) });
self.slots.push(Placed { slot, edge, title: false, options: false, bars: true, named: None, version: Box::new(version), add: Box::new(add) });
self
}
@@ -853,14 +877,17 @@ impl<'a, S> AppShell<'a, S> {
let covers_title = paged && page_kind != PageKind::BelowTitle;
let toggles = take_chrome_toggles(&ctx, viewport, &window);
if !paged {
kept.reveal.apply(&toggles, host_only, allow_reveal);
kept.reveal.apply(&toggles, host_only, allow_reveal, mode == ScreenMode::Standard);
}
let only = kept.reveal.only(host_only);
// In standard screen mode the user's Tab hides the editor's bars and rails; those slots hide and reveal
// like they do in body-only mode, while the title and status slots and the body's own parts stay.
let bars = kept.reveal.chrome_hidden();
let pointer = pointer::frame(&ctx);
let frozen = !pointer.buttons.is_empty() || any_open(&ctx, OpenFilter::Keys);
let rtl = cx.env.direction().is_rtl();
if !paged {
kept.reveal.track(Tracking::new(only, allow_reveal, edge_reveal), Aim::new(pointer.pos, frozen, cx.rect, rtl));
kept.reveal.track(Tracking::new(only || bars, allow_reveal, edge_reveal), Aim::new(pointer.pos, frozen, cx.rect, rtl));
}
// Every shown slot's rect and the body's, before any slot runs. Slots that a reveal shows in body-only mode
@@ -872,7 +899,7 @@ impl<'a, S> AppShell<'a, S> {
!bare
&& !covers_title
&& (!paged || placed.title)
&& kept.reveal.shows(&placed.slot, placed.edge, only, allow_reveal, mode, is_dropped)
&& kept.reveal.shows(&placed.slot, placed.edge, only || (bars && placed.bars), allow_reveal, mode, is_dropped)
})
.collect();
let claims: Vec<Claim> = slots
@@ -884,7 +911,7 @@ impl<'a, S> AppShell<'a, S> {
key: placed.slot.key(),
edge: placed.edge,
extent: placed.extent(&tokens, &kept.measured),
overlay: !paged && covers(&placed.slot, only),
overlay: !paged && covers(&placed.slot, only || (bars && placed.bars)),
})
.collect();
let regions = layout(cx.rect, &claims, rtl);
@@ -927,6 +954,7 @@ impl<'a, S> AppShell<'a, S> {
.with_tabs(tabs)
.with_tab_reveal(kept.reveal.tab())
.with_panels_hidden(chrome.panels_hidden)
.with_chrome_hidden(chrome.chrome_hidden)
.with_reveals_key(sub(cx.id, "reveals"));
// The room an embedded shell shows: its rect less what a scroll or a parent clips. Its dialogs are contained in
// it.
@@ -989,7 +1017,7 @@ impl<'a, S> AppShell<'a, S> {
for (placed, shown) in slots.iter_mut().zip(&visible) {
let floats = floating && placed.options;
// A floating bar is a layer over the body: it shows with the covering slots in every mode.
if !*shown || if floats { !covering } else { (!paged && covers(&placed.slot, only)) != covering } {
if !*shown || if floats { !covering } else { (!paged && covers(&placed.slot, only || (bars && placed.bars))) != covering } {
continue;
}
let by_content = placed.sized_by_content();
+24 -7
View File
@@ -13,12 +13,15 @@ pub(crate) const EDGE_REVEAL_STRIP: f32 = 8.0;
///
/// - `hidden`: the user hid every panel, tool and bar in normal mode (Tab); the window then behaves as in body-only
/// mode, and Tab shows them again.
/// - `chrome`: in standard screen mode the user hid the editor's chrome (Tab): the bars and rails built to hide with it
/// go, the title and status slots stay, and Tab shows them again. The window does not become body-only.
/// - `panels_hidden`: the panels are hidden and the tools and bars stay (Shift+Tab).
/// - `tab`: in body-only mode, Tab shows the slots built to reveal until the next Tab.
/// - `edges`: in body-only mode the pointer at the top, start or end edge shows the slots of that edge.
#[derive(Clone, Debug, Default, PartialEq)]
pub(crate) struct Reveal {
hidden: bool,
chrome: bool,
panels_hidden: bool,
tab: bool,
edges: [bool; 3],
@@ -78,14 +81,15 @@ const EDGES: [RevealEdge; 3] = [RevealEdge::Top, RevealEdge::Start, RevealEdge::
impl Reveal {
/// Applies the toggles the window's shell took from the frame state in this pass. `host_only` says the screen mode
/// shows the body only; `allow_reveal` is off for a presentation.
pub(crate) fn apply(&mut self, toggles: &[ChromeToggle], host_only: bool, allow_reveal: bool) {
/// shows the body only; `allow_reveal` is off for a presentation; `standard` says the screen mode is Standard,
/// where Tab hides the editor's chrome bars and rails while the window keeps its title and status slots.
pub(crate) fn apply(&mut self, toggles: &[ChromeToggle], host_only: bool, allow_reveal: bool, standard: bool) {
for toggle in toggles {
self.toggle(*toggle, host_only, allow_reveal);
self.toggle(*toggle, host_only, allow_reveal, standard);
}
}
fn toggle(&mut self, toggle: ChromeToggle, host_only: bool, allow_reveal: bool) {
fn toggle(&mut self, toggle: ChromeToggle, host_only: bool, allow_reveal: bool, standard: bool) {
match toggle {
ChromeToggle::Panels if host_only => {
if allow_reveal {
@@ -96,20 +100,26 @@ impl Reveal {
}
}
}
ChromeToggle::Panels if standard => {
self.chrome = !(self.chrome || self.panels_hidden);
self.panels_hidden = false;
self.end_reveal();
}
ChromeToggle::Panels => {
self.hidden = !(self.hidden || self.panels_hidden);
self.panels_hidden = false;
self.end_reveal();
}
ChromeToggle::PanelsKeepTools if !host_only && !self.hidden => self.panels_hidden = !self.panels_hidden,
ChromeToggle::PanelsKeepTools if !host_only && !(self.hidden || self.chrome) => self.panels_hidden = !self.panels_hidden,
ChromeToggle::ShowPanels => {
if self.hidden || self.panels_hidden {
if self.hidden || self.chrome || self.panels_hidden {
self.hidden = false;
self.chrome = false;
self.panels_hidden = false;
self.end_reveal();
}
}
ChromeToggle::Reveal(Some(edge)) if allow_reveal && !self.tab && (self.only(host_only) || self.panels_hidden()) => {
ChromeToggle::Reveal(Some(edge)) if allow_reveal && !self.tab && (self.only(host_only) || self.chrome || self.panels_hidden()) => {
self.edges = [false; 3];
self.edges[at(edge)] = true;
self.pinned = Some((edge, None));
@@ -125,6 +135,7 @@ impl Reveal {
/// Ends the Tab and edge reveal and the user's hiding: every screen-mode change does.
pub(crate) fn clear(&mut self) {
self.hidden = false;
self.chrome = false;
self.panels_hidden = false;
self.end_reveal();
}
@@ -155,6 +166,12 @@ impl Reveal {
self.hidden
}
/// Whether the user hid the editor's chrome bars and rails with Tab in standard screen mode; the window's title
/// and status slots, and everything of the body that is not a bar, stay.
pub(crate) fn chrome_hidden(&self) -> bool {
self.chrome
}
/// The edge whose reveal is on, when one is.
pub(crate) fn revealed_edge(&self) -> Option<RevealEdge> {
EDGES.into_iter().find(|edge| self.edges[at(*edge)])
+121 -1
View File
@@ -198,7 +198,7 @@ fn chrome_state_reads_the_hiding_the_shell_left_and_show_panels_ends_it() {
assert!(!seen.panels_hidden);
let seen = tabbed(&mut windows, &mut mode);
assert_eq!(state(&windows), (true, false, None), "Tab hid the chrome");
assert_eq!(state(&windows), (false, false, None), "Tab hid the chrome in standard mode: the window's own hiding, not the body-only one");
assert!(!seen.panels_hidden && !seen.revealed);
tabbed(&mut windows, &mut mode);
assert_eq!(state(&windows), (false, false, None), "Tab showed it");
@@ -229,3 +229,123 @@ fn chrome_state_reads_the_hiding_the_shell_left_and_show_panels_ends_it() {
"a viewport with no shell reads the default"
);
}
/// What one pass of a full document window's shell showed: the slots it laid out, whether the shell put the
/// window into its body-only hiding, and whether the body saw the chrome hiding.
struct WindowSeen {
slots: Vec<&'static str>,
hidden: bool,
bars: bool,
body_sees_bars: bool,
}
/// One frame of a document window's shell: a title bar under the host's menu-bar flag, an options bar, a status
/// bar and a tool rail, with a document canvas in the body and nothing focused, so Tab reaches the shell.
fn window_pass(windows: &mut Frames, mode: &mut ScreenMode, events: Vec<Event>) -> WindowSeen {
let ctx = windows.ctx.clone();
let mut seen = WindowSeen { slots: Vec::new(), hidden: false, bars: false, body_sees_bars: false };
windows.frame(events, |ui| {
let mut body_sees_bars = false;
let out = AppShell::new(WindowKey::main())
.screen_mode(Bind::bound(&mut *mode))
.title_bar_if(
true,
|_| Some(0),
|ui, _, _: &mut ()| {
Text::new("Title").show(ui);
},
)
.options_bar(
true,
|_| Some(0),
|ui, _, _: &mut ()| {
Text::new("Options").show(ui);
},
)
.status(
true,
|_| Some(0),
|ui, _, _: &mut ()| {
Text::new("Status").show(ui);
},
)
.start(
Slot::new("tools").reveal(),
|_| Some(0),
|ui, _, _: &mut ()| {
Text::new("Tools").show(ui);
},
)
.body(|ui, cx, _| {
body_sees_bars = cx.shell().is_some_and(|shell| shell.chrome_hidden());
let canvas = ui.scope_id().with("document");
ui.interact(ui.max_rect(), canvas, Sense::click());
host_canvas(ui.ctx(), canvas, KeyUse::CANVAS);
})
.show(ui, &mut ());
let state = chrome_state(&ctx, ViewportId::ROOT);
seen = WindowSeen {
slots: out.regions.slots.iter().map(|(key, _)| *key).collect(),
hidden: state.hidden,
bars: state.chrome_hidden,
body_sees_bars,
};
});
seen
}
fn window_settled(windows: &mut Frames, mode: &mut ScreenMode) -> WindowSeen {
(0..3).map(|_| window_pass(windows, mode, vec![])).last().expect("three passes")
}
fn window_tabbed(windows: &mut Frames, mode: &mut ScreenMode) -> WindowSeen {
let key = |pressed| Event::Key { key: Key::Tab, physical_key: None, pressed, repeat: false, modifiers: Modifiers::NONE };
window_pass(windows, mode, vec![key(true)]);
window_pass(windows, mode, vec![key(false)]);
window_settled(windows, mode)
}
#[trial]
fn tab_in_standard_hides_the_options_bar_and_rail_and_keeps_the_title_and_status() {
let mut windows = window();
let mut mode = ScreenMode::Standard;
let settled = window_settled(&mut windows, &mut mode);
assert_eq!(settled.slots, ["title", "options", "status", "tools"], "the document window shows its bars and its rail");
assert!(!settled.bars && !settled.body_sees_bars, "nothing is hidden");
let seen = window_tabbed(&mut windows, &mut mode);
assert_eq!(seen.slots, ["title", "status"], "Tab hides the options bar and the rail and keeps the title bar and the status bar");
assert!(!seen.hidden, "the window does not become body-only: its own chrome stays");
assert!(seen.bars && seen.body_sees_bars, "the pass and its body read the chrome hiding, so a body with panels hides them too");
let seen = window_tabbed(&mut windows, &mut mode);
assert_eq!(seen.slots, ["title", "options", "status", "tools"], "Tab again shows what it hid");
assert!(!seen.hidden && !seen.bars && !seen.body_sees_bars, "and the window is a normal window again");
window_tabbed(&mut windows, &mut mode);
command(&windows, ChromeToggle::Reveal(Some(RevealEdge::Top)));
assert_eq!(
window_settled(&mut windows, &mut mode).slots,
["title", "options", "status"],
"an edge reveal shows the hidden bar over the body, as it does today"
);
command(&windows, ChromeToggle::Reveal(None));
window_settled(&mut windows, &mut mode);
command(&windows, ChromeToggle::PanelsKeepTools);
let seen = window_settled(&mut windows, &mut mode);
assert_eq!(seen.slots, ["title", "status"], "Shift+Tab refuses while the bars are hidden, as it does while the window is body-only");
assert!(seen.bars && !seen.hidden, "and stays in the chrome hiding, not the window's own one");
command(&windows, ChromeToggle::ShowPanels);
let seen = window_settled(&mut windows, &mut mode);
assert_eq!(seen.slots, ["title", "options", "status", "tools"], "ShowPanels ends the chrome hiding too");
assert!(!seen.bars && !seen.hidden, "and no hiding is left");
}
#[trial]
fn tab_in_full_screen_with_menu_bar_hides_every_slot_as_before() {
let mut windows = window();
let mut mode = ScreenMode::FullScreenWithMenuBar;
assert_eq!(window_settled(&mut windows, &mut mode).slots, ["title", "options", "status", "tools"], "the mode keeps the bars and the rail");
let seen = window_tabbed(&mut windows, &mut mode);
assert!(seen.slots.is_empty(), "Tab there hides every slot, the title bar included, as it does today");
assert!(seen.hidden, "the window behaves as body-only");
let seen = window_tabbed(&mut windows, &mut mode);
assert_eq!(seen.slots, ["title", "options", "status", "tools"], "Tab again shows them");
}
+3 -1
View File
@@ -637,7 +637,9 @@ fn a_fitted_bar_keeps_its_controls_an_item_gap_apart() {
};
let _ = TitleBar::new().frame(frame).show_fitted(ui, leading, trailing);
});
fixture.room(vec2(1000.0, 80.0)).settle();
// The app draws the window's frame, so the menu bar lives in the window on every OS. Without this a Mac host puts
// it at the top of the screen and the File title never shows in the window.
fixture.chrome(craft_host::target::WindowChrome::Integrated).room(vec2(1000.0, 80.0)).settle();
let item = item.get();
assert!(item > 0.0, "the theme has an item gap");
let rect = |label: &str| fixture.by_label(label).unwrap_or_else(|| panic!("{label} is shown")).rect;
+47 -3
View File
@@ -38,6 +38,10 @@ thread_local! {
/// The window facts of each child opened from another child (a popup window): it opens where its builder puts it
/// and follows its own commands.
static OWN_INFO: RefCell<Vec<(ViewportId, ViewportInfo)>> = const { RefCell::new(Vec::new()) };
/// The child [`Windows::focus`] focused, whose window alone of the children reports focus; `None` until it is called.
static FOCUSED: Cell<Option<ViewportId>> = const { Cell::new(None) };
/// The children whose next pass reports a close request, as the window system sends one once.
static CLOSES: RefCell<Vec<ViewportId>> = const { RefCell::new(Vec::new()) };
/// The window facts the root reports.
static ROOT_INFO: RefCell<ViewportInfo> = RefCell::new(ViewportInfo::default());
/// The children whose windows are open: those that ran a pass and are still shown. Like an integration, every pass's
@@ -85,6 +89,15 @@ const FRAME_SECONDS: f64 = 1.0 / 60.0;
/// Runs `f` on the facts `id` reports: its own for a child opened from another child, else the ones every child
/// opened from the root shares.
/// The window facts the child `id` reports: its own or the shared ones, with the focus [`Windows::focus`] gave.
fn facts_of(id: ViewportId) -> ViewportInfo {
let mut info = with_facts(id, |info| info.clone());
if let Some(focused) = FOCUSED.with(Cell::get) {
info.focused = Some(focused == id);
}
info
}
fn with_facts<R>(id: ViewportId, f: impl FnOnce(&mut ViewportInfo) -> R) -> R {
let own = OWN_INFO.with(|own| {
let mut own = own.borrow_mut();
@@ -221,8 +234,12 @@ fn render_child(ctx: &Context, viewport: egui::ImmediateViewport<'_>) {
events.insert(0, egui::Event::ModifiersChanged(CHILD_MODIFIERS.with(Cell::get)));
let (hovered_files, dropped) = CHILD_FILES.with(|files| std::mem::take(&mut *files.borrow_mut()));
let dropped_files = dropped.into_iter().map(|name| Arc::new(DroppedPath(name.into())) as egui::DroppedFileHandle).collect();
let mut info = with_facts(viewport.ids.this, |info| info.clone());
let mut info = facts_of(this);
info.parent = Some(viewport.ids.parent);
if CLOSES.with(|closes| closes.borrow().contains(&this)) {
CLOSES.with(|closes| closes.borrow_mut().retain(|held| *held != this));
info.events.push(egui::ViewportEvent::Close);
}
let mut input = RawInput {
viewport_id: viewport.ids.this,
events,
@@ -260,6 +277,7 @@ fn keep_tree(output: &mut FullOutput, viewport: ViewportId) {
fn flatten(shape: &egui::Shape, into: &mut Vec<egui::Shape>) {
match shape {
egui::Shape::Vec(shapes) => shapes.iter().for_each(|shape| flatten(shape, into)),
egui::Shape::PaintChunk(shapes) => shapes.iter().for_each(|clipped| flatten(&clipped.shape, into)),
shape => into.push(shape.clone()),
}
}
@@ -353,6 +371,8 @@ impl Windows {
CHILD_INFO.with(|info| *info.borrow_mut() = ViewportInfo::default());
OWN_INFO.with(|own| own.borrow_mut().clear());
CHILDREN.with(|children| children.borrow_mut().clear());
FOCUSED.with(|focused| focused.set(None));
CLOSES.with(|closes| closes.borrow_mut().clear());
COMMANDS.with(|kept| kept.borrow_mut().clear());
BUILDERS.with(|kept| kept.borrow_mut().clear());
TEXTURES.with(|textures| textures.borrow_mut().clear());
@@ -373,9 +393,33 @@ impl Windows {
}
/// The window facts `viewport` reports: its own for a child opened from another child, else those
/// [`child_info`](Self::child_info) gave.
/// [`child_info`](Self::child_info) gave, with the focus [`focus`](Self::focus) gave.
pub fn facts(&self, viewport: ViewportId) -> ViewportInfo {
with_facts(viewport, |info| info.clone())
facts_of(viewport)
}
/// Focuses the child `viewport`'s window and unfocuses every other child's, overriding the focus in
/// [`child_info`](Self::child_info): from the next frame on their facts say so, and each open window whose focus
/// changed gets `Event::WindowFocused`.
pub fn focus(&self, viewport: ViewportId) {
let mut open = CHILDREN.with(|children| children.borrow().clone());
if !open.contains(&viewport) {
open.push(viewport);
}
let before: Vec<_> = open.iter().map(|&id| facts_of(id).focused).collect();
FOCUSED.with(|focused| focused.set(Some(viewport)));
for (id, was) in open.into_iter().zip(before) {
let now = id == viewport;
if was != Some(now) {
self.send(id, vec![Event::WindowFocused(now)]);
}
}
}
/// Has the window system ask the child `viewport` to close: its next pass reports one close request, and no other
/// child's does.
pub fn close(&self, viewport: ViewportId) {
CLOSES.with(|closes| closes.borrow_mut().push(viewport));
}
/// The modifiers held in the child's window, which its passes report from now on.
+41
View File
@@ -0,0 +1,41 @@
//! The kit's window driver gives focus and close requests to one child of several.
use craft_ui_test_kit::windows::Windows;
use egui::{ViewportBuilder, ViewportId, ViewportInfo};
use std::cell::RefCell;
use std::collections::BTreeMap;
/// What each of three children saw in a frame: (close requested, focused).
fn run(kit: &Windows) -> BTreeMap<&'static str, (bool, bool)> {
let seen = RefCell::new(BTreeMap::new());
kit.frame(Vec::new(), Vec::new(), |ui| {
for name in ["a", "b", "c"] {
ui.ctx().show_viewport_immediate(ViewportId::from_hash_of(name), ViewportBuilder::default(), |ui, _| {
let (close, focused) = ui.ctx().input(|i| (i.viewport().close_requested(), i.viewport().focused == Some(true)));
seen.borrow_mut().insert(name, (close, focused));
});
}
});
seen.into_inner()
}
#[test]
fn one_of_three_children_gets_the_close_and_the_focus() {
let kit = Windows::new();
let (a, b, c) = (ViewportId::from_hash_of("a"), ViewportId::from_hash_of("b"), ViewportId::from_hash_of("c"));
run(&kit);
kit.focus(b);
kit.close(b);
let seen = run(&kit);
assert!(seen["b"].0 && !seen["a"].0 && !seen["c"].0, "only b is asked to close");
assert!(seen["b"].1 && !seen["a"].1 && !seen["c"].1, "only b is focused");
assert!(!run(&kit)["b"].0, "a close request comes once");
kit.focus(c);
let seen = run(&kit);
assert!(seen["c"].1 && !seen["b"].1 && !seen["a"].1);
assert_eq!(kit.facts(a).focused, Some(false));
let scale = kit.facts(a).native_pixels_per_point;
kit.child_info(ViewportInfo { native_pixels_per_point: Some(3.0), ..ViewportInfo::default() });
assert_ne!(kit.facts(a).native_pixels_per_point, scale, "the shared facts still reach a child after a focus");
assert_eq!(kit.facts(c).focused, Some(true), "and the focus outlasts them");
}
+3 -1
View File
@@ -212,7 +212,9 @@ impl<'a> Bar<'a> {
}
/// Lays out the members as a row that wraps instead of scrolling under an overlay bar: no horizontal scroll, no row
/// cap; a member wider than the bar narrows and elides by the shared rules.
/// cap. A row too long for the bar first narrows its selects and elidable text to fit one line, the last first, and
/// continues on a new line only when they do not fit it even at their least; a member wider than the bar narrows
/// and elides by the shared rules.
#[must_use]
pub fn wrap(mut self) -> Self {
self.props.layout = self.props.layout.clone().wrap(true);
+55 -14
View File
@@ -7,7 +7,7 @@ use crate::contract::{
Bind, BindCheck, BindMut, Common, Component, Cx, Edit as _, EditResponse, FieldLayout, Focus as _, MeasureCx, Outcome, PaintUi, Props as _, Role,
SideLabel, Sizing, Validity, WordSetCx as _,
};
use crate::runtime::env::{Label, UnitKind};
use crate::runtime::env::{EnvView, Label, LengthUnits, UnitKind};
use crate::runtime::keys::{ScalarKeyPolicy, ScalarRow, register_scalar};
use crate::style::{ComponentStyle, StyleCx};
use crate::text::{NumberField, RangeAlert};
@@ -129,6 +129,15 @@ pub struct SliderField<'a> {
/// What the number counts: the field shows its unit and reads its spellings.
#[prop]
unit_kind: Option<UnitKind>,
/// The lengths the value is kept and shown in ([`NumberField::length`]): the binding, the range, the slider and its
/// step stay in `lengths.stored`, and the number field shows and reads the value in `lengths.shown`, at that unit's
/// own decimals. A set `step` is in `lengths.stored`: the field steps by it converted to `lengths.shown` and snaps
/// typed values to it unless `typed_decimals` is set; without a `step` the field keeps the shown unit's own step.
/// `typed_decimals`, `field_decimals` and `unit_kind` then apply to the slider only. A `number_codec` reads and
/// writes the field's text in `lengths.shown`, and `scrub_step` is a rate in `lengths.shown`. A `key_policy`
/// amount is in `lengths.stored`.
#[prop]
lengths: Option<LengthUnits>,
/// A unit shown after the number, for a quantity with no `UnitKind` (a font axis).
#[prop(into)]
unit: Option<Label>,
@@ -212,6 +221,7 @@ impl<'a> SliderField<'a> {
pointer_modifiers: craft_behavior::DragModifiers::default(),
pointer_model_step: None,
unit_kind: None,
lengths: None,
unit: None,
fill: true,
track_face: None,
@@ -256,6 +266,7 @@ impl<'a> SliderField<'a> {
pointer_modifiers: self.pointer_modifiers,
pointer_model_step: self.pointer_model_step,
unit_kind: self.unit_kind,
lengths: self.lengths,
unit: self.unit.clone(),
fill: self.fill,
thumb: self.thumb,
@@ -292,6 +303,7 @@ struct Look {
pointer_modifiers: craft_behavior::DragModifiers,
pointer_model_step: Option<f64>,
unit_kind: Option<UnitKind>,
lengths: Option<LengthUnits>,
unit: Option<Label>,
fill: bool,
thumb: SliderThumb,
@@ -361,8 +373,14 @@ impl Look {
}
}
/// The number field showing `shown`, with the composite's check as the slider has it.
fn field<'c>(&self, name: &Label, shown: Mixed<f64>, check: Check<'c>) -> NumberField<'c> {
/// How many shown units make one stored unit for a length field; `None` without lengths or for a pair with no scale.
fn length_scale(&self, env: &EnvView<'_>) -> Option<f64> {
self.lengths.and_then(|lengths| env.units().length_scale(lengths))
}
/// The number field showing `shown`, with the composite's check as the slider has it. `length_scale` is
/// [`Look::length_scale`]'s answer.
fn field<'c>(&self, name: &Label, shown: Mixed<f64>, check: Check<'c>, length_scale: Option<f64>) -> NumberField<'c> {
let number = match shown {
Mixed::Same(value) => Mixed::Same(Some(value)),
Mixed::Mixed => Mixed::Mixed,
@@ -374,6 +392,23 @@ impl Look {
if let Some(check) = check {
bind = bind.check_with(check, |check, value| value.map_or(Validity::Ok, |value| lifted(check.validity(&value))));
}
if let Some(lengths) = self.lengths {
// The decimals below are in the stored unit; a length field keeps the shown unit's own. A set step is in the
// stored unit, so the field steps by it in the shown unit and snaps typed values to it; without one the field
// keeps the shown unit's own step. The key policy's amount is in the stored unit too, and the field's
// accessibility step is in the shown one; a pair with no scale shows the stored value, as the field does.
let access_step = self.key_policy.and_then(ScalarKeyPolicy::amount).unwrap_or(0.0) * length_scale.unwrap_or(1.0);
let field = NumberField::length(name.clone(), bind, lengths)
.range(self.range.clone())
.scrub_by_label()
.pointer_modifiers(self.pointer_modifiers)
.scalar_access_step(access_step);
let field = match (self.set_step(), length_scale) {
(Some(step), Some(scale)) => field.step(step * scale).snap_typed(self.typed_decimals.is_none()),
_ => field,
};
return self.finish_field(field);
}
let step = self.field_step();
let typed_decimals = self.typed_decimals.map(|places| places.min(12));
let field = NumberField::new(name.clone(), bind)
@@ -384,14 +419,6 @@ impl Look {
.scrub_by_label()
.pointer_modifiers(self.pointer_modifiers)
.scalar_access_step(self.key_policy.and_then(ScalarKeyPolicy::amount).unwrap_or(0.0));
let field = match self.scrub_step {
Some(rate) => field.scrub_step(rate),
None => field,
};
let field = match &self.number_codec {
Some(codec) => field.codec(codec.clone()),
None => field,
};
let field = match typed_decimals {
Some(decimals) => field.max_decimals(decimals),
None => field,
@@ -406,11 +433,25 @@ impl Look {
Some(decimals) => field.fixed_decimals(decimals.min(12)),
None => field,
};
let field = if self.select_on_focus { field.select_on_focus() } else { field };
let field = match self.unit_kind {
Some(kind) => field.unit_kind(kind),
None => field,
};
self.finish_field(field)
}
/// `field` with the parts a length field and a plain one share: the scrub rate and reader, focus selection, sizing
/// and the unit text.
fn finish_field<'c>(&self, field: NumberField<'c>) -> NumberField<'c> {
let field = match self.scrub_step {
Some(rate) => field.scrub_step(rate),
None => field,
};
let field = match &self.number_codec {
Some(codec) => field.codec(codec.clone()),
None => field,
};
let field = if self.select_on_focus { field.select_on_focus() } else { field };
let field = match self.field_sizing {
Some(sizing) => field.sizing(sizing),
None => field,
@@ -466,7 +507,7 @@ impl Component for SliderField<'_> {
let name = cx.label();
let look = self.look();
let slider = cx.child("slider", &mut look.slider(&name, shown, None, None), Proposal::Ideal);
let field = cx.child("field", &mut look.field(&name, shown, None), Proposal::Ideal);
let field = cx.child("field", &mut look.field(&name, shown, None, look.length_scale(&cx.env)), Proposal::Ideal);
if cx.proposal == Proposal::Ideal {
self.field_width = field.x;
}
@@ -519,7 +560,7 @@ impl Component for SliderField<'_> {
// The group has no stop, so its tooltip, and with it the reason it is disabled, is carried by the first stop.
let face = self.track_face.take();
let bind = self.value.reborrow();
let field_view = look.field(&name, shown, Some(bind.check_of()));
let field_view = look.field(&name, shown, Some(bind.check_of()), look.length_scale(&cx.env));
// A read-only field's track is read-only too: no press on it edits the value, whatever `track_press` is, and an
// inert composite arms no first-Down gesture in its child for a later writable release.
let slider = look.slider(&name, shown, Some(bind.check_of()), face).read_only(cx.resolved.read_only);
+5 -3
View File
@@ -21,7 +21,7 @@ use crate::primitives::{TextKey, TextOptions, TextRun};
use crate::runtime::env::Label;
use crate::runtime::overlay::CloseReason;
use crate::text::{Adornment, place, reserve};
use craft_behavior::{HitLevel, HitPriority, NavMove, PartKey, PlainText, Preview, Selection, Sense};
use craft_behavior::{HitLevel, HitPriority, NavMove, PartKey, PlainText, Preview, Proposal, Selection, Sense};
use craft_i18n::matcher::Matcher;
use egui::{Rect, Response, Vec2};
@@ -191,14 +191,16 @@ impl Component for ComboBox<'_> {
}
/// The widest of the current text, the placeholder and the options, and the room of the chevron: the field keeps
/// its size whichever option is picked.
/// its size whichever option is picked. At its least, as a text field, it shows a short part of its text and
/// scrolls the rest, so only the chevron's room counts.
fn measure(&mut self, cx: &MeasureCx<'_, Self>) -> Vec2 {
let current = cx.value().map_or("", String::as_str);
let placeholder = self.placeholder.as_ref().map_or("", Label::as_str);
let texts = self.options.iter().filter_map(|option| option.value().map(String::as_str)).chain([current, placeholder]);
let widest = texts.map(|text| cx.field_text(&TextRun::new(text))).fold(Vec2::ZERO, Vec2::max);
let text = if cx.proposal == Proposal::Min { 0.0 } else { widest.x };
let name = cx.words::<PickerWords>().combo_options.clone();
Vec2::new(widest.x + reserve(cx.style, &[], &Self::trailing(name, cx.env.get())), widest.y)
Vec2::new(text + reserve(cx.style, &[], &Self::trailing(name, cx.env.get())), widest.y)
}
fn parts(&mut self, _: Rect, cx: &mut PartsCx<'_, Self>) {
+63
View File
@@ -418,6 +418,69 @@ fn a_wrapping_bar_continues_on_a_new_line() {
assert!(select.max.x <= 120.0 + SLACK, "a member wider than the bar kept its width: {select:?}");
}
/// The rects of two buttons, a select showing its short entry beside a long one and a last button in a tool bar
/// `width` wide that wraps.
fn select_among_tools(width: f32) -> [Rect; 4] {
let seen = Rc::new(Cell::new([Rect::NOTHING; 4]));
let out = Rc::clone(&seen);
let mut fixture = Fixture::new(move |ui| {
let entries = [Entry::new(0u8, "Current and Below, No Adjustments"), Entry::new(1, "All Layers")];
Bar::new("Tools", BarKind::Tool).wrap().show(ui, |ui, _| {
let first = Button::new("Create Outlines").show(ui).rect;
let second = Button::new("Duplicate").show(ui).rect;
let select = Select::new("Sample", Bind::given(1u8), &entries).show(ui).response.rect;
let last = IconButton::new(IconId::new("more")).label("More").show(ui).rect;
out.set([first, second, select, last]);
});
});
fixture.room(Vec2::new(width, 300.0)).settle();
seen.get()
}
#[trial]
fn a_wrapping_bar_narrows_its_select_to_one_line_before_it_wraps() {
let natural = select_among_tools(2000.0);
let line = natural[0].center().y;
assert!(natural.iter().all(|rect| (rect.center().y - line).abs() < SLACK), "a wide bar holds its members on one line: {natural:?}");
let width = natural[3].max.x - natural[2].width() / 4.0;
let narrowed = select_among_tools(width);
for rect in narrowed {
assert!((rect.center().y - narrowed[0].center().y).abs() < SLACK, "{rect:?} went on a new line in a bar {width} wide: {narrowed:?}");
assert!(rect.max.x <= width + SLACK, "{rect:?} lies past the bar's edge at {width}");
}
assert!(narrowed[2].width() + SLACK < natural[2].width(), "the select narrows: {:?} against {:?}", narrowed[2], natural[2]);
let wrapped = select_among_tools(natural[1].max.x);
assert!(wrapped[3].center().y > wrapped[0].center().y + SLACK, "a bar too narrow for its members at their least wraps: {wrapped:?}");
}
/// Whether a ranked row's button shows in a tool bar `width` wide that wraps, beside a select it can narrow, with the
/// select's rect.
fn ranked_beside_select(width: f32) -> (bool, Rect) {
let seen = Rc::new(Cell::new(Rect::NOTHING));
let out = Rc::clone(&seen);
let mut fixture = Fixture::new(move |ui| {
let entries = [Entry::new(0u8, "Current and Below, No Adjustments"), Entry::new(1, "All Layers")];
Bar::new("Tools", BarKind::Tool).wrap().show(ui, |ui, _| {
Row::new().fit_rank(1).show(ui, |ui, _| {
Button::new("Low").show(ui);
});
out.set(Select::new("Sample", Bind::given(1u8), &entries).show(ui).response.rect);
});
});
fixture.room(Vec2::new(width, 300.0)).settle();
(fixture.by_label("Low").is_some(), seen.get())
}
#[trial]
fn a_wrapping_bar_keeps_a_ranked_member_while_its_select_narrows() {
let (shown, select) = ranked_beside_select(2000.0);
assert!(shown, "a wide bar shows the ranked button");
let width = select.max.x - select.width() / 4.0;
let (shown, narrowed) = ranked_beside_select(width);
assert!(narrowed.width() + SLACK < select.width(), "the select narrows: {narrowed:?} against {select:?}");
assert!(shown, "the ranked button left a wrapping bar {width} wide");
}
/// What a bar of three rows, ranked 1 and 2 and unranked, `width` wide shows: whether each of their buttons is there.
fn ranked(width: f32) -> [bool; 3] {
let mut fixture = Fixture::new(|ui| {
@@ -1756,3 +1756,90 @@ fn measuring_runs_of(frames: &Frames, name: &str) -> usize {
|runs: Vec<(&'static str, egui::Id, MemoRun)>| runs.into_iter().filter(|(of, _, run)| of.contains(name) && *run == MemoRun::Ran).count();
ran(last_frame_memo_runs(&frames.ctx)) - ran(last_pass_memo_runs(&frames.ctx))
}
#[derive(MemoProps)]
struct RetainedOwnerChild {}
fn retained_owner_value(ui: &mut Ui, name: &str, initial: u32) {
use craft_ui::runtime::memory::Remember as _;
let mut stage = craft_ui::testing::memory::Stage::open(ui.ctx(), Id::unique(name));
let value = stage.memory::<u32>();
if *value == 0 {
*value = initial;
}
stage.finish();
}
fn retained_owner_child(_: &mut RetainedOwnerChild, ui: &mut Ui) {
retained_owner_value(ui, "retained-owner-child", 84);
ui.label("Child");
}
#[derive(MemoProps)]
struct RetainedOwnerParent {
show_child: bool,
revision: u32,
}
fn retained_owner_parent(props: &mut RetainedOwnerParent, ui: &mut Ui) {
retained_owner_value(ui, "retained-owner-parent", 42);
ui.label("Parent");
if props.show_child {
MemoView::new("retained-child", RetainedOwnerChild {}, retained_owner_child).show(ui);
}
}
fn peek_retained_owner(frames: &Frames, name: &str) -> u32 {
use craft_ui::runtime::memory::Remember as _;
let mut stage = craft_ui::testing::memory::Stage::open_peek(&frames.ctx, Id::unique(name));
let value = *stage.memory::<u32>();
stage.finish();
value
}
/// A cached parent keeps its children's memory alive; a rebuilt parent can transfer a
/// child back to its own cached record. Hiding either must still end its shown lifetime.
#[trial]
fn retained_owner_batches_survive_nested_rebuilds_and_release_hidden_children() {
let mut frames = Frames::new();
let draw = |ui: &mut Ui, show_child, revision| {
in_region(ui, region(0), |ui| {
MemoView::new("retained-parent", RetainedOwnerParent { show_child, revision }, retained_owner_parent).show(ui);
});
};
frames.idle(60, |ui| draw(ui, true, 0));
assert!(last_pass_memo_runs(&frames.ctx).iter().any(|(name, _, run)| name.contains("RetainedOwnerParent") && *run == MemoRun::Replayed));
assert_eq!(peek_retained_owner(&frames, "retained-owner-parent"), 42);
assert_eq!(peek_retained_owner(&frames, "retained-owner-child"), 84);
let retained_value = peek_retained_owner(&frames, "retained-owner-child") + 1;
frames.frame(vec![], |ui| {
use craft_ui::runtime::memory::Remember as _;
let mut stage = craft_ui::testing::memory::Stage::open(ui.ctx(), Id::unique("retained-owner-child"));
*stage.memory::<u32>() = retained_value;
stage.finish();
});
frames.idle(60, |ui| draw(ui, true, 0));
assert_eq!(peek_retained_owner(&frames, "retained-owner-child"), retained_value, "the edited value survives showing the parent again");
for revision in 1..5 {
frames.frame(vec![], |ui| draw(ui, true, revision));
}
frames.idle(60, |ui| draw(ui, true, 4));
assert_eq!(
peek_retained_owner(&frames, "retained-owner-child"),
retained_value,
"a child's edited memory survives transfers between retained records"
);
frames.idle(60, |ui| draw(ui, false, 5));
craft_ui::testing::memory::dispose_evicted(&frames.ctx);
assert_eq!(peek_retained_owner(&frames, "retained-owner-parent"), 42, "the parent still shows");
assert_eq!(peek_retained_owner(&frames, "retained-owner-child"), 0, "the hidden child expires even while its former parent keeps replaying");
frames.idle(60, |ui| draw(ui, true, 6));
assert_eq!(peek_retained_owner(&frames, "retained-owner-child"), 84, "the child can be rebuilt after eviction");
frames.idle(60, |_| {});
craft_ui::testing::memory::dispose_evicted(&frames.ctx);
assert_eq!(peek_retained_owner(&frames, "retained-owner-parent"), 0);
assert_eq!(peek_retained_owner(&frames, "retained-owner-child"), 0);
}
+41
View File
@@ -0,0 +1,41 @@
//! A field laid out `Line` inside a row: the label sits on the line of its number field, not in the middle of the row's
//! room.
use craft_ui::contract::{Bind, FieldLayout, Props as _, Show as _, ShowContainer as _, Sizing};
use craft_ui::form::Field;
use craft_ui::layout_components::Row;
use craft_ui::testing::{Fixture, trial};
use craft_ui::text::NumberField;
use egui::Vec2;
/// How far two baselines may differ and still line up, in points.
const SLACK: f32 = 1.0;
const NAME: &str = "Opacity";
/// In a row 300 pt wide in a room 600 pt tall, a `Line` field's label and its number field's value share one
/// baseline.
#[trial]
fn a_line_label_in_a_row_sits_on_its_fields_line() {
let mut fixture = Fixture::new(|ui| {
Row::new().show(ui, |ui, _| {
Field::new(NAME).layout(FieldLayout::Line).sizing(Sizing::Content).show(ui, |ui, _| {
NumberField::new(NAME, Bind::given(Some(50.0))).show(ui);
});
});
});
fixture.room(Vec2::new(300.0, 600.0));
fixture.settle();
let texts = fixture.texts();
let run =
|text: &str| texts.iter().find(|run| run.text.trim_end_matches(':') == text).unwrap_or_else(|| panic!("{text:?} is painted: {texts:?}"));
let (label, value) = (run(NAME), run("50"));
assert!(
(label.baseline - value.baseline).abs() <= SLACK,
"the label lines up with the field's value: label {:?} at {}, value {:?} at {}",
label.rect,
label.baseline,
value.rect,
value.baseline
);
}
+1
View File
@@ -10,6 +10,7 @@ pub mod group;
pub(crate) mod hit;
pub(crate) mod inside;
pub mod kit;
pub(crate) mod line;
pub(crate) mod link;
pub(crate) mod reach;
pub(crate) mod reset;
@@ -0,0 +1,117 @@
//! A field's help line wraps in the control column it is drawn in, and the field is tall enough for every line it
//! wraps to. In a field group the rows above the widest label read a narrower label column while the group measures
//! them: a check box row with its label after it, and a row beside a shorter label, still show their whole help.
use craft_ui::buttons::Button;
use craft_ui::choice::Checkbox;
use craft_ui::contract::{Bind, FieldLayout, LabelKind, Props as _, Show as _, ShowContainer as _, SideLabel};
use craft_ui::form::{Field, FieldGroup, Help};
use craft_ui::layout_components::Stack;
use craft_ui::runtime::env::Label;
use craft_ui::testing::{Fixture, trial};
use egui::{Rect, Vec2};
/// Half a pixel at the scales the box runs.
const ROUNDING: f32 = 0.5;
const WORDS: &str = "On the desktop, exports to files and packages are written in the background while you keep editing, \
except 3D exports; off, you wait for every one of them to finish before you can edit again.";
/// Help lines of every length from a short phrase to the whole of `WORDS`, cut at word ends.
fn helps() -> Vec<String> {
WORDS.char_indices().filter(|(_, c)| *c == ' ').map(|(at, _)| WORDS[..at].to_owned()).filter(|help| help.len() > 40).collect()
}
/// A help line painted with part of it outside the clip it paints under.
#[derive(Debug)]
#[allow(dead_code, reason = "read through the failure message")]
struct Cut {
help: String,
rows: usize,
rect: Rect,
clip: Rect,
}
/// How the rows with help lines are labelled.
#[derive(Clone, Copy)]
struct Rows {
layout: FieldLayout,
/// The rows' labels are hidden.
hidden: bool,
/// A row with a short visible side label comes first, so the rows read a column narrower than the widest.
lead: bool,
}
/// A field group whose rows, labelled as `rows` says, each show one of `helps()` above a last row with a long side
/// label: how many help lines it painted, how many wrapped, and the ones cut off.
fn cut_helps(rows: Rows) -> (usize, usize, Vec<Cut>) {
let Rows { layout, hidden, lead } = rows;
let helps = helps();
let shown = helps.clone();
let mut fixture = Fixture::new(move |ui| {
FieldGroup::new("Export").show(ui, |ui, _| {
Stack::new().show(ui, |ui, _| {
if lead {
Field::new("Short").show(ui, |ui, _| {
Button::new("First").show(ui);
});
}
for (at, help) in shown.iter().enumerate() {
let field = Field::new("Row").id_salt(at).help(Help::Text(Label::from(help.clone()))).layout(layout);
let field = if hidden { field.side(SideLabel::new().layout(layout).kind(LabelKind::Hidden)) } else { field };
field.show(ui, |ui, _| {
if layout == FieldLayout::After {
Checkbox::new(Bind::given(true)).show(ui);
} else {
Button::new("Choose").show(ui);
}
});
}
Field::new("The longest label of the group").show(ui, |ui, _| {
Button::new("Last").show(ui);
});
});
});
});
fixture.room(Vec2::new(720.0, 4000.0)).settle();
let (mut seen, mut wrapped, mut cut) = (0, 0, Vec::new());
for (clip, shape) in fixture.frame_clipped_shapes() {
let egui::Shape::Text(text) = shape else { continue };
if !helps.iter().any(|help| help == text.galley.text()) {
continue;
}
seen += 1;
wrapped += usize::from(text.galley.rows.len() > 1);
let rect = text.galley.rect.translate(text.pos.to_vec2());
if rect.max.y > clip.max.y + ROUNDING || rect.max.x > clip.max.x + ROUNDING {
cut.push(Cut { help: text.galley.text().to_owned(), rows: text.galley.rows.len(), rect, clip });
}
}
(seen, wrapped, cut)
}
fn assert_whole(rows: Rows) {
let (seen, wrapped, cut) = cut_helps(rows);
assert_eq!(seen, helps().len(), "every help line painted");
assert!(wrapped > 0, "some help lines wrap in this room");
assert!(cut.is_empty(), "help lines cut off: {cut:#?}");
}
#[trial]
fn a_help_line_after_a_check_box_above_the_widest_label_shows_every_line() {
assert_whole(Rows { layout: FieldLayout::After, hidden: false, lead: false });
assert_whole(Rows { layout: FieldLayout::After, hidden: false, lead: true });
}
#[trial]
fn a_help_line_beside_a_shorter_label_than_the_widest_shows_every_line() {
assert_whole(Rows { layout: FieldLayout::Beside, hidden: false, lead: false });
}
/// A hidden side label still takes the column, so the control and its help start in the control column: before any
/// row reported the column, and past a column narrower than the widest.
#[trial]
fn a_help_line_beside_a_hidden_label_above_the_widest_label_shows_every_line() {
assert_whole(Rows { layout: FieldLayout::Beside, hidden: true, lead: false });
assert_whole(Rows { layout: FieldLayout::Beside, hidden: true, lead: true });
}
@@ -4,10 +4,12 @@
use craft_behavior::{ColumnWidth, Mixed};
use craft_ui::choice::Checkbox;
use craft_ui::contract::{Bind, Props as _, Show as _, ShowContainer as _};
use craft_ui::contract::{Bind, Entry, Props as _, Show as _, ShowContainer as _};
use craft_ui::display::Text;
use craft_ui::layout_components::{Grid, Stack};
use craft_ui::pickers::ComboBox;
use craft_ui::testing::{Frames, shrink_least_runs, trial};
use craft_ui::text::TextField;
use craft_ui::value_drag::PointPicker;
use egui::{Rect, Ui, Vec2};
use std::cell::Cell;
@@ -112,3 +114,24 @@ fn labelled_check_boxes_stand_two_to_a_line() {
assert!(underline.top() >= bold.bottom() - SNAP, "the second pair is on the next line");
assert!((italic.left() - strike.left()).abs() <= SNAP, "the second column starts at one edge");
}
/// A combo box narrows below its widest option, as a text field narrows below its text: in a grid of two fill columns
/// too narrow for that option, the combo box and the field beside it share the line and stay inside the room.
#[trial]
fn a_combo_box_narrows_below_its_widest_option_in_a_grid() {
const ROOM: f32 = 160.0;
const PAIR: &[ColumnWidth] = &[ColumnWidth::fill(1.0), ColumnWidth::fill(1.0)];
let options = [Entry::new(LONG.to_owned(), LONG)];
let seen = Cell::new((Rect::NOTHING, Rect::NOTHING));
let _ = in_room(ROOM, |ui| {
Grid::new(PAIR).show(ui, |ui, _| {
let combo = ComboBox::new("Size", Bind::given("1x".to_owned()), &options).show(ui).edit.response.rect;
let field = TextField::new("Suffix", Bind::given(String::new())).show(ui).response.rect;
seen.set((combo, field));
});
});
let (combo, field) = seen.get();
assert!((combo.center().y - field.center().y).abs() <= SNAP, "the field stands beside the combo box: {combo:?} {field:?}");
assert!(combo.right() <= field.left() + SNAP, "the combo box ends before the field: {combo:?} {field:?}");
assert!(field.right() <= ROOM + SNAP, "both fit the room: {field:?}");
}
+1
View File
@@ -1,5 +1,6 @@
pub(crate) mod app_measure;
pub(crate) mod cross_fill;
pub(crate) mod field_help;
pub(crate) mod fill_column;
pub(crate) mod fill_height;
pub(crate) mod fill_share;
@@ -3,6 +3,7 @@
use craft_behavior::{MotionMode, NumberCodec};
use craft_ui::contract::{Bind, Role, Show as _};
use craft_ui::form::SliderField;
use craft_ui::runtime::env::{LengthUnits, UnitKind};
use craft_ui::testing::focus::AccessActionKind;
use craft_ui::testing::{Fixture, trial};
use egui::{Key, Modifiers};
@@ -41,6 +42,23 @@ fn codec_override_slider_field_reads_absolute_plus_without_changing_default_rela
assert_eq!(*stepped.borrow(), 10.0, "typed values still snap to the slider field's step");
}
/// A length field reads its text with the codec it is given: a reader that doubles bare input reads "3" as 6.
#[trial]
fn codec_override_slider_field_reads_a_length_with_its_codec() {
let value = Rc::new(RefCell::new(40.0));
let held = Rc::clone(&value);
let lengths = LengthUnits::new(UnitKind::Points, UnitKind::Points, 72.0);
let mut fixture = Fixture::new(move |ui| {
let mut value = held.borrow_mut();
let doubled = NumberCodec::default().parse_with(|text| text.parse::<f64>().ok().map(|number| number * 2.0));
SliderField::new("Mapped", Bind::bound(&mut *value), 0.0..=100.0).lengths(lengths).number_codec(doubled).show(ui);
});
fixture.motion(MotionMode::Off).settle();
let field = fixture.by_role(Role::SPIN_BUTTON).first().copied().expect("number field");
fixture.click(&field).key(Key::A, Modifiers::COMMAND).type_text("3").key(Key::Enter, Modifiers::NONE).settle();
assert_eq!(*value.borrow(), 6.0);
}
#[trial]
fn codec_override_slider_field_keeps_rejected_input_from_the_model() {
for text in ["1+2", "*2", "Auto", "NaN", "inf", "1.2.3", "1,2.3", ""] {
@@ -5,6 +5,7 @@ use craft_behavior::{EditEvent, MotionMode};
use craft_ui::contract::{Bind, Entry, Overlay, Props as _, Role, Show as _, Trigger};
use craft_ui::form::{SliderField, SliderFieldLayout};
use craft_ui::pickers::Select;
use craft_ui::runtime::env::{LengthUnits, UnitKind};
use craft_ui::runtime::focus::{FocusTarget, Initial, KeyUse, host_canvas, request};
use craft_ui::runtime::overlay::{OpenFilter, any_open};
use craft_ui::testing::focus::{AccessActionKind, key_release};
@@ -308,6 +309,25 @@ fn scalar_policy_numeric_child_accessibility_delegates_one_composite_edit() {
close(rig.scene.borrow().values[0][0], 0.01);
}
/// A length field over points that shows inches, on a 12 pt step, declares the policy's 36 pt amount as half an inch,
/// and its increment moves the stored value by 36 pt.
#[trial]
fn scalar_policy_length_numeric_child_declares_the_amount_in_the_shown_unit() {
let value = Rc::new(RefCell::new(72.0));
let held = Rc::clone(&value);
let lengths = LengthUnits::new(UnitKind::Points, UnitKind::Inches, 72.0);
let mut fixture = Fixture::new(move |ui| {
let mut value = held.borrow_mut();
let policy = ScalarKeyPolicy::new(36.0).trigger(ScalarKeyTrigger::HoveredOrFocused);
SliderField::new("Depth", Bind::bound(&mut *value), 0.0..=720.0).step(12.0).lengths(lengths).key_policy(policy).show_at(ui, ROWS[0]);
});
fixture.motion(MotionMode::Off).settle();
let target = fixture.by_role(Role::SPIN_BUTTON)[0];
close(fixture.tree().numeric_of(target.node).expect("numeric child").step.expect("step"), 0.5);
fixture.access(AccessActionKind::Increment, &target).settle();
close(*value.borrow(), 108.0);
}
#[trial]
fn scalar_policy_pointer_wheel_and_horizontal_keys_keep_the_original_steps() {
fn geometry(rig: &Rig, initial: f64) -> (Id, Rect, Pos2) {
@@ -4,6 +4,7 @@
use craft_behavior::{EditEvent, MotionMode};
use craft_ui::contract::{Bind, Role, Show as _};
use craft_ui::form::SliderField;
use craft_ui::runtime::env::{LengthUnits, UnitKind};
use craft_ui::testing::{Fixture, trial};
use egui::{Pos2, Rect, vec2};
use std::cell::RefCell;
@@ -50,6 +51,21 @@ fn a_slider_field_scrubs_its_value_at_the_rate_it_is_given() {
assert_eq!(*value.borrow(), -5.0, "a scrub stops at the range");
}
/// A field over points that shows inches scrubs by its rate in inches: 40 points at 0.03 in a point add 1.2 in.
#[trial]
fn a_length_slider_field_scrubs_its_value_at_the_rate_it_is_given() {
let value = Rc::new(RefCell::new(72.0));
let held = Rc::clone(&value);
let lengths = LengthUnits::new(UnitKind::Points, UnitKind::Inches, 72.0);
let mut fixture = Fixture::new(move |ui| {
let mut current = held.borrow_mut();
SliderField::new("Depth", Bind::bound(&mut *current), 0.0..=720.0).lengths(lengths).scrub_step(0.03).show_at(ui, ROW);
});
fixture.motion(MotionMode::Off).settle();
scrub_value(&mut fixture, 40.0);
assert!((*value.borrow() - 158.4).abs() < 1e-6, "1.2 in over 72 pt is 158.4 pt: {}", value.borrow());
}
#[trial]
fn a_slider_field_without_a_scrub_rate_scrubs_by_its_step() {
for rate in [None, Some(0.0), Some(-1.0), Some(f64::NAN)] {
+1
View File
@@ -1,3 +1,4 @@
//! The window skeleton's interface: what `ShellCx` answers by mode and reveal, and how a body reads it.
pub(crate) mod app_shell;
pub(crate) mod palette;
+63
View File
@@ -0,0 +1,63 @@
//! The command palette in an embedded shell, whose region a modal layer may fill.
use craft_ui::contract::{Bind, Role};
use craft_ui::menu::search::{HelpEntry, SearchIndex, SearchWords, Synonyms};
use craft_ui::patterns::panels::CommandPalette;
use craft_ui::runtime::commands::CommandRef;
use craft_ui::runtime::env::{Env, WindowKey};
use craft_ui::shell::AppShell;
use craft_ui::testing::{Fixture, trial};
use egui::{Rect, Vec2};
use std::cell::Cell;
use std::rc::Rc;
/// The names of the listed rows.
fn names(fixture: &Fixture) -> Vec<String> {
let tree = fixture.tree();
fixture.by_role(Role::LIST_BOX_OPTION).iter().map(|row| tree.name_of(row.node).unwrap_or_default().to_owned()).collect()
}
/// A query that lists more rows than fit below the box's top leaves the top where it was: the box stops above the
/// region's bottom and its list scrolls. Guards against a box as tall as the whole region, which the keep rule pushed
/// up past its top and which dropped back down as the rows went.
#[trial]
fn in_an_embedded_shell_a_long_list_leaves_the_palettes_top_in_place() {
let entries: Vec<HelpEntry> =
(0..60).map(|n| HelpEntry::new(CommandRef::new(format!("paletteTrial.item{n:02}")), format!("Item {n:02}"))).collect();
let open = Rc::new(Cell::new(true));
let region = Rc::new(Cell::new(Rect::NOTHING));
let (shown_open, shown_region) = (open.clone(), region.clone());
let mut fixture = Fixture::new(move |ui| {
let mut is_open = shown_open.get();
let out = AppShell::embedded(WindowKey::new("palette-region"))
.body(|ui, _, _| {
let env = Env::of(ui);
let view = env.view();
let index = SearchIndex::new(&view, &entries, &Synonyms::of(&view.words::<SearchWords>()));
CommandPalette::new("Commands", &entries, &index, Bind::bound(&mut is_open)).show(ui);
})
.show(ui, &mut ());
shown_open.set(is_open);
shown_region.set(out.response.rect);
});
fixture.room(Vec2::new(1400.0, 500.0)).settle();
let frame = |fixture: &Fixture| fixture.by_role(Role::DIALOG).first().expect("the palette's box shows").rect;
let opened = frame(&fixture);
let room = region.get();
assert!(
(opened.top() - (room.top() + room.height() * 0.15)).abs() <= 1.0,
"the box's top is 15% of the region's height down: {opened:?} in {room:?}"
);
fixture.type_text("item").settle();
let long = frame(&fixture);
assert!(names(&fixture).len() > 1, "the query lists many rows: {:?}", names(&fixture));
assert!(long.bottom() <= room.bottom() + 0.5, "the long box stays inside the region: {long:?} in {room:?}");
assert!((long.top() - opened.top()).abs() <= 0.5, "a long list leaves the box's top in place: {long:?} against {opened:?}");
fixture.type_text(" 07").settle();
assert_eq!(names(&fixture), ["Item 07"], "the query lists one row");
let short = frame(&fixture);
assert!(short.height() < long.height() - 1.0, "one row makes a shorter box: {short:?} against {long:?}");
assert!((short.top() - opened.top()).abs() <= 0.5, "the box's top stays put: {short:?} against {opened:?}");
}
+16
View File
@@ -204,6 +204,11 @@ pub struct RgbData {
pub height: u32,
/// Whether the image should be interpolated.
pub interpolate: bool,
/// PdfCraft patch (#1700): whether the source is 1 bit per component (a `/BitsPerComponent 1`
/// image, or a stencil mask). Minified, such a source is area-averaged instead of sampled:
/// picking samples drops one-pixel strokes (image-mask glyphs, fax-era and OCR fonts). See
/// `Renderer::draw_image`.
pub one_bit: bool,
/// Additional scaling factors to apply to the image.
///
/// In most cases, those factors will just be 1.0, and you can
@@ -230,6 +235,8 @@ pub struct LumaData {
pub height: u32,
/// Whether the image should be interpolated.
pub interpolate: bool,
/// PdfCraft patch (#1700): whether the source is 1 bit per component, as for [`RgbData`].
pub one_bit: bool,
/// Additional scaling factors to apply to the image.
///
/// In most cases, those factors will just be 1.0, and you can
@@ -279,6 +286,15 @@ impl ImageData {
}
}
/// PdfCraft patch (#1700): whether the source is 1 bit per component, so a minified draw
/// averages its pixels instead of picking them.
pub fn one_bit(&self) -> bool {
match self {
Self::Rgb(d) => d.one_bit,
Self::Luma(d) => d.one_bit,
}
}
/// The scaling factors of the image.
pub fn scale_factors(&self) -> (f32, f32) {
match self {
+23
View File
@@ -1026,6 +1026,7 @@ struct DecodeContext<'a> {
scale_factors: (f32, f32),
color_space: ColorSpace,
bits_per_component: u8,
dict_bpc: Option<u8>,
decode_arr: SmallVec<[(f32, f32); 4]>,
}
@@ -1154,6 +1155,7 @@ fn decode_context<'a>(
scale_factors: (scale_x, scale_y),
color_space,
bits_per_component,
dict_bpc,
decode_arr,
})
}
@@ -1187,6 +1189,11 @@ fn decode_mask(
width: ctx.width,
height,
interpolate: obj.interpolate,
// A stencil mask is 1-bit whatever a filter reports (ISO 32000-2 §8.9.6.2, Table 87:
// `/BitsPerComponent` shall be 1 when `/ImageMask` is true). A CCITT-encoded stencil
// expands to 8-bit grey rows but still carries one sample per bit, so it keeps the
// 1-bit path (its averaging when minified) instead of being picked.
one_bit: ctx.bits_per_component == 1 || obj.is_stencil_mask || ctx.dict_bpc == Some(1),
scale_factors: ctx.scale_factors,
},
})
@@ -1208,6 +1215,8 @@ fn decode_raster(
.color_space
.inverted_default_decode_arr(ctx.bits_per_component as f32);
let one_bit = ctx.dict_bpc == Some(1) || ctx.bits_per_component == 1;
let mut rgb_moved = false;
let image_data = if ctx.bits_per_component == 8
&& ctx.color_space.supports_u8()
@@ -1239,6 +1248,7 @@ fn decode_raster(
width: ctx.width,
height,
interpolate: obj.interpolate,
one_bit,
scale_factors: ctx.scale_factors,
}))
} else if ctx.color_space.is_device_rgb() {
@@ -1250,6 +1260,7 @@ fn decode_raster(
width: ctx.width,
height,
interpolate: obj.interpolate,
one_bit,
scale_factors: ctx.scale_factors,
}))
} else {
@@ -1262,6 +1273,7 @@ fn decode_raster(
width: ctx.width,
height,
interpolate: obj.interpolate,
one_bit,
scale_factors: ctx.scale_factors,
}))
}
@@ -1284,6 +1296,7 @@ fn decode_raster(
ctx.bits_per_component,
&ctx.decode_arr,
obj.interpolate,
one_bit,
) {
height = rgb.height;
Some(rgb)
@@ -1304,6 +1317,8 @@ fn decode_raster(
ctx.scale_factors,
&ctx.color_space,
obj.interpolate,
// PdfCraft patch (#1700): 1 bit per component, so a minified draw averages it.
one_bit,
)
};
@@ -1581,6 +1596,7 @@ fn resolve_alpha(
width,
height: *height,
interpolate: obj.interpolate,
one_bit: false,
scale_factors,
})
} else {
@@ -1626,6 +1642,7 @@ fn resolve_alpha(
width,
height: *height,
interpolate: obj.interpolate,
one_bit: false,
scale_factors,
})
} else {
@@ -1693,6 +1710,7 @@ fn get_rgb_data(
scale_factors: (f32, f32),
cs: &ColorSpace,
interpolate: bool,
one_bit: bool,
) -> Option<RgbData> {
// To prevent a panic when calling the `chunks` method.
if cs.num_components() == 0 {
@@ -1707,6 +1725,7 @@ fn get_rgb_data(
width,
height,
interpolate,
one_bit,
scale_factors,
})
}
@@ -1847,6 +1866,7 @@ fn rgb_via_lookup(
bits_per_component: u8,
decode: &[(f32, f32)],
interpolate: bool,
one_bit: bool,
) -> Option<RgbData> {
let n = cs.num_components() as usize;
let bpc = usize::from(bits_per_component);
@@ -1909,6 +1929,9 @@ fn rgb_via_lookup(
width,
height,
interpolate,
// PdfCraft patch (#1700): the lookup yields RGB, but a 1-bit source stays 1 bit, so a
// minified draw averages it as line art rather than picking samples.
one_bit,
scale_factors,
})
}
Loaded 100 of 102 files, more files were not shown because too many files have changed in this diff. Show more