Merge branch 'red/screenmode' into m/stage

This commit is contained in:
aiongg
2026-11-17 08:30:02 +00:00
7 changed files with 169 additions and 19 deletions
+3 -2
View File
@@ -22,8 +22,9 @@ use craft_keymap::Mods;
#[command(prefix = "canvasMomentary", scope = "canvasView")]
#[non_exhaustive]
pub enum MomentaryCommands {
/// The Hand tool while the key is held.
#[command(label = "Hand (Hold)", kind = "momentary", modal = "in_dialogs", default = "Space")]
/// The Hand tool while the key is held. While it is held, the keys of the `canvasHand` scope come before every
/// other scope's: an app binds there what a key does with the Hand held (Photoshop's Space+F).
#[command(label = "Hand (Hold)", kind = "momentary", modal = "in_dialogs", default = "Space", holds = "canvasHand")]
Hand,
/// The Zoom tool, zooming in, while the keys are held.
#[command(label = "Zoom In (Hold)", kind = "momentary", modal = "in_dialogs", default = "Cmd+Space")]
@@ -10,7 +10,7 @@ use crate::runtime::egui::{pass, repaint};
use crate::runtime::focus::EditSet;
use crate::runtime::pass_state;
use crate::runtime::reads::{self, BindKey};
use crate::runtime::{focus, keys, lazy, measure, overlay, replay, sampler};
use crate::runtime::{focus, frame, keys, lazy, measure, overlay, replay, sampler};
use craft_behavior::{EditCommand, KeyOwner, OwnerClass, pick_instance, resolve_flags};
use craft_keymap::{
Active, Chord, CommandDef, CommandKind, CommandRef, Hit, KeyInput, Keymap, Layout, Matcher, ModalRule, Overrides, Platform, Press, Scopes,
@@ -242,7 +242,18 @@ impl Board {
/// The keymap and the scopes a key matches in while `chain` (outermost first) has the keys.
fn key_scopes(&self, chain: &[Id]) -> Option<KeyScopes> {
let keymap = self.keymap.as_ref().map(|cache| Arc::clone(&cache.keymap))?;
Some(KeyScopes { keymap, scopes: self.scopes_around(chain) })
Some(KeyScopes { keymap, scopes: self.scopes_around(chain), held: self.held_scopes() })
}
/// The scopes whose keys work now: those of the momentary commands whose key is held.
fn held_scopes(&self) -> Vec<&'static str> {
self.held.iter().filter_map(|held| self.registry.held_scope(&held.command.id)).collect()
}
/// Whether the commands of `scope` go to the application: the app scope's, and a held scope's, which no instance
/// is ever of.
fn to_app(&self, scope: &str) -> bool {
is_app(scope) || self.registry.is_held_scope(scope)
}
fn is_live(&self, ctx: &Context, id: Id) -> bool {
@@ -309,7 +320,7 @@ impl Board {
/// else the picked instance, which may not exist.
fn target_of(&self, ctx: &Context, command: &CommandRef, from: &Vantage) -> (bool, Option<Id>) {
let scope = self.scope_of(command);
let app = is_app(scope);
let app = self.to_app(scope);
(app, if app { None } else { self.pick(ctx, scope, from) })
}
@@ -344,7 +355,7 @@ impl Board {
from: &Vantage,
) -> (ResolvedCommand, Option<StateKey>) {
let def = self.def(&command.id);
let app = is_app(self.scope_of(command));
let app = self.to_app(self.scope_of(command));
let instance = if app { None } else { instance };
let dialog_open = from.modal_open || from.dialog_keys;
// A command no set registers is never blocked.
@@ -408,14 +419,18 @@ fn is_app(scope: &str) -> bool {
struct KeyScopes {
keymap: Arc<Keymap>,
scopes: Vec<&'static str>,
/// The held scopes ([`Board::held_scopes`]): the keymap's contexts, whose keys come before every scope's.
held: Vec<&'static str>,
}
impl KeyScopes {
/// What a press of `input` runs, read through `layout`, with `typing` when a text field has the keys. With
/// `matcher` and the press's time the press counts toward a double press; without, it is matched on its own.
/// `matcher` and the press's time the press counts toward a double press; without, it is matched on its own. A
/// held scope's keys stay with the text while typing.
fn press(&self, layout: &Layout, input: &KeyInput, typing: bool, matcher: Option<(&mut Matcher, f64)>) -> Option<Hit> {
let (panel, outer) = self.scopes.split_first().map_or((None, &[][..]), |(panel, outer)| (Some(*panel), outer));
let active = Active { panel, contexts: &[], typing };
let held: &[&str] = if typing { &[] } else { &self.held };
let active = Active { panel, contexts: held, typing };
match matcher {
Some((matcher, now)) => matcher.press(layout, &self.keymap, &Press { input, repeat: false, now, active: &active, outer }),
None => Matcher::single(layout, &self.keymap, input, &active, outer),
@@ -475,9 +490,12 @@ pub fn keymap_builds() -> u64 {
fn build_keymap(registry: &registry::Registry, app: Option<&AppCatalog>, platform: Platform, overrides: Option<&Arc<Overrides>>) -> BuiltKeymap {
#[cfg(feature = "testing")]
KEYMAP_BUILDS.with(|builds| builds.set(builds.get() + 1));
// A held scope is a context of the keymap: its keys work while it is active, before any panel's.
let mut scopes = Scopes::new();
for def in registry.defs() {
if !def.scope.is_app() {
if registry.is_held_scope(def.scope.as_str()) {
scopes = scopes.with_context(def.scope.as_str());
} else if !def.scope.is_app() {
scopes = scopes.with_panel(def.scope.as_str());
}
}
@@ -895,7 +913,7 @@ fn wake_shown(ctx: &Context, viewport: ViewportId) {
pub(crate) fn resolve_scoped(ctx: &Context, chain: &CommandChain, command: &CommandRef) -> Option<ResolvedCommand> {
let (found, app) = with(ctx, |board| {
let scope = board.scope_of(command);
(board.innermost(chain, scope).is_some(), is_app(scope))
(board.innermost(chain, scope).is_some(), board.to_app(scope))
});
if !app && !found {
return None;
@@ -1145,6 +1163,7 @@ pub(crate) fn begin(ctx: &Context) {
let held_open = sampler::held_canvas(ctx);
// A shortcut pressed in a menu or on a menu bar matches where the focus returns to once the menus close.
let returning = focused.filter(|_| !shortcuts.keys.is_empty()).and_then(|focused| Returning::of(ctx, focused));
let shell = frame::shell_root(ctx, viewport);
let taken = with(ctx, |board| {
board.held_open = held_open;
let returned = returning
@@ -1162,6 +1181,9 @@ pub(crate) fn begin(ctx: &Context) {
if !chain.is_empty() {
board.last_focused.clone_from(&chain);
}
// Nothing focused outside a modal: the window's shell root takes the commands, so a window command's key comes
// before an app command's. Nothing holds focus there, so the chain last focused stays.
let chain = if chain.is_empty() && focused.is_none() { shell.into_iter().collect() } else { chain };
match board.here.focused.iter_mut().find(|(v, _)| *v == viewport) {
Some(entry) => entry.1.clone_from(&chain),
None => board.here.focused.push((viewport, chain.clone())),
@@ -101,6 +101,11 @@ pub trait CommandSet: Copy + Send + Sync + 'static {
#[doc(hidden)]
fn edits() -> Vec<(&'static str, EditCommand)>;
/// The momentary commands whose held key makes a scope's keys work, as `(id, scope)`: the `holds` option of the
/// command's attribute.
#[doc(hidden)]
fn holds() -> Vec<(&'static str, CommandScope)>;
/// The defaults of one platform, as `(id, platform, binding)`: on that platform they replace the command's other
/// defaults.
#[doc(hidden)]
@@ -1,7 +1,7 @@
//! The registry of command definitions: the sets `#[derive(CommandSet)]` registers, loaded at install.
use craft_behavior::EditCommand;
use craft_keymap::{Binding, BindingError, CommandDef, Platform};
use craft_keymap::{Binding, BindingError, CommandDef, CommandScope, Platform};
use std::collections::{HashMap, HashSet};
use std::sync::{Arc, OnceLock};
@@ -21,6 +21,8 @@ pub struct SetEntry {
pub no_default_on: fn() -> Vec<(&'static str, Platform)>,
/// The commands of the set a focused component takes as an edit.
pub edits: fn() -> Vec<(&'static str, EditCommand)>,
/// The momentary commands of the set whose held key makes a scope's keys work.
pub holds: fn() -> Vec<(&'static str, CommandScope)>,
/// The defaults of one platform, which replace the command's other defaults there.
pub platform_defaults: fn() -> Result<Vec<PlatformDefault>, CommandDefError>,
/// A story's set (`#[command(story)]`): loaded only by an install that shows stories.
@@ -34,9 +36,10 @@ impl SetEntry {
defs: fn() -> Result<Vec<CommandDef>, CommandDefError>,
no_default_on: fn() -> Vec<(&'static str, Platform)>,
edits: fn() -> Vec<(&'static str, EditCommand)>,
holds: fn() -> Vec<(&'static str, CommandScope)>,
platform_defaults: fn() -> Result<Vec<PlatformDefault>, CommandDefError>,
) -> Self {
SetEntry { name, defs, no_default_on, edits, platform_defaults, story: false }
SetEntry { name, defs, no_default_on, edits, holds, platform_defaults, story: false }
}
/// The entry as a story's set.
@@ -75,6 +78,7 @@ macro_rules! __register_command_set {
<$ty as $crate::runtime::commands::CommandSet>::defs,
<$ty as $crate::runtime::commands::CommandSet>::no_default_on,
<$ty as $crate::runtime::commands::CommandSet>::edits,
<$ty as $crate::runtime::commands::CommandSet>::holds,
<$ty as $crate::runtime::commands::CommandSet>::platform_defaults,
))
}
@@ -162,6 +166,8 @@ pub(crate) struct Registry {
edits: HashMap<String, EditCommand>,
/// Defaults that one platform has instead of the command's others.
platform_defaults: Vec<(String, Platform, Binding)>,
/// The scope each momentary command's held key makes work, by the command's id.
holds: HashMap<String, &'static str>,
/// Whether the stories' sets are loaded.
stories: bool,
}
@@ -176,6 +182,7 @@ impl Registry {
}
registry.no_default.extend((entry.no_default_on)().into_iter().map(|(id, platform)| (id.to_owned(), platform)));
registry.edits.extend((entry.edits)().into_iter().map(|(id, edit)| (id.to_owned(), edit)));
registry.holds.extend((entry.holds)().into_iter().map(|(id, scope)| (id.to_owned(), scope.name())));
registry
.platform_defaults
.extend((entry.platform_defaults)()?.into_iter().map(|(id, platform, binding)| (id.to_owned(), platform, binding)));
@@ -219,6 +226,17 @@ impl Registry {
self.edits.get(id).copied()
}
/// The scope whose keys work while the key of the momentary command `id` is held.
pub(crate) fn held_scope(&self, id: &str) -> Option<&'static str> {
self.holds.get(id).copied()
}
/// Whether `scope` is a held scope: its keys work while a momentary command's key is held, and its commands go to
/// the application, as no instance is ever of it.
pub(crate) fn is_held_scope(&self, scope: &str) -> bool {
self.holds.values().any(|held| *held == scope)
}
pub(crate) fn defs(&self) -> &[CommandDef] {
&self.defs
}
+8
View File
@@ -451,6 +451,14 @@ pub fn note_shell(ctx: &Context, viewport: ViewportId, window: &WindowKey, root:
});
}
/// The root container of the shell the latest pass of `viewport` showed: where a key pressed with nothing focused
/// matches, so the window's commands take it.
pub(crate) fn shell_root(ctx: &Context, viewport: ViewportId) -> Option<Id> {
pass_state::with::<FrameState, _>(ctx, |state| {
state.shells.iter().filter(|shell| shell.viewport == viewport).max_by_key(|shell| shell.pass).map(|shell| shell.root)
})
}
/// Adds a chrome toggle of `viewport` to the next `FrameOutput` and aims it at the window of the viewport that holds
/// focus, or at the first shell that asks when none does.
pub(crate) fn request_chrome_toggle(ctx: &Context, viewport: ViewportId, toggle: ChromeToggle) {
+18 -3
View File
@@ -1,6 +1,8 @@
//! `#[derive(CommandSet)]` with `#[command(prefix = "..", scope = "..", story)]` on the enum and
//! `#[command(label = "..", icon = "..", kind = "..", group = "..", modal = "..", edit = "..", default = "..", path = "..", alias = "..")]` on variants.
//! `#[command(label = "..", icon = "..", kind = "..", group = "..", modal = "..", edit = "..", holds = "..", default = "..", path = "..", alias = "..")]`
//! on variants.
//! `edit = ".."` links the command to the `EditCommand` a focused component takes it as.
//! `holds = ".."` on a `kind = "momentary"` command names the scope whose keys work while the command's key is held.
//! `default(mac = "..")` (or `windows`, `linux`) is a default of one platform: it replaces the unqualified defaults there.
use crate::util::ui_crate;
@@ -23,6 +25,7 @@ struct VariantAttrs {
group: Option<LitStr>,
modal: Option<LitStr>,
edit: Option<LitStr>,
holds: Option<LitStr>,
defaults: Vec<LitStr>,
platform_defaults: Vec<(LitStr, LitStr)>,
no_default_on: Vec<LitStr>,
@@ -147,6 +150,7 @@ fn variant(variant: &Variant) -> syn::Result<VariantAttrs> {
() if meta.path.is_ident("group") => attrs.group = Some(value(meta)?),
() if meta.path.is_ident("modal") => attrs.modal = Some(value(meta)?),
() if meta.path.is_ident("edit") => attrs.edit = Some(value(meta)?),
() if meta.path.is_ident("holds") => attrs.holds = Some(value(meta)?),
() if meta.path.is_ident("default") && meta.input.peek(syn::Token![=]) => attrs.defaults.push(value(meta)?),
() if meta.path.is_ident("default") => meta.parse_nested_meta(|inner| {
let platform = inner.path.get_ident().map(|ident| LitStr::new(&ident.to_string(), ident.span()));
@@ -229,8 +233,8 @@ pub(crate) fn derive(input: TokenStream) -> syn::Result<TokenStream> {
Some(scope) => quote!(#k::runtime::commands::CommandScope::new(#scope)),
None => quote!(#k::runtime::commands::CommandScope::APP),
};
let (mut ids, mut arms, mut defs, mut bare, mut per_platform, mut edits) =
(Vec::new(), Vec::new(), Vec::new(), Vec::new(), Vec::new(), Vec::new());
let (mut ids, mut arms, mut defs, mut bare, mut per_platform, mut edits, mut holds) =
(Vec::new(), Vec::new(), Vec::new(), Vec::new(), Vec::new(), Vec::new(), Vec::new());
for v in &data.variants {
let attrs = variant(v)?;
let name = &v.ident;
@@ -260,6 +264,13 @@ pub(crate) fn derive(input: TokenStream) -> syn::Result<TokenStream> {
let edit = edit_tokens(&k, edit)?;
edits.push(quote!((#id, #edit)));
}
if let Some(held) = &attrs.holds {
if attrs.kind.as_ref().is_none_or(|kind| kind.value() != "momentary") {
return Err(syn::Error::new(held.span(), "`holds` belongs to `kind = \"momentary\"`"));
}
check_scope(held)?;
holds.push(quote!((#id, #k::runtime::commands::CommandScope::new(#held))));
}
arms.push(quote!(#id => ::core::option::Option::Some(Self::#name)));
defs.push(quote! {
{
@@ -303,6 +314,10 @@ pub(crate) fn derive(input: TokenStream) -> syn::Result<TokenStream> {
::std::vec![#(#edits),*]
}
fn holds() -> ::std::vec::Vec<(&'static str, #k::runtime::commands::CommandScope)> {
::std::vec![#(#holds),*]
}
fn platform_defaults() -> ::core::result::Result<
::std::vec::Vec<(&'static str, #k::runtime::commands::Platform, #k::runtime::commands::Binding)>,
#k::runtime::commands::CommandDefError,
+85 -4
View File
@@ -1,15 +1,17 @@
//! Screen mode: the shell brings its OS window to the bound mode in one pass and follows the OS out of full screen.
//! Screen mode: the shell brings its OS window to the bound mode in one pass and follows the OS out of full screen, and
//! its keys reach it with nothing focused and give way to a held key's scope.
use craft_host::target::{Os, ShellInfo};
use craft_ui::contract::{Bind, Show as _};
use craft_ui::contract::{Bind, CommandSet, Show as _};
use craft_ui::display::Text;
use craft_ui::runtime::InstallSpec;
use craft_ui::runtime::env::WindowKey;
use craft_ui::runtime::frame::take_output;
use craft_ui::shell::{AppShell, ScreenMode};
use craft_ui::testing::trial;
use craft_ui::testing::windows::FakeSystem;
use craft_ui::testing::{Frames, trial};
use craft_ui_test_kit::windows::{Out, Windows};
use egui::{Pos2, Rect, ViewportCommand, ViewportId, ViewportInfo};
use egui::{Event, Key, Modifiers, Pos2, Rect, ViewportCommand, ViewportId, ViewportInfo};
use std::sync::Arc;
const WINDOW: Rect = Rect { min: Pos2::ZERO, max: Pos2::new(800.0, 600.0) };
@@ -93,3 +95,82 @@ fn on_windows_a_maximized_window_leaves_maximized_before_full_screen_and_returns
mode = ScreenMode::Standard;
assert_eq!(screen_commands(&frame(&windows, &mut mode)), [ViewportCommand::Fullscreen(false), ViewportCommand::Maximized(true)]);
}
/// An application command on F, and a momentary command whose held F12 makes the `trialHeld` scope's keys work.
#[derive(Clone, Copy, Debug, PartialEq, Eq, CommandSet)]
#[command(prefix = "trialKeys")]
enum TrialKeys {
#[command(label = "App F", default = "F")]
AppF,
#[command(label = "Hold", kind = "momentary", default = "F12", holds = "trialHeld")]
Hold,
}
/// The command F runs while F12 is held.
#[derive(Clone, Copy, Debug, PartialEq, Eq, CommandSet)]
#[command(prefix = "trialHeld", scope = "trialHeld")]
enum HeldKeys {
#[command(label = "Next", default = "F")]
Next,
}
/// One frame of a shell over a plain body, with nothing focused, its mode bound to `mode`; the ids of the commands
/// that reached the application since the last frame.
fn keyed(frames: &mut Frames, mode: &mut ScreenMode, events: Vec<Event>) -> Vec<String> {
frames.frame(events, |ui| {
AppShell::new(WindowKey::main())
.screen_mode(Bind::bound(&mut *mode))
.body(|ui, _, _| {
Text::new("Document").show(ui);
})
.show(ui, &mut ());
});
take_output(&frames.ctx).fired.into_iter().map(|fired| fired.command.id).collect()
}
fn key(key: Key, pressed: bool) -> Event {
Event::Key { key, physical_key: None, pressed, repeat: false, modifiers: Modifiers::NONE }
}
/// Presses and releases `pressed`, then settles; the commands that reached the application.
fn tap(frames: &mut Frames, mode: &mut ScreenMode, pressed: Key) -> Vec<String> {
let mut fired = keyed(frames, mode, vec![key(pressed, true)]);
fired.extend(keyed(frames, mode, vec![key(pressed, false)]));
for _ in 0..SETTLED_FRAMES {
fired.extend(keyed(frames, mode, vec![]));
}
fired
}
/// With nothing focused, a key both the window and the application bind runs the window's command: the shell's root
/// takes the keys.
#[trial]
fn a_window_command_takes_its_key_with_nothing_focused() {
let mut frames = Frames::new();
let mut mode = ScreenMode::Standard;
for _ in 0..SETTLED_FRAMES {
keyed(&mut frames, &mut mode, vec![]);
}
let fired = tap(&mut frames, &mut mode, Key::F);
assert_eq!(mode, ScreenMode::FullScreenWithMenuBar, "F cycles the screen mode");
assert!(!fired.iter().any(|id| id == TrialKeys::AppF.id()), "the application's F does not run: {fired:?}");
}
/// While a momentary command's key is held, its scope's keys come before the window's; once it is up, the window's
/// key runs again.
#[trial]
fn a_held_keys_scope_takes_its_keys_before_the_window() {
let mut frames = Frames::new();
let mut mode = ScreenMode::Standard;
for _ in 0..SETTLED_FRAMES {
keyed(&mut frames, &mut mode, vec![]);
}
keyed(&mut frames, &mut mode, vec![key(Key::F12, true)]);
let fired = tap(&mut frames, &mut mode, Key::F);
assert_eq!(mode, ScreenMode::Standard, "F with F12 held leaves the screen mode");
assert_eq!(fired.iter().filter(|id| *id == HeldKeys::Next.id()).count(), 1, "and runs the held scope's command: {fired:?}");
keyed(&mut frames, &mut mode, vec![key(Key::F12, false)]);
let fired = tap(&mut frames, &mut mode, Key::F);
assert_eq!(mode, ScreenMode::FullScreenWithMenuBar, "F with F12 up cycles the screen mode");
assert!(!fired.iter().any(|id| id == HeldKeys::Next.id()), "{fired:?}");
}