mirror of
https://github.com/storytold/craft-libs.git
synced 2026-11-26 04:27:49 +00:00
Merge remote-tracking branch 'origin/next' into publish/registry-2332
# Conflicts: # crates/automation/src/agents/mod.rs # crates/automation/src/agents/settings.rs
This commit is contained in:
Generated
+1
-3
@@ -2047,10 +2047,8 @@ name = "craft-automation"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"craft-ai-agents",
|
||||
"craft-atomic",
|
||||
"craft-behavior",
|
||||
"craft-flags",
|
||||
"craft-control",
|
||||
"craft-host",
|
||||
"craft-keymap",
|
||||
"craft-platform",
|
||||
|
||||
@@ -26,12 +26,15 @@ ui = ["dep:craft-behavior", "dep:craft-keymap", "dep:craft-ui", "dep:egui"]
|
||||
# The Actions panel's and the Agents page's stories and mock, and the integration binary `tests/it`.
|
||||
screen-testing = ["ui", "agents", "craft-ui/testing"]
|
||||
# Agents in the open window (desktop): the ArtCraft Launcher's switch, the connection file an
|
||||
# app's `<id>-cli mcp` reads, and with `ui` the link host and the Agents page. The agent settings
|
||||
# build on every target without it.
|
||||
agents = ["dep:craft-ai-agents", "dep:craft-flags", "dep:craft-atomic", "dep:craft-host"]
|
||||
# app's `<id>-cli mcp` reads and that CLI's live client (all `craft-control`'s, re-exported), and
|
||||
# with `ui` the link host and the Agents page. The agent settings build on every target without it.
|
||||
agents = ["craft-control/agents", "dep:craft-host"]
|
||||
|
||||
[dependencies]
|
||||
craft-behavior = { workspace = true, optional = true }
|
||||
# The agents code without a UI toolkit (settings, the launcher's switch, the connection file, the
|
||||
# CLI's live client), re-exported by `agents` so every app shares one copy.
|
||||
craft-control = { workspace = true }
|
||||
craft-keymap = { workspace = true, optional = true }
|
||||
craft-theme = { workspace = true }
|
||||
craft-ui = { workspace = true, optional = true }
|
||||
@@ -43,9 +46,6 @@ serde_json = { workspace = true }
|
||||
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
|
||||
base64 = "0.22"
|
||||
craft-platform = { workspace = true }
|
||||
craft-ai-agents = { workspace = true, optional = true }
|
||||
craft-atomic = { workspace = true, optional = true }
|
||||
craft-flags = { workspace = true, optional = true }
|
||||
craft-host = { workspace = true, optional = true }
|
||||
getrandom = "0.3"
|
||||
hmac = "0.12"
|
||||
|
||||
@@ -8,7 +8,7 @@ Features: `ui` (the egui parts), `agents` (agents in the open window: the launch
|
||||
| --- | --- |
|
||||
| `actions` | Recorded actions (every target): `ActionList` of `Action`s and `ActionStep`s, `ActionsFile`, playback with `ActionPlayer` and `ActionRunner` under a `PlaybackBudget`, and `Recording`. The app keeps the command table. |
|
||||
| `ui::actions` | `ActionsPanel` (every target): sets, actions and steps as a tree, include and dialog cells, rename (`start_rename`), drag to move, Button Mode, the footer and the menus (`ActionsPanelCommands`, `ActionsMenuFacts` and `panel_rows`, which leaves out the rows the host has no command for). It runs nothing; it reports `ActionsEvent`s. `ActionsPanelState` holds its view state. `ActionsWords` holds its words. |
|
||||
| `agents` | AI agents in the open window. Every target: `AgentSettings` (Control Port, the folders agents may open from and save to, `WhenAppClosed`, Allow Agent Control) and `agents_allowed`. Desktop, feature `agents`: `AgentSwitch`, the ArtCraft Launcher's switch for the app behind the suite's `AI-MCP` flag, watched on a thread; the connection file (`Connection`, `write_connection`, `read_connection`, `remove_stale_connection`, `probe`) that the app's `<id>-cli mcp` finds the open window by. With `ui`: `AgentLink`, the link host that starts, moves, stops and retries the agents' control server to match the settings and publishes the connection file. |
|
||||
| `agents` | AI agents in the open window. Every target: `AgentSettings` (Control Port, the folders agents may open from and save to, `WhenAppClosed`, Allow Agent Control) and `agents_allowed`. Desktop, feature `agents`: `AgentSwitch`, the ArtCraft Launcher's switch for the app behind the suite's `AI-MCP` flag, watched on a thread; the connection file (`Connection`, `write_connection`, `read_connection`, `remove_stale_connection`, `probe`) that the app's `<id>-cli mcp` finds the open window by; the CLI's live client (`Live`, `LiveConfig`, `Route`). All of these are `craft_control::agents`, re-exported, so apps without the shared UI library use the same code. With `ui`: `AgentLink`, the link host that starts, moves, stops and retries the agents' control server to match the settings and publishes the connection file. |
|
||||
| `ui::agents` | `AgentsPage` (desktop, features `agents` and `ui`): the Agents page of Preferences, a custom page over the agent settings in the Preferences draft, with the link's status; the folder rows are `PathSetting`s. `AgentsWords` holds its words. |
|
||||
| `args` | `ControlOptions`: the `--control <PORT>`, `--control-token`, `--control-token-file` values and their `<APP>_CONTROL_*` environment fallbacks, checked the way the apps' command lines report them (usage errors exit 2). |
|
||||
| `security` | Tokens (`generate_token`, `validate_token`, `server_token`, `client_token`), the authentication handshake (`ServerHandshake`: the challenge handshake, which never sends the token, or the one-frame `auth {token}`), bounded line reads, connection and request limits. |
|
||||
|
||||
@@ -1,117 +0,0 @@
|
||||
//! The connection file: where an app's control server listens for agents.
|
||||
|
||||
use std::net::{SocketAddr, TcpStream};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::Duration;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::AutomationError;
|
||||
|
||||
/// The connection file in the app's settings folder, present while the app accepts agents.
|
||||
pub const CONNECTION_FILE: &str = "agent-connection.json";
|
||||
/// The token file the app keeps in its settings folder for agent connections.
|
||||
pub const TOKEN_FILE: &str = "agent-control.token";
|
||||
/// How long [`probe`] waits for a connection to be accepted.
|
||||
pub const PROBE_TIMEOUT: Duration = Duration::from_millis(500);
|
||||
/// The version of the [`Connection`] file format.
|
||||
const CONNECTION_VERSION: u32 = 1;
|
||||
/// The largest connection file read; anything bigger is not one.
|
||||
const MAX_CONNECTION_BYTES: u64 = 1 << 20;
|
||||
|
||||
/// What an app publishes in [`CONNECTION_FILE`]: `{"version", "pid", "port", "tokenFile", "app"}`.
|
||||
/// Holds no secret: the token stays in its own owner-only file.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct Connection {
|
||||
/// The file format's version (1).
|
||||
pub version: u32,
|
||||
/// The app's process id: only that process removes the file.
|
||||
pub pid: u32,
|
||||
/// The loopback port of the control server.
|
||||
pub port: u16,
|
||||
/// The file holding the token.
|
||||
pub token_file: PathBuf,
|
||||
/// The app's version, for diagnostics.
|
||||
pub app: String,
|
||||
}
|
||||
|
||||
impl Connection {
|
||||
/// This process's connection on `port`, naming `app` (the app's version string).
|
||||
pub fn new(port: u16, token_file: PathBuf, app: impl Into<String>) -> Self {
|
||||
Self { version: CONNECTION_VERSION, pid: std::process::id(), port, token_file, app: app.into() }
|
||||
}
|
||||
|
||||
/// `127.0.0.1:<port>`.
|
||||
pub fn addr(&self) -> String {
|
||||
format!("127.0.0.1:{}", self.port)
|
||||
}
|
||||
}
|
||||
|
||||
fn io_error(path: &Path, e: impl std::fmt::Display) -> AutomationError {
|
||||
AutomationError::Io(format!("{}: {e}", path.display()))
|
||||
}
|
||||
|
||||
/// Publishes `c` in `dir` (made if missing), written atomically so a reader never sees half a
|
||||
/// file.
|
||||
pub fn write_connection(dir: &Path, c: &Connection) -> Result<(), AutomationError> {
|
||||
std::fs::create_dir_all(dir).map_err(|e| io_error(dir, e))?;
|
||||
let path = dir.join(CONNECTION_FILE);
|
||||
let text = serde_json::to_string_pretty(c).map_err(|e| io_error(&path, e))?;
|
||||
craft_atomic::atomic_write(&path, text.as_bytes()).map_err(|e| io_error(&path, e))
|
||||
}
|
||||
|
||||
/// The connection published in `dir`, if any. A file of another version, with port 0, or one
|
||||
/// that does not parse (invalid UTF-8 included) counts as none: the app rewrites it when it next
|
||||
/// starts listening. Anything but a regular file (a FIFO would block the read) or a file over
|
||||
/// 1 MiB is an error, and left alone.
|
||||
pub fn read_connection(dir: &Path) -> Result<Option<Connection>, AutomationError> {
|
||||
let path = dir.join(CONNECTION_FILE);
|
||||
let meta = match std::fs::metadata(&path) {
|
||||
Ok(m) => m,
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
|
||||
Err(e) => return Err(io_error(&path, e)),
|
||||
};
|
||||
if !meta.is_file() {
|
||||
return Err(io_error(&path, "not a regular file"));
|
||||
}
|
||||
if meta.len() > MAX_CONNECTION_BYTES {
|
||||
return Err(io_error(&path, format!("larger than {MAX_CONNECTION_BYTES} bytes")));
|
||||
}
|
||||
let bytes = match std::fs::read(&path) {
|
||||
Ok(b) => b,
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
|
||||
Err(e) => return Err(io_error(&path, e)),
|
||||
};
|
||||
Ok(serde_json::from_slice::<Connection>(&bytes).ok().filter(|c| c.version == CONNECTION_VERSION && c.port != 0))
|
||||
}
|
||||
|
||||
/// Removes the connection file in `dir` if process `pid` wrote it (another instance may have
|
||||
/// published its own since). Errors are ignored: a stale file only fails [`probe`].
|
||||
pub fn remove_connection(dir: &Path, pid: u32) {
|
||||
if let Ok(Some(c)) = read_connection(dir)
|
||||
&& c.pid == pid
|
||||
{
|
||||
let _ = std::fs::remove_file(dir.join(CONNECTION_FILE));
|
||||
}
|
||||
}
|
||||
|
||||
/// Removes the connection file in `dir` when nothing listens on its port any more (an app that
|
||||
/// crashed or quit without removing it), or when it does not read as a connection. A live
|
||||
/// instance's file is kept, and so is anything but a regular file. Errors are ignored.
|
||||
pub fn remove_stale_connection(dir: &Path) {
|
||||
let path = dir.join(CONNECTION_FILE);
|
||||
let stale = match read_connection(dir) {
|
||||
Ok(Some(c)) => !probe(c.port, PROBE_TIMEOUT),
|
||||
Ok(None) => path.is_file(),
|
||||
Err(_) => false,
|
||||
};
|
||||
if stale {
|
||||
let _ = std::fs::remove_file(path);
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether something accepts connections on loopback `port` within `timeout`; port 0 never does.
|
||||
pub fn probe(port: u16, timeout: Duration) -> bool {
|
||||
port != 0 && TcpStream::connect_timeout(&SocketAddr::from(([127, 0, 0, 1], port)), timeout).is_ok()
|
||||
}
|
||||
@@ -9,8 +9,8 @@
|
||||
//! While agents may connect, the app serves its control channel on loopback ([`AgentLink`], over
|
||||
//! [`crate::server`]) and publishes where in its settings folder ([`CONNECTION_FILE`]): the port,
|
||||
//! its process id and the token file ([`TOKEN_FILE`], created `0600` on Unix). The app's
|
||||
//! `<id>-cli mcp` reads that file on every tool call, then the token from the file it names, so an
|
||||
//! MCP client's configuration never holds a port or a token.
|
||||
//! `<id>-cli mcp` reads that file on every tool call ([`Live`]), then the token from the file it
|
||||
//! names, so an MCP client's configuration never holds a port or a token.
|
||||
//!
|
||||
//! The file holds no secret. A crashed (or, on macOS, quit) app can leave it behind; nothing then
|
||||
//! listens on its port ([`probe`]), and the app's next launch removes it
|
||||
@@ -18,29 +18,32 @@
|
||||
//! checks that [`Connection::pid`] is still running before it sends anything derived from the
|
||||
//! token, and authenticates with the challenge handshake ([`crate::security::ServerHandshake`]).
|
||||
//!
|
||||
//! Everything but the link host is `craft_control::agents`, re-exported here: apps that don't use
|
||||
//! the shared UI library use it from there, with the same files and formats.
|
||||
//!
|
||||
//! | Part | Names | Builds |
|
||||
//! |---|---|---|
|
||||
//! | Settings | [`AgentSettings`], [`WhenAppClosed`], [`agents_allowed`], [`folder`] | every target |
|
||||
//! | The launcher's switch | [`AgentSwitch`], [`mcp_flag`], [`launcher_allows`], [`POLL`] | desktop, feature `agents` |
|
||||
//! | The connection file | [`Connection`], [`write_connection`], [`read_connection`], [`remove_connection`], [`remove_stale_connection`], [`probe`] | desktop, feature `agents` |
|
||||
//! | The CLI's side | [`Live`], [`LiveConfig`], [`Route`], [`Window`], [`Consent`], [`HeadlessFolders`], [`find_window`], [`launcher`] | desktop, feature `agents` |
|
||||
//! | The link host | [`AgentLink`], [`AgentLinkStatus`], [`LinkProblem`], [`LinkUpdate`] | desktop, features `agents` and `ui` |
|
||||
//!
|
||||
//! The Agents page of Preferences is [`crate::ui::agents`].
|
||||
|
||||
pub(crate) mod settings;
|
||||
pub use settings::{AgentSettings, WhenAppClosed, agents_allowed, folder};
|
||||
// The links above name items of the `agents` and `ui` features; without them they have nothing to
|
||||
// point at, and the docs of the settings alone still build.
|
||||
#![cfg_attr(not(all(feature = "agents", feature = "ui", not(target_arch = "wasm32"))), allow(rustdoc::broken_intra_doc_links))]
|
||||
|
||||
pub use craft_control::agents::{AgentSettings, WhenAppClosed, agents_allowed, folder};
|
||||
|
||||
#[cfg(all(feature = "agents", not(target_arch = "wasm32")))]
|
||||
mod connection;
|
||||
#[cfg(all(feature = "agents", feature = "ui", not(target_arch = "wasm32")))]
|
||||
mod link;
|
||||
#[cfg(all(feature = "agents", not(target_arch = "wasm32")))]
|
||||
mod switch;
|
||||
#[cfg(all(feature = "agents", not(target_arch = "wasm32")))]
|
||||
pub use connection::{
|
||||
CONNECTION_FILE, Connection, PROBE_TIMEOUT, TOKEN_FILE, probe, read_connection, remove_connection, remove_stale_connection, write_connection,
|
||||
pub use craft_control::agents::{
|
||||
AgentSwitch, CONNECTION_FILE, ConnectFn, Connection, Consent, ConsentFn, HeadlessFn, HeadlessFolders, LAUNCH_POLL, LAUNCH_TIMEOUT, LaunchFn,
|
||||
Live, LiveConfig, POLL, PROBE_TIMEOUT, Route, TOKEN_FILE, Window, find_window, launcher, launcher_allows, mcp_flag, probe, read_connection,
|
||||
remove_connection, remove_stale_connection, write_connection,
|
||||
};
|
||||
#[cfg(all(feature = "agents", feature = "ui", not(target_arch = "wasm32")))]
|
||||
pub use link::{AgentLink, AgentLinkStatus, LinkProblem, LinkUpdate, RETRY};
|
||||
#[cfg(all(feature = "agents", not(target_arch = "wasm32")))]
|
||||
pub use switch::{AgentSwitch, POLL, launcher_allows, mcp_flag};
|
||||
|
||||
@@ -1,124 +0,0 @@
|
||||
//! The agent settings an app saves in its preferences, and who decides that agents may connect.
|
||||
|
||||
use std::path::PathBuf;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// The agent settings of an app's Preferences (its `integrations` section in PhotoCraft). Saved in
|
||||
/// camelCase: `allowAgentControl`, `controlPort`, `readRoot`, `writeRoot`, `whenAppClosed`.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
#[non_exhaustive]
|
||||
pub struct AgentSettings {
|
||||
/// Off refuses every control server, `--control` included.
|
||||
pub allow_agent_control: bool,
|
||||
/// The loopback port agents connect to; 0 is any free port, published in the connection file.
|
||||
pub control_port: u32,
|
||||
/// The folder agents may open from; empty is none. Applied at once while agents are connected.
|
||||
pub read_root: String,
|
||||
/// The folder agents may save to; empty is none. Applied at once while agents are connected.
|
||||
pub write_root: String,
|
||||
/// What the app's `<id>-cli mcp` does while agents may use the app but it is closed.
|
||||
pub when_app_closed: WhenAppClosed,
|
||||
}
|
||||
|
||||
impl Default for AgentSettings {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
allow_agent_control: true,
|
||||
control_port: 0,
|
||||
read_root: String::new(),
|
||||
write_root: String::new(),
|
||||
when_app_closed: WhenAppClosed::Launch,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl AgentSettings {
|
||||
/// [`Self::read_root`] as a path ([`folder`]).
|
||||
pub fn read_folder(&self) -> Option<PathBuf> {
|
||||
folder(&self.read_root)
|
||||
}
|
||||
|
||||
/// [`Self::write_root`] as a path ([`folder`]).
|
||||
pub fn write_folder(&self) -> Option<PathBuf> {
|
||||
folder(&self.write_root)
|
||||
}
|
||||
}
|
||||
|
||||
/// A folder setting as a path, trimmed; empty or blank is `None`.
|
||||
pub fn folder(pref: &str) -> Option<PathBuf> {
|
||||
let pref = pref.trim();
|
||||
(!pref.is_empty()).then(|| PathBuf::from(pref))
|
||||
}
|
||||
|
||||
/// What an app's `<id>-cli mcp` does when an agent calls a tool while the app is closed.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum WhenAppClosed {
|
||||
/// Open the app and wait for it.
|
||||
#[default]
|
||||
Launch,
|
||||
/// Run the tool without a window.
|
||||
Headless,
|
||||
/// Answer with an error that asks to open the app.
|
||||
Error,
|
||||
}
|
||||
|
||||
impl WhenAppClosed {
|
||||
/// The saved names, in [`Self::ALL`] order.
|
||||
pub const NAMES: &'static [&'static str] = &["launch", "headless", "error"];
|
||||
/// Every choice, in the order a menu lists them.
|
||||
pub const ALL: [Self; 3] = [Self::Launch, Self::Headless, Self::Error];
|
||||
|
||||
/// The saved name.
|
||||
pub fn name(self) -> &'static str {
|
||||
match self {
|
||||
Self::Launch => "launch",
|
||||
Self::Headless => "headless",
|
||||
Self::Error => "error",
|
||||
}
|
||||
}
|
||||
|
||||
/// The choice a saved name means; `None` for any other text.
|
||||
pub fn parse(name: &str) -> Option<Self> {
|
||||
Self::ALL.into_iter().find(|c| c.name() == name)
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether agents may use the open window. With the suite's `AI-MCP` flag only the launcher's
|
||||
/// switch decides: one switch for every Craft app, none in the app. Without the flag the app's own
|
||||
/// earlier consent decides (`legacy`; PhotoCraft's is a Control Port saved before the switch).
|
||||
/// Allow Agent Control off still refuses agents either way ([`AgentSettings::allow_agent_control`]).
|
||||
pub fn agents_allowed(mcp_flag: bool, launcher: bool, legacy: bool) -> bool {
|
||||
if mcp_flag { launcher } else { legacy }
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) mod tests {
|
||||
use super::*;
|
||||
use craft_ui::testing::trial;
|
||||
|
||||
// The saved names read back as the same choice, and nothing else reads as one.
|
||||
#[trial]
|
||||
fn when_app_closed_names_round_trip() {
|
||||
for choice in WhenAppClosed::ALL {
|
||||
assert_eq!(WhenAppClosed::parse(choice.name()), Some(choice));
|
||||
assert_eq!(serde_json::to_value(choice).unwrap(), serde_json::json!(choice.name()));
|
||||
}
|
||||
assert_eq!(WhenAppClosed::NAMES, WhenAppClosed::ALL.map(WhenAppClosed::name));
|
||||
assert_eq!(WhenAppClosed::parse("Launch"), None);
|
||||
let settings: AgentSettings = serde_json::from_str(r#"{"whenAppClosed": "headless", "controlPort": 7878}"#).unwrap();
|
||||
assert_eq!((settings.when_app_closed, settings.control_port, settings.allow_agent_control), (WhenAppClosed::Headless, 7878, true));
|
||||
}
|
||||
|
||||
// A folder setting is trimmed; empty or blank means no folder.
|
||||
#[trial]
|
||||
fn folder_preferences_are_trimmed() {
|
||||
assert_eq!(folder(""), None);
|
||||
assert_eq!(folder(" "), None);
|
||||
assert_eq!(folder(" /work/project "), Some(PathBuf::from("/work/project")));
|
||||
let settings = AgentSettings { read_root: " /in ".into(), ..AgentSettings::default() };
|
||||
assert_eq!((settings.read_folder(), settings.write_folder()), (Some(PathBuf::from("/in")), None));
|
||||
}
|
||||
}
|
||||
@@ -1,94 +0,0 @@
|
||||
//! The ArtCraft Launcher's switch for one app, behind the suite's `AI-MCP` flag.
|
||||
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::{Arc, Weak};
|
||||
use std::time::Duration;
|
||||
|
||||
use craft_host::Wake;
|
||||
|
||||
use super::agents_allowed;
|
||||
|
||||
/// How often [`AgentSwitch::watch`] reads the launcher's app list.
|
||||
pub const POLL: Duration = Duration::from_secs(2);
|
||||
|
||||
/// The suite's `AI-MCP` flag (`ArtCraft/flags.toml` or `CRAFT_FLAGS`). Reads the flags file;
|
||||
/// what could not be read is logged.
|
||||
pub fn mcp_flag() -> bool {
|
||||
let flags = craft_flags::load();
|
||||
for problem in &flags.problems {
|
||||
log::warn!("flags: {problem}");
|
||||
}
|
||||
flags.enabled(&craft_flags::AI_MCP)
|
||||
}
|
||||
|
||||
/// The launcher's switch (Settings › AI agents › *Let AI agents use Craft apps*) lets agents use
|
||||
/// the app `app_id`: the `AI-MCP` flag is on and the launcher's app list names the app. Reads two
|
||||
/// small files; ask from a timer or a command, not every frame ([`AgentSwitch`] does that).
|
||||
pub fn launcher_allows(app_id: &str) -> bool {
|
||||
mcp_flag() && craft_ai_agents::allowed(app_id)
|
||||
}
|
||||
|
||||
/// The launcher's switch for one app, watched on a thread so a frame can ask without touching the
|
||||
/// disk. The `AI-MCP` flag is read once, at [`Self::watch`]; the launcher's list every [`POLL`].
|
||||
/// Clones share one watch; the thread ends after the last clone is dropped.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct AgentSwitch {
|
||||
mcp_flag: bool,
|
||||
on: Arc<AtomicBool>,
|
||||
}
|
||||
|
||||
impl AgentSwitch {
|
||||
/// Watches the launcher's list for `app_id`; a change logs `agents on/off` and calls `wake`.
|
||||
/// Without the `AI-MCP` flag nothing is watched: the launcher's list means nothing then.
|
||||
pub fn watch(app_id: &'static str, wake: Wake) -> Self {
|
||||
let flag = mcp_flag();
|
||||
if !flag {
|
||||
return Self::fixed(false, false);
|
||||
}
|
||||
Self::watch_with(flag, move || craft_ai_agents::allowed(app_id), POLL, wake)
|
||||
}
|
||||
|
||||
/// A switch that never changes: tests, the web, an app without agents.
|
||||
pub fn fixed(mcp_flag: bool, launcher: bool) -> Self {
|
||||
Self { mcp_flag, on: Arc::new(AtomicBool::new(launcher)) }
|
||||
}
|
||||
|
||||
/// [`Self::watch`] with the flag given, `probe` asked once now and then every `poll`.
|
||||
#[doc(hidden)]
|
||||
pub fn watch_with(mcp_flag: bool, probe: impl Fn() -> bool + Send + 'static, poll: Duration, wake: Wake) -> Self {
|
||||
let on = Arc::new(AtomicBool::new(probe()));
|
||||
let seen: Weak<AtomicBool> = Arc::downgrade(&on);
|
||||
let started = std::thread::Builder::new().name("launcher-agents".into()).spawn(move || {
|
||||
loop {
|
||||
std::thread::sleep(poll);
|
||||
let now = probe();
|
||||
let Some(seen) = seen.upgrade() else { return };
|
||||
if seen.swap(now, Ordering::Relaxed) != now {
|
||||
log::info!("ArtCraft Launcher: agents {}", if now { "on" } else { "off" });
|
||||
wake.wake();
|
||||
}
|
||||
}
|
||||
});
|
||||
// Without a thread the answer stays what it was at launch.
|
||||
if let Err(e) = started {
|
||||
log::warn!("couldn't watch the ArtCraft Launcher's agents switch: {e}");
|
||||
}
|
||||
Self { mcp_flag, on }
|
||||
}
|
||||
|
||||
/// The `AI-MCP` flag as it was when the watch started.
|
||||
pub fn mcp_flag(&self) -> bool {
|
||||
self.mcp_flag
|
||||
}
|
||||
|
||||
/// Whether the launcher's list named the app at the last poll.
|
||||
pub fn launcher(&self) -> bool {
|
||||
self.on.load(Ordering::Relaxed)
|
||||
}
|
||||
|
||||
/// Whether agents may use the open window ([`agents_allowed`]); `legacy` is the app's own
|
||||
/// earlier consent, which counts only without the flag.
|
||||
pub fn allows(&self, legacy: bool) -> bool {
|
||||
agents_allowed(self.mcp_flag, self.launcher(), legacy)
|
||||
}
|
||||
}
|
||||
@@ -14,7 +14,7 @@ use craft_automation::agents::{
|
||||
};
|
||||
use craft_automation::server;
|
||||
use craft_automation::ui::agents::AgentsPage;
|
||||
use craft_host::{AppInfo, Host, PickId, Picked, ScriptedFiles, Wake};
|
||||
use craft_host::{AppInfo, Host, PickId, Picked, ScriptedFiles};
|
||||
use craft_ui::contract::Role;
|
||||
use craft_ui::patterns::preferences::SettingsDraft;
|
||||
use craft_ui::runtime::motion;
|
||||
@@ -68,9 +68,9 @@ fn the_switch_wakes_once_per_change() {
|
||||
};
|
||||
let wake = {
|
||||
let wakes = wakes.clone();
|
||||
Wake::new(move || {
|
||||
move || {
|
||||
wakes.fetch_add(1, Ordering::Relaxed);
|
||||
})
|
||||
}
|
||||
};
|
||||
let switch = AgentSwitch::watch_with(true, probe, Duration::from_millis(5), wake);
|
||||
let clone = switch.clone();
|
||||
@@ -161,7 +161,9 @@ fn host() -> WindowHost {
|
||||
}
|
||||
|
||||
fn on(port: u32) -> AgentSettings {
|
||||
AgentSettings { control_port: port, ..AgentSettings::default() }
|
||||
let mut s = AgentSettings::default();
|
||||
s.control_port = port;
|
||||
s
|
||||
}
|
||||
|
||||
/// A port nothing listens on: bound, then closed.
|
||||
@@ -188,7 +190,8 @@ fn turning_agents_on_publishes_a_reachable_connection_and_off_removes_it() {
|
||||
assert!(probe(port, PROBE_TIMEOUT));
|
||||
let token = std::fs::read_to_string(dir.path().join(TOKEN_FILE)).unwrap();
|
||||
|
||||
let folders = AgentSettings { read_root: "/in".into(), ..on(0) };
|
||||
let mut folders = on(0);
|
||||
folders.read_root = "/in".into();
|
||||
let kept = link.sync(Some(&folders), &host);
|
||||
assert!(kept.requests.is_none() && !kept.stopped && kept.changed, "a folder change keeps the server");
|
||||
assert_eq!(link.status().port, Some(port));
|
||||
@@ -266,7 +269,9 @@ fn allow_agent_control_off_and_no_settings_folder_keep_agents_out() {
|
||||
let mut link = AgentLink::new(Some(dir.path().to_path_buf()), "x");
|
||||
assert!(link.sync(Some(&on(0)), &host).requests.is_some());
|
||||
let port = link.status().port.expect("listening");
|
||||
let refused = link.sync(Some(&AgentSettings { allow_agent_control: false, ..on(0) }), &host);
|
||||
let mut off = on(0);
|
||||
off.allow_agent_control = false;
|
||||
let refused = link.sync(Some(&off), &host);
|
||||
assert!(refused.stopped && refused.requests.is_none());
|
||||
assert_eq!(link.status().problem, Some(LinkProblem::NotAllowed));
|
||||
assert!(!dir.path().join(CONNECTION_FILE).exists());
|
||||
|
||||
@@ -30,13 +30,15 @@ pub enum HitShape {
|
||||
/// The other end.
|
||||
b: Pos2,
|
||||
},
|
||||
/// A chain of segments, hit within [`LINE_REACH`].
|
||||
/// A chain of segments, hit within `reach` ([`LINE_REACH`] unless [`HitShape::polyline_within`] says otherwise).
|
||||
#[non_exhaustive]
|
||||
Polyline {
|
||||
/// The corners in order.
|
||||
points: Vec<Pos2>,
|
||||
/// Whether the last corner joins the first.
|
||||
closed: bool,
|
||||
/// How far from the chain a point still hits it, in points.
|
||||
reach: f32,
|
||||
},
|
||||
/// A filled polygon.
|
||||
Polygon(Vec<Pos2>),
|
||||
@@ -62,9 +64,16 @@ impl HitShape {
|
||||
HitShape::Segment { a, b }
|
||||
}
|
||||
|
||||
/// A chain of segments, closed when `closed`.
|
||||
/// A chain of segments, closed when `closed`, hit within [`LINE_REACH`].
|
||||
pub fn polyline(points: Vec<Pos2>, closed: bool) -> Self {
|
||||
HitShape::Polyline { points, closed }
|
||||
HitShape::Polyline { points, closed, reach: LINE_REACH }
|
||||
}
|
||||
|
||||
/// A chain of segments, closed when `closed`, hit within `reach` points: a tool whose measured reach differs from
|
||||
/// a line's. A negative or non-finite `reach` is [`LINE_REACH`].
|
||||
pub fn polyline_within(points: Vec<Pos2>, closed: bool, reach: f32) -> Self {
|
||||
let reach = if reach.is_finite() && reach >= 0.0 { reach } else { LINE_REACH };
|
||||
HitShape::Polyline { points, closed, reach }
|
||||
}
|
||||
|
||||
/// The part of `within` outside `polygon`.
|
||||
@@ -95,7 +104,8 @@ impl HitShape {
|
||||
}
|
||||
HitShape::Circle { center, radius } => center.distance(point) <= radius.max(across / 2.0),
|
||||
HitShape::Segment { a, b } => segment_distance(point, *a, *b) <= reach,
|
||||
HitShape::Polyline { points, closed } => {
|
||||
HitShape::Polyline { points, closed, reach: own } => {
|
||||
let reach = own.max(across / 2.0);
|
||||
let closing = closed.then(|| points.first().zip(points.last())).flatten();
|
||||
points.windows(2).any(|pair| segment_distance(point, pair[0], pair[1]) <= reach)
|
||||
|| closing.is_some_and(|(first, last)| segment_distance(point, *last, *first) <= reach)
|
||||
@@ -116,10 +126,10 @@ impl HitShape {
|
||||
HitShape::Rect(rect) => rect.contains(point),
|
||||
HitShape::Circle { center, radius } => center.distance(point) <= *radius,
|
||||
HitShape::Segment { a, b } => segment_distance(point, *a, *b) <= LINE_REACH,
|
||||
HitShape::Polyline { points, closed } => {
|
||||
HitShape::Polyline { points, closed, reach } => {
|
||||
let closing = closed.then(|| points.first().zip(points.last())).flatten();
|
||||
points.windows(2).any(|pair| segment_distance(point, pair[0], pair[1]) <= LINE_REACH)
|
||||
|| closing.is_some_and(|(first, last)| segment_distance(point, *last, *first) <= LINE_REACH)
|
||||
points.windows(2).any(|pair| segment_distance(point, pair[0], pair[1]) <= *reach)
|
||||
|| closing.is_some_and(|(first, last)| segment_distance(point, *last, *first) <= *reach)
|
||||
}
|
||||
HitShape::Polygon(points) => inside_polygon(point, points),
|
||||
HitShape::OutsidePolygon { within, polygon } => within.contains(point) && !inside_polygon(point, polygon),
|
||||
@@ -330,4 +340,18 @@ mod tests {
|
||||
let tie = [shape(big(), Sense::CLICK, 1, 0, HitLevel::Body, 0), shape(big(), Sense::CLICK, 2, 0, HitLevel::Body, 0)];
|
||||
assert_eq!(owner(&tie), Some(2));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_polyline_hits_within_its_own_reach_and_a_bad_reach_is_a_lines() {
|
||||
let points = vec![pos2(0.0, 0.0), pos2(100.0, 0.0)];
|
||||
let line = HitShape::polyline(points.clone(), false);
|
||||
assert!(line.hit(pos2(50.0, LINE_REACH)) && !line.hit(pos2(50.0, LINE_REACH + 0.5)));
|
||||
let wide = HitShape::polyline_within(points.clone(), false, 5.0);
|
||||
assert!(wide.hit(pos2(50.0, 5.0)) && wide.hit(pos2(50.0, -5.0)) && !wide.hit(pos2(50.0, 5.5)));
|
||||
let hits = |shape: HitShape, y: f32| Shape::new(shape, Sense::CLICK, 0_u8, None, HitPriority::BODY, 0).min_across(8.0).hits(pos2(50.0, y));
|
||||
assert!(hits(wide.clone(), 5.0) && !hits(wide, 5.5), "a target size under twice the reach keeps the reach");
|
||||
for bad in [f32::NAN, f32::INFINITY, -1.0] {
|
||||
assert_eq!(HitShape::polyline_within(points.clone(), false, bad), line);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -23,8 +23,8 @@
|
||||
//! | The connection file | [`Connection`], [`write_connection`], [`read_connection`], [`remove_connection`], [`remove_stale_connection`], [`probe`] | desktop, feature `agents` |
|
||||
//! | The CLI's side | [`Live`], [`LiveConfig`], [`Route`], [`Window`], [`Consent`], [`HeadlessFolders`], [`find_window`], [`launcher`] | desktop, feature `agents` |
|
||||
//!
|
||||
//! The same formats as `craft_automation::agents` on the shared UI library's branch (`next`),
|
||||
//! which adds the egui link host and the Agents page of Preferences.
|
||||
//! `craft_automation::agents` re-exports all of this and adds the egui link host and the Agents
|
||||
//! page of Preferences, for apps on the shared UI library.
|
||||
//!
|
||||
//! # Adding an app
|
||||
//!
|
||||
|
||||
@@ -47,6 +47,11 @@ use super::{PathOptionsSettings, PathTool};
|
||||
/// Insert on a picked anchor adds one halfway along the segment leaving it.
|
||||
const INSERT: Chord = Chord::plain(Key::Insert);
|
||||
|
||||
/// How far from a segment, in screen points, an Add Anchor press or hover still takes it: the reference application
|
||||
/// adds an anchor 5 px from a segment at 100 % and none at 6 px. The other tools keep a line's reach
|
||||
/// ([`LINE_REACH`](craft_behavior::hit::LINE_REACH)).
|
||||
const ADD_ANCHOR_REACH: f32 = 5.0;
|
||||
|
||||
/// Above this many anchors in the paths shown, the overlay draws outlines only and declares no part (no anchor in
|
||||
/// the AccessKit tree either) (VectorCraft's `OVERLAY_MAX_ANCHORS`).
|
||||
pub const MAX_ANCHORS: usize = 100_000;
|
||||
@@ -66,14 +71,14 @@ pub enum BezierTool {
|
||||
Convert,
|
||||
/// Anchors drawn, not edited (PhotoCraft's Path Selection and Pen tools).
|
||||
Anchors,
|
||||
/// Add Anchor Point: a press on a segment inserts an anchor at the hit's `t` ([`PathEdit::InsertAnchor`]); a drag
|
||||
/// moves the new anchor, which is selected. A press on an anchor or a shown handle selects and drags it as
|
||||
/// [`BezierTool::Direct`] does (⇧ adds to the selection, ⌥ on a handle moves it alone), and a click on empty canvas
|
||||
/// deselects the anchors and keeps the path. With ⌥ a click on a segment selects its whole subpath and a drag moves a
|
||||
/// copy of it ([`PathEdit::DuplicateSubpath`]; the subpath itself on a path that takes no copies), and a press on
|
||||
/// an anchor does nothing. Hover: the segment mark with the anchor a click adds ([`HitMark`]) and the pen with "+";
|
||||
/// over an anchor the arrow; with ⌥ no mark and the arrow with "+"; the crosshair under the canvas's precise cursor
|
||||
/// ([`CanvasSpace::precise`]).
|
||||
/// Add Anchor Point: a press on a segment, within 5 screen points of it, inserts an anchor at the hit's `t`
|
||||
/// ([`PathEdit::InsertAnchor`]); a drag moves the new anchor, which is selected. A press on an anchor or a shown
|
||||
/// handle selects and drags it as [`BezierTool::Direct`] does (⇧ adds to the selection, ⌥ on a handle moves it
|
||||
/// alone), and a click on empty canvas deselects the anchors and keeps the path. With ⌥ a click on a segment selects
|
||||
/// its whole subpath and a drag moves a copy of it ([`PathEdit::DuplicateSubpath`]; the subpath itself on a path that
|
||||
/// takes no copies), and a press on an anchor does nothing. Hover: the segment mark with the anchor a click adds
|
||||
/// ([`HitMark`]) and the pen with "+"; over an anchor the arrow; with ⌥ no mark and the arrow with "+"; the
|
||||
/// crosshair under the canvas's precise cursor ([`CanvasSpace::precise`]).
|
||||
AddAnchor,
|
||||
/// Delete Anchor Point: a click on an anchor reports [`delete`](BezierOutput::delete) of that anchor; ⌥ makes it
|
||||
/// Add Anchor Point, except that a ⌥ click on an anchor selects its whole subpath. Hover: the anchor mark.
|
||||
@@ -508,13 +513,18 @@ impl<'a> BezierOverlay<'a> {
|
||||
let start = if ends && i == 0 { reach } else { 0.0 };
|
||||
let end = if ends && i + 1 == sub.segment_count() { reach } else { 0.0 };
|
||||
let Some(points) = trim_polyline(points, start, end) else { continue };
|
||||
let shape = if self.tool == BezierTool::AddAnchor {
|
||||
HitShape::polyline_within(points, false, ADD_ANCHOR_REACH)
|
||||
} else {
|
||||
HitShape::polyline(points, false)
|
||||
};
|
||||
items.push(Item {
|
||||
kind: Kind::Segment,
|
||||
path: at,
|
||||
key: path.key,
|
||||
knot: KnotRef::new(s, i),
|
||||
at: corners[0],
|
||||
shape: HitShape::polyline(points, false),
|
||||
shape,
|
||||
interior: true,
|
||||
straight: sub.is_straight(i),
|
||||
shown: true,
|
||||
|
||||
@@ -919,6 +919,63 @@ fn add_anchor_selects_and_edits_existing_anchors_and_handles() {
|
||||
}
|
||||
}
|
||||
|
||||
// Add Anchor reaches a segment within 5 screen points, as the reference application does (PhotoCraft #12732): a click
|
||||
// 2 to 5 points above or below a straight segment adds an anchor and shows the pen with "+", one 5.5 or 6 points away
|
||||
// adds nothing; Delete Anchor and Direct Selection keep a line's reach.
|
||||
#[trial]
|
||||
fn add_anchor_reaches_a_segment_within_5_points() {
|
||||
use craft_behavior::{Cursor, CursorBadge, PaintedCursor};
|
||||
let segment = p(110.0, 60.0);
|
||||
let at_tool = |tool: BezierTool| {
|
||||
let mut h = two_paths();
|
||||
h.update(|st| st.tool = tool);
|
||||
h
|
||||
};
|
||||
let click = |h: &mut Harness, at: Pos2| {
|
||||
h.press_at(at);
|
||||
h.release_at(at);
|
||||
};
|
||||
let pen_plus = |h: &Harness| {
|
||||
matches!(
|
||||
craft_ui::runtime::cursor::current(h.fixture.ctx()),
|
||||
Some(Cursor::Painted(PaintedCursor::Tool { badge: Some(CursorBadge::Add), .. }))
|
||||
)
|
||||
};
|
||||
for off in [2.0_f32, 3.0, 4.5, 5.0, -2.0, -5.0] {
|
||||
let mut h = at_tool(BezierTool::AddAnchor);
|
||||
let at = h.screen(segment) + vec2(0.0, off);
|
||||
h.move_to(at);
|
||||
h.fixture.frame(Vec::new());
|
||||
assert!(pen_plus(&h), "{off}: the pen with + shows where a click adds");
|
||||
click(&mut h, at);
|
||||
let st = h.state.borrow();
|
||||
assert!(matches!(st.changes.last(), Some(PathEdit::InsertAnchor { path: 1, segment, .. }) if *segment == kr(0)), "{off}: {:?}", st.changes);
|
||||
assert_eq!(st.paths[0].subpaths[0].knots.len(), 5, "{off}");
|
||||
}
|
||||
for off in [5.5_f32, 6.0, -6.0] {
|
||||
let mut h = at_tool(BezierTool::AddAnchor);
|
||||
let at = h.screen(segment) + vec2(0.0, off);
|
||||
h.move_to(at);
|
||||
h.fixture.frame(Vec::new());
|
||||
assert!(!pen_plus(&h), "{off}: no + past the reach");
|
||||
click(&mut h, at);
|
||||
let st = h.state.borrow();
|
||||
assert!(st.changes.is_empty() && st.seen.is_empty(), "{off}: {:?} {:?}", st.changes, st.seen);
|
||||
assert_eq!(st.paths, [path_a(), path_b()], "{off}");
|
||||
}
|
||||
// The other tools keep a line's reach: 4.5 points from the segment misses it, 3 points hits it.
|
||||
for tool in [BezierTool::DeleteAnchor, BezierTool::Direct] {
|
||||
let mut h = at_tool(tool);
|
||||
let near = h.screen(segment) + vec2(0.0, 3.0);
|
||||
h.drag(near, vec2(0.0, FAR));
|
||||
assert!(matches!(h.last_change(), Some(PathEdit::BendSegment { path: 1, .. })), "{tool:?}: {:?}", h.last_change());
|
||||
let mut h = at_tool(tool);
|
||||
let past = h.screen(segment) + vec2(0.0, 4.5);
|
||||
h.drag(past, vec2(0.0, FAR));
|
||||
assert!(!matches!(h.last_change(), Some(PathEdit::BendSegment { .. })), "{tool:?}: {:?}", h.last_change());
|
||||
}
|
||||
}
|
||||
|
||||
// The anchor tools' canvas tool: a press off the paths begins nothing (it never starts a path), and off the paths the
|
||||
// cursor says what a click does: the arrow for Add Anchor (with "+" under ⌥, PhotoCraft #12709), the pen
|
||||
// with "-" for Delete Anchor, the Convert Point icon, the arrow for Direct Selection and under ⌘, the crosshair when
|
||||
|
||||
@@ -6,7 +6,7 @@ use crate::contract::cx::{CxCore, Decls};
|
||||
use crate::contract::run::{ErasedPass, TypeFacts};
|
||||
use crate::primitives::FaceRecord;
|
||||
use crate::runtime::access::{self, Access, FaceFacts, Own, Politeness, Role, SetPosition, SubDecl, SubNode, scope};
|
||||
use crate::runtime::commands::{self, ResolvedCommand};
|
||||
use crate::runtime::commands::ResolvedCommand;
|
||||
use crate::runtime::env::{Label, Message};
|
||||
use crate::runtime::focus::{self};
|
||||
use crate::runtime::keys;
|
||||
@@ -33,8 +33,15 @@ pub(crate) struct ReportIn<'a> {
|
||||
}
|
||||
|
||||
/// The bound command's hint and shortcut text, which describe and key its node.
|
||||
fn command_facts(command: &ResolvedCommand, platform: craft_keymap::Platform) -> (Option<&str>, Option<String>) {
|
||||
(command.hint.as_deref(), command.chord.as_ref().map(|chord| chord.display(platform)))
|
||||
fn command_facts<'a>(ctx: &egui::Context, command: &'a ResolvedCommand) -> (Option<&'a str>, Option<&'a str>) {
|
||||
let text = command.chord_text.as_deref();
|
||||
#[cfg(feature = "testing")]
|
||||
if text.is_some() {
|
||||
crate::runtime::measure::count_chord_text(ctx);
|
||||
}
|
||||
#[cfg(not(feature = "testing"))]
|
||||
let _ = ctx;
|
||||
(command.hint.as_deref(), text)
|
||||
}
|
||||
|
||||
/// The message of a validity that warns, refuses or errs, and whether it warns.
|
||||
@@ -78,40 +85,10 @@ fn report_access(p: &dyn ErasedPass<'_>, facts: &TypeFacts, input: &ReportIn<'_>
|
||||
}
|
||||
}
|
||||
*core.value_text.borrow_mut() = value_text;
|
||||
for node in &mut access.nodes {
|
||||
if let Some(toggle) = core.toggles.iter().find(|toggle| toggle.part == node.part) {
|
||||
node.expanded = Some(toggle.open);
|
||||
}
|
||||
}
|
||||
let role = access.role.unwrap_or(facts.role);
|
||||
access.access_key = access.access_key.or(core.resolved.access_key);
|
||||
if access.grid == access::GridPlace::default() {
|
||||
access.grid = core.grid;
|
||||
}
|
||||
debug_assert!(access.role.is_none_or(|alt| facts.alt_roles.contains(&alt)), "`Access::role` picks one of `ALT_ROLES`");
|
||||
let flags = core.state.flags;
|
||||
let resolved = core.resolved;
|
||||
let platform = commands::platform(ctx);
|
||||
let (hint, shortcut) = core.command.as_deref().map_or((None, None), |command| command_facts(command, platform));
|
||||
let shortcut = shortcut.as_deref();
|
||||
for (_, label) in &mut access.custom_actions {
|
||||
*label = core.env.resolve(label);
|
||||
}
|
||||
let tooltip_text = resolved.tooltip.map(|tooltip| core.env.resolve(&tooltip.spec().text));
|
||||
let tooltip = tooltip_text.as_ref().map(Label::as_str);
|
||||
if access.live.is_none() {
|
||||
access.live = input.live;
|
||||
}
|
||||
if access.expanded.is_none() {
|
||||
access.expanded = input.expanded;
|
||||
}
|
||||
if access.position.is_none() {
|
||||
access.position = input.position;
|
||||
}
|
||||
if access.position.is_none() {
|
||||
access.position =
|
||||
input.group.and_then(|group| focus::group_position(ctx, id, group)).or_else(|| core.env.facts_of(id).map(|facts| facts.position));
|
||||
}
|
||||
let paint = core.paint.borrow();
|
||||
if role == Role::Merged {
|
||||
let facts = scope::Merged {
|
||||
@@ -132,6 +109,35 @@ fn report_access(p: &dyn ErasedPass<'_>, facts: &TypeFacts, input: &ReportIn<'_>
|
||||
if !input.node {
|
||||
return;
|
||||
}
|
||||
// Facts that only a node shows are built after the node check.
|
||||
for node in &mut access.nodes {
|
||||
if let Some(toggle) = core.toggles.iter().find(|toggle| toggle.part == node.part) {
|
||||
node.expanded = Some(toggle.open);
|
||||
}
|
||||
}
|
||||
access.access_key = access.access_key.or(core.resolved.access_key);
|
||||
if access.grid == access::GridPlace::default() {
|
||||
access.grid = core.grid;
|
||||
}
|
||||
let (hint, shortcut) = core.command.as_deref().map_or((None, None), |command| command_facts(ctx, command));
|
||||
for (_, label) in &mut access.custom_actions {
|
||||
*label = core.env.resolve(label);
|
||||
}
|
||||
let tooltip_text = resolved.tooltip.map(|tooltip| core.env.resolve(&tooltip.spec().text));
|
||||
let tooltip = tooltip_text.as_ref().map(Label::as_str);
|
||||
if access.live.is_none() {
|
||||
access.live = input.live;
|
||||
}
|
||||
if access.expanded.is_none() {
|
||||
access.expanded = input.expanded;
|
||||
}
|
||||
if access.position.is_none() {
|
||||
access.position = input.position;
|
||||
}
|
||||
if access.position.is_none() {
|
||||
access.position =
|
||||
input.group.and_then(|group| focus::group_position(ctx, id, group)).or_else(|| core.env.facts_of(id).map(|facts| facts.position));
|
||||
}
|
||||
let inner_of = access::fold::owner_of(ctx, id);
|
||||
let folded = access::fold::take(ctx, id);
|
||||
if access.value.is_none() {
|
||||
|
||||
@@ -32,6 +32,44 @@ enum Declaration {
|
||||
Focused { inactive: bool },
|
||||
}
|
||||
|
||||
/// The registered instances in registration order, which `pick_instance` ranks by, with their positions by id.
|
||||
#[derive(Default)]
|
||||
struct Instances {
|
||||
list: Vec<Instance>,
|
||||
at: HashMap<Id, usize>,
|
||||
}
|
||||
|
||||
impl Instances {
|
||||
fn get(&self, id: Id) -> Option<&Instance> {
|
||||
self.at.get(&id).map(|at| &self.list[*at])
|
||||
}
|
||||
|
||||
fn iter(&self) -> std::slice::Iter<'_, Instance> {
|
||||
self.list.iter()
|
||||
}
|
||||
|
||||
/// Registers `instance`, keeping the place of one already registered under the same id.
|
||||
fn upsert(&mut self, instance: Instance) {
|
||||
match self.at.get(&instance.id) {
|
||||
Some(at) => self.list[*at] = instance,
|
||||
None => {
|
||||
self.at.insert(instance.id, self.list.len());
|
||||
self.list.push(instance);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Keeps the instances `keep` accepts, in their order.
|
||||
fn retain(&mut self, mut keep: impl FnMut(&Instance) -> bool) {
|
||||
self.list.retain(|instance| keep(instance));
|
||||
self.at = self.list.iter().enumerate().map(|(at, instance)| (instance.id, at)).collect();
|
||||
}
|
||||
|
||||
fn contains(&self, id: Id) -> bool {
|
||||
self.at.contains_key(&id)
|
||||
}
|
||||
}
|
||||
|
||||
/// A container instance that receives scoped commands.
|
||||
struct Instance {
|
||||
id: Id,
|
||||
@@ -54,6 +92,8 @@ struct KeymapCache {
|
||||
edit_chords: Arc<[(EditCommand, Chord)]>,
|
||||
/// The chords bound to the window's keys, which the input hook takes before any component.
|
||||
window_shortcuts: Arc<[(WindowShortcut, Chord)]>,
|
||||
/// `BuiltKeymap::shown_text`.
|
||||
shown_text: Arc<HashMap<Chord, Arc<str>>>,
|
||||
}
|
||||
|
||||
/// A momentary command whose key is down: its release fires the command again.
|
||||
@@ -85,7 +125,7 @@ pub(crate) struct Board {
|
||||
out: Vec<Fired>,
|
||||
/// The commands instances took since the last `FrameOutput`, in order.
|
||||
delivered: Vec<Fired>,
|
||||
instances: Vec<Instance>,
|
||||
instances: Instances,
|
||||
/// The focused component of each viewport's last step 12 and the instances around it.
|
||||
chains: HashMap<ViewportId, (Id, CommandChain)>,
|
||||
/// The focused component and its chain before the one in `chains`, per viewport; while the focus is in the menus
|
||||
@@ -98,7 +138,7 @@ pub(crate) struct Board {
|
||||
matcher: Matcher,
|
||||
held: Vec<Held>,
|
||||
/// The top modal layer's root container of each viewport that has one.
|
||||
modal_roots: Vec<(ViewportId, Id)>,
|
||||
modal_roots: HashMap<ViewportId, Id>,
|
||||
/// The states published this pass, and the pass before, by an instance inside the top modal layer.
|
||||
modal_published: HashSet<StateKey>,
|
||||
modal_published_last: HashSet<StateKey>,
|
||||
@@ -129,7 +169,7 @@ fn same_state(a: Option<&CommandState>, b: Option<&CommandState>) -> bool {
|
||||
}
|
||||
|
||||
/// Who read a command's resolution: the vantage `begin` resolves it from again.
|
||||
#[derive(Clone, PartialEq, Eq)]
|
||||
#[derive(Clone, PartialEq, Eq, Hash)]
|
||||
enum Reader {
|
||||
/// A surface with no component of its own (`resolve_global`): the key focus of the running pass.
|
||||
Global,
|
||||
@@ -142,21 +182,19 @@ enum Reader {
|
||||
InMenu(Id, CommandChain),
|
||||
}
|
||||
|
||||
/// What a reader was shown the last time it resolved a command.
|
||||
struct Shown {
|
||||
reader: Reader,
|
||||
resolved: ResolvedCommand,
|
||||
}
|
||||
|
||||
/// The readers of each state key in each viewport.
|
||||
type ShownMap = HashMap<(StateKey, ViewportId), Vec<Shown>>;
|
||||
/// What each reader was shown the last time it resolved a command, by the viewport and the state key it read. The
|
||||
/// readers of a key stay in the order they first read it: the gate is app code, and `wake_shown` asks it in that order.
|
||||
type ShownMap = HashMap<ViewportId, HashMap<StateKey, Vec<(Reader, ResolvedCommand)>>>;
|
||||
|
||||
/// Keeps `resolved` as what `reader` of `viewport` was shown under `key`, in place of what it was shown before.
|
||||
fn keep_shown(shown: &mut ShownMap, key: StateKey, viewport: ViewportId, reader: Reader, resolved: &ResolvedCommand) {
|
||||
let readers = shown.entry((key, viewport)).or_default();
|
||||
match readers.iter_mut().find(|entry| entry.reader == reader) {
|
||||
Some(entry) => entry.resolved.clone_from(resolved),
|
||||
None => readers.push(Shown { reader, resolved: resolved.clone() }),
|
||||
keep_in(shown.entry(viewport).or_default().entry(key).or_default(), reader, resolved);
|
||||
}
|
||||
|
||||
fn keep_in(readers: &mut Vec<(Reader, ResolvedCommand)>, reader: Reader, resolved: &ResolvedCommand) {
|
||||
match readers.iter_mut().find(|(kept, _)| *kept == reader) {
|
||||
Some((_, kept)) => kept.clone_from(resolved),
|
||||
None => readers.push((reader, resolved.clone())),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -238,7 +276,7 @@ impl Board {
|
||||
/// The instance of `scope` a command routed to `at` goes to: `at` when it is an instance of the scope itself (a
|
||||
/// canvas), else the innermost instance in `around`, the chain of the context `at` was shown in.
|
||||
fn instance_around(&self, at: Id, around: &CommandChain, scope: &str) -> Option<Id> {
|
||||
let own = self.instances.iter().any(|i| i.id == at && self.within(i.scope.name(), scope));
|
||||
let own = self.instances.get(at).is_some_and(|i| self.within(i.scope.name(), scope));
|
||||
if own { Some(at) } else { self.innermost(around, scope) }
|
||||
}
|
||||
|
||||
@@ -262,7 +300,7 @@ impl Board {
|
||||
}
|
||||
|
||||
fn is_live(&self, ctx: &Context, id: Id) -> bool {
|
||||
self.instances.iter().any(|i| i.id == id && self.live(ctx, i))
|
||||
self.instances.get(id).is_some_and(|i| self.live(ctx, i))
|
||||
}
|
||||
|
||||
/// The definition of the command `id`: the linked sets', else the frame's app catalog's.
|
||||
@@ -301,7 +339,7 @@ impl Board {
|
||||
/// is declared inside, after its own.
|
||||
fn scopes_around(&self, chain: &[Id]) -> Vec<&'static str> {
|
||||
let mut scopes: Vec<&'static str> = Vec::new();
|
||||
for instance in chain.iter().rev().filter_map(|id| self.instances.iter().find(|i| i.id == *id)) {
|
||||
for instance in chain.iter().rev().filter_map(|id| self.instances.get(*id)) {
|
||||
let lineage = self.lineage(instance.scope.name());
|
||||
scopes.push(lineage[0]);
|
||||
let parents: Vec<&'static str> = lineage[1..].iter().copied().filter(|scope| !scopes.contains(scope)).collect();
|
||||
@@ -318,7 +356,7 @@ impl Board {
|
||||
}
|
||||
|
||||
fn is_modal_root(&self, id: Id) -> bool {
|
||||
self.modal_roots.iter().any(|(_, root)| *root == id)
|
||||
self.modal_roots.values().any(|root| *root == id)
|
||||
}
|
||||
|
||||
/// Where `command` goes when a source with no component of its own fires it: `None` for an app-scope command,
|
||||
@@ -398,10 +436,12 @@ impl Board {
|
||||
};
|
||||
let live = app || instance.is_some_and(|id| self.is_live(ctx, id));
|
||||
let chord = self.keymap.as_ref().and_then(|cache| cache.keymap.shown_chord(command));
|
||||
let chord_text = chord.and_then(|chord| self.keymap.as_ref()?.shown_text.get(&chord).cloned());
|
||||
let resolved = ResolvedCommand {
|
||||
label: state.and_then(|s| s.title_ref().cloned()).unwrap_or_else(|| Arc::from(def.map_or(command.id.as_str(), |def| def.label.as_str()))),
|
||||
icon: def.and_then(|def| def.icon.clone()),
|
||||
chord,
|
||||
chord_text,
|
||||
enabled: flags.enabled && modal && live && !matches!(declaring, Some(Declaration::Focused { inactive: true })),
|
||||
checked: flags.checked,
|
||||
marked: state.is_some_and(CommandState::is_marked),
|
||||
@@ -464,6 +504,8 @@ pub(crate) struct BuiltKeymap {
|
||||
keymap: Arc<Keymap>,
|
||||
edit_chords: Arc<[(EditCommand, Chord)]>,
|
||||
window_shortcuts: Arc<[(WindowShortcut, Chord)]>,
|
||||
/// The text of every chord the keymap shows, written once when the keymap is built.
|
||||
shown_text: Arc<HashMap<Chord, Arc<str>>>,
|
||||
}
|
||||
|
||||
/// The keymap of `defs` on `platform` under `overrides`.
|
||||
@@ -475,6 +517,19 @@ fn keymap_of(defs: Vec<CommandDef>, scopes: Scopes, platform: Platform, override
|
||||
keymap
|
||||
}
|
||||
|
||||
#[cfg(feature = "testing")]
|
||||
thread_local! {
|
||||
static CHORD_TEXT_BUILDS: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// How many chord texts this thread's keymap builds have written: one per distinct shown chord per build, never one
|
||||
/// per report.
|
||||
#[cfg(feature = "testing")]
|
||||
#[doc(hidden)]
|
||||
pub fn chord_text_builds() -> u64 {
|
||||
CHORD_TEXT_BUILDS.with(std::cell::Cell::get)
|
||||
}
|
||||
|
||||
#[cfg(feature = "testing")]
|
||||
thread_local! {
|
||||
static KEYMAP_BUILDS: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
|
||||
@@ -558,7 +613,17 @@ fn build_keymap(registry: ®istry::Registry, app: Option<&AppCatalog>, platfor
|
||||
keymap.bindings(command).into_iter().filter(|binding| !binding.trigger.double).map(move |binding| (edit, binding.trigger.chord))
|
||||
})
|
||||
.collect();
|
||||
BuiltKeymap { keymap: Arc::new(keymap), edit_chords, window_shortcuts }
|
||||
let mut shown_text = HashMap::new();
|
||||
for def in keymap.catalog() {
|
||||
if let Some(chord) = keymap.shown_chord(&def.command) {
|
||||
shown_text.entry(chord).or_insert_with(|| {
|
||||
#[cfg(feature = "testing")]
|
||||
CHORD_TEXT_BUILDS.with(|builds| builds.set(builds.get() + 1));
|
||||
Arc::from(chord.display(platform))
|
||||
});
|
||||
}
|
||||
}
|
||||
BuiltKeymap { keymap: Arc::new(keymap), edit_chords, window_shortcuts, shown_text: Arc::new(shown_text) }
|
||||
}
|
||||
|
||||
/// Builds or reuses a keymap owned by this exact command registry.
|
||||
@@ -590,7 +655,7 @@ pub(crate) fn innermost(ctx: &Context, chain: &CommandChain, scope: &str) -> Opt
|
||||
}
|
||||
|
||||
/// The platform the keymap and the chords shown are read for.
|
||||
pub(crate) fn platform(ctx: &Context) -> Platform {
|
||||
fn platform(ctx: &Context) -> Platform {
|
||||
crate::runtime::windows::os_of(ctx)
|
||||
}
|
||||
|
||||
@@ -624,9 +689,10 @@ pub(crate) fn set_input(ctx: &Context, input: &CommandInput) {
|
||||
});
|
||||
let mut shadowed = Vec::new();
|
||||
if stale {
|
||||
let BuiltKeymap { keymap, edit_chords, window_shortcuts } =
|
||||
let BuiltKeymap { keymap, edit_chords, window_shortcuts, shown_text } =
|
||||
keymap_for(&board.registry, input.catalog.as_ref(), platform, input.overrides.as_ref());
|
||||
board.keymap = Some(KeymapCache { keymap, platform, overrides: input.overrides.clone(), generation, edit_chords, window_shortcuts });
|
||||
board.keymap =
|
||||
Some(KeymapCache { keymap, platform, overrides: input.overrides.clone(), generation, edit_chords, window_shortcuts, shown_text });
|
||||
for def in input.catalog.as_ref().map_or(&[][..], AppCatalog::defs) {
|
||||
if board.registry.get(&def.command.id).is_some() && board.shadowed.insert(def.command.id.clone()) {
|
||||
shadowed.push(def.command.id.clone());
|
||||
@@ -693,15 +759,7 @@ fn register_in(ctx: &Context, scope: CommandScope, id: Id, layer: Option<Id>) {
|
||||
crate::runtime::replay::journal(ctx, || move |ctx: &Context| register_in(ctx, scope, id, layer));
|
||||
let viewport = pass::current_viewport(ctx);
|
||||
let stamp = pass::pass_nr(ctx, viewport);
|
||||
with(ctx, |board| match board.instances.iter_mut().find(|i| i.id == id) {
|
||||
Some(instance) => {
|
||||
instance.scope = scope;
|
||||
instance.viewport = viewport;
|
||||
instance.stamp = stamp;
|
||||
instance.layer = layer;
|
||||
}
|
||||
None => board.instances.push(Instance { id, scope, viewport, stamp, layer }),
|
||||
});
|
||||
with(ctx, |board| board.instances.upsert(Instance { id, scope, viewport, stamp, layer }));
|
||||
}
|
||||
|
||||
/// Records the instances around the component `id`, which holds key focus in the running pass of its viewport. The
|
||||
@@ -725,14 +783,16 @@ pub(crate) fn note_focus(ctx: &Context, id: Id, chain: &CommandChain) {
|
||||
pub(crate) fn set_modal_open(ctx: &Context, open: bool, viewport: ViewportId, root: Option<Id>) {
|
||||
with(ctx, |board| {
|
||||
board.here.modal_open = open;
|
||||
board.modal_roots.retain(|(of, _)| *of != viewport);
|
||||
board.modal_roots.extend(root.map(|root| (viewport, root)));
|
||||
match root {
|
||||
Some(root) => board.modal_roots.insert(viewport, root),
|
||||
None => board.modal_roots.remove(&viewport),
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
/// The root of the top modal layer of `viewport`, if one is open.
|
||||
pub(crate) fn modal_root(ctx: &Context, viewport: ViewportId) -> Option<Id> {
|
||||
with(ctx, |board| board.modal_roots.iter().find(|(of, _)| *of == viewport).map(|(_, root)| *root))
|
||||
with(ctx, |board| board.modal_roots.get(&viewport).copied())
|
||||
}
|
||||
|
||||
/// Which instances a resolution counts as inside the top modal layer, where `ModalRule::InDialogs` and `Blocked`
|
||||
@@ -891,35 +951,35 @@ fn resolve_from(ctx: &Context, command: &CommandRef, from: Option<&Vantage>) ->
|
||||
/// and what the first pass's call kept, so it wakes only the readers whose resolution the first pass changed (a modal
|
||||
/// layer it opened or closed), once.
|
||||
fn wake_shown(ctx: &Context, viewport: ViewportId) {
|
||||
let mut shown = with(ctx, |board| std::mem::take(&mut board.shown));
|
||||
let mut table = with(ctx, |board| board.shown.remove(&viewport)).unwrap_or_default();
|
||||
let mut changed = Vec::new();
|
||||
for ((key, of), readers) in &mut shown {
|
||||
if *of != viewport {
|
||||
continue;
|
||||
}
|
||||
for (key, readers) in &mut table {
|
||||
// A reader beneath a layer or inside a menu that is no longer shown is gone with it.
|
||||
readers.retain(|entry| match entry.reader {
|
||||
Reader::Beneath(layer) | Reader::InMenu(layer, _) => overlay::is_open(ctx, layer),
|
||||
readers.retain(|(reader, _)| match reader {
|
||||
Reader::Beneath(layer) | Reader::InMenu(layer, _) => overlay::is_open(ctx, *layer),
|
||||
_ => true,
|
||||
});
|
||||
for entry in readers.iter_mut() {
|
||||
for (reader, kept) in readers.iter_mut() {
|
||||
// The gate is app code and may resolve commands itself, so no board lock is held here.
|
||||
let (resolved, _) = resolve_as(ctx, &entry.reader, &entry.resolved.command);
|
||||
if resolved != entry.resolved {
|
||||
entry.resolved = resolved;
|
||||
let (resolved, _) = resolve_as(ctx, reader, &kept.command);
|
||||
if resolved != *kept {
|
||||
*kept = resolved;
|
||||
changed.push(*key);
|
||||
}
|
||||
}
|
||||
}
|
||||
shown.retain(|_, readers| !readers.is_empty());
|
||||
table.retain(|_, readers| !readers.is_empty());
|
||||
with(ctx, |board| {
|
||||
// Reads the gate made while the entries were out of the board.
|
||||
let added = std::mem::replace(&mut board.shown, shown);
|
||||
for ((key, of), readers) in added {
|
||||
for entry in readers {
|
||||
keep_shown(&mut board.shown, key, of, entry.reader, &entry.resolved);
|
||||
let added = board.shown.remove(&viewport).unwrap_or_default();
|
||||
for (key, readers) in added {
|
||||
for (reader, resolved) in readers {
|
||||
keep_in(table.entry(key).or_default(), reader, &resolved);
|
||||
}
|
||||
}
|
||||
if !table.is_empty() {
|
||||
board.shown.insert(viewport, table);
|
||||
}
|
||||
});
|
||||
for (number, instance) in changed {
|
||||
lazy::note_edit(ctx, BindKey::Command(number, instance));
|
||||
@@ -1191,8 +1251,8 @@ pub(crate) fn begin(ctx: &Context) {
|
||||
board.chains.get(&viewport).filter(|(id, _)| Some(*id) == focused).map(|(_, chain)| chain.ids().collect()).unwrap_or_default()
|
||||
});
|
||||
// Nothing focused inside a modal: the modal's root takes the commands, as a plain Enter goes to its default button.
|
||||
let chain = match (chain.is_empty() && focused.is_none(), board.modal_roots.iter().find(|(of, _)| *of == viewport)) {
|
||||
(true, Some((_, root))) => vec![*root],
|
||||
let chain = match (chain.is_empty() && focused.is_none(), board.modal_roots.get(&viewport)) {
|
||||
(true, Some(root)) => vec![*root],
|
||||
_ => chain,
|
||||
};
|
||||
if !chain.is_empty() {
|
||||
@@ -1212,7 +1272,7 @@ pub(crate) fn begin(ctx: &Context) {
|
||||
}
|
||||
let mut keys = board.key_scopes(&chain)?;
|
||||
// The held-open canvas's scope is around the focus for matching: its commands fire from the dialog.
|
||||
let held_scope = held_open.and_then(|id| board.instances.iter().find(|i| i.id == id)).map(|i| i.scope.name()).filter(|scope| !is_app(scope));
|
||||
let held_scope = held_open.and_then(|id| board.instances.get(id)).map(|i| i.scope.name()).filter(|scope| !is_app(scope));
|
||||
if let Some(scope) = held_scope
|
||||
&& !keys.scopes.contains(&scope)
|
||||
{
|
||||
@@ -1289,7 +1349,7 @@ pub(crate) fn begin(ctx: &Context) {
|
||||
.iter()
|
||||
.filter(|fired| fired.phase == FirePhase::Press)
|
||||
.filter_map(|fired| fired.target)
|
||||
.filter_map(|target| board.instances.iter().find(|instance| instance.id == target)?.layer)
|
||||
.filter_map(|target| board.instances.get(target)?.layer)
|
||||
.collect()
|
||||
});
|
||||
overlay::close_popups_outside(ctx, &inside);
|
||||
@@ -1307,18 +1367,22 @@ pub(crate) fn end(ctx: &Context) {
|
||||
let alive: Vec<bool> = board.instances.iter().map(|i| board.live(ctx, i) && live.contains(&i.viewport)).collect();
|
||||
let mut keep = alive.iter();
|
||||
board.instances.retain(|_| keep.next().copied().unwrap_or(false));
|
||||
let ids: Vec<Id> = board.instances.iter().map(|i| i.id).collect();
|
||||
board.queue.retain(|fired| fired.target.is_some_and(|id| ids.contains(&id)));
|
||||
board.held.retain(|held| held.target.is_none_or(|id| ids.contains(&id)));
|
||||
let instances = &board.instances;
|
||||
let ids = |id: Id| instances.contains(id);
|
||||
board.queue.retain(|fired| fired.target.is_some_and(ids));
|
||||
board.held.retain(|held| held.target.is_none_or(ids));
|
||||
board.chains.retain(|viewport, _| live.contains(viewport));
|
||||
board.before.retain(|viewport, _| live.contains(viewport));
|
||||
board.here.focused.retain(|(viewport, _)| live.contains(viewport));
|
||||
board.shown.retain(|(_, viewport), readers| {
|
||||
readers.retain(|entry| match &entry.reader {
|
||||
Reader::Chain(chain) | Reader::InMenu(_, chain) => chain.innermost_any().is_none_or(|id| ids.contains(&id)),
|
||||
_ => true,
|
||||
board.shown.retain(|viewport, table| {
|
||||
table.retain(|_, readers| {
|
||||
readers.retain(|(reader, _)| match reader {
|
||||
Reader::Chain(chain) | Reader::InMenu(_, chain) => chain.innermost_any().is_none_or(&ids),
|
||||
_ => true,
|
||||
});
|
||||
!readers.is_empty()
|
||||
});
|
||||
live.contains(viewport) && !readers.is_empty()
|
||||
live.contains(viewport) && !table.is_empty()
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
@@ -21,16 +21,16 @@ pub(crate) use registry::{StorySelection, configure_story_sets, with_story_sets}
|
||||
pub use board::declare_child;
|
||||
#[doc(hidden)]
|
||||
pub use board::focus_within;
|
||||
#[cfg(feature = "testing")]
|
||||
#[doc(hidden)]
|
||||
pub use board::keymap_builds;
|
||||
pub(crate) use board::publish as publish_for;
|
||||
pub(crate) use board::take as take_for_instance;
|
||||
pub(crate) use board::{
|
||||
begin, binds_scoped, edit_chords, end, install, note_focus, platform, register_instance, set_input, take_delivered, take_fired, window_shortcuts,
|
||||
begin, binds_scoped, edit_chords, end, install, note_focus, register_instance, set_input, take_delivered, take_fired, window_shortcuts,
|
||||
};
|
||||
#[doc(hidden)]
|
||||
pub use board::{bound_around, take_around};
|
||||
#[cfg(feature = "testing")]
|
||||
#[doc(hidden)]
|
||||
pub use board::{chord_text_builds, keymap_builds};
|
||||
pub(crate) use board::{fire_bound, fire_resolved, resolve_bound, resolve_scoped};
|
||||
|
||||
use craft_behavior::CommandFlags;
|
||||
@@ -263,6 +263,8 @@ pub struct ResolvedCommand {
|
||||
pub icon: Option<Cow<'static, str>>,
|
||||
/// The chord surfaces show: the first single-press binding that runs the command ([`chord`]).
|
||||
pub chord: Option<Chord>,
|
||||
/// `chord` as the platform writes it, from the table the keymap builds with its bindings.
|
||||
pub chord_text: Option<Arc<str>>,
|
||||
/// The state ANDed with the gate, the modal rule and the instance's liveness.
|
||||
pub enabled: bool,
|
||||
/// The checked state of a toggle or radio command.
|
||||
@@ -343,7 +345,7 @@ impl CommandInput {
|
||||
/// The chain of container instances that receive scoped commands, innermost last. A private inherited field of
|
||||
/// the env.
|
||||
#[doc(hidden)]
|
||||
#[derive(Clone, Default, PartialEq, Eq)]
|
||||
#[derive(Clone, Default, PartialEq, Eq, Hash)]
|
||||
pub struct CommandChain(Arc<[(CommandScope, Id)]>);
|
||||
|
||||
impl CommandChain {
|
||||
|
||||
@@ -285,6 +285,18 @@ pub fn row_measures(ctx: &Context) -> Vec<(Id, u32)> {
|
||||
store::with::<RowMeasures, _>(ctx, |log| if log.pass == last { log.rows.clone() } else { Vec::new() })
|
||||
}
|
||||
|
||||
/// Counts a chord text an access report read for a node in this pass.
|
||||
#[cfg(feature = "testing")]
|
||||
pub(crate) fn count_chord_text(ctx: &Context) {
|
||||
totals(ctx, |log| log.chord_texts += 1);
|
||||
}
|
||||
|
||||
/// The chord texts the access reports of the last pass read: one per command-bound node that exists.
|
||||
#[cfg(feature = "testing")]
|
||||
pub fn chord_texts(ctx: &Context) -> u32 {
|
||||
last_totals(ctx, |log| log.chord_texts, 0)
|
||||
}
|
||||
|
||||
/// Counts a sweep of the row `id` that asks its body units for their least widths in this pass.
|
||||
#[cfg(feature = "testing")]
|
||||
pub(crate) fn count_least(ctx: &Context, id: Id) {
|
||||
@@ -347,13 +359,14 @@ pub fn last_pass_settles(ctx: &Context) -> Vec<(Id, Settle)> {
|
||||
pass_state::with::<SettleLog, _>(ctx, |log| if log.pass == last { log.decisions.clone() } else { Vec::new() })
|
||||
}
|
||||
|
||||
/// Bytes fed into memo keys in one pass, and the layouts and measure asks of that pass.
|
||||
/// Bytes fed into memo keys in one pass, and the layouts, measure asks and chord texts of that pass.
|
||||
#[cfg(feature = "testing")]
|
||||
#[derive(Default)]
|
||||
pub(crate) struct PassTotals {
|
||||
pass: u64,
|
||||
key_bytes: usize,
|
||||
text_layouts: u32,
|
||||
chord_texts: u32,
|
||||
asks: Vec<(&'static str, u32)>,
|
||||
}
|
||||
|
||||
|
||||
@@ -219,11 +219,10 @@ impl<T: Value + 'static> Component for FlyoutButton<'_, T> {
|
||||
|
||||
fn parts(&mut self, rect: Rect, cx: &mut PartsCx<'_, Self>) {
|
||||
let laid = self.resolve(cx);
|
||||
let os = cx.env.shell().os;
|
||||
let face = cx.part(FACE, rect).priority(HitPriority::new(HitLevel::Body, 0));
|
||||
if let Some(resolved) = self.lead(&laid) {
|
||||
face.tooltip(match &resolved.chord {
|
||||
Some(chord) => Label::from(format!("{} ({})", resolved.label, chord.display(os))),
|
||||
face.tooltip(match &resolved.chord_text {
|
||||
Some(chord) => Label::from(format!("{} ({chord})", resolved.label)),
|
||||
None => Label::Shared(resolved.label.clone()),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
use super::kit::{AppCommand, Dock, DockCommand, PaneCommand, Tap};
|
||||
use super::kit::{AppCommand, Dock, DockCommand, PaneCommand, Silent, Tap};
|
||||
use craft_ui::contract::{Props as _, Show as _, ShowContainer as _};
|
||||
use craft_ui::runtime::commands::{
|
||||
CommandGate, CommandInput, CommandRef, CommandState, Commands as _, EditCommands, FireSource, Fired, fire, resolve,
|
||||
CommandGate, CommandInput, CommandRef, CommandState, Commands as _, EditCommands, FireSource, Fired, chord_text_builds, fire, resolve,
|
||||
};
|
||||
use craft_ui::runtime::focus::{FocusTarget, request};
|
||||
use craft_ui::runtime::frame::take_output;
|
||||
use craft_ui::runtime::measure::chord_texts;
|
||||
use craft_ui::testing::input::key_press;
|
||||
use craft_ui::testing::pointer::{moved, press, release};
|
||||
use craft_ui::testing::{Frames, trial};
|
||||
@@ -193,3 +194,59 @@ fn undo_in_a_dialog_reaches_the_dialog_and_not_the_application() {
|
||||
assert_eq!(undone.get(), 1, "the dialog took the undo");
|
||||
assert!(take_output(&frames.ctx).fired.is_empty(), "the application's undo stays blocked");
|
||||
}
|
||||
|
||||
/// Count relation: an access report reads a chord text for each command-bound node that exists, at any number of nodes,
|
||||
/// never for a component with no node, and writes none; the texts are written when the keymap is built.
|
||||
#[trial]
|
||||
fn access_reports_read_chord_texts_for_their_nodes_and_write_none() {
|
||||
let mut frames = Frames::new();
|
||||
let mut built = 0;
|
||||
for count in [6, 12] {
|
||||
let mut show = |ui: &mut Ui| {
|
||||
for salt in 0..count {
|
||||
Tap::new().id_salt(salt).command(AppCommand::Save).show(ui);
|
||||
}
|
||||
Tap::new().id_salt("go").command(AppCommand::Go).show(ui);
|
||||
Silent::new().id_salt("silent").command(AppCommand::Save).show(ui);
|
||||
};
|
||||
frames.idle(3, &mut show);
|
||||
if built == 0 {
|
||||
built = chord_text_builds();
|
||||
}
|
||||
frames.idle(3, &mut show);
|
||||
assert_eq!(chord_text_builds(), built, "passes write no chord text");
|
||||
assert_eq!(chord_texts(&frames.ctx), count, "one read per node whose command has a chord, none for a component with no node");
|
||||
}
|
||||
}
|
||||
|
||||
/// An instance that stops registering and registers again goes last in registration order, which a non-component
|
||||
/// source's pick follows (the first live instance); lookups by id stay right throughout.
|
||||
#[trial]
|
||||
fn a_re_registered_instance_goes_last_in_the_pick() {
|
||||
let a_shown = Cell::new(true);
|
||||
let taker = Cell::new("");
|
||||
let mut show = |ui: &mut Ui| {
|
||||
for name in ["a", "b", "c"] {
|
||||
if name == "a" && !a_shown.get() {
|
||||
continue;
|
||||
}
|
||||
super::kit::Pane::new().id_salt(name).show(ui, |_, cx| {
|
||||
if cx.take_command::<PaneCommand>().is_some() {
|
||||
taker.set(name);
|
||||
}
|
||||
});
|
||||
}
|
||||
};
|
||||
let mut frames = Frames::new();
|
||||
frames.idle(3, &mut show);
|
||||
assert!(fire(&frames.ctx, PaneCommand::ZoomIn, FireSource::Palette));
|
||||
frames.idle(2, &mut show);
|
||||
assert_eq!(taker.get(), "a", "registered first");
|
||||
a_shown.set(false);
|
||||
frames.idle(3, &mut show);
|
||||
a_shown.set(true);
|
||||
frames.idle(3, &mut show);
|
||||
assert!(fire(&frames.ctx, PaneCommand::ZoomIn, FireSource::Palette));
|
||||
frames.idle(2, &mut show);
|
||||
assert_eq!(taker.get(), "b", "a registered again after b and c");
|
||||
}
|
||||
|
||||
@@ -89,6 +89,37 @@ impl Component for Tap<'_> {
|
||||
}
|
||||
}
|
||||
|
||||
/// A `Tap` whose role gives it no access node.
|
||||
#[derive(Component)]
|
||||
pub struct Silent {
|
||||
#[common]
|
||||
common: Common,
|
||||
}
|
||||
|
||||
impl Silent {
|
||||
pub fn new() -> Self {
|
||||
Silent { common: Common::new() }
|
||||
}
|
||||
}
|
||||
|
||||
impl Component for Silent {
|
||||
const ROLE: Role = Role::None;
|
||||
type Style = FixedStyle;
|
||||
type Output = Response;
|
||||
|
||||
fn style(_: &StyleCx<'_>, _: SilentStyleKey) -> FixedStyle {
|
||||
FixedStyle::default()
|
||||
}
|
||||
|
||||
fn measure(&mut self, _: &craft_ui::contract::MeasureCx<'_, Self>) -> Vec2 {
|
||||
Vec2::new(40.0, 20.0)
|
||||
}
|
||||
|
||||
fn finish(self, cx: Cx<'_, Self>) -> Response {
|
||||
cx.response.clone()
|
||||
}
|
||||
}
|
||||
|
||||
/// A container that is an instance of the `trial.pane` scope.
|
||||
#[derive(Component)]
|
||||
#[component(container)]
|
||||
|
||||
@@ -1123,7 +1123,7 @@ Control channel, screenshot queue, profiler and recorded actions for tests and s
|
||||
| `protocol` | JSON-lines wire format and parameter validators | exists |
|
||||
| `security` | Tokens, the authentication handshake (challenge or one-frame token) and transport limits | exists |
|
||||
| `server` | Loopback JSON-lines TCP transport (native): `listen`, `serve`, stopped by dropping its `Listening` | exists |
|
||||
| `agents`, `ui::agents` | AI agents in the open window: the agent settings, the ArtCraft Launcher's switch, the connection file, the link host and the Agents page of Preferences | exists |
|
||||
| `agents`, `ui::agents` | AI agents in the open window: the agent settings, the ArtCraft Launcher's switch, the connection file and the CLI's live client (re-exported from `craft-control`), the link host and the Agents page of Preferences | exists |
|
||||
| `client` | JSON-lines client for tests and command-line tools (native) | exists |
|
||||
| `synthetic` | Synthetic pointer and keyboard input: `ui.click`, `ui.move`, `ui.key`, `ui.type` | exists |
|
||||
| `dialogs` | `ui.dialog.set`, `ui.dialog.confirm` and `ui.dialog.cancel` over a `DialogHost` | exists |
|
||||
|
||||
Reference in New Issue
Block a user