Merge pull request #2473 from storytold/port/wordcraft-ui

WordCraft UI port: framework changes
This commit is contained in:
Martin Ball authored and GitHub committed 2026-11-20 13:31:28 +00:00
commit 243d68e12d
652 files changed
+41468 -5529

No files matched your search

Generated
+33
View File
@@ -2071,6 +2071,7 @@ dependencies = [
"sha2 0.10.9",
"tempfile",
"thiserror 2.0.21",
"web-time",
]
[[package]]
@@ -2357,6 +2358,7 @@ dependencies = [
"block2 0.6.2",
"craft-atomic",
"craft-behavior",
"craft-browse",
"craft-host",
"craft-i18n",
"craft-platform",
@@ -2369,6 +2371,7 @@ dependencies = [
"objc2-foundation 0.3.2",
"raw-window-handle",
"rfd",
"serde_json",
"zbus",
]
@@ -2814,8 +2817,12 @@ dependencies = [
name = "craft-gpu"
version = "0.1.0"
dependencies = [
"egui-wgpu",
"log",
"pollster 1.0.1",
"serde",
"serde_json",
"tempfile",
"thiserror 2.0.21",
]
@@ -3422,6 +3429,7 @@ version = "0.1.0"
dependencies = [
"craft-behavior",
"craft-i18n",
"craft-keymap",
"craft-text",
"craft-theme",
"craft-ui",
@@ -3598,11 +3606,13 @@ dependencies = [
"craft-docpath",
"craft-host",
"craft-theme",
"fmv-macos-events",
"futures-lite",
"js-sys",
"log",
"objc2-app-kit 0.3.2",
"objc2-foundation 0.3.2",
"rfd",
"serde",
"serde_json",
"sysinfo",
@@ -3611,6 +3621,7 @@ dependencies = [
"wasm-bindgen-test",
"web-sys",
"web-time",
"windows",
"wl-clipboard-rs",
"x11rb",
"xcap",
@@ -3697,14 +3708,19 @@ name = "craft-print"
version = "0.1.0"
dependencies = [
"craft-behavior",
"craft-host",
"craft-ui",
"craft-winprint-gdi",
"egui",
"js-sys",
"log",
"miniz_oxide 0.9.1",
"roxmltree 0.21.2",
"serde",
"serde_json",
"tempfile",
"wasm-bindgen",
"web-sys",
"winprint",
"winsafe",
]
@@ -3821,6 +3837,7 @@ dependencies = [
"craft-host",
"craft-i18n",
"craft-keymap",
"craft-pages",
"craft-theme",
"craft-ui",
"egui",
@@ -3873,11 +3890,15 @@ dependencies = [
"craft-host",
"craft-settings",
"dirs",
"log",
"serde",
"serde_json",
"tempfile",
"toml",
"toml_edit",
"wasm-bindgen-test",
"web-sys",
"web-time",
]
[[package]]
@@ -4260,6 +4281,7 @@ version = "0.1.0"
dependencies = [
"accesskit",
"craft-behavior",
"craft-codepage",
"craft-font-catalog",
"craft-fonts-build",
"craft-host",
@@ -6052,6 +6074,17 @@ dependencies = [
"syn 2.0.119",
]
[[package]]
name = "fmv-macos-events"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "90642cf66dde7f205dc8b42dfe57b47d0f3a29f571b832742883ef512e23fe55"
dependencies = [
"objc2 0.6.5",
"objc2-app-kit 0.3.2",
"objc2-foundation 0.3.2",
]
[[package]]
name = "fnv"
version = "1.0.7"
+6 -4
View File
@@ -40,16 +40,18 @@ craft-ui = { workspace = true, optional = true }
egui = { workspace = true, optional = true }
serde = { workspace = true }
serde_json = { workspace = true }
# The control channel, its server and client, screenshots, the profiler and the trace.
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
web-time = "1.1"
# The screenshot queue encodes and inlines PNGs on every target the control channel builds for.
base64 = "0.22"
png = "0.17"
# The server, client, profiler and trace.
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
craft-platform = { workspace = true }
craft-host = { workspace = true, optional = true }
getrandom = "0.3"
hmac = "0.12"
log = "0.4"
png = "0.17"
sha2 = { version = "0.10", default-features = false, features = ["std"] }
thiserror = { workspace = true }
+36 -7
View File
@@ -12,6 +12,26 @@ use crate::security::{AUTH_METHOD, IO_TIMEOUT};
/// server's own timeout error arrives before the client gives up.
pub const CALL_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(REPLY_DEADLINE.as_secs() + 5);
/// Why [`ControlClient::connect`] failed.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum ConnectError {
/// A socket or read failure: the server was not reached.
Transport(String),
/// The server answered the `auth` request with an error.
Refused(String),
}
impl std::fmt::Display for ConnectError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
ConnectError::Transport(why) | ConnectError::Refused(why) => f.write_str(why),
}
}
}
impl std::error::Error for ConnectError {}
/// One authenticated connection.
pub struct ControlClient {
stream: std::net::TcpStream,
@@ -21,16 +41,25 @@ pub struct ControlClient {
}
impl ControlClient {
/// True after a transport failure closed the connection; an error reply leaves it false. A
/// caller tells a lost connection from a refused request and never replays a mutation.
pub fn is_broken(&self) -> bool {
self.broken
}
/// Connect (read timeout [`CALL_TIMEOUT`]), send
/// `{"id": 1, "method": "auth", "params": {"token": token}}` and read one reply line; `Err` with
/// the reply's `error` text when it isn't `ok`, or the I/O error's message.
pub fn connect(addr: SocketAddr, token: &str) -> Result<Self, String> {
let stream = std::net::TcpStream::connect(addr).map_err(|e| e.to_string())?;
stream.set_read_timeout(Some(CALL_TIMEOUT)).map_err(|e| e.to_string())?;
stream.set_write_timeout(Some(IO_TIMEOUT)).map_err(|e| e.to_string())?;
let reader = BufReader::new(stream.try_clone().map_err(|e| e.to_string())?);
/// the reply's `error` text as `Refused` when it isn't `ok`, or the I/O error's message as `Transport`.
pub fn connect(addr: SocketAddr, token: &str) -> Result<Self, ConnectError> {
let io = |e: std::io::Error| ConnectError::Transport(e.to_string());
let stream = std::net::TcpStream::connect(addr).map_err(io)?;
stream.set_read_timeout(Some(CALL_TIMEOUT)).map_err(io)?;
stream.set_write_timeout(Some(IO_TIMEOUT)).map_err(io)?;
let reader = BufReader::new(stream.try_clone().map_err(io)?);
let mut client = Self { stream, broken: false, reader, next_id: 2 };
client.exchange(1, AUTH_METHOD, json!({"token": token}))?;
// `exchange` marks the client broken on a transport failure only, so an error reply is a refusal.
let auth = client.exchange(1, AUTH_METHOD, json!({"token": token}));
auth.map_err(|e| if client.broken { ConnectError::Transport(e) } else { ConnectError::Refused(e) })?;
Ok(client)
}
+50 -3
View File
@@ -14,7 +14,7 @@
//! two happened, once, between the UI thread and the transport.
use std::sync::mpsc::{Receiver, Sender};
use std::time::Instant;
use web_time::Instant;
use craft_ui::runtime::motion;
use craft_ui::runtime::windows::WindowHost;
@@ -127,9 +127,17 @@ pub enum Reply {
/// A command started a background job and the caller waits: reply with its result when it
/// has been applied, or with its error or `cancelled`.
AfterJob(JobId),
/// A `ui.accessTree`: hold the reply until the window's settled access tree can be read
/// ([`ControlChannel::poll_access_trees`]).
AccessTree,
}
impl Reply {
/// A `ui.accessTree` reply: held until the window's settled access tree is available.
pub fn access_tree() -> Reply {
Reply::AccessTree
}
/// A `ui.screenshot` reply for `token` of `viewport`, writing the PNG to `path` or inlining it
/// when `None`.
pub fn screenshot(token: u64, path: Option<String>, viewport: egui::ViewportId) -> Self {
@@ -162,6 +170,7 @@ pub struct ControlChannel {
rx: Receiver<ControlRequest>,
input_waiters: Vec<Sender<ControlResponse>>,
job_waiters: Vec<(JobId, Sender<ControlResponse>)>,
tree_waiters: Vec<Sender<ControlResponse>>,
/// The screenshot queue; the app calls its `issue` and `drain` from its UI and logic phases.
pub captures: Captures,
}
@@ -169,7 +178,7 @@ pub struct ControlChannel {
impl ControlChannel {
/// Attach a transport's receiver (TCP, stdin, tests).
pub fn new(rx: Receiver<ControlRequest>) -> Self {
Self { rx, input_waiters: Vec::new(), job_waiters: Vec::new(), captures: Captures::default() }
Self { rx, input_waiters: Vec::new(), job_waiters: Vec::new(), tree_waiters: Vec::new(), captures: Captures::default() }
}
/// The next request to run, claimed through [`Dispatch::start`]. Expired or abandoned
@@ -197,6 +206,7 @@ impl ControlChannel {
}
Reply::AfterInput => self.input_waiters.push(reply),
Reply::AfterJob(job) => self.job_waiters.push((job, reply)),
Reply::AccessTree => self.tree_waiters.push(reply),
Reply::Screenshot { token, path, viewport } => {
if let Err((reply, e)) = self.captures.admit(ScreenshotRequest { token, path, viewport, reply, document, settle_ms }, motion::now()) {
let _ = reply.send(json!({"ok": false, "error": e}));
@@ -237,6 +247,43 @@ impl ControlChannel {
}
}
/// Answers the held `ui.accessTree` requests from the window host's settled access tree; a
/// request stays held while the host has none. Runs in the logic phase of every pass, as
/// [`poll_input`](Self::poll_input) does.
pub fn poll_access_trees(&mut self, ctx: &egui::Context) {
if self.tree_waiters.is_empty() {
return;
}
// `ui.accessTree` takes no window: it reads the main window's tree.
let Some(update) = WindowHost::of(ctx).access_tree(egui::ViewportId::ROOT) else { return };
let nodes: Vec<Value> = update
.nodes
.iter()
.map(|(id, node)| {
let children: Vec<u64> = node.children().iter().map(|child| child.0).collect();
let mut entry = json!({"id": id.0, "role": format!("{:?}", node.role()), "children": children});
if let Some(name) = node.label() {
entry["name"] = json!(name);
}
if let Some(value) = node.value() {
entry["value"] = json!(value);
}
if let Some(selection) = node.text_selection() {
entry["textSelection"] = json!({
"anchor": {"node": selection.anchor.node.0, "character": selection.anchor.character_index},
"focus": {"node": selection.focus.node.0, "character": selection.focus.character_index},
});
}
entry
})
.collect();
let root = update.tree.as_ref().map(|tree| tree.root.0);
let reply = json!({"ok": true, "result": {"nodes": nodes, "focus": update.focus.0, "root": root}});
for waiter in self.tree_waiters.drain(..) {
let _ = waiter.send(reply.clone());
}
}
/// Drops the host's queued input and the step in flight, and fails every
/// [`Reply::AfterInput`] waiter with `input cancelled: {reason}`, also when only waiters
/// remain (their input was already consumed). True when anything was pending or waiting.
@@ -277,6 +324,6 @@ impl ControlChannel {
/// Waiters of every kind, for `ui.inspect`'s `pending` count and tests.
pub fn waiting(&self) -> usize {
self.input_waiters.len() + self.job_waiters.len() + self.captures.pending()
self.input_waiters.len() + self.job_waiters.len() + self.tree_waiters.len() + self.captures.pending()
}
}
+3 -4
View File
@@ -23,19 +23,18 @@ pub mod ui;
#[cfg(not(target_arch = "wasm32"))]
pub mod args;
#[cfg(all(feature = "ui", not(target_arch = "wasm32")))]
#[cfg(feature = "ui")]
pub mod control;
#[cfg(all(feature = "ui", not(target_arch = "wasm32")))]
pub mod dialogs;
#[cfg(not(target_arch = "wasm32"))]
pub mod profiler;
#[cfg(not(target_arch = "wasm32"))]
pub mod protocol;
#[cfg(all(feature = "ui", not(target_arch = "wasm32")))]
#[cfg(feature = "ui")]
pub mod screenshot;
#[cfg(not(target_arch = "wasm32"))]
pub mod security;
#[cfg(all(feature = "ui", not(target_arch = "wasm32")))]
#[cfg(feature = "ui")]
pub mod synthetic;
#[cfg(not(target_arch = "wasm32"))]
pub mod trace;
+4
View File
@@ -104,6 +104,10 @@ pub fn write_reply(out: &mut impl Write, reply: &Value) -> std::io::Result<()> {
/// The pointer buttons a request may name.
pub const BUTTONS: [&str; 4] = ["left", "right", "secondary", "middle"];
/// The method that reads the window's access tree. Params `{}`; the reply is
/// `{nodes: [{id, role, name?, value?, children, textSelection?}], focus, root}` with AccessKit
/// role names.
pub const ACCESS_TREE_METHOD: &str = "ui.accessTree";
/// The per-request reply deadline.
pub const REPLY_DEADLINE: Duration = Duration::from_secs(60);
+1 -1
View File
@@ -18,7 +18,7 @@
use std::collections::HashMap;
use std::sync::Arc;
use std::sync::mpsc::Sender;
use std::time::{Duration, Instant};
use web_time::{Duration, Instant};
use base64::Engine as _;
use craft_ui::runtime::windows::{ScreenshotFacts, ScreenshotSlot, WindowHost};
+11 -11
View File
@@ -49,9 +49,9 @@ pub const OFF_SCREEN: &str = "the document point is too far off the screen";
/// The error of a point that is not finite (NaN or infinite): refused at the request, never queued.
pub const NOT_FINITE: &str = "the point must be finite";
/// The application's map from a document point to the screen point its canvas shows it at; `None` when no canvas
/// shows a document. Applications without documents pass `&|_| None`.
pub type DocumentMap<'a> = &'a dyn Fn(Pos2) -> Option<Pos2>;
/// The application's map from a page and a document point on it to the screen point its canvas shows it at; `None`
/// when no canvas shows a document. Applications without documents pass `&|_, _| None`.
pub type DocumentMap<'a> = &'a dyn Fn(usize, Pos2) -> Option<Pos2>;
/// A point of a request: screen points, or document points the application maps.
#[derive(Clone, Copy, Debug, PartialEq)]
@@ -59,8 +59,8 @@ pub type DocumentMap<'a> = &'a dyn Fn(Pos2) -> Option<Pos2>;
pub enum At {
/// Screen points.
Screen(Pos2),
/// Document points.
Document(Pos2),
/// Document points on page `page` (0 when the request names none).
Document(Pos2, usize),
}
impl At {
@@ -70,7 +70,7 @@ impl At {
let x = p.number_in("x", "x", range)?.unwrap_or(0.0) as f32;
let y = p.number_in("y", "y", range)?.unwrap_or(0.0) as f32;
Ok(match p.choice("coordinates", "coordinates", &["screen", "document"])?.unwrap_or("screen") {
"document" => Self::Document(pos2(x, y)),
"document" => Self::Document(pos2(x, y), p.uint_field("page")?.map_or(0, |page| usize::try_from(page).unwrap_or(usize::MAX))),
_ => Self::Screen(pos2(x, y)),
})
}
@@ -81,9 +81,9 @@ impl At {
match self {
Self::Screen(at) if at.x.is_finite() && at.y.is_finite() => Ok(at),
Self::Screen(_) => Err(NOT_FINITE.to_owned()),
Self::Document(at) if !(at.x.is_finite() && at.y.is_finite()) => Err(NOT_FINITE.to_owned()),
Self::Document(at) => {
let on_screen = map(at).ok_or_else(|| NO_DOCUMENT.to_owned())?;
Self::Document(at, _) if !(at.x.is_finite() && at.y.is_finite()) => Err(NOT_FINITE.to_owned()),
Self::Document(at, page) => {
let on_screen = map(page, at).ok_or_else(|| NO_DOCUMENT.to_owned())?;
let within = |v: f32| v.is_finite() && f64::from(v.abs()) <= MAX_SCREEN_POINT;
if within(on_screen.x) && within(on_screen.y) { Ok(on_screen) } else { Err(OFF_SCREEN.to_owned()) }
}
@@ -92,7 +92,7 @@ impl At {
}
/// The point fields every pointer request takes.
const POINT: [&str; 3] = ["x", "y", "coordinates"];
const POINT: [&str; 4] = ["x", "y", "coordinates", "page"];
/// The modifier fields ([`crate::protocol::KEY_MODIFIERS`], top-level or under `modifiers`).
const MODIFIERS: [&str; 5] = ["modifiers", "shift", "alt", "command", "ctrl"];
@@ -263,7 +263,7 @@ impl Release {
/// `{button?, key?, x?, y?, coordinates?}`, no other fields. With neither `button` nor `key` everything held is
/// released, the modifiers too; both is ``"`button` and `key` exclude each other"``.
pub fn from_params(params: &Value) -> Result<Self, String> {
let p = Params(params).only(None, &["button", "key", "x", "y", "coordinates"])?;
let p = Params(params).only(None, &["button", "key", "x", "y", "coordinates", "page"])?;
let p = Params(&p);
let released = match (button(&p)?, key(&p)?) {
(Some(_), Some(_)) => return Err("`button` and `key` exclude each other".into()),
+27
View File
@@ -123,6 +123,33 @@ fn an_unauthenticated_connection_is_closed_at_the_deadline_whatever_it_sends() {
assert!(rx.try_recv().is_err(), "nothing was dispatched");
}
/// A web page can reach loopback: a browser `POST` whose body is a valid `auth` line is refused at its request line
/// and the connection closed, so neither the body's `auth` nor a request after it reaches the app.
#[trial]
fn a_browser_post_never_reaches_the_app() {
// Far longer than the trial, so the close comes from the refusal, not the deadline.
let (rx, server) = server::serve_with_deadline(TcpListener::bind("127.0.0.1:0").expect("bound"), TOKEN.into(), host(), Duration::from_secs(60))
.expect("started");
let mut stream = TcpStream::connect(server.addr).expect("connected");
stream.set_read_timeout(Some(Duration::from_secs(5))).expect("timeout");
let mut reader = BufReader::new(stream.try_clone().expect("cloned"));
let body = format!("{}\n{}\n", json!({"id": 1, "method": "auth", "params": {"token": TOKEN}}), json!({"id": 2, "method": "test.ping"}));
write!(stream, "POST / HTTP/1.1\r\n").expect("written");
let refused = read_json(&mut reader).expect("a reply to the request line");
assert_eq!(refused["ok"], false, "{refused}");
assert_eq!(refused["error"], "authentication required", "{refused}");
// The rest of what the browser sends; the server may already have closed.
let _ = write!(stream, "Host: 127.0.0.1\r\nContent-Type: text/plain\r\nContent-Length: {}\r\n\r\n{body}", body.len());
let _ = stream.flush();
let mut rest = String::new();
let closed = match reader.read_line(&mut rest) {
Ok(read) => read == 0,
Err(e) => !matches!(e.kind(), std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut),
};
assert!(closed, "the connection closes after the refusal, answering nothing more: {rest:?}");
assert!(rx.recv_timeout(Duration::from_millis(300)).is_err(), "nothing reached the app");
}
/// A request line over `MAX_REQUEST_BYTES` without a newline gets an error reply and the connection is closed.
#[trial]
fn an_over_long_request_is_refused_and_closes_the_connection() {
+14 -7
View File
@@ -32,9 +32,14 @@ struct Rig {
passes: Rc<RefCell<Vec<Seen>>>,
}
/// Document points are screen points doubled, as a canvas at 50 % shows them.
fn map(at: Pos2) -> Option<Pos2> {
Some(pos2(at.x / 2.0, at.y / 2.0))
/// Screen points between one page's top and the next's, in a canvas that stacks its pages down the screen.
const PAGE_STEP: f32 = 200.0;
/// Document points are screen points doubled, as a canvas at 50 % shows them, with each page [`PAGE_STEP`] below
/// the one before.
fn map(page: usize, at: Pos2) -> Option<Pos2> {
let page = u16::try_from(page).ok()?;
Some(pos2(at.x / 2.0, at.y / 2.0 + f32::from(page) * PAGE_STEP))
}
impl Rig {
@@ -109,6 +114,8 @@ fn a_held_press_stays_down_until_its_release() {
assert_eq!(rig.now().pos, Some(pos2(100.0, 50.0)), "the document point is mapped");
rig.send("ui.move", json!({"x": 300, "y": 100, "coordinates": "document"}));
assert!(rig.now().primary_down && rig.now().pos == Some(pos2(150.0, 50.0)), "a move while held drags");
rig.send("ui.move", json!({"x": 300, "y": 100, "coordinates": "document", "page": 1}));
assert_eq!(rig.now().pos, Some(pos2(150.0, 50.0 + PAGE_STEP)), "a document point is mapped on the page it names");
rig.send("ui.release", json!({}));
assert!(!rig.now().primary_down, "the release lets it go");
rig.send("ui.click", json!({"x": 10, "y": 10}));
@@ -276,7 +283,7 @@ fn injected_passes_are_the_passes_that_carry_a_step() {
fn document_points_need_a_canvas() {
let rig = Rig::new();
let host = rig.host();
let none = |_: Pos2| None;
let none = |_: usize, _: Pos2| None;
let refused = input_method("ui.move", &json!({"x": 1, "y": 1, "coordinates": "document"}), &host, ViewportId::ROOT, &none);
assert_eq!(refused, Some(Err(NO_DOCUMENT.to_owned())));
assert!(host.injected_idle());
@@ -409,9 +416,9 @@ fn ui_ime_reaches_a_focused_text_field_as_a_preedit_then_a_commit_in_order() {
#[trial]
fn a_point_that_is_not_finite_is_refused() {
for bad in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY] {
for at in [At::Screen(pos2(bad, 1.0)), At::Screen(pos2(1.0, bad)), At::Document(pos2(bad, 1.0))] {
assert_eq!(at.resolve(&|p| Some(p)), Err(NOT_FINITE.to_owned()), "{at:?}");
for at in [At::Screen(pos2(bad, 1.0)), At::Screen(pos2(1.0, bad)), At::Document(pos2(bad, 1.0), 0)] {
assert_eq!(at.resolve(&|_, p| Some(p)), Err(NOT_FINITE.to_owned()), "{at:?}");
}
}
assert_eq!(At::Screen(pos2(3.0, 4.0)).resolve(&|_| None), Ok(pos2(3.0, 4.0)));
assert_eq!(At::Screen(pos2(3.0, 4.0)).resolve(&|_, _| None), Ok(pos2(3.0, 4.0)));
}
+10 -1
View File
@@ -196,6 +196,8 @@ pub enum PaintedCursor {
Arrow {
/// The arrow is drawn hollow.
hollow: bool,
/// The art turns about its hotspot to point along this direction; `None` is the base art.
toward: Option<Vec2>,
},
/// An I-beam across a path with a filled triangle toward each grabbable side.
#[non_exhaustive]
@@ -216,6 +218,8 @@ pub enum PaintedCursor {
},
/// No cursor at all.
Hidden,
/// A plain I-beam, visible on light and dark.
IBeam,
}
impl PaintedCursor {
@@ -275,7 +279,12 @@ impl PaintedCursor {
/// An arrow with its tip on the hotspot, hollow when `hollow`.
pub const fn arrow(hollow: bool) -> Self {
PaintedCursor::Arrow { hollow }
PaintedCursor::Arrow { hollow, toward: None }
}
/// A solid arrow turned about its hotspot to point along `dir`.
pub const fn arrow_toward(dir: Vec2) -> Self {
PaintedCursor::Arrow { hollow: false, toward: Some(dir) }
}
/// An I-beam across the path with a triangle toward each grabbable side.
+12 -2
View File
@@ -52,6 +52,9 @@ pub enum EditorInput {
forward: bool,
/// How much to delete.
by: Granularity,
/// Shift was held (`Intent::Delete::shift`): Shift+Delete is a word processor's Cut, which deletes nothing
/// without a selection, so an editor that gives it that meaning tells it from a plain Delete.
shift: bool,
},
/// Text around the caret or the marked text, deleted for the IME.
#[non_exhaustive]
@@ -87,14 +90,21 @@ pub enum EditorInput {
Newline,
/// Tab.
Tab,
/// Shift+Tab, which reaches only a document canvas's editor part that keeps Tab.
BackTab,
/// Escape.
Cancel,
}
impl EditorInput {
/// A `Delete` of `by`.
/// A `Delete` of `by`, without Shift.
pub const fn delete(forward: bool, by: Granularity) -> Self {
EditorInput::Delete { forward, by }
EditorInput::Delete { forward, by, shift: false }
}
/// A `Delete` of `by` with Shift held when `shift`.
pub const fn delete_with_shift(forward: bool, by: Granularity, shift: bool) -> Self {
EditorInput::Delete { forward, by, shift }
}
/// A `DeleteSurrounding` of `before` and `after` characters.
+67 -16
View File
@@ -1,6 +1,6 @@
//! The fit rules: which tabs, bar items or titles stay in a strip and which go to an overflow menu. [`fit`] and
//! [`fit_whole`] assign tab widths (tabs shrink before they overflow, or keep their width); [`fit_items`] drops
//! command items and titles from the end. All of them read no egui types.
//! [`fit_whole`] assign tab widths (tabs shrink before they overflow, or keep their width); [`fit_items`] shortens
//! items that have a short form, then drops command items and titles from the end. All of them read no egui types.
/// Tabs visible on a strip and tabs that need an overflow menu, all in original order.
#[derive(Clone, Debug, Default, PartialEq)]
@@ -122,9 +122,13 @@ fn fit_keeping_selected(natural: &[f32], selected: usize, available: f32, minimu
/// gets less than its natural width; its painter elides the label. A lone tab never reserves a
/// button.
///
/// The tabs marked in `kept` take the room after the selected tab before the others, in order while each fits; a
/// kept tab that does not fit overflows. The others then follow the rule above. A `kept` slice that is empty or
/// shorter than `natural` marks no tab past its end, so an empty slice gives the plain rule.
///
/// Dimensions are sanitized as in [`fit`], and the shown widths plus `overflow_width` never
/// exceed the sanitized available width. Work and storage are linear in the input count.
pub fn fit_whole(natural: &[f32], selected: usize, available: f32, overflow_width: f32) -> TabFit {
pub fn fit_whole(natural: &[f32], selected: usize, kept: &[bool], available: f32, overflow_width: f32) -> TabFit {
let available = tab_extent(available);
let natural: Vec<f32> = natural.iter().map(|&w| tab_extent(w)).collect();
if natural.iter().map(|&w| f64::from(w)).sum::<f64>() <= f64::from(available) {
@@ -138,17 +142,33 @@ pub fn fit_whole(natural: &[f32], selected: usize, available: f32, overflow_widt
let selected = selected.min(natural.len().saturating_sub(1));
let active = natural.get(selected).copied().unwrap_or(0.0).min(budget);
let mut room = f64::from(budget - active);
let mut keep = vec![false; natural.len()];
if let Some(keep) = keep.get_mut(selected) {
*keep = true;
}
// The kept tabs take room first, then the others; each run stops at its first tab that does not fit.
for kept_run in [true, false] {
for (i, &width) in natural.iter().enumerate() {
if i == selected || kept.get(i).copied().unwrap_or(false) != kept_run {
continue;
}
if f64::from(width) > room {
break;
}
room -= f64::from(width);
if let Some(keep) = keep.get_mut(i) {
*keep = true;
}
}
}
let mut shown = Vec::new();
let mut overflow = Vec::new();
let mut full = false;
for (i, &width) in natural.iter().enumerate() {
if i == selected {
shown.push((i, active));
} else if !full && f64::from(width) <= room {
room -= f64::from(width);
} else if keep.get(i).copied().unwrap_or(false) {
shown.push((i, width));
} else {
full = true;
overflow.push(i);
}
}
@@ -208,12 +228,20 @@ pub struct FitItem {
pub section: u16,
/// Whether the item may overflow.
pub keep: FitKeep,
/// The extent of the item's shorter form, if it has one.
pub short: Option<f32>,
}
impl FitItem {
/// An item `extent` long in `section`.
pub const fn new(extent: f32, section: u16, keep: FitKeep) -> Self {
FitItem { extent, section, keep }
FitItem { extent, section, keep, short: None }
}
/// The item with a shorter form `extent` long, which it takes before any free item leaves.
pub const fn short(mut self, extent: f32) -> Self {
self.short = Some(extent);
self
}
}
@@ -225,6 +253,8 @@ pub struct Fit {
pub shown: Vec<usize>,
/// The items in the overflow menu; empty when everything fits.
pub overflow: Vec<usize>,
/// The shown items that take their shorter form, as indexes into the input.
pub short: Vec<usize>,
}
fn item_extent(value: f32) -> f64 {
@@ -247,24 +277,45 @@ pub fn run_extent(items: &[FitItem], shown: &[bool], gap: f64, section_gap: f64)
}
/// Decides which items stay in a strip `available` long. Everything fits and no item is `Menu`: all items show.
/// Otherwise the `Menu` items are in the menu, and the last `Free` item leaves first, one at a time, until the rest
/// and an overflow control `overflow_extent` long, set off by `gap`, fit; `Pinned` items stay even when they alone
/// are longer than `available`. Negative and non-finite lengths count as zero.
/// Otherwise the `Menu` items are in the menu, and the items with a [`FitItem::short`] form take it first, the last
/// one first, until the run fits (listed in [`Fit::short`]); a `Pinned` item shortens as a `Free` one does. Only then
/// does the last `Free` item leave, one at a time, until the rest and an overflow control `overflow_extent` long,
/// set off by `gap`, fit; `Pinned` items stay even when they alone are longer than `available`. Items that leave are
/// never listed as short. Negative and non-finite lengths count as zero.
pub fn fit_items(items: &[FitItem], available: f32, gap: f32, section_gap: f32, overflow_extent: f32) -> Fit {
let (available, gap, section_gap, overflow_extent) =
(item_extent(available), item_extent(gap), item_extent(section_gap), item_extent(overflow_extent));
let mut shown: Vec<bool> = items.iter().map(|item| item.keep != FitKeep::Menu).collect();
if shown.iter().all(|shown| *shown) && run_extent(items, &shown, gap, section_gap) <= available {
return Fit { shown: (0..items.len()).collect(), overflow: Vec::new() };
return Fit { shown: (0..items.len()).collect(), overflow: Vec::new(), short: Vec::new() };
}
let fits = |shown: &[bool]| {
// The overflow control takes room only while some item is in the menu; a run that every item is in, shortened,
// needs no control.
let fits = |run: &[FitItem], shown: &[bool]| {
let extent = run_extent(run, shown, gap, section_gap);
if shown.iter().all(|shown| *shown) {
return extent <= available;
}
let before_control = if shown.iter().any(|shown| *shown) { gap } else { 0.0 };
run_extent(items, shown, gap, section_gap) + before_control + overflow_extent <= available
extent + before_control + overflow_extent <= available
};
while !fits(&shown) {
// The shadow run holds each item at the extent it takes: shortened items at their `short` extent.
let mut run: Vec<FitItem> = items.to_vec();
let mut short = vec![false; items.len()];
while !fits(&run, &shown) {
let Some(last) = (0..items.len()).rev().find(|&at| shown[at] && !short[at] && items[at].short.is_some()) else {
break;
};
short[last] = true;
if let (Some(item), Some(extent)) = (run.get_mut(last), items[last].short) {
item.extent = extent;
}
}
while !fits(&run, &shown) {
let Some(last) = (0..items.len()).rev().find(|&at| shown[at] && items[at].keep == FitKeep::Free) else { break };
shown[last] = false;
}
let (kept, left): (Vec<usize>, Vec<usize>) = (0..items.len()).partition(|&at| shown[at]);
Fit { shown: kept, overflow: left }
let short = kept.iter().copied().filter(|&at| short[at]).collect();
Fit { shown: kept, overflow: left, short }
}
+2 -1
View File
@@ -27,5 +27,6 @@ pub use outside::outside_pieces;
pub use quad::{BoxAllow, BoxDrag, BoxPart, BoxRules, BoxState, Homography, Parts, SKEW_LIMIT, ScaleRule, TransformMode, drag};
pub use selection_op::SelectionOperation;
pub use snap::{
SNAP_PX, SnapGesture, SnapKind, SnapKinds, SnapLine, SnapOptions, SnapTarget, SnapTargets, across_axis, coordinate_across, motion_across,
SNAP_PX, SnapGesture, SnapKind, SnapKinds, SnapLine, SnapOptions, SnapSuspend, SnapTarget, SnapTargets, across_axis, coordinate_across,
motion_across,
};
+16 -2
View File
@@ -100,6 +100,9 @@ pub enum ScaleRule {
/// A shape or path bounds box: a corner scales by the projection of the drag on the anchor-corner diagonal,
/// keeping the proportions; an edge stretches its one axis.
Shape,
/// A corner keeps the proportions and ⇧ frees them, as [`ScaleRule::Proportional`]; an edge stretches its one
/// axis, as [`ScaleRule::Shape`]. The aspect link plays no part.
Corners,
}
/// What the box's content allows. PhotoCraft: editable type refuses distort and perspective
@@ -271,8 +274,9 @@ impl BoxRules {
/// The modifiers a drag of `part` acts on, from the keys held: ⌘ is dropped on a corner or
/// edge the content refuses to distort or skew, the legacy scale rule ([`ScaleRule::Free`])
/// or an unlinked aspect ratio turns ⇧ over on corners and edges, and the shape rule
/// ([`ScaleRule::Shape`]) sets ⇧ by the part alone. Mode keys ([`TransformMode::Distort`],
/// or an unlinked aspect ratio turns ⇧ over on corners and edges, the shape rule
/// ([`ScaleRule::Shape`]) sets ⇧ by the part alone, and the corners rule ([`ScaleRule::Corners`]) sets ⇧ on
/// edges only. Mode keys ([`TransformMode::Distort`],
/// [`TransformMode::Perspective`]) are not added here: they are part of
/// [`drag_kind`](Self::drag_kind). [`drag`] acts on these modifiers.
fn drag_modifiers(&self, part: BoxPart, mods: Mods) -> Mods {
@@ -285,6 +289,7 @@ impl BoxRules {
}
match self.scale {
ScaleRule::Shape => shape_mods(part, mods),
ScaleRule::Corners => corners_mods(part, mods),
scale => {
let legacy = scale == ScaleRule::Free;
legacy_mods(legacy, part, unlinked_mods(!self.aspect_linked, legacy, part, mods))
@@ -313,6 +318,15 @@ pub fn drag(start: &BoxState, last: &BoxState, part: BoxPart, from: Point, to: P
apply_mode_drag(&g, to, rules, mods)
}
/// The [`ScaleRule::Corners`] rule: a corner keeps the keys as given, so it keeps the proportions and ⇧ frees them;
/// an edge stretches its one axis whatever ⇧ and the aspect link say. ⌘ gestures are left alone.
fn corners_mods(part: BoxPart, mut mods: Mods) -> Mods {
if !mods.cmd && matches!(part, BoxPart::Edge(_)) {
mods.shift = true;
}
mods
}
/// The shape bounds box's rule: a corner keeps the proportions along the diagonal and an edge
/// stretches its one axis, whatever ⇧ and the aspect link say. ⌘ gestures are left alone.
fn shape_mods(part: BoxPart, mut mods: Mods) -> Mods {
+65 -8
View File
@@ -7,11 +7,13 @@
//! caller converts [`SNAP_PX`] screen points with the zoom. Results carry [`SnapLine`]s the
//! caller draws.
//!
//! Snapping is on when View › Snap is; holding Ctrl while dragging turns it off, except when Ctrl
//! is the tool's own modifier (the caller reads the keys). Smart guides follow View › Show ›
//! Snapping is on when View › Snap is; holding the suspend key ([`SnapSuspend`], Ctrl by default)
//! while dragging turns it off, except when that key is the tool's own modifier (the caller reads
//! the keys). Smart guides follow View › Show ›
//! Smart Guides and also snap the Move tool to other layers' edges and centres.
use crate::flow::Axis;
use craft_keymap::{Mods, Platform};
use kurbo::{Point, Rect, Vec2};
/// Screen points within which a position snaps (Photoshop).
@@ -158,12 +160,51 @@ pub struct SnapOptions {
pub selection: bool,
/// View › Show › Smart Guides.
pub smart_guides: bool,
/// The key that suspends snapping.
pub suspend: SnapSuspend,
}
impl Default for SnapOptions {
/// Photoshop's defaults: everything on.
fn default() -> Self {
Self { on: true, guides: true, grid: true, layers: true, document_bounds: true, selection: true, smart_guides: true }
Self {
on: true,
guides: true,
grid: true,
layers: true,
document_bounds: true,
selection: true,
smart_guides: true,
suspend: SnapSuspend::default(),
}
}
}
/// The key that suspends snapping.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum SnapSuspend {
/// The Control key.
#[default]
Control,
/// The Alt key.
Alt,
}
impl SnapSuspend {
/// Whether this key is held in `mods` on `os`: Control is the Control key without ⌘ on macOS and Ctrl
/// elsewhere (where it is `Mods::cmd`); Alt is Alt (⌥).
pub fn is_held(self, mods: Mods, os: Platform) -> bool {
match self {
SnapSuspend::Control => {
if os.is_mac() {
mods.ctrl && !mods.cmd
} else {
mods.cmd
}
}
SnapSuspend::Alt => mods.alt,
}
}
}
@@ -197,6 +238,15 @@ pub struct SnapTargets {
/// Distances closer than this are equal.
const TIE: f64 = 1e-9;
/// Whether `target` reaches a point or box spanning `across` on the other axis: a target with a span (a layer's
/// edge on its page) only where the two overlap; a target without a span, or a query without an extent, always.
fn reaches(target: &SnapTarget, across: Option<(f64, f64)>) -> bool {
match (target.span, across) {
(Some((a, b)), Some((lo, hi))) => lo <= b && a <= hi,
_ => true,
}
}
/// The line through `target` reaching the snapped object at `a..b` along the line; a target
/// without a span stays full height.
fn line(target: &SnapTarget, a: f64, b: f64) -> SnapLine {
@@ -291,8 +341,15 @@ impl SnapTargets {
/// The nearest target of a kind in `kinds` among the lines that run `along` an axis, within `tolerance` of
/// `value` across them; [`SnapTargets::nearest`] is this with [`SnapKinds::ALL`].
pub fn nearest_of(&self, along: Axis, value: f64, tolerance: f64, kinds: SnapKinds) -> Option<SnapTarget> {
self.nearest_within(along, value, None, tolerance, kinds)
}
/// [`nearest_of`](Self::nearest_of) that also takes the query's extent `across` the other axis: a target with a
/// span catches only a point or box overlapping that span there; without `across`, or for a target without a
/// span, it is `nearest_of`.
pub fn nearest_within(&self, along: Axis, value: f64, across: Option<(f64, f64)>, tolerance: f64, kinds: SnapKinds) -> Option<SnapTarget> {
let mut best: Option<(f64, SnapTarget)> = None;
for target in self.targets.iter().filter(|t| t.along == along && kinds.contains(t.kind)) {
for target in self.targets.iter().filter(|t| t.along == along && kinds.contains(t.kind) && reaches(t, across)) {
let distance = (target.position - value).abs();
if distance > tolerance {
continue;
@@ -325,11 +382,11 @@ impl SnapTargets {
pub fn snap_point_of(&self, point: Point, tolerance: f64, kinds: SnapKinds) -> (Point, Vec<SnapLine>) {
let mut out = point;
let mut lines = Vec::new();
if let Some(t) = self.nearest_of(Axis::Y, point.x, tolerance, kinds) {
if let Some(t) = self.nearest_within(Axis::Y, point.x, Some((point.y, point.y)), tolerance, kinds) {
out.x = t.position;
lines.push(line(&t, point.y, point.y));
}
if let Some(t) = self.nearest_of(Axis::X, point.y, tolerance, kinds) {
if let Some(t) = self.nearest_within(Axis::X, point.y, Some((out.x, out.x)), tolerance, kinds) {
out.y = t.position;
lines.push(line(&t, out.x, out.x));
}
@@ -359,7 +416,7 @@ impl SnapTargets {
let anchors = [lo, hi, (lo + hi) / 2.0];
let mut best: Option<f64> = None;
for anchor in anchors {
if let Some(t) = self.nearest_of(along, anchor, tolerance, kinds) {
if let Some(t) = self.nearest_within(along, anchor, Some(other), tolerance, kinds) {
let d = t.position - anchor;
if best.is_none_or(|b| d.abs() < b.abs() - TIE) {
best = Some(d);
@@ -376,7 +433,7 @@ impl SnapTargets {
let hit = self
.targets
.iter()
.filter(|t| t.along == along && kinds.contains(t.kind) && (t.position - moved).abs() < 1e-6)
.filter(|t| t.along == along && kinds.contains(t.kind) && reaches(t, Some(other)) && (t.position - moved).abs() < 1e-6)
.min_by_key(|t| u8::from(t.kind != SnapKind::Guide));
if let Some(t) = hit {
lines.push(line(t, other.0, other.1));
+2
View File
@@ -177,6 +177,8 @@ pub enum Intent {
Text(Arc<str>),
/// Tab in a component whose key filter keeps it.
Tab,
/// Shift+Tab in a document canvas's editor part that keeps Tab.
BackTab,
/// An edit command the focused component lists.
Edit(EditCommand),
/// Switch to the next or previous page.
+6
View File
@@ -39,6 +39,12 @@ pub trait ItemLayout {
None
}
/// `NavShape::RaggedGrid`: the columns a vertical move from row `from` to row `to` shifts the column by, when the rows
/// are offset against each other; 0 when they line up.
fn column_shift(&self, _from: usize, _to: usize) -> isize {
0
}
/// Whether item `at` takes a place in the layout; a hidden item (in a closed group) cannot take the lead.
fn shown(&self, _at: usize) -> bool {
true
+4
View File
@@ -178,6 +178,10 @@ impl<K> NavOutline for Outline<'_, K> {
self.layout.and_then(|layout| layout.row_len(row))
}
fn column_shift(&self, from: usize, to: usize) -> isize {
self.layout.map_or(0, |layout| layout.column_shift(from, to))
}
fn columns(&self) -> usize {
self.columns
}
+9 -2
View File
@@ -64,6 +64,12 @@ pub trait NavOutline {
None
}
/// `RaggedGrid`: how many columns a vertical move from row `from` to row `to` shifts the column by, for rows that are
/// offset against each other (a honeycomb's). 0 for rows that line up.
fn column_shift(&self, _from: usize, _to: usize) -> isize {
0
}
/// `Cell`: the cells of every position (a row of a sheet).
fn columns(&self) -> usize {
1
@@ -325,8 +331,9 @@ fn ragged(outline: &dyn NavOutline, state: &NavState, lead: usize, mv: NavMove)
let Some((row, column, _)) = locate(outline, lead) else { return NavStep::Unhandled };
let rows = (0..).take_while(|&r| outline.row_len(r).is_some()).count();
// A row without a position that takes the lead (a closed group's) is passed over in the move's direction.
let toward = |rows: Vec<usize>| moved(rows.into_iter().find_map(|row| ragged_at(outline, row, column)));
let vertical = |to: Option<usize>| moved(to.and_then(|row| ragged_at(outline, row, column)));
let shifted = |to: usize| column.saturating_add_signed(outline.column_shift(row, to));
let toward = |rows: Vec<usize>| moved(rows.into_iter().find_map(|to| ragged_at(outline, to, shifted(to))));
let vertical = |to: Option<usize>| moved(to.and_then(|to| ragged_at(outline, to, shifted(to))));
match mv {
NavMove::Back => moved(neighbour(outline, state, lead, false)),
NavMove::Forward => moved(neighbour(outline, state, lead, true)),
+41 -2
View File
@@ -1,6 +1,6 @@
//! The fit rules: tab widths (`fit`).
//! The fit rules: tab widths (`fit`) and strip items (`fit_items`).
use craft_behavior::fit::{TabFit, fit};
use craft_behavior::fit::{FitItem, FitKeep, TabFit, fit, fit_items};
fn total(fit: &TabFit) -> f32 {
fit.shown.iter().map(|&(_, width)| width).sum::<f32>() + fit.overflow_width
@@ -25,6 +25,45 @@ fn overflow_retains_selection_and_partitions_all_tabs() {
}
}
/// Guards the shortening stage of `fit_items`: short forms go last first, before any free item leaves, a leaving item
/// is not reported short, and items without a short form fit exactly as before (the menu bar, bar items and
/// breadcrumbs build no short forms).
#[test]
fn short_items_shorten_from_the_end_before_any_item_leaves() {
let item = |extent| FitItem::new(extent, 0, FitKeep::Free);
let shortening = [item(50.0).short(20.0), item(50.0), item(50.0).short(20.0)];
let plain = [item(50.0), item(50.0), item(50.0)];
let at = |items: &[FitItem], available| fit_items(items, available, 0.0, 0.0, 10.0);
let wide = at(&shortening, 150.0);
assert!(wide.short.is_empty() && wide.overflow.is_empty(), "a run that fits keeps every full form: {wide:?}");
let narrower = at(&shortening, 120.0);
assert!(narrower.overflow.is_empty(), "shortening comes before any item leaves: {narrower:?}");
assert!(narrower.short.contains(&2) && !narrower.short.contains(&0), "the last short item goes first: {narrower:?}");
let narrow = at(&shortening, 90.0);
assert!(narrow.overflow.is_empty(), "every short form is taken before an item leaves: {narrow:?}");
assert!(narrow.short.contains(&0) && narrow.short.contains(&2), "then the earlier ones: {narrow:?}");
let narrowest = at(&shortening, 80.0);
assert!(narrowest.overflow.contains(&2) && narrowest.shown.contains(&0), "then the last free item leaves: {narrowest:?}");
assert!(narrowest.short.iter().all(|i| narrowest.shown.contains(i)), "a leaving item is not short: {narrowest:?}");
for available in [0.0, 40.0, 80.0, 90.0, 120.0, 150.0] {
let fit = at(&plain, available);
assert!(fit.short.is_empty(), "no short form, no short item: {fit:?}");
let shown = shortening.len() - fit.overflow.len();
assert_eq!(fit.shown, (0..shown).collect::<Vec<_>>(), "items without short forms leave from the end: {fit:?}");
}
assert!(!at(&plain, 120.0).overflow.is_empty(), "without short forms the narrower run overflows");
let pinned = [FitItem::new(80.0, 0, FitKeep::Pinned).short(30.0), FitItem::new(90.0, 0, FitKeep::Pinned).short(30.0)];
let squeezed = fit_items(&pinned, 40.0, 0.0, 0.0, 0.0);
assert!(squeezed.overflow.is_empty(), "pinned items never leave: {squeezed:?}");
assert_eq!(squeezed.short.len(), 2, "pinned items shorten as free ones do: {squeezed:?}");
}
#[test]
fn kept_selection_keeps_its_width_and_overflow_starts_at_the_end() {
let natural = [80.0, 90.0, 85.0, 95.0, 70.0];
+23
View File
@@ -92,6 +92,29 @@ fn a_distort_corner_stops_before_the_box_folds() {
assert_eq!(q, [p(5.0, 5.0), p(1.0, 0.0), p(2.0, 0.0), p(3.0, 0.0)]);
}
#[test]
fn a_corners_box_keeps_a_corner_proportional_until_shift_and_stretches_an_edge_on_one_axis() {
let linked = BoxRules::default().with_scale(ScaleRule::Corners);
let unlinked = linked.with_aspect_linked(false);
for rules in [&linked, &unlinked] {
// A plain corner keeps the proportions along the diagonal, whatever the aspect link says.
let kept = dragged(p(100.0, 50.0), p(200.0, 60.0), Mods::NONE, rules);
assert!(corners_are(&kept, 0.0, 0.0, 184.0, 92.0), "{:?}", kept.quad);
// ⇧ frees them.
let freed = dragged(p(100.0, 50.0), p(200.0, 60.0), Mods::SHIFT, rules);
assert!(corners_are(&freed, 0.0, 0.0, 200.0, 60.0), "{:?}", freed.quad);
// The right edge's middle stretches only x, with ⇧ or without.
for mods in [Mods::NONE, Mods::SHIFT] {
let edge = dragged(p(100.0, 25.0), p(150.0, 40.0), mods, rules);
assert!(corners_are(&edge, 0.0, 0.0, 150.0, 50.0), "{mods:?}: {:?}", edge.quad);
}
}
// A ⌘ corner distorts as it does under the default rule: the gesture is left alone.
let distorted = dragged(p(100.0, 50.0), p(200.0, 60.0), Mods::CMD, &linked);
assert_eq!(distorted, dragged(p(100.0, 50.0), p(200.0, 60.0), Mods::CMD, &BoxRules::default()));
assert!(near(distorted.quad[2], p(200.0, 60.0)) && near(distorted.quad[0], p(0.0, 0.0)), "{:?}", distorted.quad);
}
#[test]
fn a_shape_box_scales_corners_by_the_diagonal_and_edges_on_one_axis() {
// The reference measurement: the bounds 100,98–723,451, the bottom-right handle dragged by
+26 -1
View File
@@ -2,7 +2,7 @@
use craft_behavior::Axis;
use craft_behavior::geometry::{SnapKind, SnapKinds, SnapTarget, SnapTargets};
use kurbo::{Rect, Vec2};
use kurbo::{Point, Rect, Vec2};
fn guide(along: Axis, position: f64) -> SnapTarget {
SnapTarget::new(along, position, SnapKind::Guide)
@@ -31,3 +31,28 @@ fn a_moving_rect_skips_the_kinds_left_out() {
let (offset, lines) = targets.snap_rect_of(rect, 4.0, SnapKinds::ALL.without(SnapKind::Selection));
assert_eq!((offset, lines.len()), (Vec2::ZERO, 0), "a moved selection ignores the selection's edges");
}
#[test]
fn a_spanned_target_catches_only_a_box_that_overlaps_its_span_on_the_other_axis() {
let mut targets = SnapTargets::new();
// A layer on page 2: its left edge at x 100 spans y 1200 to 1300.
targets.add_rect(Rect::new(100.0, 1200.0, 300.0, 1300.0), SnapKind::LayerEdge, SnapKind::LayerCenter);
targets.add(guide(Axis::Y, 400.0));
// Over page 1, 2 units right of the edge's line but far from its span: no snap.
let (offset, lines) = targets.snap_rect(Rect::new(102.0, 50.0, 150.0, 90.0), 4.0);
assert_eq!((offset, lines.len()), (Vec2::ZERO, 0), "a box over page 1 is not caught by page 2's layer");
// Beside the layer on page 2: caught.
let (offset, _) = targets.snap_rect(Rect::new(102.0, 1210.0, 150.0, 1240.0), 4.0);
assert_eq!(offset.x, -2.0, "a box overlapping the span snaps to the edge");
// A point the same way.
let (at, lines) = targets.snap_point(Point::new(102.0, 60.0), 4.0);
assert_eq!((at, lines.len()), (Point::new(102.0, 60.0), 0));
let (at, _) = targets.snap_point(Point::new(102.0, 1250.0), 4.0);
assert_eq!(at.x, 100.0);
// A full-height guide catches a box anywhere along it.
let (offset, _) = targets.snap_rect(Rect::new(402.0, 50.0, 450.0, 90.0), 4.0);
assert_eq!(offset.x, -2.0, "an unspanned target is unchanged");
}
+71 -5
View File
@@ -1,4 +1,4 @@
//! `FolderCache`: roots and subfolder listings made in jobs, kept until they go stale.
//! `FolderCache`: roots, subfolder and entries listings made in jobs, kept until they go stale.
use std::collections::{HashMap, HashSet};
use std::path::{Path, PathBuf};
@@ -7,7 +7,7 @@ use std::sync::Arc;
use craft_host::queue::{JobQueue, Priority, QueueOptions};
use craft_host::{Jobs, Wake};
use super::{Directories, Folder, StandardFolder, Volume};
use super::{Directories, Entry, Folder, FolderEntries, StandardFolder, Volume};
/// The standard folders and volumes, from one job.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
@@ -29,11 +29,28 @@ pub enum Listing<'a> {
Failed(&'a str),
}
/// One folder's files and folders as the cache has them.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Entries<'a> {
/// Not listed yet; a job is queued.
Loading,
/// The entries, and whether the listing stopped at its limit.
Ready {
/// The files and folders.
entries: &'a [Entry],
/// The listing stopped at the limit before the folder ended.
truncated: bool,
},
/// The folder couldn't be listed; the system's message.
Failed(&'a str),
}
/// What a listing job returns.
enum Found {
Roots(Roots),
Subfolders(Result<Vec<Folder>, String>),
Unlisted(Vec<PathBuf>),
Entries(Result<FolderEntries, String>),
}
/// Which listing a job makes.
@@ -42,6 +59,8 @@ enum Job {
Roots,
Subfolders(PathBuf),
Unlisted(PathBuf),
/// A folder's files and folders, up to a limit of entries read.
Entries(PathBuf, usize),
}
/// Folder listings for a places tree, made in jobs on a [`JobQueue`] (lanes from
@@ -62,6 +81,8 @@ pub struct FolderCache {
roots: Option<Roots>,
listings: HashMap<PathBuf, (Result<Vec<Folder>, String>, bool)>,
unlisted: HashMap<PathBuf, Vec<PathBuf>>,
/// Files and folders by (folder, limit), each with its stale flag like `listings`.
entries: HashMap<(PathBuf, usize), (Result<FolderEntries, String>, bool)>,
stale_roots: bool,
/// What this pass asked for, for [`finish_pass`](Self::finish_pass).
asked: HashSet<Job>,
@@ -82,6 +103,7 @@ impl FolderCache {
roots: None,
listings: HashMap::new(),
unlisted: HashMap::new(),
entries: HashMap::new(),
stale_roots: false,
asked: HashSet::new(),
generations: HashMap::new(),
@@ -118,6 +140,31 @@ impl FolderCache {
}
}
/// `folder`'s files and folders up to `limit` entries, listed in a job like
/// [`subfolders`](Self::subfolders); the cache keys a listing by folder and limit.
pub fn entries(&mut self, folder: &Path, limit: usize) -> Entries<'_> {
// ui-egui: crates/ui-egui/src/file_browser.rs:58 (`list_dir`, read in the pass there; in a job here).
self.drain();
let key = (folder.to_path_buf(), limit);
let job = Job::Entries(key.0.clone(), limit);
self.asked.insert(job.clone());
match self.entries.get(&key).map(|(_, stale)| *stale) {
None => self.submit(job, Priority::VISIBLE),
Some(true) => self.submit(job, Priority::NEAR),
Some(false) => {}
}
self.held_entries(folder, limit).unwrap_or(Entries::Loading)
}
/// The listing of `folder` at `limit` the cache holds now, without taking in finished jobs or queueing one: for a
/// reader that cannot borrow the cache mutably (automation). `None` when none is held.
pub fn held_entries(&self, folder: &Path, limit: usize) -> Option<Entries<'_>> {
self.entries.get(&(folder.to_path_buf(), limit)).map(|(result, _)| match result {
Ok(found) => Entries::Ready { entries: &found.entries, truncated: found.truncated },
Err(message) => Entries::Failed(message),
})
}
/// The hidden folders on the way to `path` ([`Directories::unlisted_ancestors`]); `None` until
/// listed.
pub fn unlisted(&mut self, path: &Path) -> Option<&[PathBuf]> {
@@ -141,17 +188,31 @@ impl FolderCache {
for (_, stale) in self.listings.values_mut() {
*stale = true;
}
for (_, stale) in self.entries.values_mut() {
*stale = true;
}
}
/// Marks one folder's listing stale.
/// Marks one folder's listings stale: its subfolders and its entries at every limit.
pub fn refresh_folder(&mut self, folder: &Path) {
// new: the tree calls it when a row opens.
if let Some(generation) = self.generations.get_mut(&Job::Subfolders(folder.to_path_buf())) {
*generation += 1;
for (job, generation) in &mut self.generations {
let of_folder = match job {
Job::Subfolders(path) | Job::Entries(path, _) => path == folder,
Job::Roots | Job::Unlisted(_) => false,
};
if of_folder {
*generation += 1;
}
}
if let Some((_, stale)) = self.listings.get_mut(folder) {
*stale = true;
}
for ((path, _), (_, stale)) in &mut self.entries {
if path == folder {
*stale = true;
}
}
}
/// Drops the listings of folders not asked for since the last call, and cancels their jobs
@@ -161,6 +222,7 @@ impl FolderCache {
let asked = std::mem::take(&mut self.asked);
self.listings.retain(|path, _| asked.contains(&Job::Subfolders(path.clone())));
self.unlisted.retain(|path, _| asked.contains(&Job::Unlisted(path.clone())));
self.entries.retain(|(path, limit), _| asked.contains(&Job::Entries(path.clone(), *limit)));
self.queue.reprioritize(|job, priority| asked.contains(job).then_some(priority));
self.generations.retain(|job, _| *job == Job::Roots || asked.contains(job));
}
@@ -178,6 +240,7 @@ impl FolderCache {
Job::Roots => Found::Roots(Roots { standard: directories.standard(), volumes: directories.volumes() }),
Job::Subfolders(folder) => Found::Subfolders(directories.subfolders(&folder, cancel).map_err(|e| e.to_string())),
Job::Unlisted(path) => Found::Unlisted(directories.unlisted_ancestors(&path)),
Job::Entries(folder, limit) => Found::Entries(directories.entries(&folder, limit, cancel).map_err(|e| e.to_string())),
};
(generation, found)
});
@@ -203,6 +266,9 @@ impl FolderCache {
(Job::Unlisted(path), Found::Unlisted(found)) => {
self.unlisted.insert(path, found);
}
(Job::Entries(folder, limit), Found::Entries(result)) => {
self.entries.insert((folder, limit), (result, !current));
}
_ => {}
}
}
+132 -2
View File
@@ -50,6 +50,26 @@ pub struct Folder {
pub name: String,
}
/// A file or folder in a [`FolderEntries`] listing.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Entry {
/// Its path.
pub path: PathBuf,
/// Its name.
pub name: String,
/// Whether it is a folder.
pub folder: bool,
}
/// The files and folders of one folder, as [`Directories::entries`] lists them.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct FolderEntries {
/// The entries read, hidden ones left out, in `natural_cmp` order of their names.
pub entries: Vec<Entry>,
/// The listing stopped at the limit before the folder ended.
pub truncated: bool,
}
/// The folder lookups a places tree needs (owner question 4: a small trait in this crate, with a
/// system implementation and a fake). Every call can block on a slow or network disk:
/// [`FolderCache`](super::FolderCache) calls them only in jobs.
@@ -70,6 +90,11 @@ pub trait Directories: Send + Sync {
/// The hidden folders among `path` and its ancestors, innermost first (LightCraft's
/// `unlisted_ancestors`); a tree never opens through one.
fn unlisted_ancestors(&self, path: &Path) -> Vec<PathBuf>;
/// The files and folders of `folder`, with the hidden rule and the `natural_cmp` order of
/// [`subfolders`](Self::subfolders). Stops after `limit` entries read and reports
/// `truncated`; checks `cancel` between entries.
fn entries(&self, folder: &Path, limit: usize, cancel: &Cancel) -> io::Result<FolderEntries>;
}
/// [`Directories`] over the file system.
@@ -79,7 +104,7 @@ pub trait Directories: Send + Sync {
/// - `volumes`: macOS the entries of `/Volumes`; Linux `/media/$USER/*`, `/run/media/$USER/*` and
/// `/mnt/*`; Windows the drive letters `A:` to `Z:` whose root exists. `network` and `removable`
/// stay false where `std` can't tell (a platform service may add them later).
/// - `subfolders`: `std::fs::read_dir`, as the trait says.
/// - `subfolders` and `entries`: `std::fs::read_dir`, as the trait says.
#[cfg(not(target_arch = "wasm32"))]
#[derive(Clone, Copy, Debug, Default)]
pub struct SystemDirectories;
@@ -162,6 +187,33 @@ impl Directories for SystemDirectories {
Ok(out)
}
fn entries(&self, folder: &Path, limit: usize, cancel: &Cancel) -> io::Result<FolderEntries> {
// ui-egui: crates/ui-egui/src/file_browser.rs:58 (`list_dir`: `MAX_SCANNED` entries read, hidden left out, links to folders are folders).
let mut out = FolderEntries::default();
for (read, entry) in std::fs::read_dir(folder)?.enumerate() {
if cancel.is_cancelled() {
break;
}
// Hidden entries count as read too: the limit bounds the time a huge folder takes.
if read >= limit {
out.truncated = true;
break;
}
let Ok(entry) = entry else { continue };
let path = entry.path();
let folder = match entry.file_type() {
Ok(t) if t.is_symlink() => path.is_dir(),
Ok(t) => t.is_dir(),
Err(_) => continue,
};
if !is_hidden(&path, || entry.metadata()) {
out.entries.push(Entry { name: entry.file_name().to_string_lossy().into_owned(), path, folder });
}
}
out.entries.sort_by(|a, b| craft_platform::open::natural_cmp(&a.name, &b.name));
Ok(out)
}
fn unlisted_ancestors(&self, path: &Path) -> Vec<PathBuf> {
// lightcraft: crates/ui-egui/src/panels/left/local.rs:201 (`unlisted_ancestors`).
path.ancestors().filter(|p| is_hidden(p, || std::fs::symlink_metadata(p))).map(Path::to_path_buf).collect()
@@ -177,7 +229,7 @@ fn home() -> Option<PathBuf> {
// lightcraft: crates/engine/src/walk.rs:56 (`hidden_with_metadata`).
#[cfg(not(target_arch = "wasm32"))]
fn is_hidden(path: &Path, metadata: impl FnOnce() -> io::Result<std::fs::Metadata>) -> bool {
if path.file_name().is_some_and(|n| n.to_string_lossy().starts_with('.')) {
if dotted(path) {
return true;
}
#[cfg(windows)]
@@ -199,6 +251,12 @@ fn is_hidden(path: &Path, metadata: impl FnOnce() -> io::Result<std::fs::Metadat
}
}
/// Whether the path's name starts with a dot: the part of the hidden rule a name alone tells, so
/// [`FakeDirectories`] hides what [`SystemDirectories`] hides on every platform.
fn dotted(path: &Path) -> bool {
path.file_name().is_some_and(|n| n.to_string_lossy().starts_with('.'))
}
/// [`Directories`] over an in-memory tree, for tests and stories. Folders are added with
/// [`folder`](Self::folder) (their ancestors are implied) and can be added or removed through a
/// shared reference while a cache holds it.
@@ -207,6 +265,10 @@ pub struct FakeDirectories {
standard: Vec<(StandardFolder, PathBuf)>,
volumes: Vec<Volume>,
children: Mutex<BTreeMap<PathBuf, BTreeSet<String>>>,
/// Files, by their folder; only [`entries`](Directories::entries) lists them.
files: Mutex<BTreeMap<PathBuf, BTreeSet<String>>>,
/// Links, by path, to their target.
links: BTreeMap<PathBuf, PathBuf>,
unlisted: Vec<PathBuf>,
failing: Vec<PathBuf>,
calls: AtomicUsize,
@@ -239,6 +301,41 @@ impl FakeDirectories {
self
}
/// The file at `path`, with its folder and that folder's ancestors.
/// [`entries`](Directories::entries) lists it; [`subfolders`](Directories::subfolders) does
/// not.
#[must_use]
pub fn file(self, path: impl AsRef<Path>) -> Self {
let path = path.as_ref();
if let (Some(parent), Some(name)) = (path.parent(), path.file_name()) {
self.add_folder(parent);
let mut files = self.files.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
files.entry(parent.to_path_buf()).or_default().insert(name.to_string_lossy().into_owned());
}
self
}
/// Removes the file at `path`; later listings leave it out.
pub fn remove_file(&self, path: impl AsRef<Path>) {
let path = path.as_ref();
let (Some(parent), Some(name)) = (path.parent(), path.file_name()) else { return };
if let Some(names) = self.files.lock().unwrap_or_else(std::sync::PoisonError::into_inner).get_mut(parent) {
names.remove(&*name.to_string_lossy());
}
}
/// A link at `path` to `target`. [`entries`](Directories::entries) lists it as a folder when
/// `target` is a folder of this tree, else as a file.
#[must_use]
pub fn link(mut self, path: impl AsRef<Path>, target: impl Into<PathBuf>) -> Self {
let path = path.as_ref();
if let Some(parent) = path.parent() {
self.add_folder(parent);
}
self.links.insert(path.to_path_buf(), target.into());
self
}
/// A hidden folder: `unlisted_ancestors` reports it for paths inside it.
#[must_use]
pub fn hidden(mut self, path: impl Into<PathBuf>) -> Self {
@@ -299,6 +396,39 @@ impl Directories for FakeDirectories {
Ok(out)
}
fn entries(&self, folder: &Path, limit: usize, cancel: &Cancel) -> io::Result<FolderEntries> {
if self.failing.iter().any(|p| p == folder) {
return Err(io::Error::new(io::ErrorKind::PermissionDenied, "permission denied"));
}
let children = self.children.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
let is_folder = |path: &Path| {
children.contains_key(path)
|| matches!((path.parent(), path.file_name()), (Some(parent), Some(name)) if children.get(parent).is_some_and(|names| names.contains(&*name.to_string_lossy())))
};
// The read order of this fake: folders, files, then links, each by name.
let folders = children.get(folder).into_iter().flatten().map(|n| (folder.join(n), true));
let file_names = self.files.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
let files = file_names.get(folder).into_iter().flatten().map(|n| (folder.join(n), false));
let links = self.links.iter().filter(|(path, _)| path.parent() == Some(folder)).map(|(path, target)| (path.clone(), is_folder(target)));
let mut out = FolderEntries::default();
for (read, (path, is_dir)) in folders.chain(files).chain(links).enumerate() {
if cancel.is_cancelled() {
break;
}
if read >= limit {
out.truncated = true;
break;
}
if dotted(&path) {
continue;
}
let name = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
out.entries.push(Entry { path, name, folder: is_dir });
}
out.entries.sort_by(|a, b| craft_platform::open::natural_cmp(&a.name, &b.name));
Ok(out)
}
fn unlisted_ancestors(&self, path: &Path) -> Vec<PathBuf> {
path.ancestors().filter(|a| self.unlisted.iter().any(|h| h == a)).map(Path::to_path_buf).collect()
}
+2 -2
View File
@@ -21,10 +21,10 @@ mod tests;
use std::path::{Path, PathBuf};
pub use cache::{FolderCache, Listing, Roots};
pub use cache::{Entries, FolderCache, Listing, Roots};
#[cfg(not(target_arch = "wasm32"))]
pub use directories::SystemDirectories;
pub use directories::{Directories, FakeDirectories, Folder, StandardFolder, Volume};
pub use directories::{Directories, Entry, FakeDirectories, Folder, FolderEntries, StandardFolder, Volume};
/// What kind of root a place is; the tree's icon, name and menu follow from it.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
+57
View File
@@ -163,3 +163,60 @@ fn a_listing_started_before_a_refresh_is_listed_again() {
assert!(cache.roots().is_some());
assert_eq!(jobs.waiting(), 0, "the refreshed roots landed fresh");
}
fn entries_of(entries: Entries<'_>) -> (Vec<(String, bool)>, bool) {
match entries {
Entries::Ready { entries, truncated } => (entries.iter().map(|e| (e.name.clone(), e.folder)).collect(), truncated),
other => panic!("not ready: {other:?}"),
}
}
// The listing half of WordCraft's `listing_filters_sorts_and_caps`: files and folders in one natural order, hidden ones out, a link to a folder is a folder, a limit cuts off and says so.
#[trial]
fn a_folder_listing_with_files_skips_hidden_entries_and_counts_links_to_folders() {
let fake = Arc::new(
FakeDirectories::new()
.folder("/d/zeta")
.folder("/d/.git")
.folder("/target")
.file("/d/file10.txt")
.file("/d/file2.txt")
.file("/d/.hidden.txt")
.file("/d/Alpha.txt")
.link("/d/shortcut", "/target")
.link("/d/doc-link", "/d/file2.txt"),
);
let jobs = Arc::new(ManualJobs::new());
let mut cache = FolderCache::new(fake.clone(), jobs.clone(), Wake::new(|| {}));
let dir = Path::new("/d");
assert_eq!(cache.entries(dir, 100), Entries::Loading, "nothing is read in the pass");
jobs.run_all();
let (listed, truncated) = entries_of(cache.entries(dir, 100));
let expected = [("Alpha.txt", false), ("doc-link", false), ("file2.txt", false), ("file10.txt", false), ("shortcut", true), ("zeta", true)];
assert_eq!(listed, expected.map(|(n, f)| (n.to_string(), f)));
assert!(!truncated, "eight entries read, none left over");
// Exactly the limit read: the folder ended, so nothing was cut off.
assert_eq!(cache.entries(dir, 8), Entries::Loading);
jobs.run_all();
assert!(!entries_of(cache.entries(dir, 8)).1);
// Hidden entries count as read: three read (`.git`, `zeta`, `.hidden.txt`), one shown.
assert_eq!(cache.entries(dir, 3), Entries::Loading, "another limit is another listing");
jobs.run_all();
let (listed, truncated) = entries_of(cache.entries(dir, 3));
assert_eq!(listed, [("zeta".to_string(), true)]);
assert!(truncated);
// A folder of files only lists them; an unreadable folder reports why.
let fake = Arc::new(FakeDirectories::new().file("/e/a.txt"));
let mut cache = FolderCache::new(fake, jobs.clone(), Wake::new(|| {}));
let failing = Arc::new(FakeDirectories::new().failing("/e"));
let mut broken = FolderCache::new(failing, jobs.clone(), Wake::new(|| {}));
assert_eq!(cache.entries(Path::new("/e"), 10), Entries::Loading);
assert_eq!(broken.entries(Path::new("/e"), 10), Entries::Loading);
jobs.run_all();
assert_eq!(entries_of(cache.entries(Path::new("/e"), 10)).0, [("a.txt".to_string(), false)]);
assert!(matches!(broken.entries(Path::new("/e"), 10), Entries::Failed(_)), "an unreadable folder fails, never panics");
}
+136
View File
@@ -282,6 +282,77 @@ pub fn is_text_code_page(code_page: u16) -> bool {
is_byte_code_page(code_page) || is_multibyte_code_page(code_page)
}
/// The character Word on Windows types for an Alt+numpad code (decimal digits, as typed):
/// - with a leading 0 and a value up to 255, the ANSI code page's character (`ansi`, one of
/// [`SINGLE_BYTE_CODE_PAGES`]): `0233` → é and `0128` → € in Windows-1252, `0185` → ą in 1250;
/// - without one, 1–255 is the OEM code page's character (`oem`, one of [`OEM_CODE_PAGES`]):
/// `233` → Θ in 437, Ú in 850 (é is `130` in both), `165` → ą in 852; 1–31 and 127 are the
/// code page's glyphs (`1` → ☺, `7` → •);
/// - above 255, with or without the 0, the Unicode character with that decimal value
/// (`8364` → €), as Word inserts it.
///
/// `None` for an empty or non-numeric code, 0, a control character, a byte the code page leaves
/// unassigned or a value past Unicode.
pub fn alt_code_char(code: &str, ansi: u16, oem: u16) -> Option<char> {
if code.is_empty() || !code.bytes().all(|b| b.is_ascii_digit()) {
return None;
}
let digits = code.trim_start_matches('0');
// More than seven significant digits is past U+10FFFF (1114111).
if digits.len() > 7 {
return None;
}
let value: u32 = if digits.is_empty() { 0 } else { digits.parse().ok()? };
let c = match u8::try_from(value) {
Ok(0) => return None,
Ok(b) if code.starts_with('0') => windows_byte(ansi, b),
Ok(b) => oem_byte(oem, b),
Err(_) => char::from_u32(value)?,
};
Some(c).filter(|c| codeable(*c) && *c != '\u{FFFD}')
}
/// The (ANSI, OEM) code pages Windows uses for a locale (BCP 47 tag or POSIX name; `None` for
/// none), limited to the pages [`alt_code_char`] decodes: Windows-1252 and OEM 437 for US
/// English, unknown locales and those with other pages (Asian double-byte pages, OEM
/// 775/720/862…).
pub fn windows_code_pages(locale: Option<&str>) -> (u16, u16) {
let Some(tag) = locale else { return (1252, 437) };
let parts: Vec<&str> = tag.split(['-', '_', '.', '@']).collect();
let lang = parts.first().copied().unwrap_or_default().to_ascii_lowercase();
let rest = parts.get(1..).unwrap_or_default();
let region = rest.iter().find(|p| p.len() == 2 && p.chars().all(|c| c.is_ascii_alphabetic())).map(|r| r.to_ascii_uppercase());
let script = rest.iter().find(|p| p.len() == 4 && p.chars().all(|c| c.is_ascii_alphabetic())).map(|r| r.to_ascii_lowercase());
const WESTERN: [&str; 18] = ["ca", "da", "de", "es", "eu", "fi", "fo", "fr", "ga", "gl", "is", "it", "nb", "nl", "nn", "no", "pt", "sv"];
match lang.as_str() {
"en" => match region.as_deref() {
None | Some("US") => (1252, 437),
Some(_) => (1252, 850),
},
l if WESTERN.contains(&l) => (1252, 850),
"pl" | "cs" | "sk" | "hu" | "sl" | "hr" | "ro" | "sq" | "bs" => (1250, 852),
"sr" if script.as_deref() == Some("latn") => (1250, 852),
"ru" | "uk" | "be" | "bg" => (1251, 866),
// Macedonian and Cyrillic Serbian use OEM 855, which isn't decoded.
"sr" | "mk" => (1251, 437),
"el" => (1253, 737),
"az" if script.as_deref() == Some("cyrl") => (1251, 866),
"tr" | "az" => (1254, 857),
"he" => (1255, 437),
"ar" | "fa" | "ur" => (1256, 437),
"et" | "lv" | "lt" => (1257, 437),
"vi" => (1258, 437),
"th" => (874, 437),
_ => (1252, 437),
}
}
/// Characters Alt+numpad types: not control characters (breaks included) and not the object
/// placeholder U+FFFC, which a document reserves for embedded objects.
fn codeable(c: char) -> bool {
!c.is_control() && c != '\u{FFFC}'
}
/// The code page of an RTF or Word font charset (`\fcharset`): 204 Russian → 1251, 238 Eastern
/// European → 1250, 77 Mac → 10000, 254 PC / 255 OEM → 437, 128 Japanese → 932, 129 Korean → 949,
/// 134 Simplified Chinese → 936, 136 Traditional Chinese → 950, 2 Symbol → [`SYMBOL_CODE_PAGE`]…
@@ -437,4 +508,69 @@ mod tests {
}
}
}
#[test]
fn alt_numpad_codes_map_like_word_on_windows() {
let c = |code| alt_code_char(code, 1252, 437);
// Leading 0: Windows-1252.
assert_eq!(c("0233"), Some('é'));
assert_eq!(c("0128"), Some('€'));
assert_eq!(c("0150"), Some('–'));
assert_eq!(c("065"), Some('A'));
assert_eq!(c("0032"), Some(' '));
assert_eq!(c("0255"), Some('ÿ'));
// No leading 0: the OEM code page (437 here, 850 in Western Europe).
assert_eq!(c("233"), Some('Θ'));
// The CP850 mapping file has Ú at 0xE9 (é is 130 in both).
assert_eq!(alt_code_char("233", 1252, 850), Some('Ú'));
assert_eq!(alt_code_char("130", 1252, 850), Some('é'));
assert_eq!(c("130"), Some('é'));
assert_eq!(alt_code_char("155", 1252, 850), Some('ø'));
assert_eq!(c("155"), Some('¢'));
assert_eq!(c("65"), Some('A'));
assert_eq!(c("1"), Some('☺'));
assert_eq!(c("7"), Some('•'));
assert_eq!(c("127"), Some('⌂'));
assert_eq!(c("176"), Some('░'));
// Above 255: the Unicode character with that decimal value.
assert_eq!(c("8364"), Some('€'));
assert_eq!(c("09733"), Some('★'));
assert_eq!(c("128512"), Some('😀'));
// Nothing for junk, 0, control characters, surrogates or values past Unicode.
for bad in ["", "0", "000", "0009", "0013", "0127", "0129", "x1", "-5", "55296", "1114112", "99999999999999999999", "4294967361"] {
assert_eq!(c(bad), None, "{bad:?}");
}
// The object placeholder is not typed.
assert_eq!(c("65532"), None);
}
#[test]
fn alt_numpad_codes_follow_the_system_code_pages() {
// Polish (1250/852): Alt+0185 and Alt+165 are both ą, not ¹ / Ñ.
assert_eq!(alt_code_char("0185", 1250, 852), Some('ą'));
assert_eq!(alt_code_char("165", 1250, 852), Some('ą'));
assert_eq!(alt_code_char("0185", 1252, 437), Some('¹'));
// Russian (1251/866), Greek (1253/737), Turkish (1254/857).
assert_eq!(alt_code_char("0207", 1251, 866), Some('П'));
assert_eq!(alt_code_char("143", 1251, 866), Some('П'));
assert_eq!(alt_code_char("0193", 1253, 737), Some('Α'));
assert_eq!(alt_code_char("128", 1253, 737), Some('Α'));
assert_eq!(alt_code_char("0253", 1254, 857), Some('ı'));
assert_eq!(alt_code_char("141", 1254, 857), Some('ı'));
// Above 255 the code page doesn't matter.
assert_eq!(alt_code_char("8364", 1251, 866), Some('€'));
// A byte the code page leaves unassigned types nothing.
assert_eq!(alt_code_char("213", 1254, 857), None);
assert_eq!(alt_code_char("0219", 874, 437), None);
assert_eq!(windows_code_pages(None), (1252, 437));
assert_eq!(windows_code_pages(Some("en-US")), (1252, 437));
assert_eq!(windows_code_pages(Some("en_GB.UTF-8")), (1252, 850));
assert_eq!(windows_code_pages(Some("de-DE")), (1252, 850));
assert_eq!(windows_code_pages(Some("pl-PL")), (1250, 852));
assert_eq!(windows_code_pages(Some("sr-Latn-RS")), (1250, 852));
assert_eq!(windows_code_pages(Some("ru_RU.UTF-8")), (1251, 866));
assert_eq!(windows_code_pages(Some("el-GR")), (1253, 737));
assert_eq!(windows_code_pages(Some("tr-TR")), (1254, 857));
assert_eq!(windows_code_pages(Some("ja-JP")), (1252, 437));
}
}
+11 -10
View File
@@ -225,24 +225,25 @@ fn paint_field(painter: &ContentPainterCx, plot: Rect, mode: AreaMode, base: &Mo
let mut mesh = Mesh::default();
match levels {
Some(levels) => flat_cells(&mut mesh, plot, &at, levels),
None => smooth_mesh(&mut mesh, plot, &at),
None => smooth_mesh(&mut mesh, plot, MESH, &at),
}
painter.painter.add(mesh);
}
/// The colours as a mesh of vertices, blending between them.
fn smooth_mesh(mesh: &mut Mesh, plot: Rect, at: &dyn Fn(f32, f32) -> craft_theme::Srgba) {
let last = (MESH - 1) as f32;
for row in 0..MESH {
for col in 0..MESH {
/// The colours as a mesh of `steps` by `steps` vertices over `plot`, blending between them; `at` gives the colour at a
/// fraction across and down.
pub fn smooth_mesh(mesh: &mut Mesh, plot: Rect, steps: usize, at: &dyn Fn(f32, f32) -> craft_theme::Srgba) {
let last = (steps - 1) as f32;
for row in 0..steps {
for col in 0..steps {
let (fx, fy) = (col as f32 / last, row as f32 / last);
mesh.colored_vertex(pos2(egui::lerp(plot.x_range(), fx), egui::lerp(plot.y_range(), fy)), at(fx, fy).into());
}
}
for row in 0..MESH - 1 {
for col in 0..MESH - 1 {
let a = (row * MESH + col) as u32;
let b = a + MESH as u32;
for row in 0..steps - 1 {
for col in 0..steps - 1 {
let a = (row * steps + col) as u32;
let b = a + steps as u32;
mesh.add_triangle(a, a + 1, b + 1);
mesh.add_triangle(a, b + 1, b);
}
+2 -2
View File
@@ -46,7 +46,7 @@ mod warning;
mod wheel;
pub use crate::AreaMode;
pub use area::{AreaShape, ColorArea, ColorAreaStyle};
pub use area::{AreaShape, ColorArea, ColorAreaStyle, smooth_mesh};
pub use channels::finite_values;
pub use choice::{ChosenColor, ColorChoice, ColorChoiceOutput, ColorChoiceWords, NamedColor};
pub use compare::{CompareSwatch, CompareSwatchOutput, CompareSwatchStyle};
@@ -73,7 +73,7 @@ pub use panel::{
ColorPanel, ColorPanelCommand, ColorPanelMenu, ColorPanelMode, ColorPanelOutput, ColorPanelRamp, ColorPanelState, ColorPanelWords, PanelTarget,
};
pub use picker::{ColorConstraint, ColorPicker, ColorPickerLayout, ColorPickerOutput, ColorPickerWords, PickedColor, ScreenPickGesture};
pub use picker_dialog::{ColorPickerDialog, ColorPickerDialogWords, ColorPickerMemory, ColorPickerResult};
pub use picker_dialog::{ColorPickerDialog, ColorPickerDialogLayout, ColorPickerDialogWords, ColorPickerMemory, ColorPickerResult, ColorPickerTab};
pub use popover::{ColorPopover, ColorPopoverOutput};
pub use profile_prompts::{ProfileAction, ProfileAnswer, ProfileMismatchDialog, ProfileMode, ProfileQuestion, ProfileStatus, ProfileWords};
pub use ramp::{ColorRamp, ColorRampOutput, ColorRampStyle, ColorRampWords, Gamut, RampKind, RampPick};
+1 -1
View File
@@ -70,7 +70,7 @@ fn paint_chip_open(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
}
/// The Solid popover with the recent colours, two swatch folders and the Color Picker… button.
#[story(PaintChip<'static>, covers = [], drive = Drive::Custom(open_popover))]
#[story(PaintChip<'static>, covers = [Open], drive = Drive::Custom(open_popover))]
fn paint_chip_open_with_recents_and_swatches(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let entry = |name: &str, rgb: [f32; 3]| SwatchEntry::new(name, SwatchColor::Rgb(rgb));
let groups = vec![
+14 -4
View File
@@ -23,6 +23,9 @@ pub(super) struct Body<'a> {
pub layout: ColorPickerLayout,
pub models: Vec<&'a dyn ColorModel>,
pub warnings: Vec<ColorWarning>,
/// Compact only: the host gave a compare colour, so the compare block stands beside the area (Word's Colors
/// dialog's New over Current). The Full layout always shows it.
pub compare: bool,
pub alpha: bool,
pub dynamic_tracks: bool,
pub eyedropper: bool,
@@ -44,7 +47,12 @@ impl<'a> Body<'a> {
let words = Env::of(ui).words::<ColorPickerWords>();
let model = self.models.iter().copied().find(|m| Some(m.id()) == pass.model);
let visible: Vec<&dyn ColorModel> = model.into_iter().chain([pass.mode.model()]).collect();
self.area_and_strip(ui, pass, &visible, AreaShape::Plot, got);
Row::new().show(ui, |ui, _| {
self.area_and_strip(ui, pass, &visible, AreaShape::Plot, got);
if self.compare {
self.compare_block(ui, pass, &words, got);
}
});
if let Some(model) = model {
FieldGroup::new(words.channels.as_str().to_owned()).labels(LabelScheme::Inspector).show(ui, |ui, _| {
let values = pass.shown.values_in(model);
@@ -119,10 +127,12 @@ impl<'a> Body<'a> {
}
}
/// The hex field, at `sizing` when given. The picker's first show focuses it, its text selected.
/// The hex field, at `sizing` when given. The picker's first show focuses it, its text selected. Enter in it
/// commits the typed digits and does not reach the dialog's OK, as in the production Colors dialog.
pub(super) fn hex_field(&self, ui: &mut Ui, pass: &Pass<'a>, words: &ColorPickerWords, sizing: Option<Sizing>, got: &mut Collected) {
let field =
TextField::hex(words.hex.as_str().to_owned(), Bind::given(pass.shows(pass.shown.color.to_rgba()))).empty(pass.shown.color.to_rgba());
let field = TextField::hex(words.hex.as_str().to_owned(), Bind::given(pass.shows(pass.shown.color.to_rgba())))
.empty(pass.shown.color.to_rgba())
.submits();
let edit = match sizing {
Some(sizing) => field.sizing(sizing),
None => field,
+3 -2
View File
@@ -84,8 +84,9 @@ impl<'a> Body<'a> {
}
/// The compare block, the colour being edited over the one the picker started from, with the warnings column after
/// it; a click on the current half or on a warning sets that colour.
fn compare_block(&self, ui: &mut Ui, pass: &Pass<'a>, words: &ColorPickerWords, got: &mut Collected) {
/// it; a click on the current half or on a warning sets that colour. The Compact layout shows it beside its area
/// when the host gives a compare colour.
pub(super) fn compare_block(&self, ui: &mut Ui, pass: &Pass<'a>, words: &ColorPickerWords, got: &mut Collected) {
let current = match pass.compare {
Mixed::Same(current) => Mixed::Same(current.color),
Mixed::Mixed => Mixed::Mixed,
+33 -6
View File
@@ -158,7 +158,7 @@ craft_ui::words! {
/// What the picker keeps between passes.
#[derive(Clone, Default)]
struct Memo {
/// The model of the Compact rows.
/// The model of the Compact rows while the host binds none ([`ColorPicker::shown_model`]).
model: Option<&'static str>,
/// What the area and strip show while the host holds no mode.
mode: AreaMode,
@@ -308,6 +308,9 @@ pub struct ColorPicker<'a> {
/// The host's answer to a screen or canvas pick, for this pass; a `Set` that keeps the picker's alpha.
#[prop]
sampled: Option<Srgba>,
/// The Compact rows' model, held by the host; kept per picker without it.
#[prop]
shown_model: Option<Bind<'a, Option<&'static str>>>,
}
impl<'a> ColorPicker<'a> {
@@ -328,6 +331,7 @@ impl<'a> ColorPicker<'a> {
warnings: Vec::new(),
constrain: None,
sampled: None,
shown_model: None,
}
}
@@ -385,11 +389,21 @@ impl<'a> ColorPicker<'a> {
warnings,
constrain,
sampled,
mut shown_model,
} = self;
let full = layout == ColorPickerLayout::Full;
let models: Vec<&'a dyn ColorModel> = models
.unwrap_or_else(|| builtin_models().into_iter().filter(|m| if full { m.default_on().full } else { m.default_on().compact }).collect());
let parts = compact::Body { layout, models: models.clone(), warnings, alpha, dynamic_tracks, eyedropper, eyedropper_busy };
let parts = compact::Body {
layout,
models: models.clone(),
warnings,
compare: compare.is_some(),
alpha,
dynamic_tracks,
eyedropper,
eyedropper_busy,
};
let mut run = Run {
name: Arc::from(label.as_str()),
full,
@@ -397,6 +411,7 @@ impl<'a> ColorPicker<'a> {
value: value.reborrow(),
mode: mode.as_mut().map(|held| held.reborrow()),
web: web_colors.as_mut().map(|held| held.reborrow()),
shown_model: shown_model.as_mut().map(|held| held.reborrow()),
constrain,
sampled,
compare,
@@ -421,6 +436,8 @@ struct Run<'s, 'a> {
value: BindMut<'s, PickedColor>,
mode: Option<BindMut<'s, AreaMode>>,
web: Option<BindMut<'s, bool>>,
/// The host's model of the Compact rows; without it `Memo.model` holds it.
shown_model: Option<BindMut<'s, Option<&'static str>>>,
constrain: Option<ColorConstraint<'a>>,
sampled: Option<Srgba>,
/// The host's compare colour.
@@ -456,14 +473,18 @@ impl<'a> Run<'_, 'a> {
}
let first_show = !memo.opened;
let model = memo.model.filter(|id| self.models.iter().any(|m| m.id() == *id)).or_else(|| self.models.first().map(|m| m.id()));
let held_model = self.shown_model.as_ref().and_then(|held| held.read(&mut *body)).and_then(|held| held.same().copied()).flatten();
let wanted = if self.shown_model.is_some() { held_model } else { memo.model };
let model = wanted.filter(|id| self.models.iter().any(|m| m.id() == *id)).or_else(|| self.models.first().map(|m| m.id()));
let focus_hex = first_show && body.resolved.enabled;
let held = self.value.read(&mut *body).and_then(|held| held.same().copied());
let first = if first_show { held } else { memo.first };
{
let memo = body.memory::<Memo>();
memo.mode = mode;
memo.model = model;
if self.shown_model.is_none() {
memo.model = model;
}
memo.opened = true;
memo.first = first;
}
@@ -507,8 +528,14 @@ impl<'a> Run<'_, 'a> {
}
}
}
if let Some(model) = got.model_pick {
body.memory::<Memo>().model = Some(model);
if let Some(next) = got.model_pick {
match self.shown_model.as_mut() {
Some(held) => {
let event = EditEvent::set(Mixed::Same(model), Some(next), Arc::from("Color model"), None);
let _ = held.write(&mut *body, &event);
}
None => body.memory::<Memo>().model = Some(next),
}
}
(std::mem::take(&mut self.events), got.screen_pick)
}
+45 -2
View File
@@ -3,14 +3,57 @@
use craft_theme::{Channel, ColorModel, DefaultOn, HsbModel, LabModel, MAX_CHANNELS, ModelValues, OklchModel, RgbModel, Srgba};
use craft_ui::contract::{Bind, Props as _, Show as _};
use craft_ui::dialog::stories::hosted;
use craft_ui::runtime::env::Label;
use craft_ui::testing::{Drive, StoryData, StoryOutput, story};
use egui::Ui;
use super::channel::{ChannelRow, ChannelRule, TrackRamp};
use super::screen_pick::ScreenPickButton;
use super::{ColorPicker, ColorPickerLayout, ColorPickerOutput, PickedColor};
use crate::ui::{AreaMode, ColorPickerDialog, ColorWarning};
use craft_ui::dialog::stories::hosted;
use crate::ui::{AreaMode, ColorPickerDialog, ColorPickerDialogLayout, ColorPickerTab, ColorWarning};
type StandardColors = (Vec<(Label, Srgba)>, Vec<(Label, Srgba)>);
/// A colour of full brightness and saturation at `hue` (0 to 1).
fn hue_color(hue: f32) -> Srgba {
let channel = |n: f32| (((hue * 6.0 + n) % 6.0 - 3.0).abs() - 1.0).clamp(0.0, 1.0);
Srgba::rgb(channel(5.0), channel(3.0), channel(1.0))
}
/// The Standard tab's honeycomb of 19 hues and its row of greys.
fn standard_colors() -> StandardColors {
let cells = (0..19).map(|i| (Label::from(format!("Color {}", i + 1)), hue_color(i as f32 / 19.0))).collect();
let greys = (0..8)
.map(|i| {
let level = i as f32 / 7.0;
(Label::from(format!("Gray {}", i + 1)), Srgba::rgb(level, level, level))
})
.collect();
(cells, greys)
}
/// The tabbed dialog on the story's dialog host, opened from a button, on `tab`.
fn tabbed(ui: &mut Ui, data: &mut StoryData, tab: ColorPickerTab) -> StoryOutput {
hosted(ui, data, (), || {
let (cells, greys) = standard_colors();
ColorPickerDialog::new("story", "Colors", Srgba::rgb(0.2, 0.5, 0.8))
.layout(ColorPickerDialogLayout::Tabbed)
.standard(cells, greys)
.tab(tab)
.web_colors_remembered(false)
})
}
#[story(ColorPickerDialog, covers = [], drive = Drive::Never)]
fn color_picker_dialog_tabbed(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
tabbed(ui, data, ColorPickerTab::Standard)
}
#[story(ColorPickerDialog, covers = [], drive = Drive::Never)]
fn color_picker_dialog_tabbed_custom(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
tabbed(ui, data, ColorPickerTab::Custom)
}
/// A naive CMYK in percent, without a working space: a host's model for the stories. A real host converts through its
/// CMYK profile.
+171 -9
View File
@@ -9,16 +9,18 @@
//! }
//! ```
use craft_behavior::Mixed;
use craft_behavior::{Mixed, Selection, SelectionChange, keyed};
use craft_cms::convert::CmykConverter;
use craft_host::Host;
use craft_host::target::Caps;
use craft_settings::Remembered;
use craft_theme::{ColorModel, Srgba, builtin_models};
use craft_ui::contract::{Bind, CanvasGesture, Sampler as _, ShowContainer as _};
use craft_ui::choice::{SwatchArrangement, SwatchTable};
use craft_ui::contract::{Bind, CanvasGesture, CollectionEvent, Sampler as _, ShowCollection as _, ShowContainer as _};
use craft_ui::dialog::{
ButtonPlace, Dialog, DialogId, DialogResult, DialogStack, FieldRefusal, StackDialog, dialog_id, serde_fields, set_serde_field,
};
use craft_ui::layout_components::Stack;
use craft_ui::patterns::form_dialogs::{HostRequests, ResetFooter};
use craft_ui::runtime::env::{Env, Label};
use craft_ui::runtime::focus::Initial;
@@ -26,12 +28,17 @@ use craft_ui::runtime::overlay::CloseReason;
use craft_ui::runtime::requests::{ColorRequest, EyedropperRequest, HostAnswer};
use craft_ui::runtime::words::CommonWords;
use craft_ui::sections::{DialogRole, FooterButton};
use craft_ui::tabs::{Tab, TabKind, TabStrip};
use egui::{Context, Id, Ui};
use serde::{Deserialize, Serialize};
use std::borrow::Cow;
use std::sync::Arc;
use super::{ColorPicker, ColorPickerLayout, ColorWarning, PickedColor, ScreenPickGesture};
use crate::{AreaMode, CmykModel, not_web_safe, web_safe};
type StandardColors = (Vec<(Label, Srgba)>, Vec<(Label, Srgba)>);
craft_ui::words! {
/// The Color Picker dialog's own words, English by default. The picker body's words are `ColorPickerWords`; OK and
/// Cancel are the common words.
@@ -44,12 +51,16 @@ craft_ui::words! {
add_to_swatches: "colorPickerDialog.addToSwatches" = "Add to Swatches";
out_of_gamut: "colorPickerDialog.outOfGamut" = "Out of gamut for printing: click for the nearest printable color";
not_web_color: "colorPickerDialog.notWebColor" = "Not a web color: click for the nearest web color";
standard_tab: "colorPickerDialog.standardTab" = "Standard";
custom_tab: "colorPickerDialog.customTab" = "Custom";
standard_colors: "colorPickerDialog.standardColors" = "Standard colors";
greys: "colorPickerDialog.greys" = "Shades of gray";
}
}
/// What the picker keeps across opens and runs (`Remembered` under the scope `colorPicker.memory`): the component the
/// field shows and Only Web Colors, as Photoshop. Stored when the dialog closes with OK.
#[derive(Clone, Copy, Debug, Default, PartialEq, serde::Serialize, serde::Deserialize)]
#[derive(Clone, Debug, Default, PartialEq, serde::Serialize, serde::Deserialize)]
#[serde(default, rename_all = "camelCase")]
#[non_exhaustive]
pub struct ColorPickerMemory {
@@ -57,6 +68,10 @@ pub struct ColorPickerMemory {
pub mode: AreaMode,
/// Only Web Colors: snap to the 216 web-safe colours.
pub web_colors: bool,
/// The tab a tabbed dialog showed last.
pub tab: ColorPickerTab,
/// The id of the model the Custom tab's model switch showed last; `None` while no switch shows.
pub model: Option<String>,
}
/// The remembered scope of [`ColorPickerMemory`].
@@ -72,6 +87,29 @@ pub struct ColorPickerResult {
pub picked: PickedColor,
}
/// How a [`ColorPickerDialog`] lays out its body.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum ColorPickerDialogLayout {
/// Photoshop's Color Picker: the Full picker.
#[default]
Full,
/// Word's Colors dialog: a Standard tab with the honeycomb and a Custom tab with the compact picker.
Tabbed,
}
/// The tab a tabbed [`ColorPickerDialog`] shows.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub enum ColorPickerTab {
/// The Standard honeycomb and the greys.
#[default]
Standard,
/// The compact picker.
Custom,
}
/// The dialog's title: given by the app, or one of the two the library words.
#[derive(Clone, Debug, PartialEq)]
enum Title {
@@ -103,6 +141,7 @@ enum Title {
/// the app takes the colour with [`take_add_to_swatches`](Self::take_add_to_swatches).
/// - **Preview:** [`current`](Self::current) follows every edit, so an app that previews reads it each pass through
/// `DialogHost::get_by_id` and shows it live; Cancel is the app's cue to put the old colour back.
#[derive(craft_ui::contract::Pattern)]
pub struct ColorPickerDialog {
id: DialogId,
/// Which of several pickers of the same key this is ([`instance`](Self::instance)).
@@ -131,6 +170,93 @@ pub struct ColorPickerDialog {
host: Option<Arc<Host>>,
started: bool,
open: bool,
layout: ColorPickerDialogLayout,
/// The Standard tab's honeycomb cells and grey row.
standard: Option<StandardColors>,
/// The tab the app asked to open on; it wins over the remembered one, once.
tab: Option<ColorPickerTab>,
}
/// What the tabbed body shows besides the memory and the colour it edits.
struct TabbedBody<'a> {
title: &'a Label,
words: &'a ColorPickerDialogWords,
standard: Option<&'a StandardColors>,
compare: Option<Mixed<PickedColor>>,
}
/// The selection of the entry whose colour is exactly `current`.
fn chosen(entries: &[(Label, Srgba)], current: Option<Srgba>) -> Selection<usize> {
current.and_then(|color| entries.iter().position(|(_, entry)| *entry == color)).map_or_else(Selection::default, Selection::single)
}
impl TabbedBody<'_> {
/// The tab strip over the page of `memory.tab`: the honeycomb and the greys, or the compact picker with the compare
/// swatch. A pick on either page sets `held`.
fn show(&self, ui: &mut Ui, memory: &mut ColorPickerMemory, held: &mut Mixed<PickedColor>) {
let words = self.words;
Stack::new().show(ui, |ui, _| {
let tabs = [(ColorPickerTab::Standard, words.standard_tab.clone()), (ColorPickerTab::Custom, words.custom_tab.clone())];
let source = keyed(&tabs[..], |tab: &(ColorPickerTab, Label)| tab.0).with_text(|tab| Cow::Borrowed(tab.1.as_str()));
let out = TabStrip::new(self.title.clone()).kind(TabKind::Text).shown(memory.tab).natural_height(true).show_items(
ui,
&source,
&mut |key, _| Tab::new(tabs.iter().find(|tab| tab.0 == *key).map_or_else(Label::default, |tab| tab.1.clone())),
);
for event in out.response.events {
if let CollectionEvent::Selection(SelectionChange::Set(keys)) = event
&& let Some(picked) = keys.last()
{
memory.tab = *picked;
}
}
match memory.tab {
ColorPickerTab::Standard => self.standard_page(ui, held),
ColorPickerTab::Custom => self.custom_page(ui, memory, held),
}
});
}
/// The honeycomb over the row of greys; the selection follows the colour by exact match.
fn standard_page(&self, ui: &mut Ui, held: &mut Mixed<PickedColor>) {
let (cells, greys) = self.standard.map_or((&[][..], &[][..]), |(cells, greys)| (cells.as_slice(), greys.as_slice()));
let current = held.same().map(|picked| picked.color);
let mut pick = None;
Stack::new().show(ui, |ui, _| {
let honeycomb = SwatchTable::new(self.words.standard_colors.clone(), cells)
.arrangement(SwatchArrangement::Honeycomb)
.tips(true)
.selection(Bind::given(chosen(cells, current)))
.show_all(ui);
if let Some(at) = honeycomb.selected {
pick = cells.get(at).map(|(_, color)| *color);
}
let row = SwatchTable::new(self.words.greys.clone(), greys)
.per_row(greys.len().max(1))
.tips(true)
.selection(Bind::given(chosen(greys, current)))
.show_all(ui);
if let Some(at) = row.selected {
pick = greys.get(at).map(|(_, color)| *color);
}
});
if let Some(color) = pick {
*held = Mixed::Same(PickedColor::rgb(color));
}
}
/// The compact picker over the colour, the compare swatch beside its area; the model switch is the memory's.
fn custom_page(&self, ui: &mut Ui, memory: &mut ColorPickerMemory, held: &mut Mixed<PickedColor>) {
let models: Vec<&dyn ColorModel> = builtin_models().into_iter().filter(|model| model.default_on().compact).collect();
let mut model: Option<&'static str> = memory.model.as_deref().and_then(|id| models.iter().map(|known| known.id()).find(|known| *known == id));
let mut picker =
ColorPicker::new(self.title.clone(), Bind::bound_mixed(held)).layout(ColorPickerLayout::Compact).shown_model(Bind::bound(&mut model));
if let Some(compare) = self.compare {
picker = picker.compare(compare);
}
let _ = picker.show(ui);
memory.model = model.map(str::to_owned);
}
}
impl ColorPickerDialog {
@@ -185,9 +311,33 @@ impl ColorPickerDialog {
host: None,
started: false,
open: true,
layout: ColorPickerDialogLayout::default(),
standard: None,
tab: None,
}
}
/// Sets the dialog's layout: Full (Photoshop) or Tabbed (Word's Colors dialog).
#[must_use]
pub fn layout(mut self, l: ColorPickerDialogLayout) -> ColorPickerDialog {
self.layout = l;
self
}
/// Sets the Standard tab's honeycomb `cells` and `greys`, each a name and a colour.
#[must_use]
pub fn standard(mut self, cells: Vec<(Label, Srgba)>, greys: Vec<(Label, Srgba)>) -> ColorPickerDialog {
self.standard = Some((cells, greys));
self
}
/// Sets the tab a tabbed dialog shows.
#[must_use]
pub fn tab(mut self, t: ColorPickerTab) -> ColorPickerDialog {
self.tab = Some(t);
self
}
/// Fills `{name}` in a given title with `value`, after the title is translated: the title follows a language
/// switch while the dialog is open. The value is shown as given, never translated.
#[must_use]
@@ -343,7 +493,11 @@ impl ColorPickerDialog {
{
self.memory = memory;
}
if let Some(tab) = self.tab.take() {
self.memory.tab = tab;
}
if self.memory.web_colors
&& self.layout == ColorPickerDialogLayout::Full
&& let Some(opening) = self.opening
{
let [r, g, b] = web_safe([opening.color.r, opening.color.g, opening.color.b]);
@@ -354,7 +508,7 @@ impl ColorPickerDialog {
/// Files or withdraws the canvas eyedropper request as the dialog gains or loses the top.
fn follow_top(&mut self, top: bool) {
let sampling = self.canvas_samples && top;
let sampling = self.canvas_samples && top && self.layout == ColorPickerDialogLayout::Full;
if sampling && !self.sampling {
self.requests.request_eyedropper(EyedropperRequest::new(self.key.clone()));
} else if !sampling && self.sampling {
@@ -386,7 +540,7 @@ impl StackDialog for ColorPickerDialog {
self.instance
}
/// `color` (`#rrggbb`, null when there is none yet), and the memory's own `mode` and `webColors`.
/// `color` (`#rrggbb`, null when there is none yet), and the memory's own `mode`, `webColors`, `tab` and `model`.
fn json_fields(&self) -> Option<serde_json::Value> {
let mut fields = serde_fields(&self.memory)?;
let color = self.current.map_or(serde_json::Value::Null, |picked| picked.color.to_hex().into());
@@ -443,14 +597,17 @@ impl StackDialog for ColorPickerDialog {
let footer = ResetFooter::new(ui, None, true);
let changed = self.current != self.opening;
let mut buttons = footer.buttons(FooterButton::new(common.ok.clone(), DialogRole::Accept).enabled(self.current.is_some()), changed).to_vec();
if self.add_to_swatches {
if self.add_to_swatches && self.layout == ColorPickerDialogLayout::Full {
buttons.push(FooterButton::new(words.add_to_swatches.clone(), DialogRole::Other).stays_open(true));
}
let arm = self.sampling.then_some(self.canvas).flatten();
let keep_open = self.canvas;
let screen = self.eyedropper && env.view().shell().caps.contains(Caps::SCREEN_CAPTURE);
let Self { current, opening, compare, memory, screen_busy, sample, pending_screen, open, .. } = self;
let screen = self.eyedropper && self.layout == ColorPickerDialogLayout::Full && env.view().shell().caps.contains(Caps::SCREEN_CAPTURE);
// The Full picker keeps a cell for the buttons; the tabbed body has none, so they stand in the side column, as in
// Word's Colors dialog.
let place = if self.layout == ColorPickerDialogLayout::Full { ButtonPlace::Body } else { ButtonPlace::Side };
let Self { current, opening, compare, memory, screen_busy, sample, pending_screen, open, layout, standard, .. } = self;
let mut held: Mixed<PickedColor> = current.map_or(Mixed::Mixed, Mixed::Same);
let (sampled, busy, compare_with) = (sample.take(), *screen_busy, compare.then(|| opening.map_or(Mixed::Mixed, Mixed::Same)));
let color = current.map(|current| current.color);
@@ -458,7 +615,7 @@ impl StackDialog for ColorPickerDialog {
let shown = Dialog::new(title.clone())
.opened(Bind::bound(open))
.buttons(buttons)
.button_place(ButtonPlace::Body)
.button_place(place)
.close_on_enter(true)
.initial_focus(Initial::Keep)
.roomy(true)
@@ -469,6 +626,11 @@ impl StackDialog for ColorPickerDialog {
if let Some(canvas) = arm {
cx.pass_canvas_gesture(canvas, CanvasGesture::PRIMARY);
}
if *layout == ColorPickerDialogLayout::Tabbed {
let body = TabbedBody { title: &title, words: &words, standard: standard.as_ref(), compare: compare_with };
body.show(ui, &mut *memory, &mut held);
return;
}
let mut models: Vec<&dyn ColorModel> = builtin_models().into_iter().filter(|model| model.default_on().full).collect();
models.push(&cmyk);
let mut warnings = Vec::new();
+70 -2
View File
@@ -4,13 +4,16 @@ use std::cell::RefCell;
use std::rc::Rc;
use craft_behavior::Mixed;
use craft_color_ui::ui::{ColorPicker, ColorPickerDialog, ColorPickerLayout, ColorPopover, ColorReadout, ColorWarning, PickedColor};
use craft_color_ui::ui::{
ColorPicker, ColorPickerDialog, ColorPickerDialogLayout, ColorPickerLayout, ColorPickerTab, ColorPopover, ColorReadout, ColorWarning, PickedColor,
};
use craft_host::{AppInfo, Host};
use craft_theme::{ColorModel, HsbModel, LabModel, ModelValues, OklchModel, RgbModel, Rgba, Size, Srgba, ThemeId};
use craft_ui::contract::{Bind, Role, ShowContainer as _};
use craft_ui::dialog::{DialogHost, DialogResult, dialog_id};
use craft_ui::dialog::{DialogHost, DialogResult, StackDialog, dialog_id};
use craft_ui::layout::RowAlign;
use craft_ui::layout_components::Row;
use craft_ui::runtime::env::Label;
use craft_ui::testing::{Fixture, trial};
use egui::{Key, Modifiers, Rect, vec2};
@@ -382,3 +385,68 @@ fn the_compact_picker_is_as_wide_as_its_area_and_strip_wherever_it_opens() {
assert!(first.0.x > first.0.y, "the compact area is wider than tall");
assert!(first.1 > first.0.x, "the rows reach past the area, to the strip's end");
}
/// A field of the open dialog as automation reads it.
fn dialog_field(dialogs: &Rc<RefCell<DialogHost>>, name: &str) -> Option<serde_json::Value> {
dialogs.borrow().get::<ColorPickerDialog>().and_then(|dialog| dialog.json_fields()).and_then(|fields| fields.get(name).cloned())
}
/// The current colour of the open dialog as `#rrggbb`.
fn dialog_color(dialogs: &Rc<RefCell<DialogHost>>) -> Option<String> {
dialogs.borrow().get::<ColorPickerDialog>().and_then(|dialog| dialog.current()).map(|picked| picked.color.to_hex())
}
/// The tabbed dialog opens on the tab it was given; a hex typed on Custom and a honeycomb cell picked on Standard both
/// reach the answer, and the tab is a field automation reads and sets.
#[trial]
fn the_tabbed_colors_dialog_opens_on_its_tab_and_answers_from_either_page() {
let dialogs = Rc::new(RefCell::new(DialogHost::new()));
let shown = Rc::clone(&dialogs);
let mut fixture = Fixture::new(move |ui| shown.borrow_mut().run(ui));
fixture.room(vec2(900.0, 700.0));
fixture.host(std::sync::Arc::new(Host::builder(AppInfo { id: "picker-test", name: "Picker test", version: "0" }).build()));
let ctx = fixture.ctx().clone();
let id = dialog_id(("color-picker", "fill"));
let colour = |hex: &str| Srgba::from_hex(hex).expect("a colour");
let cells: Vec<(Label, Srgba)> = ["#ff0000", "#00ff00", "#0000ff", "#ffff00"]
.iter()
.enumerate()
.map(|(at, hex)| (Label::from(format!("Standard {at}")), colour(hex)))
.collect();
let greys = vec![(Label::from("Gray 1"), colour("#808080"))];
dialogs.borrow_mut().open(
ColorPickerDialog::new("fill", "Fill", colour("#123456"))
.layout(ColorPickerDialogLayout::Tabbed)
.standard(cells, greys)
.tab(ColorPickerTab::Custom)
.web_colors_remembered(false),
);
fixture.idle(6);
assert_eq!(dialog_field(&dialogs, "tab"), Some(serde_json::json!("custom")), "the dialog opens on the tab it was given");
assert!(fixture.by_label("Hex color").is_some(), "the Custom page shows the compact picker");
assert!(fixture.by_label("Standard 0").is_none(), "and not the honeycomb");
assert_eq!(dialog_field(&dialogs, "model"), Some(serde_json::Value::Null), "no model is picked yet");
assert!(fixture.by_label("Red").is_none(), "the first model (HSB) shows no red channel");
let set = dialogs.borrow_mut().set_json_field(&ctx, id, "model", serde_json::json!(RgbModel.id()));
assert_eq!(set, Ok(()), "the model of the Custom page is a field");
fixture.idle(6);
assert_eq!(dialog_field(&dialogs, "model"), Some(serde_json::json!(RgbModel.id())), "the field names the model shown");
assert!(fixture.by_label("Red").is_some(), "and the compact rows show that model's channels");
type_into(&mut fixture, "Hex color", "336699");
assert_eq!(dialog_color(&dialogs).as_deref(), Some("#336699"), "a hex typed on Custom is the colour");
let set = dialogs.borrow_mut().set_json_field(&ctx, id, "tab", serde_json::json!("standard"));
assert_eq!(set, Ok(()), "the tab is a field of the dialog");
fixture.idle(6);
assert!(fixture.by_label("Hex color").is_none(), "Standard shows no hex field");
let cell = fixture.by_label("Standard 2").expect("the honeycomb shows its cells");
fixture.click(&cell);
fixture.idle(4);
assert_eq!(dialog_color(&dialogs).as_deref(), Some("#0000ff"), "a honeycomb pick is the colour");
assert!(dialogs.borrow_mut().confirm::<ColorPickerDialog>(&ctx), "OK answers");
let answered = dialogs.borrow_mut().take::<ColorPickerDialog>().and_then(DialogResult::ok).map(|result| result.picked.color.to_hex());
assert_eq!(answered.as_deref(), Some("#0000ff"));
}
+6 -3
View File
@@ -382,7 +382,7 @@ develop-model = ["dep:craft-develop-model"]
dex = ["dep:craft-dex"]
dialogs = ["dep:craft-dialogs"] # native only: rfd's folder picker and file paths
dialogs = ["dep:craft-dialogs", "browse"] # native only: rfd's folder picker and file paths
doc = ["dep:craft-doc"]
doc-pcraft-pixels = ["doc", "craft-doc/pcraft-pixels"]
@@ -482,6 +482,7 @@ gif = ["dep:craft-gif"]
gif-frames = ["gif", "craft-gif/frames"]
gpu = ["dep:craft-gpu"]
gpu-startup = ["gpu", "craft-gpu/startup"]
gpu-null = ["dep:craft-gpu-null"]
@@ -632,7 +633,7 @@ openpgp = ["dep:craft-openpgp"]
ora = ["dep:craft-ora"]
pages = ["dep:craft-pages"]
pages = ["dep:craft-pages", "keymap", "text"]
palette = ["dep:craft-palette"]
@@ -670,8 +671,10 @@ pkcs7 = ["dep:craft-pkcs7"]
platform = ["dep:craft-platform"]
platform-appearance = ["platform", "craft-platform/appearance"]
platform-apple-events = ["platform", "craft-platform/apple-events"]
platform-browser = ["platform", "craft-platform/browser"]
platform-clipboard = ["platform", "craft-platform/clipboard"]
platform-clipboard-system = ["platform", "craft-platform/clipboard-system"]
platform-pointer = ["platform", "craft-platform/pointer"]
platform-screen = ["platform", "craft-platform/screen"]
platform-testing = ["platform", "craft-platform/testing"]
@@ -738,7 +741,7 @@ raw-raf = ["raw", "craft-raw/raf"]
raw-rw2 = ["raw", "craft-raw/rw2"]
raw-srw = ["raw", "craft-raw/srw"]
review = ["dep:craft-review", "keymap"]
review = ["dep:craft-review", "keymap", "pages"]
rtf = ["dep:craft-rtf"]
rtf-doc = ["rtf", "craft-rtf/doc"]
+17 -2
View File
@@ -37,6 +37,13 @@ const BASE: &[&str] = &["color-ui"];
/// and not a family itself.
const COMPOSITION: &[&str] = &["menu"];
/// Edges between families that are allowed, each with its reason (developer ruling, port S-L347).
const ALLOWED: &[(&str, &str, &str)] = &[
("dialogs", "browse", "the file chooser lists browse's places"),
("pages", "text", "the page rulers are text's ruler over a page"),
("review", "pages", "comment balloons sit beside placed pages"),
];
/// Family crates `m`'s `ui` depends on: through its `ui` feature, and through dependencies that turn `ui` on.
fn ui_edges(m: &Member) -> Vec<String> {
let mut edges: Vec<String> = m.features.get("ui").into_iter().flatten().filter_map(|e| common::crate_of(e)).map(str::to_owned).collect();
@@ -58,10 +65,18 @@ fn family_ui_depends_on_no_other_family() {
let mut offenders = Vec::new();
for m in members().iter().filter(|m| FAMILIES.contains(&m.dir.as_str()) && !COMPOSITION.contains(&m.dir.as_str())) {
for dep in ui_edges(m) {
if dep != m.dir && FAMILIES.contains(&dep.as_str()) && !BASE.contains(&dep.as_str()) {
if dep != m.dir
&& FAMILIES.contains(&dep.as_str())
&& !BASE.contains(&dep.as_str())
&& !ALLOWED.iter().any(|(from, to, _)| *from == m.dir && *to == dep)
{
offenders.push(format!("craft-{}'s ui depends on craft-{dep}", m.dir));
}
}
}
assert!(offenders.is_empty(), "family ui crates may depend only on craft-color-ui's ui, not on each other:\n{}", offenders.join("\n"));
assert!(
offenders.is_empty(),
"family ui crates may depend only on craft-color-ui's ui, not on each other (beyond ALLOWED):\n{}",
offenders.join("\n")
);
}
+46 -41
View File
@@ -27,47 +27,52 @@ const CLOSED: &[&str] = &[
"SetPosition",
"States",
"StateMix",
"ShowReadouts", // the one Show Transformation Values flag: a bool, fixed by meaning
"PenDraft", // whose anchors a pen draft holds: own or foreign, fixed by meaning
"CollectionEvent", // built or matched in craft-ui-patterns
"ColumnAlign", // built or matched in craft-ui-widgets
"ColumnEvent", // built or matched in craft-ui-widgets
"DialogOutput", // built or matched in craft-ui-canvas
"DocText", // built or matched in craft-ui-widgets
"DockEvent", // built or matched in craft-ui-patterns
"Drag", // built or matched in craft-ui-canvas
"Drive", // built or matched in craft-ui-widgets
"FirePhase", // built or matched in craft-ui-canvas
"FocusPolicy", // built or matched in craft-ui-canvas
"GridEvent", // built or matched in craft-ui-patterns
"GroupAt", // built or matched in craft-ui-patterns
"GroupItem", // built or matched in craft-ui-patterns
"Guide", // built or matched in craft-ui-canvas
"GuideColor", // built or matched in craft-ui-patterns
"GuideLine", // built or matched in craft-ui-canvas
"HAlign", // built or matched in craft-ui-widgets
"HostAnswer", // built or matched in craft-ui-patterns
"IconSpec", // built or matched in craft-ui-widgets
"Inner", // built or matched in craft-ui-panels
"MenuKey", // built or matched in craft-ui-widgets
"Mount", // built or matched in craft-ui-panels
"OpenChange", // built or matched in craft-ui-patterns
"OuterEdit", // built or matched in craft-ui-widgets
"Pending", // built or matched in craft-ui-canvas
"ProxyColor", // built or matched in craft-ui-patterns
"ReorderMove", // built or matched in craft-ui-patterns
"RowState", // built or matched in craft-ui-widgets
"RuleLook", // built or matched in craft-ui-canvas
"ShellRegions", // built or matched in craft-ui-shell
"SizeLimits", // built or matched in craft-ui-panels
"StoryOutput", // built or matched in craft-ui-widgets
"SurfaceStyle", // built or matched in craft-ui-widgets
"Target", // built or matched in craft-ui-canvas
"TextOptions", // built or matched in craft-ui-widgets
"TransformReach", // `MoveOnly { points }` is built in PhotoCraft's type tool
"ToastEnd", // built or matched in craft-ui-widgets
"TrackLook", // built or matched in craft-ui-widgets
"VariantParts", // built or matched in craft-ui-widgets
"ShowReadouts", // the one Show Transformation Values flag: a bool, fixed by meaning
"PenDraft", // whose anchors a pen draft holds: own or foreign, fixed by meaning
"CollectionEvent", // built or matched in craft-ui-patterns
"ColumnAlign", // built or matched in craft-ui-widgets
"ColumnEvent", // built or matched in craft-ui-widgets
"DialogOutput", // built or matched in craft-ui-canvas
"DocText", // built or matched in craft-ui-widgets
"DockEvent", // built or matched in craft-ui-patterns
"Drag", // built or matched in craft-ui-canvas
"Drive", // built or matched in craft-ui-widgets
"FirePhase", // built or matched in craft-ui-canvas
"FocusPolicy", // built or matched in craft-ui-canvas
"GridEvent", // built or matched in craft-ui-patterns
"GroupAt", // built or matched in craft-ui-patterns
"GroupItem", // built or matched in craft-ui-patterns
"Guide", // built or matched in craft-ui-canvas
"GuideColor", // built or matched in craft-ui-patterns
"GuideLine", // built or matched in craft-ui-canvas
"HAlign", // built or matched in craft-ui-widgets
"HostAnswer", // built or matched in craft-ui-patterns
"IconSpec", // built or matched in craft-ui-widgets
"Inner", // built or matched in craft-ui-panels
"MenuKey", // built or matched in craft-ui-widgets
"Mount", // built or matched in craft-ui-panels
"OpenChange", // built or matched in craft-ui-patterns
"OuterEdit", // built or matched in craft-ui-widgets
"Pending", // built or matched in craft-ui-canvas
"ProxyColor", // built or matched in craft-ui-patterns
"ReorderMove", // built or matched in craft-ui-patterns
"RowState", // built or matched in craft-ui-widgets
"RuleLook", // built or matched in craft-ui-canvas
"ShellRegions", // built or matched in craft-ui-shell
"SizeLimits", // built or matched in craft-ui-panels
"StoryOutput", // built or matched in craft-ui-widgets
"SurfaceStyle", // built or matched in craft-ui-widgets
"Target", // built or matched in craft-ui-canvas
"TextOptions", // built or matched in craft-ui-widgets
"TransformReach", // `MoveOnly { points }` is built in PhotoCraft's type tool
"GalleryItem", // built in WordCraft's ui-egui, one literal per tile, with its key, label and face
"RibbonOutput", // built in WordCraft's ui-egui, which reports an empty ribbon output while no ribbon shows
"LineBreakOptions", // built field by field in WordCraft's paragraph dialog, a record of check boxes that mirrors the format
"AsianTypography", // built field by field in WordCraft's paragraph dialog, a record of check boxes that mirrors the format
"GapEdge", // the start and the end of a column gap: two edges, fixed by meaning, matched in WordCraft's column ruler
"ToastEnd", // built or matched in craft-ui-widgets
"TrackLook", // built or matched in craft-ui-widgets
"VariantParts", // built or matched in craft-ui-widgets
];
/// Permission keys whose only allowed location is craft-ui-contract's `runtime::egui`.
+8 -5
View File
@@ -22,9 +22,12 @@ craft-host = { workspace = true }
craft-i18n = { workspace = true }
craft-platform = { workspace = true }
craft-behavior = { workspace = true, optional = true }
craft-browse = { workspace = true, optional = true }
craft-ui = { workspace = true, optional = true }
egui = { workspace = true, optional = true }
raw-window-handle = "0.6.2"
# `ui`: the file chooser's automation fields are JSON (craft-ui does not re-export serde_json).
serde_json = { workspace = true, optional = true }
rfd = { version = "0.17.2", default-features = false, features = ["xdg-portal"] }
# The file-dialog probe asks the session bus whether the desktop portal offers a file chooser.
@@ -36,10 +39,10 @@ objc2 = { version = "0.6.4", default-features = false, features = ["std"] }
objc2-app-kit = { version = "0.3.2", default-features = false, features = ["std", "block2", "NSApplication", "NSOpenPanel", "NSPanel", "NSResponder", "NSSavePanel", "NSView", "NSWindow"] }
objc2-foundation = { version = "0.3.2", default-features = false, features = ["std", "NSArray", "NSString", "NSURL"] }
# The Linux Save panel asks the desktop portal itself, which reports the file type picked. The
# versions craft-platform already builds (zbus with async-io and blocking-api), so adopting the
# crate adds nothing new to the apps' Cargo.lock.
[target.'cfg(target_os = "linux")'.dependencies]
# The Linux and BSD Save panel asks the desktop portal itself, which reports the file type picked.
# The versions craft-platform already builds (zbus with async-io and blocking-api), so adopting the
# crate adds nothing new to the apps' Cargo.lock. The cfg is the one on `mod portal` in `lib.rs`.
[target.'cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))'.dependencies]
futures-lite = "2"
log = "0.4"
zbus = { version = "5", default-features = false, features = ["async-io", "blocking-api"] }
@@ -47,7 +50,7 @@ zbus = { version = "5", default-features = false, features = ["async-io", "block
[features]
default = []
# `craft_dialogs::ui`: `PathField` and the other egui parts of the file service.
ui = ["dep:craft-behavior", "dep:craft-ui", "dep:egui"]
ui = ["dep:craft-behavior", "dep:craft-browse", "dep:craft-ui", "dep:egui", "dep:serde_json"]
# The stories and the integration binary of the file service's UI parts.
screen-testing = ["ui", "craft-ui/testing"]
+19 -7
View File
@@ -21,7 +21,7 @@
mod filter;
mod native;
#[cfg(target_os = "linux")]
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))]
mod portal;
mod probe;
pub mod save;
@@ -257,14 +257,13 @@ enum Show {
Override(Override),
/// Tests: a stand-in for the native dialog that answers (or doesn't) through the reply.
#[cfg(test)]
Custom(Box<dyn FnMut(Request, Reply)>),
Custom(Box<dyn FnMut(Request, Reply) -> native::Shown>),
}
/// The dialog on screen.
struct Open<T> {
then: T,
answer: Receiver<Answer>,
#[cfg_attr(not(target_os = "macos"), allow(dead_code))]
shown: native::Shown,
}
@@ -315,10 +314,12 @@ impl<T> Dialogs<T> {
let reply = Reply { tx: Some(tx), wake: self.wake.clone() };
// A panic while showing (rfd's own checks) must not unwind into winit's handler.
let shown = match &mut self.show {
Show::Override(answer_with) => catch_unwind(AssertUnwindSafe(|| reply.send(answer_with(&request)))).map(|()| None),
Show::Override(answer_with) => {
catch_unwind(AssertUnwindSafe(|| reply.send(answer_with(&request)))).map(|()| native::Shown::default())
}
Show::Native => catch_unwind(AssertUnwindSafe(|| native::show(request, parent, reply))),
#[cfg(test)]
Show::Custom(show) => catch_unwind(AssertUnwindSafe(|| show(request, reply))).map(|()| None),
Show::Custom(show) => catch_unwind(AssertUnwindSafe(|| show(request, reply))),
};
let shown = match shown {
Ok(shown) => shown,
@@ -349,7 +350,7 @@ impl<T> Dialogs<T> {
/// that would show it again. Does nothing elsewhere, where dialogs are modal to the window.
pub fn raise(&self) {
#[cfg(target_os = "macos")]
if let Some(panel) = self.open.as_ref().and_then(|open| open.shown.as_ref()) {
if let Some(panel) = self.open.as_ref().and_then(|open| open.shown.panel.as_ref()) {
macos::raise(panel);
}
}
@@ -366,9 +367,20 @@ impl<T> Dialogs<T> {
self.show = answer_with.map_or(Show::Native, Show::Override);
}
/// Stops the open dialog when `gone` says nobody waits for its answer any more (its pick was
/// forgotten): a portal Save closes. Other dialogs cannot be closed from outside; their answer
/// comes as usual and the caller drops it.
pub(crate) fn cancel_open_if(&mut self, gone: impl FnOnce(&T) -> bool) {
if let Some(open) = &mut self.open
&& gone(&open.then)
{
open.shown.cancel_save();
}
}
/// Tests: show requests through `show` instead of a native dialog.
#[cfg(test)]
fn set_custom(&mut self, show: impl FnMut(Request, Reply) + 'static) {
fn set_custom(&mut self, show: impl FnMut(Request, Reply) -> native::Shown + 'static) {
self.show = Show::Custom(Box::new(show));
}
+101 -37
View File
@@ -9,13 +9,17 @@
//! Folder don't go through rfd at all on macOS: see [`crate::macos`].
//! - Windows: the dialog runs on a thread rfd starts when the worker first polls the future.
//! - Linux and the BSDs: the desktop portal (zenity as a fallback) works when the worker polls the
//! future; rfd's optional GTK3 backend runs on rfd's own GTK thread.
//! future; rfd's optional GTK3 backend runs on rfd's own GTK thread. A portal that cannot show
//! its dialog answers "nothing picked" at once, which reads like a cancel; [`timed`] tells the
//! two apart by how long the dialog was open.
use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
use std::sync::mpsc;
use std::task::{Context, Poll, Wake, Waker};
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))]
use std::time::{Duration, Instant};
use raw_window_handle::{HasDisplayHandle, HasWindowHandle};
@@ -24,12 +28,26 @@ use crate::{Answer, FileDialog, Kind, Message, MessageButtons, MessageLevel, Mes
type Pending = Pin<Box<dyn Future<Output = Answer> + Send>>;
/// What [`crate::Dialogs`] keeps while a dialog is on screen: on macOS, the free-standing panel to
/// raise. Other platforms have none.
pub(crate) type Shown = Option<Panel>;
#[cfg(target_os = "macos")]
pub(crate) use crate::macos::Panel;
#[cfg(not(target_os = "macos"))]
pub(crate) type Panel = std::convert::Infallible;
/// raise; on Linux and the BSDs, the cancel of a portal Save in flight.
#[derive(Default)]
pub(crate) struct Shown {
/// The free-standing Open or Folder panel.
#[cfg(target_os = "macos")]
pub(crate) panel: Option<crate::macos::Panel>,
/// Stops the portal Save this dialog is.
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))]
pub(crate) cancel: Option<crate::portal::Cancel>,
}
impl Shown {
/// Closes the portal Save this dialog is; other dialogs cannot be closed from outside.
pub(crate) fn cancel_save(&mut self) {
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))]
if let Some(cancel) = self.cancel.take() {
cancel.cancel();
}
}
}
pub(crate) fn show<W: HasWindowHandle + HasDisplayHandle>(request: Request, parent: Option<&W>, reply: Reply) -> Shown {
// rfd quietly drops a parent whose handles it can't get; the checks below need to know.
@@ -38,7 +56,7 @@ pub(crate) fn show<W: HasWindowHandle + HasDisplayHandle>(request: Request, pare
Request::File(dialog) => show_file(dialog, parent, reply),
Request::Message(message) => {
show_message(message, parent, reply);
None
Shown::default()
}
}
}
@@ -46,19 +64,16 @@ pub(crate) fn show<W: HasWindowHandle + HasDisplayHandle>(request: Request, pare
fn show_file<W: HasWindowHandle + HasDisplayHandle>(d: FileDialog, parent: Option<&W>, reply: Reply) -> Shown {
#[cfg(target_os = "macos")]
let parent = match d.kind {
Kind::Open { .. } | Kind::Folder => return crate::macos::show_panel(&d, reply),
Kind::Open { .. } | Kind::Folder => return Shown { panel: crate::macos::show_panel(&d, reply) },
Kind::Save => match crate::macos::sheet_parent(parent) {
Ok(parent) => Some(parent),
Err(why) => {
reply.send(Answer::Unavailable(why));
return None;
return Shown::default();
}
},
};
let mut dialog = rfd::AsyncFileDialog::new();
if let Some(parent) = parent {
dialog = dialog.set_parent(parent);
}
if let Some(title) = &d.title {
dialog = dialog.set_title(title);
}
@@ -71,10 +86,50 @@ fn show_file<W: HasWindowHandle + HasDisplayHandle>(d: FileDialog, parent: Optio
if let Some(name) = &d.file_name {
dialog = dialog.set_file_name(name);
}
// The same dialog without a parent: a dialog that closed at once is asked again with it.
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))]
let bare = dialog.clone();
if let Some(parent) = parent {
dialog = dialog.set_parent(parent);
}
// The worker first, so a dialog once shown always has somewhere to answer.
let worker = worker(reply)?;
let Some(worker) = worker(reply) else { return Shown::default() };
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))]
let (pending, shown): (Pending, Shown) = match d.kind {
// The portal's own Save dialog, which reports the file type picked; rfd's when the portal
// can't show it.
Kind::Save => {
let parent_id = crate::portal::parent_id(parent.and_then(|p| p.window_handle().ok()).map(|h| h.as_raw()));
let request = crate::portal::SaveRequest::new(&d, parent_id);
let cancel = crate::portal::Cancel::default();
let shown = Shown { cancel: Some(cancel.clone()) };
let pending: Pending = Box::pin(async move {
match crate::portal::save_as(request, &cancel) {
crate::portal::SaveOutcome::Saved(path) => Answer::Paths(vec![path]),
crate::portal::SaveOutcome::Cancelled => Answer::Cancelled,
crate::portal::SaveOutcome::Unavailable(why) => Answer::Unavailable(why),
crate::portal::SaveOutcome::UseRfd(why) => {
log::info!("portal save dialog unavailable ({why}), using rfd");
retried(dialog, bare, Kind::Save).await
}
}
});
(pending, shown)
}
kind => (retried(dialog, bare, kind), Shown::default()),
};
#[cfg(not(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd")))]
let (pending, shown) = (rfd_pick(dialog, d.kind), Shown::default());
// The worker can't be gone: it waits for this. If it were, its reply answers Unavailable.
let _ = worker.send(pending);
shown
}
/// rfd's dialog of `kind`, as an answer. On macOS creating the future shows the dialog, so this
/// runs where the dialog is to show.
fn rfd_pick(dialog: rfd::AsyncFileDialog, kind: Kind) -> Pending {
let one = |file: Option<rfd::FileHandle>| file.map_or(Answer::Cancelled, |f| Answer::Paths(vec![f.path().to_path_buf()]));
let pending: Pending = match d.kind {
match kind {
Kind::Open { multiple: false } => {
let picked = dialog.pick_file();
Box::pin(async move { one(picked.await) })
@@ -92,32 +147,41 @@ fn show_file<W: HasWindowHandle + HasDisplayHandle>(d: FileDialog, parent: Optio
let picked = dialog.pick_folder();
Box::pin(async move { one(picked.await) })
}
// On Linux the portal's own dialog, which reports the file type picked; rfd if the portal
// can't show it.
#[cfg(target_os = "linux")]
Kind::Save => {
let parent_id = crate::portal::parent_id(parent.and_then(|p| p.window_handle().ok()).map(|h| h.as_raw()));
let request = crate::portal::SaveRequest::new(&d, parent_id);
Box::pin(async move {
match crate::portal::save_as(request) {
Ok(Some(path)) => Answer::Paths(vec![path]),
Ok(None) => Answer::Cancelled,
Err(e) => {
log::info!("portal save dialog unavailable ({e}), using rfd");
one(dialog.save_file().await)
}
}
})
}
#[cfg(not(target_os = "linux"))]
Kind::Save => {
let picked = dialog.save_file();
Box::pin(async move { one(picked.await) })
}
};
// The worker can't be gone: it waits for this. If it were, its reply answers Unavailable.
let _ = worker.send(pending);
None
}
}
/// rfd's dialog of `kind` on `dialog`, [`timed`], asked again on `bare` (no parent) when it
/// closed at once.
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))]
fn retried(dialog: rfd::AsyncFileDialog, bare: rfd::AsyncFileDialog, kind: Kind) -> Pending {
let start = Instant::now();
Box::pin(timed(rfd_pick(dialog, kind), move || rfd_pick(bare, kind), move || start.elapsed()))
}
/// The answer of a pick, told apart from a dialog that never showed: an empty answer within
/// [`TOO_QUICK`](crate::portal::TOO_QUICK) is a portal that failed to show its dialog (#2999), not
/// a user's cancel, so the pick is asked once more through `again` (the dialog without a parent,
/// which some portals refuse). Empty at once again answers [`Answer::Unavailable`]. A slow empty
/// answer is the user's cancel. `now` reads a monotonic clock.
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))]
pub(crate) async fn timed<F, G>(pick: F, again: impl FnOnce() -> G, now: impl Fn() -> Duration) -> Answer
where
F: Future<Output = Answer>,
G: Future<Output = Answer>,
{
let at_once = |answer: &Answer, since: Duration| matches!(answer, Answer::Cancelled) && now().saturating_sub(since) < crate::portal::TOO_QUICK;
let start = now();
let answer = pick.await;
if !at_once(&answer, start) {
return answer;
}
let start = now();
let answer = again().await;
if at_once(&answer, start) { Answer::Unavailable(crate::portal::CLOSED_AT_ONCE.into()) } else { answer }
}
fn show_message<W: HasWindowHandle + HasDisplayHandle>(m: Message, parent: Option<&W>, reply: Reply) {
+236 -63
View File
@@ -1,4 +1,4 @@
//! Save through the XDG desktop portal on Linux.
//! Save through the XDG desktop portal on Linux and the BSDs.
//!
//! The GTK file chooser behind the portal keeps the typed name when the user picks another file
//! type, and rfd 0.17 reads only the file name from the portal's answer, so `image.psd` with PNG
@@ -7,17 +7,40 @@
//! ([`with_chosen_type`]). rfd stays the fallback (zenity, or no portal), and this can go once an
//! rfd release reads the picked type (PolyMeilex/rfd#341).
//!
//! A Save in flight can be stopped through its [`Cancel`] (its pick was forgotten): the wait for
//! the portal's answer races the cancel and the portal leaving the bus, and a cancel closes the
//! portal's request. How each answer reads is [`classify`]'s one rule.
//!
//! The dialog is attached to the window on X11. On Wayland it has no parent: naming the window to
//! the portal needs an xdg-foreign handle, which takes `unsafe` code the workspace forbids.
use std::collections::HashMap;
use std::future::Future;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
use std::task::{Poll, Waker};
use std::time::{Duration, Instant};
use raw_window_handle::RawWindowHandle;
use zbus::zvariant::{OwnedObjectPath, OwnedValue, Value};
use crate::{FileDialog, Filter};
/// How soon an empty answer means the dialog never showed: a portal that fails answers at once
/// (#2999), and no user closes a file dialog this quickly.
pub(crate) const TOO_QUICK: Duration = Duration::from_millis(300);
/// The cause a pick answers when the system dialog closed at once, twice.
pub(crate) const CLOSED_AT_ONCE: &str = "the system file dialog closed at once";
/// The cause of a Save whose file type the portal did not report and the typed name does not
/// tell: no dialog can answer it, and a guessed type would write the wrong format.
const AMBIGUOUS: &str = "ambiguous file type";
/// The portal's bus name.
const PORTAL: &str = "org.freedesktop.portal.Desktop";
/// A Save dialog to show.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub(crate) struct SaveRequest {
@@ -59,7 +82,7 @@ impl SaveRequest {
/// What the user chose: the path, as typed, and the label of the file type picked.
#[derive(Clone, Debug, PartialEq, Eq)]
struct Saved {
pub(crate) struct Saved {
path: PathBuf,
filter: Option<String>,
}
@@ -69,6 +92,117 @@ fn normal(ext: &str) -> String {
ext.trim_start_matches('.').to_ascii_lowercase()
}
/// A flag that cancels a portal Save in flight. Clones share the flag: the dialog's owner keeps
/// one, the worker waiting for the portal another.
#[derive(Clone, Debug, Default)]
pub(crate) struct Cancel(Arc<CancelState>);
#[derive(Debug, Default)]
struct CancelState {
cancelled: AtomicBool,
/// The task waiting in [`Cancel::cancelled`], woken by [`Cancel::cancel`].
waiter: Mutex<Option<Waker>>,
}
impl Cancel {
/// Asks the Save to stop.
pub(crate) fn cancel(&self) {
self.0.cancelled.store(true, Ordering::SeqCst);
if let Some(waker) = self.0.waiter.lock().unwrap_or_else(|e| e.into_inner()).take() {
waker.wake();
}
}
/// Whether [`cancel`](Self::cancel) was called.
pub(crate) fn is_cancelled(&self) -> bool {
self.0.cancelled.load(Ordering::SeqCst)
}
/// Resolves once [`cancel`](Self::cancel) is called.
fn cancelled(&self) -> impl Future<Output = ()> + '_ {
std::future::poll_fn(move |cx| {
if self.is_cancelled() {
return Poll::Ready(());
}
*self.0.waiter.lock().unwrap_or_else(|e| e.into_inner()) = Some(cx.waker().clone());
// A cancel between the check and the store found no waker to wake: look again.
if self.is_cancelled() { Poll::Ready(()) } else { Poll::Pending }
})
}
}
/// How a portal Save ended.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) enum SaveOutcome {
/// The user saved to this path.
Saved(PathBuf),
/// The user cancelled, or the Save was cancelled.
Cancelled,
/// The portal could not show the dialog: the caller shows rfd's.
UseRfd(String),
/// The file type picked is ambiguous: no dialog can answer.
Unavailable(String),
}
/// What a portal response means for a Save.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) enum Decision {
/// The user saved: the path and the file type picked.
Saved(Saved),
/// The user cancelled, or the Save was cancelled.
Cancelled,
/// The answer came too quickly to be the user's: the dialog never showed, ask another way.
Retry,
/// No portal answered usefully; the text says why.
Unavailable(String),
}
/// Reads one portal response into a [`Decision`]: the response `code`, how long the dialog was
/// open, whether a cancel was queued, whether the portal left the bus, and the `results`.
///
/// A queued cancel wins over any answer that arrived after it. Code 0 is a save with the first
/// `uris` entry; 1 is Cancel (KDE's Esc too). 2 is a dialog closed some other way: Esc in GNOME's
/// after a while, which is a cancel and no reason to show another dialog, or, within
/// [`TOO_QUICK`], a portal that failed to show it (#2999), which is a [`Decision::Retry`].
// pc: apps/photocraft/src/portal_save.rs:111 answer
pub(crate) fn classify(code: u32, elapsed: Duration, cancel_queued: bool, backend_gone: bool, results: &HashMap<String, OwnedValue>) -> Decision {
if cancel_queued {
return Decision::Cancelled;
}
if backend_gone {
return Decision::Unavailable("the desktop portal left the session bus".into());
}
match code {
0 => {}
1 => return Decision::Cancelled,
2 if elapsed < TOO_QUICK => return Decision::Retry,
2 => return Decision::Cancelled,
_ => return Decision::Unavailable(format!("the save dialog failed (portal response {code})")),
}
match saved(results) {
Ok(saved) => Decision::Saved(saved),
Err(why) => Decision::Unavailable(why),
}
}
/// The file and type a code-0 response names.
fn saved(results: &HashMap<String, OwnedValue>) -> Result<Saved, String> {
let uris: Vec<String> = results
.get("uris")
.ok_or("no file in the portal's answer")?
.try_clone()
.map_err(|e| e.to_string())?
.try_into()
.map_err(|e: zbus::zvariant::Error| e.to_string())?;
let uri = uris.first().ok_or("no file in the portal's answer")?;
let path = file_uri_path(uri).ok_or_else(|| format!("not a local file: {uri}"))?;
let filter = results.get("current_filter").and_then(|v| {
let (label, _globs): (String, Vec<(u32, String)>) = v.try_clone().ok()?.try_into().ok()?;
Some(label)
});
Ok(Saved { path, filter })
}
/// The portal's parent window identifier for `window`: `x11:<xid>` on X11, empty elsewhere.
// pc: apps/photocraft/src/portal_save.rs:47 parent_id
pub(crate) fn parent_id(window: Option<RawWindowHandle>) -> String {
@@ -79,35 +213,77 @@ pub(crate) fn parent_id(window: Option<RawWindowHandle>) -> String {
}
}
/// Shows the portal's Save dialog and waits for it. `Ok(None)` is Cancel; `Err` means the portal
/// couldn't show it (no portal, no FileChooser), so the caller falls back to rfd.
// pc: apps/photocraft/src/portal_save.rs:58 save_file
fn save_file(conn: &zbus::blocking::Connection, req: &SaveRequest) -> Result<Option<Saved>, String> {
/// Shows the portal's Save dialog and waits for its answer, the portal leaving the bus or
/// `cancel`, whichever comes first. A cancel closes the portal's request. `Err` when the portal
/// couldn't be asked (no portal, no FileChooser).
// pc: apps/photocraft/src/portal_save.rs:310 save_file, :266 close_request, :333 NameOwnerChanged
fn save_file(conn: &zbus::blocking::Connection, req: &SaveRequest, cancel: &Cancel) -> Result<Decision, String> {
use futures_lite::StreamExt;
use futures_lite::future::{block_on, or};
use zbus::blocking::Proxy;
enum Event {
Reply(Option<zbus::message::Message>),
Gone,
Cancelled,
}
let text = |e: zbus::Error| e.to_string();
let unique = conn.unique_name().ok_or("Portal connection has no unique name")?.as_str().trim_start_matches(':').replace('.', "_");
static NEXT: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
let token = format!("craft_dialogs_save_{}_{}", std::process::id(), NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed));
let token = format!("craft_dialogs_save_{}_{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed));
let path = format!("/org/freedesktop/portal/desktop/request/{unique}/{token}");
// Listen before asking, so a quick answer isn't missed.
let request = Proxy::new(conn, "org.freedesktop.portal.Desktop", path.as_str(), "org.freedesktop.portal.Request").map_err(|e| e.to_string())?;
let mut replies = futures_lite::future::block_on(request.inner().receive_signal("Response")).map_err(|e| e.to_string())?;
let chooser = Proxy::new(conn, "org.freedesktop.portal.Desktop", "/org/freedesktop/portal/desktop", "org.freedesktop.portal.FileChooser")
.map_err(|e| e.to_string())?;
let handle: OwnedObjectPath = chooser.call("SaveFile", &(req.parent.as_str(), "Save As", options(req, &token))).map_err(|e| e.to_string())?;
// Listen before asking, so a quick answer isn't missed: to the request's answer, and to the
// portal leaving the bus, after which no answer comes.
let request = Proxy::new(conn, PORTAL, path.as_str(), "org.freedesktop.portal.Request").map_err(text)?;
let replies = block_on(request.inner().receive_signal("Response")).map_err(text)?;
let bus = Proxy::new(conn, "org.freedesktop.DBus", "/org/freedesktop/DBus", "org.freedesktop.DBus").map_err(text)?;
let mut owners = block_on(bus.inner().receive_signal_with_args("NameOwnerChanged", &[(0, PORTAL)])).map_err(text)?;
let chooser = Proxy::new(conn, PORTAL, "/org/freedesktop/portal/desktop", "org.freedesktop.portal.FileChooser").map_err(text)?;
let started = Instant::now();
let handle: OwnedObjectPath = chooser.call("SaveFile", &(req.parent.as_str(), "Save As", options(req, &token))).map_err(text)?;
// A portal older than 0.9 ignores `handle_token` and answers on a request path of its own,
// which it returns: listen there instead, as the Request documentation asks.
let reply = if handle.as_str() == path {
futures_lite::future::block_on(replies.next())
let (request, mut replies) = if handle.as_str() == path {
(request, replies)
} else {
let request =
Proxy::new(conn, "org.freedesktop.portal.Desktop", handle.as_str(), "org.freedesktop.portal.Request").map_err(|e| e.to_string())?;
let mut replies = futures_lite::future::block_on(request.inner().receive_signal("Response")).map_err(|e| e.to_string())?;
futures_lite::future::block_on(replies.next())
}
.ok_or("The save dialog closed without an answer")?;
let (code, results): (u32, HashMap<String, OwnedValue>) = reply.body().deserialize().map_err(|e| e.to_string())?;
answer(code, &results)
let request = Proxy::new(conn, PORTAL, handle.as_str(), "org.freedesktop.portal.Request").map_err(text)?;
let replies = block_on(request.inner().receive_signal("Response")).map_err(text)?;
(request, replies)
};
let event = block_on(or(
async { Event::Reply(replies.next().await) },
or(
async {
cancel.cancelled().await;
Event::Cancelled
},
async {
// NameOwnerChanged(name, old owner, new owner): no new owner is the portal gone.
while let Some(change) = owners.next().await {
if change.body().deserialize::<(String, String, String)>().is_ok_and(|(_, _, new)| new.is_empty()) {
return Event::Gone;
}
}
Event::Gone
},
),
));
let elapsed = started.elapsed();
let nothing = HashMap::new();
// Without a response there is no code: the cancel and backend flags decide.
Ok(match event {
Event::Reply(Some(reply)) => {
let (code, results): (u32, HashMap<String, OwnedValue>) = reply.body().deserialize().map_err(text)?;
classify(code, elapsed, cancel.is_cancelled(), false, &results)
}
Event::Reply(None) | Event::Gone => classify(0, elapsed, cancel.is_cancelled(), true, &nothing),
Event::Cancelled => {
// The portal closes its dialog; a request it already answered has nothing to close.
let _ = request.call_method("Close", &());
classify(0, elapsed, true, false, &nothing)
}
})
}
/// A filter as the portal takes it: its label and one `*.ext` glob per pattern (the case-insensitive
@@ -139,32 +315,6 @@ fn options<'a>(req: &'a SaveRequest, token: &'a str) -> HashMap<&'static str, Va
o
}
/// Reads the portal's `Response`: code 0 with the first `uris` entry. 1 is Cancel, and 2 a dialog
/// closed some other way, such as with Esc in GNOME's: no file either, and not a reason to show
/// rfd's dialog instead (it did, so Esc opened a second Save As).
// pc: apps/photocraft/src/portal_save.rs:111 answer
fn answer(code: u32, results: &HashMap<String, OwnedValue>) -> Result<Option<Saved>, String> {
match code {
0 => {}
1 | 2 => return Ok(None),
_ => return Err(format!("the save dialog failed (portal response {code})")),
}
let uris: Vec<String> = results
.get("uris")
.ok_or("no file in the portal's answer")?
.try_clone()
.map_err(|e| e.to_string())?
.try_into()
.map_err(|e: zbus::zvariant::Error| e.to_string())?;
let uri = uris.first().ok_or("no file in the portal's answer")?;
let path = file_uri_path(uri).ok_or_else(|| format!("not a local file: {uri}"))?;
let filter = results.get("current_filter").and_then(|v| {
let (label, _globs): (String, Vec<(u32, String)>) = v.try_clone().ok()?.try_into().ok()?;
Some(label)
});
Ok(Some(Saved { path, filter }))
}
/// `file:///home/me/A%20b.psd` → `/home/me/A b.psd`; `None` for other schemes.
// pc: apps/photocraft/src/portal_save.rs:134 file_uri_path
fn file_uri_path(uri: &str) -> Option<PathBuf> {
@@ -205,6 +355,18 @@ fn chosen_type(filters: &[Filter], picked: Option<usize>) -> Option<usize> {
}
}
/// Whether a Save answer with no file type ([`chosen_type`] is `None`) leaves the format open:
/// several types were offered and the typed name's extension is none of theirs.
// pc: apps/wordcraft/src/portal_save.rs:446 is_ambiguous_filter
fn is_ambiguous(filters: &[Filter], path: &Path) -> bool {
let listed = path
.extension()
.and_then(|e| e.to_str())
.map(normal)
.is_some_and(|ext| filters.iter().any(|f| f.extensions.iter().any(|e| normal(e) == ext)));
filters.len() > 1 && !listed
}
/// `path` with the extension of the file type picked in the Save dialog (`chosen`, its extensions
/// without the dot), where the dialog left the name alone: the format follows the extension, and
/// the GTK file chooser keeps the typed name when another type is picked. Only a name that still
@@ -234,24 +396,35 @@ pub(crate) fn with_chosen_type(path: &Path, opened_with: Option<&str>, chosen: &
}
}
/// Save on Linux: the portal's dialog, with the name given the extension of the file type picked.
/// When that changes the name to one that already exists, the dialog opens again under the new
/// name, so the portal asks before replacing it (it asked only about the typed name). Connects to
/// the session bus; `Err` when the portal can't be reached, and the caller shows rfd's dialog.
// pc: apps/photocraft/src/portal_save.rs:174 save_as, services.rs:244-280
pub(crate) fn save_as(mut req: SaveRequest) -> Result<Option<PathBuf>, String> {
let conn = zbus::blocking::connection::Builder::session().and_then(|b| b.build()).map_err(|e| e.to_string())?;
/// Save on Linux and the BSDs: the portal's dialog, with the name given the extension of the file
/// type picked. When that changes the name to one that already exists, the dialog opens again
/// under the new name, so the portal asks before replacing it (it asked only about the typed
/// name). A portal that can't be reached or can't show the dialog answers
/// [`SaveOutcome::UseRfd`]; an answer whose file type nothing tells answers
/// [`SaveOutcome::Unavailable`], never a guess.
// pc: apps/photocraft/src/portal_save.rs:174 save_as, services.rs:244-280; apps/wordcraft/src/portal_save.rs:471 save_as
pub(crate) fn save_as(mut req: SaveRequest, cancel: &Cancel) -> SaveOutcome {
let conn = match zbus::blocking::connection::Builder::session().and_then(|b| b.build()) {
Ok(conn) => conn,
Err(e) => return SaveOutcome::UseRfd(e.to_string()),
};
loop {
let Some(saved) = save_file(&conn, &req)? else { return Ok(None) };
let picked = saved.filter.as_deref().and_then(|label| req.filters.iter().position(|f| f.name == label));
// A typed extension is the user's own: `with_chosen_type` keeps one it recognises.
let exts: &[String] = match chosen_type(&req.filters, picked) {
Some(i) => &req.filters[i].extensions,
None => &[],
let saved = match save_file(&conn, &req, cancel) {
Ok(Decision::Saved(saved)) => saved,
Ok(Decision::Cancelled) => return SaveOutcome::Cancelled,
Ok(Decision::Retry) => return SaveOutcome::UseRfd(CLOSED_AT_ONCE.into()),
Ok(Decision::Unavailable(why)) | Err(why) => return SaveOutcome::UseRfd(why),
};
let picked = saved.filter.as_deref().and_then(|label| req.filters.iter().position(|f| f.name == label));
let chosen = chosen_type(&req.filters, picked);
if chosen.is_none() && is_ambiguous(&req.filters, &saved.path) {
return SaveOutcome::Unavailable(AMBIGUOUS.into());
}
// A typed extension is the user's own: `with_chosen_type` keeps one it recognises.
let exts: &[String] = chosen.and_then(|i| req.filters.get(i)).map_or(&[], |f| f.extensions.as_slice());
let path = with_chosen_type(&saved.path, req.suggested.as_deref(), exts, &req.filters);
if path == saved.path || !path.exists() {
return Ok(Some(path));
return SaveOutcome::Saved(path);
}
req.name = path.file_name().map(|n| n.to_string_lossy().into_owned());
req.suggested = req.name.clone();
+18
View File
@@ -1,6 +1,24 @@
use super::*;
use craft_ui::testing::trial;
/// A portal answer falls back to another dialog only when the portal failed: a quick code 2 is a
/// dialog that never showed, a slow one is Esc, a queued cancel wins over a late answer, and a
/// failed or empty answer is unavailable.
#[trial]
fn a_portal_answer_falls_back_only_when_it_failed() {
let nothing: HashMap<String, OwnedValue> = HashMap::new();
let file = HashMap::from([("uris".to_owned(), Value::from(vec!["file:///s/a.txt".to_owned()]).try_to_owned().expect("an owned value"))]);
let (quick, slow) = (Duration::ZERO, TOO_QUICK);
assert_eq!(classify(2, quick, false, false, &nothing), Decision::Retry, "a dialog that closed at once never showed");
assert_eq!(classify(2, slow, false, false, &nothing), Decision::Cancelled, "Esc in GNOME's dialog is a cancel");
assert_eq!(classify(1, quick, false, false, &nothing), Decision::Cancelled, "Cancel is never asked again");
assert!(matches!(classify(0, slow, false, false, &file), Decision::Saved(saved) if saved.path == *"/s/a.txt"), "a save names its file");
assert_eq!(classify(0, slow, true, false, &file), Decision::Cancelled, "an answer after a queued cancel is a cancel");
assert!(matches!(classify(0, slow, false, true, &nothing), Decision::Unavailable(_)), "the portal left the bus");
assert!(matches!(classify(3, slow, false, false, &file), Decision::Unavailable(_)), "another code is a failure");
assert!(matches!(classify(0, slow, false, false, &nothing), Decision::Unavailable(_)), "a save without a file");
}
#[trial]
fn file_uris_become_local_paths() {
assert_eq!(file_uri_path("file:///home/me/Untitled-1.psd"), Some(PathBuf::from("/home/me/Untitled-1.psd")));
+11 -8
View File
@@ -10,8 +10,11 @@
//! The probe only ever explains an empty answer; it never stops a dialog from opening. Anything
//! it can't tell counts as present, so a working system never sees the cause.
// Only Linux probes; the types and helpers stay testable on every platform.
#![cfg_attr(not(target_os = "linux"), allow(dead_code))]
// Only Linux and the BSDs probe; the types and helpers stay testable on every platform.
#![cfg_attr(
not(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd")),
allow(dead_code)
)]
use std::sync::OnceLock;
@@ -52,10 +55,10 @@ fn on_path(program: &str, path: &std::ffi::OsStr) -> bool {
}
/// Looks for the file dialog backends on a helper thread (the portal call can take a moment).
/// Runs once per process, and only on Linux.
/// Runs once per process, and only on Linux and the BSDs.
// pc: apps/photocraft/src/file_dialog_probe.rs:56 start
pub(crate) fn start() {
#[cfg(target_os = "linux")]
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))]
{
use std::sync::Once;
static STARTED: Once = Once::new();
@@ -112,7 +115,7 @@ fn ldconfig_output_is_valid(output: &str) -> bool {
/// Whether the linker cache lists `soname`; `None` when the cache can't be read, which proves
/// nothing (musl, NixOS, some containers).
// pc: apps/photocraft/src/linux_libs.rs:247 read_ldconfig, :270 cached
#[cfg(target_os = "linux")]
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))]
fn linker_cache_has(soname: &str) -> Option<bool> {
// `/sbin` isn't on a normal user's PATH on Debian. The listing is parsed, so it must be the
// untranslated one.
@@ -131,7 +134,7 @@ fn linker_cache_has(soname: &str) -> Option<bool> {
/// one a property read fails with `InvalidArgs` ("No such interface"). The interface list answers
/// the question directly.
// pc: apps/photocraft/src/file_dialog_probe.rs:79 file_chooser_portal
#[cfg(target_os = "linux")]
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))]
fn file_chooser_portal() -> Option<bool> {
const REPLY_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(5);
let Ok(conn) = zbus::blocking::connection::Builder::session().and_then(|b| b.method_timeout(REPLY_TIMEOUT).build()) else {
@@ -153,7 +156,7 @@ fn file_chooser_portal() -> Option<bool> {
/// Whether introspection XML lists the portal's `FileChooser` interface (not a longer name such as
/// `FileChooser2`).
// pc: apps/photocraft/src/file_dialog_probe.rs:102 interface_listed
#[cfg(target_os = "linux")]
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))]
fn interface_listed(xml: &str) -> bool {
["\"", "'"].iter().any(|quote| xml.contains(&format!("<interface name={quote}org.freedesktop.portal.FileChooser{quote}")))
}
@@ -162,7 +165,7 @@ fn interface_listed(xml: &str) -> bool {
/// service, object or interface isn't there, `None` for anything else (a timeout, a dropped
/// connection, an unknown error), which counts as present.
// pc: apps/photocraft/src/file_dialog_probe.rs:110 classify_error
#[cfg(target_os = "linux")]
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))]
fn classify_error(e: &zbus::Error) -> Option<bool> {
use zbus::fdo::Error as Fdo;
// Names a bus daemon or portal answers with when the thing asked about is absent.
+2 -2
View File
@@ -25,7 +25,7 @@ fn a_dialog_is_explained_only_when_no_backend_can_show_one() {
assert_eq!(problem(findings(None, Some(false), false)).as_deref(), Some("no desktop portal offers a file chooser"));
}
#[cfg(target_os = "linux")]
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))]
#[trial]
fn the_interface_list_says_whether_a_file_chooser_is_offered() {
let xml = |name: &str, quote: char| format!("<node><interface name={quote}{name}{quote}><method name=\"OpenFile\"/></interface></node>");
@@ -36,7 +36,7 @@ fn the_interface_list_says_whether_a_file_chooser_is_offered() {
assert!(!interface_listed(""));
}
#[cfg(target_os = "linux")]
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))]
#[trial]
fn dbus_errors_for_a_missing_interface_mean_absent() {
use zbus::fdo::Error as Fdo;
+12
View File
@@ -59,6 +59,18 @@ impl Files for ScriptedFiles {
Err(FileError::Unsupported)
}
fn save(&self, request: PickRequest, _bytes: Vec<u8>) -> PickId {
self.pick(request)
}
fn can_pick(&self) -> bool {
true
}
fn browser_saves(&self) -> bool {
false
}
fn last_folder(&self, _purpose: &str) -> Option<PathBuf> {
None
}
+269 -26
View File
@@ -23,8 +23,14 @@ use std::sync::{Arc, Mutex};
use craft_host::{FileError, Files, PickAnswer, PickId, PickRequest, Wake};
use raw_window_handle::{HasDisplayHandle, HasWindowHandle};
#[cfg(feature = "ui")]
use craft_browse::places::{FolderCache, SystemDirectories};
#[cfg(feature = "ui")]
use craft_host::ThreadJobs;
use craft_host::{PickKind, Picked};
#[cfg(feature = "ui")]
use crate::ui::FileChooser;
use crate::{Answer, Dialogs, FileDialog, Filter, Kind, Message, MessageButtons, MessageLevel, MessageResult, probe};
/// The words of the Replace question: a native message box, so they come from the app's catalog
@@ -61,6 +67,19 @@ fn file_error(e: std::io::Error, path: &Path) -> FileError {
}
}
/// Writes `bytes` to `path` atomically: the one write of [`Files::write`] and of a finished save.
// pc: apps/photocraft/src/services.rs:359 write_atomic
fn write_file(path: &Path, bytes: &[u8]) -> Result<(), FileError> {
craft_atomic::atomic_write(path, bytes).map_err(|e| file_error(e, path))
}
/// The folder a picker starts in: the request's own folder, else the purpose's remembered one
/// (`last`), else the request's first-time folder. The native panels and the fallback chooser
/// both start here.
fn start_folder(request: &PickRequest, last: Option<&Path>) -> Option<PathBuf> {
request.directory.clone().or_else(|| last.map(Path::to_path_buf)).or_else(|| request.default_directory.clone())
}
/// The name a Save panel starts with. Where the panel adds the filter's extension itself
/// (`adds_extension`, Windows), a lowercase extension is left off so the name does not end up
/// doubled; an uppercase extension is the user's spelling and stays.
@@ -151,6 +170,8 @@ struct Pending {
request: PickRequest,
/// The Save path waiting on the replace question's answer.
awaiting_replace: Option<ReplaceQuestion>,
/// What a [`Files::save`] writes to the settled path.
bytes: Option<Vec<u8>>,
}
/// A Save answer that collides with an existing file after the extension policy: the path the
@@ -170,6 +191,17 @@ struct AskedPrompt {
dialog: Option<craft_ui::dialog::DialogId>,
}
/// A pick the fallback chooser answers on the app's `DialogHost`: the ticket, its request, why the
/// native dialog was not used (`None` when the request asked for the chooser), and the chooser's
/// id once it is open.
#[cfg(feature = "ui")]
struct AskedChooser {
id: PickId,
request: PickRequest,
cause: Option<String>,
dialog: Option<craft_ui::dialog::DialogId>,
}
/// The native file service: the Host's side. Requests go to the [`FilePanels`] over a channel;
/// answers come back through the shared state.
pub struct FileService {
@@ -192,6 +224,12 @@ pub struct FilePanels {
/// The replace questions [`pump_with`](FilePanels::pump_with) put on the app's dialog host.
#[cfg(feature = "ui")]
prompts: Vec<AskedPrompt>,
/// The picks [`pump_with`](FilePanels::pump_with) answers with the fallback chooser, in order.
#[cfg(feature = "ui")]
choosers: Vec<AskedChooser>,
/// Repaint request for the fallback chooser's folder jobs.
#[cfg(feature = "ui")]
wake: Wake,
}
struct Inner {
@@ -226,6 +264,10 @@ impl FileService {
backend_problem: probe::known_problem,
#[cfg(feature = "ui")]
prompts: Vec::new(),
#[cfg(feature = "ui")]
choosers: Vec::new(),
#[cfg(feature = "ui")]
wake: wake.clone(),
};
(Self { inner, wake, to_panels }, panels)
}
@@ -295,6 +337,7 @@ impl FilePanels {
// pc: crates/ui-egui/src/file_dialog.rs:310 poll_file_dialog, :349 finish_file_dialog, :365 saved_path
pub fn pump<W: HasWindowHandle + HasDisplayHandle>(&mut self, parent: Option<&W>) {
self.start_requests();
self.cancel_forgotten();
// A replace question queued by `finish` shows in the same pass, so the loop runs until no
// answer is left to settle.
loop {
@@ -304,7 +347,7 @@ impl FilePanels {
break;
}
for (id, answer) in answers {
if let Some(question) = self.finish(id, answer) {
if let Some(question) = self.finish(id, answer, true) {
self.dialogs.ask_message(self.replace_message(&question.settled), id);
}
}
@@ -319,11 +362,23 @@ impl FilePanels {
/// open makes the question wait its turn. The question is a prompt instance
/// ([`StandardPrompt::instance`](craft_ui::dialog::StandardPrompt::instance)), so the app's
/// `take::<StandardPrompt>()` and its own prompts leave its answer alone.
///
/// A request with [`PickRequest::fallback`] set, and one whose native dialog answered
/// [`Answer::Unavailable`], is answered by the in-app [`FileChooser`] on the same host instead,
/// one chooser at a time; its answer is settled like a native one.
// pc: crates/ui-egui/src/dialogs/replace_prompt.rs:23 open
#[cfg(feature = "ui")]
pub fn pump_with<W: HasWindowHandle + HasDisplayHandle>(&mut self, dialogs: &mut craft_ui::dialog::DialogHost, parent: Option<&W>) {
self.collect_prompt_answers(dialogs);
self.start_requests();
self.collect_chooser_answers(dialogs);
while let Ok((id, request)) = self.requests.try_recv() {
if request.fallback {
self.choosers.push(AskedChooser { id, request, cause: None, dialog: None });
} else {
self.ask_panel(id, &request);
}
}
self.cancel_forgotten();
loop {
self.dialogs.show_pending(parent);
let answers = self.dialogs.take_answers();
@@ -331,15 +386,82 @@ impl FilePanels {
break;
}
for (id, answer) in answers {
if let Some(question) = self.finish(id, answer) {
// No native dialog could show: the chooser answers the pick, unless it was
// forgotten or is settling a replace question.
let answer = match answer {
Answer::Unavailable(why) => {
let unsettled = lock(&self.inner).pending.get(&id).filter(|p| p.awaiting_replace.is_none()).map(|p| p.request.clone());
match unsettled {
Some(request) => {
self.choosers.push(AskedChooser { id, request, cause: Some(why), dialog: None });
continue;
}
None => Answer::Unavailable(why),
}
}
answer => answer,
};
if let Some(question) = self.finish(id, answer, true) {
self.prompts.push(AskedPrompt { id, question, dialog: None });
}
}
}
self.open_choosers(dialogs);
self.open_prompts(dialogs);
self.mark_busy();
}
/// Opens the next waiting chooser when none is open. Its folder source lists the file system
/// on threads and repaints the app when a listing is in.
#[cfg(feature = "ui")]
fn open_choosers(&mut self, dialogs: &mut craft_ui::dialog::DialogHost) {
if dialogs.get::<FileChooser>().is_some() {
return;
}
let Some(asked) = self.choosers.iter_mut().find(|a| a.dialog.is_none()) else { return };
let last = lock(&self.inner).last_folder.get(&asked.request.purpose).cloned();
let mut request = asked.request.clone();
request.directory = start_folder(&request, last.as_deref());
let folders = FolderCache::new(Arc::new(SystemDirectories), Arc::new(ThreadJobs), self.wake.clone());
asked.dialog = Some(dialogs.open(FileChooser::new(request, asked.cause.clone(), folders)));
}
/// Settles the picks whose chooser has finished: OK with its answer, anything else as
/// `Cancelled`, the same for a chooser closed from outside. A pick forgotten before its
/// chooser opened is dropped; one forgotten while it is open is dropped by `finish`.
#[cfg(feature = "ui")]
fn collect_chooser_answers(&mut self, dialogs: &mut craft_ui::dialog::DialogHost) {
use craft_ui::dialog::DialogResult;
for asked in std::mem::take(&mut self.choosers) {
let answer = match asked.dialog {
None => {
let pending = lock(&self.inner).pending.contains_key(&asked.id);
if pending {
self.choosers.push(asked);
}
continue;
}
Some(dialog) => match dialogs.take_by_id::<FileChooser>(dialog) {
Some(DialogResult::Ok(answer)) => answer,
Some(_) => Answer::Cancelled,
None if dialogs.get_by_id::<FileChooser>(dialog).is_some() => {
// A forgotten pick has no one to answer: its chooser closes, as its
// native panel does (`cancel_forgotten`).
if !lock(&self.inner).pending.contains_key(&asked.id) {
dialogs.close_by_id(dialog);
}
self.choosers.push(asked);
continue;
}
None => Answer::Cancelled,
},
};
if let Some(question) = self.finish(asked.id, answer, false) {
self.prompts.push(AskedPrompt { id: asked.id, question, dialog: None });
}
}
}
/// The dialog ids of the Replace questions open on the app's dialog host, for an app that lists
/// its open prompts to automation (`ui.inspect`) and answers them by id
/// (`DialogHost::confirm_by_id`).
@@ -393,12 +515,23 @@ impl FilePanels {
/// Drains the requests the service queued into the native panels' queue.
fn start_requests(&mut self) {
while let Ok((id, request)) = self.requests.try_recv() {
let folder = lock(&self.inner).last_folder.get(&request.purpose).cloned();
let dialog = self.file_dialog(&request, folder.as_deref());
self.dialogs.ask(dialog, id);
self.ask_panel(id, &request);
}
}
/// Queues the native panel of pick `id`.
fn ask_panel(&mut self, id: PickId, request: &PickRequest) {
let folder = lock(&self.inner).last_folder.get(&request.purpose).cloned();
let dialog = self.file_dialog(request, folder.as_deref());
self.dialogs.ask(dialog, id);
}
/// Closes the open panel of a pick that was forgotten (a closed document's portal Save).
fn cancel_forgotten(&mut self) {
let inner = &self.inner;
self.dialogs.cancel_open_if(|id| !lock(inner).pending.contains_key(id));
}
fn mark_busy(&self) {
lock(&self.inner).panel_busy = self.dialogs.is_open() || self.dialogs.queued() > 0;
}
@@ -416,7 +549,7 @@ impl FilePanels {
});
dialog.title = request.title.clone();
dialog.filters = request.filters.iter().map(|f| Filter { name: f.name.clone(), extensions: f.extensions.clone() }).collect();
dialog.directory = request.directory.clone().or_else(|| last_folder.map(Path::to_path_buf)).or_else(|| request.default_directory.clone());
dialog.directory = start_folder(request, last_folder);
if request.kind == PickKind::Save {
let adds_extension = cfg!(windows) && !request.filters.is_empty();
dialog.file_name = request.file_name.as_deref().and_then(|name| dialog_file_name(name, adds_extension));
@@ -471,10 +604,11 @@ impl FilePanels {
/// the policy and guard, `Unavailable` stays `Unavailable` with the cause, and a `Cancelled` on a
/// system where the probe found no dialog backend becomes `Unavailable` with the probe's
/// cause. A Save that needs the replace
/// question stays pending and returns the question for the caller to ask.
fn finish(&mut self, id: PickId, answer: Answer) -> Option<ReplaceQuestion> {
let pending = lock(&self.inner).pending.remove(&id)?;
let picked = match (answer, pending.awaiting_replace) {
/// question stays pending and returns the question for the caller to ask. `from_panel` says a
/// native panel answered, not the fallback chooser, whose Cancel is always the user's.
fn finish(&mut self, id: PickId, answer: Answer, from_panel: bool) -> Option<ReplaceQuestion> {
let Pending { request, awaiting_replace, bytes } = lock(&self.inner).pending.remove(&id)?;
let picked = match (answer, awaiting_replace) {
(Answer::Message(result), Some(question)) => {
let replace =
matches!(&result, MessageResult::Ok) || matches!(&result, MessageResult::Custom(label) if *label == self.replace_words.replace);
@@ -482,12 +616,12 @@ impl FilePanels {
}
(Answer::Paths(paths), _) if paths.is_empty() => Picked::Cancelled,
(Answer::Paths(mut paths), _) => {
if pending.request.kind == PickKind::Save {
if request.kind == PickKind::Save {
let answered = paths.swap_remove(0);
let settled = Self::settled_save_path(self.extension_policy, &answered, pending.request.suggested_extension.as_deref());
let settled = Self::settled_save_path(self.extension_policy, &answered, request.suggested_extension.as_deref());
if self.replace_guard == ReplaceGuard::AskWhenUnasked && Self::replaces_unasked(&answered, &settled) {
let question = ReplaceQuestion { answered, settled };
lock(&self.inner).pending.insert(id, Pending { request: pending.request, awaiting_replace: Some(question.clone()) });
lock(&self.inner).pending.insert(id, Pending { request, awaiting_replace: Some(question.clone()), bytes });
return Some(question);
}
paths = vec![settled];
@@ -497,10 +631,10 @@ impl FilePanels {
(Answer::Unavailable(why), _) => Picked::Unavailable(why),
// A panel that answers nothing on a system without a dialog backend did not get
// cancelled; the probe knows why.
(Answer::Cancelled, None) => (self.backend_problem)().map_or(Picked::Cancelled, Picked::Unavailable),
(Answer::Cancelled, None) if from_panel => (self.backend_problem)().map_or(Picked::Cancelled, Picked::Unavailable),
(Answer::Cancelled | Answer::Message(_), _) => Picked::Cancelled,
};
self.complete(id, pending.request, picked);
self.complete(id, request, picked, bytes);
None
}
@@ -508,12 +642,20 @@ impl FilePanels {
/// `Cancelled` otherwise. A forgotten pick has nothing to settle.
#[cfg(feature = "ui")]
fn settle_replace(&mut self, id: PickId, replace: bool) {
let Some(Pending { request, awaiting_replace: Some(question) }) = lock(&self.inner).pending.remove(&id) else { return };
self.complete(id, request, if replace { Picked::Paths(vec![question.settled]) } else { Picked::Cancelled });
let Some(Pending { request, awaiting_replace: Some(question), bytes }) = lock(&self.inner).pending.remove(&id) else { return };
self.complete(id, request, if replace { Picked::Paths(vec![question.settled]) } else { Picked::Cancelled }, bytes);
}
/// Remembers the folder of a chosen path and queues the answer.
fn complete(&self, id: PickId, request: PickRequest, picked: Picked) {
/// Writes a save's `bytes` to the settled path (a failed write answers `Failed` with the
/// system's message), remembers the folder of a chosen path and queues the answer.
fn complete(&self, id: PickId, request: PickRequest, picked: Picked, bytes: Option<Vec<u8>>) {
let picked = match (picked, bytes) {
(Picked::Paths(paths), Some(bytes)) => match paths.first().map(|path| write_file(path, &bytes)) {
Some(Err(e)) => Picked::Failed(e.to_string()),
_ => Picked::Paths(paths),
},
(picked, _) => picked,
};
let mut inner = lock(&self.inner);
if let Picked::Paths(paths) = &picked
&& let Some(first) = paths.first()
@@ -527,14 +669,16 @@ impl FilePanels {
}
}
impl Files for FileService {
impl FileService {
/// Allocates the ticket of `request`, counts it pending and queues it for the panels; a save's
/// `bytes` wait in the pending entry for the settled path.
// new: ticket allocation and queueing on `Dialogs::ask`
fn pick(&self, request: PickRequest) -> PickId {
fn ask(&self, request: PickRequest, bytes: Option<Vec<u8>>) -> PickId {
let id = {
let mut inner = lock(&self.inner);
inner.next += 1;
let id = PickId(inner.next);
inner.pending.insert(id, Pending { request: request.clone(), awaiting_replace: None });
inner.pending.insert(id, Pending { request: request.clone(), awaiting_replace: None, bytes });
id
};
// The panels gone (the app is shutting down) leaves the ticket unanswered.
@@ -542,6 +686,12 @@ impl Files for FileService {
self.wake.wake();
id
}
}
impl Files for FileService {
fn pick(&self, request: PickRequest) -> PickId {
self.ask(request, None)
}
fn take_answer(&self, id: PickId) -> Option<Picked> {
let mut inner = lock(&self.inner);
@@ -549,7 +699,8 @@ impl Files for FileService {
inner.answered.remove(at).map(|a| a.picked)
}
// A ticket still pending leaves `pending`, so the answer the panel gives later is dropped by `finish`.
// A ticket still pending leaves `pending`, so the answer the panel gives later is dropped by
// `finish`, and the next pump closes its portal Save (`cancel_forgotten`).
fn forget(&self, id: PickId) {
let mut inner = lock(&self.inner);
inner.pending.remove(&id);
@@ -566,9 +717,22 @@ impl Files for FileService {
std::fs::read(path).map_err(|e| file_error(e, path))
}
// pc: apps/photocraft/src/services.rs:359 write_atomic
fn write(&self, path: &Path, bytes: &[u8]) -> Result<(), FileError> {
craft_atomic::atomic_write(path, bytes).map_err(|e| file_error(e, path))
write_file(path, bytes)
}
/// Queues a Save pick, then writes `bytes` to the settled path and answers `Paths` or
/// `Failed`.
fn save(&self, request: PickRequest, bytes: Vec<u8>) -> PickId {
self.ask(request, Some(bytes))
}
fn can_pick(&self) -> bool {
true
}
fn browser_saves(&self) -> bool {
false
}
fn last_folder(&self, purpose: &str) -> Option<PathBuf> {
@@ -700,6 +864,85 @@ mod service_tests {
let _ = std::fs::remove_dir_all(&dir);
}
// A save is a ticketed pick that writes: the answer names the written file once; a target
// that cannot be written answers `Failed`, which names no path.
#[trial]
fn a_save_writes_the_bytes_once_and_answers_by_ticket() {
let dir = std::env::temp_dir().join(format!("craft-dialogs-save-{}", std::process::id()));
std::fs::create_dir_all(&dir).expect("scratch dir");
let written = dir.join("Notes.txt");
let unwritable = dir.join("missing").join("Notes.txt");
let (service, mut panels, _) = service_with(vec![Answer::Paths(vec![written.clone()]), Answer::Paths(vec![unwritable.clone()])]);
let saved = service.save(PickRequest::save("export"), b"hello".to_vec());
assert!(service.pick_pending(), "the save waits for its panel");
panels.pump(NONE);
assert_eq!(service.take_answer(saved), Some(Picked::Paths(vec![written.clone()])));
assert_eq!(std::fs::read(&written).expect("the save wrote the file"), b"hello");
assert_eq!(service.take_answer(saved), None, "an answer is read once");
assert!(!service.pick_pending());
let failed = service.save(PickRequest::save("export"), b"lost".to_vec());
panels.pump(NONE);
let picked = answered(&service, failed);
assert!(matches!(picked, Picked::Failed(_)), "{picked:?}");
assert_eq!(picked.first_path(), None);
assert!(!unwritable.exists());
let _ = std::fs::remove_dir_all(&dir);
}
// A closed document forgets its save: the portal Save on screen is cancelled, and the answer it
// gives anyway is dropped without a write.
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))]
#[trial]
fn forgetting_a_pending_save_cancels_its_panel() {
let late = std::env::temp_dir().join(format!("craft-dialogs-forgotten-{}.txt", std::process::id()));
let (service, mut panels) = FileService::new(Wake::none());
panels.backend_problem = || None;
let cancel = crate::portal::Cancel::default();
let shown = cancel.clone();
let replies: Rc<RefCell<Vec<crate::Reply>>> = Rc::default();
let kept = replies.clone();
panels.dialogs.set_custom(move |_, reply| {
kept.borrow_mut().push(reply);
crate::native::Shown { cancel: Some(shown.clone()) }
});
let id = service.save(PickRequest::save("export"), b"late".to_vec());
panels.pump(NONE);
assert!(!cancel.is_cancelled(), "a save still wanted stays open");
service.forget(id);
panels.pump(NONE);
assert!(cancel.is_cancelled(), "the forgotten save's panel is cancelled");
let reply = replies.borrow_mut().remove(0);
reply.send(Answer::Paths(vec![late.clone()]));
panels.pump(NONE);
assert!(service.take_answer(id).is_none(), "the late answer stays dropped");
assert!(!late.exists(), "nothing is written for a forgotten save");
}
// A closed document forgets its save: the fallback chooser on screen closes with the next
// pass of the host, and nothing is answered for the ticket.
#[cfg(feature = "ui")]
#[trial]
fn forgetting_a_pending_save_closes_its_chooser() {
use craft_ui::testing::Fixture;
let (service, mut panels) = FileService::scripted(Wake::none(), []);
let host = Rc::new(RefCell::new(craft_ui::dialog::DialogHost::new()));
let shown = host.clone();
let mut fixture = Fixture::new(move |ui| shown.borrow_mut().run(ui));
let id = service.save(PickRequest::save("export").fallback(true), b"late".to_vec());
panels.pump_with(&mut host.borrow_mut(), NONE);
assert!(host.borrow().is_open::<FileChooser>(), "the chooser opens for the request");
service.forget(id);
panels.pump_with(&mut host.borrow_mut(), NONE);
fixture.idle(2);
panels.pump_with(&mut host.borrow_mut(), NONE);
assert!(!host.borrow().is_open::<FileChooser>(), "the forgotten save's chooser is closed");
assert!(service.take_answer(id).is_none());
}
// Saving over an existing `PHOTO.PNG` with Lowercase Extension on writes `PHOTO.PNG`, the
// file the panel asked about, not a new `PHOTO.png` beside it (on a file system that tells
// letter case apart) or a renamed one (on one that does not). A new name is still lowercased.
+45 -1
View File
@@ -38,7 +38,10 @@ fn held() -> (Dialogs<Rc<str>>, Shown, Arc<AtomicUsize>) {
}));
let shown = Rc::new(RefCell::new(Vec::new()));
let log = shown.clone();
dialogs.set_custom(move |request, reply| log.borrow_mut().push((request, reply)));
dialogs.set_custom(move |request, reply| {
log.borrow_mut().push((request, reply));
crate::native::Shown::default()
});
(dialogs, shown, wakes)
}
@@ -76,3 +79,44 @@ fn a_worker_that_ends_without_answering_closes_the_dialog() {
dialogs.show_pending(NONE);
assert_eq!(shown.borrow().len(), 1, "the next request shows");
}
/// A scripted dialog: it stays open for `open` on the test's clock, then answers `answer`.
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))]
async fn scripted(answer: Answer, open: std::time::Duration, clock: Rc<std::cell::Cell<std::time::Duration>>) -> Answer {
clock.set(clock.get() + open);
answer
}
/// An empty answer at once is a dialog that never showed: it is asked again (without a parent),
/// and empty at once again is unavailable. A slow empty answer is the user's cancel.
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))]
#[trial]
fn a_dialog_that_closes_at_once_is_asked_again_without_a_parent() {
use crate::native::timed;
use crate::portal::{CLOSED_AT_ONCE, TOO_QUICK};
use std::cell::Cell;
use std::time::Duration;
let (at_once, slow) = (Duration::from_millis(5), TOO_QUICK + Duration::from_millis(1));
let picked = Answer::Paths(vec![std::path::PathBuf::from("/s/a.txt")]);
// The first dialog's answer and how long it was open, the same for the second; gives the
// answer and whether the second was asked.
let run = |first: (Answer, Duration), second: (Answer, Duration)| {
let clock = Rc::new(Cell::new(Duration::ZERO));
let again = Rc::new(Cell::new(false));
let (opened, reopened, read, asked) = (clock.clone(), clock.clone(), clock, again.clone());
let answer = futures_lite::future::block_on(timed(
scripted(first.0, first.1, opened),
move || {
asked.set(true);
scripted(second.0, second.1, reopened)
},
move || read.get(),
));
(answer, again.get())
};
assert_eq!(run((Answer::Cancelled, at_once), (Answer::Cancelled, at_once)), (Answer::Unavailable(CLOSED_AT_ONCE.into()), true));
assert_eq!(run((Answer::Cancelled, at_once), (picked.clone(), at_once)), (picked.clone(), true), "the second dialog's pick counts");
assert_eq!(run((Answer::Cancelled, slow), (picked.clone(), at_once)), (Answer::Cancelled, false), "a slow empty answer is a cancel");
assert_eq!(run((picked.clone(), at_once), (Answer::Cancelled, at_once)), (picked, false), "a quick pick is a pick");
}
+644
View File
@@ -0,0 +1,644 @@
//! [`FileChooser`]: the in-app file chooser a pick falls back to when no native dialog can open.
//!
//! The folder reading is craft-browse's: the chooser asks its [`FolderCache`] for a folder's entries
//! ([`FolderCache::entries`]), which lists them in a job, with the hidden rule and the natural order of the places
//! tree, and answers `Loading` until the job lands. No folder is read in the pass.
mod accept;
#[cfg(test)]
mod tests;
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex, PoisonError};
use craft_behavior::{IconId, Selection, SelectionChange, keyed};
use craft_browse::places::{Entries, Entry, FolderCache, StandardFolder, folder_within};
use craft_host::{FileFilter, PickKind, PickRequest};
use craft_ui::bars::{BreadcrumbBar, path_crumbs};
use craft_ui::contract::{Bind, CollectionEvent, Entry as Choice, Props as _, SelectMode, Show as _, ShowCollection as _, ShowContainer as _};
use craft_ui::dialog::{
ChildDialog, Dialog, DialogId, DialogResult, DialogStack, FieldRefusal, PromptChoice, StackDialog, StandardPrompt, dialog_id,
};
use craft_ui::display::Text;
use craft_ui::form::Field;
use craft_ui::list::{List, ListRow};
use craft_ui::pickers::Select;
use craft_ui::primitives::IconSpec;
use craft_ui::runtime::env::Env;
use craft_ui::runtime::words::CommonWords;
use craft_ui::sections::{DialogRole, FooterButton};
use craft_ui::text::TextField;
use egui::{Context, Ui};
use serde_json::{Value, json};
use self::accept::{Accept, accept, needs_home, typed_path};
use super::UnavailableWords;
use crate::Answer;
/// At most this many entries of a folder are read, so a huge folder cannot stall the listing job.
// ui-egui: crates/ui-egui/src/file_browser.rs:22 (`MAX_SCANNED`).
const SCANNED: usize = 100_000;
/// The rows the list shows before it scrolls: the list owns its scroll, so the dialog's body does not scroll along it.
const LIST_ROWS: u16 = 12;
/// At most this many entries are shown; a bigger folder shows the first ones and says so.
// ui-egui: crates/ui-egui/src/file_browser.rs:20 (`MAX_LISTED`).
const SHOWN: usize = 5_000;
craft_ui::words! {
/// The words of the [`FileChooser`].
pub struct ChooserWords {
open_title: "fileChooser.openTitle" = "Open";
save_title: "fileChooser.saveTitle" = "Save As";
folder_title: "fileChooser.folderTitle" = "Choose a Folder";
open: "fileChooser.open" = "Open";
save: "fileChooser.save" = "Save";
choose: "fileChooser.choose" = "Choose";
location: "fileChooser.location" = "Folder path";
path: "fileChooser.path" = "Folder";
home: "fileChooser.home" = "Home";
entries: "fileChooser.entries" = "Files and folders";
name: "fileChooser.name" = "File name";
types: "fileChooser.types" = "File type";
all_files: "fileChooser.allFiles" = "All files";
loading: "fileChooser.loading" = "Reading the folder…";
empty: "fileChooser.empty" = "No items to show.";
cant_read: template "fileChooser.cantRead" = "This folder can't be read: {error}";
not_found: template "fileChooser.notFound" = "{name} wasn't found.";
truncated: template "fileChooser.truncated" = "Showing the first {count} items.";
}
}
/// What the chooser's listing of the shown folder is in this pass.
#[derive(Clone, Debug, PartialEq)]
enum View {
/// No folder yet: the home folder is still being looked up.
Wait,
/// The listing job runs.
Loading,
/// The folder can't be read; the system's message.
Failed(String),
/// The entries are ready; `truncated` when the folder had more than were read or shown.
Ready { truncated: bool },
}
/// The view of a listing for a pick of `kind` under `filter`, and the entries to show: folders first, then files, each
/// group in the listing's order, at most [`SHOWN`].
fn shape(kind: PickKind, filter: Option<&FileFilter>, entries: Entries<'_>) -> (View, Vec<Entry>) {
match entries {
Entries::Loading => (View::Loading, Vec::new()),
Entries::Failed(message) => (View::Failed(message.to_owned()), Vec::new()),
Entries::Ready { entries, truncated } => {
let mut matched: Vec<&Entry> = entries.iter().filter(|entry| shows(kind, filter, entry)).collect();
matched.sort_by_key(|entry| !entry.folder);
let more = matched.len() > SHOWN;
let shown = matched.into_iter().take(SHOWN).cloned().collect();
(View::Ready { truncated: truncated || more }, shown)
}
}
}
/// The Replace question as a child dialog. A host keeps a child's answer for the app, not for its parent, so the
/// prompt files its choice where the chooser reads it on its next pass.
struct ReplaceAsk {
prompt: StandardPrompt,
answer: Arc<Mutex<Option<PromptChoice>>>,
}
impl ReplaceAsk {
fn file(&self, choice: PromptChoice) {
*self.answer.lock().unwrap_or_else(PoisonError::into_inner) = Some(choice);
}
}
impl StackDialog for ReplaceAsk {
type Result = ();
fn id(&self) -> DialogId {
StackDialog::id(&self.prompt)
}
fn instance(&self) -> Option<DialogId> {
StackDialog::instance(&self.prompt)
}
fn show(&mut self, ui: &mut Ui, stack: &DialogStack) -> Option<DialogResult<()>> {
let done = StackDialog::show(&mut self.prompt, ui, stack)?;
self.file(match done {
DialogResult::Ok(answer) => answer.choice,
_ => PromptChoice::Cancel,
});
Some(DialogResult::Ok(()))
}
fn confirm(&mut self, ctx: &Context) -> Option<()> {
let answer = StackDialog::confirm(&mut self.prompt, ctx)?;
self.file(answer.choice);
Some(())
}
fn json_fields(&self) -> Option<Value> {
StackDialog::json_fields(&self.prompt)
}
fn set_json_field(&mut self, ctx: &Context, field: &str, value: Value) -> Result<(), String> {
StackDialog::set_json_field(&mut self.prompt, ctx, field, value)
}
}
/// What the body reported in its last run of a pass.
#[derive(Default)]
struct Seen {
/// Enter in the folder field.
location_submitted: bool,
/// Enter in the name field.
name_submitted: bool,
/// The name field was edited.
name_edited: bool,
/// The crumb opened.
crumb: Option<String>,
/// The list's selection changes, in order.
selection: Vec<SelectionChange<PathBuf>>,
/// The row activated (Enter or a double click).
activated: Option<PathBuf>,
}
/// The fallback file chooser: a folder field, a breadcrumb bar from the home root, a list of the folder's entries,
/// name and type rows for a Save, and the line that says why the native dialog is unavailable. It reads folders only
/// from the [`FolderCache`] its caller gives it.
///
/// - Start: in the request's `directory` (the service resolves it as it does for a native panel), else the Home root
/// of [`FolderCache::roots`].
/// - Listing: folders always show; files show when they match the type picked (a folder pick shows no files). At
/// most 5 000 show, with a note when there were more or the folder was read only in part. The folder is listed
/// again when it is entered and when the window regains focus.
/// - OK, Enter and a double click on a file accept: a folder is entered, a file is opened, a Save to a listed file
/// asks Replace once, a typed path elsewhere is listed first and accepted there. The result is
/// `Ok(Answer::Paths(..))`; Cancel, Escape and the close action give `Cancel`.
/// - Automation fields: `folder`, `name` and `selection` (names in the shown folder); `listed` (read only) says the
/// listing is ready, and `replace` (read only) names the file the open Replace question is about. The question is a
/// child prompt: it is answered as every prompt is.
/// - A second pass in a frame applies only its own input: the listing lands through the cache, and a typed name
/// waiting on it is accepted once, then dropped.
#[derive(craft_ui::contract::Pattern)]
#[pattern(dialog)]
pub struct FileChooser {
request: PickRequest,
cause: Option<String>,
folders: FolderCache,
/// The shown folder; `None` until the home folder is known.
folder: Option<PathBuf>,
/// The folder field's text.
location: String,
/// The name field's text.
name: String,
/// The type picked: an index into the request's filters; past them, every file.
filter: usize,
selection: Selection<PathBuf>,
/// The file whose name the selection put in the name field: its exact path stays the answer while the field
/// holds that name, even after a relisting leaves it out.
chosen: Option<Entry>,
/// Typed text waiting on a listing (or on the home folder) before it is accepted.
pending: Option<String>,
/// The name the last accept did not find.
note: Option<String>,
/// The path the Replace question is open for, and where its answer lands.
replacing: Option<(PathBuf, Arc<Mutex<Option<PromptChoice>>>)>,
/// How many Replace questions were asked: each gets a prompt of its own.
asks: u64,
/// The Replace question the host opens as a child after this pass.
child: Option<ChildDialog>,
}
impl FileChooser {
/// A chooser for `request`. `cause` is the text of the `Picked::Unavailable` that opened it;
/// `folders` is the caller's folder source.
pub fn new(request: PickRequest, cause: Option<String>, folders: FolderCache) -> Self {
// PLAN(platform-w4): start folder resolved in pump_with
let folder = request.directory.clone();
let name = if request.kind == PickKind::Save { request.file_name.clone().unwrap_or_default() } else { String::new() };
let location = folder.as_deref().map(|f| f.to_string_lossy().into_owned()).unwrap_or_default();
Self {
request,
cause,
folders,
folder,
location,
name,
filter: 0,
selection: Selection::default(),
chosen: None,
pending: None,
note: None,
replacing: None,
asks: 0,
child: None,
}
}
/// The home folder: `None` until the roots are listed, then the Home root if there is one.
fn home(&mut self) -> Option<Option<PathBuf>> {
let roots = self.folders.roots()?;
Some(roots.standard.iter().find(|(kind, _)| *kind == StandardFolder::Home).map(|(_, path)| path.clone()))
}
/// Shows `folder`: listed again, with nothing selected and no note.
fn navigate(&mut self, folder: PathBuf) {
self.folders.refresh_folder(&folder);
self.location = folder.to_string_lossy().into_owned();
self.folder = Some(folder);
self.selection = Selection::default();
self.chosen = None;
self.note = None;
}
/// Whether the type selector shows: a Save with types, or an Open with a choice of them.
fn offers_types(&self) -> bool {
!self.request.filters.is_empty() && (self.request.kind == PickKind::Save || self.request.filters.len() > 1)
}
/// The view of the shown folder and its entries to show, from the cache's answer now (queues the listing).
fn list(&mut self) -> (View, Vec<Entry>) {
let Some(folder) = self.folder.clone() else { return (View::Wait, Vec::new()) };
shape(self.request.kind, self.request.filters.get(self.filter), self.folders.entries(&folder, SCANNED))
}
/// [`list`](Self::list) from what the cache holds, for readers that cannot borrow it mutably.
fn peek(&self) -> (View, Vec<Entry>) {
let Some(folder) = self.folder.as_deref() else { return (View::Wait, Vec::new()) };
let held = self.folders.held_entries(folder, SCANNED).unwrap_or(Entries::Loading);
shape(self.request.kind, self.request.filters.get(self.filter), held)
}
/// The `rows` that are selected; when none is, the chosen file whose name `typed` still is.
fn selected(&self, rows: &[Entry], typed: &str) -> Vec<Entry> {
let shown: Vec<Entry> = rows.iter().filter(|entry| self.selection.contains(&entry.path)).cloned().collect();
if shown.is_empty() { self.chosen.iter().filter(|file| file.name == typed).cloned().collect() } else { shown }
}
/// Accepts `typed`: the answer when the chooser finishes, else `None` (it moved, asks Replace, or says why not).
/// Waits for the listing, and for the home folder when the text starts from it.
fn accept_typed(&mut self, typed: String) -> Option<DialogResult<Answer>> {
let home = self.home();
let waits_for_home = home.is_none() && needs_home(typed.trim());
let (view, rows) = self.list();
let ready = matches!(view, View::Ready { .. });
let Some(folder) = self.folder.clone().filter(|_| ready && !waits_for_home) else {
self.pending = Some(typed);
return None;
};
let selected = self.selected(&rows, &typed);
let picked_folder = matches!(selected.as_slice(), [one] if one.folder);
match accept(&self.request, &typed, &folder, &rows, &selected, home.flatten().as_deref()) {
Accept::Open(paths) => return Some(DialogResult::Ok(Answer::Paths(paths))),
Accept::Save(path) => return Some(DialogResult::Ok(Answer::Paths(vec![path]))),
Accept::Replace(path) => {
self.asks += 1;
let name = path.file_name().map_or_else(|| path.to_string_lossy(), |n| n.to_string_lossy()).into_owned();
let answer = Arc::new(Mutex::new(None));
let prompt = StandardPrompt::replace_file(name, None).instance(("craft-dialogs.chooser", self.asks));
self.child = Some(ChildDialog::new(ReplaceAsk { prompt, answer: answer.clone() }));
self.replacing = Some((path, answer));
}
Accept::Enter(path) => {
// A typed folder name is used up by entering it; the name a selected folder leaves alone stays.
if !picked_folder {
self.name.clear();
}
self.navigate(path);
}
Accept::Look { folder, name } => {
let name = name.to_string_lossy().into_owned();
if self.request.kind != PickKind::Folder {
self.name.clone_from(&name);
}
self.navigate(folder);
self.pending = Some(name);
}
Accept::Refuse(name) => self.note = Some(name).filter(|name| !name.is_empty()),
}
None
}
/// Applies one change of the list's selection over `rows`; a selected file's name goes into the name field.
fn select(&mut self, change: SelectionChange<PathBuf>, rows: &[Entry]) {
match change {
SelectionChange::Set(keys) => {
let lead = keys.last().cloned();
self.selection = Selection::new(keys, lead.clone(), lead);
}
SelectionChange::Toggle(key) => {
if self.selection.contains(&key) {
self.selection.items.retain(|item| *item != key);
} else {
self.selection.items.push(key.clone());
self.selection.lead = Some(key);
}
}
SelectionChange::Clear => self.selection = Selection::default(),
_ => return,
}
self.note = None;
let lead = self.selection.lead.clone().filter(|lead| self.selection.contains(lead));
if let Some(file) = lead.and_then(|lead| rows.iter().find(|entry| entry.path == lead && !entry.folder))
&& self.request.kind != PickKind::Folder
{
self.name.clone_from(&file.name);
self.chosen = Some(file.clone());
}
}
/// The crumbs of the shown folder: from the Home root when the folder lies in it, else from the top.
fn crumbs(&mut self, words: &ChooserWords) -> Vec<Choice<String>> {
let Some(folder) = self.folder.clone() else { return Vec::new() };
let all = path_crumbs(&folder.to_string_lossy());
match self.home().flatten().filter(|home| folder_within(&folder, home)) {
Some(home) => {
let below = all.into_iter().filter(|crumb| crumb.value().is_some_and(|path| !folder_within(&home, Path::new(path))));
std::iter::once(Choice::new(home.to_string_lossy().into_owned(), words.home.clone())).chain(below).collect()
}
None => all,
}
}
/// Shows one pass: the chooser, and over it the Replace question while one is open.
fn present(&mut self, ui: &mut Ui) -> Option<DialogResult<Answer>> {
// Folders are not watched, so the listings go stale when the window regains focus, as the places tree's do:
// files changed in another app show on return. egui-winit sends `WindowFocused` from
// `State::on_window_event` (`WindowEvent::Focused`), and only to a frame's first pass, so a second pass does not
// refresh again.
if ui.input(|input| input.events.iter().any(|event| matches!(event, egui::Event::WindowFocused(true)))) {
self.folders.refresh();
}
if self.folder.is_none()
&& let Some(home) = self.home()
{
self.navigate(home.unwrap_or_else(|| PathBuf::from(std::path::MAIN_SEPARATOR_STR)));
}
let (mut view, mut rows) = self.list();
if matches!(view, View::Ready { .. })
&& let Some(typed) = self.pending.take()
{
if let Some(done) = self.accept_typed(typed) {
return Some(done);
}
// The accept may have moved to another folder: show that one's listing.
(view, rows) = self.list();
}
let env = Env::of(ui);
let words = env.words::<ChooserWords>();
let common = env.words::<CommonWords>();
let unavailable = env.words::<UnavailableWords>();
let crumbs = self.crumbs(&words);
let kind = self.request.kind;
let (title, ok) = match kind {
PickKind::Open | PickKind::OpenMany => (words.open_title.clone(), words.open.clone()),
PickKind::Save => (words.save_title.clone(), words.save.clone()),
PickKind::Folder => (words.folder_title.clone(), words.choose.clone()),
};
let title = self.request.title.clone().map_or_else(|| title, craft_ui::runtime::env::Label::from);
let mut types: Vec<Choice<usize>> =
self.request.filters.iter().enumerate().map(|(at, filter)| Choice::new(at, filter.name.clone())).collect();
types.push(Choice::new(self.request.filters.len(), words.all_files.clone()));
let offers_types = self.offers_types();
let names_file = kind != PickKind::Folder;
let filter_before = self.filter;
let buttons = [FooterButton::new(ok, DialogRole::Accept).stays_open(true), FooterButton::new(common.cancel.clone(), DialogRole::Cancel)];
let selection_shown = self.selection.clone();
let FileChooser { cause, location, name, filter, note, .. } = self;
let entries = &rows;
let shown = Dialog::new(title).resizable(true).buttons(buttons).show(ui, |ui, _| {
let mut seen = Seen::default();
if let Some(cause) = cause.as_deref() {
Text::new(unavailable.sentence(cause)).show(ui);
}
// Not a `PathField`: its Browse button picks through `host.files()`, which from inside the fallback
// chooser would open another pick. The folder row is a text field alone, Enter navigating.
Field::new(words.location.clone()).id_salt("location").show(ui, |ui, _| {
seen.location_submitted = TextField::new(words.location.clone(), Bind::bound(&mut *location)).show(ui).submitted;
});
// PLAN: `fair_widths` in ui-widgets `bars/breadcrumb.rs:143` floors a crumb's natural width, so a crumb with a
// fractional width reads as cut (`width < full`) and elides with room to spare; owner: the ui-widgets set.
seen.crumb = BreadcrumbBar::new(words.path.clone(), &crumbs).show(ui).picked;
match &view {
View::Wait | View::Loading => {
Text::new(words.loading.clone()).show(ui);
}
View::Failed(error) => {
Text::new(words.cant_read.fill(&[("error", error.as_str())])).show(ui);
}
View::Ready { .. } if entries.is_empty() => {
Text::new(words.empty.clone()).show(ui);
}
View::Ready { truncated } => {
let source = keyed(entries.as_slice(), |entry: &Entry| entry.path.clone());
let select = if kind == PickKind::OpenMany { SelectMode::Multi } else { SelectMode::Single };
let events = List::new(words.entries.clone())
.select(select)
.type_ahead(true)
.max_rows(LIST_ROWS)
.selection(Bind::given(selection_shown.clone()))
.show_items(ui, &source, &mut |path, _| {
let entry = entries.iter().find(|entry| entry.path == *path);
let icon = if entry.is_some_and(|entry| entry.folder) { "folder" } else { "file" };
ListRow::new(entry.map_or_else(String::new, |entry| entry.name.clone())).icon(IconSpec::svg(IconId::new(icon)))
})
.events;
for event in events {
match event {
CollectionEvent::Selection(change) => seen.selection.push(change),
CollectionEvent::Activate(path) => seen.activated = Some(path),
_ => {}
}
}
if *truncated {
Text::new(words.truncated.fill(&[("count", entries.len().to_string().as_str())])).show(ui);
}
}
}
if let Some(missing) = note.as_deref() {
Text::new(words.not_found.fill(&[("name", missing)])).show(ui);
}
if names_file {
Field::new(words.name.clone()).id_salt("name").show(ui, |ui, _| {
let edited = TextField::new(words.name.clone(), Bind::bound(&mut *name)).show(ui);
seen.name_submitted = edited.submitted;
seen.name_edited = !edited.events.is_empty();
});
}
if offers_types {
Field::new(words.types.clone()).id_salt("types").show(ui, |ui, _| {
Select::new(words.types.clone(), Bind::bound(&mut *filter), &types).show(ui);
});
}
seen
});
if let Some((path, answer)) = self.replacing.clone() {
let given = answer.lock().unwrap_or_else(PoisonError::into_inner).take();
if let Some(choice) = given {
self.replacing = None;
if choice == PromptChoice::Proceed {
return Some(DialogResult::Ok(Answer::Paths(vec![path])));
}
}
return None;
}
if shown.output.closed.is_some() {
return Some(DialogResult::Cancel);
}
let seen = shown.inner.unwrap_or_default();
if self.filter != filter_before {
self.selection = Selection::default();
}
if seen.name_edited {
self.selection = Selection::default();
self.chosen = None;
self.note = None;
}
for change in seen.selection {
self.select(change, &rows);
}
if let Some(crumb) = seen.crumb {
self.navigate(PathBuf::from(crumb));
return None;
}
if seen.location_submitted {
let text = self.location.trim().to_owned();
let home = self.home().flatten();
if let Some(folder) = self.folder.clone().or_else(|| home.clone())
&& let Some(to) = typed_path(&text, &folder, home.as_deref())
{
self.navigate(to);
}
return None;
}
if let Some(path) = seen.activated {
let entry = rows.iter().find(|entry| entry.path == path).cloned()?;
if entry.folder {
self.navigate(entry.path);
return None;
}
self.selection = Selection::single(entry.path.clone());
self.name.clone_from(&entry.name);
let typed = entry.name.clone();
self.chosen = Some(entry);
return self.accept_typed(typed);
}
if shown.output.picked == Some(0) || seen.name_submitted {
let typed = self.name.clone();
return self.accept_typed(typed);
}
None
}
}
/// Whether `entry` shows under `filter`: a folder always does; a file when the pick takes files and it has one of the
/// filter's extensions (any case; `*` takes any), or with no filter.
fn shows(kind: PickKind, filter: Option<&FileFilter>, entry: &Entry) -> bool {
// ui-egui: crates/ui-egui/src/file_browser.rs:50 (`matches`).
if entry.folder {
return true;
}
if kind == PickKind::Folder {
return false;
}
let Some(filter) = filter else { return true };
let extension = Path::new(&entry.name).extension().and_then(|e| e.to_str());
filter.extensions.iter().any(|wanted| wanted == "*" || extension.is_some_and(|ext| ext.eq_ignore_ascii_case(wanted)))
}
impl StackDialog for FileChooser {
type Result = Answer;
fn id(&self) -> DialogId {
dialog_id("fileChooser")
}
fn show(&mut self, ui: &mut Ui, _: &DialogStack) -> Option<DialogResult<Answer>> {
let done = self.present(ui);
self.folders.finish_pass();
done
}
/// OK as its button gives it: the answer when the typed name or the selection is one, else `None` (the chooser
/// moved, waits for its listing, asks Replace or shows why not).
fn confirm(&mut self, _: &Context) -> Option<Answer> {
if self.replacing.is_some() {
return None;
}
let typed = self.name.clone();
match self.accept_typed(typed)? {
DialogResult::Ok(answer) => Some(answer),
_ => None,
}
}
fn take_child(&mut self) -> Option<ChildDialog> {
self.child.take()
}
fn json_fields(&self) -> Option<Value> {
let (view, rows) = self.peek();
let selection: Vec<&str> = self.selected_names(&rows);
let mut fields = json!({
"folder": self.folder.as_deref().map(|f| f.to_string_lossy()),
"name": self.name,
"selection": selection,
"listed": matches!(view, View::Ready { .. }),
});
if let Some((path, _)) = &self.replacing {
fields["replace"] = json!(path.to_string_lossy());
}
Some(fields)
}
fn set_json_field(&mut self, _: &Context, field: &str, value: Value) -> Result<(), String> {
match field {
"folder" => {
let text = value.as_str().ok_or_else(|| FieldRefusal::Rejects(&value).message(field))?.trim().to_owned();
let home = self.home().flatten();
let base = self.folder.clone().or_else(|| home.clone()).unwrap_or_else(|| PathBuf::from(std::path::MAIN_SEPARATOR_STR));
let to = typed_path(&text, &base, home.as_deref()).ok_or_else(|| FieldRefusal::Rejects(&value).message(field))?;
self.navigate(to);
}
"name" if self.request.kind != PickKind::Folder => {
let text = value.as_str().ok_or_else(|| FieldRefusal::Rejects(&value).message(field))?;
self.name = text.to_owned();
self.selection = Selection::default();
self.note = None;
}
"name" => return Err(FieldRefusal::Inactive.message(field)),
"selection" => {
let names: Vec<String> = match &value {
Value::String(one) => vec![one.clone()],
Value::Array(many) => many
.iter()
.map(|v| v.as_str().map(str::to_owned))
.collect::<Option<_>>()
.ok_or_else(|| FieldRefusal::Rejects(&value).message(field))?,
_ => return Err(FieldRefusal::Rejects(&value).message(field)),
};
let (_, rows) = self.list();
let keys: Option<Vec<PathBuf>> =
names.iter().map(|name| rows.iter().find(|entry| entry.name == *name).map(|entry| entry.path.clone())).collect();
let keys = keys.filter(|keys| keys.len() <= 1 || self.request.kind == PickKind::OpenMany);
let Some(keys) = keys else { return Err(FieldRefusal::Rejects(&value).message(field)) };
self.select(if keys.is_empty() { SelectionChange::Clear } else { SelectionChange::Set(keys) }, &rows);
}
"listed" | "replace" => return Err(FieldRefusal::ReadOnly.message(field)),
_ => return Err(FieldRefusal::Unknown.message(field)),
}
Ok(())
}
}
impl FileChooser {
/// The names of the selected `rows`, for automation.
fn selected_names<'a>(&self, rows: &'a [Entry]) -> Vec<&'a str> {
rows.iter().filter(|entry| self.selection.contains(&entry.path)).map(|entry| entry.name.as_str()).collect()
}
}
+124
View File
@@ -0,0 +1,124 @@
//! What Enter or OK does in the chooser with the typed text and the shown entries.
use std::ffi::OsString;
use std::path::{Component, Path, PathBuf};
use craft_browse::places::{Entry, same_folder};
use craft_host::{PickKind, PickRequest};
/// What accepting the typed text does.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) enum Accept {
/// Open these files (or, for a folder pick, answer this folder).
Open(Vec<PathBuf>),
/// Save to this path; nothing is listed there, so no question is asked.
Save(PathBuf),
/// Save to this path, a file the shown listing has: ask Replace first. The rule that tells a listed file from a
/// new name lives here, so the chooser does not look again.
Replace(PathBuf),
/// Enter this folder.
Enter(PathBuf),
/// List `folder`, then accept `name` against that listing: a typed path outside the shown folder.
Look {
/// The folder to list.
folder: PathBuf,
/// The name to accept there.
name: OsString,
},
/// Refuse: the name that was not found, or empty when nothing was typed.
Refuse(String),
}
/// Decides what Enter or OK does with `typed` in `folder`, given the shown `entries` and the `selected` ones. Reads
/// no folder: listing, the hidden rule and the sort come from craft-browse.
///
/// - A selected folder that is still listed is entered (a folder pick answers it); a selected folder never becomes
/// the typed name.
/// - Several selected files of an Open Many answer all of them.
/// - A selected file whose name is in the field keeps its exact path, leading spaces and all, listed or not.
/// - Otherwise the typed text, trimmed: `~` stands for `home`; a path outside `folder` is a [`Accept::Look`]; a
/// name in `folder` is entered when it is a listed folder, opened (or asked about on Save) when it is a listed
/// file, saved to when nothing is listed under it, and refused as not found on Open.
pub(crate) fn accept(request: &PickRequest, typed: &str, folder: &Path, entries: &[Entry], selected: &[Entry], home: Option<&Path>) -> Accept {
// ui-egui: crates/ui-egui/src/file_browser.rs:228 (`FileBrowser::accept`), :93 (`resolve`).
let listed = |path: &Path| entries.iter().find(|e| e.path == path);
if let [one] = selected
&& one.folder
&& listed(&one.path).is_some()
{
return if request.kind == PickKind::Folder { Accept::Open(vec![one.path.clone()]) } else { Accept::Enter(one.path.clone()) };
}
let files: Vec<&Entry> = selected.iter().filter(|e| !e.folder).collect();
if request.kind == PickKind::OpenMany && files.len() > 1 {
return Accept::Open(files.iter().map(|e| e.path.clone()).collect());
}
if let [file] = files.as_slice()
&& file.name == typed
{
return in_listing(request, file.path.clone(), &file.name, listed(&file.path));
}
let text = typed.trim();
if text.is_empty() {
return if request.kind == PickKind::Folder { Accept::Open(vec![folder.to_path_buf()]) } else { Accept::Refuse(String::new()) };
}
let Some(path) = typed_path(text, folder, home) else { return Accept::Refuse(text.to_owned()) };
let (Some(parent), Some(name)) = (path.parent(), path.file_name()) else { return Accept::Enter(path) };
if !same_folder(parent, folder) {
return Accept::Look { folder: parent.to_path_buf(), name: name.to_os_string() };
}
let path = folder.join(name);
in_listing(request, path.clone(), text, listed(&path))
}
/// The path typed `text` (trimmed by the caller) names from `folder`: `~` and `~/rest` under `home`, an absolute
/// path as it is, anything else inside `folder`; `.` and `..` resolved without reading the disk. `None` for a `~`
/// path without a home. The name field and the folder field both read typed paths through it.
pub(crate) fn typed_path(text: &str, folder: &Path, home: Option<&Path>) -> Option<PathBuf> {
// ui-egui: crates/ui-egui/src/file_browser.rs:93 (`resolve`).
let expanded = if text == "~" {
home.map(Path::to_path_buf)
} else if let Some(rest) = text.strip_prefix("~/").or_else(|| text.strip_prefix("~\\")) {
home.map(|home| home.join(rest))
} else {
Some(folder.join(text))
};
expanded.map(|path| lexical(&path))
}
/// Whether typed `text` (trimmed) starts from the home folder, so [`typed_path`] needs it.
pub(crate) fn needs_home(text: &str) -> bool {
text == "~" || text.starts_with("~/") || text.starts_with("~\\")
}
/// What a path in the shown folder does: `found` is its entry in the listing, `None` when nothing is listed under it.
fn in_listing(request: &PickRequest, path: PathBuf, name: &str, found: Option<&Entry>) -> Accept {
match (request.kind, found.map(|e| e.folder)) {
(PickKind::Folder, Some(true)) => Accept::Open(vec![path]),
(_, Some(true)) => Accept::Enter(path),
(PickKind::Open | PickKind::OpenMany, Some(false)) => Accept::Open(vec![path]),
(PickKind::Save, Some(false)) => Accept::Replace(path),
(PickKind::Save, None) => Accept::Save(path),
// A listed file is no folder: refused without a "not found" note, which would be untrue.
(PickKind::Folder, Some(false)) => Accept::Refuse(String::new()),
(PickKind::Open | PickKind::OpenMany | PickKind::Folder, _) => Accept::Refuse(name.to_owned()),
}
}
/// `path` with `.` dropped and `..` taking off the part before it, without reading the disk.
fn lexical(path: &Path) -> PathBuf {
let mut out = PathBuf::new();
for part in path.components() {
match part {
Component::CurDir => {}
// `..` at a root stays at the root; at the start of a relative path it is kept.
Component::ParentDir => {
if !out.pop() && !out.has_root() {
out.push(part);
}
}
other => out.push(other),
}
}
out
}
+261
View File
@@ -0,0 +1,261 @@
//! Trials of the fallback chooser: the accept rules of WordCraft's built-in browser, driven through the dialog on a
//! `DialogHost`, and its place in the file service.
#![allow(clippy::panic, clippy::expect_used, clippy::unwrap_used, reason = "trials assert by panicking")]
use std::cell::{Cell, RefCell};
use std::path::Path;
use std::rc::Rc;
use std::sync::Arc;
use std::time::Duration;
use craft_browse::places::{FakeDirectories, FolderCache, StandardFolder};
use craft_host::{Files as _, ManualJobs, PickRequest, Picked, Wake};
use craft_ui::dialog::{DialogHost, DialogResult};
use craft_ui::testing::{Fixture, trial};
use raw_window_handle::{DisplayHandle, HandleError, HasDisplayHandle, HasWindowHandle, WindowHandle};
use serde_json::Value;
use super::{ChooserWords, FileChooser};
use crate::Answer;
use crate::service::FileService;
use crate::ui::UnavailableWords;
/// The chooser's fields, as automation lists them; `Null` once it closed.
fn fields(host: &RefCell<DialogHost>) -> Value {
host.borrow().open_dialogs().into_iter().find_map(|open| open.fields.filter(|fields| fields.get("listed").is_some())).unwrap_or(Value::Null)
}
/// `/d` with two folders and three files, one of them named with a leading space, and a home folder with a letter.
fn tree() -> FakeDirectories {
FakeDirectories::new()
.standard_folder(StandardFolder::Home, "/home/u")
.file("/home/u/Letters/aunt.txt")
.folder("/d/drafts")
.folder("/d/Chapters")
.file("/d/drafts/old.docx")
.file("/d/ report.docx")
.file("/d/report.docx")
}
/// A chooser on a dialog host over [`tree`], its jobs run at the start of every frame. Each click's frames run two
/// passes, and only the first has the input.
struct Chooser {
host: Rc<RefCell<DialogHost>>,
fake: Arc<FakeDirectories>,
fixture: Fixture,
twice: Rc<Cell<bool>>,
}
impl Chooser {
fn open(request: PickRequest) -> Self {
let fake = Arc::new(tree());
let jobs = Arc::new(ManualJobs::new());
let cache = FolderCache::new(fake.clone(), jobs.clone(), Wake::none());
let host = Rc::new(RefCell::new(DialogHost::new()));
host.borrow_mut().open(FileChooser::new(request, None, cache));
let twice = Rc::new(Cell::new(false));
let (shown, rerun) = (host.clone(), twice.clone());
let mut fixture = Fixture::new(move |ui| {
jobs.run_all();
shown.borrow_mut().run(ui);
if rerun.get() && ui.ctx().current_pass_index() == 0 {
ui.ctx().request_discard("the chooser's pass runs twice");
}
});
fixture.idle(10);
let chooser = Chooser { host, fake, fixture, twice };
assert_eq!(chooser.field("listed"), Value::Bool(true), "the folder is listed");
chooser
}
fn field(&self, name: &str) -> Value {
fields(&self.host).get(name).cloned().unwrap_or(Value::Null)
}
fn click(&mut self, label: &str) {
let target = self.fixture.by_label(label).unwrap_or_else(|| panic!("`{label}` is shown"));
self.twice.set(true);
self.fixture.click(&target);
self.twice.set(false);
self.fixture.idle(6);
}
/// Types `text` into the (empty) name field.
fn type_name(&mut self, text: &str) {
self.click("File name");
self.fixture.type_text(text);
self.fixture.idle(2);
}
/// The window lost the focus and has it back: the listing is read again.
fn refocus(&mut self) {
self.fixture.frame(vec![egui::Event::WindowFocused(false)]);
self.fixture.frame(vec![egui::Event::WindowFocused(true)]);
self.fixture.idle(6);
}
fn answer(&self) -> Option<DialogResult<Answer>> {
self.host.borrow_mut().take::<FileChooser>()
}
}
/// The folder field's text for `child` in `dir`, joined with the platform's separator (a backslash on Windows).
fn shown(dir: &str, child: &str) -> String {
Path::new(dir).join(child).display().to_string()
}
fn picked(path: impl AsRef<Path>) -> Option<DialogResult<Answer>> {
Some(DialogResult::Ok(Answer::Paths(vec![path.as_ref().to_path_buf()])))
}
// WordCraft's `save_adds_the_extension_and_asks_before_replacing`, `selecting_a_file_preserves_leading_spaces`,
// `a_selected_folder_never_replaces_the_typed_save_name` and `a_removed_selected_file_keeps_its_exact_save_path`, with
// `~` and "not found". The extension is the service's policy now, so the chooser answers the name as typed.
#[trial]
fn the_chooser_lists_and_accepts_like_a_file_panel() {
// A typed folder is entered and its name used up; a new name is answered as typed.
let mut save = Chooser::open(PickRequest::save("document").directory("/d"));
save.type_name("drafts");
save.click("Save");
assert_eq!((save.field("folder"), save.field("name")), (Value::from(shown("/d", "drafts")), Value::from("")), "the typed folder opens");
save.type_name("chapter");
save.click("Save");
assert_eq!(save.answer(), picked("/d/drafts/chapter"), "a new name is saved to as typed");
// A listed file is replaced only after the question, asked once.
let mut replace = Chooser::open(PickRequest::save("document").directory("/d/drafts"));
replace.type_name("old.docx");
replace.click("Save");
assert_eq!(replace.answer(), None, "the chooser asks before replacing");
replace.click("Replace");
assert_eq!(replace.answer(), picked("/d/drafts/old.docx"));
// A selected file keeps its exact name, leading space and all, for Open and for Save's question.
let mut open = Chooser::open(PickRequest::open("document").directory("/d"));
open.click(" report.docx");
open.click("Open");
assert_eq!(open.answer(), picked("/d/ report.docx"), "Open answers the selected file, not its trimmed sibling");
let mut save = Chooser::open(PickRequest::save("document").file_name("Draft.docx").directory("/d"));
save.click(" report.docx");
assert_eq!(save.field("name"), Value::from(" report.docx"), "the selected file's name fills the field");
save.click("Save");
assert_eq!(save.answer(), None, "Save asks before replacing the selected file");
save.click("Replace");
assert_eq!(save.answer(), picked("/d/ report.docx"));
// A selected file removed meanwhile still names the exact path, and nothing is asked.
let mut removed = Chooser::open(PickRequest::save("document").file_name("Draft.docx").directory("/d"));
removed.click(" report.docx");
removed.fake.remove_file("/d/ report.docx");
removed.refocus();
removed.click("Save");
assert_eq!(removed.answer(), picked("/d/ report.docx"), "the removed selection keeps its path, not `report.docx`");
// A selected folder is entered and never becomes the save name; once it is gone, the typed name is saved to.
let mut folder = Chooser::open(PickRequest::save("document").file_name("chapter.docx").directory("/d"));
folder.click("Chapters");
assert_eq!(folder.field("name"), Value::from("chapter.docx"), "a folder leaves the name alone");
folder.click("Save");
assert_eq!((folder.field("folder"), folder.field("name")), (Value::from(shown("/d", "Chapters")), Value::from("chapter.docx")));
let mut gone = Chooser::open(PickRequest::save("document").file_name("chapter.docx").directory("/d"));
gone.click("Chapters");
gone.fake.remove_folder("/d/Chapters");
gone.refocus();
gone.click("Save");
assert_eq!(gone.answer(), picked("/d/chapter.docx"), "the removed folder is not saved over as `Chapters.docx`");
// `~` is the Home root; a typed path elsewhere is listed, then opened.
let mut home = Chooser::open(PickRequest::open("document").directory("/d"));
home.type_name("~/Letters/aunt.txt");
home.click("Open");
assert_eq!(home.answer(), picked("/home/u/Letters/aunt.txt"));
// A missing name on Open is refused and said.
let mut missing = Chooser::open(PickRequest::open("document").directory("/d"));
missing.type_name("missing.docx");
missing.click("Open");
assert_eq!(missing.answer(), None, "nothing is answered");
let not_found = ChooserWords::default().not_found.fill(&[("name", "missing.docx")]);
assert!(missing.fixture.by_label(&not_found).is_some(), "the chooser says what was not found");
}
/// No window: `pump_with(.., None::<&NoWindow>)`.
struct NoWindow;
impl HasWindowHandle for NoWindow {
fn window_handle(&self) -> Result<WindowHandle<'_>, HandleError> {
Err(HandleError::Unavailable)
}
}
impl HasDisplayHandle for NoWindow {
fn display_handle(&self) -> Result<DisplayHandle<'_>, HandleError> {
Err(HandleError::Unavailable)
}
}
const NONE: Option<&NoWindow> = None;
// WordCraft's `no_system_dialog_falls_back_to_the_built_in_browser`: the service opens the chooser over the real
// folders, and its answer settles like a panel's.
#[trial]
fn an_unavailable_or_forced_pick_opens_the_chooser_and_settles_its_answer() {
let dir = std::env::temp_dir().join(format!("craft-dialogs-chooser-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(dir.join("report.docx"), b"x").unwrap();
let (service, panels) = FileService::scripted(Wake::none(), [Answer::Unavailable("no portal".to_owned())]);
let panels = Rc::new(RefCell::new(panels));
let host = Rc::new(RefCell::new(DialogHost::new()));
let (pumped, shown) = (panels.clone(), host.clone());
let mut fixture = Fixture::new(move |ui| {
pumped.borrow_mut().pump_with(&mut shown.borrow_mut(), NONE);
shown.borrow_mut().run(ui);
});
// The service lists the real folder on its own threads: wait until the chooser is listed.
let listed = |fixture: &mut Fixture| {
for _ in 0..400 {
fixture.idle(1);
if fields(&host).get("listed") == Some(&Value::Bool(true)) {
return;
}
std::thread::sleep(Duration::from_millis(5));
}
panic!("the chooser listed the folder");
};
let click = |fixture: &mut Fixture, label: &str| {
let target = fixture.by_label(label).unwrap_or_else(|| panic!("`{label}` is shown"));
fixture.click(&target);
fixture.idle(6);
};
// The panel answers Unavailable: the chooser opens with the cause, and a new name gets the suggested extension.
let id = service.pick(PickRequest::save("document").directory(&dir).suggested_extension("docx"));
listed(&mut fixture);
assert!(host.borrow().is_open::<FileChooser>(), "the chooser stands in for the panel");
assert!(fixture.by_label(&UnavailableWords::default().sentence("no portal")).is_some(), "it says why");
click(&mut fixture, "File name");
fixture.type_text("novel");
click(&mut fixture, "Save");
assert_eq!(service.take_answer(id), Some(Picked::Paths(vec![dir.join("novel.docx")])), "the policy adds the extension");
// A forced chooser: `report` is no listed file, so the chooser asks nothing; the policy's `report.docx` is,
// so the service asks once.
let id = service.pick(PickRequest::save("document").directory(&dir).suggested_extension("docx").fallback(true));
listed(&mut fixture);
click(&mut fixture, "File name");
fixture.type_text("report");
click(&mut fixture, "Save");
assert_eq!(service.take_answer(id), None, "the Replace question waits");
click(&mut fixture, "Replace");
assert_eq!(service.take_answer(id), Some(Picked::Paths(vec![dir.join("report.docx")])));
// Cancel settles as Cancelled.
let id = service.pick(PickRequest::open("document").directory(&dir).fallback(true));
listed(&mut fixture);
click(&mut fixture, "Cancel");
assert_eq!(service.take_answer(id), Some(Picked::Cancelled));
assert!(!host.borrow().is_open::<FileChooser>(), "the chooser closed");
let _ = std::fs::remove_dir_all(&dir);
}
+2
View File
@@ -1,9 +1,11 @@
//! The file service's UI part: [`PathField`], and the words of the service's native boxes.
mod chooser;
mod path_field;
#[cfg(feature = "screen-testing")]
mod stories;
pub use chooser::{ChooserWords, FileChooser};
pub use path_field::{PathField, PathFieldOutput, PathFieldWords};
craft_ui::words! {
+69 -3
View File
@@ -1,8 +1,12 @@
//! Stories of the path field.
//! Stories of the path field and the fallback file chooser.
use super::PathField;
use craft_host::PickRequest;
use std::sync::Arc;
use super::{FileChooser, PathField};
use craft_browse::places::{FakeDirectories, FolderCache, StandardFolder};
use craft_host::{ManualJobs, PickRequest, Wake};
use craft_ui::contract::Bind;
use craft_ui::dialog::stories::hosted_with;
use craft_ui::testing::{Drive, StoryData, StoryOutput, story};
use egui::Ui;
@@ -23,3 +27,65 @@ fn path_field_missing_file(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
.show(ui)
.into()
}
/// The folders the chooser stories browse: a home with documents, pictures, a hidden folder and an empty folder.
fn story_tree() -> FakeDirectories {
let mut fake = FakeDirectories::new().standard_folder(StandardFolder::Home, "/home/u").folder("/home/u/Empty").folder("/home/u/.cache");
for file in [
"/home/u/Documents/Chapter 1.docx",
"/home/u/Documents/Chapter 2.docx",
"/home/u/Documents/Chapter 10.docx",
"/home/u/Documents/notes.txt",
"/home/u/Documents/.draft.docx",
"/home/u/Documents/Research/sources.txt",
"/home/u/Documents/cover.png",
"/home/u/Pictures/sunrise.jpg",
] {
fake = fake.file(file);
}
fake
}
/// A chooser for `request` over [`story_tree`] on the story's dialog host, its listing jobs run before each pass;
/// `cause` is the unavailable panel's message, when the story shows one.
fn chooser_story(ui: &mut Ui, data: &mut StoryData, name: &'static str, request: PickRequest, cause: Option<&'static str>) -> StoryOutput {
let jobs = data.note("jobs", Arc::new(ManualJobs::new())).clone();
let (running, waiting) = (jobs.clone(), jobs.clone());
let ctx = ui.ctx().clone();
let open = move || {
let wake = Wake::new(move || ctx.request_repaint());
FileChooser::new(request, cause.map(str::to_owned), FolderCache::new(Arc::new(story_tree()), jobs, wake))
};
let facts = hosted_with(ui, data, name, open, move |_| {
running.run_all();
});
// A listing asked for in this pass runs before the next one.
if waiting.waiting() > 0 {
ui.ctx().request_repaint();
}
facts
}
#[story(FileChooser, covers = [Default], drive = Drive::Never)]
fn file_chooser_open(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let request =
PickRequest::open("document").filter("Documents", &["docx", "txt"]).filter("Pictures", &["png", "jpg"]).directory("/home/u/Documents");
chooser_story(ui, data, "open", request, None)
}
#[story(FileChooser, covers = [], drive = Drive::Never)]
fn file_chooser_save(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let request = PickRequest::save("document").filter("Word document", &["docx"]).file_name("Chapter 3.docx").directory("/home/u/Documents");
chooser_story(ui, data, "save", request, None)
}
#[story(FileChooser, covers = [], drive = Drive::Never)]
fn file_chooser_empty_folder(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
chooser_story(ui, data, "empty", PickRequest::open("document").directory("/home/u/Empty"), None)
}
#[story(FileChooser, covers = [], drive = Drive::Never)]
fn file_chooser_unavailable(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let request = PickRequest::save("document").file_name("Chapter 3.docx");
chooser_story(ui, data, "unavailable", request, Some("no file chooser portal and no zenity"))
}
+12
View File
@@ -59,6 +59,18 @@ impl Files for StubFiles {
Err(FileError::Unsupported)
}
fn save(&self, request: PickRequest, _bytes: Vec<u8>) -> PickId {
self.pick(request)
}
fn can_pick(&self) -> bool {
true
}
fn browser_saves(&self) -> bool {
false
}
fn last_folder(&self, _purpose: &str) -> Option<PathBuf> {
None
}
+2
View File
@@ -14,6 +14,7 @@ pub mod gradient_overlay;
pub mod map;
mod palette;
mod swatch;
mod tile;
pub use fill::{GradientFill, GradientStyle};
pub use fill_editor::{GradientFillEditor, GradientFillEditorOutput, GradientFillWords};
@@ -22,3 +23,4 @@ pub use gradient_overlay::{GradientLineWords, GradientOverlay, GradientOverlayOu
pub use map::{GradientMap, GradientMapEditor, GradientMapOutput};
pub use palette::{GradientGroup, GradientItem, GradientPalette, GradientPaletteOutput, GradientRef};
pub use swatch::{GradientSwatch, GradientSwatchOutput};
pub use tile::{FocusOutline, GradientTile};
+38 -9
View File
@@ -12,6 +12,8 @@ mod stories;
use craft_color_ui::ui::gradient::{GradientRamp, GradientStops, Sampler, StopRows, default_sampler};
use super::GradientTile;
/// The presets take their content height up to this many small control heights, then scroll.
const MAX_ROWS: f32 = 6.0;
@@ -40,12 +42,21 @@ pub struct GradientItem {
pub name: String,
/// The preset's stops.
pub stops: GradientStops,
/// How the preset's cell is drawn: the ramp chip, or a square tile.
pub tile: GradientTile,
}
impl GradientItem {
/// A preset called `name` with `stops`.
pub fn new(name: impl Into<String>, stops: GradientStops) -> Self {
Self { name: name.into(), stops }
Self { name: name.into(), stops, tile: GradientTile::default() }
}
/// Draws the preset's cell as `tile`.
#[must_use]
pub fn tile(mut self, tile: GradientTile) -> Self {
self.tile = tile;
self
}
}
@@ -200,20 +211,30 @@ impl<'a> GradientPalette<'a> {
let default = default_sampler(self.rows);
let sampler: &Sampler = self.sampler.unwrap_or(&default);
let (groups, recent) = (self.groups, self.recent);
let (wide, high) = GradientRamp::CHIP_ASPECT;
// The browser has one cell shape for the grid and the list, so any tile makes every cell square.
let square = groups.iter().flat_map(|g| &g.items).any(|item| item.tile != GradientTile::Ramp);
let thumb =
move |cx: &craft_ui::primitives::ContentPainterCx, rect: egui::Rect, info: craft_ui::patterns::presets::ThumbInfo<'_, GradientRef>| {
if let Some(stops) = stops_of(groups, recent, *info.key) {
let (radius, edge) = GradientRamp::chip_look(&cx.style_cx());
GradientRamp::paint_chip(cx, rect, radius, &GradientRamp::colors(stops, sampler), edge);
let tile = item_of(groups, *info.key).map_or(GradientTile::Ramp, |item| item.tile);
if tile != GradientTile::Ramp {
tile.paint(cx, rect, radius, stops, sampler, edge);
return;
}
let chip = if square {
egui::Rect::from_center_size(rect.center(), egui::vec2(rect.width(), rect.width() * f32::from(high) / f32::from(wide)))
} else {
rect
};
GradientRamp::paint_chip(cx, chip, radius, &GradientRamp::colors(stops, sampler), edge);
}
};
let (wide, high) = GradientRamp::CHIP_ASPECT;
let most = Env::of(ui).tokens.size.control.sm * MAX_ROWS;
let mut browser = PresetBrowser::new(self.label, self.state, &rows)
.cell_shape(CellShape::ratio(wide, high))
.tiles(PresetTiles::Chips)
.room_height(most)
.thumb(thumb);
let shape = if square { CellShape::Square } else { CellShape::ratio(wide, high) };
let mut browser =
PresetBrowser::new(self.label, self.state, &rows).cell_shape(shape).tiles(PresetTiles::Chips).room_height(most).thumb(thumb);
if let Some(selected) = self.selected {
browser = browser.selected(selected);
}
@@ -234,6 +255,14 @@ impl<'a> GradientPalette<'a> {
pub(super) fn stops_of<'a>(groups: &'a [GradientGroup], recent: &'a [GradientStops], key: GradientRef) -> Option<&'a GradientStops> {
match key {
GradientRef::Recent(i) => recent.get(i),
GradientRef::Item { group, item } => groups.get(group)?.items.get(item).map(|preset| &preset.stops),
GradientRef::Item { .. } => item_of(groups, key).map(|preset| &preset.stops),
}
}
/// The group item `key` names; none for a recent gradient (which has stops only) or a group header.
pub(super) fn item_of(groups: &[GradientGroup], key: GradientRef) -> Option<&GradientItem> {
match key {
GradientRef::Recent(_) => None,
GradientRef::Item { group, item } => groups.get(group)?.items.get(item),
}
}
@@ -7,6 +7,7 @@ use craft_ui::testing::{StoryData, StoryOutput, story};
use egui::Ui;
use super::{GradientGroup, GradientItem, GradientPalette, GradientRef};
use crate::ui::gradient::{FocusOutline, GradientStyle, GradientTile};
use craft_color_ui::ui::gradient::{ColorStop, GradientStops};
fn pair(a: [f32; 3], b: [f32; 3]) -> GradientStops {
@@ -48,6 +49,24 @@ fn gradient_palette(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
palette(ui, data, PresetView::Grid)
}
/// Presets drawn as square tiles: a style at an angle, a focus tile, and a plain ramp among them.
#[story(GradientPalette<'static>, covers = [], title = "Tiles")]
fn gradient_palette_tiles(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let stops = pair([0.95, 0.6, 0.1], [0.5, 0.1, 0.5]);
let focus = egui::Rect::from_min_max(egui::pos2(0.25, 0.25), egui::pos2(0.75, 0.75));
let mut items: Vec<GradientItem> = GradientStyle::ALL
.into_iter()
.map(|style| GradientItem::new(format!("{style:?}"), stops.clone()).tile(GradientTile::Style { style, angle: -45.0 }))
.collect();
items.push(GradientItem::new("Focus, circle", stops.clone()).tile(GradientTile::Focus { outline: FocusOutline::Circle, focus }));
items.push(GradientItem::new("Focus, rectangle", stops.clone()).tile(GradientTile::Focus { outline: FocusOutline::Rect, focus }));
items.push(GradientItem::new("Ramp", stops));
let groups = [GradientGroup::new("Tiles", items)];
let state = data.value("state", PresetState::<GradientRef>::new());
let shown = GradientPalette::new("Gradient tiles", &groups, Bind::bound(&mut *state)).show(ui);
StoryOutput::from(shown)
}
#[story(GradientPalette<'static>, covers = [Default])]
fn gradient_palette_list(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
palette(ui, data, PresetView::List)
+22 -1
View File
@@ -10,6 +10,8 @@ use egui::{CornerRadius, Response, Vec2};
use craft_color_ui::ui::gradient::{GradientRamp, GradientStops, Sampler, StopRows, default_sampler};
use super::GradientTile;
#[cfg(feature = "screen-testing")]
mod stories;
@@ -72,13 +74,25 @@ pub struct GradientSwatch<'a> {
/// Tells AccessKit that a click opens a dialog.
#[prop(flag)]
has_popup: bool,
/// How the gradient is drawn: the ramp chip, or a square two-dimensional tile.
#[prop]
tile: GradientTile,
clicked: bool,
}
impl<'a> GradientSwatch<'a> {
/// A swatch of `stops`; `label` names it for a screen reader.
pub fn new(label: impl Into<craft_ui::runtime::env::Label>, stops: &'a GradientStops) -> Self {
GradientSwatch { common: Common::new(), stops, rows: StopRows::Split, sampler: None, has_popup: false, clicked: false }.label(label)
GradientSwatch {
common: Common::new(),
stops,
rows: StopRows::Split,
sampler: None,
has_popup: false,
tile: GradientTile::default(),
clicked: false,
}
.label(label)
}
}
@@ -104,6 +118,9 @@ impl Component for GradientSwatch<'_> {
fn measure(&mut self, cx: &MeasureCx<'_, Self>) -> Vec2 {
let height = cx.style.side;
if self.tile != GradientTile::Ramp {
return Vec2::splat(height);
}
let (wide, high) = GradientRamp::CHIP_ASPECT;
let chip = height * f32::from(wide) / f32::from(high);
let width = if cx.resolved.sizing() == Some(Sizing::FillWidth) {
@@ -137,6 +154,10 @@ impl Component for GradientSwatch<'_> {
let style = cx.style;
let default = default_sampler(self.rows);
let sampler: &Sampler = self.sampler.unwrap_or(&default);
if self.tile != GradientTile::Ramp {
self.tile.paint(&ui.content_painter(cx), cx.rect, style.radius, self.stops, sampler, style.edge);
return;
}
let colors = GradientRamp::colors(self.stops, sampler);
GradientRamp::paint_chip(&ui.content_painter(cx), cx.rect, style.radius, &colors, style.edge);
}
@@ -1,6 +1,7 @@
//! Stories of `GradientSwatch`.
use super::GradientSwatch;
use crate::ui::gradient::{FocusOutline, GradientStyle, GradientTile};
use craft_color_ui::ui::gradient::{ColorStop, GradientStops, OpacityStop, StopRows};
use craft_theme::Srgba;
use craft_ui::contract::{Props as _, Show as _, ShowContainer as _, Sizing};
@@ -59,6 +60,26 @@ fn gradient_swatch(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
StoryOutput { clicked, ..StoryOutput::default() }.readout(craft_i18n::fmt(words.clicked.as_str(), &[("count", clicks.to_string().as_str())]))
}
/// One square tile per gradient style at an angle, and a focus tile in each outline, each with its name.
#[story(GradientSwatch, covers = [], drive = Drive::Never, title = "Tiles")]
fn gradient_swatch_tiles(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
let stops = GradientStops::new(vec![stop(0.0, [0.96, 0.65, 0.14]), stop(1.0, [0.24, 0.39, 0.87])]);
let focus = egui::Rect::from_min_max(egui::pos2(0.25, 0.25), egui::pos2(0.5, 0.5));
let mut tiles: Vec<(String, GradientTile)> =
GradientStyle::ALL.into_iter().map(|style| (format!("{style:?}"), GradientTile::Style { style, angle: -45.0 })).collect();
tiles.push(("Focus, circle".to_owned(), GradientTile::Focus { outline: FocusOutline::Circle, focus }));
tiles.push(("Focus, rectangle".to_owned(), GradientTile::Focus { outline: FocusOutline::Rect, focus }));
Stack::new().show(ui, |ui, _| {
for (name, tile) in &tiles {
Row::new().show(ui, |ui, _| {
GradientSwatch::new(name.clone(), &stops).tile(*tile).show(ui);
Text::new(name.clone()).shade(Shade::Muted).show(ui);
});
}
});
StoryOutput::default()
}
/// A gradient fading in, enabled and disabled, each with its name.
#[story(GradientSwatch, covers = [], drive = Drive::Never, title = "Disabled")]
fn gradient_swatch_disabled(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
+144
View File
@@ -0,0 +1,144 @@
//! [`GradientTile`]: a square two-dimensional gradient in a swatch or the palette grid.
use std::cell::Cell;
use std::f32::consts::TAU;
use craft_color_ui::ui::gradient::{GradientStops, Sampler};
use craft_color_ui::ui::smooth_mesh;
use craft_ui::primitives::{Checker, ContentPainterCx, PaintShape, StrokeWidth};
use craft_ui::style::StyleColor;
use egui::{CornerRadius, Mesh, Rect, Vec2, vec2};
use super::GradientStyle;
/// Vertices along a side of a tile's mesh.
const TILE_STEPS: usize = 17;
/// How a gradient swatch or palette cell draws its gradient.
///
/// A tile other than [`Ramp`](GradientTile::Ramp) is one `craft_color_ui::ui::smooth_mesh` sampled through
/// [`t_at`](GradientTile::t_at). `p` below is a point in the tile's unit square (0 to 1, y down) and `c` its centre.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
#[non_exhaustive]
pub enum GradientTile {
/// The ramp chip: the gradient along its length.
#[default]
Ramp,
/// A square tile of `style` at `angle`.
#[non_exhaustive]
Style {
/// How the gradient runs.
style: GradientStyle,
/// The angle of the gradient line, in degrees, in the convention of `GradientFill::angle`: 0 points right and
/// 90 points up.
angle: f32,
},
/// A square tile whose gradient runs out from `focus`.
#[non_exhaustive]
Focus {
/// The shape of the outline the gradient follows.
outline: FocusOutline,
/// The focus rectangle, in the tile's unit square.
focus: egui::Rect,
},
}
impl GradientTile {
/// A square tile of `style` at `angle`.
pub const fn style(style: GradientStyle, angle: f32) -> Self {
GradientTile::Style { style, angle }
}
/// A square tile whose gradient runs out from `focus`, in the shape of `outline`.
pub const fn focus(outline: FocusOutline, focus: egui::Rect) -> Self {
GradientTile::Focus { outline, focus }
}
}
/// The outline a [`GradientTile::Focus`] gradient follows.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum FocusOutline {
/// A circle.
Circle,
/// A rectangle.
Rect,
}
impl GradientTile {
/// The gradient position, 0 to 1, at `p` in the tile's unit square.
///
/// - `Linear`: the line runs through the centre from edge to edge, 0 on the start side and 1 on the far side.
/// - `Radial`, `Reflected`, `Diamond`: 0 at the centre, 1 at the edge along the angle's direction, in circles,
/// mirrored about the centre, or in diamonds.
/// - `Angle`: the counter-clockwise sweep from the angle's direction, over a full turn.
/// - `Focus`: 0 at the focus rectangle's centre, 1 at the farthest corner, in circles or in rectangles.
///
/// `Ramp` has no second dimension: its position is `p.x`.
pub fn t_at(&self, p: Vec2) -> f32 {
// design: allow[literal-size/vec2](the centre of the tile unit square, a gradient coordinate and not a size)
let c = vec2(0.5, 0.5);
let t = match *self {
GradientTile::Ramp => p.x,
GradientTile::Style { style, angle } => {
let rad = angle.to_radians();
let d = vec2(rad.cos(), -rad.sin());
let v = p - c;
let h = (d.x.abs() + d.y.abs()) / 2.0;
let along = v.dot(d);
match style {
GradientStyle::Linear => 0.5 + along / (2.0 * h),
GradientStyle::Radial => v.length() / h,
GradientStyle::Reflected => along.abs() / h,
GradientStyle::Diamond => (along.abs() + v.dot(vec2(-d.y, d.x)).abs()) / h,
GradientStyle::Angle => {
let at = (-v.y).atan2(v.x);
(at - rad).rem_euclid(TAU) / TAU
}
}
}
GradientTile::Focus { outline, focus } => {
let f = focus.center().to_vec2();
let corners = [vec2(0.0, 0.0), vec2(1.0, 0.0), vec2(0.0, 1.0), vec2(1.0, 1.0)];
let distance = |v: Vec2| match outline {
FocusOutline::Circle => v.length(),
FocusOutline::Rect => v.x.abs().max(v.y.abs()),
};
let far = corners.iter().map(|&corner| distance(corner - f)).fold(0.0, f32::max);
if far > 0.0 { distance(p - f) / far } else { 0.0 }
}
};
if t.is_finite() { t.clamp(0.0, 1.0) } else { 0.0 }
}
/// Paints the tile over `rect`: the checkerboard where a colour is translucent, the gradient of `stops` through
/// `sampler`, then a thin `edge` ring. A `Ramp` tile paints nothing here; the ramp chip is the caller's.
pub(crate) fn paint(
&self,
cx: &ContentPainterCx<'_>,
rect: Rect,
radius: CornerRadius,
stops: &GradientStops,
sampler: &Sampler,
edge: StyleColor,
) {
if matches!(self, GradientTile::Ramp) || rect.width() <= 0.0 || rect.height() <= 0.0 {
return;
}
let translucent = Cell::new(false);
let at = |fx: f32, fy: f32| {
let color = sampler(stops, self.t_at(vec2(fx, fy)));
if color.a < 1.0 {
translucent.set(true);
}
color
};
let mut mesh = Mesh::default();
smooth_mesh(&mut mesh, rect, TILE_STEPS, &at);
if translucent.get() {
cx.checker_with(&Checker::new(), rect, radius);
}
cx.mesh_in(rect, radius, mesh);
cx.with_draw(|draw| draw.stroke(&PaintShape::Rect(rect, radius), StrokeWidth::Thin, edge));
}
}
+3 -3
View File
@@ -77,11 +77,11 @@ pub use crop::{
CropPresetList, CropPresetListOutput, CropSizeTarget, PerspectiveCropBar, PerspectiveCropBarOutput, PerspectiveCropPass, PerspectiveInput,
};
pub use crop::{PerspectiveCropQuad, PerspectiveQuad};
pub use gradient::{GradientFill, GradientFillEditor, GradientFillEditorOutput, GradientFillWords, GradientStyle};
pub use gradient::{
GradientGroup, GradientItem, GradientLine, GradientMap, GradientMapEditor, GradientMapOutput, GradientOverlay, GradientPalette, GradientRef,
GradientSwatch, LineGradient, LinePart,
FocusOutline, GradientGroup, GradientItem, GradientLine, GradientMap, GradientMapEditor, GradientMapOutput, GradientOverlay, GradientPalette,
GradientRef, GradientSwatch, GradientTile, LineGradient, LinePart,
};
pub use gradient::{GradientFill, GradientFillEditor, GradientFillEditorOutput, GradientFillWords, GradientStyle};
pub use measure::{
MIN_LINE, RulerBar, RulerBarOutput, RulerLine, RulerOverlay, RulerPass, RulerTool, RulerWords, box_distances, ruler_line_form, show_ruler,
};
+4 -1
View File
@@ -13,5 +13,8 @@ pub use session::{
};
pub use session_bar::{BarSlot, TransformBar, TransformBarOutput, TransformBarWords};
pub use session_overlay::{TransformOverlay, TransformOverlayOutput, TransformTool};
pub use transform_box::{ApplyBy, BOX, LineLook, RotateZone, TransformBox, TransformBoxOutput, TransformBoxStyle, TransformBoxWords, TransformReach};
pub use transform_box::{
ApplyBy, BOX, LineEnd, LineEndDrag, LineEnds, LineLook, RotateZone, TransformBox, TransformBoxOutput, TransformBoxStyle, TransformBoxWords,
TransformReach,
};
pub use transform_fields::{SizeUnit, TransformField, TransformFieldWords, TransformFields, TransformFieldsOutput, TransformGroups, TransformRow};
+283 -40
View File
@@ -6,11 +6,11 @@
mod stories;
use craft_behavior::geometry::quad::{self, BoxAllow, BoxDrag, BoxPart, BoxRules, BoxState, ScaleRule, TransformMode};
use craft_behavior::geometry::{SNAP_PX, SnapKind, SnapKinds, SnapLine};
use craft_behavior::geometry::{SNAP_PX, SnapKind, SnapKinds, SnapLine, SnapSuspend};
use craft_behavior::kurbo::{Point, Rect as DocRect, Vec2 as DocVec};
use craft_behavior::{
Axis, CancelReason, CanvasView, Cursor, CursorIcon, CursorPriority, HitLevel, HitPriority, HitShape, Intent, Metrics, NavShape, PaintedCursor,
PartKey, PartRef, PointerButton, PressPhase, Roving, Sense, resize_cursor,
Axis, CancelReason, CanvasView, Cursor, CursorIcon, CursorPriority, GesturePhase, HitLevel, HitPriority, HitShape, Intent, Metrics, NavShape,
PaintedCursor, PartKey, PartRef, PointerButton, PressPhase, Roving, Sense, resize_cursor,
};
use craft_keymap::Mods;
use craft_ui::canvas::{CanvasSpace, GestureSnap, Snap, canvas_snap, canvas_space, readout};
@@ -72,6 +72,18 @@ const OVERFLOW_IN_HANDLES: f32 = 1.5;
/// The keyboard path of a rotation by the outside parts: the options bar's angle field, which the host shows beside the box.
const ROTATE_BY_KEY: &str = "the angle field in the options bar";
/// The rotate handle of [`RotateZone::Handle`]: the zone's one rotating part, a knob on a stem off the middle of side 0.
const ROTATE_HANDLE: PartKey = PartKey::new("rotateHandle");
/// The length of the rotate handle's stem, from the side to the knob's centre, in standard handle sides.
const STEM_IN_HANDLES: f32 = 3.0;
/// The ends of a line in [`LineEnds::Free`]: `LINE_END.at(0)` its start, `LINE_END.at(1)` its end.
const LINE_END: PartKey = PartKey::new("lineEnd");
/// The keyboard path of a free line end: the host commits the ends, through its own fields for them.
const LINE_END_BY_KEY: &str = "the line's end fields in the options bar";
/// The part the keyboard picked, as the box remembers it between passes.
#[derive(Clone, Copy, Default)]
struct KeyPicked(Option<BoxPart>);
@@ -110,6 +122,9 @@ pub enum RotateZone {
/// The reach outside the sides, in screen points.
points: f32,
},
/// Only the rotate handle on its stem (Office's rotate handle); Alt is not the pivot key when snapping suspends on
/// Alt.
Handle,
}
impl RotateZone {
@@ -124,6 +139,8 @@ impl RotateZone {
match self {
RotateZone::Border { points } => border_distance(quad, pointer) <= points,
RotateZone::Outside | RotateZone::Band => true,
// The handle is the zone's only outside part, so a press that reaches the outside is on it.
RotateZone::Handle => true,
}
}
}
@@ -145,6 +162,41 @@ pub enum TransformReach {
},
}
/// What a line's two end controls are ([`LineLook::ends`]).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum LineEnds {
/// Each end stands for a handle of the box aligned with the segment.
#[default]
Box,
/// Each end moves as a free point, reported for the host to commit.
Free,
}
/// Which end of a line is dragged ([`LineEndDrag::end`]).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum LineEnd {
/// The line's start.
From,
/// The line's end.
To,
}
/// A drag of one end of a line in [`LineEnds::Free`], for the host to commit.
#[derive(Clone, Copy, Debug, PartialEq)]
#[non_exhaustive]
pub struct LineEndDrag {
/// Where the drag stands in this pass.
pub phase: GesturePhase,
/// The end dragged.
pub end: LineEnd,
/// Where the end is, in document units.
pub at: Point,
/// The modifier keys held.
pub mods: Mods,
}
/// The box drawn as a live line's controls ([`TransformBox::line`]), in document units: a square at each end of the
/// segment and the round widget at its middle, with no frame. `outline`, for a line with an arrowhead, is the box
/// aligned with the segment that holds the arrowheads, drawn with a square at the middle of each side.
@@ -157,12 +209,24 @@ pub struct LineLook {
pub to: Point,
/// The box aligned with the segment, corner by corner around it.
pub outline: Option<[Point; 4]>,
/// What the two ends are: box handles, or free points the host commits.
pub ends: LineEnds,
}
impl LineEnd {
/// The repeat of [`LINE_END`] the end is declared under.
const fn index(self) -> u64 {
match self {
LineEnd::From => 0,
LineEnd::To => 1,
}
}
}
impl LineLook {
/// The controls of the line from `from` to `to`, with no outline.
/// The controls of the line from `from` to `to`, with no outline, each end a box handle.
pub fn new(from: Point, to: Point) -> Self {
LineLook { from, to, outline: None }
LineLook { from, to, outline: None, ends: LineEnds::Box }
}
/// These controls with the segment-aligned box `outline`.
@@ -172,10 +236,24 @@ impl LineLook {
self
}
/// These controls with `ends`: whether the ends are box handles or free points reported for the host to commit.
#[must_use]
pub fn ends(mut self, ends: LineEnds) -> Self {
self.ends = ends;
self
}
/// Each end that stands for a box handle, with the handle: the corner the end points to, away from the other end
/// (on a level or upright line, the side). A line of no length has none.
fn ends(&self) -> impl Iterator<Item = (BoxPart, Point)> {
[(self.from, self.to), (self.to, self.from)].into_iter().filter_map(|(end, other)| Some((end_part(end, other)?, end)))
/// (on a level or upright line, the side). A line of no length, or one with free ends, has none.
fn end_parts(&self) -> impl Iterator<Item = (BoxPart, Point)> {
let boxed = self.ends == LineEnds::Box;
[(self.from, self.to), (self.to, self.from)].into_iter().filter(move |_| boxed).filter_map(|(end, other)| Some((end_part(end, other)?, end)))
}
/// Each free end with its point, in [`LineEnds::Free`]; none when the ends are box handles.
fn free_ends(&self) -> impl Iterator<Item = (LineEnd, Point)> {
let free = self.ends == LineEnds::Free;
[(LineEnd::From, self.from), (LineEnd::To, self.to)].into_iter().filter(move |_| free)
}
}
@@ -240,6 +318,10 @@ pub struct TransformBoxStyle {
band_outer: f32,
pivot_radius: f32,
pivot_arm: f32,
/// The rotate handle's stem, from the side to the knob's centre.
rotate_stem: f32,
/// The radius of the rotate handle's knob.
rotate_knob: f32,
/// The round widget at a live line's middle: the corner widgets' look.
widget: CornerStyle,
}
@@ -269,6 +351,7 @@ struct Report {
picked: Option<BoxPart>,
held: Option<BoxPart>,
snapped: Vec<SnapLine>,
line_end: Option<LineEndDrag>,
}
/// The press the box is dragging a part with, kept from the press to its release.
@@ -297,6 +380,21 @@ impl Default for Grip {
}
}
/// The press dragging a free line end, kept from the press to its release.
#[derive(Clone, Copy, Debug)]
struct EndGrip {
end: LineEnd,
/// From the press to the end, in document units: the end keeps it, so a press off the end's point does not jump.
offset: DocVec,
began: bool,
}
impl Default for EndGrip {
fn default() -> Self {
EndGrip { end: LineEnd::From, offset: DocVec::ZERO, began: false }
}
}
/// Whether a press on `part` moves the box from the first pointer move inside the slop, so the box does not jump when
/// the drag is recognised: every part but the outside, where a click applies the box. The parts' declared sense
/// ([`slop_sense`]) and the grip both read it.
@@ -336,7 +434,10 @@ fn slop_sense(part: BoxPart) -> Sense {
/// [`session_arrows`](Self::session_arrows) off the arrows stay the tool's (the Move tool nudges the layer).
/// - A [centre mark](Self::centre_mark) draws the reference point's glyph at the middle of the box and takes no press.
/// A [live line's look](Self::line) declares only the line's two ends, each standing for the box handle it points
/// to, and draws the line's controls in place of the frame.
/// to, and draws the line's controls in place of the frame. With [free ends](LineEnds::Free) each end is a point of
/// its own: its drag reports [`TransformBoxOutput::line_end`] for the host to commit and leaves the box alone.
/// - In [`RotateZone::Handle`] only the rotate handle, a knob on a stem off the middle of the top side, rotates, and
/// the rest of the outside is the tool's. While Alt is the canvas's snap suspend key, the drag never reads Alt.
/// - Nothing mirrors in a right-to-left interface: the box is the document's.
#[derive(craft_ui::contract::Component, craft_ui::contract::Props)]
#[component(canvas_control)]
@@ -454,7 +555,7 @@ impl<'a> TransformBox<'a> {
return Vec::new();
}
if let Some(line) = &self.line {
return line.ends().map(|(part, _)| part).filter(|&part| self.rules.allows(part)).collect();
return line.end_parts().map(|(part, _)| part).filter(|&part| self.rules.allows(part)).collect();
}
let corners = (0..4u8).map(BoxPart::Corner);
let edges = (0..4u8).map(BoxPart::Edge);
@@ -466,7 +567,7 @@ impl<'a> TransformBox<'a> {
/// Where `part` is drawn and taken, in document units: a live line's end, else [`handle_point`].
fn part_point(&self, state: &BoxState, part: BoxPart) -> Option<Point> {
match &self.line {
Some(line) => line.ends().find(|(end_part, _)| *end_part == part).map(|(_, end)| end),
Some(line) => line.end_parts().find(|(end_part, _)| *end_part == part).map(|(_, end)| end),
None => handle_point(state, part),
}
}
@@ -491,15 +592,17 @@ impl<'a> TransformBox<'a> {
/// - The reference point snaps to the nine points of the box at the press (corners, edge midpoints, centre) and
/// to nothing else, with or without the canvas's snap, the Control key held or not.
/// - In [`TransformMode::Distort`] only the corners snap, and to guides only. The outside (rotating) never snaps.
/// - The Control key suspends the snapping unless the drag reads it (off macOS Ctrl is ⌘): where it changes what
/// the drag does (a corner distorts, an edge skews) or on a corner that distorts.
/// - The canvas's suspend key (Control by default) suspends the snapping unless the drag reads it
/// ([`reads_suspend_key`](Self::reads_suspend_key)). The snap reads the keys as held; the drag acts on them as
/// [`drag_mods`] leaves them, so with Alt as the suspend key Alt only suspends.
fn proposal(&self, space: &CanvasSpace, snap: Option<&Snap>, grip: &Grip, pos: Pos2, mods: Mods) -> (BoxState, Vec<SnapLine>) {
let to = space.view.to_doc(pos);
let kind = self.rules.drag_kind(grip.part, mods);
let reads_control = mods.cmd && (kind != self.rules.drag_kind(grip.part, Mods { cmd: false, ..mods }) || kind == Some(BoxDrag::Distort));
let suspend = suspend_key(snap);
let acting = drag_mods(mods, suspend);
let kind = self.rules.drag_kind(grip.part, acting);
let distort_mode = self.rules.effective_mode() == TransformMode::Distort;
let kinds = if distort_mode { SnapKinds::only(SnapKind::Guide) } else { SnapKinds::ALL };
let gesture = GestureSnap::default().reads_control(reads_control).kinds(kinds);
let gesture = GestureSnap::default().reads_suspend_key(self.reads_suspend_key(grip.part, acting, suspend)).kinds(kinds);
let grabbed = handle_point(&grip.start, grip.part);
let (to, mut lines) = match (grip.part, snap, grabbed) {
(BoxPart::Pivot, _, Some(grabbed)) if !distort_mode => {
@@ -520,7 +623,7 @@ impl<'a> TransformBox<'a> {
}
_ => (to, Vec::new()),
};
let dragged = quad::drag(&grip.start, &grip.last, grip.part, grip.from, to, mods, &self.rules);
let dragged = quad::drag(&grip.start, &grip.last, grip.part, grip.from, to, acting, &self.rules);
// The canvas's pixel grid rounds an upright box and its corners to whole document units; keys are not rounded.
let dragged = if snap.is_some_and(Snap::rounds_to_pixels) { on_pixel_grid(dragged) } else { dragged };
if kind == Some(BoxDrag::Distort)
@@ -534,6 +637,20 @@ impl<'a> TransformBox<'a> {
(dragged, lines)
}
/// Whether a drag of `part` with `mods` (as the drag acts on them, [`drag_mods`]) reads the snap's `suspend` key
/// itself, so the key does not suspend the snapping. Control: where ⌘ (Ctrl off macOS) changes what the drag
/// does (a corner distorts, an edge skews) or on a corner that distorts. Alt: never, since the drag does not
/// see Alt while Alt is the suspend key.
fn reads_suspend_key(&self, part: BoxPart, mods: Mods, suspend: SnapSuspend) -> bool {
match suspend {
SnapSuspend::Alt => false,
_ => {
let kind = self.rules.drag_kind(part, mods);
mods.cmd && (kind != self.rules.drag_kind(part, Mods { cmd: false, ..mods }) || kind == Some(BoxDrag::Distort))
}
}
}
/// The pointer for `part` at `pointer`, `dragging` during its drag.
fn cursor(&self, look: &CursorLook<'_>, part: BoxPart, pointer: Pos2, mods: Mods, dragging: bool) -> Cursor {
let Some(kind) = self.rules.drag_kind(part, mods) else { return CursorIcon::Default.into() };
@@ -542,6 +659,10 @@ impl<'a> TransformBox<'a> {
let turn = || Cursor::from(PaintedCursor::turn(quad::bisector(screen, corner)));
let along = |from: usize| vec2_of(screen.quad[(from + 1) % 4] - screen.quad[from % 4]);
match (kind, part) {
// The rotate handle turns the cursor with the box: it points in across the side the handle stands on.
(BoxDrag::Rotate, BoxPart::Outside) if self.rotate_zone == RotateZone::Handle => {
Cursor::from(PaintedCursor::turn(-outward_normals(&screen.quad.map(pos))[0]))
}
(BoxDrag::Rotate, BoxPart::Outside) if !dragging && !self.rotate_zone.rotates_at(&screen.quad, pointer) => CursorIcon::Default.into(),
(BoxDrag::Rotate, BoxPart::Outside) => {
if dragging || matches!(self.rotate_zone, RotateZone::Band | RotateZone::Border { .. }) || away <= style.rotate_reach {
@@ -610,8 +731,8 @@ impl<'a> TransformBox<'a> {
}
/// The parts that take a press, with the box part each stands for. Mirrors what [`parts`](Component::parts)
/// declares: the keyboard parts, a segment per allowed edge, the centre where declared, and the outside; or only the
/// move strips.
/// declares: the keyboard parts, a segment per allowed edge, the centre where declared, and the outside or the
/// rotate handle; or only the move strips.
fn pointer_parts(&self) -> Vec<(PartRef, BoxPart)> {
if self.move_only().is_some() {
let parts = if self.ring_reach().is_some() { 0..8 } else { 0..0 };
@@ -631,6 +752,7 @@ impl<'a> TransformBox<'a> {
parts.push((CENTRE.at(0), BoxPart::Inside));
}
parts.extend((0..4).map(|corner| (OUTSIDE.at(corner), BoxPart::Outside)));
parts.push((ROTATE_HANDLE.at(0), BoxPart::Outside));
parts
}
@@ -640,15 +762,17 @@ impl<'a> TransformBox<'a> {
let style = cx.style;
let mut held: Option<Grip> = *cx.press_slot::<Grip>();
let snap = canvas_snap(&cx.env);
let suspend = suspend_key(snap.as_ref());
for (reference, part) in self.pointer_parts() {
let Some(result) = cx.part_if_declared(reference) else { continue };
let (press, hover) = (result.press, result.hover_pos.filter(|_| result.hovered));
let mods = self.mods.unwrap_or(press.mods);
let acting = drag_mods(mods, suspend);
if let Some(pos) = hover
&& held.is_none()
{
self.report.hovered = Some(part);
let cursor = self.cursor(&CursorLook { space, screen: &screen, style }, part, pos, mods, false);
let cursor = self.cursor(&CursorLook { space, screen: &screen, style }, part, pos, acting, false);
cx.cursor(cursor, CursorPriority::Part);
}
match press.phase {
@@ -656,8 +780,10 @@ impl<'a> TransformBox<'a> {
PressPhase::Down { start, .. } if part == BoxPart::Outside && !self.rotate_zone.rotates_at(&screen.quad, start.origin) => {}
PressPhase::Down { start, .. } if start.button == PointerButton::Primary => {
let from = space.view.to_doc(start.origin);
// The move reach only moves: an Alt press there is a move too.
let moves_pivot = mods.alt && self.move_only().is_none() && matches!(part, BoxPart::Inside | BoxPart::Outside);
// The move reach only moves: an Alt press there is a move too. The rotate handle is a handle, so
// an Alt press on it rotates.
let away_from_handles = part == BoxPart::Inside || (part == BoxPart::Outside && self.rotate_zone != RotateZone::Handle);
let moves_pivot = acting.alt && self.move_only().is_none() && away_from_handles;
let follows = follows_in_slop(part);
let (part, begin) = if moves_pivot { (BoxPart::Pivot, BoxState::new(shown.quad, from)) } else { (part, *shown) };
held = Some(Grip { part, start: begin, from, began: false, follows, moves_pivot, pressed: *shown, last: *shown });
@@ -702,7 +828,7 @@ impl<'a> TransformBox<'a> {
cx.cancel(CancelReason::Unchanged);
} else if grip.began {
cx.commit();
} else if grip.part == BoxPart::Outside && click && start.clicks <= 1 {
} else if grip.part == BoxPart::Outside && reference.key == OUTSIDE && click && start.clicks <= 1 {
self.report.apply = Some(ApplyBy::ClickOutside { at: space.view.to_doc(start.origin) });
} else if grip.moves_pivot && click {
cx.set(grip.start);
@@ -725,10 +851,62 @@ impl<'a> TransformBox<'a> {
cx.propose(next);
let rows = self.readout_rows(cx, space, grip.part, &next, &grip.start);
readout(&*cx, pos, &rows);
let cursor = self.cursor(&CursorLook { space, screen: &on_screen(&space.view, &next), style }, grip.part, pos, mods, true);
let acting = drag_mods(mods, suspend_key(snap));
let cursor = self.cursor(&CursorLook { space, screen: &on_screen(&space.view, &next), style }, grip.part, pos, acting, true);
cx.cursor(cursor, CursorPriority::Drag);
}
/// The pointer on a line's free ends: a drag of an end reports [`LineEndDrag`] (`Begin` with its first position
/// once the press passes the slop, `Update`, `Commit` on the release, `Cancel` when the press is cancelled) with
/// the end snapped through the canvas's snap, and leaves the box's value alone: the host moves the end. A click
/// moves nothing.
fn run_line_ends(&mut self, cx: &mut Cx<'_, Self>, space: &CanvasSpace, line: &LineLook) {
let snap = canvas_snap(&cx.env);
let mut held: Option<EndGrip> = *cx.press_slot::<EndGrip>();
for (end, at) in line.free_ends() {
let Some(result) = cx.part_if_declared(LINE_END.at(end.index())) else { continue };
let (press, hovered) = (result.press, result.hovered);
let mods = self.mods.unwrap_or(press.mods);
if hovered && held.is_none() {
cx.cursor(Cursor::System(CursorIcon::Move), CursorPriority::Part);
}
let ours = held.filter(|grip| grip.end == end);
let (phase, pos, grip) = match (press.phase, ours) {
(PressPhase::Down { start, .. }, _) if start.button == PointerButton::Primary => {
held = Some(EndGrip { end, offset: at - space.view.to_doc(start.origin), began: false });
continue;
}
(PressPhase::DragStart { pos, .. }, Some(grip)) => (GesturePhase::Begin, pos, grip),
(PressPhase::Drag { pos, .. }, Some(grip)) if grip.began => (GesturePhase::Update, pos, grip),
(PressPhase::Release { pos, .. }, Some(grip)) => {
held = None;
if !grip.began {
continue;
}
(GesturePhase::Commit, pos, grip)
}
(PressPhase::Cancel { .. }, Some(grip)) => {
held = None;
if grip.began {
self.report.line_end = Some(LineEndDrag { phase: GesturePhase::Cancel, end, at, mods });
}
continue;
}
_ => continue,
};
let to = space.view.to_doc(pos) + grip.offset;
let (to, lines) = match &snap {
Some(snap) => snap.point(to, mods, GestureSnap::default()),
None => (to, Vec::new()),
};
self.report.snapped = lines;
self.report.line_end = Some(LineEndDrag { phase, end, at: to, mods });
held = (phase != GesturePhase::Commit).then_some(EndGrip { began: true, ..grip });
cx.cursor(Cursor::System(CursorIcon::Move), CursorPriority::Drag);
}
*cx.press_slot::<EndGrip>() = held;
}
/// The session keys: the arrows nudge the picked part (the whole box when no part has focus), Enter applies and
/// Escape closes the box. Untaken, a session's arrows go back to the canvas's tool.
fn run_keys(&mut self, cx: &mut Cx<'_, Self>, space: &CanvasSpace, shown: &BoxState, pressing: bool) {
@@ -775,10 +953,7 @@ impl TransformBox<'_> {
fn paint_handle(&self, draw: &Draw<'_>, cx: &Cx<'_, Self>, part: BoxPart, at: Pos2, enlarged: bool) {
let look = &cx.style.handle;
let side = if enlarged { look.side * OVERFLOW_IN_HANDLES } else { look.side };
let square = PaintShape::Rect(Rect::from_center_size(at, Vec2::splat(side)), CornerRadius::ZERO);
let fill = if self.rules.allows(part) { cx.resolve_part(BOX.at(part.index()), &look.fill) } else { cx.resolve(&look.fill) };
draw.fill(&square, fill);
draw.stroke(&square, StrokeWidth::Thin, look.stroke);
paint_square(draw, cx, at, side, self.rules.allows(part).then(|| BOX.at(part.index())));
if enlarged {
Handle::plus(draw, look, at, side);
}
@@ -791,21 +966,53 @@ impl TransformBox<'_> {
if let Some(outline) = line.outline {
let corners = outline.map(|corner| view.to_screen(corner));
paint_frame(draw, style, corners);
let look = &style.handle;
for k in 0..4 {
let middle = corners[k].lerp(corners[(k + 1) % 4], 0.5);
let square = PaintShape::Rect(Rect::from_center_size(middle, Vec2::splat(look.side)), CornerRadius::ZERO);
draw.fill(&square, cx.resolve(&look.fill));
draw.stroke(&square, StrokeWidth::Thin, look.stroke);
paint_square(draw, cx, corners[k].lerp(corners[(k + 1) % 4], 0.5), style.handle.side, None);
}
}
for (part, end) in line.ends() {
for (part, end) in line.end_parts() {
self.paint_handle(draw, cx, part, view.to_screen(end), false);
}
for (end, at) in line.free_ends() {
paint_square(draw, cx, view.to_screen(at), style.handle.side, Some(LINE_END.at(end.index())));
}
paint_widget(draw, view.to_screen(line.from.midpoint(line.to)), &style.widget);
}
}
/// A handle square of `side` centred on `at`, filled as the state of `part` shows, or at rest without one.
fn paint_square(draw: &Draw<'_>, cx: &Cx<'_, TransformBox<'_>>, at: Pos2, side: f32, part: Option<PartRef>) {
let look = &cx.style.handle;
let square = PaintShape::Rect(Rect::from_center_size(at, Vec2::splat(side)), CornerRadius::ZERO);
let fill = match part {
Some(part) => cx.resolve_part(part, &look.fill),
None => cx.resolve(&look.fill),
};
draw.fill(&square, fill);
draw.stroke(&square, StrokeWidth::Thin, look.stroke);
}
/// The rotate handle of [`RotateZone::Handle`] on the box whose corners are `quad` on the screen: its stem from the
/// middle of side 0 over its halo, and the round knob at its end, filled as the handle's state shows.
fn paint_rotate_handle(draw: &Draw<'_>, cx: &Cx<'_, TransformBox<'_>>, quad: &[Pos2; 4]) {
let style = cx.style;
let (base, knob) = rotate_handle(quad, style.rotate_stem);
let stem = PaintShape::Path(vec![base, knob]);
draw.stroke(&stem, StrokeWidth::Thick, style.halo);
draw.stroke(&stem, StrokeWidth::Medium, style.line);
let look = &style.handle;
let circle = PaintShape::Circle(knob, style.rotate_knob);
draw.fill(&circle, cx.resolve_part(ROTATE_HANDLE.at(0), &look.fill));
draw.stroke(&circle, StrokeWidth::Thin, look.stroke);
}
/// The rotate handle of the box whose corners are `quad` on the screen: the middle of side 0 (corners 0 to 1) and the
/// knob's centre, `stem` out from it across the side, so the handle turns with the box.
fn rotate_handle(quad: &[Pos2; 4], stem: f32) -> (Pos2, Pos2) {
let base = quad[0].lerp(quad[1], 0.5);
(base, base + outward_normals(quad)[0] * stem)
}
/// The outline of a box whose corners are `corners` on the screen: the line over its halo.
fn paint_frame(draw: &Draw<'_>, style: &TransformBoxStyle, corners: [Pos2; 4]) {
let outline = PaintShape::Polygon(corners.to_vec());
@@ -913,6 +1120,8 @@ impl Component for TransformBox<'_> {
band_outer: handle.md * BAND_OUTER_IN_HANDLES,
pivot_radius: cx.tokens.size.handle.sm / 2.0,
pivot_arm: hit.target,
rotate_stem: handle.md * STEM_IN_HANDLES,
rotate_knob: handle.sm / 2.0,
widget: CornerStyle::from_cx(cx),
}
}
@@ -943,7 +1152,8 @@ impl Component for TransformBox<'_> {
/// alike, so the nearest wins where they overlap on a small box;
/// they rank above a side, which ranks above the inside, which ranks above the outside. Every part takes a press's
/// click with its drag, so a press on the box is the box's alone, not split with what lies under it (8.3). A live
/// line's controls declare its two ends only.
/// line's controls declare its two ends only; free ends as points of their own. In [`RotateZone::Handle`] the
/// rotate handle ranks with the handles and is the only outside part.
fn parts(&mut self, rect: Rect, cx: &mut PartsCx<'_, Self>) {
let (Some(space), Some(state)) = (canvas_space(&cx.env), cx.value().copied()) else { return };
let style = cx.style;
@@ -981,7 +1191,13 @@ impl Component for TransformBox<'_> {
cx.part(BOX.at(part.index()), shape).sense(sense | slop_sense(part)).priority(priority).focus_shape(focus).focusable();
any = true;
}
if self.line.is_some() {
if let Some(line) = self.line {
for (end, at) in line.free_ends() {
cx.part(LINE_END.at(end.index()), HitShape::circle(space.view.to_screen(at), style.handle_reach))
.sense(Sense::DRAG | Sense::CLICK)
.priority(HitPriority::new(HitLevel::Handle, HANDLE_SUB))
.pointer_only(LINE_END_BY_KEY);
}
if any {
cx.roving(Roving::new(NavShape::Flat).page(Some(1)));
}
@@ -1033,17 +1249,28 @@ impl Component for TransformBox<'_> {
}
}
RotateZone::Band => {}
RotateZone::Handle if self.rules.allows(BoxPart::Outside) => {
let (_, knob) = rotate_handle(&quad, style.rotate_stem);
cx.part(ROTATE_HANDLE.at(0), HitShape::circle(knob, style.handle_reach))
.sense(Sense::DRAG | Sense::CLICK | slop_sense(BoxPart::Outside))
.priority(HitPriority::new(HitLevel::Handle, HANDLE_SUB))
.pointer_only(ROTATE_BY_KEY);
}
RotateZone::Handle => {}
}
}
fn update(&mut self, cx: &mut Cx<'_, Self>) {
let (Some(space), Some(shown)) = (canvas_space(&cx.env), cx.value().copied()) else { return };
let held = cx.press_slot::<Grip>().is_some();
let held = cx.press_slot::<Grip>().is_some() || cx.press_slot::<EndGrip>().is_some();
self.run_pointer(cx, &space, &shown);
if let Some(line) = self.line.filter(|line| line.ends == LineEnds::Free) {
self.run_line_ends(cx, &space, &line);
}
self.pivot_held = cx.press_slot::<Grip>().is_some_and(|grip| grip.part == BoxPart::Pivot);
self.dragging = cx.press_slot::<Grip>().is_some_and(|grip| grip.began);
self.report.held = cx.press_slot::<Grip>().map(|grip| grip.part);
let pressing = held || cx.press_slot::<Grip>().is_some();
let pressing = held || cx.press_slot::<Grip>().is_some() || cx.press_slot::<EndGrip>().is_some();
if self.move_only().is_none() {
self.run_keys(cx, &space, &shown, pressing);
}
@@ -1064,6 +1291,9 @@ impl Component for TransformBox<'_> {
Some(line) => self.paint_line(&draw, cx, &space.view, &line),
None => {
paint_frame(&draw, style, screen.quad.map(pos));
if self.rotate_zone == RotateZone::Handle && self.rules.allows(BoxPart::Outside) {
paint_rotate_handle(&draw, cx, &screen.quad.map(pos));
}
if self.centre_mark {
let centre = screen.quad.iter().fold(Vec2::ZERO, |sum, corner| sum + pos(*corner).to_vec2()) / 4.0;
paint_centre_glyph(&draw, centre.to_pos2(), style);
@@ -1100,8 +1330,8 @@ impl Component for TransformBox<'_> {
}
fn finish(self, cx: Cx<'_, Self>) -> TransformBoxOutput {
let Report { apply, discard, hovered, picked, held, snapped } = self.report;
TransformBoxOutput { edit: cx.edit_response(), apply, discard, picked, hovered, held, snapped }
let Report { apply, discard, hovered, picked, held, snapped, line_end } = self.report;
TransformBoxOutput { edit: cx.edit_response(), apply, discard, picked, hovered, held, snapped, line_end }
}
}
@@ -1124,6 +1354,8 @@ pub struct TransformBoxOutput {
pub held: Option<BoxPart>,
/// The snap lines of the point being dragged, for the host's one drawing site.
pub snapped: Vec<craft_behavior::geometry::SnapLine>,
/// The drag of a line end, in [`LineEnds::Free`].
pub line_end: Option<LineEndDrag>,
}
impl Outcome for TransformBoxOutput {
@@ -1148,6 +1380,17 @@ fn vec2_of(v: DocVec) -> Vec2 {
Vec2::new(v.x as f32, v.y as f32)
}
/// The suspend key of the canvas's snap, Control without one.
fn suspend_key(snap: Option<&Snap>) -> SnapSuspend {
snap.map_or_else(SnapSuspend::default, |snap| snap.options().suspend)
}
/// The keys a drag acts on, from the keys held: while Alt suspends the canvas's snapping, Alt is the snap's alone, so
/// it neither scales about the reference point nor moves it.
fn drag_mods(mods: Mods, suspend: SnapSuspend) -> Mods {
if suspend == SnapSuspend::Alt { Mods { alt: false, ..mods } } else { mods }
}
/// The position of a corner, an edge's midpoint or the reference point; `None` for the inside and the outside.
fn handle_point(state: &BoxState, part: BoxPart) -> Option<Point> {
let q = &state.quad;
@@ -1,7 +1,8 @@
//! Stories of the transform box: Free Transform with its reference point, the Move tool's controls, Distort, the
//! Ellipse tool's centre mark and the Line tool's live-line controls.
//! Ellipse tool's centre mark, the rotate handle and the Line tool's live-line controls, with box or free ends.
use super::{BOX, LineLook, RotateZone, TransformBox};
use super::{BOX, LINE_END, LineEnd, LineEnds, LineLook, ROTATE_HANDLE, RotateZone, TransformBox, TransformBoxOutput};
use craft_behavior::GesturePhase;
use craft_behavior::geometry::quad::{BoxPart, BoxRules, BoxState, TransformMode};
use craft_behavior::kurbo::{Point, Rect as DocRect};
use craft_ui::canvas::Canvas;
@@ -27,6 +28,11 @@ fn free_box(state: Bind<'_, BoxState>) -> TransformBox<'_> {
/// Shows the box `make` builds over the story's box as the only canvas control of a canvas.
fn on_canvas(ui: &mut Ui, data: &mut StoryData, make: impl for<'a> Fn(Bind<'a, BoxState>) -> TransformBox<'a>) -> StoryOutput {
shown_on_canvas(ui, data, make).map(|output| StoryOutput::from(output.edit)).unwrap_or_default()
}
/// [`on_canvas`] with the box's whole output.
fn shown_on_canvas(ui: &mut Ui, data: &mut StoryData, make: impl for<'a> Fn(Bind<'a, BoxState>) -> TransformBox<'a>) -> Option<TransformBoxOutput> {
let state = data.value("box", BoxState::from_rect(PICTURE));
let room = craft_ui::testing::stage(ui);
let view = craft_ui::testing::canvas_story::story_view(room, ui.pixels_per_point(), PICTURE.center(), 100.0);
@@ -36,7 +42,7 @@ fn on_canvas(ui: &mut Ui, data: &mut StoryData, make: impl for<'a> Fn(Bind<'a, B
show_quad(ui, body.rect, "Layer", state.quad, &layer);
make(Bind::bound(&mut *state)).show_at(ui, body.rect)
});
shown.inner.map(|output| StoryOutput::from(output.edit)).unwrap_or_default()
shown.inner
}
#[story(TransformBox<'static>, covers = [Default], drive = Drive::Drag(Grip::part(BOX.at(BoxPart::Corner(2).index())).toward(vec2(1.0, 1.0))))]
@@ -80,3 +86,38 @@ fn live_line(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let line = LineLook::new(quad[3], quad[1]);
on_canvas(ui, data, move |state| free_box(state).rotate_zone(RotateZone::Band).inside_moves(false).reference_point(false).line(line))
}
/// Free Transform turned only by the rotate handle on its stem above the top side; the rest of the outside is the
/// tool's.
#[story(TransformBox<'static>, covers = [Default], drive = Drive::Drag(Grip::part(ROTATE_HANDLE.at(0)).toward(vec2(1.0, 0.0))))]
fn rotate_handle(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
on_canvas(ui, data, |state| free_box(state).reference_point(true).rotate_zone(RotateZone::Handle))
}
/// A live line whose ends are free points: dragging an end moves only that end, at any angle, and the story commits
/// it as a host does; the box stays.
#[story(TransformBox<'static>, covers = [Default], drive = Drive::Drag(Grip::part(LINE_END.at(1)).toward(vec2(1.0, -1.0))))]
fn line_free_ends(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let quad = BoxState::from_rect(PICTURE).quad;
let ends = *data.value("ends", [quad[3], quad[1]]);
let line = LineLook::new(ends[0], ends[1]).ends(LineEnds::Free);
let shown =
shown_on_canvas(ui, data, move |state| free_box(state).rotate_zone(RotateZone::Band).inside_moves(false).reference_point(false).line(line));
let Some(output) = shown else { return StoryOutput::default() };
if let Some(drag) = output.line_end {
let index = usize::from(drag.end == LineEnd::To);
match drag.phase {
GesturePhase::Cancel => {
let before = *data.value("before", ends);
*data.value("ends", ends) = before;
}
phase => {
if phase == GesturePhase::Begin {
*data.value("before", ends) = ends;
}
data.value("ends", ends)[index] = drag.at;
}
}
}
StoryOutput::from(output.edit)
}
@@ -485,12 +485,12 @@ impl Cells<'_> {
/// The reference point picker; a pick moves the reference point to that point of the box.
fn reference(&mut self, ui: &mut Ui, cx: &mut BodyCx<'_>, pass: &Pass, compact: bool) {
let anchor = pass.before.state.anchor_of_pivot().unwrap_or(Anchor9::Centre);
let mut picker = ReferencePoint::new(self.words.reference.clone(), Bind::given(anchor)).enabled(self.enabled);
let mut picker = ReferencePoint::new(self.words.reference.clone(), Bind::given(Some(anchor))).enabled(self.enabled);
if compact {
picker = picker.compact();
}
let shown = picker.show(ui);
let Some(picked) = shown.value().copied() else { return };
let Some(picked) = shown.value().copied().flatten() else { return };
let before = pass.before;
let state = BoxState::new(before.state.quad, before.state.point_at(picked));
let event = EditEvent::set(Mixed::Same(before), TransformRow { state, skew_v: before.skew_v }, self.name.clone(), None);
+57 -1
View File
@@ -5,7 +5,9 @@ use std::rc::Rc;
use craft_behavior::EditEvent;
use craft_color_ui::ui::gradient::{ColorStop, GradientStops};
use craft_draw::ui::gradient::{GradientFill, GradientFillEditor, GradientGroup, GradientItem, GradientRef, GradientStyle};
use craft_draw::ui::gradient::{
FocusOutline, GradientFill, GradientFillEditor, GradientGroup, GradientItem, GradientRef, GradientStyle, GradientTile,
};
use craft_theme::Srgba;
use craft_ui::contract::{Bind, Role};
use craft_ui::patterns::presets::PresetState;
@@ -110,3 +112,57 @@ fn each_row_reports_one_gesture_of_the_whole_fill() {
assert_eq!(value, &expected, "the preset replaces the stops with centred midpoints and keeps the rest");
}
}
#[trial]
fn a_style_tile_samples_its_parameter_from_the_start_point_outward() {
let tile = |style, angle| GradientTile::Style { style, angle };
let t = |tile: GradientTile, x: f32, y: f32| tile.t_at(vec2(x, y));
// Linear at -90 runs down: 0 at the top, 1 at the bottom, equal along a row.
let down = tile(GradientStyle::Linear, -90.0);
assert!(t(down, 0.5, 0.0) < 0.01 && t(down, 0.5, 1.0) > 0.99);
assert!(t(down, 0.5, 0.25) < t(down, 0.5, 0.75));
assert!((t(down, 0.1, 0.4) - t(down, 0.9, 0.4)).abs() < 1e-4);
// At -45 the start is the top-left corner and the end the bottom-right.
let diagonal = tile(GradientStyle::Linear, -45.0);
assert!(t(diagonal, 0.0, 0.0) < 0.01 && t(diagonal, 1.0, 1.0) > 0.99);
// Radial is 0 at the centre and equal on a circle round it.
let radial = tile(GradientStyle::Radial, 0.0);
assert!(t(radial, 0.5, 0.5) < 0.01);
assert!(t(radial, 0.5, 0.5) < t(radial, 0.6, 0.5) && t(radial, 0.6, 0.5) < t(radial, 0.8, 0.5));
assert!((t(radial, 0.7, 0.5) - t(radial, 0.5, 0.3)).abs() < 1e-4);
// Reflected is mirrored about the centre.
let mirrored = tile(GradientStyle::Reflected, 0.0);
assert!(t(mirrored, 0.5, 0.5) < 0.01);
assert!((t(mirrored, 0.8, 0.3) - t(mirrored, 0.2, 0.7)).abs() < 1e-4);
assert!(t(mirrored, 0.6, 0.5) < t(mirrored, 0.9, 0.5));
// Diamond isolines run through the points of equal |dx| + |dy|, which a circle does not.
let diamond = tile(GradientStyle::Diamond, 0.0);
assert!((t(diamond, 0.7, 0.5) - t(diamond, 0.6, 0.6)).abs() < 1e-4);
assert!(t(diamond, 0.5, 0.5) < 0.01);
// Angle sweeps counter-clockwise from the start direction, rising round the centre.
let sweep = tile(GradientStyle::Angle, 0.0);
assert!(t(sweep, 0.9, 0.5) < 0.01);
assert!(t(sweep, 0.9, 0.5) < t(sweep, 0.5, 0.1), "up is a quarter turn counter-clockwise");
assert!(t(sweep, 0.5, 0.1) < t(sweep, 0.1, 0.5));
assert!(t(sweep, 0.1, 0.5) < t(sweep, 0.5, 0.9));
// Focus: 0 at the focus centre, rising outward; circles round, rectangles square.
let focus = egui::Rect::from_min_max(egui::pos2(0.25, 0.25), egui::pos2(0.75, 0.75));
let circle = GradientTile::Focus { outline: FocusOutline::Circle, focus };
let rect = GradientTile::Focus { outline: FocusOutline::Rect, focus };
for tile in [circle, rect] {
assert!(t(tile, 0.5, 0.5) < 0.01);
assert!(t(tile, 0.5, 0.5) < t(tile, 0.6, 0.5) && t(tile, 0.6, 0.5) < t(tile, 0.9, 0.5));
assert!((t(tile, 0.7, 0.5) - t(tile, 0.5, 0.3)).abs() < 1e-4);
}
// Both reach 1 at the farthest corner, so a diagonal step reads the same in both; along an axis the rectangle's
// square isoline is nearer the centre than the circle's, so it rises faster there.
assert!((t(circle, 0.7, 0.7) - t(rect, 0.7, 0.7)).abs() < 1e-4, "both outlines reach the corner together");
assert!(t(rect, 0.9, 0.5) > t(circle, 0.9, 0.5) + 0.05, "along an axis a rectangle rises faster than a circle");
assert!((t(rect, 0.7, 0.7) - t(rect, 0.7, 0.5)).abs() < 1e-4, "a rectangle's isoline is square");
}
+191 -5
View File
@@ -1,12 +1,13 @@
//! `TransformBox`, `TransformOverlay` and `TransformTool`: the parts the pointer takes, what each drag does, the
//! keys, the readout and the overlay's edits.
use craft_behavior::geometry::quad::{BoxPart, BoxRules, BoxState, ScaleRule, TransformMode};
use craft_behavior::geometry::{SnapKind, SnapOptions, SnapTarget, SnapTargets};
use craft_behavior::kurbo::{Point, Rect};
use craft_behavior::{CanvasView, EditEvent, RulerUnits, Ticks};
use craft_behavior::geometry::quad::{BoxAllow, BoxPart, BoxRules, BoxState, ScaleRule, TransformMode};
use craft_behavior::geometry::{SnapKind, SnapOptions, SnapSuspend, SnapTarget, SnapTargets};
use craft_behavior::kurbo::{Affine, Point, Rect};
use craft_behavior::{CanvasView, EditEvent, GesturePhase, RulerUnits, Ticks};
use craft_draw::ui::transform::{
LineLook, RotateZone, TransformBox, TransformEdit, TransformOverlay, TransformReach, TransformSession, TransformSettings,
LineEnd, LineEndDrag, LineEnds, LineLook, RotateZone, TransformBox, TransformEdit, TransformOverlay, TransformReach, TransformSession,
TransformSettings,
};
use craft_keymap::{Mods, Platform};
use craft_ui::canvas::{Canvas, RulerText, Snap};
@@ -55,6 +56,8 @@ struct Config {
line: Option<LineLook>,
/// Snap targets beside the guides at [`SNAP_XS`].
targets: Vec<SnapTarget>,
/// The key that suspends the canvas's snapping.
suspend: SnapSuspend,
/// egui runs each frame twice and gives the frame's input to its first pass only.
twice: bool,
}
@@ -73,6 +76,8 @@ struct Host {
guide_events: usize,
/// The snap lines the last pass reported.
snapped: usize,
/// Every free line end drag the passes reported.
line_ends: Vec<LineEndDrag>,
}
struct Harness {
@@ -101,6 +106,7 @@ fn defaults() -> Config {
centre_mark: false,
line: None,
targets: Vec::new(),
suspend: SnapSuspend::Control,
twice: false,
}
}
@@ -128,6 +134,7 @@ fn harness(state: BoxState, setup: impl FnOnce(&mut Config)) -> Harness {
view: CanvasView::new(egui::Rect::NOTHING, Point::ZERO, 1.0),
guide_events: 0,
snapped: 0,
line_ends: Vec::new(),
}));
let shown_host = Rc::clone(&host);
let mut guides = vec![Guide::new(GuideKey::new(1), craft_behavior::Axis::Y, 300.0)];
@@ -145,6 +152,7 @@ fn harness(state: BoxState, setup: impl FnOnce(&mut Config)) -> Harness {
// A box on the pixel grid alone has the grid through a snap that snaps to nothing.
let mut options = SnapOptions::default();
options.on = config.snap;
options.suspend = config.suspend;
let snap = Snap::new(Arc::clone(&targets), options).whole_pixels(config.pixel_grid);
let view = CanvasView::new(room, Point::new(f64::from(room.width()) / 2.0, f64::from(room.height()) / 2.0), 1.0)
.rotation(config.rotation)
@@ -193,6 +201,9 @@ fn harness(state: BoxState, setup: impl FnOnce(&mut Config)) -> Harness {
let mut host = shown_host.borrow_mut();
host.guide_events += guide_edits;
host.snapped = output.snapped.len();
if let Some(drag) = output.line_end {
host.line_ends.push(drag);
}
host.id = output.edit.response.id;
host.applied += usize::from(output.apply.is_some());
host.discarded += usize::from(output.discard);
@@ -1012,6 +1023,181 @@ fn control_keeps_snapping_on_an_explicit_distort_corner_only() {
}
}
/// The rotate handle stands on its stem above the middle of the top side: a drag from it turns the box about its
/// reference point (Shift in rotate steps); the rest of the outside is the tool's, and a click there or on the handle
/// applies nothing. Where the rules refuse rotating there is no handle.
#[trial]
fn the_rotate_handle_turns_the_box_about_its_reference_point_and_the_rest_of_the_outside_is_the_tools() {
let handle = |config: &mut Config| config.zone = RotateZone::Handle;
// The points straight above the top side's middle that the handle takes.
let handle_reach = |h: &mut Harness| -> Vec<Point> {
(1..80)
.map(|up| Point::new(200.0, RECT.y0 - f64::from(up)))
.filter(|&at| {
hover(h, at);
h.host.borrow().hovered == Some(BoxPart::Outside)
})
.collect()
};
let mut h = harness(BoxState::from_rect(RECT), handle);
let reach = handle_reach(&mut h);
assert!(!reach.is_empty(), "the handle stands above the top side");
assert!(reach[0].y < RECT.y0 - 8.0, "on a stem, clear of the top edge's handle: {reach:?}");
let knob = reach[reach.len() / 2];
let centre = RECT.center();
for (mods, angle, within) in [(None, 20.0, 0.01), (Some(Mods::SHIFT), 15.0, 1e-6)] {
let mut h = harness(BoxState::from_rect(RECT), |config| {
handle(config);
config.mods = mods;
});
drag(&mut h, knob, Affine::rotate_about(20f64.to_radians(), centre) * knob);
let state = h.state();
assert!((state.angle() - angle).abs() < within, "{mods:?}: turned {}, expected {angle}", state.angle());
assert!(state.pivot.distance(centre) < 1e-9, "about the reference point: {:?}", state.pivot);
assert_eq!(h.host.borrow().events.last(), Some(&Seen::Commit));
}
// Elsewhere outside: nothing of the box.
let mut h = harness(BoxState::from_rect(RECT), handle);
let away = Point::new(340.0, 260.0);
hover(&mut h, away);
assert_eq!(h.host.borrow().hovered, None, "the rest of the outside is the tool's");
drag(&mut h, away, Point::new(360.0, 200.0));
assert!(h.host.borrow().events.is_empty(), "a drag there turns nothing: {:?}", h.host.borrow().events);
assert_eq!(h.state(), BoxState::from_rect(RECT));
for at in [away, knob] {
let at = h.screen(at);
frame(&mut h, vec![pointer::moved(at)]);
frame(&mut h, vec![pointer::press(at)]);
frame(&mut h, vec![pointer::release(at)]);
frame(&mut h, Vec::new());
}
assert_eq!(h.host.borrow().applied, 0, "a click outside or on the handle applies nothing");
let mut h = harness(BoxState::from_rect(RECT), |config| {
handle(config);
config.rules = BoxRules::default().with_allow(BoxAllow::new(false, true, true));
});
assert!(handle_reach(&mut h).is_empty(), "no handle where rotating is refused");
}
/// With Alt as the snap suspend key, Alt suspends the snapping and is never the drag's: a corner does not scale about
/// the reference point and an Alt press inside moves the box, not the reference point. Control no longer suspends.
#[trial]
fn with_alt_as_the_snap_key_alt_suspends_snapping_and_no_alt_press_moves_the_reference_point() {
// (os, the keys held, whether the corner snaps onto 310)
let cases = [
(Platform::Mac, None, true),
(Platform::Mac, Some(Mods::ALT), false),
(Platform::Mac, Some(Mods::CTRL), true),
(Platform::Windows, Some(Mods::ALT), false),
];
for (os, held, snaps) in cases {
let mut h = harness(BoxState::from_rect(RECT), |config| {
config.snap = true;
config.suspend = SnapSuspend::Alt;
config.mods = held;
config.rules = BoxRules::default().with_aspect_linked(false);
});
h.fixture.os(os);
let from = h.screen(Point::new(300.0, 220.0));
frame(&mut h, vec![pointer::moved(from)]);
frame(&mut h, vec![pointer::press(from)]);
frame(&mut h, vec![pointer::moved(from + by(4.0, 0.0))]);
frame(&mut h, vec![pointer::moved(from + by(7.0, 0.0))]);
frame(&mut h, vec![pointer::release(from + by(7.0, 0.0))]);
let quad = h.state().quad;
let moved = quad[2].x - RECT.x1;
let expected = if snaps { 10.0 } else { 7.0 };
assert!((moved - expected).abs() < 1e-3, "{os:?} {held:?}: moved {moved}, expected {expected}");
assert!(quad[0].distance(Point::new(RECT.x0, RECT.y0)) < 1e-6, "{os:?} {held:?}: no scaling about the reference point: {quad:?}");
}
let mut h = harness(BoxState::from_rect(RECT), |config| {
config.snap = true;
config.suspend = SnapSuspend::Alt;
config.mods = Some(Mods::ALT);
});
// 7 right brings the right edge within reach of the guide at 310; the Alt drag stays unsnapped.
drag(&mut h, Point::new(150.0, 120.0), Point::new(157.0, 120.0));
let state = h.state();
assert!(state.quad[0].distance(Point::new(107.0, RECT.y0)) < 1e-3, "the Alt drag moves the box, unsnapped: {:?}", state.quad);
assert!(state.pivot.distance(Point::new(207.0, 150.0)) < 1e-3, "the reference point rides along: {:?}", state.pivot);
}
/// The resize arrows follow the box's own axes: corner 2's along its bisector, the right edge's along the box's x
/// axis, so a box turned by 30° shows other arrows than a level one.
#[trial]
fn a_turned_box_shows_resize_arrows_along_its_own_axes() {
use craft_behavior::{Cursor, CursorIcon};
let cursor_over = |h: &mut Harness, at: Point| {
hover(h, at);
craft_ui::runtime::cursor::current(h.fixture.ctx())
};
let level = BoxState::from_rect(RECT);
let turned = level.turned_about_pivot(30f64.to_radians());
// Level: the corner's arrow at 45°, the edge's at 0°. Turned by 30°: 75° and 30°.
for (state, corner, edge) in
[(level, CursorIcon::ResizeNwSe, CursorIcon::ResizeHorizontal), (turned, CursorIcon::ResizeVertical, CursorIcon::ResizeNwSe)]
{
let mut h = harness(state, |_| {});
let at_corner = state.quad[2];
let at_edge = state.quad[1].midpoint(state.quad[2]);
assert_eq!(cursor_over(&mut h, at_corner), Some(Cursor::from(corner)), "corner 2 of {:?}", state.quad);
assert_eq!(cursor_over(&mut h, at_edge), Some(Cursor::from(edge)), "the right edge of {:?}", state.quad);
}
}
/// Free line ends: a drag of an end reports Begin, Update and Commit for that end only, at any angle, snapped through
/// the canvas's snap unless Control suspends it, and leaves the box value alone; Escape cancels the drag.
#[trial]
fn free_line_ends_move_one_end_and_report_the_drag_for_the_host_to_commit() {
let (from, to) = (Point::new(RECT.x0, RECT.y1), Point::new(RECT.x1, RECT.y0));
let line = LineLook::new(from, to).ends(LineEnds::Free);
let free = |held: Option<Mods>| {
let mut h = harness(BoxState::from_rect(RECT), |config| {
config.snap = true;
config.mods = held;
config.reference_point = false;
config.zone = RotateZone::Band;
config.line = Some(line);
});
h.fixture.os(Platform::Mac);
h
};
// 7 right and 30 up, at a slant: the end lands on the guide at 310.
let dragged_to = to + kurbo_vec(7.0, -30.0);
for (held, x) in [(None, 310.0), (Some(Mods::CTRL), 307.0)] {
let mut h = free(held);
drag(&mut h, to, dragged_to);
let drags = h.host.borrow().line_ends.clone();
let phases: Vec<GesturePhase> = drags.iter().map(|drag| drag.phase).collect();
assert_eq!(phases.first(), Some(&GesturePhase::Begin), "{held:?}: {phases:?}");
assert_eq!(phases.last(), Some(&GesturePhase::Commit), "{held:?}: {phases:?}");
assert!(phases[1..phases.len() - 1].iter().all(|phase| *phase == GesturePhase::Update), "{held:?}: {phases:?}");
assert!(drags.iter().all(|drag| drag.end == LineEnd::To), "only the dragged end moves: {drags:?}");
let Some(last) = drags.last() else { panic!("no drag reported") };
assert!(last.at.distance(Point::new(x, dragged_to.y)) < 1e-3, "{held:?}: the end at {:?}, expected x {x}", last.at);
assert_eq!(h.state(), BoxState::from_rect(RECT), "the box value is unchanged");
assert!(h.host.borrow().events.is_empty(), "no edit of the box: {:?}", h.host.borrow().events);
}
let mut h = free(None);
let (start, end) = (h.screen(to), h.screen(dragged_to));
frame(&mut h, vec![pointer::moved(start)]);
frame(&mut h, vec![pointer::press(start)]);
frame(&mut h, vec![pointer::moved(start + (end - start) * 0.5)]);
frame(&mut h, vec![pointer::moved(end)]);
h.fixture.key(egui::Key::Escape, egui::Modifiers::NONE);
frame(&mut h, vec![pointer::release(end)]);
frame(&mut h, Vec::new());
let phases: Vec<GesturePhase> = h.host.borrow().line_ends.iter().map(|drag| drag.phase).collect();
assert_eq!(phases.last(), Some(&GesturePhase::Cancel), "Escape cancels the end drag: {phases:?}");
assert!(!phases.contains(&GesturePhase::Commit), "nothing is committed: {phases:?}");
assert_eq!(h.host.borrow().discarded, 0, "Escape cancels the drag and does not close the box");
}
/// The reference point snaps to the turned box's nine points and to nothing else, with the canvas's snapping on or
/// off: 2 units off the guide at 160 it stays put.
#[trial]
+5
View File
@@ -45,6 +45,11 @@ craft_ui::words! {
installed: "missingFonts.installed" = "Installed";
missing: "missingFonts.missing" = "Missing";
warning: template "missingFonts.warning" = "font '{family}' is not installed; text may render using a fallback face";
/// The note for a shown font that is not installed, with `{family}` the missing family and `{face}` the face shown
/// in its place.
shown_as: template "missingFonts.shownAs" = "{family} isn't installed on this computer, so its text is shown in {face}. Line breaks and page count can differ from where the document was made.";
/// The advice that follows the note when the host's list has a row that adds a font.
add_font: "missingFonts.addFont" = "If you have the font file, add it with Add Font… at the end of this list.";
missing_font: template "missingFonts.missingFont" = "{font} ({status})";
installed_style: template "missingFonts.installedStyle" = "{status} ({style})";
font_status: template "missingFonts.fontStatus" = "{font}: {status}";
+113 -12
View File
@@ -14,7 +14,7 @@ use craft_behavior::{Codec, EditEvent, IconId, Mixed, NotAValue, PartKey, Sense,
use craft_behavior::{HitLevel, HitPriority, NavMove, Preview};
use craft_font_catalog::Catalog;
use craft_host::Section;
use craft_ui::buttons::IconButton;
use craft_ui::buttons::{ControlPlace, IconButton};
use craft_ui::contract::{
Bind, Common, Component, Cx, Edit as _, EditResponse, Focus as _, Input, MeasureCx, Outcome, OverlayUi, Overlays as _, PaintUi, PartsCx,
Pointer as _, Props as _, Remember as _, Role, WordSetCx as _,
@@ -27,6 +27,7 @@ use craft_ui::text::{Adornment, place, reserve};
use egui::{Rect, Response, Vec2};
use serde::{Deserialize, Serialize};
use crate::missing::{DocumentFont, FontStatus, MissingFontsWords, document_fonts};
use rank::{Info, infos, shown_name};
craft_ui::words! {
@@ -35,6 +36,10 @@ craft_ui::words! {
pub struct FontPickerWords {
search: "fontPicker.search" = "Search fonts";
recent: "fontPicker.recent" = "Recent";
/// The `Plain` picker's heading over the recent families.
recently_used: "fontPicker.recentlyUsed" = "Recently Used Fonts";
/// The `Plain` picker's heading over every family.
all_fonts: "fontPicker.allFonts" = "All Fonts";
favorites: "fontPicker.favorites" = "Show favorite fonts";
similar: "fontPicker.similar" = "Show similar fonts";
variable: "fontPicker.variable" = "Show variable fonts";
@@ -297,6 +302,28 @@ pub fn family_rows(
rank::list(catalog, &infos(catalog), &listing, &rank::Language { folder: &folder, collator: &collator }, true).0
}
/// How a [`FontPicker`] lays out its list.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum FontPickerKind {
/// The library picker: stars, recents, filters and the class column.
#[default]
Library,
/// Word's plain font box: recent fonts, actions and all fonts.
Plain,
}
/// What the note of a shown font that is not installed advises.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum MissingAdvice {
/// The note alone.
#[default]
None,
/// The note, then the advice to add the font file with the host's Add Font row.
AddFont,
}
/// What a [`FontPicker`] reports.
#[derive(Debug)]
#[non_exhaustive]
@@ -314,6 +341,8 @@ pub struct FontPickerOutput {
/// of the open list (Photoshop previews on hover). It ends when the pointer leaves the rows, the list closes
/// (Escape, a press outside) or a row is picked. The field's value and text stay.
pub preview: Preview<String>,
/// The index of the action row picked, in the `actions` the host gave.
pub action: Option<usize>,
}
impl Outcome for FontPickerOutput {
@@ -334,6 +363,9 @@ const TEXT: PartKey = PartKey::new("text");
/// The chevron that opens and closes the list.
const CHEVRON: PartKey = PartKey::new("chevron");
const CHEVRON_ICON: &str = "chevron_down";
/// The mark before the chevron of a shown font that is not installed; its tooltip is the note.
const WARNING: PartKey = PartKey::new("missing");
const WARNING_ICON: &str = "warning";
/// The popup the chevron and Alt+Down toggle.
const POPUP: &str = "list";
/// The star at the end of a row.
@@ -350,6 +382,8 @@ fn text_key() -> TextKey<String> {
struct FamilyCodec {
infos: Arc<rank::Infos>,
language: String,
/// A typed name that is no installed family is a value too (Word's font box applies it as typed).
free: bool,
}
impl FamilyCodec {
@@ -365,13 +399,18 @@ impl Codec for FamilyCodec {
self.infos.families.get(family).map_or_else(|| family.clone(), |info| self.shown(family, info))
}
/// A family whose name, shown or in the catalog, is the text apart from case.
/// A family whose name, shown or in the catalog, is the text apart from case; for a `free` codec, else the
/// trimmed text when it is not empty.
fn parse(&self, text: &str, _: &String) -> Result<String, NotAValue> {
let wanted = text.trim().to_lowercase();
let named = |(family, info): (&String, &Info)| {
(family.to_lowercase() == wanted || self.shown(family, info).to_lowercase() == wanted).then(|| family.clone())
};
self.infos.families.iter().find_map(named).ok_or(NotAValue)
match self.infos.families.iter().find_map(named) {
Some(family) => Ok(family),
None if self.free && !wanted.is_empty() => Ok(text.trim().to_owned()),
None => Err(NotAValue),
}
}
fn sample(&self, current: &String) -> std::borrow::Cow<'_, str> {
@@ -461,6 +500,19 @@ pub struct FontPicker<'a> {
/// Families the host can fetch but that are not installed, listed with the served mark.
#[prop]
served: &'a [String],
/// How the list is laid out: the library picker, or Word's plain font box.
#[prop]
kind: FontPickerKind,
/// Action rows after the families (the `Plain` box), reported through `FontPickerOutput::action`.
#[prop]
actions: &'a [Label],
/// The face the shown font is displayed in when it is not installed, for the note beside it.
#[prop]
shown_as: Option<&'a str>,
/// What the note advises beyond naming the face; `AddFont` when an action row adds a font.
#[prop]
advice: MissingAdvice,
action: Option<usize>,
}
impl<'a> FontPicker<'a> {
@@ -478,16 +530,44 @@ impl<'a> FontPicker<'a> {
preview: Preview::Unchanged,
preview_text: None,
served: &[],
kind: FontPickerKind::default(),
actions: &[],
shown_as: None,
advice: MissingAdvice::default(),
action: None,
}
.label(label)
}
fn trailing(name: Label) -> [Adornment; 1] {
[Adornment::button(CHEVRON, IconSpec::svg(IconId::new(CHEVRON_ICON)), name)]
/// The adornments at the end of the field: the missing mark when `missing`, then the chevron. The mark is a glyph
/// whose part carries the note.
fn trailing(name: Label, missing: bool) -> Vec<Adornment> {
let mut all = Vec::with_capacity(2);
if missing {
all.push(Adornment::glyph(IconSpec::svg(IconId::new(WARNING_ICON))));
}
all.push(Adornment::button(CHEVRON, IconSpec::svg(IconId::new(CHEVRON_ICON)), name));
all
}
/// The note for `family` when it is shown in another face because the catalog lacks it, by the rule the Missing
/// Fonts dialog uses: the missing-font sentence, then the advice the host chose.
fn missing_note(&self, family: &str, words: &MissingFontsWords) -> Option<Label> {
let face = self.shown_as?;
let status = document_fonts(self.catalog, &[DocumentFont::new(family, "", None)]).into_iter().next()?.status;
if status != FontStatus::Missing {
return None;
}
let mut note = words.shown_as.fill(&[("family", family), ("face", face)]);
if self.advice == MissingAdvice::AddFont {
note.push(' ');
note.push_str(words.add_font.as_str());
}
Some(Label::from(note))
}
fn codec(&self, env: &EnvView<'_>) -> FamilyCodec {
FamilyCodec { infos: infos(self.catalog), language: ui_language(env) }
FamilyCodec { infos: infos(self.catalog), language: ui_language(env), free: self.kind == FontPickerKind::Plain }
}
/// The families in list order without filters or recents, which the arrows and the wheel step through.
@@ -508,8 +588,11 @@ impl Component for FontPicker<'_> {
type Style = craft_ui::text::FieldStyle;
type Output = FontPickerOutput;
/// A field; in a ribbon (`ControlPlace::Ribbon`) held at the small field length (`size.length.field.sm`), as a
/// ribbon's font box is: wide enough for a family name and its menu arrow, the same width whichever it shows.
fn style(cx: &craft_ui::style::StyleCx<'_>, _: FontPickerStyleKey) -> craft_ui::text::FieldStyle {
craft_ui::text::FieldStyle::at(cx)
let field = craft_ui::text::FieldStyle::at(cx);
if cx.env::<ControlPlace>() == ControlPlace::Ribbon { field.held_at(cx.tokens.size.length.field.sm) } else { field }
}
/// The wheel steps the family through the list.
@@ -518,18 +601,30 @@ impl Component for FontPicker<'_> {
}
/// The width of the longest family names in common use, so the field keeps its size whichever family is picked.
/// In a ribbon the name field is the short field length (`size.length.short`) wide whichever family it shows, a
/// longer name scrolling in it as in a word processor's font box: that is its least, about the old ribbon's font
/// name, so a row short of room never narrows the box to its menu arrow; where the room allows the style holds
/// the box at the small field length (`FieldStyle::held_at`).
fn measure(&mut self, cx: &MeasureCx<'_, Self>) -> Vec2 {
let current = cx.value().map_or("", String::as_str);
let widest = [NAME_SAMPLE, current].into_iter().map(|text| cx.field_text(&TextRun::new(text))).fold(Vec2::ZERO, Vec2::max);
let ribbon = cx.env.get::<ControlPlace>() == ControlPlace::Ribbon;
let widest = if ribbon { Vec2::new(cx.tokens.size.length.short, widest.y) } else { widest };
let name = cx.words::<FontPickerWords>().list.clone();
Vec2::new(widest.x + reserve(cx.style, &[], &Self::trailing(name)), widest.y)
let note = self.missing_note(current, &cx.words::<MissingFontsWords>());
Vec2::new(widest.x + reserve(cx.style, &[], &Self::trailing(name, note.is_some())), widest.y)
}
fn parts(&mut self, _: Rect, cx: &mut PartsCx<'_, Self>) {
let name = cx.words::<FontPickerWords>().list.clone();
let trailing = Self::trailing(name);
let family = cx.value().cloned().unwrap_or_default();
let note = self.missing_note(&family, &cx.words::<MissingFontsWords>());
let trailing = Self::trailing(name, note.is_some());
let placed = place(cx.content_rect, cx.style, &[], &trailing, cx.flow.is_rtl());
if let Some(at) = placed.trailing.first() {
if let (Some(note), Some(at)) = (note, placed.trailing.first()) {
cx.part(WARNING, *at).tooltip(note);
}
if let Some(at) = placed.trailing.last() {
cx.part(CHEVRON, *at)
.sense(Sense::CLICK | Sense::KEEP_FOCUS)
.priority(HitPriority::new(HitLevel::Handle, 0))
@@ -537,7 +632,6 @@ impl Component for FontPicker<'_> {
.toggles(POPUP);
}
let codec = self.codec(&cx.env);
let family = cx.value().cloned().unwrap_or_default();
let mut options = TextOptions::new();
options.select_on_focus = true;
cx.text(text_key(), placed.text, &codec, &family, &options);
@@ -603,6 +697,13 @@ impl Component for FontPicker<'_> {
fn paint(&mut self, ui: &mut PaintUi<'_>, cx: &Cx<'_, Self>) {
let name = cx.words::<FontPickerWords>().list.clone();
let family = cx.value().cloned().unwrap_or_default();
let missing = self.missing_note(&family, &cx.words::<MissingFontsWords>()).is_some();
let trailing = Self::trailing(name.clone(), missing);
let placed = place(cx.content_rect, cx.style, &[], &trailing, cx.env.direction().is_rtl());
if let (true, Some(at)) = (missing, placed.trailing.first()) {
ui.draw().icon(*at, &IconSpec::svg(IconId::new(WARNING_ICON)));
}
ui.face(CHEVRON, IconButton::new(IconId::new(CHEVRON_ICON)).label(name));
}
@@ -620,6 +721,6 @@ impl Component for FontPicker<'_> {
settings.note_recent(family);
write(&mut bind, &mut cx, settings, "Recent font");
}
FontPickerOutput { edit, picked, preview: self.preview, picked_style: self.picked_style, rested: self.rested }
FontPickerOutput { edit, picked, preview: self.preview, picked_style: self.picked_style, rested: self.rested, action: self.action }
}
}
+69 -19
View File
@@ -24,8 +24,8 @@ use egui::Rect;
use super::rank::{Infos, Language, Listing, list, shown_name};
use super::{
FamilyRow, FontClass, FontFilters, FontFormat, FontPicker, FontPickerSettings, FontPickerWords, POPUP, STAR, Typing, infos, read, ui_language,
write,
FamilyRow, FontClass, FontFilters, FontFormat, FontPicker, FontPickerKind, FontPickerSettings, FontPickerWords, POPUP, STAR, Typing, infos, read,
ui_language, write,
};
use crate::panel::faces::{Owner, Shown, paint_sample, shown};
use craft_ui::style::DataColor;
@@ -37,12 +37,29 @@ const SAMPLE_ASPECT: (u16, u16) = (4, 1);
/// The banner's sample is this many times as wide as high.
const BANNER_ASPECT: (u16, u16) = (12, 1);
/// One position of the list: a family, one style of an open family, or the gap between the recents and the other
/// families.
/// The headings of the `Plain` list.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
enum Heading {
Recent,
All,
}
/// One position of the list: a family, one style of an open family, the gap between the recents and the other
/// families, a heading of the `Plain` list, or one of the host's action rows.
enum Slot {
Family { row: FamilyRow, open: bool },
Style { family: String, style: String },
Gap,
Heading(Heading),
Action(usize),
}
/// What shapes the slots besides the rows.
struct Layout {
/// Headings over the recents and the families, and the action rows after them: the `Plain` list with nothing typed.
sections: bool,
/// How many action rows follow the families.
actions: usize,
}
/// What names a slot across passes. A family opening shifts the positions after it, so the list keys its rows by what
@@ -50,6 +67,8 @@ enum Slot {
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
enum SlotKey {
Gap,
Heading(Heading),
Action(usize),
Family { family: String, recent: bool },
Style { family: String, style: String },
}
@@ -60,6 +79,8 @@ impl Slot {
Slot::Family { row, .. } => SlotKey::Family { family: row.family.clone(), recent: row.recent },
Slot::Style { family, style } => SlotKey::Style { family: family.clone(), style: style.clone() },
Slot::Gap => SlotKey::Gap,
Slot::Heading(heading) => SlotKey::Heading(*heading),
Slot::Action(at) => SlotKey::Action(*at),
}
}
@@ -68,7 +89,7 @@ impl Slot {
match self {
Slot::Family { row, .. } => Some(&row.family),
Slot::Style { family, .. } => Some(family),
Slot::Gap => None,
Slot::Gap | Slot::Heading(_) | Slot::Action(_) => None,
}
}
@@ -77,7 +98,7 @@ impl Slot {
match self {
Slot::Family { row, .. } => Some((&row.family, None)),
Slot::Style { family, style } => Some((family, Some(style))),
Slot::Gap => None,
Slot::Gap | Slot::Heading(_) | Slot::Action(_) => None,
}
}
}
@@ -116,26 +137,35 @@ impl DisplayOrder<SlotKey> for Slots<'_> {
}
fn is_section(&self, at: usize) -> bool {
matches!(self.0[at], Slot::Gap)
matches!(self.0[at], Slot::Gap | Slot::Heading(_))
}
fn text(&self, at: usize) -> Option<Cow<'_, str>> {
match &self.0[at] {
Slot::Family { row, .. } => Some(Cow::Borrowed(row.shown.as_str())),
Slot::Style { style, .. } => Some(Cow::Borrowed(style.as_str())),
Slot::Gap => None,
Slot::Gap | Slot::Heading(_) | Slot::Action(_) => None,
}
}
}
impl ItemSource<SlotKey> for Slots<'_> {}
/// The rows with a gap after the recents and the styles of each expanded family under its row.
fn slots(catalog: &Catalog, rows: Vec<FamilyRow>, expanded: &[String]) -> Vec<Slot> {
/// The rows with a gap after the recents (headings over the recents and the families under `layout.sections`), the
/// styles of each expanded family under its row, and the action rows at the end.
fn slots(catalog: &Catalog, rows: Vec<FamilyRow>, expanded: &[String], layout: &Layout) -> Vec<Slot> {
let recents = rows.iter().take_while(|row| row.recent).count();
let mut slots: Vec<Slot> = Vec::with_capacity(rows.len() + 1);
let mut slots: Vec<Slot> = Vec::with_capacity(rows.len() + 2);
for (at, row) in rows.into_iter().enumerate() {
if at == recents && recents > 0 {
if layout.sections {
if at == 0 && recents > 0 {
slots.push(Slot::Heading(Heading::Recent));
}
if at == recents {
slots.push(Slot::Heading(Heading::All));
}
} else if at == recents && recents > 0 {
slots.push(Slot::Gap);
}
let open = !row.recent && row.styles > 1 && expanded.contains(&row.family);
@@ -151,6 +181,9 @@ fn slots(catalog: &Catalog, rows: Vec<FamilyRow>, expanded: &[String]) -> Vec<Sl
}
}
}
if layout.sections {
slots.extend((0..layout.actions).map(Slot::Action));
}
slots
}
@@ -298,7 +331,10 @@ pub(super) fn popup<'a>(picker: &mut FontPicker<'a>, ui: &mut OverlayUi<'_>, cx:
let mut hide_classes = cx.memory::<Typing>().hide_classes;
let family = cx.value().cloned().unwrap_or_default();
let settings = read(&mut picker.settings, cx);
let mut filters = read(&mut picker.filters, cx);
let plain = picker.kind == FontPickerKind::Plain;
// The plain list has no filters: neither the bar nor the column shows, and nothing narrows the list.
let mut filters = read(&mut picker.filters, cx).filter(|_| !plain);
let actions = picker.actions;
let has_filters = filters.is_some();
let narrowing = filters.clone().unwrap_or_default();
let catalog = picker.catalog;
@@ -314,7 +350,8 @@ pub(super) fn popup<'a>(picker: &mut FontPicker<'a>, ui: &mut OverlayUi<'_>, cx:
served: picker.served,
};
let (found, comparable) = list(catalog, &infos, &listing, &Language { folder: &folder, collator: &collator }, true);
let slots = slots(catalog, found, &expanded);
let layout = Layout { sections: plain && query.trim().is_empty(), actions: actions.len() };
let slots = slots(catalog, found, &expanded, &layout);
let current = slots.iter().position(|slot| matches!(slot, Slot::Family { row, .. } if row.family == family));
let size = settings.as_ref().map_or(ThumbSize::None, |s| s.preview.thumb());
let favorites_empty = settings.as_ref().is_none_or(|s| s.favorites.is_empty());
@@ -365,21 +402,29 @@ pub(super) fn popup<'a>(picker: &mut FontPicker<'a>, ui: &mut OverlayUi<'_>, cx:
.rows_stamp(stamp.finish())
.show_items(ui, &source, &mut |_, item| match &slots[item.at] {
Slot::Gap => ListRow::spacer(),
Slot::Heading(Heading::Recent) => ListRow::new(words.recently_used.clone()).section_heading(),
Slot::Heading(Heading::All) => ListRow::new(words.all_fonts.clone()).section_heading(),
Slot::Action(at) => ListRow::new(actions[*at].clone()).option().depth(0),
Slot::Style { style, .. } => ListRow::new(style.clone()).option().depth(1),
Slot::Family { row, open } => {
let icon = if row.starred { "star_filled" } else { "star" };
let name = Label::from(words.favorite.fill(&[("row", row.shown.as_str())]));
let star = TrailingFace::Icon(IconSpec::svg(IconId::new(icon)));
let mut line =
ListRow::new(row.shown.clone()).option().depth(0).check(current == Some(item.at)).trailing_part(STAR, star, name);
let mut line = ListRow::new(row.shown.clone()).option().depth(0).check(current == Some(item.at));
if !plain {
line = line.trailing_part(STAR, star, name);
}
if source.has_children(item.at) {
line = line.group(*open);
}
if let Some(class) = row.class {
if let Some(class) = row.class.filter(|_| !plain) {
line = line.trailing_named(class_mark(class, &words), class_label(class, &words));
}
line = match row.format {
Some(format) => line.trailing_named(Label::from(format.badge().to_owned()), format_label(format, &words)),
Some(format) if !plain => {
line.trailing_named(Label::from(format.badge().to_owned()), format_label(format, &words))
}
Some(_) => line,
None => line.trailing_named(words.served.clone(), words.served.clone()),
};
if size == ThumbSize::None {
@@ -463,7 +508,12 @@ pub(super) fn popup<'a>(picker: &mut FontPicker<'a>, ui: &mut OverlayUi<'_>, cx:
{
write(&mut picker.filters, cx, filters, "Font filters");
}
if let Some((family, style)) = picked.and_then(|key| slot_of(&slots, &key)).and_then(Slot::pick) {
let chosen = picked.and_then(|key| slot_of(&slots, &key));
if let Some(Slot::Action(at)) = chosen {
picker.action = Some(*at);
end_preview(picker, cx);
popup.close(cx);
} else if let Some((family, style)) = chosen.and_then(Slot::pick) {
picker.picked = Some(family.to_owned());
picker.picked_style = style.map(str::to_owned);
end_preview(picker, cx);
+78 -10
View File
@@ -5,12 +5,12 @@ use std::sync::{Arc, OnceLock};
use craft_behavior::Mixed;
use craft_ui::contract::{Bind, Show as _, Validity};
use craft_ui::runtime::env::Message;
use craft_ui::runtime::env::{Label, Message};
use craft_ui::testing::focus::AccessActionKind;
use craft_ui::testing::{Drive, Fixture, StoryData, StoryOutput, story};
use egui::{Key, Modifiers, Ui};
use super::{FontFilters, FontPicker, FontPickerSettings};
use super::{FontFilters, FontPicker, FontPickerKind, FontPickerSettings, MissingAdvice};
use crate::Catalog;
use crate::craft_font_catalog::{Limits, Source};
use crate::panel::fixtures::story_catalog;
@@ -55,6 +55,10 @@ fn styled_catalog() -> Arc<Catalog> {
struct Extras<'a> {
served: &'a [String],
banner: Option<&'a str>,
kind: FontPickerKind,
actions: &'a [Label],
shown_as: Option<&'a str>,
advice: MissingAdvice,
}
fn show_with(ui: &mut Ui, data: &mut StoryData, init: Demo, catalog: &Arc<Catalog>, extras: &Extras<'_>) -> StoryOutput {
@@ -62,7 +66,13 @@ fn show_with(ui: &mut Ui, data: &mut StoryData, init: Demo, catalog: &Arc<Catalo
let mut picker = FontPicker::new("Font family", Bind::bound(family), catalog)
.settings(Bind::bound(settings))
.filters(Bind::bound(filters))
.served(extras.served);
.served(extras.served)
.kind(extras.kind)
.actions(extras.actions)
.advice(extras.advice);
if let Some(face) = extras.shown_as {
picker = picker.shown_as(face);
}
if let Some(text) = extras.banner {
picker = picker.preview_text(text);
}
@@ -78,6 +88,21 @@ fn font_picker(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
show_picker(ui, data, demo("Ubuntu", FontPickerSettings::default(), FontFilters::default()))
}
/// The plain font box in a ribbon group's place (`ControlPlace::Ribbon`): held at the small field length whichever
/// family it shows, as a word processor's ribbon font box is; a row short of room narrows it no further than a name
/// field the short field length wide and its arrow.
#[story(FontPicker<'static>, covers = [], title = "In a ribbon")]
fn font_picker_in_ribbon(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let extras = Extras { kind: FontPickerKind::Plain, ..Extras::default() };
craft_ui::runtime::env::with_env(
ui,
|overrides| {
overrides.values.set(craft_ui::buttons::ControlPlace::Ribbon);
},
|ui| show_with(ui, data, demo("Ubuntu", FontPickerSettings::default(), FontFilters::default()), &catalog(), &extras),
)
}
/// Focuses the field and types the start of a name, which opens the list on the matches.
fn type_query(fixture: &mut Fixture) {
fixture.key(Key::Tab, Modifiers::NONE);
@@ -98,7 +123,7 @@ fn open_list(fixture: &mut Fixture) {
fixture.settle();
}
#[story(FontPicker<'static>, covers = [], drive = Drive::Custom(open_list))]
#[story(FontPicker<'static>, covers = [Open], drive = Drive::Custom(open_list))]
fn font_picker_open_with_filters(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let settings = FontPickerSettings { favorites: vec!["Hack".to_owned()], ..FontPickerSettings::default() };
show_picker(ui, data, demo("Hack", settings, FontFilters { favorites: true, ..FontFilters::default() }))
@@ -114,32 +139,75 @@ fn expand_inter(fixture: &mut Fixture) {
}
/// A family of two styles with its style rows showing.
#[story(FontPicker<'static>, covers = [], drive = Drive::Custom(expand_inter))]
#[story(FontPicker<'static>, covers = [Open], drive = Drive::Custom(expand_inter))]
fn font_picker_expanded_styles(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
show_with(ui, data, demo("Inter", FontPickerSettings::default(), FontFilters::default()), &styled_catalog(), &Extras::default())
}
/// Families the host can fetch, listed with the "Not installed" mark.
#[story(FontPicker<'static>, covers = [], drive = Drive::Custom(open_list))]
#[story(FontPicker<'static>, covers = [Open], drive = Drive::Custom(open_list))]
fn font_picker_served(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let served = ["Gotham".to_owned(), "Proxima Nova".to_owned()];
show_with(ui, data, demo("Hack", FontPickerSettings::default(), FontFilters::default()), &catalog(), &Extras { served: &served, banner: None })
show_with(
ui,
data,
demo("Hack", FontPickerSettings::default(), FontFilters::default()),
&catalog(),
&Extras { served: &served, ..Extras::default() },
)
}
/// The preview banner above the filters.
#[story(FontPicker<'static>, covers = [], drive = Drive::Custom(open_list))]
#[story(FontPicker<'static>, covers = [Open], drive = Drive::Custom(open_list))]
fn font_picker_banner_text(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let extras = Extras { served: &[], banner: Some("The quick brown fox") };
let extras = Extras { banner: Some("The quick brown fox"), ..Extras::default() };
show_with(ui, data, demo("Ubuntu", FontPickerSettings::default(), FontFilters::default()), &catalog(), &extras)
}
/// Large samples: a face with Arabic letters gets the second sample after the Latin one.
#[story(FontPicker<'static>, covers = [], drive = Drive::Custom(open_list))]
#[story(FontPicker<'static>, covers = [Open], drive = Drive::Custom(open_list))]
fn font_picker_arabic_sample(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let settings = FontPickerSettings { preview: crate::picker::FontPreviewSize::Large, ..FontPickerSettings::default() };
show_with(ui, data, demo("Inter", settings, FontFilters::default()), &styled_catalog(), &Extras::default())
}
/// Settings whose recents are the families `recent`.
fn recents(recent: &[&str]) -> FontPickerSettings {
FontPickerSettings { recent: recent.iter().map(|family| (*family).to_owned()).collect(), ..FontPickerSettings::default() }
}
/// Word's plain font box, closed.
#[story(FontPicker<'static>, covers = [], drive = Drive::Never)]
fn font_picker_plain(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let extras = Extras { kind: FontPickerKind::Plain, ..Extras::default() };
show_with(ui, data, demo("Ubuntu", recents(&["Hack"]), FontFilters::default()), &catalog(), &extras)
}
/// The plain list open: recent fonts, all fonts and an action row.
#[story(FontPicker<'static>, covers = [Open], drive = Drive::Custom(open_list))]
fn font_picker_plain_open_with_recents(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let actions = [Label::from("Add Font…")];
let extras = Extras { kind: FontPickerKind::Plain, actions: &actions, ..Extras::default() };
show_with(ui, data, demo("Ubuntu", recents(&["Hack"]), FontFilters::default()), &catalog(), &extras)
}
/// The plain list on a typed query: matches only, no headings and no action rows.
#[story(FontPicker<'static>, covers = [Open], drive = Drive::Custom(type_query))]
fn font_picker_plain_typed(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let actions = [Label::from("Add Font…")];
let extras = Extras { kind: FontPickerKind::Plain, actions: &actions, ..Extras::default() };
show_with(ui, data, demo("Ubuntu", recents(&["Ubuntu"]), FontFilters::default()), &catalog(), &extras)
}
/// A font the catalog lacks, shown in another face: the field carries the missing mark and its note.
#[story(FontPicker<'static>, covers = [], drive = Drive::Never)]
fn font_picker_plain_missing(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let actions = [Label::from("Add Font…")];
let extras =
Extras { kind: FontPickerKind::Plain, actions: &actions, shown_as: Some("Inter"), advice: MissingAdvice::AddFont, ..Extras::default() };
show_with(ui, data, demo("Gotham", FontPickerSettings::default(), FontFilters::default()), &catalog(), &extras)
}
/// The family of a selection whose members differ.
#[story(FontPicker<'static>, covers = [Mixed], drive = Drive::Never)]
fn font_picker_mixed(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
+2
View File
@@ -6,10 +6,12 @@
use std::collections::HashMap;
use std::path::{Path, PathBuf};
#[cfg(not(target_arch = "wasm32"))]
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Condvar, Mutex};
#[cfg(not(target_arch = "wasm32"))]
use craft_font_catalog::Catalog;
pub use craft_font_store::UserSource;
#[cfg(not(target_arch = "wasm32"))]
+176 -2
View File
@@ -5,12 +5,19 @@ use std::cell::RefCell;
use std::rc::Rc;
use std::sync::Arc;
use craft_behavior::Preview;
use craft_behavior::{PartKey, Preview};
use craft_font_manager::craft_font_catalog::{Limits, Os, Source};
use craft_font_manager::picker::{FontFilters, FontPicker, FontPickerSettings, SIMILAR_COUNT, family_rows};
use craft_font_manager::missing::MissingFontsWords;
use craft_font_manager::picker::{
FontFilters, FontPicker, FontPickerKind, FontPickerSettings, FontPickerWords, MissingAdvice, SIMILAR_COUNT, family_rows,
};
use craft_font_manager::{Catalog, FontEnv};
use craft_ui::buttons::ControlPlace;
use craft_ui::contract::tooltip::DELAY;
use craft_ui::contract::{Bind, Show as _};
use craft_ui::runtime::env::{Label, with_env};
use craft_ui::testing::focus::AccessActionKind;
use craft_ui::testing::pointer::moved;
use craft_ui::testing::{Fixture, Room, trial};
use egui::{Event, Key, Modifiers};
@@ -33,6 +40,9 @@ struct Seen {
rested: Vec<String>,
/// The family the open list proposes as a live preview, as the last pass reported it.
preview: Option<String>,
actions: Vec<usize>,
/// The id of the shown picker, as the last pass reported it.
id: Option<egui::Id>,
}
fn rig(catalog: Arc<Catalog>, served: Vec<String>) -> (Fixture, Rc<RefCell<Seen>>) {
@@ -186,3 +196,167 @@ fn a_click_on_the_focused_closed_field_selects_the_name_so_typing_replaces_it()
assert_eq!(seen.borrow().picks.last().map(|(picked, _)| picked.as_str()), Some(family), "the typed name is picked");
}
}
/// A `Plain` picker over `family` with `recent` families, `actions` rows and the face `shown_as`.
fn plain_rig(
catalog: Arc<Catalog>,
family: &str,
recent: &[&str],
actions: Vec<Label>,
shown_as: Option<&'static str>,
) -> (Fixture, Rc<RefCell<Seen>>) {
let seen = Rc::new(RefCell::new(Seen { family: family.to_owned(), ..Seen::default() }));
let shown = Rc::clone(&seen);
let mut settings = FontPickerSettings::default();
settings.recent = recent.iter().map(|family| (*family).to_owned()).collect();
let mut fx = Fixture::new(move |ui| {
let mut seen = shown.borrow_mut();
let mut picker = FontPicker::new("Font family", Bind::bound(&mut seen.family), &catalog)
.settings(Bind::bound(&mut settings))
.kind(FontPickerKind::Plain)
.actions(&actions)
.advice(if actions.is_empty() { MissingAdvice::None } else { MissingAdvice::AddFont });
if let Some(face) = shown_as {
picker = picker.shown_as(face);
}
let out = picker.show(ui);
seen.id = Some(out.edit.response.id);
if let Some(family) = out.picked {
seen.picks.push((family, out.picked_style));
}
seen.actions.extend(out.action);
});
fx.in_room(Room::Window);
fx.settle();
(fx, seen)
}
#[trial]
fn a_plain_box_commits_an_unknown_typed_name_lists_recents_first_and_again_after_a_cleared_query() {
let catalog = catalog_of(&[INTER_REGULAR, epaint_default_fonts::HACK_REGULAR]);
let (mut fx, seen) = plain_rig(catalog, "Inter", &["Hack"], vec![], None);
let words = FontPickerWords::default();
let (recently, all) = (words.recently_used.as_str(), words.all_fonts.as_str());
open(&mut fx);
assert!(present(&fx, recently), "the recents have their heading");
assert!(present(&fx, all), "the families have theirs");
fx.key(Key::Escape, Modifiers::NONE);
fx.settle();
let field = fx.by_label("Font family").expect("the family field");
fx.click(&field);
fx.settle();
fx.type_text("x");
fx.settle();
assert!(!present(&fx, recently), "a query lists its matches only");
fx.key(Key::Backspace, Modifiers::NONE);
fx.settle();
assert!(present(&fx, recently), "a cleared query lists the recents again");
fx.type_text("Zapfino");
fx.settle();
fx.key(Key::Enter, Modifiers::NONE);
fx.settle();
assert_eq!(seen.borrow().family, "Zapfino", "a name that is no family is applied as typed");
assert_eq!(seen.borrow().picks.last().map(|(picked, _)| picked.as_str()), Some("Zapfino"));
}
#[trial]
fn an_action_row_is_reported_not_committed_and_a_missing_family_shows_the_note_naming_the_face() {
let words = MissingFontsWords::default();
let note = format!("{} {}", words.shown_as.fill(&[("family", "Gotham"), ("face", "Inter")]), words.add_font.as_str());
let note = note.as_str();
let (mut fx, seen) = plain_rig(catalog_of(&[INTER_REGULAR]), "Gotham", &[], vec![Label::from("Add Font…")], Some("Inter"));
// The note is the tooltip of the field's warning mark, so it shows once the pointer rests on the mark.
let picker = seen.borrow().id.expect("the picker");
let mark = fx.part_rect(picker, PartKey::new("missing")).expect("the field carries a mark while the family is not installed");
assert!(!present(&fx, note), "the note waits for a rest on the mark");
fx.frame(vec![moved(mark.center())]);
fx.advance(DELAY);
fx.settle();
assert!(present(&fx, note), "a rest on the mark shows the note");
open(&mut fx);
let action = fx.by_label("Add Font…").expect("the action row");
fx.click(&action);
fx.settle();
assert_eq!(seen.borrow().actions, [0], "the action is reported by its index");
assert_eq!(seen.borrow().family, "Gotham", "an action leaves the family");
assert!(seen.borrow().picks.is_empty(), "and picks nothing");
let (fx, seen) = plain_rig(catalog_of(&[INTER_REGULAR]), "Inter", &[], vec![Label::from("Add Font…")], Some("Inter"));
let picker = seen.borrow().id.expect("the picker");
assert!(fx.part_rect(picker, PartKey::new("missing")).is_none(), "an installed family has no mark");
}
/// The width of a plain picker over `family`, in a ribbon group's place or not.
fn picker_width(family: &'static str, ribbon: bool) -> f32 {
let catalog = catalog_of(&[INTER_REGULAR]);
let mut fx = Fixture::new(move |ui| {
let mut family = family.to_owned();
let mut show = |ui: &mut egui::Ui| {
let _ = FontPicker::new("Font family", Bind::bound(&mut family), &catalog).kind(FontPickerKind::Plain).show(ui);
};
if ribbon {
with_env(
ui,
|overrides| {
overrides.values.set(ControlPlace::Ribbon);
},
show,
);
} else {
show(ui);
}
});
fx.in_room(Room::Window);
fx.settle();
fx.by_label("Font family").expect("the picker").rect.width()
}
/// In a ribbon the font box is held at the small field length, narrower than in a form, and keeps its width whichever
/// family it shows.
#[trial]
fn a_ribbons_font_box_is_short_and_keeps_its_width() {
let (ribbon, standard) = (picker_width("Inter", true), picker_width("Inter", false));
assert!(ribbon < standard - 0.5, "the ribbon's font box is narrower: {ribbon} against {standard}");
let length = craft_ui::testing::style::tokens(craft_theme::Mode::Light, craft_theme::Contrast::Standard).size.length.field.sm;
assert!((ribbon - length).abs() < 0.5, "the ribbon's font box is the small field length {length}: {ribbon}");
let long = picker_width("Source Sans Pro Semibold Condensed Extra", true);
assert!((long - ribbon).abs() < 0.5, "a long family name leaves its width: {long} against {ribbon}");
}
/// The width of a plain picker over "Inter" in a ribbon group's place, in a row beside a block that leaves it 60 pt of
/// the window, so the row shrinks it to its least.
fn squeezed_ribbon_picker_width() -> f32 {
use craft_ui::contract::ShowContainer as _;
let catalog = catalog_of(&[INTER_REGULAR]);
let mut fx = Fixture::new(move |ui| {
let mut family = "Inter".to_owned();
with_env(
ui,
|overrides| {
overrides.values.set(ControlPlace::Ribbon);
},
|ui| {
let rest = ui.available_width() - 60.0;
craft_ui::layout_components::Row::new().show(ui, |ui, _| {
let _ = FontPicker::new("Font family", Bind::bound(&mut family), &catalog).kind(FontPickerKind::Plain).show(ui);
craft_ui::testing::layout::Block::new(egui::Vec2::new(rest, 20.0)).show(ui);
});
},
);
});
fx.in_room(Room::Window);
fx.settle();
fx.by_label("Font family").expect("the picker").rect.width()
}
/// A ribbon row that lacks room narrows its font box no further than its least: a name field the short field length
/// (`size.length.short`) wide, about the old ribbon's font name, plus its menu arrow; never to an arrow alone.
#[trial]
fn a_squeezed_ribbon_font_box_keeps_a_short_fields_name() {
let squeezed = squeezed_ribbon_picker_width();
let short = craft_ui::testing::style::tokens(craft_theme::Mode::Light, craft_theme::Contrast::Standard).size.length.short;
assert!(squeezed > short, "the squeezed font box keeps a name field {short} wide and its arrow: {squeezed}");
assert!(squeezed <= picker_width("Inter", true) + 0.5, "and is no wider than where the room allows");
}
+17 -1
View File
@@ -1,17 +1,33 @@
[package]
name = "craft-gpu"
description = "Provider-neutral GPU traits, GpuJob envelope, and registry (no vendor IO)"
description = "Provider-neutral GPU traits, GpuJob envelope, and registry (no vendor IO); with `startup`, eframe's wgpu start-up choices per platform"
version.workspace = true
edition.workspace = true
license.workspace = true
rust-version.workspace = true
repository.workspace = true
[lints]
workspace = true
[features]
default = []
# GPU start-up choices for apps on eframe's wgpu backend (`configure`): backends, power preference, DX12 compiler and
# the Linux DRM device pick. Off by default, so the provider-neutral traits pull in no vendor crate.
startup = ["dep:egui-wgpu", "dep:log", "dep:pollster"]
[dependencies]
serde = { workspace = true }
thiserror = { workspace = true }
# A `[patch.crates-io]` row at the framework root points egui-wgpu at the pinned egui fork; it is not a workspace dependency.
# Its `wgpu` re-export is the wgpu eframe draws with.
egui-wgpu = { version = "0.37", default-features = false, optional = true }
log = { workspace = true, optional = true }
[target.'cfg(windows)'.dependencies]
# Waits for the DirectX 12 adapter list of the start-up probe.
pollster = { version = "1", optional = true }
[dev-dependencies]
serde_json = { workspace = true }
tempfile = "3"
+30
View File
@@ -0,0 +1,30 @@
//! The GPU start-up choices, one module per platform.
//!
//! The Windows and Linux choices are compiled under tests on every platform too, so their trials run on every CI
//! host; the parts that talk to the system stay gated to their platform. The macOS module is only wiring.
#[cfg(any(target_os = "linux", test))]
pub(crate) mod drm;
#[cfg(any(target_os = "linux", test))]
pub(crate) mod linux;
#[cfg(target_os = "macos")]
pub(crate) mod macos;
#[cfg(any(windows, test))]
pub(crate) mod windows;
/// Sets the GPU start-up choices of the running platform on `setup`: the backends, the power preference, the DX12
/// shader compiler and, on Linux, the DRM device to render on. Call it before eframe creates the wgpu instance.
pub fn configure(setup: &mut egui_wgpu::WgpuSetupCreateNew) {
#[cfg(windows)]
windows::configure(setup);
#[cfg(target_os = "macos")]
macos::configure(setup);
// egui-wgpu draws on the discrete GPU by default; draw on the GPU that drives the screen instead.
#[cfg(target_os = "linux")]
{
setup.native_adapter_selector = Some(std::sync::Arc::new(linux::pick_adapter));
}
// Other platforms keep egui-wgpu's own choices.
#[cfg(not(any(windows, target_os = "macos", target_os = "linux")))]
let _ = setup;
}
+108
View File
@@ -0,0 +1,108 @@
//! Which graphics cards drive displays, as the system reports them (Linux: `/sys/class/drm`).
//!
//! A window drawn on one card and shown on a screen attached to another is copied across on every
//! frame, so the app draws on the card that drives the screen (see the `linux` module).
use std::io::Read as _;
use std::path::Path;
/// A graphics card and the displays connected to it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct DisplayCard {
/// PCI vendor id: 0x1002 AMD, 0x10de NVIDIA, 0x8086 Intel.
pub vendor: u32,
/// PCI device id.
pub device: u32,
/// PCI address in the form `0000:05:00.0`, lowercase; empty when the system doesn't give one.
pub pci_slot: String,
/// Connected displays that are switched on, of any kind, built-in panel included.
pub displays: u32,
/// A connected, switched-on built-in panel (eDP, LVDS or DSI): this card drives a laptop's
/// own screen.
pub built_in_panel: bool,
}
/// Connector kinds that are a computer's own screen rather than a monitor plugged into it.
const BUILT_IN_PANELS: &[&str] = &["eDP", "LVDS", "DSI"];
/// At most this many entries are read from the DRM folder.
pub(crate) const MAX_ENTRIES: usize = 512;
/// At most this many bytes are read from one sysfs file.
pub(crate) const MAX_FILE: u64 = 4096;
/// The graphics cards on this computer and what's connected to them. Empty where the system
/// doesn't say (a sandbox without `/sys`).
#[cfg(target_os = "linux")]
pub(crate) fn display_cards() -> Vec<DisplayCard> {
display_cards_in(Path::new("/sys/class/drm"))
}
/// The display cards read from a DRM folder laid out like `/sys/class/drm`: a `cardN` entry per
/// card, with the card's PCI ids in `cardN/device/uevent`, and a `cardN-<kind>-<n>` entry per
/// connector, with `connected` or `disconnected` in its `status` and, where the kernel gives it,
/// `enabled` or `disabled` in its `enabled`. Cards without PCI ids (a firmware framebuffer) are
/// left out.
pub(crate) fn display_cards_in(drm: &Path) -> Vec<DisplayCard> {
let Ok(entries) = std::fs::read_dir(drm) else {
return Vec::new();
};
let mut names: Vec<String> = entries.take(MAX_ENTRIES).filter_map(|e| e.ok()?.file_name().into_string().ok()).collect();
names.sort();
let cards = names.iter().filter(|n| is_card(n));
cards
.filter_map(|card| {
let uevent = read_small(&drm.join(card).join("device").join("uevent"))?;
let (vendor, device) = pci_ids(&uevent)?;
let pci_slot = uevent_value(&uevent, "PCI_SLOT_NAME").unwrap_or_default().to_ascii_lowercase();
let prefix = format!("{card}-");
let mut out = DisplayCard { vendor, device, pci_slot, displays: 0, built_in_panel: false };
for connector in names.iter().filter_map(|n| n.strip_prefix(&prefix)) {
let dir = drm.join(format!("{prefix}{connector}"));
let status = read_small(&dir.join("status")).unwrap_or_default();
// A panel can be connected but switched off (a closed lid with a monitor in use):
// `enabled` then reads `disabled`, and it drives nothing. No `enabled`: it counts.
let enabled = read_small(&dir.join("enabled")).unwrap_or_default();
if status.trim() != "connected" || enabled.trim() == "disabled" {
continue;
}
out.displays = out.displays.saturating_add(1);
if BUILT_IN_PANELS.contains(&connector_kind(connector)) {
out.built_in_panel = true;
}
}
Some(out)
})
.collect()
}
/// `card0`, `card12`: a card, not a connector (`card0-eDP-1`) or a render node.
pub(crate) fn is_card(name: &str) -> bool {
name.strip_prefix("card").is_some_and(|n| !n.is_empty() && n.bytes().all(|b| b.is_ascii_digit()))
}
/// `eDP-1` → `eDP`, `HDMI-A-1` → `HDMI-A`: the connector's name without its number.
pub(crate) fn connector_kind(connector: &str) -> &str {
match connector.rsplit_once('-') {
Some((kind, n)) if !n.is_empty() && n.bytes().all(|b| b.is_ascii_digit()) => kind,
_ => connector,
}
}
/// `PCI_ID=1002:1638` → (0x1002, 0x1638).
pub(crate) fn pci_ids(uevent: &str) -> Option<(u32, u32)> {
let (vendor, device) = uevent_value(uevent, "PCI_ID")?.split_once(':')?;
Some((u32::from_str_radix(vendor.trim(), 16).ok()?, u32::from_str_radix(device.trim(), 16).ok()?))
}
/// The value of `key` in a `KEY=value` uevent file.
pub(crate) fn uevent_value<'a>(uevent: &'a str, key: &str) -> Option<&'a str> {
uevent.lines().find_map(|l| l.strip_prefix(key)?.strip_prefix('=')).map(str::trim)
}
/// The first [`MAX_FILE`] bytes of a sysfs file as text; `None` when it can't be read.
pub(crate) fn read_small(path: &Path) -> Option<String> {
let mut text = String::new();
std::fs::File::open(path).ok()?.take(MAX_FILE).read_to_string(&mut text).ok()?;
Some(text)
}
+147
View File
@@ -0,0 +1,147 @@
//! Linux: draw on the GPU that drives the screen.
//!
//! egui-wgpu picks the discrete GPU by default (`PowerPreference::HighPerformance`). On a laptop
//! whose integrated GPU drives the panel, every frame drawn on the discrete one is copied across
//! to it, and the discrete GPU leaves its idle state whenever the window redraws: on an Intel HD
//! 530 + NVIDIA Quadro M4000M laptop, from 7 W at P8 to over 20 W at P0/P1. Forcing the integrated
//! GPU instead breaks desktops whose screen is on the discrete card (storytold/pdfcraft#96), and a
//! desktop with a monitor on each card needs the discrete one (storytold/pdfcraft#445). So the
//! choice follows the connected displays, as in craft-anything (storytold/craft-anything#571):
//!
//! 1. `WGPU_ADAPTER_NAME` (part of the adapter's name) or `WGPU_POWER_PREF` (`high`, `low`,
//! `none`), when set, decide;
//! 2. a connected built-in panel: the GPU behind it;
//! 3. displays on only one GPU: that GPU;
//! 4. otherwise (displays on several GPUs, or nothing readable): the discrete GPU, as egui-wgpu does.
use super::drm::DisplayCard;
use egui_wgpu::wgpu::{DeviceType, PowerPreference};
/// What we know of one adapter wgpu offers.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct Candidate {
pub name: String,
pub vendor: u32,
pub device: u32,
/// `0000:05:00.0`, lowercase; empty when the driver doesn't say (always, under GL).
pub pci_slot: String,
pub device_type: DeviceType,
pub gl: bool,
}
/// What the person asked for through wgpu's environment variables.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub(crate) struct Asked {
pub adapter_name: Option<String>,
pub power: Option<PowerPreference>,
}
/// Why an adapter was chosen, for the log.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Why {
AskedByName,
AskedPower,
BuiltInPanel,
OnlyGpuWithDisplays,
Fallback,
}
/// The index of the adapter to draw with, and why; `None` when there is none.
pub(crate) fn choose(candidates: &[Candidate], cards: &[DisplayCard], asked: &Asked) -> Option<(usize, Why)> {
if let Some(want) = asked.adapter_name.as_deref().map(str::to_lowercase).filter(|w| !w.is_empty()) {
// As wgpu's own `WGPU_ADAPTER_NAME`: part of the name, any case. No match: the usual choice.
if let Some(i) = candidates.iter().position(|c| c.name.to_lowercase().contains(&want)) {
return Some((i, Why::AskedByName));
}
log::warn!("WGPU_ADAPTER_NAME={want}: no graphics adapter has that in its name");
}
if let Some(power) = asked.power {
return by_kind(candidates, power).map(|i| (i, Why::AskedPower));
}
let panels: Vec<&DisplayCard> = cards.iter().filter(|c| c.built_in_panel).collect();
let with_displays: Vec<&DisplayCard> = cards.iter().filter(|c| c.displays > 0).collect();
let target = if !panels.is_empty() {
Some((panels, Why::BuiltInPanel))
} else if with_displays.len() == 1 {
Some((with_displays, Why::OnlyGpuWithDisplays))
} else {
None
};
if let Some((wanted, why)) = target {
// Vulkan before GL for the same card; otherwise wgpu's order.
let found = candidates.iter().enumerate().filter(|(_, c)| wanted.iter().any(|card| drives(card, c, cards))).min_by_key(|(_, c)| c.gl);
if let Some((i, _)) = found {
return Some((i, why));
}
}
by_kind(candidates, PowerPreference::HighPerformance).map(|i| (i, Why::Fallback))
}
/// Whether `card` is the GPU behind `adapter`: by PCI address when the driver gives one, else by
/// PCI ids, which count only when no other card has the same ids (two cards of one model); GL
/// gives only a vendor, which counts only when no other card has that vendor.
fn drives(card: &DisplayCard, adapter: &Candidate, all: &[DisplayCard]) -> bool {
if !adapter.pci_slot.is_empty() && !card.pci_slot.is_empty() {
return adapter.pci_slot == card.pci_slot;
}
if adapter.device != 0 {
return adapter.vendor == card.vendor
&& adapter.device == card.device
&& all.iter().filter(|c| c.vendor == card.vendor && c.device == card.device).count() == 1;
}
adapter.vendor != 0 && adapter.vendor == card.vendor && all.iter().filter(|c| c.vendor == card.vendor).count() == 1
}
/// The first adapter in wgpu's own order for that power preference.
fn by_kind(candidates: &[Candidate], power: PowerPreference) -> Option<usize> {
let rank = |t: DeviceType| match (power, t) {
(PowerPreference::None, _) => 0,
(PowerPreference::LowPower, DeviceType::IntegratedGpu) | (PowerPreference::HighPerformance, DeviceType::DiscreteGpu) => 1,
(_, DeviceType::IntegratedGpu | DeviceType::DiscreteGpu) => 2,
(_, DeviceType::Other) => 3,
(_, DeviceType::VirtualGpu) => 4,
(_, DeviceType::Cpu) => 5,
};
candidates.iter().enumerate().min_by_key(|(_, c)| rank(c.device_type)).map(|(i, _)| i)
}
#[cfg(target_os = "linux")]
impl Candidate {
fn of(info: &egui_wgpu::wgpu::AdapterInfo) -> Self {
Candidate {
name: info.name.clone(),
vendor: info.vendor,
device: info.device,
pci_slot: info.device_pci_bus_id.to_ascii_lowercase(),
device_type: info.device_type,
gl: info.backend == egui_wgpu::wgpu::Backend::Gl,
}
}
}
#[cfg(target_os = "linux")]
impl Asked {
fn from_env() -> Self {
Asked { adapter_name: std::env::var("WGPU_ADAPTER_NAME").ok(), power: PowerPreference::from_env() }
}
}
/// The adapter that draws the window, among those that can draw to it: egui-wgpu's
/// `native_adapter_selector`.
#[cfg(target_os = "linux")]
pub(crate) fn pick_adapter(
adapters: &[egui_wgpu::wgpu::Adapter],
surface: Option<&egui_wgpu::wgpu::Surface<'_>>,
) -> Result<egui_wgpu::wgpu::Adapter, String> {
let usable: Vec<&egui_wgpu::wgpu::Adapter> = adapters.iter().filter(|a| surface.is_none_or(|s| a.is_surface_supported(s))).collect();
let candidates: Vec<Candidate> = usable.iter().map(|a| Candidate::of(&a.get_info())).collect();
let cards = super::drm::display_cards();
let picked = choose(&candidates, &cards, &Asked::from_env()).and_then(|(i, why)| Some((*usable.get(i)?, why)));
match picked {
Some((a, why)) => {
log::info!("drawing with {:?} ({why:?}); displays: {cards:?}", a.get_info());
Ok(a.clone())
}
None => Err(format!("None of the {} graphics adapters found can draw this window.", adapters.len())),
}
}
+38
View File
@@ -0,0 +1,38 @@
//! macOS: wgpu's indirect-call validation, left out on Intel Macs.
/// wgpu compiles its indirect-call validation compute shaders inside `request_device`. On old
/// Intel Macs (HD Graphics 5000 on Big Sur, #2652) Metal's Intel
/// compiler aborts on them, the device is lost and eframe exits before the window opens. Craft apps
/// issue no indirect draws or dispatches, so Intel Macs skip them; every other GPU keeps wgpu's
/// default. Same fix as PhotoCraft's storytold/PhotoCraft#3171.
///
/// `x86_64_build` is the build's architecture. An x86_64 build also runs on Apple silicon under Rosetta
/// (#5199), so it skips only when the machine itself (`apple_silicon_host`) isn't Apple silicon.
pub(crate) fn skips_indirect_validation(x86_64_build: bool, apple_silicon_host: bool) -> bool {
x86_64_build && !apple_silicon_host
}
/// Whether the machine is Apple silicon, also when this process is translated by Rosetta:
/// `hw.optional.arm64` describes the hardware, not the process. Assumes not (an Intel Mac) when
/// the system can't tell.
#[cfg(target_os = "macos")]
fn runs_on_apple_silicon() -> bool {
std::process::Command::new("/usr/sbin/sysctl")
.args(["-n", "hw.optional.arm64"])
.output()
.is_ok_and(|out| out.status.success() && out.stdout.trim_ascii() == b"1")
}
/// Leaves wgpu's indirect-call validation out of the instance eframe creates on an Intel Mac
/// ([`skips_indirect_validation`]). `WGPU_VALIDATION_INDIRECT_CALL=1` still turns it back on.
#[cfg(target_os = "macos")]
pub(crate) fn configure(setup: &mut egui_wgpu::WgpuSetupCreateNew) {
let x86_64_build = cfg!(target_arch = "x86_64");
// An arm64 build runs only on Apple silicon: only an x86_64 build asks the system.
let apple_silicon_host = !x86_64_build || runs_on_apple_silicon();
if !skips_indirect_validation(x86_64_build, apple_silicon_host) {
return;
}
let flags = &mut setup.instance_descriptor.flags;
*flags = flags.difference(egui_wgpu::wgpu::InstanceFlags::VALIDATION_INDIRECT_CALL).with_env();
}
+129
View File
@@ -0,0 +1,129 @@
//! Windows: the backends to initialize and the DirectX 12 shader compiler, applied before wgpu can initialize any
//! driver.
use egui_wgpu::wgpu::{Backends, DeviceType, Dx12Compiler};
/// What the start-up probe learned about one DirectX 12 adapter.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct Dx12Adapter {
/// `Cpu` is WARP (Microsoft's software rasteriser): it works, but every frame is drawn on the
/// processor, which makes the app lag on older machines (#316).
pub device_type: DeviceType,
/// Whether the adapter offers the limits eframe will ask for when it creates the device.
pub meets_limits: bool,
}
/// The backends to initialize on Windows.
///
/// An explicit `backend_override` (normally `Backends::from_env()`, i.e. `WGPU_BACKEND`) always
/// wins. Otherwise DirectX 12 only, as long as `dx12_graphics` is set and `dx12_adapters` (what a
/// DirectX 12-only probe found) contains a usable hardware GPU. Without one, OpenGL is the way to
/// the GPU: graphics chips whose driver has no DirectX 12 support (Intel 4th generation on Windows
/// 11, #316) still have an OpenGL driver, and GL can't reach the AMD driver crash described in
/// `configure`, because an AMD GPU with a driver shows up as a DirectX 12 adapter and
/// keeps us on DirectX 12. When DirectX 12 offers only WARP, it stays enabled next to GL as a last
/// resort for machines without an OpenGL driver either (virtual machines): wgpu prefers any GPU
/// over a software adapter, so it's only picked when GL has nothing better.
///
/// `dx12_graphics` is false on 32-bit Windows. wgpu creates the graphics pipeline through
/// `ID3D12Device2::CreatePipelineState`, and that stream is aligned to 8 bytes. The 32-bit runtime
/// expects pointer alignment (4), so creation returns `E_INVALIDARG` ("The parameter is incorrect")
/// and the process exits before the first frame. Compute pipelines use the older API and succeed,
/// which is why startup gets as far as the egui pipeline and then quits. OpenGL does not use that
/// stream.
pub(crate) fn choose_backends(backend_override: Option<Backends>, dx12_adapters: &[Dx12Adapter], dx12_graphics: bool) -> Backends {
if let Some(backends) = backend_override {
return backends;
}
if !dx12_graphics {
return Backends::GL;
}
let hardware = |a: &&Dx12Adapter| a.device_type != DeviceType::Cpu;
if dx12_adapters.iter().filter(hardware).any(|a| a.meets_limits) {
Backends::DX12
} else if !dx12_adapters.is_empty() && !dx12_adapters.iter().any(|a| hardware(&a)) {
Backends::DX12 | Backends::GL
} else {
// No DirectX 12 adapter at all, or only GPUs that can't run the app: GL alone, so a
// DirectX 12 GPU that would fail device creation isn't picked over the OpenGL one.
Backends::GL
}
}
/// The DirectX 12 shader compiler: FXC (`d3dcompiler_47.dll`, part of Windows) unless `env`
/// (normally `WGPU_DX12_COMPILER`, wgpu's own variable: `fxc`, `dxc`, `auto`…) names another.
///
/// #603: wgpu's default (`Auto`) uses DXC, loading whichever `dxcompiler.dll` the DLL search path
/// finds first. The app ships none, so that copy belongs to another program. Without a matching
/// `dxil.dll` beside it, DXC warns that the DXIL is unsigned; wgpu takes the warning for a compile
/// error, its own indirect-validation pipeline fails, the device is lost and eframe exits before
/// the first frame. FXC is always there and compiles everything egui's shaders need.
pub(crate) fn dx12_compiler(env: Option<&str>) -> Dx12Compiler {
let Some(value) = env else { return Dx12Compiler::Fxc };
value.parse().unwrap_or_else(|e| {
log::warn!("graphics: WGPU_DX12_COMPILER={value:?} ignored ({e}), using FXC");
Dx12Compiler::Fxc
})
}
/// Sets the DirectX 12 shader compiler ([`dx12_compiler`]) and the backends ([`choose_backends`]) on `setup`.
/// Without a `WGPU_BACKEND` override this first probes DirectX 12 with a short-lived instance of its own, which
/// is dropped before eframe creates the real one.
#[cfg(windows)]
pub(crate) fn configure(setup: &mut egui_wgpu::WgpuSetupCreateNew) {
// First, so the probe's instance doesn't load a stray `dxcompiler.dll` either.
let compiler = dx12_compiler(std::env::var("WGPU_DX12_COMPILER").ok().as_deref());
log::info!("graphics: DirectX 12 shader compiler {compiler:?}");
setup.instance_descriptor.backend_options.dx12.shader_compiler = compiler;
let backends = match Backends::from_env() {
Some(backends) => {
log::info!("graphics: WGPU_BACKEND override, backends {backends:?}");
backends
}
None => {
// 32-bit: skip the DirectX 12 probe. A capable GPU would be selected, then
// CreatePipelineState fails and the app exits with no window.
let dx12_graphics = cfg!(not(target_arch = "x86"));
let adapters = if dx12_graphics { probe_dx12(setup) } else { Vec::new() };
let backends = choose_backends(None, &adapters, dx12_graphics);
if dx12_graphics {
log::info!("graphics: {} DirectX 12 adapter(s) {adapters:?}, backends {backends:?}", adapters.len());
} else {
log::info!("graphics: 32-bit Windows uses OpenGL; DirectX 12 graphics pipeline creation fails");
}
backends
}
};
// eframe's default includes GL. Creating that backend can crash inside AMD's
// atio6axx.dll before adapter selection or any Rust error handling runs, so the
// window never appears. Choosing an adapter afterwards is too late: only leaving GL
// out of the instance avoids it. This matches the verified WGPU_BACKEND=dx12
// workaround without mutating process environment variables.
setup.instance_descriptor.backends = backends;
}
/// Lists the DirectX 12 adapters, checking each against the limits `setup`'s device descriptor
/// will require. Empty when this build has no DirectX 12 backend.
#[cfg(windows)]
fn probe_dx12(setup: &egui_wgpu::WgpuSetupCreateNew) -> Vec<Dx12Adapter> {
use egui_wgpu::wgpu::{Instance, InstanceDescriptor};
// `Instance::new` panics when the build has no backend for the platform.
if !Instance::enabled_backend_features().contains(Backends::DX12) {
return Vec::new();
}
let instance = Instance::new(InstanceDescriptor {
backends: Backends::DX12,
backend_options: setup.instance_descriptor.backend_options.clone(),
..InstanceDescriptor::new_without_display_handle()
});
pollster::block_on(instance.enumerate_adapters(Backends::DX12))
.iter()
.map(|adapter| {
let info = adapter.get_info();
let required = (setup.device_descriptor)(adapter).required_limits;
let meets_limits = required.check_limits(&adapter.limits());
log::info!("graphics: DirectX 12 adapter {:?} ({:?}, driver {:?}), limits ok: {meets_limits}", info.name, info.device_type, info.driver);
Dx12Adapter { device_type: info.device_type, meets_limits }
})
.collect()
}
+250
View File
@@ -0,0 +1,250 @@
//! Trials of the GPU start-up choices. Every platform's choice is pure, so all of them run on every host.
use crate::device::drm::{self, DisplayCard, display_cards_in};
use crate::device::linux::{Asked, Candidate, Why, choose};
use crate::device::windows::{Dx12Adapter, choose_backends, dx12_compiler};
use egui_wgpu::wgpu::{Backends, DeviceType, Dx12Compiler, PowerPreference};
use std::fs;
use std::path::Path;
const fn adapter(device_type: DeviceType, meets_limits: bool) -> Dx12Adapter {
Dx12Adapter { device_type, meets_limits }
}
/// #316: the backends Windows starts on. A wrong row loses the window on Intel 4th-generation and AMD machines.
#[test]
fn windows_backend_choice() {
let warp_only = [adapter(DeviceType::Cpu, true)];
let gpu = [adapter(DeviceType::IntegratedGpu, true)];
// `WGPU_BACKEND` wins over the 32-bit rule and over a usable GPU.
assert_eq!(choose_backends(Some(Backends::VULKAN), &gpu, false), Backends::VULKAN);
let weak_gpu = [adapter(DeviceType::IntegratedGpu, false), adapter(DeviceType::Cpu, true)];
let mixed = [adapter(DeviceType::Cpu, true), adapter(DeviceType::IntegratedGpu, false), adapter(DeviceType::DiscreteGpu, true)];
let rows: [(&str, &[Dx12Adapter], bool, Backends); 6] = [
("no DirectX 12 adapter: OpenGL", &[], true, Backends::GL),
("only WARP: OpenGL, WARP kept as a last resort", &warp_only, true, Backends::DX12 | Backends::GL),
("a GPU that can't create the device beside WARP: OpenGL alone", &weak_gpu, true, Backends::GL),
("a usable GPU beside WARP and a weaker GPU: DirectX 12 only", &mixed, true, Backends::DX12),
("a usable integrated GPU: DirectX 12 only, no OpenGL", &gpu, true, Backends::DX12),
("32-bit with a usable GPU: OpenGL", &gpu, false, Backends::GL),
];
for (case, adapters, dx12_graphics, want) in rows {
assert_eq!(choose_backends(None, adapters, dx12_graphics), want, "{case}");
}
}
/// #603: DirectX 12 shaders compile with FXC, never a `dxcompiler.dll` found on the search
/// path, unless `WGPU_DX12_COMPILER` asks for it.
#[test]
fn dx12_compiles_with_fxc_unless_asked() {
assert!(matches!(dx12_compiler(None), Dx12Compiler::Fxc));
assert!(matches!(dx12_compiler(Some("bogus")), Dx12Compiler::Fxc));
assert!(matches!(dx12_compiler(Some("dxc")), Dx12Compiler::DynamicDxc { .. }));
}
const AMD: (u32, u32, &str) = (0x1002, 0x1638, "0000:05:00.0");
const NVIDIA: (u32, u32, &str) = (0x10de, 0x25a2, "0000:01:00.0");
const INTEL: (u32, u32, &str) = (0x8086, 0xa780, "0000:00:02.0");
fn vulkan(name: &str, (vendor, device, slot): (u32, u32, &str), device_type: DeviceType) -> Candidate {
Candidate { name: name.into(), vendor, device, pci_slot: slot.into(), device_type, gl: false }
}
fn gl(name: &str, vendor: u32, device_type: DeviceType) -> Candidate {
Candidate { name: name.into(), vendor, device: 0, pci_slot: String::new(), device_type, gl: true }
}
fn card((vendor, device, slot): (u32, u32, &str), displays: u32, built_in_panel: bool) -> DisplayCard {
DisplayCard { vendor, device, pci_slot: slot.into(), displays, built_in_panel }
}
/// What wgpu offers on a laptop whose AMD iGPU drives the panel, in its order (Vulkan, then GL).
fn laptop_adapters() -> Vec<Candidate> {
vec![
vulkan("AMD Radeon Graphics (RADV RENOIR)", AMD, DeviceType::IntegratedGpu),
vulkan("NVIDIA GeForce RTX 3050 Laptop GPU", NVIDIA, DeviceType::DiscreteGpu),
gl("AMD Radeon Graphics (radeonsi, renoir)", 0x1002, DeviceType::IntegratedGpu),
]
}
/// The adapter behind the displays draws: a laptop stays off its discrete GPU (7 W against over 20 W), a desktop
/// keeps its surface.
#[test]
fn the_adapter_behind_the_displays_is_chosen() {
let none = Asked::default();
let laptop = laptop_adapters();
// The iGPU drives the panel; egui-wgpu's default drew on the discrete GPU.
let panel_on_amd = [card(NVIDIA, 0, false), card(AMD, 1, true)];
assert_eq!(choose(&laptop, &panel_on_amd, &none), Some((0, Why::BuiltInPanel)), "laptop panel");
let mut swapped = laptop_adapters();
swapped.swap(0, 1);
assert_eq!(choose(&swapped, &panel_on_amd, &none), Some((1, Why::BuiltInPanel)), "laptop panel, discrete listed first");
let monitor_on_nvidia = [card(NVIDIA, 1, false), card(AMD, 1, true)];
assert_eq!(choose(&laptop, &monitor_on_nvidia, &none), Some((0, Why::BuiltInPanel)), "the panel wins over a monitor on the other card");
// The measured laptop: Intel HD 530 behind the panel, a Quadro M4000M offered first with nothing connected.
const HD530: (u32, u32, &str) = (0x8086, 0x191b, "0000:00:02.0");
const M4000M: (u32, u32, &str) = (0x10de, 0x13f9, "0000:01:00.0");
let measured =
[vulkan("Quadro M4000M", M4000M, DeviceType::DiscreteGpu), vulkan("Intel(R) HD Graphics 530 (SKL GT2)", HD530, DeviceType::IntegratedGpu)];
assert_eq!(choose(&measured, &[card(M4000M, 0, false), card(HD530, 1, true)], &none), Some((1, Why::BuiltInPanel)), "Intel and NVIDIA laptop");
// A desktop with its only monitor on one card (a low-power default can't start the window there).
let desktop =
[vulkan("Intel(R) Graphics (RPL-S)", INTEL, DeviceType::IntegratedGpu), vulkan("NVIDIA GeForce RTX", NVIDIA, DeviceType::DiscreteGpu)];
assert_eq!(
choose(&desktop, &[card(INTEL, 0, false), card(NVIDIA, 1, false)], &none),
Some((1, Why::OnlyGpuWithDisplays)),
"monitor on the discrete card"
);
assert_eq!(choose(&desktop, &[card(INTEL, 2, false), card(NVIDIA, 0, false)], &none), Some((0, Why::OnlyGpuWithDisplays)), "monitor on the iGPU");
// A monitor on each card: the discrete GPU (an iGPU choice there lost its surface).
assert_eq!(choose(&desktop, &[card(INTEL, 1, false), card(NVIDIA, 1, false)], &none), Some((1, Why::Fallback)), "monitors on two cards");
// Nothing readable: the discrete GPU.
assert_eq!(choose(&laptop, &[], &none), Some((1, Why::Fallback)), "no display facts");
assert_eq!(choose(&laptop, &[card((0x1234, 0x1, "0000:09:00.0"), 1, true)], &none), Some((1, Why::Fallback)), "a card no adapter matches");
assert_eq!(choose(&[], &[card(AMD, 1, true)], &none), None, "no adapter at all");
// The environment variables decide when set: prime-run style requests reach the NVIDIA card.
let asked = |name: Option<&str>, power: Option<PowerPreference>| Asked { adapter_name: name.map(Into::into), power };
assert_eq!(choose(&laptop, &panel_on_amd, &asked(None, Some(PowerPreference::HighPerformance))), Some((1, Why::AskedPower)));
assert_eq!(choose(&laptop, &panel_on_amd, &asked(None, Some(PowerPreference::LowPower))), Some((0, Why::AskedPower)));
assert_eq!(choose(&laptop, &panel_on_amd, &asked(None, Some(PowerPreference::None))), Some((0, Why::AskedPower)));
assert_eq!(choose(&laptop, &panel_on_amd, &asked(Some("nvidia"), None)), Some((1, Why::AskedByName)));
assert_eq!(
choose(&laptop, &panel_on_amd, &asked(Some("RadeonSI"), Some(PowerPreference::HighPerformance))),
Some((2, Why::AskedByName)),
"the name beats the power"
);
// A name nothing has, or an empty one: the usual choice, not a failure.
assert_eq!(choose(&laptop, &panel_on_amd, &asked(Some("matrox"), None)), Some((0, Why::BuiltInPanel)));
assert_eq!(choose(&laptop, &panel_on_amd, &asked(Some(""), None)), Some((0, Why::BuiltInPanel)));
// Under GL there's no PCI address or device id: the vendor finds the card only when no other card shares it.
let gl_adapters =
[gl("NVIDIA GeForce RTX 3050", 0x10de, DeviceType::Other), gl("AMD Radeon Graphics (radeonsi)", 0x1002, DeviceType::IntegratedGpu)];
assert_eq!(choose(&gl_adapters, &panel_on_amd, &none), Some((1, Why::BuiltInPanel)), "GL, one AMD card");
let two_amd = [card((0x1002, 0x73df, "0000:03:00.0"), 0, false), card(AMD, 1, true)];
let gl_two_amd = [gl("AMD Radeon RX 6700", 0x1002, DeviceType::Other), gl("AMD Radeon Graphics", 0x1002, DeviceType::IntegratedGpu)];
assert_eq!(choose(&gl_two_amd, &two_amd, &none), Some((1, Why::Fallback)), "GL, two AMD cards");
// Two adapters for the panel's card: Vulkan, whatever the order.
let gl_first = [
gl("AMD Radeon Graphics (radeonsi)", 0x1002, DeviceType::IntegratedGpu),
vulkan("AMD Radeon Graphics (RADV RENOIR)", AMD, DeviceType::IntegratedGpu),
];
assert_eq!(choose(&gl_first, &[card(AMD, 1, true)], &none), Some((1, Why::BuiltInPanel)), "Vulkan before GL");
// A closed laptop with a monitor on the NVIDIA card: the switched-off panel isn't one (`drm` skips it).
assert_eq!(choose(&laptop, &[card(NVIDIA, 1, false), card(AMD, 0, false)], &none), Some((1, Why::OnlyGpuWithDisplays)), "closed laptop");
// Two cards of one model: only the PCI address tells them apart; without one the old choice stands.
const SECOND: (u32, u32, &str) = (0x10de, 0x25a2, "0000:02:00.0");
let twins = [card(NVIDIA, 0, false), card(SECOND, 1, false)];
let with_slots = [vulkan("NVIDIA A", NVIDIA, DeviceType::DiscreteGpu), vulkan("NVIDIA B", SECOND, DeviceType::DiscreteGpu)];
assert_eq!(choose(&with_slots, &twins, &none), Some((1, Why::OnlyGpuWithDisplays)), "twins with PCI addresses");
let without: Vec<Candidate> = with_slots.iter().cloned().map(|c| Candidate { pci_slot: String::new(), ..c }).collect();
assert_eq!(choose(&without, &twins, &none), Some((0, Why::Fallback)), "twins without PCI addresses");
}
fn add_card(dir: &Path, card: &str, id: &str, slot: &str) {
let device = dir.join(card).join("device");
fs::create_dir_all(&device).unwrap();
fs::write(device.join("uevent"), format!("DRIVER=x\nPCI_CLASS=30000\nPCI_ID={id}\nPCI_SLOT_NAME={slot}\n")).unwrap();
}
/// A fake `/sys/class/drm`: cards as (name, PCI_ID, PCI_SLOT_NAME), connectors as (name, status), and the render
/// node and version file a real one has.
fn drm(cards: &[(&str, &str, &str)], connectors: &[(&str, &str)]) -> tempfile::TempDir {
let dir = tempfile::tempdir().unwrap();
for (card, id, slot) in cards {
add_card(dir.path(), card, id, slot);
}
for (connector, status) in connectors {
let c = dir.path().join(connector);
fs::create_dir_all(&c).unwrap();
fs::write(c.join("status"), format!("{status}\n")).unwrap();
}
fs::create_dir_all(dir.path().join("renderD128")).unwrap();
fs::write(dir.path().join("version"), "drm 1.1.0\n").unwrap();
dir
}
/// Parsing of the kernel's DRM folder: hostile or odd content is left out, never a panic.
#[test]
fn sysfs_display_cards() {
// A laptop whose AMD iGPU drives the panel, with an NVIDIA card that has no outputs.
let d = drm(
&[("card0", "10DE:25A2", "0000:01:00.0"), ("card1", "1002:1638", "0000:05:00.0")],
&[("card1-DP-1", "disconnected"), ("card1-eDP-1", "connected"), ("card1-HDMI-A-1", "disconnected")],
);
assert_eq!(
display_cards_in(d.path()),
vec![
DisplayCard { vendor: 0x10de, device: 0x25a2, pci_slot: "0000:01:00.0".into(), displays: 0, built_in_panel: false },
DisplayCard { vendor: 0x1002, device: 0x1638, pci_slot: "0000:05:00.0".into(), displays: 1, built_in_panel: true },
],
"laptop panel"
);
// A desktop with monitors on each card: counted on each, no built-in panel.
let d = drm(
&[("card0", "8086:A780", "0000:00:02.0"), ("card1", "10de:2206", "0000:01:00.0")],
&[("card0-HDMI-A-1", "connected"), ("card1-DP-1", "connected"), ("card1-DP-2", "connected"), ("card1-DP-3", "disconnected")],
);
let counts: Vec<(u32, bool)> = display_cards_in(d.path()).iter().map(|c| (c.displays, c.built_in_panel)).collect();
assert_eq!(counts, vec![(1, false), (2, false)], "monitors on two cards");
// `card10` is a different card from `card1`, and its connectors aren't `card1`'s.
let d = drm(&[("card1", "1002:1638", "0000:05:00.0"), ("card10", "10de:25a2", "0000:01:00.0")], &[("card10-DP-1", "connected")]);
let counts: Vec<(u32, u32)> = display_cards_in(d.path()).iter().map(|c| (c.vendor, c.displays)).collect();
assert_eq!(counts, vec![(0x1002, 0), (0x10de, 1)], "card10 is not card1");
// LVDS and DSI panels are built in too; HDMI-A is a monitor, whatever its number.
assert_eq!(drm::connector_kind("eDP-1"), "eDP");
assert_eq!(drm::connector_kind("HDMI-A-1"), "HDMI-A");
assert_eq!(drm::connector_kind("DSI-12"), "DSI");
assert_eq!(drm::connector_kind("Virtual"), "Virtual");
let d = drm(&[("card0", "8086:9a49", "0000:00:02.0")], &[("card0-LVDS-1", "connected")]);
let cards = display_cards_in(d.path());
assert!(!cards.is_empty() && cards.iter().all(|c| c.built_in_panel), "LVDS is a panel: {cards:?}");
// A status of `unknown` (some virtual outputs) isn't a connected display.
let d = drm(&[("card0", "1af4:1050", "0000:00:01.0")], &[("card0-Virtual-1", "unknown")]);
assert_eq!(display_cards_in(d.path()).first().map(|c| c.displays), Some(0), "only connected counts");
// A closed lid with a monitor on the discrete card: the panel reads `connected` but is switched off.
let d = drm(
&[("card0", "10de:25a2", "0000:01:00.0"), ("card1", "1002:1638", "0000:05:00.0")],
&[("card0-HDMI-A-1", "connected"), ("card1-eDP-1", "connected")],
);
fs::write(d.path().join("card0-HDMI-A-1").join("enabled"), "enabled\n").unwrap();
fs::write(d.path().join("card1-eDP-1").join("enabled"), "disabled\n").unwrap();
let seen: Vec<(u32, u32, bool)> = display_cards_in(d.path()).iter().map(|c| (c.vendor, c.displays, c.built_in_panel)).collect();
assert_eq!(seen, vec![(0x10de, 1, false), (0x1002, 0, false)], "a switched-off panel does not count");
// A firmware framebuffer has no PCI ids; unreadable or odd entries are skipped.
let d = drm(&[("card0", "nonsense", ""), ("card1", "1002:", "")], &[("card0-Virtual-1", "connected")]);
fs::create_dir_all(d.path().join("card2")).unwrap();
fs::create_dir_all(d.path().join("card")).unwrap();
assert!(display_cards_in(d.path()).is_empty(), "unreadable cards are left out");
assert!(display_cards_in(&d.path().join("missing")).is_empty(), "a missing folder gives no cards");
assert_eq!(drm::pci_ids("PCI_ID=10de:25a2"), Some((0x10de, 0x25a2)));
assert_eq!(drm::pci_ids("PCI_IDX=10de:25a2"), None);
// The bounds: a uevent whose ids lie past `MAX_FILE` bytes isn't read that far, and no more than `MAX_ENTRIES`
// entries of the folder are looked at.
let d = tempfile::tempdir().unwrap();
let device = d.path().join("card0").join("device");
fs::create_dir_all(&device).unwrap();
let padding = "x".repeat(usize::try_from(drm::MAX_FILE).unwrap() * 2);
fs::write(device.join("uevent"), format!("PAD={padding}\nPCI_ID=1002:1638\n")).unwrap();
assert!(display_cards_in(d.path()).is_empty(), "ids past the read bound are not seen");
let d = tempfile::tempdir().unwrap();
for n in 0..drm::MAX_ENTRIES + 40 {
add_card(d.path(), &format!("card{n}"), "1002:1638", "");
}
assert_eq!(display_cards_in(d.path()).len(), drm::MAX_ENTRIES, "the folder is read up to its entry bound");
}
+12
View File
@@ -2,12 +2,18 @@
//!
//! Application crates register [`GpuProvider`] implementations; generic hosts dispatch
//! [`GpuJob`] values by [`GpuJob::provider_id`] without importing app project types.
//!
//! With the `startup` feature, the GPU start-up choices per platform for apps on eframe's wgpu backend: which backends
//! to try, the power preference, the DX12 shader compiler and, on Linux, which DRM device to render on. An app calls
//! `configure` on the `WgpuSetupCreateNew` it hands to eframe.
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
mod caps;
mod chunk;
mod context;
#[cfg(feature = "startup")]
mod device;
mod error;
mod job;
mod provider;
@@ -17,9 +23,15 @@ mod registry;
#[cfg(test)]
mod tests;
#[cfg(test)]
#[cfg(feature = "startup")]
mod device_tests;
pub use caps::DeviceCaps;
pub use chunk::chunk_buffer;
pub use context::{GpuContext, ReadOutcome, ReadRequest, WorkerKind};
#[cfg(feature = "startup")]
pub use device::configure;
pub use error::GpuFault;
pub use job::{GpuJob, GpuJobOutcome, GpuJobParams, HandleId};
pub use provider::GpuProvider;
+110 -9
View File
@@ -65,6 +65,10 @@ pub struct PickRequest {
pub file_name: Option<String>,
/// The extension a Save answer gets when the user typed none (`"png"`), lowercase.
pub suggested_extension: Option<String>,
/// Forces the in-app chooser for this request.
pub fallback: bool,
/// The save makes the document a new file on the host page; other services ignore it.
pub save_as: bool,
}
impl PickRequest {
@@ -79,6 +83,8 @@ impl PickRequest {
default_directory: None,
file_name: None,
suggested_extension: None,
fallback: false,
save_as: false,
}
}
@@ -138,6 +144,19 @@ impl PickRequest {
self.suggested_extension = Some(extension.into().trim_start_matches('.').to_ascii_lowercase());
self
}
/// Forces the in-app chooser for this request instead of the system's file dialog.
pub fn fallback(mut self, on: bool) -> Self {
self.fallback = on;
self
}
/// Makes the save a new file on the host page: a Save As, or a Save under a name the page
/// never sent. Services without a host page ignore it.
pub fn save_as(mut self, on: bool) -> Self {
self.save_as = on;
self
}
}
/// The ticket of a pending pick; the answer carries it back.
@@ -159,6 +178,11 @@ pub enum Picked {
/// the text is the technical cause, not a sentence for the user. A feature without a status
/// line to report on treats it as nothing chosen.
Unavailable(String),
/// A chosen save path that could not be written; the message is the system's.
Failed(String),
/// A save the browser handed to the user as a download, under this file name. The page holds no
/// file of the document, so it names nothing the app could reopen.
Downloaded(String),
}
impl Picked {
@@ -167,16 +191,25 @@ impl Picked {
match self {
Picked::Paths(paths) => paths.first().cloned(),
Picked::Contents(files) => files.first().map(|(name, _)| PathBuf::from(name)),
Picked::Cancelled | Picked::Unavailable(_) => None,
Picked::Cancelled | Picked::Unavailable(_) | Picked::Failed(_) | Picked::Downloaded(_) => None,
}
}
/// Whether the document is now the file a finished save made. A save answers
/// [`Picked::Paths`] with the file it made: the path a native service wrote, or the name
/// under which a hosted browser page now holds the document. A browser download answers
/// [`Picked::Downloaded`], which names a file the page does not hold, so this is false for it.
/// The app sets its session path only when this is true.
pub fn records_file(&self) -> bool {
matches!(self, Picked::Paths(paths) if !paths.is_empty())
}
/// Every chosen path; on wasm the files' names. Empty when cancelled or unavailable.
pub fn paths(&self) -> Vec<PathBuf> {
match self {
Picked::Paths(paths) => paths.clone(),
Picked::Contents(files) => files.iter().map(|(name, _)| PathBuf::from(name)).collect(),
Picked::Cancelled | Picked::Unavailable(_) => Vec::new(),
Picked::Cancelled | Picked::Unavailable(_) | Picked::Failed(_) | Picked::Downloaded(_) => Vec::new(),
}
}
}
@@ -249,6 +282,15 @@ pub trait Files: Send + Sync {
fn write(&self, path: &Path, bytes: &[u8]) -> Result<(), FileError>;
/// The folder the last answered pick of `purpose` chose.
fn last_folder(&self, purpose: &str) -> Option<PathBuf>;
/// Queues a save of `bytes` as ticket `request`'s answer, taken with
/// [`take_answer`](Files::take_answer): the desktop service asks for the path, then writes
/// atomically; the browser service opens the save picker or makes one download. Counted in
/// [`pick_pending`](Files::pick_pending).
fn save(&self, request: PickRequest, bytes: Vec<u8>) -> PickId;
/// Whether a pick can answer paths that [`read`](Files::read) opens again.
fn can_pick(&self) -> bool;
/// Whether [`save`](Files::save) hands the bytes to the browser instead of writing a path.
fn browser_saves(&self) -> bool;
}
/// No pickers (every pick answers `Cancelled`); reads and writes go to the file system. The
@@ -307,12 +349,26 @@ impl Files for NoPickFiles {
fn last_folder(&self, _purpose: &str) -> Option<PathBuf> {
None
}
/// Answers `Cancelled` like [`pick`](Files::pick); nothing is written.
fn save(&self, request: PickRequest, _bytes: Vec<u8>) -> PickId {
self.pick(request)
}
fn can_pick(&self) -> bool {
false
}
fn browser_saves(&self) -> bool {
false
}
}
/// A file service that answers from a script, for tests of the features that ask for files. It
/// records every [`PickRequest`], keeps files in memory, and answers each pick in order from the
/// answers the test queued: the first queued answer goes to the first pick, and a pick with
/// nothing queued is `Cancelled`.
/// nothing queued is `Cancelled`. A [`save`](Files::save) is a pick whose bytes go to the chosen
/// path in memory when it is answered with `Paths`.
///
/// A test that expects no picker asserts [`requests`](ScriptedFiles::requests) is empty. Every
/// method takes `&self`, so a test keeps its own `Arc<ScriptedFiles>` and hands a clone to the
@@ -336,6 +392,23 @@ struct ScriptState {
open: Vec<(PickId, PickRequest)>,
answered: Vec<PickAnswer>,
files: HashMap<PathBuf, Vec<u8>>,
/// The bytes of the saves not answered yet, written to the chosen path with the answer.
saves: HashMap<PickId, Vec<u8>>,
/// Stands in for a browser host.
browser: bool,
}
impl ScriptState {
/// Files `picked` as ticket `id`'s answer; a save's bytes go to the path it chose.
fn settle(&mut self, id: PickId, request: PickRequest, picked: Picked) {
if let Some(bytes) = self.saves.remove(&id)
&& let Picked::Paths(paths) = &picked
&& let Some(path) = paths.first()
{
self.files.insert(path.clone(), bytes);
}
self.answered.push(PickAnswer { id, request, picked });
}
}
impl ScriptedFiles {
@@ -367,6 +440,13 @@ impl ScriptedFiles {
self
}
/// A service that stands in for a browser host: [`Files::can_pick`] answers false and
/// [`Files::browser_saves`] true.
pub fn in_browser(self) -> Self {
self.state().browser = true;
self
}
/// Puts a file in memory, for [`Files::read`].
pub fn with_file(self, path: impl Into<PathBuf>, bytes: impl Into<Vec<u8>>) -> Self {
self.state().files.insert(path.into(), bytes.into());
@@ -392,7 +472,7 @@ impl ScriptedFiles {
pub fn answer(&self, picked: Picked) -> Option<PickId> {
let mut state = self.state();
let (id, request) = state.open.pop()?;
state.answered.push(PickAnswer { id, request, picked });
state.settle(id, request, picked);
Some(id)
}
@@ -401,7 +481,7 @@ impl ScriptedFiles {
let mut state = self.state();
let Some(at) = state.open.iter().position(|(open, _)| *open == id) else { return false };
let (_, request) = state.open.remove(at);
state.answered.push(PickAnswer { id, request, picked });
state.settle(id, request, picked);
true
}
@@ -419,13 +499,15 @@ impl ScriptedFiles {
let name = PathBuf::from(request.file_name.clone().unwrap_or_default());
Picked::Paths(vec![request.directory.as_ref().map_or_else(|| name.clone(), |dir| dir.join(&name))])
}
}
impl Files for ScriptedFiles {
fn pick(&self, request: PickRequest) -> PickId {
/// Records `request` and answers it from the script; a save's `bytes` wait for the answer.
fn ask(&self, request: PickRequest, bytes: Option<Vec<u8>>) -> PickId {
let mut state = self.state();
state.next += 1;
let id = PickId(state.next);
if let Some(bytes) = bytes {
state.saves.insert(id, bytes);
}
let suggested = (state.save_suggested && request.kind == PickKind::Save).then(|| Self::suggested(&request));
state.asked.push(request.clone());
if state.held {
@@ -433,9 +515,15 @@ impl Files for ScriptedFiles {
return id;
}
let picked = suggested.or_else(|| state.queued.pop_front()).unwrap_or(Picked::Cancelled);
state.answered.push(PickAnswer { id, request, picked });
state.settle(id, request, picked);
id
}
}
impl Files for ScriptedFiles {
fn pick(&self, request: PickRequest) -> PickId {
self.ask(request, None)
}
fn take_answer(&self, id: PickId) -> Option<Picked> {
let mut state = self.state();
@@ -447,6 +535,7 @@ impl Files for ScriptedFiles {
let mut state = self.state();
state.answered.retain(|a| a.id != id);
state.open.retain(|(open, _)| *open != id);
state.saves.remove(&id);
}
fn pick_pending(&self) -> bool {
@@ -465,6 +554,18 @@ impl Files for ScriptedFiles {
fn last_folder(&self, _purpose: &str) -> Option<PathBuf> {
None
}
fn save(&self, request: PickRequest, bytes: Vec<u8>) -> PickId {
self.ask(request, Some(bytes))
}
fn can_pick(&self) -> bool {
!self.state().browser
}
fn browser_saves(&self) -> bool {
self.state().browser
}
}
#[cfg(not(target_arch = "wasm32"))]
+39
View File
@@ -2,6 +2,8 @@
use unicode_bidi::{BidiClass, bidi_class};
use crate::scripts::Direction;
pub(super) const LRI: char = '\u{2066}';
pub(super) const RLI: char = '\u{2067}';
pub(super) const FSI: char = '\u{2068}';
@@ -30,6 +32,43 @@ pub fn ltr(value: &str) -> String {
wrap(LRI, value)
}
/// A file name for display in an interface of `direction`: unchanged for left-to-right, an
/// isolate with a left-to-right mark before a short extension for right-to-left.
pub fn file_name(name: &str, direction: Direction) -> String {
if direction.is_rtl() { isolate(&mark_extension(name)) } else { name.to_string() }
}
/// A path for display in an interface of `direction`: unchanged for left-to-right, a left-to-right
/// isolate with marks after every separator and before a short extension for right-to-left.
pub fn path(value: &str, direction: Direction) -> String {
if !direction.is_rtl() {
return value.to_string();
}
let marked = mark_extension(value);
let mut out = String::with_capacity(marked.len() + 8);
for c in marked.chars() {
out.push(c);
// Keeps two right-to-left folder names from joining into one run that swaps them.
if matches!(c, '/' | '\\') {
out.push(LRM);
}
}
ltr(&out)
}
/// `name` with a left-to-right mark before its extension (the text after the last `.`, not at the start, 1 to 8 ASCII
/// letters or digits), which a right-to-left line would otherwise draw as `docx.2` for `2.docx`.
fn mark_extension(name: &str) -> String {
if let Some(dot) = name.rfind('.')
&& dot > 0
&& name.get(dot + 1..).is_some_and(|ext| !ext.is_empty() && ext.len() <= 8 && ext.bytes().all(|b| b.is_ascii_alphanumeric()))
&& let (Some(stem), Some(ext)) = (name.get(..dot), name.get(dot..))
{
return format!("{stem}{LRM}{ext}");
}
name.to_string()
}
/// `text` without isolate marks (LRI, RLI, FSI, PDI): a [`crate::fmt`] or [`crate::I18n::trn`] result made fit
/// for a file name, a log or a comparison.
pub fn strip_isolates(text: &str) -> String {
+1 -1
View File
@@ -33,7 +33,7 @@ use bidi::{FSI, has_bidi_control, has_rtl, is_one_isolate, unwrap_isolate, wrap}
use negotiation::posix_env_tags;
use negotiation::{bare, candidates, is_region, marked, plural_rules};
pub use bidi::{isolate, ltr, strip_isolates};
pub use bidi::{file_name, isolate, ltr, path, strip_isolates};
/// The CLDR number, plural and date data for every CLDR locale, from `data/generate.sh`.
mod data {
+71
View File
@@ -119,6 +119,77 @@ fn script_subtag_never_picks_another_script() {
}
}
#[test]
fn system_tags_match_languages_in_order() {
let i = all(&[("fr", "", ""), ("pt-br", "", ""), ("zh-hant", "", ""), ("de", "", "")]).0;
for (tag, want) in [
("fr_CA.UTF-8", Some("fr")),
("fr-FR", Some("fr")),
("pt-BR", Some("pt-br")),
("zh-Hant-MO", Some("zh-hant")),
("de_DE@euro", Some("de")),
("xx-YY", None),
] {
assert_eq!(i.match_tag(tag).map(|l| i.code(l)), want, "{tag}");
}
assert!(i.match_tag("C") == Some(Lang::EN) && i.match_tag("POSIX") == Some(Lang::EN));
assert_eq!(i.code(i.match_tags(["xx", "de", "fr"])), "de", "the first known tag wins");
assert!(i.match_tags(["xx", "yy"]) == Lang::EN && i.match_tags([]) == Lang::EN, "English when none fits");
}
#[test]
fn lookup_falls_back_to_english_and_context_never_borrows_the_plain_row() {
let (i, _) = all(E);
let fr = lang(&i, "fr");
assert_eq!(i.t(fr, "Save"), "Sauvegarder", "the app's row wins over the shared one");
assert_eq!(i.t(fr, "Open"), "Ouvrir");
assert_eq!(i.tc(fr, "menu", "Open"), "Ouvrir le menu");
assert_eq!(i.tid(fr, "file.save", "Save file"), "Enregistrer le fichier");
assert_eq!(i.t(fr, "Not translated"), "Not translated");
assert_eq!(i.get(fr, "menu", "Save"), None, "a context row is not the plain row");
assert_eq!(i.t(Lang::EN, "Save"), "Save");
}
#[test]
fn plurals_take_the_languages_categories() {
let i = all(P).0;
let ru = lang(&i, "ru");
for (n, want) in [(1, "1 файл"), (2, "2 файла"), (5, "5 файлов"), (11, "11 файлов"), (21, "21 файл"), (22, "22 файла")]
{
assert_eq!(i.trn(ru, n, "{n} file", "{n} files"), want, "{n}");
}
}
#[test]
fn a_file_name_or_path_keeps_its_extension_and_separators_left_to_right_in_a_right_to_left_text() {
let rtl = Direction::Rtl;
let lrm = '\u{200E}';
// What the isolates and marks wrap is the input, unchanged.
let bare = |shown: &str| strip_isolates(shown).replace(lrm, "");
let named = file_name("تقرير 2.docx", rtl);
assert!(named.contains(&format!("{lrm}.docx")), "a mark directly before the extension: {named:?}");
assert_eq!(bare(&named), "تقرير 2.docx");
for text in ["ملاحظات", "v1.2 تقرير"] {
let shown = file_name(text, rtl);
assert!(!shown.contains(lrm), "no extension, no mark: {shown:?}");
assert_eq!(bare(&shown), text);
}
for sep in ['/', '\\'] {
let input = format!("C:{sep}ملفات{sep}تقرير.docx");
let shown = path(&input, rtl);
assert_eq!(shown.matches(&format!("{sep}{lrm}")).count(), 2, "a mark after every {sep:?}: {shown:?}");
assert!(shown.contains(&format!("{lrm}.docx")), "a mark before the extension: {shown:?}");
assert_eq!(bare(&shown), input);
}
for text in ["تقرير 2.docx", "v1.2 تقرير", "C:/ملفات/تقرير.docx"] {
assert_eq!(file_name(text, Direction::Ltr), text);
assert_eq!(path(text, Direction::Ltr), text);
}
}
#[test]
fn check_all_reports_every_bad_row() {
let (i, problems) = all(E);
+4 -26
View File
@@ -1,16 +1,13 @@
//! [`HostedAdjustDialog`]: an Image › Adjustments dialog on the dialog host, around any adjustment editor.
use craft_behavior::{GestureId, Value};
use craft_theme::variant::Tone;
use craft_ui::contract::{Bind, Sampler as _, Show as _};
use craft_ui::contract::{Bind, Sampler as _};
use craft_ui::dialog::{
DialogId, DialogResult, DialogStack, FieldRefusal, HeldAnswer, HeldOk, StackDialog, dialog_id, serde_fields, set_serde_field,
};
use craft_ui::notices::{Notice, NoticeLayout};
use craft_ui::patterns::form_dialogs::FormDialog;
use craft_ui::runtime::env::Label;
use craft_ui::runtime::memory::SaveKey;
use craft_ui::runtime::overlay::CloseReason;
use egui::{Context, Ui};
use serde::Serialize;
use serde::de::DeserializeOwned;
@@ -348,9 +345,6 @@ impl<V: Value + Default + Serialize + DeserializeOwned, E: Send + 'static> Stack
held,
..
} = self;
// The app accepted the held OK: this pass closes the dialog with it. A measuring run closes nothing.
let finish = held.is_accepted() && !craft_ui::runtime::measure::active(ui.ctx());
let refusal = held.refusal().map(|(reason, refused)| (reason.clone(), refused.clone()));
// The request to select a point is this pass's alone: a rerun of the pass in the frame finds none.
let (canvas, select_point) = (*canvas, select_point.take());
let (context, resizable, remember) = (*context, *resizable, remember.clone());
@@ -360,8 +354,6 @@ impl<V: Value + Default + Serialize + DeserializeOwned, E: Send + 'static> Stack
.opened(Bind::bound(open))
.preview(Some(Bind::bound(&mut *preview)))
.opening(opening.clone())
.accept_stays_open(*hold)
.ok_enabled(!held.is_waiting())
.shaped(move |dialog| {
let dialog = dialog.resizable(resizable);
match remember {
@@ -373,6 +365,8 @@ impl<V: Value + Default + Serialize + DeserializeOwned, E: Send + 'static> Stack
Some(target) => form.reset_with(target),
None => form,
};
// A held OK files the value for the app; the form shows the app's refusal and closes with the accepted value.
let form = if *hold { form.held(&mut *held) } else { form };
let shown = form.show(ui, |ui, form, value| {
if let Some(canvas) = canvas {
form.keep_view_open(canvas);
@@ -380,31 +374,15 @@ impl<V: Value + Default + Serialize + DeserializeOwned, E: Send + 'static> Stack
let mut cx =
AdjustDialogCx { context, canvas, picker: &mut *picker, channel: &mut *channel, select_point, clipping: &mut *clipping, edit: None };
asks.extend(editor(ui, value, &mut cx));
if let Some((reason, _)) = refusal.as_ref().filter(|(_, refused)| refused == value) {
Notice::new(Tone::Bad, reason.clone()).layout(NoticeLayout::Inline).show(ui);
}
if finish {
form.request_close_as(CloseReason::Activated);
}
true
});
*comparing = shown.comparing;
*edited |= *value != before;
if held.refusal().is_some_and(|(_, refused)| refused != value) {
held.clear_refusal();
}
// The pass reports a press only in the pass that took the input, so a second pass of the frame files nothing.
if *hold && shown.picked == Some(0) && !held.is_waiting() {
held.file(value.clone());
}
if finish && shown.closed == Some(CloseReason::Activated) {
return Some(held.finish().map_or(DialogResult::Cancel, DialogResult::Ok));
}
#[cfg(feature = "screen-testing")]
{
self.facts = craft_ui::contract::Outcome::story_facts(&shown.response);
}
let accepted = shown.accepted.filter(|_| !*hold).map(DialogResult::Ok);
let accepted = shown.accepted.map(DialogResult::Ok);
accepted.or(shown.closed.map(|_| DialogResult::Cancel))
}
+27 -4
View File
@@ -390,22 +390,32 @@ impl Keymap {
/// [`lookup`](Self::lookup) with the panels around the focused one in `outer` ([`Scopes::rank_nested`]).
pub fn lookup_nested(&self, chord: &Chord, double: bool, active: &Active, outer: &[&str]) -> Lookup {
self.lookup_where(chord, double, active, outer, &|_| true)
}
/// [`lookup_nested`](Self::lookup_nested) among the commands `accept` takes: the bindings of a command it refuses
/// (one disabled where the press lands) are passed over, so the chord's next binding, in an outer scope, runs.
pub fn lookup_where(&self, chord: &Chord, double: bool, active: &Active, outer: &[&str], accept: &dyn Fn(&CommandRef) -> bool) -> Lookup {
let command = |i: usize| self.catalog[i].command.clone();
match self.winners(Trigger { chord: chord.effective(self.platform), double }, active, outer) {
match self.winners(Trigger { chord: chord.effective(self.platform), double }, active, outer, accept) {
Winners::None => Lookup::None,
Winners::Run(i) => Lookup::Run(command(i)),
Winners::Cycle(cycle) => Lookup::Cycle(cycle.into_iter().map(command).collect()),
}
}
/// The commands, by catalog position, that a press of the effective trigger `want` runs with `active` focus.
fn winners(&self, want: Trigger, active: &Active, outer: &[&str]) -> Winners {
/// The commands, by catalog position, that a press of the effective trigger `want` runs with `active` focus, among
/// the commands `accept` takes.
fn winners(&self, want: Trigger, active: &Active, outer: &[&str], accept: &dyn Fn(&CommandRef) -> bool) -> Winners {
let held = active.typing && !self.typing.fires(&want.chord, self.platform);
let Some(holders) = self.by_trigger.get(&want) else { return Winners::None };
// Each command's nearest rank; `holders` is in catalog order.
let mut ranks: Vec<(usize, u8)> = Vec::new();
for &(i, k) in holders {
let Some(r) = self.at(i, k).and_then(|(_, s)| self.scopes.rank_nested(s, active, outer)) else { continue };
if !accept(&self.catalog[i].command) {
continue;
}
// The typing rule holds back everything except bindings of an active context (rank 0).
if held && r != 0 {
continue;
@@ -457,7 +467,7 @@ impl Keymap {
ScopeKind::Panel => Active::panel(name[0]),
ScopeKind::Context => Active { panel: None, contexts: &name, typing: false },
};
match self.winners(Trigger { chord: trigger.chord.effective(self.platform), double: false }, &active, &[]) {
match self.winners(Trigger { chord: trigger.chord.effective(self.platform), double: false }, &active, &[], &|_| true) {
Winners::None => false,
Winners::Run(j) => j == i,
Winners::Cycle(cycle) => cycle.contains(&i),
@@ -485,6 +495,19 @@ impl Keymap {
self.by_trigger.get(&want)?.iter().find(|&&(i, k)| self.at(i, k).is_some()).map(|&(i, _)| self.catalog[i].command.clone())
}
/// Every command a single press of `chord` is bound to, in any scope, in catalog order, each once: a caller that
/// asks whether the press can run anything now reads each one's state.
pub fn holders(&self, chord: &Chord) -> Vec<CommandRef> {
let want = Trigger { chord: chord.effective(self.platform), double: false };
let mut found: Vec<usize> = Vec::new();
for &(i, k) in self.by_trigger.get(&want).into_iter().flatten() {
if self.at(i, k).is_some() && !found.contains(&i) {
found.push(i);
}
}
found.into_iter().map(|i| self.catalog[i].command.clone()).collect()
}
/// Adds a binding to a command.
pub fn assign(&mut self, command: &CommandRef, binding: Binding, policy: Policy) -> Result<Assigned, AssignError> {
let i = self.find(command).ok_or(AssignError::UnknownCommand)?;
+7 -1
View File
@@ -13,7 +13,13 @@
//! without Shift). A digit-row press that types punctuation also matches its position's digit,
//! after the punctuation: AZERTY's `-` key runs Ctrl+- and, when that has no binding, Ctrl+6.
//! 3. **Punctuation:** the character typed, without Shift when the layout needs Shift for it
//! (German `/` is ⇧7, so ⇧⌘7 is ⌘/; US `:` is ⇧;, so ⇧; is `:`). A Shift binding on a US
//! (German `/` is ⇧7, so ⇧⌘7 is ⌘/; US `:` is ⇧;, so ⇧; is `:`). One exception, for the
//! command a press runs (lead ruling, [`Matcher`](crate::Matcher)): when the person held Shift
//! and the keymap binds the chord with Shift kept, that binding wins over the Shift-dropped
//! chord's; on a layout where `=` is ⇧0, Ctrl+Shift+0 runs Ctrl+Shift+= (Word's Superscript),
//! not Ctrl+= (Subscript), and Ctrl+= only when Ctrl+Shift+= is unbound. Recording
//! ([`Layout::resolve`]), [`Layout::candidates`] and [`Layout::matches`] keep rule 3. A Shift
//! binding on a US
//! base key also matches the same press (`Shift+;` matches `:`), and `=` and `+` stand for
//! each other so zoom keys work with and without Shift. egui has no key for the characters the
//! ISO key next to left Shift types (`<` and `>` on Turkish Q) and reports both as that key,
+45 -18
View File
@@ -79,37 +79,63 @@ impl Matcher {
/// The command `press` runs, with `layout` reading the key.
pub fn press(&mut self, layout: &Layout, keymap: &Keymap, press: &Press<'_>) -> Option<Hit> {
self.press_where(layout, keymap, press, &|_| true)
}
/// [`press`](Self::press) among the commands `accept` takes ([`Keymap::lookup_where`]): a binding of a refused
/// command (one disabled where the press lands) is passed over, and the press matches the next binding, in an outer
/// scope or of its next chord candidate, as if the refused one were not bound.
pub fn press_where(&mut self, layout: &Layout, keymap: &Keymap, press: &Press<'_>, accept: &dyn Fn(&CommandRef) -> bool) -> Option<Hit> {
let Press { input, repeat, now, active, outer } = *press;
let chords = Chords::of(layout, input)?;
let m = Match { keymap, active, outer, accept };
if repeat {
return chords.single(keymap, active, outer);
return chords.single(&m);
}
let first = chords.first();
let again = self
.last
.as_ref()
.is_some_and(|l| l.chord == first && !l.ran_double && l.panel.as_deref() == active.panel && now >= l.at && now - l.at < DOUBLE_PRESS);
let double = if again { chords.find(keymap, true, active, outer) } else { None };
let double = if again { chords.find(&m, true) } else { None };
self.last = Some(LastPress { chord: first, at: now, ran_double: double.is_some(), panel: active.panel.map(str::to_owned) });
double.or_else(|| chords.single(keymap, active, outer))
double.or_else(|| chords.single(&m))
}
/// The command a press of `input` runs on its own, as [`press`](Self::press) matches a press that completes no
/// double press: for a key that is held down rather than pressed now (a key automation holds). Keeps no state.
pub fn single(layout: &Layout, keymap: &Keymap, input: &KeyInput, active: &Active<'_>, outer: &[&str]) -> Option<Hit> {
Chords::of(layout, input)?.single(keymap, active, outer)
Chords::of(layout, input)?.single(&Match { keymap, active, outer, accept: &|_| true })
}
}
/// The chords one press can run, most specific first: the layout's candidates, then Delete and Backspace standing
/// for each other.
struct Chords(Vec<Chord>);
/// What one press is matched against: the keymap, what has the keyboard, the panels around it, and the commands the
/// press may run.
#[derive(Clone, Copy)]
struct Match<'a> {
keymap: &'a Keymap,
active: &'a Active<'a>,
outer: &'a [&'a str],
accept: &'a dyn Fn(&CommandRef) -> bool,
}
/// The chords one press can run, most specific first: the chord with the Shift the layout dropped kept (rule 3's
/// exception), the layout's candidates, then Delete and Backspace standing for each other.
struct Chords(Vec<Chord>, Chord);
impl Chords {
/// `None` when the press names no key.
fn of(layout: &Layout, input: &KeyInput) -> Option<Chords> {
let mut chords = layout.candidates(input);
chords.first()?;
let meant = chords.first().copied()?;
// Rule 3's exception (`layout` docs): where the layout dropped the Shift the person held for a symbol that
// needs it, the chord with Shift kept is tried first, so its binding wins over the dropped chord's. The press
// still means the dropped chord (a double press, `Hit::exact`).
if input.mods.shift && !meant.mods.shift && meant.key.is_symbol() {
let kept = Chord::new(input.mods, meant.key);
chords.retain(|chord| *chord != kept);
chords.insert(0, kept);
}
let twins: Vec<Chord> = chords
.iter()
.filter_map(|c| match c.key {
@@ -119,36 +145,37 @@ impl Chords {
})
.collect();
chords.extend(twins);
Some(Chords(chords))
Some(Chords(chords, meant))
}
/// The chord the press means ([`Layout::resolve`]).
fn first(&self) -> Chord {
self.0[0]
self.1
}
/// The first chord with a binding, pressed twice when `double`.
fn find(&self, keymap: &Keymap, double: bool, active: &Active<'_>, outer: &[&str]) -> Option<Hit> {
fn find(&self, m: &Match<'_>, double: bool) -> Option<Hit> {
let first = self.first();
self.0
.iter()
.find_map(|&chord| Hit::from_lookup(keymap.lookup_nested(&chord, double, active, outer), Trigger { chord, double }, chord == first))
self.0.iter().find_map(|&chord| {
Hit::from_lookup(m.keymap.lookup_where(&chord, double, m.active, m.outer, m.accept), Trigger { chord, double }, chord == first)
})
}
/// The single press's binding, else its Alt variant.
fn single(&self, keymap: &Keymap, active: &Active<'_>, outer: &[&str]) -> Option<Hit> {
self.find(keymap, false, active, outer).or_else(|| self.alt_variant(keymap, active, outer))
fn single(&self, m: &Match<'_>) -> Option<Hit> {
self.find(m, false).or_else(|| self.alt_variant(m))
}
/// Only when no binding owns the Alt chord itself, so a bound Alt chord runs its own command.
fn alt_variant(&self, keymap: &Keymap, active: &Active<'_>, outer: &[&str]) -> Option<Hit> {
fn alt_variant(&self, m: &Match<'_>) -> Option<Hit> {
let Match { keymap, active, outer, accept } = *m;
let (first, platform) = (self.first(), keymap.platform());
self.0.iter().filter(|c| c.mods.alt).find_map(|&chord| {
if active.typing && !keymap.typing_rule().fires(&chord, platform) {
return None;
}
let plain = Chord::new(Mods { alt: false, ..chord.mods }, chord.key);
match keymap.lookup_nested(&plain, false, &Active { typing: false, ..*active }, outer) {
match keymap.lookup_where(&plain, false, &Active { typing: false, ..*active }, outer, accept) {
Lookup::Run(command) if keymap.bindable(&command).is_some_and(|b| b.has_alt_variant) => {
Some(Hit { command, cycle: Vec::new(), trigger: Trigger { chord, double: false }, exact: chord == first, alt_variant: true })
}
+74
View File
@@ -61,6 +61,80 @@ pub fn assign(labels: &[&str], folder: &Folder) -> Vec<Option<(char, usize)>> {
out
}
/// The keytip badge of each `(label, requested badge)` in a bar, in three passes; `reserved` letters are never
/// assigned and no badge is a prefix of another.
///
/// 1. A requested badge is kept, in order, when it is typable (ASCII letters and digits, upper-cased in the folder's
/// language) and neither starts nor is the start of a badge already kept. It may use a reserved letter: the app
/// gives a control the letter of its own Alt shortcut.
/// 2. Every other label takes one letter: its `&` marked letter, else the first free letter of its text, word starts
/// first, else the first free letter of the alphabet. A letter is free when no badge uses it, it is not reserved,
/// and no kept badge of two or more letters starts with it.
/// 3. The labels left over get two letters. Their first letter is one no one-letter badge keeps (so typing it waits for
/// the second): the letters of the last one-letter badges of pass 2 are given up for this until the alphabet's
/// unreserved second letters cover the overflow, and those labels take two letters too, in label order.
///
/// A label gets an empty badge, which shows nothing, only when the alphabet cannot hold every label.
pub fn assign_keytips(labels: &[(&str, Option<&str>)], reserved: &[char], folder: &Folder) -> Vec<String> {
let turkic = folder.turkic();
let clashes = |a: &str, b: &str| a.starts_with(b) || b.starts_with(a);
let mut out: Vec<Option<String>> = vec![None; labels.len()];
// Pass 1: the badges the app asks for; one that clashes with an earlier kept badge is left to pass 2.
let mut kept: Vec<String> = Vec::new();
for ((_, requested), slot) in labels.iter().zip(&mut out) {
let Some(requested) = requested else { continue };
let typed: Option<String> = requested.chars().map(|c| letter(c, turkic)).collect();
let Some(typed) = typed.filter(|typed| !typed.is_empty()) else { continue };
if kept.iter().any(|earlier| clashes(earlier, &typed)) {
continue;
}
kept.push(typed.clone());
*slot = Some(typed);
}
// Pass 2: one letter from the label.
let mut blocked: Vec<char> = reserved.iter().filter_map(|&c| letter(c, turkic)).collect();
blocked.extend(out.iter().flatten().filter_map(|badge| badge.chars().next()));
let mut named: Vec<usize> = Vec::new();
let mut overflow: Vec<usize> = Vec::new();
for (at, (label, _)) in labels.iter().enumerate() {
if out[at].is_some() {
continue;
}
let (text, mark) = marked(label, folder);
let chosen = mark
.filter(|c| !blocked.contains(c))
.or_else(|| first_unused(&text, &blocked, turkic).map(|(c, _)| c))
.or_else(|| ('A'..='Z').find(|c| !blocked.contains(c)));
match chosen {
Some(c) => {
blocked.push(c);
out[at] = Some(c.to_string());
named.push(at);
}
None => overflow.push(at),
}
}
// Pass 3: two letters, whose first letter no one-letter badge keeps.
let reserved_keys: Vec<char> = reserved.iter().filter_map(|&c| letter(c, turkic)).collect();
let seconds: Vec<char> = ('A'..='Z').filter(|c| !reserved_keys.contains(c)).collect();
let mut firsts: Vec<char> = Vec::new();
let mut two = overflow;
while !two.is_empty() && firsts.len() * seconds.len() < two.len() {
let Some(at) = named.pop() else { break };
firsts.extend(out[at].take().and_then(|badge| badge.chars().next()));
two.push(at);
}
two.sort_unstable();
let mut pairs = firsts.iter().flat_map(|a| seconds.iter().map(move |b| format!("{a}{b}")));
for at in two {
out[at] = pairs.next();
}
out.into_iter().map(Option::unwrap_or_default).collect()
}
fn first_unused(text: &str, used: &[char], turkic: bool) -> Option<(char, usize)> {
let mut previous_alnum = false;
let mut starts = Vec::new();
+40
View File
@@ -218,6 +218,46 @@ fn the_alt_variant_follows_the_commands_key_and_yields_to_a_bound_alt_chord() {
assert!(hit(&km, &alt(Key::F2, false, false)).is_none(), "a command that did not opt in has no Alt variant");
}
/// A press passes over the binding of a command the caller refuses (one disabled where it lands): the chord's binding
/// in an outer scope runs instead, the lookup says the same, and with every holder refused the press runs nothing.
#[test]
fn a_refused_command_leaves_its_chord_to_the_next_binding() {
let km = Keymap::new(
vec![in_scope("view.zoomIn", "Canvas", &["Cmd+="]), app("format.subscript", &["Cmd+="])],
Scopes::new().with_panel("Canvas"),
Platform::Linux,
);
let input = KeyInput::new(Mods { cmd: true, ctrl: false, alt: false, shift: false }).with_physical(Key::Equals);
let active = Active::panel("Canvas");
let press = Press { input: &input, repeat: false, now: 0.0, active: &active, outer: &[] };
let hit = |accept: &dyn Fn(&CommandRef) -> bool| Matcher::new().press_where(&Layout::new(), &km, &press, accept).map(|hit| hit.command);
assert_eq!(hit(&|_| true), Some(cmd("view.zoomIn")), "the canvas's binding ranks first");
assert_eq!(hit(&|c| c.id != "view.zoomIn"), Some(cmd("format.subscript")), "refused, it leaves the chord to the app's binding");
assert_eq!(hit(&|_| false), None, "with every holder refused the press runs nothing");
let refused = |c: &CommandRef| c.id != "view.zoomIn";
assert_eq!(km.lookup_where(&chord("Cmd+="), false, &active, &[], &refused), Lookup::Run(cmd("format.subscript")));
let all = Matcher::new().press(&Layout::new(), &km, &press).map(|hit| hit.command);
assert_eq!(all, Some(cmd("view.zoomIn")), "a plain press accepts every command");
}
/// Rule 3's exception (lead ruling): on a layout where `=` is ⇧0 (German), Ctrl+Shift+0 types `=` with Shift held.
/// Rule 3 reads it as Ctrl+=, but when the keymap binds Ctrl+Shift+= that binding runs (Word's Superscript, not
/// Subscript), as the old app did; with Ctrl+Shift+= unbound the press is Ctrl+= as before. The layout's own reading,
/// which recording and claims use, keeps rule 3.
#[test]
fn a_held_shift_runs_the_shift_kept_binding_before_rule_3_drops_it() {
let shift_zero = KeyInput::new(Mods { cmd: true, ctrl: false, alt: false, shift: true }).with_typed(Key::Equals).with_physical(Key::Num0);
let ran = |defs: Vec<CommandDef>| {
let km = Keymap::new(defs, Scopes::new(), Platform::Linux);
let press = Press { input: &shift_zero, repeat: false, now: 0.0, active: &Active::NONE, outer: &[] };
Matcher::new().press(&Layout::new(), &km, &press).map(|hit| hit.command)
};
let both = vec![app("format.subscript", &["Cmd+="]), app("format.superscript", &["Cmd+Shift+="])];
assert_eq!(ran(both), Some(cmd("format.superscript")), "the Shift-kept binding wins");
assert_eq!(ran(vec![app("format.subscript", &["Cmd+="])]), Some(cmd("format.subscript")), "unbound, rule 3 holds");
assert_eq!(Layout::new().resolve(&shift_zero), Some(chord("Cmd+=")), "the press is still recorded as rule 3 reads it");
}
/// Tools that share a chord: within one group a press cycles through them, so each shows the chord; across groups the
/// first in catalog order runs, so only it shows the chord. `shown_chord` decides on catalog positions (#15493) and
/// must answer as the lookup does.
+517
View File
@@ -0,0 +1,517 @@
//! `Keytips`: the Alt and F10 key hints of a ribbon. Badges over its tabs and controls name the letters that pick a
//! tab or run a command, so the whole ribbon is reachable from the keyboard without moving focus off the document.
#[cfg(feature = "screen-testing")]
mod stories;
use std::sync::Arc;
use craft_behavior::{Insets, Metrics, Sense};
use craft_keymap::mnemonic::assign_keytips;
use craft_keymap::{Chord, CommandRef, Key, Mods};
use craft_ui::contract::{Common, Component, Cx, Focus as _, MeasureCx, MenuKey, NoValue, Outcome, PaintUi, Remember as _, Role, Styled as _};
use craft_ui::primitives::TextRun;
use craft_ui::runtime::commands::{self, FireSource};
use craft_ui::runtime::env::Label;
use craft_ui::runtime::overlay::{self, OpenFilter};
use craft_ui::runtime::{focus, inspect};
use craft_ui::style::{ComponentStyle, StateSet, Stateful, StyleCx, SurfaceLook, TextLook, TypeRole, UiTokens};
use egui::{Context, Id, Pos2, Rect, Response, Ui, Vec2};
/// Escape ends the keytips while they show.
const ESCAPE: Chord = Chord::plain(Key::Escape);
/// The look of the badges.
#[derive(Clone, Debug, PartialEq, ComponentStyle)]
#[non_exhaustive]
pub struct KeytipsStyle {
/// The room around a badge's letters; its top is also a badge's inset from its control's corner.
#[style(metrics)]
metrics: Metrics,
/// A badge: the accent fill, with the ring that parts it from the control under it. Not the component's root
/// surface, which would fill the whole area the keytips show over.
badge: SurfaceLook,
/// The badge letters.
#[style(text)]
text: TextLook,
}
/// What the keys are on.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
enum Phase {
/// No keytips: the ribbon works as without them.
#[default]
Off,
/// Badges over the tabs and the digit badges.
Tabs,
/// Badges over the controls of the shown tab.
Commands,
/// Partway through a host sequence, which shows no badges.
Sequence,
}
/// The keytips between passes: held interaction state, changed only in the pass that receives a key.
#[derive(Clone, Debug, Default)]
struct State {
phase: Phase,
/// The badge letters typed so far in this phase.
typed: String,
}
impl State {
fn active(&self) -> bool {
self.phase != Phase::Off
}
}
/// What completing a badge or a sequence does.
#[derive(Clone, Debug)]
enum Act {
/// Picks the tab of this badge, as the app gave it.
Tab(String),
/// Fires the command.
Fire(CommandRef),
}
/// Where a badge shows.
#[derive(Clone, Debug)]
enum Place {
/// On the element that stands for the access node of this id (a tab).
Tab(Id),
/// On the element bound to this command.
Command(CommandRef),
/// Nowhere: a host sequence.
Hidden,
}
/// A badge or sequence the keys can complete in a phase.
#[derive(Clone, Debug)]
struct Entry {
/// The letters, upper case.
badge: String,
act: Act,
place: Place,
}
/// What a key the keytips claimed means.
#[derive(Clone, Copy, Debug)]
enum Typed {
/// A badge or sequence letter.
Letter(char),
/// Alt with a tab badge's first letter.
Tab(char),
/// Escape.
Escape,
}
/// What a pass's keys did, reported by that pass only.
#[derive(Clone, Debug, Default)]
struct Reported {
tab: Option<String>,
fired: Option<CommandRef>,
}
/// Alt and F10 keytips with one- and two-letter badges ([`assign_keytips`]), placed at the rect of each element of
/// the given inspected-region records ([`Keytips::places`]) that has a tab's id or is bound to a control's command,
/// from this pass's records.
///
/// - A lone Alt tap or F10 shows the tab badges and the digit badges, and hides them again; Alt with a letter picks
/// the tab of that badge at once (the chord is claimed, so any other Alt+letter stays the app's shortcut). On macOS
/// only F10 opens them, since Option types characters there. Escape ends them, and so does a press anywhere: the
/// press does what it does.
/// - Typing a tab's badge reports the tab ([`KeytipsOutput::tab`]) and shows the badges of the controls the app
/// passes for it. Typing a control's or a digit's badge fires its command with `FireSource::Keytip` and ends the
/// keytips. After the first letter of a two-letter badge only the badges it can complete show.
/// - A letter a badge or a sequence can still need is claimed while the keytips show, so it never types into the
/// focused document, and the letters of one frame apply in the order they arrived; a letter no badge has is not
/// taken.
/// - Off while a text field or a shortcut recorder has focus (`focus::takes_letters`), under a modal layer, while the
/// window is in the background, and when the app passes `false` to [`Keytips::new`] because its window shows an in-window menu bar,
/// which takes Alt and F10 itself.
///
/// The badges paint in the layer of the `Ui` the keytips show in, over its whole clip rect, so the keytips show after
/// the ribbon, in a `Ui` that covers it and any other recorded region.
#[derive(craft_ui::contract::Component, craft_ui::contract::Props)]
#[must_use = "show the keytips with `show`"]
pub struct Keytips<'a> {
#[common]
common: Common,
/// The ribbon's tabs, each with its name, its badge letters and the id of its access node (a ribbon reports them in
/// `RibbonOutput::tab_ids`). A tab's badge shows on the element of the records that stands for that node
/// (`Element::node`), and [`KeytipsOutput::tab`] reports the badge.
#[prop]
tabs: &'a [(Label, &'a str, Id)],
/// The controls of the shown tab that get a badge, in the order they are shown: their badges come from their
/// labels and fixed letters ([`assign_keytips`]).
#[prop]
controls: &'a [KeytipControl<'a>],
/// Fixed letter sequences typed after Alt, each with the command it fires. They show no badge, start only on a
/// letter they lead with, and wait for their next letter until they are complete or Escape ends them.
#[prop]
sequences: &'a [(&'a str, CommandRef)],
/// The commands the digit badges fire, in order (a quick access toolbar's): the first nine take one digit, the
/// rest a leading zero and digits of one width, so no digit badge is the start of another.
#[prop]
digits: &'a [CommandRef],
/// Letters no assigned control badge may use: the letters the app's Alt+letter shortcuts take.
#[prop]
reserved: &'a [char],
/// The inspected-region records whose elements the badges are placed at: the ribbon's, and any other region the
/// app records (a quick access toolbar in the title bar).
#[prop]
places: &'a [Arc<inspect::Recorded>],
/// The state this pass ends with.
state: State,
/// Each badge of this pass with the rect of the control it sits on, in this component's layer.
badges: Vec<(Rect, String)>,
reported: Reported,
}
impl<'a> Keytips<'a> {
/// Keytips that react to the keys when `enabled`. An app that shows an in-window menu bar passes `false`: that
/// bar takes Alt and F10.
pub fn new(enabled: bool) -> Self {
let keytips = Keytips {
common: Common::new(),
tabs: &[],
controls: &[],
sequences: &[],
digits: &[],
reserved: &[],
places: &[],
state: State::default(),
badges: Vec::new(),
reported: Reported::default(),
};
craft_ui::contract::Props::enabled(keytips, enabled)
}
/// Shows the badges and reads the keys. Show it after the regions it places badges on, in a `Ui` that covers
/// them.
pub fn show_over(self, ui: &mut Ui) -> KeytipsOutput {
let area = ui.clip_rect().intersect(ui.ctx().content_rect());
craft_ui::contract::Show::show_at(self, ui, area)
}
/// The badges of the controls, in the order of `controls`; an empty badge shows nothing.
fn control_badges(&self, cx: &Cx<'_, Self>) -> Vec<String> {
let labels: Vec<(&str, Option<&str>)> = self.controls.iter().map(|control| (control.label, control.letters)).collect();
assign_keytips(&labels, self.reserved, &cx.env.folder())
}
/// Every badge and sequence the keys can complete in `phase`.
fn entries(&self, phase: Phase, controls: &[String]) -> Vec<Entry> {
let fire = |badge: String, command: &CommandRef, place: Place| Entry { badge, act: Act::Fire(command.clone()), place };
let sequences = move || self.sequences.iter().map(move |(keys, command)| fire(keys.to_ascii_uppercase(), command, Place::Hidden));
match phase {
Phase::Off => Vec::new(),
Phase::Tabs => {
let tabs = self.tabs.iter().map(|(_, badge, id)| Entry {
badge: badge.to_ascii_uppercase(),
act: Act::Tab((*badge).to_owned()),
place: Place::Tab(*id),
});
let count = self.digits.len();
let digits =
self.digits.iter().enumerate().map(|(index, command)| fire(digit_badge(index, count), command, Place::Command(command.clone())));
tabs.chain(digits).chain(sequences()).filter(|entry| !entry.badge.is_empty()).collect()
}
Phase::Commands => self
.controls
.iter()
.zip(controls)
.filter(|(_, badge)| !badge.is_empty())
.map(|(control, badge)| fire(badge.clone(), &control.command, Place::Command(control.command.clone())))
.collect(),
Phase::Sequence => sequences().collect(),
}
}
/// The letters the entries `state` leads to can still need, with their chords. All of them are claimed, not only
/// the next one: one frame can carry a whole badge, and the claim made by the pass before is the only thing that
/// keeps its letters from typing into the document.
fn needed(&self, state: &State, controls: &[String]) -> Vec<(char, Chord)> {
let mut keys: Vec<(char, Chord)> = Vec::new();
for entry in self.entries(state.phase, controls) {
let Some(rest) = entry.badge.strip_prefix(state.typed.as_str()) else { continue };
for letter in rest.chars() {
if keys.iter().any(|(known, _)| *known == letter) {
continue;
}
if let Some(key) = Key::from_char(letter) {
keys.push((letter, Chord::plain(key)));
}
}
}
keys
}
/// The Alt+letter chord of each tab's first badge letter, with the letter: they pick a tab at once. None on
/// macOS, where Option types characters.
fn tab_chords(&self, cx: &Cx<'_, Self>) -> Vec<(Chord, char)> {
if cx.env.shell().os.is_mac() {
return Vec::new();
}
self.tabs
.iter()
.filter_map(|(_, badge, _)| {
let letter = badge.chars().next()?.to_ascii_uppercase();
Some((Chord::new(Mods::ALT, Key::from_char(letter)?), letter))
})
.collect()
}
/// The letter `letter` typed in `state`. A complete badge or sequence acts and ends its phase; the start of one
/// waits for the next letter; a letter that leads nowhere changes nothing.
fn press(&mut self, state: &mut State, letter: char, controls: &[String], cx: &Cx<'_, Self>) {
let typed = format!("{}{letter}", state.typed);
let entries = self.entries(state.phase, controls);
if let Some(entry) = entries.iter().find(|entry| entry.badge == typed) {
match &entry.act {
Act::Tab(badge) => {
self.reported.tab = Some(badge.clone());
*state = State { phase: Phase::Commands, typed: String::new() };
}
Act::Fire(command) => {
if commands::fire(&cx.response.ctx, command.clone(), FireSource::Keytip) {
self.reported.fired = Some(command.clone());
}
*state = State::default();
}
}
return;
}
let leading: Vec<&Entry> = entries.iter().filter(|entry| entry.badge.starts_with(&typed)).collect();
if leading.is_empty() {
return;
}
// Only sequences go on from here: their hint stands in for the badges.
if leading.iter().all(|entry| matches!(entry.place, Place::Hidden)) {
state.phase = Phase::Sequence;
}
state.typed = typed;
}
/// The badges `state` shows, each at the rect of its element in the layer `layer`. An element takes one badge.
fn placed(&self, state: &State, controls: &[String], cx: &Cx<'_, Self>) -> Vec<(Rect, String)> {
let ctx = &cx.response.ctx;
let mut taken: Vec<(usize, usize)> = Vec::new();
let mut placed = Vec::new();
for entry in self.entries(state.phase, controls) {
if !entry.badge.starts_with(&state.typed) {
continue;
}
let found = match &entry.place {
Place::Hidden => None,
Place::Tab(id) => self.find(&taken, |element| element.node() == *id),
Place::Command(command) => self.find(&taken, |element| element.command.as_ref() == Some(command)),
};
let Some((region, index)) = found else { continue };
taken.push((region, index));
if let Some(rect) = self.places[region].rect_in(ctx, index, cx.response.layer_id) {
placed.push((rect, entry.badge));
}
}
placed
}
/// The first element of the records, in their order, that `matches` and has no badge yet: its region and index.
fn find(&self, taken: &[(usize, usize)], matches: impl Fn(&inspect::Element) -> bool) -> Option<(usize, usize)> {
self.places.iter().enumerate().find_map(|(region, recorded)| {
recorded
.elements
.iter()
.enumerate()
.find(|(index, element)| element.rect.is_positive() && !taken.contains(&(region, *index)) && matches(element))
.map(|(index, _)| (region, index))
})
}
}
/// The digit badge of the command at `index` of `count`: one digit for the first nine, then a leading zero and the
/// rest's number, all of one width (12 commands: `1`..`9`, `01`, `02`, `03`).
fn digit_badge(index: usize, count: usize) -> String {
if index < 9 {
(index + 1).to_string()
} else {
let width = count.saturating_sub(9).to_string().len();
format!("0{:0width$}", index - 8)
}
}
/// Whether the keytips stay off: a text field or a shortcut recorder has focus (the letters are typed; a document's
/// editor is neither, see `focus::takes_letters`), a modal layer is open, or the window is in the background.
fn suppressed(ctx: &Context) -> bool {
let typing = focus::focused_rec(ctx).is_some_and(|rec| focus::takes_letters(&rec.stop.keys));
typing || overlay::any_open(ctx, OpenFilter::Modal) || !ctx.input(|input| input.focused)
}
/// Where a badge with letters `text` across goes on the control at `control`: inside its top start corner when the
/// control is more than twice the badge's height, else centred on that corner, so it hangs into the gap beside a
/// compact control instead of covering its glyph. The badge is the letters in `padding`.
fn badge_rect(control: Rect, text: Vec2, padding: Insets, rtl: bool) -> Rect {
let height = text.y + padding.top + padding.bottom;
let size = Vec2::new((text.x + padding.start + padding.end).max(height), height);
let corner = if rtl { control.right_top() } else { control.left_top() };
if size.y * 2.0 > control.height() {
return Rect::from_center_size(corner, size);
}
let inset = padding.top;
let x = if rtl { corner.x - inset - size.x } else { corner.x + inset };
Rect::from_min_size(Pos2::new(x, corner.y + inset), size)
}
impl Component for Keytips<'_> {
const ROLE: Role = Role::None;
const PARTS: bool = false;
const STOPS: bool = false;
const INPUT: craft_behavior::Input = craft_behavior::Input::Display;
const SHOWS_LABEL: bool = false;
const OVERLAYS: bool = false;
type Style = KeytipsStyle;
type Output = KeytipsOutput;
fn style(cx: &StyleCx<'_>, _: KeytipsStyleKey) -> KeytipsStyle {
let colors = &cx.tokens.color;
let pad = cx.tokens.space.pad.chip;
let badge = SurfaceLook::new(Stateful::new(cx.color(colors.accent.solid)))
.radius(UiTokens::corner(cx.tokens.shape.radius.sm))
.border(Stateful::new(cx.color(colors.overlay.halo)), cx.tokens.stroke.thin);
KeytipsStyle {
metrics: Metrics::new().padding(Insets::new(pad, pad, pad, pad)),
badge,
text: TextLook::new(TypeRole::Caption, Stateful::new(cx.color(colors.text.on_accent))),
}
}
fn measure(&mut self, _: &MeasureCx<'_, Self>) -> Vec2 {
Vec2::ZERO
}
fn sense(&self) -> Sense {
Sense::empty()
}
/// The keys of this pass. Only the pass that receives the frame's input sees its menu keys and claimed chords, so
/// a second pass of the frame keeps the state the first one wrote and reports nothing new.
fn update(&mut self, cx: &mut Cx<'_, Self>) {
let ctx = cx.response.ctx.clone();
if !cx.resolved.enabled || suppressed(&ctx) {
*cx.memory::<State>() = State::default();
return;
}
// Alt+letter is a mnemonic of this bar only for the tab chords it claims: any other stays the app's shortcut.
cx.register_menu_bar_by_claim();
let before = cx.memory::<State>().clone();
let mut state = before.clone();
let controls = self.control_badges(cx);
for key in cx.take_menu_keys() {
if matches!(key, MenuKey::Focus) {
state = State { phase: if state.phase == Phase::Tabs { Phase::Off } else { Phase::Tabs }, typed: String::new() };
}
}
// The chords claimed for this frame are those the last pass claimed; they apply in the order they arrived.
let tab_chords = self.tab_chords(cx);
let mut keys: Vec<(Chord, Typed)> = tab_chords.iter().map(|(chord, letter)| (*chord, Typed::Tab(*letter))).collect();
if before.active() {
keys.extend(self.needed(&before, &controls).into_iter().map(|(letter, chord)| (chord, Typed::Letter(letter))));
keys.push((ESCAPE, Typed::Escape));
}
let chords: Vec<Chord> = keys.iter().map(|(chord, _)| *chord).collect();
while let Some(chord) = cx.take_first_claimed(&chords) {
match keys.iter().find(|(known, _)| *known == chord).map(|(_, typed)| *typed) {
Some(Typed::Letter(letter)) => self.press(&mut state, letter, &controls, cx),
Some(Typed::Escape) => state = State::default(),
Some(Typed::Tab(letter)) => {
// Alt with a tab's letter picks the tab at once; a badge that is no tab's leaves the keytips as they are.
let mut tried = State { phase: Phase::Tabs, typed: String::new() };
self.press(&mut tried, letter, &controls, cx);
if tried.phase != Phase::Tabs || !tried.typed.is_empty() {
state = tried;
}
}
None => {}
}
}
// A press ends the keytips, as a click anywhere does in a ribbon app; the press itself does what it does. The
// input of a pass is its own, so a second pass of the frame sees no press.
if state.active() && ctx.input(|input| input.pointer.any_pressed()) {
state = State::default();
}
for (chord, _) in &tab_chords {
cx.claim(*chord);
}
if state.active() {
for (_, chord) in self.needed(&state, &controls) {
cx.claim(chord);
}
cx.claim(ESCAPE);
}
self.badges = if state.phase == Phase::Sequence { Vec::new() } else { self.placed(&state, &controls, cx) };
*cx.memory::<State>() = state.clone();
self.state = state;
}
fn paint(&mut self, ui: &mut PaintUi<'_>, cx: &Cx<'_, Self>) {
let draw = ui.draw();
let style = cx.style;
let rtl = cx.env.direction().is_rtl();
let color = cx.resolve(&style.text.color);
let at_rest = StateSet::default();
for (control, badge) in &self.badges {
let run = TextRun::new(badge.clone()).role(style.text.role).color(color);
let layout = draw.layout(&run, f32::INFINITY);
let rect = badge_rect(*control, layout.size(), style.metrics.padding, rtl);
draw.surface_look(rect, &style.badge, &at_rest);
draw.galley(rect.center() - layout.size() / 2.0, &layout);
}
}
fn finish(self, cx: Cx<'_, Self>) -> KeytipsOutput {
let pending = (self.state.active() && !self.state.typed.is_empty()).then(|| self.state.typed.clone());
KeytipsOutput { tab: self.reported.tab, fired: self.reported.fired, pending, active: self.state.active(), response: cx.response.clone() }
}
}
/// A control that gets a keytip.
#[derive(Clone, Debug)]
#[non_exhaustive]
pub struct KeytipControl<'a> {
/// The control's command: its badge shows on the element of the records bound to it.
pub command: CommandRef,
/// The text the badge letters come from.
pub label: &'a str,
/// The letters the app fixes for the badge, when it does.
pub letters: Option<&'a str>,
}
impl<'a> KeytipControl<'a> {
/// A control firing `command`, its badge letters taken from `label` unless `letters` fixes them.
pub const fn new(command: CommandRef, label: &'a str, letters: Option<&'a str>) -> Self {
KeytipControl { command, label, letters }
}
}
/// What the keytips report for a pass. `tab` and `fired` come from the pass that received the key only.
#[derive(Clone, Debug)]
#[non_exhaustive]
pub struct KeytipsOutput {
/// The tab the keys chose, by its badge as the app gave it.
pub tab: Option<String>,
/// The command the keys fired; it went through the command queue with `FireSource::Keytip`.
pub fired: Option<CommandRef>,
/// The badge or sequence letters typed so far, while they wait for the next one.
pub pending: Option<String>,
/// Whether the keytips are showing.
pub active: bool,
/// The component's response, which every component output carries.
response: Response,
}
impl Outcome for KeytipsOutput {
type Value = NoValue;
fn response(&self) -> &Response {
&self.response
}
}
+113
View File
@@ -0,0 +1,113 @@
//! Stories of `Keytips` over a small recorded region: two tabs and the controls of one, shown with F10 and the keys
//! typed after it.
use std::sync::Arc;
use craft_theme::ControlSize;
use craft_ui::buttons::Button;
use craft_ui::contract::{CommandSet, Props as _, Show as _, ShowContainer as _};
use craft_ui::layout_components::{Row, Stack};
use craft_ui::runtime::commands::CommandRef;
use craft_ui::runtime::env::Label;
use craft_ui::runtime::inspect::{self, Recorded};
use craft_ui::testing::{Drive, Fixture, StoryData, StoryOutput, story};
use egui::{Id, Key, Modifiers, Ui};
use super::{KeytipControl, Keytips};
/// The id of the tab button named `name`.
fn tab_id(name: &str) -> Id {
Id::NULL.with(("story.keytips.tab", name))
}
/// The commands of the story's controls.
#[derive(Clone, Copy, Debug, PartialEq, Eq, CommandSet)]
#[command(prefix = "keytipsStory")]
#[non_exhaustive]
enum StoryCommand {
#[command(label = "Paste", modal = "always")]
Paste,
#[command(label = "Bold", modal = "always")]
Bold,
#[command(label = "Italic", modal = "always")]
Italic,
#[command(label = "Format Painter", modal = "always")]
FormatPainter,
#[command(label = "Find", modal = "always")]
Find,
}
/// The controls in the order they show, with the label their badge letters come from.
const CONTROLS: [(StoryCommand, &str); 5] = [
(StoryCommand::Paste, "Paste"),
(StoryCommand::Bold, "Bold"),
(StoryCommand::Italic, "Italic"),
(StoryCommand::FormatPainter, "Format Painter"),
(StoryCommand::Find, "Find"),
];
/// The tab row and the control row, recorded as one inspected region; its record, in a real run.
fn region(ui: &mut Ui, size: ControlSize) -> Option<Arc<Recorded>> {
let (_, recorded) = inspect::record(ui, Id::NULL.with("story.keytips"), |ui| {
Stack::new().show(ui, |ui, _| {
Row::new().show(ui, |ui, _| {
Button::new("Home").id(tab_id("Home")).show(ui);
Button::new("Insert").id(tab_id("Insert")).show(ui);
});
Row::new().show(ui, |ui, _| {
for (command, _) in CONTROLS {
Button::command(command).size(size).show(ui);
}
});
})
});
recorded
}
/// The region with its keytips: the controls of size `size`, each with the fixed badge `letters` gives it.
fn shown(ui: &mut Ui, size: ControlSize, letters: [Option<&'static str>; 5]) -> StoryOutput {
let places: Vec<Arc<Recorded>> = region(ui, size).into_iter().collect();
let tabs = [(Label::from("Home"), "H", tab_id("Home")), (Label::from("Insert"), "N", tab_id("Insert"))];
let controls: Vec<KeytipControl<'static>> =
CONTROLS.iter().zip(letters).map(|((command, label), letters)| KeytipControl::new(CommandRef::from(*command), label, letters)).collect();
let output = Keytips::new(true).tabs(&tabs).controls(&controls).places(&places).show_over(ui);
output.response.into()
}
/// F10 shows the tab badges.
fn open(fixture: &mut Fixture) {
fixture.settle();
fixture.key(Key::F10, Modifiers::NONE).settle();
}
/// The Home tab's badge shows its controls' badges.
fn open_home(fixture: &mut Fixture) {
open(fixture);
fixture.key(Key::H, Modifiers::NONE).settle();
}
/// The first letter of the two-letter badges leaves only theirs.
fn open_prefix(fixture: &mut Fixture) {
open_home(fixture);
fixture.key(Key::F, Modifiers::NONE).settle();
}
#[story(Keytips<'static>, covers = [Default], drive = Drive::Custom(open))]
fn keytips_tabs(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
shown(ui, ControlSize::Md, [None; 5])
}
#[story(Keytips<'static>, covers = [], drive = Drive::Custom(open_home))]
fn keytips_commands(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
shown(ui, ControlSize::Md, [None; 5])
}
#[story(Keytips<'static>, covers = [], drive = Drive::Custom(open_prefix))]
fn keytips_two_letter_prefix(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
shown(ui, ControlSize::Md, [None, None, None, Some("FP"), Some("FD")])
}
#[story(Keytips<'static>, covers = [], drive = Drive::Custom(open_home))]
fn keytips_compact(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
shown(ui, ControlSize::Sm, [None; 5])
}
+7
View File
@@ -101,6 +101,7 @@ mod documents;
mod driver;
mod help;
mod keymap;
mod keytips;
mod language;
mod layout;
mod modal;
@@ -110,6 +111,7 @@ mod theme;
pub mod mac;
pub mod ribbon;
pub mod shortcuts;
pub use bar::{EnglishHook, Labeled, MenuBarOutput, MenuBarUi};
@@ -119,6 +121,7 @@ pub use documents::DOCUMENT_COMMAND_PREFIX;
pub use driver::{Backend, ClipboardKeys, CommandHook, Dispatch, Event, Gate, NativeMenu, had_input};
pub use help::{HelpCommand, HelpLabels, HelpLink, HelpMenu};
pub use keymap::{ItemState, apply_keymap, apply_state};
pub use keytips::{KeytipControl, Keytips, KeytipsOutput};
pub use language::{LANGUAGE_COMMAND, LanguageChoice, LanguageLabels, LanguageMenu, LanguageRow};
pub use layout::{Clash, Layout, LayoutOptions, Target, desktop_layout, layout, mac_layout, web_layout};
pub use modal::{ModalRules, NAVIGATION_COMMANDS, PendingRule};
@@ -126,6 +129,10 @@ pub use model::{
Alternate, Builtin, Document, Item, ItemKind, ItemRole, Menu, MenuBar, MenuRole, Node, Platforms, Row, Standard, from_items, structure_key, tidy,
window_key,
};
pub use ribbon::{
Gallery, GalleryFace, GalleryItem, GalleryMore, GalleryOutput, GroupLevel, GroupWidths, Ribbon, RibbonGroup, RibbonMenuRequest, RibbonOutput,
RibbonRow, RibbonTab, plan,
};
pub use theme::{THEME_COMMAND, ThemeChoice, ThemeLabels, ThemeMenu, ThemeRow};
#[cfg(feature = "screen-testing")]
+594
View File
@@ -0,0 +1,594 @@
//! The ribbon: a tab strip over a scrolling row of command groups.
mod gallery;
mod group;
mod plan;
#[cfg(feature = "screen-testing")]
mod stories;
use std::borrow::Cow;
use std::fmt::Debug;
use std::hash::Hash;
use std::sync::Arc;
use craft_behavior::{CanvasTransform, EditEvent, IconId, Metrics, Mixed, SelectionChange, Sense, keyed};
use craft_keymap::CommandRef;
use craft_ui::buttons::IconButton;
use craft_ui::contract::overlay::Anchor;
use craft_ui::contract::{
Access, Bind, BodyCx, CollectionEvent, Common, Component, Container, ContainerProps, Cx, NoValue, Outcome, Props as _, Role, Scroll, Show as _,
ShowCollection as _, ShowContainer as _, Sizing, Trigger, clicked, scroll_step,
};
use craft_ui::layout_components::Row;
use craft_ui::menu::Menu;
use craft_ui::runtime::env::{Env, Label};
use craft_ui::runtime::inspect;
use craft_ui::runtime::memory::with_session;
use craft_ui::runtime::motion::{Animate as _, spec};
use craft_ui::style::{ComponentStyle, StyleCx};
use craft_ui::tabs::{StripEnd, Tab, TabKind, TabRole, TabStrip, TabStripOutput};
use egui::{Id, Pos2, Rect, Response, Ui, Vec2, vec2};
pub use craft_ui::buttons::{GroupLevel, RibbonLook};
pub use gallery::{Gallery, GalleryFace, GalleryItem, GalleryMore, GalleryOutput};
use group::BodyHeight;
pub use group::RibbonGroup;
pub use plan::{GroupWidths, plan};
type ContextMenuBody<'a> = &'a mut dyn FnMut(&mut Ui, &RibbonMenuRequest, &mut BodyCx<'_>);
craft_ui::words! {
/// The words of the ribbon's own controls.
struct RibbonWords {
scroll_left: "ribbon.scrollLeft" = "Scroll left";
scroll_right: "ribbon.scrollRight" = "Scroll right";
context_menu: "ribbon.contextMenu" = "Ribbon menu";
}
}
/// The ribbon: a [`TabKind::Ribbon`](craft_ui::tabs::TabKind) strip over a scrolling group row,
/// with minimise and a context menu. The strip and the row show inside one inspected region
/// (`inspect::record`), whose record ([`RibbonOutput::controls`]) gives each control's rect and
/// command, and [`RibbonOutput::tab_ids`] says which recorded element is which tab. On a tab change
/// the group row slides in from the side on which the new tab lies relative to the old one
/// (mirrored in right-to-left), through one `Tween`; with reduce motion the new content shows at
/// rest.
///
/// A context request (a secondary click, the Menu key or Shift+F10) on a tab, a control or the row's
/// background opens the ribbon's own menu, whose rows the app's [`context_menu`](Ribbon::context_menu)
/// body shows for that request. The ribbon holds the request while the menu is open, and focus goes back
/// where it was when the menu closes by key.
#[must_use = "show the ribbon with `show`"]
#[derive(craft_ui::contract::Pattern)]
#[pattern(probe(Ribbon<'static, usize>))]
pub struct Ribbon<'a, T: Clone + Eq + Hash + Send + Sync + Debug + 'static> {
label: Label,
tabs: &'a [RibbonTab<T>],
shown: Bind<'a, T>,
trailing: &'a [StripEnd<'a>],
minimised: Option<Bind<'a, bool>>,
/// The body of the context menu: the rows for the request that opened it.
context_menu: Option<ContextMenuBody<'a>>,
/// The icon sides of the groups' buttons.
icons: RibbonLook,
/// The icon of every group's dialog launcher.
launcher: IconId,
}
impl<'a, T: Clone + Eq + Hash + Send + Sync + Debug + 'static> Ribbon<'a, T> {
/// A ribbon named `label` over `tabs`, showing the tab `shown` binds.
pub fn new(label: impl Into<Label>, tabs: &'a [RibbonTab<T>], shown: Bind<'a, T>) -> Self {
Ribbon {
label: label.into(),
tabs,
shown,
trailing: &[],
minimised: None,
context_menu: None,
icons: RibbonLook::default(),
launcher: IconId::new("maximize_2"),
}
}
/// The rows of the ribbon's context menu. The ribbon opens its menu on a context request and runs `body` inside
/// it on every pass the menu is open, with the request that opened it: the command of the control it was on, or
/// none on a tab or the row's background. Without a body a context request opens nothing.
pub fn context_menu(mut self, body: &'a mut dyn FnMut(&mut Ui, &RibbonMenuRequest, &mut BodyCx<'_>)) -> Self {
self.context_menu = Some(body);
self
}
/// Items at the reading end of the tab strip, after the tabs.
pub fn trailing(mut self, items: &'a [StripEnd<'a>]) -> Self {
self.trailing = items;
self
}
/// Whether the group row is minimised, bound to the app's state. A double click on a tab toggles it through a
/// write-through binding.
pub fn minimised(mut self, minimised: Bind<'a, bool>) -> Self {
self.minimised = Some(minimised);
self
}
/// The key of the tab shown: the binding's, else the first tab's.
/// How the groups' controls look (`RibbonLook`): an app whose ribbon icons, menu arrows or small rows differ
/// from its other controls sets them here. The framework's look by default.
pub fn look(mut self, look: RibbonLook) -> Self {
self.icons = look;
self
}
/// The icon of every group's dialog launcher: an app's own glyph in place of the framework's.
pub fn launcher_icon(mut self, icon: IconId) -> Self {
self.launcher = icon;
self
}
fn current(&mut self) -> Option<T> {
let bound = self.shown.reborrow().get().and_then(|value| value.same().cloned());
bound.or_else(|| self.tabs.first().map(|tab| tab.key.clone()))
}
/// Shows the strip and the group row of the shown tab; `body` fills the row for that tab.
///
/// The tab a click picks comes back in [`RibbonOutput::shown`]; the app applies it to its own state. A request
/// the pass's input made (a context request, a double click) is taken in the pass that received that input: the
/// framework records it in that pass's real run only, so a second pass of the frame takes none. The context menu
/// it opened stays open on later passes until it closes.
pub fn show(mut self, ui: &mut Ui, mut body: impl FnMut(&mut RibbonRow<'_>, &T)) -> RibbonOutput<T> {
let current = self.current();
let minimised = self.minimised.as_mut().and_then(|bind| bind.reborrow().get()).and_then(|value| value.same().copied()).unwrap_or(false);
let id = ui.scope_id().with(self.label.as_str());
let tabs = self.tabs;
let trailing = self.trailing;
let icons = self.icons;
let launcher = self.launcher.clone();
let strip_label = self.label.clone();
let label_of = |key: &T| tabs.iter().find(|tab| tab.key == *key).map_or(Label::Empty, |tab| tab.label.clone());
let role_of = |key: &T| tabs.iter().find(|tab| tab.key == *key).map_or(TabRole::Standard, |tab| tab.role);
let ((strip, region), controls) = inspect::record(ui, id, |ui| {
let strip: Option<TabStripOutput<T>> = (!tabs.is_empty()).then(|| {
let keys: Vec<T> = tabs.iter().map(|tab| tab.key.clone()).collect();
let source = keyed(&keys, |key: &T| key.clone()).with_text(|key: &T| Cow::Owned(label_of(key).as_str().to_owned()));
let strip: TabStrip<'_, T> = TabStrip::new(strip_label).kind(TabKind::Ribbon).roles(role_of);
// PLAN: `TabStrip::trailing(&[StripEnd])` is rb.R3 (ribbon-w1) and is not in this tree yet; this call compiles once it lands.
let mut strip = strip.trailing(trailing);
if let Some(key) = current.clone() {
strip = strip.shown(key);
}
// The look reaches the strip too: its tabs' ink and underline (`RibbonLook::tabs`).
craft_ui::runtime::env::with_env(
ui,
|overrides| {
overrides.values.set(icons);
},
|ui| strip.show_items(ui, &source, &mut |key: &T, _| Tab::new(label_of(key)).role(role_of(key))),
)
});
let region = match (&current, minimised) {
(Some(key), false) => Some(craft_ui::runtime::env::with_env(
ui,
|overrides| {
overrides.values.set(icons);
},
|ui| show_row(ui, id, tabs, key, (icons, &launcher), &mut body),
)),
_ => None,
};
(strip, region)
});
let mut chosen: Option<T> = None;
let mut toggle = false;
let mut picked: Option<T> = None;
let mut asked: Option<(RibbonMenuRequest, Asker)> = None;
let mut strip_response: Option<Response> = None;
let mut tab_ids: Vec<(T, Id)> = Vec::new();
if let Some(strip) = strip {
for event in &strip.response.events {
match event {
CollectionEvent::Selection(SelectionChange::Set(keys)) => chosen = keys.last().cloned().or(chosen),
CollectionEvent::Activate(_) if strip.response.activation_clicks == 2 => toggle = true,
_ => {}
}
}
// Each tab the strip shows reports its access node in its row; a tab in the overflow menu has no row.
tab_ids = strip.response.shown.iter().map(|row| (row.key.clone(), row.id)).collect();
picked = strip.picked;
asked = strip.menu.map(|request| (RibbonMenuRequest { command: None, at: request.at }, Asker::Strip));
strip_response = Some(strip.response.response.clone());
}
if toggle && let Some(bind) = self.minimised.as_mut() {
let _ = bind.reborrow().apply(&EditEvent::set(Mixed::Same(minimised), !minimised, Arc::from("ribbon.minimise"), None));
}
if let Some(request) = region.as_ref().and_then(|region| row_request(region, controls.as_deref())) {
asked = Some((request, Asker::Row));
}
if let Some(body) = self.context_menu.take() {
let openers = Openers { strip: strip_response.as_ref(), row: region.as_ref().map(|region| &region.response) };
context_menu(ui, id, asked, openers, body);
}
let tabs_rect = strip_response.as_ref().map(|response| response.rect);
RibbonOutput { shown: chosen.or(current), picked, tab_ids, controls, tabs: tabs_rect }
}
}
/// Which of the ribbon's regions asked for its context menu: the menu hangs from that region's response.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Asker {
/// The tab strip, for a tab.
Strip,
/// The group row, for a control or its background.
Row,
}
/// The responses of this pass the ribbon's context menu can hang from; `None` for a region not shown.
struct Openers<'r> {
strip: Option<&'r Response>,
row: Option<&'r Response>,
}
/// The context menu the ribbon holds open: the request that opened it and the region that asked, and the frame the
/// ribbon last showed in. It is the menu's open-popup state, kept in the ribbon's own slot.
#[derive(Clone, Default)]
struct HeldMenu {
menu: Option<(RibbonMenuRequest, Asker)>,
frame: u64,
}
/// Shows the ribbon `id`'s context menu while it is open: `asked`, this pass's request, opens it (or moves it to the
/// new request), and `body` shows its rows. The menu hangs from this pass's response of the region that asked, at the
/// request's point; the held request goes when the menu closes or that region is not shown.
fn context_menu(
ui: &mut Ui,
id: Id,
asked: Option<(RibbonMenuRequest, Asker)>,
openers: Openers<'_>,
body: &mut dyn FnMut(&mut Ui, &RibbonMenuRequest, &mut BodyCx<'_>),
) {
let slot = id.with("context_menu");
let frame = ui.ctx().cumulative_frame_nr();
let held = with_session(ui.ctx(), slot, |held: &mut HeldMenu| {
// A frame without the ribbon closed its menu with it: the request must not open the menu again when the
// ribbon shows again.
if held.frame.saturating_add(1) < frame {
held.menu = None;
}
if asked.is_some() {
held.menu = asked;
}
held.frame = frame;
held.menu.clone()
});
let Some((request, asker)) = held else { return };
let opener = match asker {
Asker::Strip => openers.strip,
Asker::Row => openers.row,
};
let mut open = opener.is_some();
if let Some(opener) = opener {
let words = Env::of(ui).words::<RibbonWords>();
let shown = Menu::new(words.context_menu.clone())
.opened_by(opener, Trigger::Manual)
.anchor(Anchor::Point(request.at))
.open(Bind::bound(&mut open))
.show(ui, |ui, cx| body(ui, &request, cx));
if shown.output.closed.is_some() {
open = false;
}
}
if !open {
with_session(ui.ctx(), slot, |held: &mut HeldMenu| held.menu = None);
}
}
/// Shows the group row of the tab `key` in the region that senses its context requests. The row slides in from the
/// side the tab lies on relative to the tab shown before, and a row wider than the room scrolls, with an edge chevron
/// on each side that has groups out of view.
fn show_row<T: Clone + Eq + Hash + Send + Sync + Debug + 'static>(
ui: &mut Ui,
base: Id,
tabs: &[RibbonTab<T>],
key: &T,
(icons, launcher): (RibbonLook, &IconId),
body: &mut impl FnMut(&mut RibbonRow<'_>, &T),
) -> RegionOutput {
let place = tabs.iter().position(|tab| tab.key == *key).unwrap_or(0) as f32;
Region::new()
.show(ui, |ui, cx| {
// The tab's place is the tween: it starts at the previous tab's place, which the motion's memory holds, and
// the gap to the target is how far the row still has to travel, on the side the new tab lies on. Under
// reduce motion the tween is at its target at once, so the row shows at rest.
let gap = place - cx.anim("place", place, spec::MOVE);
let side = if cx.env.direction().is_rtl() { -1.0 } else { 1.0 };
let distance = cx.style::<Region>().map_or(0.0, |style| style.slide);
let lead = gap.clamp(-1.0, 1.0) * side * distance;
let chevron = cx.style::<Region>().map_or(0.0, |style| style.chevron);
// Rows a look sets stand a tight gap apart: three of them are the body's least height.
let least = match icons.row {
0 => cx.style::<Region>().map_or(0.0, |style| style.body),
row => 3.0 * f32::from(row) + 2.0 * craft_ui::contract::Gap::Tight.points(ui),
};
let title_line = cx.style::<Region>().map_or(0.0, |style| style.title);
let start = cx.style::<Region>().map_or(0.0, |style| style.start);
// The row moves through the slide container's own offset, which places its body on a layer of its own.
let shown = Region::slide(lead)
.show(ui, |ui, _| {
// The titles sit under the tallest content of the last pass; a change shows in the next frame.
let slot = base.with("ribbon.body");
let last = with_session(ui.ctx(), slot, |kept: &mut BodyHeight| kept.0);
let row = Row::new().scroll(Scroll::horizontal()).fill_width().show(ui, |ui, _| {
// The groups start a regular pad in from the row's start edge, as the old ribbon's did.
craft_ui::layout::place_in_flow(ui, Vec2::new(start, 0.0));
let mut row = RibbonRow {
ui,
base,
groups: Vec::new(),
body: last.max(least),
title_line,
tallest: 0.0,
icons,
launcher: launcher.clone(),
};
body(&mut row, key);
(row.groups, row.tallest)
});
let (groups, tallest) = row.inner.unwrap_or_default();
if tallest > 0.0 && (tallest - last).abs() >= 0.5 {
with_session(ui.ctx(), slot, |kept: &mut BodyHeight| kept.0 = tallest);
ui.ctx().request_repaint();
}
(row.output.id, row.output.rect, groups)
})
.inner;
if let Some((owner, view, groups)) = shown {
chevrons(ui, owner, view, &groups, chevron, lead);
}
})
.output
}
/// The edge chevrons of a row `view` whose `groups` do not all show: one at each edge that has a group past it, each
/// stepping the scrolling body `owner` by one group toward its side (`contract::scroll_step`). `view` and `groups` are
/// in the points of the row's layer, which the slide offsets by `lead`; the chevrons sit at the edges as they show.
/// `width` is a chevron's width.
fn chevrons(ui: &mut Ui, owner: Id, view: Rect, groups: &[Rect], width: f32, lead: f32) {
// Half a point past the edge counts as inside: less than a pixel shows at any scale.
let left = groups.iter().any(|group| group.min.x < view.min.x - 0.5);
let right = groups.iter().any(|group| group.max.x > view.max.x + 0.5);
let words = Env::of(ui).words::<RibbonWords>();
let edges = view.translate(vec2(lead, 0.0));
let size = Vec2::new(width, view.height());
for (on, right_side, icon, name) in
[(left, false, "chevron_left", words.scroll_left.clone()), (right, true, "chevron_right", words.scroll_right.clone())]
{
if !on {
continue;
}
let at =
if right_side { Rect::from_min_size(Pos2::new(edges.max.x - width, edges.min.y), size) } else { Rect::from_min_size(edges.min, size) };
let button = IconButton::new(IconId::new(icon)).label(name).focusable(false).show_at(ui, at);
if clicked(&button.response) {
scroll_step(ui.ctx(), owner, view, groups, right_side);
}
}
}
/// The context request of the group row, from the framework's requests of this pass: the deepest control of the
/// ribbon's record with a bound command that asked (a secondary click on it, or the Menu key or Shift+F10 while it
/// held focus), else the region itself when its background asked. A request on a tab is the strip's.
fn row_request(region: &RegionOutput, recorded: Option<&inspect::Recorded>) -> Option<RibbonMenuRequest> {
let control = recorded.and_then(|recorded| {
region
.requests
.iter()
.filter_map(|(asked, rect)| {
recorded
.elements
.iter()
.find(|element| element.id == *asked && element.part.is_none() && element.command.is_some())
.map(|element| (element, *rect))
})
.max_by_key(|(element, _)| element.depth)
});
match control {
Some((element, rect)) => Some(RibbonMenuRequest { command: element.command.clone(), at: rect.left_bottom() }),
None => region.own.map(|rect| RibbonMenuRequest { command: None, at: rect.left_bottom() }),
}
}
/// One tab of the ribbon.
pub struct RibbonTab<T> {
key: T,
label: Label,
role: TabRole,
}
impl<T> RibbonTab<T> {
/// A plain tab named `label` that `key` identifies.
pub fn new(key: T, label: impl Into<Label>) -> Self {
RibbonTab { key, label: label.into(), role: TabRole::Standard }
}
/// Makes the tab a contextual one: it shows only while its context is on.
pub fn contextual(mut self) -> Self {
self.role = TabRole::Contextual;
self
}
}
/// The row of groups the ribbon's body fills for the shown tab.
pub struct RibbonRow<'a> {
ui: &'a mut Ui,
/// The ribbon's id: each group's id is made under it, so it stays the same in every sweep of the row.
base: Id,
/// The rect of each group this run of the row showed, in order: the units the edge chevrons step by.
groups: Vec<Rect>,
/// The height under each open group's top at which its title row sits: the tallest content of the last pass.
body: f32,
/// The height of every group's title line, the launcher's side: one line of the caption role.
title_line: f32,
/// The tallest open group content of this run, every level the row measured included.
tallest: f32,
/// The icon sides of the groups' buttons (`Ribbon::icons`).
icons: RibbonLook,
/// The icon of every group's dialog launcher (`Ribbon::launcher_icon`).
launcher: IconId,
}
/// What the ribbon reports for a pass.
pub struct RibbonOutput<T> {
/// The tab shown after this pass.
pub shown: Option<T>,
/// The tab the user picked this pass.
pub picked: Option<T>,
/// Each tab shown this pass with the id of its access node, which its element in
/// [`controls`](RibbonOutput::controls) stands for (`Element::node`; a keytip's place); a tab in the overflow menu
/// has none.
pub tab_ids: Vec<(T, Id)>,
/// The inspected record of the strip and the row: each control's rect and command.
pub controls: Option<Arc<inspect::Recorded>>,
/// The tab row's rect this pass; `None` while no strip shows.
pub tabs: Option<Rect>,
}
/// A request for the ribbon's context menu, on a control, a tab or the row's background.
#[derive(Clone, Debug)]
#[non_exhaustive]
pub struct RibbonMenuRequest {
/// The command of the control the request is for, when it has one; none on a tab or the row's background.
pub command: Option<CommandRef>,
/// Where the menu opens.
pub at: Pos2,
}
impl RibbonMenuRequest {
/// A request for the menu of the control of `command`, if any, opening at `at`.
pub const fn new(command: Option<CommandRef>, at: Pos2) -> Self {
RibbonMenuRequest { command, at }
}
}
/// The style of the row's regions: the slide distance and the edge chevrons' width.
/// How opaque the raised surface lies over the chrome in a looks body fill: 60 %, the old ribbons band (249 over the
/// 240 bars of the light theme).
const BODY_LIFT: u8 = 153;
#[derive(Clone, Debug, PartialEq, ComponentStyle)]
struct RegionStyle {
#[style(metrics)]
metrics: Metrics,
/// How far the row travels as a tab change slides it in (`motion.slide`).
slide: f32,
/// The width of an edge chevron: a hit target's.
chevron: f32,
/// The least height of the group row's body, under which each group's title sits: three controls stacked with the
/// row gap between them, the ribbon's three rows of small buttons. Taller content lowers every title with it.
body: f32,
/// The height of a group's title line, directly under its body: one line of the caption role
/// (`typography.caption.line_height`), which the dialog launcher's square also takes.
title: f32,
/// The room before the first group (`space.pad.regular`), as the old ribbon kept it.
start: f32,
/// The body's own fill where the look asks for one (`RibbonLook::body`): the raised surface laid thinly
/// over the chrome (`BODY_LIFT`), a band lighter than the bars around it.
fill: Option<craft_ui::style::StyleColor>,
}
/// What a row region reports.
struct RegionOutput {
response: Response,
/// The region's own context request of this pass (a secondary click on its background), at this rect.
own: Option<Rect>,
/// Every context request of this pass made by the time the region finished, those of its controls among them.
requests: Vec<(Id, Rect)>,
}
impl Outcome for RegionOutput {
type Value = NoValue;
fn response(&self) -> &Response {
&self.response
}
fn unshown(response: Response) -> Option<Self> {
Some(RegionOutput { response, own: None, requests: Vec::new() })
}
}
/// A region of the group row: the outer one takes the ribbon's width, senses secondary presses on its surface and
/// reports the context requests of its controls (`Cx::context_requests`); the inner one (`slide`) shows the row
/// through its offset while a tab change slides it in.
#[derive(craft_ui::contract::Component, craft_ui::contract::Props)]
#[component(container, unregistered)]
struct Region {
#[common]
common: Common,
#[container]
props: ContainerProps,
/// Whether the region senses context presses on its surface.
senses: bool,
}
impl Region {
/// The outer region.
fn new() -> Self {
Region { common: Common::new(), props: ContainerProps::new().sizing(Sizing::FillWidth), senses: true }
}
/// The inner region, its body offset by `lead` along x.
fn slide(lead: f32) -> Self {
let props = ContainerProps::new().sizing(Sizing::FillWidth).transform(CanvasTransform::new(1.0, vec2(lead, 0.0)));
Region { common: Common::new(), props, senses: false }
}
}
impl Component for Region {
const ROLE: Role = Role::GROUP;
const ALT_ROLES: &'static [Role] = &[Role::None];
type Style = RegionStyle;
type Output = RegionOutput;
fn style(cx: &StyleCx<'_>, _: RegionStyleKey) -> RegionStyle {
let body = 3.0 * cx.control().height + 2.0 * cx.tokens.space.gap.row;
let title = cx.tokens.typography.caption.line_height;
RegionStyle {
metrics: Metrics::new(),
slide: cx.tokens.motion.slide as f32,
chevron: cx.tokens.size.hit.target,
body,
title,
start: cx.tokens.space.pad.regular,
fill: cx.env::<RibbonLook>().body.then(|| cx.color(cx.tokens.color.surface.raised.with_alpha(BODY_LIFT))),
}
}
fn sense(&self) -> Sense {
if self.senses { Sense::SURFACE | Sense::CONTEXT_CLICK } else { Sense::empty() }
}
/// The outer region paints the body's fill and its top and bottom rules where the look asks for them.
fn paint(&mut self, ui: &mut craft_ui::contract::PaintUi<'_>, cx: &Cx<'_, Self>) {
let Some(fill) = cx.style.fill.filter(|_| self.senses) else { return };
let draw = ui.draw();
draw.fill(&craft_ui::primitives::PaintShape::Rect(cx.rect, egui::CornerRadius::ZERO), fill);
for side in [craft_ui::primitives::RectSide::Top, craft_ui::primitives::RectSide::Bottom] {
draw.edge_rule(craft_ui::style::RuleKind::Divider, cx.rect, side);
}
}
/// The region only lays out the groups: it is no node of its own.
fn access(&self, access: &mut Access, _: &Cx<'_, Self>) {
access.role(Role::None);
}
fn finish(self, cx: Cx<'_, Self>) -> RegionOutput {
let requests = if self.senses { cx.context_requests() } else { Vec::new() };
let own = requests.iter().find(|(asked, _)| *asked == cx.id).map(|(_, rect)| *rect);
RegionOutput { response: cx.response.clone(), own, requests }
}
}
impl Container for Region {}
+723
View File
@@ -0,0 +1,723 @@
//! `Gallery`: an in-ribbon gallery with stepping and a More button.
//!
//! The gallery is one component: its parts are a tile per shown item and the column of up, down and More at the
//! reading end, so the tiles are one Tab stop with arrow keys between them. The first shown item is the component's
//! own memory; More opens through the component's overlay.
use std::hash::Hash;
use craft_behavior::{DisplayOrder, Flow, IconId, Insets, ItemSource, Metrics, NavShape, PartKey, Roving, Selection, SelectionChange, Sense};
use craft_keymap::{Chord, CommandRef, Key};
use craft_ui::buttons::IconButton;
use craft_ui::contract::{
Access, Bind, CollectionEvent, Common, Component, ContextMenuRequest, Cx, DisabledLook, Focus as _, MeasureCx, Name, NoValue, Outcome, Overlay,
OverlayUi, Overlays as _, PaintUi, PartsCx, Props as _, Remember as _, Role, SelectMode, SetPosition, ShowCollection as _, WordSetCx as _,
};
use craft_ui::display::{Picture, PictureSize};
use craft_ui::list::{ThumbAspect, ThumbSize};
use craft_ui::primitives::textures::{Revision, ThumbSource, Thumbnails};
use craft_ui::primitives::{ContentPainterCx, HAlign, PaintShape, TextRun};
use craft_ui::runtime::env::Label;
use craft_ui::runtime::focus::KeyUse;
use craft_ui::style::{ComponentStyle, Flags, FocusLook, StyleColor, StyleCx, TypeRole};
use craft_ui::tile_grid::{CaptionPlace, Tile, TileGrid};
use egui::{ColorImage, CornerRadius, Rect, Response, Ui, Vec2};
use super::GroupLevel;
#[cfg(feature = "screen-testing")]
mod stories;
const TILE: PartKey = PartKey::new("tile");
const UP: PartKey = PartKey::new("up");
const DOWN: PartKey = PartKey::new("down");
const MORE: PartKey = PartKey::new("more");
/// The keys the strip takes while it holds focus: Up and Down step the tiles as the chevrons do.
const STEP_KEYS: &[Chord] = &[Chord::plain(Key::Up), Chord::plain(Key::Down)];
craft_ui::words! {
/// The words of the in-ribbon gallery.
pub struct GalleryWords {
up: "gallery.up" = "Previous row";
down: "gallery.down" = "Next row";
more: "gallery.more" = "More";
}
}
/// An in-ribbon gallery of tiles with stepping and More. The tile count follows the group's
/// `GroupLevel`. `Image` faces draw from `Picture`'s store, which packs, so packed previews need
/// no other face.
///
/// - The strip shows `full` tiles at `GroupLevel::Full` and `compact` at `Compact`; a `Collapsed` group shows its
/// gallery in a popover at `Full`.
/// - The up and down buttons (and the Up and Down keys on the strip) move the shown tiles by the count shown; the
/// shown run never runs past the last full run, so no tile is empty, and it falls back when the items shrink.
/// - More opens the whole list as a grid, runs a command, or opens the app's own body.
/// - Each tile's picture is [`aspect`](Gallery::aspect) times as wide as the medium thumbnail is high (square unless
/// set), and with `CaptionPlace::Below` the tile names its item under the picture (a style gallery's 'Normal').
#[must_use = "show the gallery with `show`"]
#[derive(craft_ui::contract::Component, craft_ui::contract::Props)]
#[component(overlay, probe(Gallery<'static, usize>))]
pub struct Gallery<'a, K: Clone + Eq + Hash + Send + Sync + 'static> {
#[common]
common: Common,
items: &'a [GalleryItem<'a, K>],
current: Option<&'a K>,
full: u8,
compact: u8,
/// What the More button opens.
#[prop]
more: GalleryMore<'a>,
/// Whether one rounded frame holds the tiles and the buttons.
framed: bool,
/// Whether the buttons give way while every item shows.
spare_buttons: bool,
/// The width of each tile's picture as a multiple of its height, the medium thumbnail's (`size.thumb.md`): a wide
/// sample (a paragraph style's first letters) fills a wide tile instead of shrinking into a square one.
#[prop]
aspect: ThumbAspect,
/// The height of each tile's picture: a thumbnail size.
thumb_size: ThumbSize,
/// Where each tile shows its item's name: `CaptionPlace::Below` names it under the picture, in the caption role;
/// `None` (the default) and `Start` show no name. The name stays each tile's accessible name either way.
#[prop]
caption: CaptionPlace,
/// Each shown tile's rect.
laid: Vec<Rect>,
picked: Option<K>,
menu: Option<ContextMenuRequest<K>>,
}
/// The remembered state of a gallery while it is shown.
#[derive(Clone, Default)]
struct State {
/// The first item the strip shows.
start: usize,
}
/// The first item of the last full run: stepping never goes past it, so no tile of the strip is empty.
fn last_start(len: usize, visible: usize) -> usize {
len - len.min(visible)
}
impl<'a, K: Clone + Eq + Hash + Send + Sync + 'static> Gallery<'a, K> {
/// A gallery named `label` over `items`, with `current` marked. The counts of `tiles` are the caller's: a
/// gallery without them shows one tile per level.
pub fn new(label: impl Into<Label>, items: &'a [GalleryItem<'a, K>], current: Option<&'a K>) -> Self {
Gallery {
common: Common::new(),
items,
current,
full: 1,
compact: 1,
more: GalleryMore::Grid,
framed: false,
spare_buttons: false,
aspect: ThumbAspect::SQUARE,
thumb_size: ThumbSize::Medium,
caption: CaptionPlace::None,
laid: Vec::new(),
picked: None,
menu: None,
}
.label(label)
}
/// How many tiles show at the full and the compact level, each at least 1.
pub fn tiles(mut self, full: u8, compact: u8) -> Self {
self.full = full.max(1);
self.compact = compact.max(1);
self
}
/// One rounded frame on the raised surface around the tiles and the buttons, as the old Word-style ribbon drew
/// its Styles gallery.
pub fn framed(mut self) -> Self {
self.framed = true;
self
}
/// No up, down and More buttons while every item shows at the level: nothing is left to step to.
pub fn spare_buttons(mut self) -> Self {
self.spare_buttons = true;
self
}
/// The height of each tile's picture, a thumbnail size (`size.thumb.*`; medium unless set): a gallery whose
/// previews are small pages (a style set's title, heading and paragraph) takes the large size, so the pages read.
/// `ThumbSize::None` keeps the medium size: a gallery tile always shows its picture.
pub fn thumb(mut self, size: ThumbSize) -> Self {
self.thumb_size = if size == ThumbSize::None { ThumbSize::Medium } else { size };
self
}
/// Whether the tiles name their items under the pictures.
fn captioned(&self) -> bool {
self.caption == CaptionPlace::Below
}
/// The tiles the level shows at most.
fn visible(&self, level: GroupLevel) -> usize {
usize::from(if level == GroupLevel::Compact { self.compact } else { self.full }).max(1)
}
/// Whether the level shows the column of buttons.
fn buttons(&self, level: GroupLevel) -> bool {
!(self.spare_buttons && self.items.len() <= self.visible(level))
}
/// The room between a framed gallery's edge and its tiles; none without a frame.
fn inset(&self, style: &GalleryStyle) -> f32 {
if self.framed { style.inset } else { 0.0 }
}
/// The position of the current item.
fn current_at(&self) -> Option<usize> {
let key = self.current?;
self.items.iter().position(|item| item.key == *key)
}
/// The first shown item for `state` at `level`, clamped in the pass that reads the count so a shorter list never
/// shows an empty strip.
fn start_of(&self, state: &State, level: GroupLevel) -> usize {
state.start.min(last_start(self.items.len(), self.visible(level)))
}
fn sizes(&self, cx: &MeasureCx<'_, Self>) -> Sizes {
let words = cx.env.words::<GalleryWords>();
let button = cx.face(IconButton::new(IconId::new("more")).label(words.more.clone()));
Sizes { tile: cx.face(GalleryTile::blank(self.aspect, self.thumb_size, self.captioned())), button, gap: cx.gap() }
}
}
/// One tile of a gallery.
pub struct GalleryItem<'a, K> {
/// What the tile picks.
pub key: K,
/// The tile's name.
pub label: Label,
/// How the tile is drawn.
pub face: GalleryFace<'a>,
}
/// How a gallery tile is drawn. Each tile builds a `Picture` from its face when it shows.
#[non_exhaustive]
pub enum GalleryFace<'a> {
/// An image from `Picture`'s store, made again when `revision` changes.
#[non_exhaustive]
Image {
/// The store key.
key: u64,
/// The image's revision.
revision: Revision,
/// Makes the image.
image: &'a dyn Fn() -> ColorImage,
},
/// A rendered thumbnail.
#[non_exhaustive]
Rendered {
/// The thumbnail key.
key: u64,
/// The thumbnail store.
thumbnails: &'a Thumbnails<u64>,
/// What renders the thumbnail.
source: &'a dyn ThumbSource<u64>,
},
/// A tile painted directly.
Paint(&'a dyn Fn(&ContentPainterCx, Rect)),
}
/// The size every tile's picture has, `size` high and `aspect` times as wide, so a tile measures the same with and
/// without its picture.
fn thumb(picture: Picture<'_>, aspect: ThumbAspect, size: ThumbSize) -> Picture<'_> {
picture.extent(PictureSize::Thumb(size)).aspect(aspect)
}
/// A picture that paints nothing, for measuring a tile.
fn blank_picture(aspect: ThumbAspect, size: ThumbSize) -> Picture<'static> {
thumb(Picture::painter(Label::default(), aspect, |_: &ContentPainterCx<'_>, _: Rect| {}), aspect, size)
}
impl<'a> GalleryFace<'a> {
/// An image from `Picture`'s store under `key`, made by `image` again when `revision` changes.
pub fn image(key: u64, revision: Revision, image: &'a dyn Fn() -> ColorImage) -> Self {
GalleryFace::Image { key, revision, image }
}
/// A thumbnail under `key`, rendered by `source` into `thumbnails`.
pub fn rendered(key: u64, thumbnails: &'a Thumbnails<u64>, source: &'a dyn ThumbSource<u64>) -> Self {
GalleryFace::Rendered { key, thumbnails, source }
}
/// The picture this face shows, `size` high and `aspect` times as wide. It is decoration: the tile that holds it
/// carries the name.
fn picture(&self, aspect: ThumbAspect, size: ThumbSize) -> Picture<'a> {
let picture = match self {
GalleryFace::Image { key, revision, image } => Picture::new(Label::default(), *key, *image).revision(*revision),
GalleryFace::Rendered { key, thumbnails, source } => Picture::rendered(Label::default(), *key, thumbnails, *source),
GalleryFace::Paint(paint) => {
let paint = *paint;
Picture::painter(Label::default(), aspect, move |cx: &ContentPainterCx<'_>, rect: Rect| paint(cx, rect))
}
};
thumb(picture, aspect, size)
}
}
/// What the More button of a gallery opens.
#[non_exhaustive]
pub enum GalleryMore<'a> {
/// A grid of every tile.
Grid,
/// The command that opens the app's own surface.
Command(CommandRef),
/// The app's menu body.
Body(&'a mut dyn FnMut(&mut Ui)),
}
/// What a gallery reports for a pass.
#[non_exhaustive]
pub struct GalleryOutput<K> {
/// The tile picked this pass.
pub picked: Option<K>,
/// A context menu was asked for on a tile: a secondary click, the Menu key or Shift+F10.
pub menu: Option<ContextMenuRequest<K>>,
/// The gallery's response.
// PLAN: S-L214 drops this field, but `Outcome` (the component output's bound) reads the response through it.
pub response: Response,
}
impl<K> Outcome for GalleryOutput<K> {
type Value = NoValue;
fn response(&self) -> &Response {
&self.response
}
}
// ---------------------------------------------------------------------------------------------------------------
// The More grid.
/// The items of the More grid, keyed by their position.
struct Indexes(usize);
impl DisplayOrder<usize> for Indexes {
fn len(&self) -> usize {
self.0
}
fn key(&self, at: usize) -> usize {
at
}
fn index_of(&self, key: &usize) -> Option<usize> {
(*key < self.0).then_some(*key)
}
}
impl ItemSource<usize> for Indexes {}
/// What the More grid reports: the picked item and the item a menu was asked for, by position.
#[derive(Default)]
struct GridResult {
picked: Option<usize>,
menu: Option<(usize, egui::Pos2)>,
}
/// The whole list as a grid of the same faces; a click or Enter picks, and a context request is forwarded. The
/// grid sizes its columns from the room it is given.
fn grid<K>(ui: &mut Ui, label: &Label, items: &[GalleryItem<'_, K>], current: Option<usize>, aspect: ThumbAspect, size: ThumbSize) -> GridResult {
let selection = Selection::new(current.into_iter().collect(), current, current);
let grid = TileGrid::<usize>::new(label.clone()).select(SelectMode::Single).selection(Bind::given(selection));
let out = grid.show_items(ui, &Indexes(items.len()), &mut |key, _| match items.get(*key) {
Some(item) => Tile::new(item.label.clone()).picture(aspect, item.face.picture(aspect, size)),
None => Tile::new(Label::default()),
});
let mut result = GridResult::default();
for event in out.response.events {
match event {
CollectionEvent::Activate(key) => result.picked = Some(key),
CollectionEvent::Selection(SelectionChange::Set(keys)) => {
if let Some(key) = keys.last() {
result.picked = Some(*key);
}
}
CollectionEvent::ContextMenu(request) => result.menu = Some((request.key, request.at)),
_ => {}
}
}
result
}
// ---------------------------------------------------------------------------------------------------------------
// The tile.
/// The style of a gallery tile: the theme's selection fill and edge while it is the current one.
#[derive(Clone, Debug, PartialEq, ComponentStyle)]
#[non_exhaustive]
struct GalleryTileStyle {
#[style(metrics)]
metrics: Metrics,
#[style(focus)]
focus: FocusLook,
/// Between the tile's edge and its picture.
pad: f32,
/// The selection edge's width.
stroke: f32,
/// The current tile's fill.
fill: StyleColor,
/// The current tile's edge.
edge: StyleColor,
/// The ink of the item's name under the picture, in a captioned gallery.
caption: StyleColor,
/// Between the picture and the caption.
gap: f32,
/// The picture's height at each thumbnail size, small, medium and large (`size.thumb.sm`, `md`, `lg`), as `thumb`
/// sizes it.
thumbs: [f32; 3],
}
impl GalleryTileStyle {
/// The picture's height at `size`.
fn thumb(&self, size: ThumbSize) -> f32 {
let [small, medium, large] = self.thumbs;
match size {
ThumbSize::Small => small,
ThumbSize::Large => large,
_ => medium,
}
}
}
/// The face a tile part wears: its picture, and in a captioned gallery the item's name under it, inside the tile's
/// selection look.
#[derive(craft_ui::contract::Component)]
#[component(unregistered)]
struct GalleryTile<'a> {
#[common]
common: Common,
/// The picture shown; a tile with none only has its size.
picture: Option<Picture<'a>>,
/// Whether the tile is the gallery's current item.
selected: bool,
/// The width of the picture as a multiple of its height.
aspect: ThumbAspect,
/// The picture's height, a thumbnail size.
thumb_size: ThumbSize,
/// The item's name under the picture; `None` in a gallery without captions.
caption: Option<Label>,
}
impl<'a> GalleryTile<'a> {
/// A tile that shows `picture`, `size` high and `aspect` times as wide, with `caption` under it when set.
fn of(picture: Picture<'a>, selected: bool, aspect: ThumbAspect, size: ThumbSize, caption: Option<Label>) -> Self {
GalleryTile { common: Common::new(), picture: Some(picture), selected, aspect, thumb_size: size, caption }
}
/// A tile with no picture, for measuring; a `captioned` one keeps a line for its caption.
fn blank(aspect: ThumbAspect, size: ThumbSize, captioned: bool) -> Self {
GalleryTile { common: Common::new(), picture: None, selected: false, aspect, thumb_size: size, caption: captioned.then(Label::default) }
}
}
/// The caption's type role.
const CAPTION: TypeRole = TypeRole::Caption;
impl Component for GalleryTile<'_> {
const DISABLED: DisabledLook = DisabledLook::Faded;
const ROLE: Role = Role::IMAGE;
const PARTS: bool = false;
const OVERLAYS: bool = false;
const SHOWS_LABEL: bool = false;
type Style = GalleryTileStyle;
type Output = Response;
fn style(cx: &StyleCx<'_>, _: GalleryTileStyleKey) -> GalleryTileStyle {
let colors = &cx.tokens.color;
let pad = cx.tokens.space.pad.chip;
GalleryTileStyle {
metrics: Metrics::new().padding(Insets::new(pad, pad, pad, pad)),
focus: cx.focus_look(),
pad,
stroke: cx.tokens.stroke.thin,
fill: cx.color(colors.state.selected),
edge: cx.color(colors.line.control_edge),
caption: cx.color(colors.text.normal),
gap: cx.tokens.space.gap.tight,
thumbs: [cx.tokens.size.thumb.sm, cx.tokens.size.thumb.md, cx.tokens.size.thumb.lg],
}
}
/// The picture, and in a captioned gallery the gap and one caption line under it. The caption is as wide as the
/// picture: a longer name elides.
fn measure(&mut self, cx: &MeasureCx<'_, Self>) -> Vec2 {
let picture = cx.face(blank_picture(self.aspect, self.thumb_size));
match self.caption {
Some(_) => {
let line = cx.layout(&TextRun::new("Ag").role(CAPTION)).size().y;
Vec2::new(picture.x, picture.y + cx.style.gap + line)
}
None => picture,
}
}
fn paint(&mut self, ui: &mut PaintUi<'_>, cx: &Cx<'_, Self>) {
let area = cx.content_rect;
if area.width() <= 0.0 || area.height() <= 0.0 {
return;
}
if self.selected {
let outer = area.expand(cx.style.pad);
let draw = ui.draw();
draw.fill(&PaintShape::Rect(outer, CornerRadius::ZERO), cx.style.edge);
draw.fill(&PaintShape::Rect(outer.shrink(cx.style.stroke), CornerRadius::ZERO), cx.style.fill);
}
// A captioned tile keeps the picture's height at the top and shows the name in the rest under it.
let (area, caption) = match self.caption {
Some(_) => {
let picture = Rect::from_min_size(area.min, Vec2::new(area.width(), cx.style.thumb(self.thumb_size).min(area.height())));
let top = (picture.max.y + cx.style.gap).min(area.max.y);
(picture, Some(Rect::from_min_max(egui::pos2(area.min.x, top), area.max)))
}
None => (area, None),
};
if let Some(picture) = self.picture.take() {
let _ = ui.child("picture", area, picture);
}
if let (Some(rect), Some(name)) = (caption, self.caption.as_ref()) {
let run = TextRun::new(name.as_str()).role(CAPTION).color(cx.style.caption).align(HAlign::Center).elide();
let _ = ui.draw().text(rect, &run);
}
}
fn finish(self, cx: Cx<'_, Self>) -> Response {
cx.response.clone()
}
}
// ---------------------------------------------------------------------------------------------------------------
// The gallery's component.
/// The style of the gallery: the gap between its tiles.
#[derive(Clone, Debug, PartialEq, ComponentStyle)]
#[non_exhaustive]
pub struct GalleryStyle {
#[style(metrics)]
metrics: Metrics,
/// A framed gallery's fill, edge and corner radius.
frame: (StyleColor, StyleColor, f32),
/// The room inside a frame.
inset: f32,
}
/// The sizes the gallery's faces measure.
struct Sizes {
tile: Vec2,
button: Vec2,
gap: f32,
}
impl<K: Clone + Eq + Hash + Send + Sync + 'static> Component for Gallery<'_, K> {
const ROLE: Role = Role::RADIO_GROUP;
type Style = GalleryStyle;
type Output = GalleryOutput<K>;
fn style(cx: &StyleCx<'_>, _: GalleryStyleKey<K>) -> GalleryStyle {
let colors = &cx.tokens.color;
GalleryStyle {
metrics: Metrics::new().gap(cx.tokens.space.gap.inline),
frame: (cx.color(colors.surface.raised), cx.color(colors.line.control_edge), cx.tokens.shape.radius.control),
inset: cx.tokens.space.gap.inline,
}
}
fn keys(&self) -> KeyUse {
Self::KEYS.with_claims(STEP_KEYS)
}
/// The room for every tile of the level, so the gallery keeps its width while the last run shows fewer, and the
/// column of three buttons.
fn measure(&mut self, cx: &MeasureCx<'_, Self>) -> Vec2 {
let sizes = self.sizes(cx);
let level = cx.env.get::<GroupLevel>();
let slots = self.visible(level) as f32;
let tiles = slots * sizes.tile.x + (slots - 1.0).max(0.0) * sizes.gap;
let inner = if self.buttons(level) {
Vec2::new(tiles + sizes.gap + sizes.button.x, sizes.tile.y.max(3.0 * sizes.button.y))
} else {
Vec2::new(tiles, sizes.tile.y)
};
// The frame takes room at the sides only: the tiles and buttons already keep their own room above and below.
inner + Vec2::new(2.0 * self.inset(cx.style), 0.0)
}
fn sense(&self) -> Sense {
Sense::HOVER
}
/// Places the tiles from the start edge and the column of buttons at the end edge, and declares them as one
/// roving group in reading order. Which items the tiles hold follows the remembered step, which `update`, `paint`
/// and `access` read; the part set depends only on the count.
fn parts(&mut self, rect: Rect, cx: &mut PartsCx<'_, Self>) {
let sizes = self.sizes(cx);
let level = cx.env.get::<GroupLevel>();
let shown = self.visible(level).min(self.items.len());
let buttons = self.buttons(level);
let rect = rect.shrink2(Vec2::new(self.inset(cx.style), 0.0));
let (column, rest) = Flow::new(rect, cx.flow.is_rtl()).take_end(if buttons { sizes.button.x } else { 0.0 });
self.laid.clear();
for at in 0..shown {
let cell = rest.span(at as f32 * (sizes.tile.x + sizes.gap), sizes.tile.x);
self.laid.push(cell);
cx.part(TILE.at(at as u64), cell).sense(Sense::CLICK | Sense::FOCUS).focusable();
}
let height = column.height() / 3.0;
let cell = |at: usize| Rect::from_min_size(column.min + Vec2::new(0.0, at as f32 * height), Vec2::new(column.width(), height));
for (at, key) in [UP, DOWN, MORE].into_iter().enumerate().filter(|_| buttons) {
let part = cx.part(key, cell(at)).sense(Sense::CLICK | Sense::FOCUS).focusable();
if key == MORE && !matches!(self.more, GalleryMore::Command(_)) {
part.toggles("more");
}
}
cx.roving(Roving::new(NavShape::Flat));
}
/// The gallery joins the body's roving group; a click or the activation key on a tile picks it, on a chevron
/// steps, and on More fires the command (a surface of its own opens through the part's toggle). Up and Down on the
/// strip step as the chevrons do. A pass applies only its own input, so a second pass of the frame steps nothing.
fn update(&mut self, cx: &mut Cx<'_, Self>) {
cx.join_roving();
let level = cx.env.get::<GroupLevel>();
let visible = self.visible(level);
let len = self.items.len();
let last = last_start(len, visible);
let start = self.start_of(cx.memory::<State>(), level);
for at in 0..visible.min(len) {
if cx.part_activated(TILE.at(at as u64)).is_some()
&& let Some(item) = self.items.get(start + at)
{
self.picked = Some(item.key.clone());
}
}
let (up_key, down_key) = (cx.take_claimed(STEP_KEYS[0]), cx.take_claimed(STEP_KEYS[1]));
let up = cx.part_activated(UP).is_some() || up_key;
let down = cx.part_activated(DOWN).is_some() || down_key;
if let Some(source) = cx.part_activated(MORE)
&& let GalleryMore::Command(command) = &self.more
{
cx.fire(command.clone(), source);
}
let mut next = start;
if up {
next = start.saturating_sub(visible);
}
if down {
next = (start + visible).min(last);
}
cx.memory::<State>().start = next;
}
/// The whole list as a grid of the same faces, an app's own body, or nothing for a command.
fn overlay(&mut self, ui: &mut OverlayUi<'_>, cx: &mut Cx<'_, Self>) {
// The More part registers the popup (`toggles`); a gallery whose buttons gave way has none to show.
if matches!(self.more, GalleryMore::Command(_)) || !self.buttons(cx.env.get::<GroupLevel>()) {
return;
}
let popup = cx.popup("more");
let name = cx.label();
let (items, current, aspect, size) = (self.items, self.current_at(), self.aspect, self.thumb_size);
let more = &mut self.more;
let shown = ui.show(popup, Overlay::popover(), |ui, _| match more {
GalleryMore::Body(body) => {
(**body)(ui);
GridResult::default()
}
_ => grid(ui, &name, items, current, aspect, size),
});
let Some(result) = shown else { return };
if let Some(item) = result.picked.and_then(|at| items.get(at)) {
self.picked = Some(item.key.clone());
popup.close(cx);
}
if let Some((at, point)) = result.menu
&& let Some(item) = items.get(at)
{
self.menu = Some(ContextMenuRequest::new(item.key.clone(), point));
}
}
/// Each tile is a radio button named by its label with its place in the whole list and checked while it is the
/// current item; the column's buttons are named by the gallery's words.
fn access(&self, access: &mut Access, cx: &Cx<'_, Self>) {
let words = cx.words::<GalleryWords>();
let level = cx.env.get::<GroupLevel>();
let start = self.start_of(&cx.recall::<State>(), level);
let current = self.current_at();
for at in 0..self.visible(level).min(self.items.len()) {
let Some(item) = self.items.get(start + at) else { continue };
let node = access.node(TILE.at(at as u64), Role::RADIO_BUTTON);
node.name = Name::Text(item.label.as_str().to_owned());
node.position = Some(SetPosition::new(start + at).of(self.items.len()));
if current == Some(start + at) {
node.flags |= Flags::CHECKED;
}
}
if !self.buttons(level) {
return;
}
access.node(UP, Role::BUTTON).name = Name::Text(words.up.as_str().to_owned());
access.node(DOWN, Role::BUTTON).name = Name::Text(words.down.as_str().to_owned());
access.node(MORE, Role::BUTTON).name = Name::Text(words.more.as_str().to_owned());
}
fn paint(&mut self, ui: &mut PaintUi<'_>, cx: &Cx<'_, Self>) {
let words = cx.words::<GalleryWords>();
let level = cx.env.get::<GroupLevel>();
let visible = self.visible(level);
let len = self.items.len();
let last = last_start(len, visible);
let start = self.start_of(&cx.recall::<State>(), level);
let current = self.current_at();
if self.framed {
let (fill, edge, radius) = cx.style.frame;
let shape = PaintShape::Rect(cx.rect, CornerRadius::same(radius.round().clamp(0.0, 255.0) as u8));
let draw = ui.draw();
draw.fill(&shape, fill);
draw.stroke(&shape, craft_ui::primitives::StrokeWidth::Thin, edge);
}
for at in 0..visible.min(len) {
if let Some(item) = self.items.get(start + at) {
let caption = self.captioned().then(|| item.label.clone());
let tile = GalleryTile::of(
item.face.picture(self.aspect, self.thumb_size),
current == Some(start + at),
self.aspect,
self.thumb_size,
caption,
);
ui.face(TILE.at(at as u64), tile);
}
}
if !self.buttons(level) {
return;
}
ui.face(UP, IconButton::new(IconId::new("chevron_up")).label(words.up.clone()).enabled(start > 0));
ui.face(DOWN, IconButton::new(IconId::new("chevron_down")).label(words.down.clone()).enabled(start < last));
ui.face(MORE, IconButton::new(IconId::new("more")).label(words.more.clone()));
}
/// The context request is recorded after `update`, so `finish` reads it: a secondary click on a tile, or the Menu
/// key or Shift+F10 with a tile active, from the tile's bottom start corner. A request from the More grid, made in
/// `overlay`, wins.
fn finish(self, cx: Cx<'_, Self>) -> GalleryOutput<K> {
let start = self.start_of(&cx.recall::<State>(), cx.env.get::<GroupLevel>());
let menu = self.menu.or_else(|| {
let part = cx.context_part().filter(|part| part.key == TILE)?;
let at = usize::try_from(part.index?).ok()?;
let item = self.items.get(start + at)?;
Some(ContextMenuRequest::new(item.key.clone(), self.laid.get(at)?.left_bottom()))
});
GalleryOutput { picked: self.picked, menu, response: cx.response.clone() }
}
}
+184
View File
@@ -0,0 +1,184 @@
//! Stories of the in-ribbon gallery.
use std::sync::Arc;
use craft_host::InlineJobs;
use craft_ui::contract::Show as _;
use craft_ui::list::{ThumbAspect, ThumbSize};
use craft_ui::primitives::textures::Revision;
use craft_ui::primitives::{FakeThumbSource, ThumbnailOptions, Thumbnails};
use craft_ui::runtime::env::{Label, with_env};
use craft_ui::testing::pictures::sample_picture;
use craft_ui::testing::{Drive, Fixture, StoryData, StoryOutput, story};
use craft_ui::tile_grid::CaptionPlace;
use egui::Ui;
use super::{Gallery, GalleryFace, GalleryItem, GalleryMore};
use crate::ribbon::GroupLevel;
type Paint = Box<dyn Fn(&craft_ui::primitives::ContentPainterCx, egui::Rect)>;
/// How many tiles every story's gallery holds: more than a row at either level.
const COUNT: usize = 10;
/// The gallery of `items` with the third one current, six tiles in a row at the full level and three at the compact.
fn show(ui: &mut Ui, items: &[GalleryItem<'_, usize>]) -> StoryOutput {
let current = 2;
Gallery::new("Styles", items, Some(&current)).tiles(6, 3).show(ui).into()
}
/// The name of tile `at`.
fn name(at: usize) -> Label {
Label::from(format!("Style {}", at + 1))
}
/// A gallery of pictures from `Picture`'s store, one of the stories' photos each.
fn pictured(ui: &mut Ui) -> StoryOutput {
let images: Vec<Box<dyn Fn() -> egui::ColorImage>> =
(0..COUNT).map(|at| Box::new(move || sample_picture(at as u64, [48, 48])) as Box<dyn Fn() -> egui::ColorImage>).collect();
let items: Vec<GalleryItem<'_, usize>> = images
.iter()
.enumerate()
.map(|(at, image)| GalleryItem {
key: at,
label: name(at),
face: GalleryFace::Image { key: at as u64, revision: Revision::default(), image: &**image },
})
.collect();
let current = 2;
Gallery::new("Styles", &items, Some(&current)).tiles(6, 3).more(GalleryMore::Grid).show(ui).into()
}
#[story(Gallery<'static, usize>, covers = [Default], drive = Drive::Never)]
fn gallery(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
pictured(ui)
}
/// A style gallery: wide samples, two to one, each named under its picture.
#[story(Gallery<'static, usize>, covers = [], drive = Drive::Never)]
fn gallery_captioned(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
let images: Vec<Box<dyn Fn() -> egui::ColorImage>> =
(0..COUNT).map(|at| Box::new(move || sample_picture(at as u64, [96, 48])) as Box<dyn Fn() -> egui::ColorImage>).collect();
let items: Vec<GalleryItem<'_, usize>> = images
.iter()
.enumerate()
.map(|(at, image)| GalleryItem {
key: at,
label: name(at),
face: GalleryFace::Image { key: at as u64, revision: Revision::default(), image: &**image },
})
.collect();
let current = 2;
Gallery::new("Styles", &items, Some(&current)).tiles(6, 3).aspect(ThumbAspect::new(2, 1)).caption(CaptionPlace::Below).show(ui).into()
}
/// A gallery of small pages at the large thumbnail size: each preview (a style set's title, heading and paragraph)
/// reads at the size of a ribbon's three rows.
#[story(Gallery<'static, usize>, covers = [], drive = Drive::Never, title = "Large tiles")]
fn gallery_large(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
let images: Vec<Box<dyn Fn() -> egui::ColorImage>> =
(0..COUNT).map(|at| Box::new(move || sample_picture(at as u64, [52, 48])) as Box<dyn Fn() -> egui::ColorImage>).collect();
let items: Vec<GalleryItem<'_, usize>> = images
.iter()
.enumerate()
.map(|(at, image)| GalleryItem {
key: at,
label: name(at),
face: GalleryFace::Image { key: at as u64, revision: Revision::default(), image: &**image },
})
.collect();
Gallery::new("Style Sets", &items, None).tiles(7, 4).thumb(ThumbSize::Large).aspect(ThumbAspect::new(12, 11)).show(ui).into()
}
/// A framed gallery that holds every item: one rounded frame around the tiles, and no buttons while nothing is left
/// to step to.
#[story(Gallery<'static, usize>, covers = [], drive = Drive::Never, title = "Framed, every item shown")]
fn gallery_framed(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
let images: Vec<Box<dyn Fn() -> egui::ColorImage>> =
(0..4).map(|at| Box::new(move || sample_picture(at as u64, [96, 48])) as Box<dyn Fn() -> egui::ColorImage>).collect();
let items: Vec<GalleryItem<'_, usize>> = images
.iter()
.enumerate()
.map(|(at, image)| GalleryItem {
key: at,
label: name(at),
face: GalleryFace::Image { key: at as u64, revision: Revision::default(), image: &**image },
})
.collect();
let current = 1;
Gallery::new("Styles", &items, Some(&current))
.tiles(6, 3)
.aspect(ThumbAspect::new(2, 1))
.caption(CaptionPlace::Below)
.framed()
.spare_buttons()
.show(ui)
.into()
}
#[story(Gallery<'static, usize>, covers = [], drive = Drive::Never)]
fn gallery_compact(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
with_env(
ui,
|set| {
set.values.set(GroupLevel::Compact);
},
pictured,
)
}
/// Clicks the down chevron once: the strip shows the last run of items.
fn step_down(fixture: &mut Fixture) {
if let Some(button) = fixture.by_label("Next row") {
fixture.click(&button);
}
fixture.idle(2);
}
#[story(Gallery<'static, usize>, covers = [], drive = Drive::Custom(step_down))]
fn gallery_stepped(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
pictured(ui)
}
/// Clicks More: the popover with the whole list opens.
fn open_more(fixture: &mut Fixture) {
if let Some(button) = fixture.by_label("More") {
fixture.click(&button);
}
fixture.idle(2);
}
#[story(Gallery<'static, usize>, covers = [Open], drive = Drive::Custom(open_more))]
fn gallery_more_open(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
pictured(ui)
}
#[story(Gallery<'static, usize>, covers = [], drive = Drive::Never)]
fn gallery_painted(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
// Glyph tiles: a disc in the content painter's ink whose size grows with the tile's place.
let paints: Vec<Paint> = (0..COUNT)
.map(|at| {
Box::new(move |cx: &craft_ui::primitives::ContentPainterCx, rect: egui::Rect| {
let radius = rect.size().min_elem() * (at as f32 + 3.0) / (2.0 * COUNT as f32);
cx.data_shapes([egui::Shape::circle_filled(rect.center(), radius, cx.ink())]);
}) as Paint
})
.collect();
let items: Vec<GalleryItem<'_, usize>> =
paints.iter().enumerate().map(|(at, paint)| GalleryItem { key: at, label: name(at), face: GalleryFace::Paint(&**paint) }).collect();
show(ui, &items)
}
#[story(Gallery<'static, usize>, covers = [], drive = Drive::Never)]
fn gallery_rendered(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
// The source renders as a `Later` job: each tile shows the store's placeholder, then its picture. The jobs run
// inline, so the pictures land in the next frame and not whenever a thread ends: the suite's settled frames are
// the same on every run.
let options = ThumbnailOptions::new().jobs(Arc::new(InlineJobs));
let thumbnails = Thumbnails::<u64>::in_context(ui.ctx(), "craft_menu.gallery.story", options);
let source = FakeThumbSource::<u64>::new().later(true);
let items: Vec<GalleryItem<'_, usize>> = (0..COUNT)
.map(|at| GalleryItem { key: at, label: name(at), face: GalleryFace::Rendered { key: at as u64, thumbnails: &thumbnails, source: &source } })
.collect();
show(ui, &items)
}
+265
View File
@@ -0,0 +1,265 @@
//! `RibbonGroup`: a titled group of controls in the ribbon's row.
use std::hash::Hash;
use craft_behavior::IconId;
use craft_keymap::CommandRef;
use craft_ui::buttons::{Arrangement, Button, ControlPlace, IconButton};
use craft_ui::contract::{Bind, Gap, Props as _, Show as _, ShowContainer as _, Trigger};
use craft_ui::display::{Divider, Shade, Text};
use craft_ui::layout::levelled_unit;
use craft_ui::layout_components::{Row, Stack};
use craft_ui::popover::Popover;
use craft_ui::primitives::IconSpec;
use craft_ui::runtime::env::{Env, Label, with_env};
use craft_ui::runtime::measure;
use craft_ui::runtime::memory::{key_salt, with_session};
use craft_ui::style::TypeRole;
use egui::{Id, Pos2, Rect, Ui, Vec2};
use super::{GroupLevel, RibbonLook, RibbonRow};
craft_ui::words! {
/// The words of a ribbon group.
struct GroupWords {
launcher: template "ribbon.launcher" = "{title} settings";
}
}
/// The arrow of a collapsed group's button where the look sets menu arrows: the small filled triangle.
const COLLAPSED_ARROW: craft_ui::controls::disclosure::DisclosureGlyph = craft_ui::controls::disclosure::DisclosureGlyph::new(1.0);
/// The levels a group shows at, widest first: the order the row's levelled units report their widths in.
pub(super) const LEVELS: [GroupLevel; 3] = [GroupLevel::Full, GroupLevel::Compact, GroupLevel::Collapsed];
/// A group of the ribbon: a title, an icon for its collapsed form, and an optional launcher. Each
/// group sets its `GroupLevel` for its content; groups are access nodes (role group, named by
/// their title), and a collapsed group opens a popover.
pub struct RibbonGroup<'a> {
/// The group's identity: it keeps levels apart where titles repeat.
key: u64,
title: Label,
icon: IconSpec<'a>,
launcher: Option<CommandRef>,
}
impl<'a> RibbonGroup<'a> {
/// A group identified by `key`, titled `title`, with `icon` on its collapsed button.
pub fn new(key: impl Hash, title: impl Into<Label>, icon: IconSpec<'a>) -> Self {
RibbonGroup { key: key_salt(&key), title: title.into(), icon, launcher: None }
}
/// The command of the group's dialog launcher.
pub fn launcher(mut self, command: impl Into<CommandRef>) -> Self {
self.launcher = Some(command.into());
self
}
/// The group's content over its title row, with no gap between them: the title sits directly under the content,
/// `body` under the content's top whatever the content's height, so every group's title shares one line at the foot
/// of the row; a taller content pushes it down. `kept` is the slot of this group's content height at this level.
///
/// The spacer under the content and the separator's length come from the content height the last real run kept,
/// never from the content's output in this run: a measuring run has no real size for the content yet, so a spacer
/// sized from it there took the whole `body`, the group measured its content's height too tall (the ribbon stood
/// one body too high under its titles), and the real run, placing another spacer, never matched what was measured,
/// so the row measured again on every pass. Both runs of a pass now place the same sizes; a changed content height
/// is kept by the real run and shows in the next pass.
///
/// Returns the content's height as the real run found it (none in a measuring run), which sets `body` for the
/// row's next pass, and the height of the whole group, which its separator takes.
fn open(&self, ui: &mut Ui, add: &mut dyn FnMut(&mut Ui), room: &TitleRoom, kept: Id) -> (Option<f32>, f32) {
let ctx = ui.ctx().clone();
let line = if room.line.is_finite() { room.line.max(0.0) } else { 0.0 };
let body = if room.body.is_finite() { room.body.max(0.0) } else { 0.0 };
let held = with_session(&ctx, kept, |kept: &mut ContentHeight| kept.0);
let held = if held.is_finite() { held.max(0.0) } else { 0.0 };
let side = if self.launcher.is_some() { line } else { 0.0 };
let centred = kept.with("title");
let centre = with_session(&ctx, centred, |kept: &mut TitleCentre| *kept);
let mut took = f32::NAN;
let mut took_width = f32::NAN;
let mut title = Rect::NOTHING;
let shown = Stack::new().gap(Gap::None).show(ui, |ui, _| {
// A look that sets the row height (`RibbonLook::row`) packs its columns as close as its rows: a tight gap
// apart, as the old ribbon packed them.
let columns = if room.icons.row > 0 { Gap::Tight } else { Gap::Row };
let content = Row::new().gap(columns).show(ui, |ui, _| add(ui)).output.rect;
took = content.height();
took_width = content.width();
// Every group places this spacer, an empty one too, so each has the same gaps above its title.
craft_ui::layout::place_in_flow(ui, Vec2::new(0.0, (body - held).max(0.0)));
// The title on a line `line` high in every group, so the titles of groups with and without a launcher
// share one line, centred across the group's width as the old ribbon centred it, the launcher's square
// included. The row keeps the launcher's room on both sides of the title, so a group as narrow as its
// title still centres it clear of the launcher; under wider content a lead centres it, sized from the
// widths the last real run kept, so both runs of a pass place the same sizes (as the spacer above).
let lead = ((centre.content - centre.title) / 2.0).max(0.0);
title = Row::new()
.gap(Gap::None)
.show(ui, |ui, _| {
craft_ui::layout::place_in_flow(ui, Vec2::new(lead + side, line));
Text::new(self.title.clone()).role(TypeRole::Caption).shade(Shade::Muted).show(ui);
craft_ui::layout::place_in_flow(ui, Vec2::new(side, 0.0));
})
.output
.rect;
});
// Only the real run keeps what the content took; a measuring run's output is no size of it.
let found = (!measure::active(&ctx) && took.is_finite()).then_some(took.max(0.0));
if let Some(found) = found
&& (found - held).abs() >= 0.5
{
with_session(&ctx, kept, |kept: &mut ContentHeight| kept.0 = found);
ctx.request_repaint();
}
// The real run keeps the content's and the title row's own widths for the next pass's lead.
if !measure::active(&ctx) && took_width.is_finite() && title.is_finite() {
let lead = ((centre.content - centre.title) / 2.0).max(0.0);
let found = TitleCentre { content: took_width.max(0.0), title: (title.width() - lead).max(0.0) };
if (found.content - centre.content).abs() >= 0.5 || (found.title - centre.title).abs() >= 0.5 {
with_session(&ctx, centred, |kept: &mut TitleCentre| *kept = found);
ctx.request_repaint();
}
}
let group = shown.output.rect;
// The dialog launcher: a square as high as the title line, at the group's end edge on that line, as the old
// ribbon placed it. It shows at its place, not in the flow, so it never makes its group's title line taller.
if let Some(command) = &self.launcher
&& group.is_finite()
&& title.is_finite()
{
let rtl = Env::of(ui).direction.is_rtl();
let x = if rtl { group.min.x } else { group.max.x - side };
let at = Rect::from_min_size(Pos2::new(x, title.center().y - side / 2.0), Vec2::splat(side));
let words = Env::of(ui).words::<GroupWords>();
let name = words.launcher.fill(&[("title", self.title.as_str())]);
// The launcher keeps the framework's glyph side: the ribbon's icon sides are its buttons', not this square's.
let icon = room.launcher.clone();
with_env(
ui,
|overrides| {
overrides.values.set(RibbonLook::default());
},
|ui| IconButton::command(icon, command.clone()).label(name).show_at(ui, at),
);
}
// What the stack places: the content or the body, whichever is taller, and the title line.
(found, held.max(body) + line)
}
/// One button with the group's icon and title; its popover holds the content at the full level. A press in a
/// popup the content opens does not close the popover: the overlay family keeps it open.
fn collapsed(&self, ui: &mut Ui, add: &mut dyn FnMut(&mut Ui), icons: RibbonLook) {
let face = Button::new(self.title.clone()).icon(self.icon.clone()).arrangement(Arrangement::Stacked);
// A look that sets menu arrows (`RibbonLook::arrow`) marks the collapsed group's button as the menu it opens.
let face = if icons.arrow > 0 { face.trailing_icon(IconSpec::glyph(&COLLAPSED_ARROW)) } else { face };
let button = face.show(ui);
Popover::new(self.title.clone(), Bind::kept()).overlay(|overlay| overlay.opened_by(&button.response, Trigger::Click)).show(ui, |ui, _| {
with_env(
ui,
|overrides| {
overrides.values.set(GroupLevel::Full);
overrides.values.set(ControlPlace::Ribbon);
overrides.values.set(icons);
},
|ui| {
Row::new().show(ui, |ui, _| add(ui));
},
);
});
}
/// The group as the row shows it at `level`: one container `id`, a group node named by the title (a labelled
/// `Row` reports `Role::GROUP`), holding the body and the separator after it. An open group's title sits `body`
/// under its top on a line `line` high (`open`). The separator is as long as the group is high: a line that filled
/// the row would take whatever room the row was offered, and every group would set the ribbon's height by it.
/// Returns the rect it took and the height of its open content (none when collapsed).
fn unit(&self, ui: &mut Ui, id: Id, add: &mut dyn FnMut(&mut Ui), level: GroupLevel, room: &TitleRoom) -> (Rect, Option<f32>) {
let mut content = None;
let rect = Row::new()
.id(id)
.label(self.title.clone())
.show(ui, |ui, _| {
let high = if level == GroupLevel::Collapsed {
self.collapsed(ui, add, room.icons);
room.body + room.line
} else {
let (took, high) = self.open(ui, add, room, id.with(("content", level)));
content = took;
high
};
Divider::vertical().length(high).show(ui);
})
.output
.rect;
(rect, content)
}
}
/// The height of the tallest open group content the ribbon's row showed in its last pass: the line every group's
/// title sits under. Kept in the ribbon's session memory.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub(super) struct BodyHeight(pub(super) f32);
/// The height of one open group's content at one level, as the last real run found it: what the spacer under it and
/// the group's separator are sized from in every run of the next pass. Kept in the ribbon's session memory.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
struct ContentHeight(f32);
/// The width of one open group's content at one level and of its title row without its lead, as the last real run
/// found them: what the lead that centres the title is sized from in every run of the next pass.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
struct TitleCentre {
content: f32,
title: f32,
}
/// Where a group's title goes: `body` under the group's top, on a line `line` high.
#[derive(Clone, Debug)]
struct TitleRoom {
body: f32,
line: f32,
/// The icon sides the group's buttons take.
icons: RibbonLook,
/// The dialog launcher's icon (`Ribbon::launcher_icon`).
launcher: IconId,
}
impl RibbonRow<'_> {
/// Adds `group` to the row, at the level the row's fit gives it; `add` fills its content.
///
/// The group is a levelled unit of the row (`layout::levelled_unit`): when the row measures (its room or its
/// content changed), it runs `add` once at each level to measure the group, and gives each group its level by
/// production's rule ([`plan`](super::plan)); a pass in which nothing the row measures changed shows each group
/// once, at its kept level. So `add` must be free of side effects in a measuring run, as every row body is: it
/// reads the outputs of the controls it shows, and the framework reports those in the real run only.
pub fn group(&mut self, group: RibbonGroup<'_>, mut add: impl FnMut(&mut Ui)) -> &mut Self {
let id = self.base.with(("ribbon.group", group.key));
let mut shown = None;
let room = TitleRoom { body: self.body, line: self.title_line, icons: self.icons, launcher: self.launcher.clone() };
let mut tallest = self.tallest;
levelled_unit(self.ui, id, LEVELS.len(), |ui, at| {
let level = LEVELS.get(at).copied().unwrap_or(GroupLevel::Collapsed);
// A ribbon's controls take the ribbon's look: flat buttons, fields as long as the ribbon's.
let (rect, content) = with_env(
ui,
|overrides| {
overrides.values.set(level);
overrides.values.set(ControlPlace::Ribbon);
overrides.values.set(room.icons);
},
|ui| group.unit(ui, id, &mut add, level, &room),
);
if let Some(content) = content.filter(|height| height.is_finite()) {
tallest = tallest.max(content);
}
shown = Some(rect);
});
self.tallest = tallest;
if let Some(rect) = shown {
self.groups.push(rect);
}
self
}
}
Loaded 100 of 652 files, more files were not shown because too many files have changed in this diff. Show more