mirror of
https://github.com/storytold/craft-libs.git
synced 2026-11-27 01:08:38 +00:00
Merge pull request #3360 from aiongg/next-host-input
Hosted egui apps on next: host quit, dock tab focus, float order, host panel fill, app icon, keymap override warnings
This commit is contained in:
@@ -1,12 +1,13 @@
|
||||
# craft-host
|
||||
|
||||
The services every Craft library feature reads from the app: who the app is (`AppInfo`), the
|
||||
catalogs and current language, settings sections, command words and background jobs. The app builds
|
||||
The services every Craft library feature reads from the app: who the app is (`AppInfo`, and its
|
||||
icon), the catalogs and current language, settings sections, command words and background jobs. The app builds
|
||||
one `Host` at startup and installs it on the egui context; features read it with `Host::of(ui)` and
|
||||
never take services as parameters.
|
||||
|
||||
```ignore
|
||||
let host = craft_host::Host::builder(craft_host::AppInfo { id: "photocraft", name: "PhotoCraft", version: "1.0" })
|
||||
.icon_png(include_bytes!("../assets/icon-128.png"))
|
||||
.i18n(i18n)
|
||||
.settings(settings)
|
||||
.build();
|
||||
|
||||
+16
-1
@@ -26,6 +26,7 @@ pub use ui::HostScope;
|
||||
#[derive(Clone)]
|
||||
pub struct Host {
|
||||
app: AppInfo,
|
||||
icon_png: Option<&'static [u8]>,
|
||||
i18n: Option<Arc<I18n>>,
|
||||
lang: Lang,
|
||||
settings: Arc<dyn SectionStore>,
|
||||
@@ -45,6 +46,7 @@ fn next_generation() -> u64 {
|
||||
/// Collects a [`Host`]'s services; each one defaults when not set.
|
||||
pub struct HostBuilder {
|
||||
app: AppInfo,
|
||||
icon_png: Option<&'static [u8]>,
|
||||
i18n: Option<Arc<I18n>>,
|
||||
lang: Option<Lang>,
|
||||
settings: Option<Arc<dyn SectionStore>>,
|
||||
@@ -56,7 +58,7 @@ pub struct HostBuilder {
|
||||
impl Host {
|
||||
/// Starts a host for `app`; every service not set on the builder gets its default.
|
||||
pub fn builder(app: AppInfo) -> HostBuilder {
|
||||
HostBuilder { app, i18n: None, lang: None, settings: None, commands: None, jobs: None, files: None }
|
||||
HostBuilder { app, icon_png: None, i18n: None, lang: None, settings: None, commands: None, jobs: None, files: None }
|
||||
}
|
||||
|
||||
/// Which host this is: a host and its clones hold the same services and language, and one built anew
|
||||
@@ -71,6 +73,11 @@ impl Host {
|
||||
&self.app
|
||||
}
|
||||
|
||||
/// The app's icon as PNG bytes ([`HostBuilder::icon_png`]); `None` when the app gave none.
|
||||
pub fn icon_png(&self) -> Option<&'static [u8]> {
|
||||
self.icon_png
|
||||
}
|
||||
|
||||
/// The app's catalogs; `None` until the app uses craft-i18n (library words are English then).
|
||||
pub fn i18n(&self) -> Option<&I18n> {
|
||||
self.i18n.as_deref()
|
||||
@@ -151,6 +158,13 @@ impl Host {
|
||||
}
|
||||
|
||||
impl HostBuilder {
|
||||
/// The app's icon as PNG bytes, its 128 px app icon: the library dialogs that name the app (the update dialogs)
|
||||
/// show it beside the name. Default: none; those dialogs then show the name's first letter in its place.
|
||||
pub fn icon_png(mut self, png: &'static [u8]) -> Self {
|
||||
self.icon_png = Some(png);
|
||||
self
|
||||
}
|
||||
|
||||
/// Default: none (English).
|
||||
pub fn i18n(mut self, i18n: Arc<I18n>) -> Self {
|
||||
self.i18n = Some(i18n);
|
||||
@@ -192,6 +206,7 @@ impl HostBuilder {
|
||||
let lang = self.lang.or_else(|| self.i18n.as_ref().map(|i18n| i18n.system_lang())).unwrap_or(Lang::EN);
|
||||
Host {
|
||||
app: self.app,
|
||||
icon_png: self.icon_png,
|
||||
i18n: self.i18n,
|
||||
lang,
|
||||
settings: self.settings.unwrap_or_else(|| Arc::new(MemorySections::default())),
|
||||
|
||||
@@ -27,7 +27,7 @@ mod binding;
|
||||
mod command;
|
||||
|
||||
pub use binding::{Binding, BindingError};
|
||||
pub use command::{CommandDef, CommandKind, ModalRule, TypingRule};
|
||||
pub use command::{CommandDef, CommandKind, DeleteKeys, ModalRule, TypingRule};
|
||||
|
||||
mod editing;
|
||||
pub use editing::text_editing_chords;
|
||||
@@ -267,6 +267,7 @@ pub struct Keymap {
|
||||
scopes: Scopes,
|
||||
platform: Platform,
|
||||
typing: TypingRule,
|
||||
delete_keys: DeleteKeys,
|
||||
reserved: Vec<Chord>,
|
||||
overrides: Overrides,
|
||||
/// Tools of different groups may share a chord ([`Keymap::with_shared_tool_keys`]).
|
||||
@@ -294,6 +295,7 @@ impl Keymap {
|
||||
scopes,
|
||||
platform,
|
||||
typing: TypingRule::default(),
|
||||
delete_keys: DeleteKeys::default(),
|
||||
reserved: Vec::new(),
|
||||
overrides: Overrides::new(),
|
||||
shared_tool_keys: false,
|
||||
@@ -324,6 +326,12 @@ impl Keymap {
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets how a press of Delete or Backspace finds its binding ([`DeleteKeys`]).
|
||||
pub fn with_delete_keys(mut self, keys: DeleteKeys) -> Keymap {
|
||||
self.delete_keys = keys;
|
||||
self
|
||||
}
|
||||
|
||||
/// Chords that cannot be assigned or bound, e.g. [`reserved::system`](crate::reserved::system).
|
||||
/// Without this call the keymap reserves no chord. A default binding on a reserved chord is dropped.
|
||||
pub fn with_reserved(mut self, chords: Vec<Chord>) -> Keymap {
|
||||
@@ -367,6 +375,11 @@ impl Keymap {
|
||||
self.typing
|
||||
}
|
||||
|
||||
/// How a press of Delete or Backspace finds its binding.
|
||||
pub fn delete_keys(&self) -> DeleteKeys {
|
||||
self.delete_keys
|
||||
}
|
||||
|
||||
/// Every command the user can bind, in catalog order.
|
||||
pub fn catalog(&self) -> &[CommandDef] {
|
||||
&self.catalog
|
||||
|
||||
@@ -179,6 +179,19 @@ pub enum TypingRule {
|
||||
AllWait,
|
||||
}
|
||||
|
||||
/// How a press of Delete or Backspace finds its binding.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
|
||||
#[non_exhaustive]
|
||||
pub enum DeleteKeys {
|
||||
/// Delete and Backspace are one key, as in Photoshop: a press runs its own key's binding, else the other key's
|
||||
/// with the same modifiers. The Mac's key labelled "delete" sends Backspace, so a Delete binding runs from it.
|
||||
#[default]
|
||||
OneKey,
|
||||
/// Delete and Backspace are two keys: a press runs only its own key's binding, for an app that gives them
|
||||
/// different jobs (Delete removes the layer, Backspace a path tool's point).
|
||||
Apart,
|
||||
}
|
||||
|
||||
impl TypingRule {
|
||||
/// Whether `chord` may fire while typing on `platform`.
|
||||
pub fn fires(self, chord: &Chord, platform: Platform) -> bool {
|
||||
|
||||
@@ -158,7 +158,7 @@ pub use import::{
|
||||
ContextRule, DecodedCode, ForeignEntry, ForeignKey, ForeignSet, ImportOptions, ImportPlan, ImportReport, NoneDefined, NotRead, Start, plan,
|
||||
};
|
||||
pub use keymap::{
|
||||
AssignError, Assigned, Binding, BindingError, CommandDef, CommandKind, Conflict, ConflictKind, DropReason, Holder, Keymap, Lookup,
|
||||
AssignError, Assigned, Binding, BindingError, CommandDef, CommandKind, Conflict, ConflictKind, DeleteKeys, DropReason, Holder, Keymap, Lookup,
|
||||
MAX_BINDING_TEXT, MAX_BINDINGS, MAX_COMMANDS, MAX_CONFLICTS, ModalRule, Overrides, Policy, Problem, TypingRule, text_editing_chords,
|
||||
};
|
||||
pub use layout::{COMMON_SYMBOLS, KeyInput, Layout, SYMBOL_TABLE, SymbolLayout};
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
use crate::DOUBLE_PRESS;
|
||||
use crate::chord::{Chord, Key, Mods, PressKind, Trigger};
|
||||
use crate::command::CommandRef;
|
||||
use crate::keymap::{Keymap, Lookup};
|
||||
use crate::keymap::{DeleteKeys, Keymap, Lookup};
|
||||
use crate::layout::{KeyInput, Layout};
|
||||
use crate::scope::Active;
|
||||
|
||||
@@ -72,7 +72,7 @@ pub struct Matcher {
|
||||
}
|
||||
|
||||
impl Matcher {
|
||||
/// A matcher with Delete and Backspace standing for each other.
|
||||
/// A matcher with no previous press.
|
||||
pub fn new() -> Matcher {
|
||||
Matcher::default()
|
||||
}
|
||||
@@ -87,7 +87,7 @@ impl Matcher {
|
||||
/// 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 chords = Chords::of(layout, keymap, input)?;
|
||||
let m = Match { keymap, active, outer, accept };
|
||||
if repeat {
|
||||
return chords.single(&m);
|
||||
@@ -105,13 +105,13 @@ impl Matcher {
|
||||
/// 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(&Match { keymap, active, outer, accept: &|_| true })
|
||||
Chords::of(layout, keymap, input)?.single(&Match { keymap, active, outer, accept: &|_| true })
|
||||
}
|
||||
|
||||
/// The command a hold of `input` runs: for a key that stays down past the hold time. Keeps no state.
|
||||
// PLAN: `Keymap::hold_of` ranks without the outer panels, so `outer` has no effect yet.
|
||||
pub fn hold(layout: &Layout, keymap: &Keymap, input: &KeyInput, active: &Active<'_>, _outer: &[&str]) -> Option<Hit> {
|
||||
Chords::of(layout, input)?.hold(keymap, active)
|
||||
Chords::of(layout, keymap, input)?.hold(keymap, active)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -126,12 +126,13 @@ struct Match<'a> {
|
||||
}
|
||||
|
||||
/// 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.
|
||||
/// exception), the layout's candidates, then, where the keymap takes them as one key ([`DeleteKeys::OneKey`]), 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> {
|
||||
fn of(layout: &Layout, keymap: &Keymap, input: &KeyInput) -> Option<Chords> {
|
||||
let mut chords = layout.candidates(input);
|
||||
let meant = chords.first().copied()?;
|
||||
// Rule 3's exception (`layout` docs): where the layout dropped the Shift the person held for a symbol that
|
||||
@@ -142,15 +143,17 @@ impl Chords {
|
||||
chords.retain(|chord| *chord != kept);
|
||||
chords.insert(0, kept);
|
||||
}
|
||||
let twins: Vec<Chord> = chords
|
||||
.iter()
|
||||
.filter_map(|c| match c.key {
|
||||
Key::Delete => Some(Chord::new(c.mods, Key::Backspace)),
|
||||
Key::Backspace => Some(Chord::new(c.mods, Key::Delete)),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
chords.extend(twins);
|
||||
if keymap.delete_keys() == DeleteKeys::OneKey {
|
||||
let twins: Vec<Chord> = chords
|
||||
.iter()
|
||||
.filter_map(|c| match c.key {
|
||||
Key::Delete => Some(Chord::new(c.mods, Key::Backspace)),
|
||||
Key::Backspace => Some(Chord::new(c.mods, Key::Delete)),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
chords.extend(twins);
|
||||
}
|
||||
Some(Chords(chords, meant))
|
||||
}
|
||||
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
//! Integration tests of craft-keymap: keymap.
|
||||
|
||||
use craft_keymap::{
|
||||
Active, Binding, Chord, CommandDef, CommandRef, DropReason, Key, KeyInput, Keymap, Layout, Lookup, MAX_COMMANDS, Matcher, Mods, Overrides,
|
||||
Platform, Policy, Press, Problem, Scope, Scopes, Trigger,
|
||||
Active, Binding, Chord, CommandDef, CommandRef, DeleteKeys, DropReason, Key, KeyInput, Keymap, Layout, Lookup, MAX_COMMANDS, Matcher, Mods,
|
||||
Overrides, Platform, Policy, Press, Problem, Scope, Scopes, Trigger,
|
||||
};
|
||||
use serde_json::json;
|
||||
|
||||
@@ -218,6 +218,28 @@ 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");
|
||||
}
|
||||
|
||||
/// Delete and Backspace: a press runs its own key's binding; with the keys one key (the default) a key with no
|
||||
/// binding of its own runs the other's, and with the keys apart it runs nothing.
|
||||
#[test]
|
||||
fn delete_and_backspace_run_their_own_bindings_and_stand_in_only_as_one_key() {
|
||||
let hit = |km: &Keymap, key: Key| {
|
||||
let input = KeyInput::new(Mods::NONE).with_physical(key);
|
||||
let press = Press { input: &input, repeat: false, now: 0.0, active: &Active::NONE, outer: &[] };
|
||||
Matcher::new().press(&Layout::new(), km, &press).map(|hit| hit.command)
|
||||
};
|
||||
let both = || vec![app("layer.remove", &["Delete"]), app("path.removePoint", &["Backspace"])];
|
||||
for keys in [DeleteKeys::OneKey, DeleteKeys::Apart] {
|
||||
let km = Keymap::new(both(), Scopes::new(), Platform::Linux).with_delete_keys(keys);
|
||||
assert_eq!(hit(&km, Key::Delete), Some(cmd("layer.remove")), "{keys:?}: Delete runs its own binding");
|
||||
assert_eq!(hit(&km, Key::Backspace), Some(cmd("path.removePoint")), "{keys:?}: Backspace runs its own binding");
|
||||
}
|
||||
let delete_only = || vec![app("layer.remove", &["Delete"])];
|
||||
let km = Keymap::new(delete_only(), Scopes::new(), Platform::Mac);
|
||||
assert_eq!(hit(&km, Key::Backspace), Some(cmd("layer.remove")), "one key: Backspace runs the Delete binding");
|
||||
let km = Keymap::new(delete_only(), Scopes::new(), Platform::Mac).with_delete_keys(DeleteKeys::Apart);
|
||||
assert_eq!(hit(&km, Key::Backspace), None, "apart: Backspace runs nothing");
|
||||
}
|
||||
|
||||
/// 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]
|
||||
|
||||
@@ -139,6 +139,30 @@
|
||||
"text.muted": "#aeaeb6",
|
||||
"text.normal": "#ececef"
|
||||
}
|
||||
},
|
||||
"deckcraft": {
|
||||
"light": {
|
||||
"accent.solid": "#d95a1a",
|
||||
"accent.text": "#b54b16",
|
||||
"text.on_accent": "#ffffff"
|
||||
},
|
||||
"dark": {
|
||||
"accent.solid": "#f26b1d",
|
||||
"accent.text": "#fbcdb2",
|
||||
"text.on_accent": "#ffffff"
|
||||
}
|
||||
},
|
||||
"soundcraft": {
|
||||
"light": {
|
||||
"accent.solid": "#3e74b4",
|
||||
"accent.text": "#3b6eab",
|
||||
"text.on_accent": "#ffffff"
|
||||
},
|
||||
"dark": {
|
||||
"accent.solid": "#4084c4",
|
||||
"accent.text": "#c4d9ed",
|
||||
"text.on_accent": "#ffffff"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -76,10 +76,44 @@ impl FontRef {
|
||||
/// Gives the UI `definitions`, as when on-demand script coverage loads the glyphs of another script. Text
|
||||
/// measured in this pass used the old metrics, so the pass asks for one discard pass: layout memory and the
|
||||
/// new metrics agree when the frame is shown. Between frames nothing was measured with the old metrics, and
|
||||
/// the next frame measures with the new ones.
|
||||
/// the next frame measures with the new ones. What text layout reads of the definitions follows them: framework text
|
||||
/// in a semibold role draws in the [`SEMIBOLD`] family only when `definitions` have it, else in the proportional one.
|
||||
pub fn load(ctx: &Context, definitions: FontDefinitions) {
|
||||
load_with(ctx, definitions, Vec::new());
|
||||
}
|
||||
|
||||
/// [`load`], with `providers` serving the characters the faces lack to the probe that measures the definitions' line
|
||||
/// ratio: a stack's own providers.
|
||||
pub(crate) fn load_with(ctx: &Context, definitions: FontDefinitions, providers: Vec<std::sync::Arc<dyn egui::FontProvider>>) {
|
||||
stack::record_facts(ctx, &definitions, providers);
|
||||
egui_fonts::set_definitions(ctx, definitions);
|
||||
if frame::in_pass(ctx) {
|
||||
layout_memory::ask_discard(ctx);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(all(feature = "testing", any(test, feature = "suite")))]
|
||||
pub(crate) mod facts_tests {
|
||||
use crate::fonts::{SEMIBOLD, deflated_default_definitions, load, stack_facts};
|
||||
use crate::testing::trial;
|
||||
use craft_theme::{Contrast, Mode, TypeRole};
|
||||
use egui::{Context, FontFamily};
|
||||
|
||||
/// Definitions an app gives in place of the stack's carry what text layout reads: without the semibold family, a
|
||||
/// framework title draws in a family the definitions have.
|
||||
#[trial]
|
||||
fn a_title_draws_in_a_family_the_loaded_definitions_have() {
|
||||
let ctx = Context::default();
|
||||
let tokens = crate::testing::style::tokens(Mode::Light, Contrast::Standard);
|
||||
let semibold = FontFamily::Name(SEMIBOLD.into());
|
||||
let mut definitions = deflated_default_definitions();
|
||||
load(&ctx, definitions.clone());
|
||||
assert!(stack_facts(&ctx).semibold, "the default definitions have the semibold family");
|
||||
assert_eq!(tokens.font(stack_facts(&ctx), TypeRole::Title, false).family, semibold, "and a title draws in it");
|
||||
definitions.families.remove(&semibold);
|
||||
load(&ctx, definitions.clone());
|
||||
assert!(!stack_facts(&ctx).semibold, "definitions without it say so");
|
||||
let title = tokens.font(stack_facts(&ctx), TypeRole::Title, false).family;
|
||||
assert!(definitions.families.contains_key(&title), "a title draws in a family the definitions have, not {title:?}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -49,6 +49,7 @@ use craft_theme::InterfaceFont;
|
||||
use egui::{FontData, FontDefinitions, FontFamily, FontProvider};
|
||||
|
||||
pub(super) use chain::{EM_SQUARE_SCRIPTS, covers, is_cjk};
|
||||
pub(in crate::fonts) use install::record_facts;
|
||||
pub(crate) use install::{StackFacts, stack_facts};
|
||||
|
||||
use super::FontRef;
|
||||
|
||||
@@ -2,29 +2,25 @@
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use egui::{Context, FontFamily, FontProvider};
|
||||
use egui::{Context, FontDefinitions, FontFamily, FontProvider};
|
||||
|
||||
use super::{SEMIBOLD, Stack, SystemFonts};
|
||||
use crate::fonts::faces::{Installed, on_baseline};
|
||||
use crate::fonts::served::loader;
|
||||
use crate::fonts::system::installed_system_font_provider;
|
||||
use crate::fonts::system::ui_face::{self, SYSTEM_UI_REGULAR, SYSTEM_UI_SEMIBOLD, SystemUiFace};
|
||||
use crate::fonts::{FontRef, RegularWeight, load, system_font_provider};
|
||||
use crate::fonts::{FontRef, RegularWeight, load_with, system_font_provider};
|
||||
use crate::runtime::egui::fonts::{self as egui_fonts, GlyphProbe};
|
||||
use crate::runtime::egui::memory;
|
||||
|
||||
/// Starts building the system font index for a context.
|
||||
type StartIndex = fn(&Context);
|
||||
|
||||
/// What a context remembers of the stack installed in it.
|
||||
/// What a context remembers of the stack installed in it and of the font definitions it was given last.
|
||||
#[derive(Default)]
|
||||
struct State {
|
||||
/// Whether the OS's interface face draws in the proportional family of that stack.
|
||||
system_ui: bool,
|
||||
/// Whether that stack has the semibold family.
|
||||
semibold: bool,
|
||||
/// The line height per point of text of the face that leads the proportional family, measured at install.
|
||||
line_ratio: f32,
|
||||
/// The facts of the definitions given last ([`record_facts`]).
|
||||
facts: StackFacts,
|
||||
/// The provider that serves the stack's faces after the system fonts, swapped in place by every install.
|
||||
installed: Option<Arc<Installed>>,
|
||||
/// A stack installed before the OS face resolved, to install again with it.
|
||||
@@ -35,21 +31,34 @@ struct State {
|
||||
/// height is negligible in the ratio.
|
||||
const LINE_PROBE_SIZE: f32 = 100.0;
|
||||
|
||||
/// What text layout and control sizing read of the stack last installed in a context, read once per layout or pass.
|
||||
/// What text layout and control sizing read of the font definitions a context was given last ([`crate::fonts::load`],
|
||||
/// which a stack's install calls), read once per layout or pass.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq)]
|
||||
pub(crate) struct StackFacts {
|
||||
/// Whether the OS's interface face draws in the proportional family ([`craft_theme::InterfaceFont::System`], once
|
||||
/// the face resolved).
|
||||
pub system_ui: bool,
|
||||
/// Whether the semibold family exists.
|
||||
/// Whether the semibold family ([`SEMIBOLD`]) exists.
|
||||
pub semibold: bool,
|
||||
/// The line height per point of text of the face that leads the proportional family; 0 before a stack installs.
|
||||
pub line_ratio: f32,
|
||||
}
|
||||
|
||||
/// The facts of the stack last installed in `ctx`.
|
||||
/// The facts of the font definitions `ctx` was given last.
|
||||
pub(crate) fn stack_facts(ctx: &Context) -> StackFacts {
|
||||
memory::with::<State, _>(ctx, |state| StackFacts { system_ui: state.system_ui, semibold: state.semibold, line_ratio: state.line_ratio })
|
||||
memory::with::<State, _>(ctx, |state| state.facts)
|
||||
}
|
||||
|
||||
/// Records the facts of `definitions`, which `ctx` is given now: `providers` serve the characters their faces lack, to
|
||||
/// the probe that measures the line ratio.
|
||||
pub(in crate::fonts) fn record_facts(ctx: &Context, definitions: &FontDefinitions, providers: Vec<Arc<dyn FontProvider>>) {
|
||||
let proportional = definitions.families.get(&FontFamily::Proportional).map(Vec::as_slice).unwrap_or_default();
|
||||
let facts = StackFacts {
|
||||
system_ui: proportional.iter().any(|name| name == SYSTEM_UI_REGULAR) && definitions.font_data.contains_key(SYSTEM_UI_REGULAR),
|
||||
semibold: definitions.families.contains_key(&FontFamily::Name(SEMIBOLD.into())),
|
||||
line_ratio: GlyphProbe::new(definitions.clone(), providers).row_height(&FontRef::proportional(), LINE_PROBE_SIZE) / LINE_PROBE_SIZE,
|
||||
};
|
||||
memory::with::<State, _>(ctx, |state| state.facts = facts);
|
||||
}
|
||||
|
||||
/// Installs the stack kept for `ctx` once the OS face has resolved: the first pass after it resolves.
|
||||
@@ -96,16 +105,10 @@ impl Stack {
|
||||
|
||||
/// [`Self::install`] without fetching; `miss` is asked for characters no face has.
|
||||
pub(in crate::fonts) fn install_faces(&self, ctx: &Context, miss: Option<Arc<dyn FontProvider>>) {
|
||||
load(ctx, self.checked_definitions());
|
||||
let system_ui = self.has_system_ui();
|
||||
let semibold = self.definitions.families.contains_key(&FontFamily::Name(SEMIBOLD.into()));
|
||||
let line_ratio = self.probe(false).row_height(&FontRef::proportional(), LINE_PROBE_SIZE) / LINE_PROBE_SIZE;
|
||||
load_with(ctx, self.checked_definitions(), self.providers(false));
|
||||
let (system, start_index) = self.context_lookup();
|
||||
let (installed, added, replaced) = memory::with::<State, _>(ctx, |state| {
|
||||
let replaced = state.pending.take();
|
||||
state.system_ui = system_ui;
|
||||
state.semibold = semibold;
|
||||
state.line_ratio = line_ratio;
|
||||
state.pending = self.system_ui_pending.then(|| self.clone());
|
||||
match &state.installed {
|
||||
Some(installed) => (Arc::clone(installed), false, replaced),
|
||||
@@ -160,11 +163,6 @@ impl Stack {
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the system face draws in the proportional family: its slot is there, with data.
|
||||
fn has_system_ui(&self) -> bool {
|
||||
self.chain_of(&FontFamily::Proportional).iter().any(|n| n == SYSTEM_UI_REGULAR) && self.definitions.font_data.contains_key(SYSTEM_UI_REGULAR)
|
||||
}
|
||||
|
||||
/// A glyph probe over the stack, for coverage checks. `with_system` adds the system font
|
||||
/// provider.
|
||||
pub(in crate::fonts) fn probe(&self, with_system: bool) -> GlyphProbe {
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
//! `HostStyle`: an app's own egui code shown inside a framework part keeps the style and the background it has outside,
|
||||
//! and runs once per pass.
|
||||
|
||||
use crate::runtime::egui::{alloc, memory, style};
|
||||
use crate::runtime::{layout_memory, measure};
|
||||
use egui::{Id, Rect, Ui, UiBuilder, Vec2};
|
||||
use std::sync::Arc;
|
||||
|
||||
/// The egui style of an app's own `Ui`, kept where a framework part takes the app's egui code into a `Ui` of its own:
|
||||
/// the framework's regions set their layout spacing on the `Ui`s they hand out, and app code shown in one (a dock
|
||||
/// panel's body that the app draws with egui) lays out and paints as it would outside the part when it runs through
|
||||
/// [`HostStyle::show`] on [`HostStyle::paint_panel`]'s background.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct HostStyle(Arc<egui::Style>);
|
||||
|
||||
/// What the last real run of the app's code under an id took and returned (`HostStyle::show`).
|
||||
#[derive(Clone, Default)]
|
||||
struct LastRun<R> {
|
||||
size: Option<Vec2>,
|
||||
out: R,
|
||||
}
|
||||
|
||||
impl HostStyle {
|
||||
/// The style `ui` has now.
|
||||
pub fn of(ui: &Ui) -> Self {
|
||||
HostStyle(style::style_of(ui))
|
||||
}
|
||||
|
||||
/// Runs `run` on `ui` with the kept style, and gives `ui` its own style back after it. For code the framework asks
|
||||
/// for a measure itself (a host view measured at a width); code a part shows goes through [`HostStyle::show`].
|
||||
pub fn run<R>(&self, ui: &mut Ui, run: impl FnOnce(&mut Ui) -> R) -> R {
|
||||
let own = style::style_of(ui);
|
||||
style::set_style(ui, &self.0);
|
||||
let shown = run(ui);
|
||||
style::set_style(ui, &own);
|
||||
shown
|
||||
}
|
||||
|
||||
/// Shows the app's code `run` in `ui` as [`HostStyle::run`] runs it, in the real run of a pass only: in a child of
|
||||
/// `ui` with its layout and the rest of its room, scoped by `id`, which `ui` then takes. A measuring run
|
||||
/// (`runtime::measure`) does not run it: `ui` takes the size the code took in its last real run, and the call
|
||||
/// returns what that run returned (nothing and `R::default()` before the first). The app's code registers its
|
||||
/// widgets with egui and acts on input, so a run in a measuring run would show egui each widget twice in one pass,
|
||||
/// at two places.
|
||||
pub fn show<R: Clone + Default + Send + Sync + 'static>(&self, ui: &mut Ui, id: Id, run: impl FnOnce(&mut Ui) -> R) -> R {
|
||||
let ctx = ui.ctx().clone();
|
||||
if measure::active(&ctx) {
|
||||
let last = memory::peek_clone::<LastRun<R>>(&ctx, id).unwrap_or_default();
|
||||
if let Some(size) = last.size {
|
||||
alloc::space(ui, size);
|
||||
}
|
||||
return last.out;
|
||||
}
|
||||
let mut child = alloc::child(ui, UiBuilder::new().max_rect(ui.available_rect_before_wrap()).layout(*ui.layout()).scope_id(id));
|
||||
let out = self.run(&mut child, run);
|
||||
let rect = child.min_rect();
|
||||
// The child writes its widget rect when it drops.
|
||||
drop(child);
|
||||
alloc::advance_past(ui, rect);
|
||||
let size = rect.size();
|
||||
// A pass a kept measurement serves learns here that the code took another size since, and runs again.
|
||||
layout_memory::backstop(&ctx, id, size);
|
||||
memory::put(&ctx, id, LastRun { size: Some(size), out: out.clone() });
|
||||
out
|
||||
}
|
||||
|
||||
/// Fills `rect` on `ui` with the kept style's panel fill (`Visuals::panel_fill`), as an egui panel of the app paints
|
||||
/// its background.
|
||||
pub fn paint_panel(&self, ui: &Ui, rect: Rect) {
|
||||
ui.painter().rect_filled(rect, 0.0, self.0.visuals.panel_fill);
|
||||
}
|
||||
}
|
||||
@@ -10,6 +10,7 @@ mod focus_ring;
|
||||
#[doc(hidden)]
|
||||
pub mod glyph;
|
||||
mod handle;
|
||||
mod host;
|
||||
mod icon;
|
||||
mod ime_surface;
|
||||
mod kit;
|
||||
@@ -40,6 +41,7 @@ pub use face::FacePaint;
|
||||
pub use faces::FacesCx;
|
||||
pub use focus_ring::{FocusKind, FocusRing};
|
||||
pub use handle::{Handle, HandleShape};
|
||||
pub use host::HostStyle;
|
||||
pub(crate) use icon::SvgIcon;
|
||||
pub use icon::{Glyph, IconMark, IconSet, IconSource, IconSpec, Mirror, has_icon, icon_names, paint_icon};
|
||||
pub use ime_surface::ImeSurface;
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
|
||||
use super::{
|
||||
AppCatalog, CommandChain, CommandGate, CommandInput, CommandScope, CommandSet, CommandState, EditCommands, FirePhase, FireSource, Fired,
|
||||
ResolvedCommand, WindowShortcut, registry,
|
||||
ResolvedCommand, WindowShortcut, registry, yields_default,
|
||||
};
|
||||
use crate::contract::Revision;
|
||||
use crate::runtime::egui::sizing::{Rerun, request_discard};
|
||||
@@ -17,7 +17,7 @@ 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, PressKind,
|
||||
Scopes, Trigger, TypingRule,
|
||||
Problem, Scopes, Trigger, TypingRule,
|
||||
};
|
||||
use egui::{Context, Id, ViewportId};
|
||||
use std::collections::{HashMap, HashSet};
|
||||
@@ -974,8 +974,9 @@ pub fn keymap_builds() -> u64 {
|
||||
/// definition, and the catalog's default bindings join the registry's after them (an app's alternate keys, such as
|
||||
/// F2/F3/F4 for Cut/Copy/Paste).
|
||||
///
|
||||
/// A window shortcut's default chord that another command also binds is that command's: the window shortcut loses it, so the
|
||||
/// app's binding beats the framework's default. A window shortcut the overrides name keeps what they give it.
|
||||
/// A yielding library command's default chord (a window shortcut's, Quit's: `yields_default`) that another command also
|
||||
/// binds is that command's: the library command loses it, so the app's binding beats the framework's default. One the
|
||||
/// overrides name keeps what they give it.
|
||||
fn build_keymap(
|
||||
registry: ®istry::Registry,
|
||||
app: Option<&AppCatalog>,
|
||||
@@ -1022,9 +1023,9 @@ fn build_keymap(
|
||||
let overridden = |def: &CommandDef| overrides.is_some_and(|overrides| overrides.get(&def.command.id).is_some());
|
||||
let yielded: Vec<(CommandRef, Trigger)> = defs
|
||||
.iter()
|
||||
.filter(|def| WindowShortcut::of(&def.command).is_some() && !overridden(def))
|
||||
.filter(|def| yields_default(&def.command) && !overridden(def))
|
||||
.flat_map(|def| keymap.conflicts_with(&def.command))
|
||||
.filter(|conflict| WindowShortcut::of(&conflict.b.0).is_none())
|
||||
.filter(|conflict| !yields_default(&conflict.b.0))
|
||||
.map(|conflict| (conflict.a.0, conflict.chord))
|
||||
.collect();
|
||||
if !yielded.is_empty() {
|
||||
@@ -1034,6 +1035,13 @@ fn build_keymap(
|
||||
}
|
||||
keymap = keymap_of(joined(defs.as_slice()), scopes, platform, overrides, typing, holds);
|
||||
}
|
||||
// An override whose key names no command binds nothing and leaves that command's defaults in place; a misspelt id in
|
||||
// an app's own table otherwise fails without a trace.
|
||||
for problem in keymap.problems() {
|
||||
if let Problem::UnknownCommand { key } = problem {
|
||||
log::warn!("shortcut override `{key}` names no command and binds nothing");
|
||||
}
|
||||
}
|
||||
let window_shortcuts = registry
|
||||
.defs()
|
||||
.iter()
|
||||
|
||||
@@ -122,6 +122,28 @@ pub enum NavCommand {
|
||||
FocusMenuBar,
|
||||
}
|
||||
|
||||
/// The `window` command that quits the app (egui's own quit shortcut, which the runtime clears at install, had the same
|
||||
/// default). The runtime runs it: it asks the root window to close through the window's close path
|
||||
/// (`WindowAction::Close`), so the app's close decision (`embed::logic`) asks about unsaved work as it does for the
|
||||
/// window's close button. It fires whatever is open; under an app-modal layer the close path refuses the close and
|
||||
/// brings the modal forward. Its default chord, like the window shortcuts', yields to another command that binds the
|
||||
/// same chord; an app that reads its quit key from egui itself unbinds it in its overrides.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, craft_ui_macros::CommandSet)]
|
||||
#[command(prefix = "window")]
|
||||
#[non_exhaustive]
|
||||
pub enum QuitCommand {
|
||||
/// Quit the app.
|
||||
#[command(label = "Quit", default = "Cmd+Q", modal = "always")]
|
||||
Quit,
|
||||
}
|
||||
|
||||
/// Whether `command` is a library command whose default chords yield to another command that binds the same chord:
|
||||
/// the window shortcuts and Quit. An app's binding beats the framework's default.
|
||||
pub(crate) fn yields_default(command: &CommandRef) -> bool {
|
||||
use super::CommandSet as _;
|
||||
WindowShortcut::of(command).is_some() || QuitCommand::from_ref(command).is_some()
|
||||
}
|
||||
|
||||
/// A key the window owns before any component: a chrome toggle (Tab), a pane move (F6) or the menu bar's focus (F10),
|
||||
/// as the commands of `ChromeCommand` and `NavCommand` are bound.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
|
||||
@@ -9,8 +9,8 @@ pub use clipboard::{ClipContent, ClipError, ClipItem, ClipboardHandle};
|
||||
pub use craft_behavior::EditCommand;
|
||||
pub use craft_keymap::{Binding, CommandDef, CommandKind, CommandRef, CommandScope, ModalRule, Platform, Scope, Trigger, TypingRule};
|
||||
pub use library::ChromeCommand;
|
||||
pub(crate) use library::WindowShortcut;
|
||||
pub use library::{EditCommands, NavCommand, WindowCommand};
|
||||
pub use library::{EditCommands, NavCommand, QuitCommand, WindowCommand};
|
||||
pub(crate) use library::{WindowShortcut, yields_default};
|
||||
pub use registry::CommandDefError;
|
||||
#[doc(hidden)]
|
||||
pub use registry::{SetEntry, sets};
|
||||
|
||||
@@ -40,8 +40,9 @@ struct Echo {
|
||||
/// after the Alt release. Returns whether an Alt release in `events` ended a hold in which digits were typed (a code,
|
||||
/// or one a focus loss dropped), so the key stage does not take it for a lone Alt. The caller does not call it on macOS, where Option+digit types its own characters.
|
||||
///
|
||||
/// `claimed` tells whether the key stage takes a press as a chord a component claims or a capture holds: such an
|
||||
/// Alt+digit is its owner's, as an app's shortcut goes before Alt-code entry, and it ends the entry like any other key.
|
||||
/// `claimed` tells whether the key stage takes a press as a chord the key target claims (the focused component, or with
|
||||
/// nothing focused the window's document canvas) or a capture holds: such an Alt+digit is its owner's, as an app's
|
||||
/// shortcut goes before Alt-code entry, and it ends the entry like any other key.
|
||||
pub(crate) fn fold(entry: &mut AltCodeEntry, events: &mut Vec<Event>, pages: AltCodePages, os: Os, claimed: &dyn Fn(&Event) -> bool) -> bool {
|
||||
let composes = os == Os::Windows;
|
||||
let mut ended = false;
|
||||
|
||||
@@ -419,6 +419,11 @@ pub(crate) fn set_layer_order(ctx: &Context, order: &[LayerId]) {
|
||||
ctx.set_layer_order(order);
|
||||
}
|
||||
|
||||
/// Brings `layer` to the top of egui's own area order at the end of the running pass, as a press on it does.
|
||||
pub(crate) fn move_to_top(ctx: &Context, layer: LayerId) {
|
||||
ctx.move_to_top(layer);
|
||||
}
|
||||
|
||||
/// Makes `layer` the modal layer of the running pass: layers below it take no input.
|
||||
pub(crate) fn set_modal_layer(ctx: &Context, layer: LayerId) {
|
||||
ctx.memory_mut(|memory| memory.set_modal_layer(layer));
|
||||
|
||||
@@ -131,7 +131,8 @@ pub(crate) fn request_repaint_of(ctx: &Context, viewport: ViewportId) {
|
||||
ctx.request_repaint_of(viewport);
|
||||
}
|
||||
|
||||
/// The options the runtime owns at install: interface scale and quit are commands, so egui's own shortcuts go.
|
||||
/// The options the runtime owns at install: the interface scale is the app's `RootEnv::scale` and quit is a command
|
||||
/// (`QuitCommand`), so egui's own keyboard zoom and quit shortcuts go.
|
||||
pub(crate) fn clear_shortcuts(ctx: &Context) {
|
||||
ctx.options_mut(|options| {
|
||||
options.zoom_with_keyboard = false;
|
||||
@@ -682,7 +683,7 @@ const PINCH_CONTINUES: f64 = 0.25;
|
||||
|
||||
/// Windows and Linux: turns a fractional Ctrl+wheel (or a Wayland point-unit one) into `Event::Zoom` at egui's Ctrl-scroll
|
||||
/// speed; a whole notch stays a wheel event unless within 0.25 s of a pinch step. An input that carries `Event::Zoom`
|
||||
/// already is left alone and ends the run of pinch steps.
|
||||
/// already is left alone and ends the run of pinch steps. Runs while `RootEnv::ctrl_wheel_pinch` is on.
|
||||
pub(crate) fn fold_legacy_pinch(ctx: &Context, input: &mut RawInput) {
|
||||
let os = crate::runtime::windows::os_of(ctx);
|
||||
if os == Os::Mac {
|
||||
@@ -741,14 +742,16 @@ pub(crate) struct RawState {
|
||||
/// A frame's raw events reach only its first pass; a second pass's input holds none, so each wheel delta is scaled
|
||||
/// once and each digit folded once, with nothing to replay or remember between passes.
|
||||
pub(crate) fn prepare(ctx: &Context, input: &mut RawInput) {
|
||||
fold_legacy_pinch(ctx, input);
|
||||
// This frame's `RootEnv`, which `set_input` stored before egui ran the input hook.
|
||||
// PLAN: assumed `pub(crate) fn root_input(ctx: &Context) -> (WheelSpeed, AltCodePages)` in `runtime/frame.rs` (platform-w3).
|
||||
let (wheel, pages) = crate::runtime::frame::root_input(ctx);
|
||||
scale_wheel(&mut input.events, wheel);
|
||||
let root = crate::runtime::frame::root_input(ctx);
|
||||
if root.ctrl_wheel_pinch {
|
||||
fold_legacy_pinch(ctx, input);
|
||||
}
|
||||
let pages = root.alt_codes;
|
||||
scale_wheel(&mut input.events, root.wheel);
|
||||
let os = crate::runtime::windows::os_of(ctx);
|
||||
let macos = os == Os::Mac;
|
||||
// A chord a component claims or a capture holds goes to its owner before Alt-code entry.
|
||||
// A chord the key target claims or a capture holds goes to its owner before Alt-code entry.
|
||||
let claimed = crate::runtime::keys::claims_press(ctx, input);
|
||||
let events = &mut input.events;
|
||||
PerViewport::<RawState>::with(ctx, input.viewport_id, |state| {
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
use craft_theme::Mode;
|
||||
use egui::epaint::FontColorTransferFunction;
|
||||
use egui::{Context, Theme, Ui};
|
||||
use std::sync::Arc;
|
||||
|
||||
/// Turns off egui's own caret blink in `ui`, and hides the caret stroke unless `visible`: the runtime blinks it.
|
||||
pub(crate) fn set_text_cursor(ui: &mut Ui, visible: bool) {
|
||||
@@ -66,6 +67,17 @@ pub(crate) fn set_item_spacing(ui: &mut Ui, gap: egui::Vec2) {
|
||||
ui.spacing_mut().item_spacing = gap;
|
||||
}
|
||||
|
||||
/// The egui style `ui` has now, for a framework part that shows an app's own egui code in a `Ui` of its own
|
||||
/// (`primitives::HostStyle`).
|
||||
pub(crate) fn style_of(ui: &Ui) -> Arc<egui::Style> {
|
||||
Arc::clone(ui.style())
|
||||
}
|
||||
|
||||
/// Gives `ui` the style `style`: an app's own egui style kept by `primitives::HostStyle`, or `ui`'s own back after it.
|
||||
pub(crate) fn set_style(ui: &mut Ui, style: &Arc<egui::Style>) {
|
||||
ui.set_style(Arc::clone(style));
|
||||
}
|
||||
|
||||
/// Matches egui's font coverage transfer function to `mode` across both egui theme styles, so dark-on-light text
|
||||
/// never renders with the dark-mode curve (or vice versa) when the app's mode differs from the OS's.
|
||||
pub(crate) fn set_text_color_transfer(ctx: &Context, mode: Mode) {
|
||||
|
||||
+13
@@ -67,6 +67,12 @@ pub struct RootEnv {
|
||||
pub wheel: WheelSpeed,
|
||||
/// The code pages that decode Alt+numpad codes.
|
||||
pub alt_codes: AltCodePages,
|
||||
/// On Windows and Linux, a Ctrl+wheel in fractions of a notch (a point-unit one on Linux) is a touchpad pinch
|
||||
/// and arrives as `egui::Event::Zoom`: Windows hands a precision touchpad's pinch to apps only that way, and some
|
||||
/// Wayland stacks do too. On by default. Off, it stays a wheel event with Ctrl held, for an app whose Ctrl+wheel
|
||||
/// does something else or zooms at its own rate (Zoom with Trackpad Pinch off). Whole notches stay wheel events
|
||||
/// either way; macOS sends a pinch as its own event.
|
||||
pub ctrl_wheel_pinch: bool,
|
||||
}
|
||||
|
||||
impl Default for RootEnv {
|
||||
@@ -95,6 +101,7 @@ impl Default for RootEnv {
|
||||
today: None,
|
||||
wheel: WheelSpeed::default(),
|
||||
alt_codes: AltCodePages::default(),
|
||||
ctrl_wheel_pinch: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -279,6 +286,12 @@ impl RootEnv {
|
||||
self.alt_codes = pages;
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets whether a fractional Ctrl+wheel arrives as a pinch (`ctrl_wheel_pinch`).
|
||||
pub fn ctrl_wheel_pinch(mut self, pinch: bool) -> Self {
|
||||
self.ctrl_wheel_pinch = pinch;
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
/// The mode, contrast and motion of a pass, with `System` resolved.
|
||||
|
||||
@@ -76,6 +76,8 @@ pub(crate) struct FocusedRecord {
|
||||
pub(crate) claims: Vec<craft_keymap::Chord>,
|
||||
/// The component of the focused stop: only its state-dependent claims hold.
|
||||
pub(crate) focused: Option<Id>,
|
||||
/// The focused stop is the app's own egui widget (`Stop::host`): it reads the presses it claims from egui.
|
||||
pub(crate) host: bool,
|
||||
/// The arena root of the focused stop when the stop is a non-text member of an arena (a part of a canvas's frame
|
||||
/// overlay): the root's state-dependent claims hold too, so a canvas tool's keys work with a part focused.
|
||||
pub(crate) root: Option<Id>,
|
||||
@@ -237,21 +239,24 @@ pub(crate) fn register_stop(ctx: &Context, stop: Stop) {
|
||||
/// Registers the app's own egui widget `id`, drawn in the running pass, as its window's document canvas: a focus stop
|
||||
/// with `keys`, marked as the canvas (`KeyUse::chrome_key`). The window then shows a document, so with
|
||||
/// `RootEnv::tab_toggles_chrome` a bare Tab with nothing focused toggles its panels, as with a framework canvas. Focus
|
||||
/// reaches the canvas by Tab, F6 or `request`; while it has focus, its keys route as `keys` says (the arrows as
|
||||
/// nudges, Escape as its `Intent::Cancel`). `keys` is `KeyUse::CANVAS`, or a variant such as
|
||||
/// `KeyUse::CANVAS.with_keep(KeepKeys::Tab).with_edits(..)` while the canvas edits text in place and Tab and the
|
||||
/// clipboard are its own. With nothing focused the canvas is the key target: a bare Tab it keeps, and the clipboard
|
||||
/// events and edit chords of its edit set, stay in egui's input for the app, and nothing toggles or fires with them;
|
||||
/// Page Up and Down, Home and End arrive as its `Intent::Move`, as while it has the focus. With the canvas focused, Tab it keeps stays in egui too, and its edit set arrives as `Intent::Edit`
|
||||
/// (`keys::intents_of`), as for any focused stop. Call it each pass the canvas shows.
|
||||
/// reaches the canvas by Tab, F6, `request` or the app's own egui focus request; while it has focus, Tab and the arrows
|
||||
/// route as `keys` says (the arrows as nudges, Tab moving focus on or toggling the panels unless it keeps Tab). `keys`
|
||||
/// is `KeyUse::CANVAS`, or a variant such as `KeyUse::CANVAS.with_keep(KeepKeys::Tab).with_edits(..)` while Tab and the
|
||||
/// clipboard are the canvas's own. The canvas reads its keys from egui: with nothing focused it is the key target, and
|
||||
/// a bare Tab it keeps, the chords it claims (`KeyUse::with_claims`; Alt+numpad code entry leaves a claimed Alt+digit
|
||||
/// alone), and the clipboard events and edit chords of its edit set stay in egui's input for the app, and nothing
|
||||
/// toggles or fires with them; Page Up and Down, Home and End arrive as its `Intent::Move`, as while it has the focus.
|
||||
/// With the canvas focused, the same keys stay in egui, and Escape too, as for any focused widget of the app's own;
|
||||
/// Escape with nothing focused is the window's cancel. Call it each pass the canvas shows.
|
||||
pub fn host_canvas(ctx: &Context, id: Id, keys: KeyUse) {
|
||||
register_stop(ctx, Stop::new(id, keys.with_chrome_key(true)).host());
|
||||
}
|
||||
|
||||
/// The keys of the document canvas `viewport` registered in its last pass (`KeyUse::chrome_key`), framework or the
|
||||
/// app's own. Read before the begin hook rotates the registrations, by the input hook and the begin hook's Tab moves.
|
||||
pub(crate) fn canvas_keys(ctx: &Context, viewport: ViewportId) -> Option<KeyUse> {
|
||||
with_viewport(ctx, viewport, |state| state.stops.iter().find(|rec| rec.stop.keys.chrome_key).map(|rec| rec.stop.keys))
|
||||
/// The stop of the document canvas `viewport` registered in its last pass (`KeyUse::chrome_key`), framework or the
|
||||
/// app's own (`Stop::host`). Read before the begin hook rotates the registrations, by the input hook and the begin
|
||||
/// hook's Tab moves.
|
||||
pub(crate) fn canvas_stop(ctx: &Context, viewport: ViewportId) -> Option<Stop> {
|
||||
with_viewport(ctx, viewport, |state| state.stops.iter().find(|rec| rec.stop.keys.chrome_key).map(|rec| rec.stop.clone()))
|
||||
}
|
||||
|
||||
/// The document canvas the running viewport registered in its last pass (`KeyUse::chrome_key`): the window's key
|
||||
|
||||
@@ -262,7 +262,9 @@ impl State {
|
||||
let stop = &rec.stop;
|
||||
let roving = stop.group.is_some();
|
||||
let keys = stop.keys;
|
||||
let escape = keys.claims.iter().any(|chord| chord.key == craft_keymap::Key::Escape);
|
||||
// An app's own widget (`Stop::host`) reads its Escape from egui, as a stop that claims it does: egui keeps its
|
||||
// focus on it.
|
||||
let escape = stop.host || keys.claims.iter().any(|chord| chord.key == craft_keymap::Key::Escape);
|
||||
let filter = egui_focus::filter(
|
||||
keys.keep == super::KeepKeys::Tab,
|
||||
roving || matches!(keys.keep, super::KeepKeys::InlineArrows | super::KeepKeys::BlockArrows),
|
||||
@@ -862,6 +864,7 @@ pub(super) fn end(state: &mut State, focused: Option<Id>, on_app_widget: bool, f
|
||||
state.record = super::FocusedRecord {
|
||||
claims: keys.map(|keys| keys.claims.to_vec()).unwrap_or_default(),
|
||||
focused: stop.as_ref().map(|stop| stop.id),
|
||||
host: stop.as_ref().is_some_and(|stop| stop.host),
|
||||
root: stop.as_ref().filter(|stop| stop.root != stop.id && !stop.text).map(|stop| stop.root),
|
||||
menu: state.focused_menu_level(),
|
||||
pages: stop.as_ref().is_some_and(|stop| stop.role.pages),
|
||||
|
||||
@@ -295,7 +295,9 @@ pub struct KeyUse {
|
||||
pub keep: KeepKeys,
|
||||
/// The keys that activate.
|
||||
pub activate: ActivateKeys,
|
||||
/// Chords kept from the shortcut dispatcher while focused.
|
||||
/// Chords kept from the shortcut dispatcher, and from Alt+numpad code entry, while focused, and for the window's
|
||||
/// document canvas also while nothing has the focus. An app's own egui widget (`focus::host_canvas`) reads their
|
||||
/// presses from egui's input; a framework component reads them as claimed chords.
|
||||
pub claims: &'static [Chord],
|
||||
/// Edit commands delivered as `Intent::Edit`.
|
||||
pub edits: EditSet,
|
||||
|
||||
@@ -32,6 +32,12 @@ pub struct FrameInput {
|
||||
pub host: Option<Arc<Host>>,
|
||||
/// The modifiers the app's own tablet or latched-key reader holds down beyond the window's input.
|
||||
pub latched: Mods,
|
||||
/// The window in which the app's own egui code shows a modal this frame (a dialog the app draws itself, not a
|
||||
/// framework layer). It blocks the app's other windows as a framework app-modal layer open in it does: their
|
||||
/// presses, keys, wheel and text go nowhere, a press there brings the modal's window forward, and they refuse to
|
||||
/// close. A panel floated into a window of its own is one of them. `None` (the default) when the app shows no such
|
||||
/// modal; set every frame from the app's own state.
|
||||
pub app_modal: Option<ViewportId>,
|
||||
/// Whether the window system's input reaches the OS windows the runtime hosts.
|
||||
pub window_input: WindowInput,
|
||||
}
|
||||
@@ -54,7 +60,7 @@ pub enum WindowInput {
|
||||
impl FrameInput {
|
||||
/// A frame with `root` and no host.
|
||||
pub fn new(root: RootEnv) -> Self {
|
||||
FrameInput { root, commands: CommandInput::new(), host: None, latched: Mods::NONE, window_input: WindowInput::Live }
|
||||
FrameInput { root, commands: CommandInput::new(), host: None, latched: Mods::NONE, app_modal: None, window_input: WindowInput::Live }
|
||||
}
|
||||
|
||||
/// Sets whether the window system's input reaches the hosted windows.
|
||||
@@ -75,6 +81,12 @@ impl FrameInput {
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets the window in which the app's own egui code shows a modal ([`FrameInput::app_modal`](Self::app_modal)).
|
||||
pub fn app_modal(mut self, viewport: Option<ViewportId>) -> Self {
|
||||
self.app_modal = viewport;
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets the host: the same `Arc<Host>` every frame, a new one to switch (see [`FrameInput::host`](Self::host)).
|
||||
pub fn host(mut self, host: Arc<Host>) -> Self {
|
||||
self.host = Some(host);
|
||||
@@ -163,6 +175,9 @@ pub struct FrameOutput {
|
||||
#[derive(Default)]
|
||||
pub(crate) struct FrameState {
|
||||
input: Option<FrameInput>,
|
||||
/// The window of `FrameInput::app_modal` and the root frame its modal first showed in: its place in the modal stack
|
||||
/// (`overlay::modal_viewport`). It stays while the app names the same window frame after frame.
|
||||
app_modal: Option<(ViewportId, u64)>,
|
||||
/// The pointer tolerances of the app's resolved tokens (`tokens.size.hit`) and the `sizes` they came from:
|
||||
/// the input hook writes the slop before any `Env` exists, and the press lifecycle reads the hit target.
|
||||
hit: Option<(Arc<AppSizes>, HitSizes)>,
|
||||
@@ -393,6 +408,10 @@ pub fn set_input(ctx: &Context, input: FrameInput) {
|
||||
if !state.hit.as_ref().is_some_and(|(sizes, _)| Arc::ptr_eq(sizes, &input.root.sizes)) {
|
||||
state.hit = Some((input.root.sizes.clone(), resolved_hit(&input.root.sizes)));
|
||||
}
|
||||
state.app_modal = match (input.app_modal, state.app_modal) {
|
||||
(Some(viewport), Some((shown, since))) if shown == viewport => Some((viewport, since)),
|
||||
(viewport, _) => viewport.map(|viewport| (viewport, pass::root_frame_nr(ctx))),
|
||||
};
|
||||
state.input = Some(input);
|
||||
ran
|
||||
});
|
||||
@@ -434,9 +453,30 @@ fn frame_hit(ctx: &Context) -> HitSizes {
|
||||
pass_state::with::<FrameState, _>(ctx, |state| state.hit.as_ref().map(|(_, hit)| *hit)).unwrap_or_else(|| resolved_hit(&AppSizes::default()))
|
||||
}
|
||||
|
||||
/// The wheel speed and Alt-code pages of the frame's root values; the defaults before the app sets any input.
|
||||
pub(crate) fn root_input(ctx: &Context) -> (WheelSpeed, AltCodePages) {
|
||||
pass_state::with::<FrameState, _>(ctx, |state| state.input.as_ref().map(|input| (input.root.wheel, input.root.alt_codes))).unwrap_or_default()
|
||||
/// What the raw-input step reads of the frame's root values (`RootEnv`).
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub(crate) struct RootInput {
|
||||
pub(crate) wheel: WheelSpeed,
|
||||
pub(crate) alt_codes: AltCodePages,
|
||||
pub(crate) ctrl_wheel_pinch: bool,
|
||||
}
|
||||
|
||||
impl RootInput {
|
||||
fn of(root: &RootEnv) -> Self {
|
||||
RootInput { wheel: root.wheel, alt_codes: root.alt_codes, ctrl_wheel_pinch: root.ctrl_wheel_pinch }
|
||||
}
|
||||
}
|
||||
|
||||
/// The raw-input values of the frame's root values; the defaults before the app sets any input.
|
||||
pub(crate) fn root_input(ctx: &Context) -> RootInput {
|
||||
pass_state::with::<FrameState, _>(ctx, |state| state.input.as_ref().map(|input| RootInput::of(&input.root)))
|
||||
.unwrap_or_else(|| RootInput::of(&RootEnv::default()))
|
||||
}
|
||||
|
||||
/// The window in which the app's own egui code shows a modal this frame (`FrameInput::app_modal`), and the root frame
|
||||
/// that modal first showed in.
|
||||
pub(crate) fn app_modal(ctx: &Context) -> Option<(ViewportId, u64)> {
|
||||
pass_state::with::<FrameState, _>(ctx, |state| state.app_modal)
|
||||
}
|
||||
|
||||
/// The frame's window-input policy; `Live` before the app sets any input.
|
||||
@@ -476,9 +516,12 @@ pub fn take_output(ctx: &Context) -> FrameOutput {
|
||||
output.declined = commands::take_declined(ctx);
|
||||
// The menu, palette and automation fires of the chrome and nav commands reach the app as ordinary fires with no
|
||||
// window: the focused window's shell takes a toggle, and its focus service a pane move, in the next pass. A key fire
|
||||
// already acted in the key stage.
|
||||
// already acted in the key stage. Quit, from any source, asks the root window to close through its close path.
|
||||
let focused = crate::runtime::egui::viewports::reported(ctx).into_iter().find(|(_, facts)| facts.focused).map(|(viewport, _)| viewport);
|
||||
for fired in &output.fired {
|
||||
if fired.phase == commands::FirePhase::Press && commands::QuitCommand::from_ref(&fired.command).is_some() {
|
||||
windows::act(ctx, ViewportId::ROOT, windows::WindowAction::Close);
|
||||
}
|
||||
if fired.source == commands::FireSource::Key {
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -204,8 +204,8 @@ fn with_browser_caps(shell: ShellInfo) -> ShellInfo {
|
||||
shell
|
||||
}
|
||||
|
||||
/// Adds the runtime plugin to `ctx` and sets the egui options the runtime owns: interface scale is a command, quit goes
|
||||
/// through the close guard, and the wheel's modifiers are the spec's. A second call on the same context is an error,
|
||||
/// Adds the runtime plugin to `ctx` and sets the egui options the runtime owns: the interface scale is the app's
|
||||
/// (`RootEnv::scale`), quit is a command that goes through the close guard, and the wheel's modifiers are the spec's. A second call on the same context is an error,
|
||||
/// checked first so an app that installs again (a language change) gets that answer; a call inside a pass is one too.
|
||||
pub fn install(ctx: &Context, spec: InstallSpec) -> Result<(), InstallError> {
|
||||
if plugin::is_registered(ctx) {
|
||||
|
||||
@@ -5,7 +5,7 @@ use super::{AltTrack, Batch, EscapePress, LastPress, MenuKey, NavKeys, Press, Sh
|
||||
use crate::runtime::commands::{self, EditCommands, FirePhase, NavCommand, WindowShortcut};
|
||||
use crate::runtime::egui::input::{self as raw_input, Arrived, KeyEvent, RawInput};
|
||||
use crate::runtime::env::Env;
|
||||
use crate::runtime::focus::{self, EndKey, KeyUse};
|
||||
use crate::runtime::focus::{self, EditSet, EndKey, KeyUse};
|
||||
use crate::runtime::frame::{ChromeToggle, request_chrome_toggle};
|
||||
use crate::runtime::overlay;
|
||||
use crate::runtime::sampler;
|
||||
@@ -25,7 +25,8 @@ struct Strip<'a> {
|
||||
records: bool,
|
||||
/// A press or a drag session is open: an Escape cancels it whatever the modifiers.
|
||||
press_captured: bool,
|
||||
claims: &'a [Chord],
|
||||
claims: &'a Claims,
|
||||
/// The edit commands the focused framework component takes as `Intent::Edit`.
|
||||
edits: &'a dyn Fn(EditCommand) -> bool,
|
||||
/// The chords bound to the edit commands that are the platform's text-editing chords.
|
||||
edit_chords: &'a [(EditCommand, Chord)],
|
||||
@@ -44,10 +45,17 @@ struct Strip<'a> {
|
||||
/// An app's own egui widget or popup has the focus (`FocusedRecord::foreign`): Tab, Escape and the clipboard
|
||||
/// events are its own.
|
||||
foreign: bool,
|
||||
/// The focused stop is the app's own egui widget (`Stop::host`, `FocusedRecord::host`), which reads its keys from
|
||||
/// egui: its Escape stays there, as an app's own focused widget's does. Tab and the arrows follow its `KeyUse`, as
|
||||
/// the framework's navigation reads it.
|
||||
host: bool,
|
||||
/// The keys of the window's canvas while nothing has the focus, neither a framework stop nor an app's own widget
|
||||
/// or popup: the canvas is then the key target, as the chrome gate takes it, and reads from egui the keys its
|
||||
/// `KeyUse` keeps (Tab with `KeepKeys::Tab`) and the clipboard events and edit chords of its edit set.
|
||||
/// `KeyUse` keeps (Tab with `KeepKeys::Tab`).
|
||||
canvas: Option<KeyUse>,
|
||||
/// The edit set whose clipboard events and edit chords stay in egui's input: the focused stop's when it is the
|
||||
/// app's own widget (`host`), else the canvas's with nothing focused (`canvas`).
|
||||
egui_edits: EditSet,
|
||||
/// egui holds no focus and the window registered no focus stop in its last pass: a framework focus move has
|
||||
/// nowhere to go, so a bare Tab is egui's. Focus on a component's widget without a stop is focus: egui would take
|
||||
/// a Tab from it as a move to the next widget it shows, in a later pass.
|
||||
@@ -214,7 +222,7 @@ impl Strip<'_> {
|
||||
false
|
||||
}
|
||||
KeyEvent::Clip { .. } if self.foreign => true,
|
||||
KeyEvent::Clip { command, .. } if self.canvas.is_some_and(|canvas| canvas.edits.contains(command)) => true,
|
||||
KeyEvent::Clip { command, .. } if self.egui_edits.contains(command) => true,
|
||||
KeyEvent::Clip { command: EditCommand::Copy | EditCommand::Cut, .. } if self.label_selection => true,
|
||||
// A clipboard event behind an open menu reaches nothing: the menu keeps it, as a platform menu does. The
|
||||
// chord's own key press still runs its command, which closes the menu.
|
||||
@@ -290,7 +298,7 @@ impl Strip<'_> {
|
||||
}
|
||||
let input = KeyInput::new(Mods { alt: false, ..mods }).with_typed(key);
|
||||
if !lone {
|
||||
let PressUse::Claimed(chord) = self.use_of(key, &input) else { return false };
|
||||
let PressUse::Claimed { chord, .. } = self.use_of(key, &input) else { return false };
|
||||
batch.claimed.push(chord);
|
||||
return true;
|
||||
}
|
||||
@@ -333,7 +341,8 @@ impl Strip<'_> {
|
||||
/// What the key stage makes of a press of `key` with `input`.
|
||||
fn use_of(&self, key: Key, input: &KeyInput) -> PressUse {
|
||||
let mods = input.mods;
|
||||
let claimed = self.claims.iter().find(|chord| self.layout.matches(chord, input, self.os));
|
||||
let matches = |claims: &[Chord]| claims.iter().find(|chord| self.layout.matches(chord, input, self.os)).copied();
|
||||
let claimed = matches(&self.claims.framework).map(|chord| (chord, false)).or_else(|| matches(&self.claims.host).map(|chord| (chord, true)));
|
||||
let ctrl_tab = key == Key::Tab && (if self.os == Os::Mac { mods.ctrl && !mods.cmd } else { mods.cmd });
|
||||
let ctrl_tab = ctrl_tab && self.pages && !self.keeps_tab;
|
||||
let bare_tab = key == Key::Tab && !mods.cmd && !mods.ctrl && !mods.alt;
|
||||
@@ -353,9 +362,8 @@ impl Strip<'_> {
|
||||
&& key.is_letter()
|
||||
&& ((mods == Mods::ALT && !self.shortcut_text(input)) || on_bar);
|
||||
let edit = self.edit_chords.iter().find(|(command, chord)| (self.edits)(*command) && self.layout.matches(chord, input, self.os));
|
||||
let canvas_edit = self.canvas.is_some_and(|canvas| {
|
||||
self.edit_chords.iter().any(|(command, chord)| canvas.edits.contains(*command) && self.layout.matches(chord, input, self.os))
|
||||
});
|
||||
let egui_edit =
|
||||
self.edit_chords.iter().any(|(command, chord)| self.egui_edits.contains(*command) && self.layout.matches(chord, input, self.os));
|
||||
let canvas_tab = bare_tab && self.canvas.is_some_and(|canvas| canvas.keep == focus::KeepKeys::Tab);
|
||||
// The chrome keys are Tab's, which the bare-Tab arm and `take_nav` read.
|
||||
let window_shortcut = self
|
||||
@@ -363,13 +371,13 @@ impl Strip<'_> {
|
||||
.iter()
|
||||
.find(|(key, chord)| !matches!(key, WindowShortcut::Chrome(_)) && self.layout.matches(chord, input, self.os))
|
||||
.map(|(key, _)| *key);
|
||||
if let Some(chord) = claimed {
|
||||
PressUse::Claimed(*chord)
|
||||
if let Some((chord, egui)) = claimed {
|
||||
PressUse::Claimed { chord, egui }
|
||||
} else if let Some((command, _)) = edit {
|
||||
PressUse::Edit(*command)
|
||||
} else if key == Key::Space && self.canvas_space {
|
||||
PressUse::CanvasSpace
|
||||
} else if (self.foreign && (bare_tab || escape)) || canvas_tab || canvas_edit {
|
||||
} else if (self.foreign && (bare_tab || escape)) || (self.host && escape && !self.press_captured) || canvas_tab || egui_edit {
|
||||
PressUse::Egui
|
||||
} else if bare_tab && self.no_stops {
|
||||
PressUse::TabToEgui
|
||||
@@ -393,9 +401,9 @@ impl Strip<'_> {
|
||||
fn press(&self, batch: &mut Batch, key: Key, input: &KeyInput, repeat: bool, at: Option<f64>) -> bool {
|
||||
let mods = input.mods;
|
||||
match self.use_of(key, input) {
|
||||
PressUse::Claimed(chord) => {
|
||||
PressUse::Claimed { chord, egui } => {
|
||||
batch.claimed.push(chord);
|
||||
false
|
||||
egui
|
||||
}
|
||||
PressUse::Edit(command) => {
|
||||
batch.clips.push((command, batch.place));
|
||||
@@ -429,8 +437,9 @@ impl Strip<'_> {
|
||||
}
|
||||
false
|
||||
}
|
||||
// The app's own focused widget or popup, or the canvas with nothing focused, reads the key from egui; the
|
||||
// runtime routes nothing for it, so no shortcut toggles the chrome or fires an edit command with it either.
|
||||
// The app's own focused widget (a host stop included) or popup, or the canvas with nothing focused, reads
|
||||
// the key from egui; the runtime routes nothing for it, so no shortcut toggles the chrome or fires an edit
|
||||
// command with it either.
|
||||
PressUse::Egui => true,
|
||||
PressUse::TabToEgui => {
|
||||
// egui moves its own focus with it, from nothing focused into the app's own widgets (`focus::begin`).
|
||||
@@ -514,8 +523,12 @@ impl Strip<'_> {
|
||||
|
||||
/// What the key stage makes of one press (`Strip::use_of`).
|
||||
enum PressUse {
|
||||
/// The focused component or a capture claims the chord.
|
||||
Claimed(Chord),
|
||||
/// The key target or a capture claims the chord. `egui`: the claim is an app's own egui widget's
|
||||
/// (`Stop::host`), which reads the press from egui's input, so egui keeps it.
|
||||
Claimed {
|
||||
chord: Chord,
|
||||
egui: bool,
|
||||
},
|
||||
/// The chord of an edit command the focused component lists.
|
||||
Edit(EditCommand),
|
||||
/// The Space of the canvas a dialog keeps open.
|
||||
@@ -545,6 +558,14 @@ enum PressUse {
|
||||
/// Shift+Tab.
|
||||
pub(super) fn focused_claims(record: &focus::FocusedRecord, stage: &Stage) -> Vec<Chord> {
|
||||
let mut claims = record.claims.clone();
|
||||
claims.extend(state_claims(record, stage));
|
||||
claims
|
||||
}
|
||||
|
||||
/// The chords of `focused_claims` that the focused stop does not declare: the state-dependent ones (the unfocused
|
||||
/// canvas's included) and the End of `EndKey::EndMode`.
|
||||
fn state_claims(record: &focus::FocusedRecord, stage: &Stage) -> Vec<Chord> {
|
||||
let mut claims = Vec::new();
|
||||
let canvas = record.canvas.filter(|_| !record.foreign);
|
||||
let holds = |owner: Id| [record.focused, record.root, record.menu, record.menu_bar].contains(&Some(owner));
|
||||
// The unfocused canvas's tool never takes Tab or Shift+Tab: with nothing focused they move focus into the window,
|
||||
@@ -590,7 +611,7 @@ pub(super) fn tab_toggles_now(ctx: &Context) -> bool {
|
||||
let viewport = crate::runtime::egui::pass::current_viewport(ctx);
|
||||
let enabled = Env::root_for(ctx, viewport).is_some_and(|env| env.tab_toggles_chrome);
|
||||
let focused = focus::focused_rec(ctx);
|
||||
let canvas = focus::canvas_keys(ctx, viewport).is_some();
|
||||
let canvas = focus::canvas_stop(ctx, viewport).is_some();
|
||||
let layer = overlay::key_layer(ctx, &focused.as_ref().map(|rec| focus::scope_chain(ctx, rec)).unwrap_or_default(), None);
|
||||
let pressed = focused.as_ref().is_some_and(|rec| focus::origin(ctx, rec) == Some(focus::FocusOrigin::Press));
|
||||
tab_toggles_chrome(enabled, canvas, layer, focused.as_ref().map(|rec| &rec.stop), pressed)
|
||||
@@ -641,7 +662,8 @@ pub(crate) fn input_hook(ctx: &Context, input: &RawInput, events: &mut Vec<Arriv
|
||||
let keys = record.keys;
|
||||
let menu_bar = record.menu_bar.is_some() && keys.is_none_or(|keys| !focus::takes_letters(&keys));
|
||||
let before = events.len();
|
||||
let canvas = focus::canvas_keys(ctx, viewport).filter(|_| keys.is_none() && !record.foreign);
|
||||
let target_canvas = target_canvas(ctx, viewport, &record);
|
||||
let canvas = target_canvas.as_ref().map(|stop| stop.keys);
|
||||
let lists_edits = |keys: &KeyUse| EditCommands::ALL.iter().any(|command| command.edit().is_some_and(|edit| keys.edits.contains(edit)));
|
||||
let edit_chords = if keys.as_ref().or(canvas.as_ref()).is_some_and(lists_edits) { commands::edit_chords(ctx) } else { Arc::default() };
|
||||
let window_shortcuts = commands::window_shortcuts(ctx);
|
||||
@@ -655,8 +677,8 @@ pub(crate) fn input_hook(ctx: &Context, input: &RawInput, events: &mut Vec<Arriv
|
||||
let press_captured = crate::runtime::pointer::press_captured_in(ctx, viewport) || crate::runtime::drag::running(ctx);
|
||||
let repeats = Env::root_for(ctx, viewport).is_some_and(|env| env.shortcuts_repeat);
|
||||
let (batch, visible, later) = with(ctx, viewport, |stage| {
|
||||
let claims = stage_claims(&record, stage);
|
||||
let edits = |command| keys.is_some_and(|keys| keys.edits.contains(command));
|
||||
let claims = stage_claims(&record, target_canvas.as_ref(), stage);
|
||||
let edits = |command| !record.host && keys.is_some_and(|keys| keys.edits.contains(command));
|
||||
stage.layout.set_latin(input.keyboard_layout_is_latin);
|
||||
let strip = Strip {
|
||||
os,
|
||||
@@ -675,7 +697,9 @@ pub(crate) fn input_hook(ctx: &Context, input: &RawInput, events: &mut Vec<Arriv
|
||||
holds_drafts: keys.is_some_and(|keys| keys.holds_drafts),
|
||||
canvas_space: hole.as_ref().is_some_and(|hole| hole.space || hole.space_pressed),
|
||||
foreign: record.foreign,
|
||||
host: record.host,
|
||||
canvas,
|
||||
egui_edits: keys.filter(|_| record.host).or(canvas).map_or(EditSet::NONE, |keys| keys.edits),
|
||||
no_stops,
|
||||
label_selection: record.label_selection,
|
||||
alt_claimed: !stage.alt_claims.is_empty(),
|
||||
@@ -760,12 +784,33 @@ pub(crate) fn input_hook(ctx: &Context, input: &RawInput, events: &mut Vec<Arriv
|
||||
(trimmed || events.len() != before, later)
|
||||
}
|
||||
|
||||
/// The chords the key stage takes as claimed (`PressUse::Claimed`): the focused component's (`focused_claims`) and
|
||||
/// every capture's.
|
||||
fn stage_claims(record: &focus::FocusedRecord, stage: &Stage) -> Vec<Chord> {
|
||||
let mut claims = focused_claims(record, stage);
|
||||
claims.extend(stage.captures.iter().map(|(_, chord)| *chord));
|
||||
claims
|
||||
/// The chords the key stage takes as claimed (`PressUse::Claimed`).
|
||||
struct Claims {
|
||||
/// The captures', the menu level's and the menu bar's, and the key target's when it is a framework component.
|
||||
framework: Vec<Chord>,
|
||||
/// The ones the key target declares (`KeyUse::claims`) when it is an app's own egui widget (`Stop::host`): egui
|
||||
/// keeps their presses, where the app reads them.
|
||||
host: Vec<Chord>,
|
||||
}
|
||||
|
||||
/// The window's document canvas as the key target of `viewport`'s input: nothing has the focus, neither a framework
|
||||
/// stop nor an app's own widget or popup (`Strip::canvas`).
|
||||
fn target_canvas(ctx: &Context, viewport: ViewportId, record: &focus::FocusedRecord) -> Option<focus::Stop> {
|
||||
focus::canvas_stop(ctx, viewport).filter(|_| record.keys.is_none() && !record.foreign)
|
||||
}
|
||||
|
||||
/// The claims of the key stage: the focused component's (`focused_claims`) and every capture's. With nothing focused
|
||||
/// the window's document canvas `canvas` (`target_canvas`) stands for the focused component with the chords it
|
||||
/// declares, as it does for a fired command (`claims::fire_claimed`).
|
||||
fn stage_claims(record: &focus::FocusedRecord, canvas: Option<&focus::Stop>, stage: &Stage) -> Claims {
|
||||
let (mut framework, mut host) =
|
||||
if record.host { (state_claims(record, stage), record.claims.clone()) } else { (focused_claims(record, stage), Vec::new()) };
|
||||
framework.extend(stage.captures.iter().map(|(_, chord)| *chord));
|
||||
if let Some(canvas) = canvas {
|
||||
let to = if canvas.host { &mut host } else { &mut framework };
|
||||
to.extend_from_slice(canvas.keys.claims);
|
||||
}
|
||||
Claims { framework, host }
|
||||
}
|
||||
|
||||
/// Whether the key stage of `input`'s viewport will take a press as a claimed chord (`PressUse::Claimed`), read before
|
||||
@@ -775,12 +820,13 @@ pub(crate) fn claims_press(ctx: &Context, input: &RawInput) -> impl Fn(&egui::Ev
|
||||
let viewport = input.viewport_id;
|
||||
let os = crate::runtime::windows::os_of(ctx);
|
||||
let record = focus::record(ctx, viewport);
|
||||
let (claims, mut layout) = with(ctx, viewport, |stage| (stage_claims(&record, stage), stage.layout.clone()));
|
||||
let canvas = target_canvas(ctx, viewport, &record);
|
||||
let (claims, mut layout) = with(ctx, viewport, |stage| (stage_claims(&record, canvas.as_ref(), stage), stage.layout.clone()));
|
||||
layout.set_latin(input.keyboard_layout_is_latin);
|
||||
let latin = input.latin_layout_chars.clone();
|
||||
// Only a press is read, and it carries its own modifiers.
|
||||
move |event: &egui::Event| match raw_input::key_event(event, os, &latin, Mods::NONE) {
|
||||
KeyEvent::Press { input: pressed, .. } => claims.iter().any(|chord| layout.matches(chord, &pressed, os)),
|
||||
KeyEvent::Press { input: pressed, .. } => claims.framework.iter().chain(&claims.host).any(|chord| layout.matches(chord, &pressed, os)),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -217,7 +217,8 @@ pub(crate) fn begin(ctx: &Context, press_captured: bool) -> EscapeRouting {
|
||||
None => {
|
||||
// A capture's owner, else the claim's: the focused component's own, then its arena root's, then its
|
||||
// menu level's, then the registered menu bar's (keytips hold their letters with no focus), then the
|
||||
// document canvas's with nothing focused.
|
||||
// document canvas's with nothing focused: a state-dependent claim it holds, else one it declares
|
||||
// (`KeyUse::claims`).
|
||||
let held = |owner: Option<Id>| held_claims.iter().find(|(id, held)| Some(*id) == owner && held == chord).map(|(id, _)| *id);
|
||||
let owner = captures.iter().find(|(_, held)| held == chord).map(|(owner, _)| *owner);
|
||||
claimed.extend(
|
||||
@@ -228,6 +229,7 @@ pub(crate) fn begin(ctx: &Context, press_captured: bool) -> EscapeRouting {
|
||||
.or_else(|| held(menu_bar))
|
||||
.or_else(|| held(record.canvas))
|
||||
.or(focused)
|
||||
.or_else(|| canvas.as_ref().map(|canvas| canvas.stop.id))
|
||||
.map(|id| (id, *chord)),
|
||||
);
|
||||
}
|
||||
@@ -547,12 +549,12 @@ pub(crate) fn take_shortcuts(ctx: &Context) -> Shortcuts {
|
||||
}
|
||||
|
||||
/// Asks the focused component of the running viewport to take `command` as `Intent::Edit` in the next pass.
|
||||
/// `false` when it does not list the command. A paste asks the platform for the clipboard text, which arrives as
|
||||
/// `false` when it does not list the command, or is the app's own widget (`Stop::host`), whose edits are the app's. A paste asks the platform for the clipboard text, which arrives as
|
||||
/// the paste event that becomes the intent. Focus is read as it is now: a menu pick returns focus in its pass
|
||||
/// before its command fires, and the command goes where focus returned.
|
||||
pub(crate) fn queue_edit(ctx: &Context, command: EditCommand) -> bool {
|
||||
let viewport = crate::runtime::egui::pass::current_viewport(ctx);
|
||||
if !focus::focused_rec(ctx).is_some_and(|rec| rec.stop.keys.edits.contains(command)) {
|
||||
if !focus::focused_rec(ctx).is_some_and(|rec| !rec.stop.host && rec.stop.keys.edits.contains(command)) {
|
||||
return false;
|
||||
}
|
||||
if command == EditCommand::Paste {
|
||||
|
||||
@@ -859,15 +859,16 @@ fn families(entries: &[OpenEntry], raised: &IdMap<u64>) -> Vec<Vec<OpenEntry>> {
|
||||
groups.into_iter().map(|(_, members)| members).collect()
|
||||
}
|
||||
|
||||
/// The end hook: raises the families that appeared or were pressed, hands egui the whole order, and records the
|
||||
/// open-modal fact.
|
||||
/// The end hook: raises the families that appeared, were pressed or were asked to (`raise`), hands egui the order of
|
||||
/// every layer above the floating windows (which keep egui's own area order, where an asked raise moves them to the
|
||||
/// top), and records the open-modal fact.
|
||||
pub(crate) fn end_pass(ctx: &Context) {
|
||||
let viewport = pass::current_viewport(ctx);
|
||||
let (current, last_ids, raise) =
|
||||
with_pass(ctx, |pass| (pass.current.clone(), pass.last.iter().map(|entry| entry.id).collect::<Vec<_>>(), pass.raise.clone()));
|
||||
let pressed = pointer::frame_raw(ctx).press.map(|press| press.origin);
|
||||
let now = pass::root_frame_nr(ctx);
|
||||
let order = with_persist(ctx, viewport, |persist| {
|
||||
let (order, to_top) = with_persist(ctx, viewport, |persist| {
|
||||
let stamp = |id: Id, persist: &mut Persist| {
|
||||
persist.counter += 1;
|
||||
persist.raised.insert(id, persist.counter);
|
||||
@@ -883,6 +884,7 @@ pub(crate) fn end_pass(ctx: &Context) {
|
||||
stamp(*root, persist);
|
||||
}
|
||||
}
|
||||
let mut asked: Vec<Id> = Vec::new();
|
||||
for id in raise {
|
||||
let mut at = current.iter().find(|entry| entry.id == id);
|
||||
while let Some(parent) = at.and_then(|entry| entry.parent).and_then(|parent| current.iter().find(|other| other.id == parent)) {
|
||||
@@ -890,6 +892,7 @@ pub(crate) fn end_pass(ctx: &Context) {
|
||||
}
|
||||
if let Some(root) = at {
|
||||
stamp(root.id, persist);
|
||||
asked.push(root.id);
|
||||
}
|
||||
}
|
||||
persist.raised.retain(|id, _| roots.contains(id));
|
||||
@@ -906,12 +909,24 @@ pub(crate) fn end_pass(ctx: &Context) {
|
||||
}
|
||||
let families = families(¤t, &persist.raised);
|
||||
let mut order: Vec<Layer> = Vec::new();
|
||||
let mut listed: Vec<Id> = Vec::new();
|
||||
let mut to_top: Vec<Layer> = Vec::new();
|
||||
persist.stack.clear();
|
||||
for members in &families {
|
||||
for member in members {
|
||||
if !member.window {
|
||||
// A floating window or panel (`Rank::Window`) is left to egui's own area order, which raises a layer
|
||||
// when it first shows and when it is pressed: the app's own egui windows stack with it in that one
|
||||
// order, so a dialog the app opens later shows above it. Listed layers would go above every unlisted
|
||||
// layer of their egui order, so a float opened from a listed layer (a panel floated from a full-window
|
||||
// container) is listed too, above its parent. An OS window has no egui layer here.
|
||||
let over_listed = member.parent.is_some_and(|parent| listed.contains(&parent));
|
||||
if !member.window && (member.rank != Rank::Window || over_listed) {
|
||||
order.extend(member.cover);
|
||||
order.push(member.layer);
|
||||
listed.push(member.id);
|
||||
} else if !member.window && members.first().is_some_and(|root| asked.contains(&root.id)) {
|
||||
// An asked raise of a layer left to egui's area order raises it there, as a press on it does.
|
||||
to_top.push(member.layer);
|
||||
}
|
||||
persist.stack.push(member.id);
|
||||
}
|
||||
@@ -938,9 +953,12 @@ pub(crate) fn end_pass(ctx: &Context) {
|
||||
.map(|(_, members)| {
|
||||
members.iter().flat_map(|member| std::iter::once(member.rect).chain(member.anchor).chain(member.peers.iter().copied())).collect()
|
||||
});
|
||||
order
|
||||
(order, to_top)
|
||||
});
|
||||
areas::set_layer_order(ctx, &order);
|
||||
for layer in to_top {
|
||||
areas::move_to_top(ctx, layer);
|
||||
}
|
||||
// An owner takes a close in the frame after the request at the latest; one nobody took is for a layer that is not shown.
|
||||
pass_state::with::<Closes, _>(ctx, |closes| closes.0.retain(|(.., queued, carried)| *carried || queued + 1 >= now));
|
||||
let top_modal = current.iter().rev().find(|entry| entry.blocks_window() && !entry.exiting);
|
||||
@@ -1027,23 +1045,29 @@ pub(crate) fn beneath(ctx: &Context, layer: Id) -> (bool, Option<Id>) {
|
||||
(root.is_some() || modal_elsewhere(ctx, viewport), root)
|
||||
}
|
||||
|
||||
/// The live viewports with a modal layer open as of their last finished pass, each with its place in the modal stack
|
||||
/// (`Persist::modal`).
|
||||
/// The live viewports with a modal open, each with its place in the modal stack: a modal layer as of their last
|
||||
/// finished pass (`Persist::modal`), or the app's own egui modal (`FrameInput::app_modal`), which blocks the app's other
|
||||
/// windows as a modal layer does. With both, the one that opened later is the window's top modal.
|
||||
fn modal_viewports(ctx: &Context) -> impl Iterator<Item = (ViewportId, u64)> + '_ {
|
||||
pass::live_viewports(ctx).into_iter().filter_map(|viewport| with_persist(ctx, viewport, |persist| persist.modal).map(|opened| (viewport, opened)))
|
||||
let app_modal = crate::runtime::frame::app_modal(ctx);
|
||||
pass::live_viewports(ctx).into_iter().filter_map(move |viewport| {
|
||||
let layer = with_persist(ctx, viewport, |persist| persist.modal);
|
||||
let app = app_modal.filter(|(shown, _)| *shown == viewport).map(|(_, since)| since);
|
||||
layer.max(app).map(|opened| (viewport, opened))
|
||||
})
|
||||
}
|
||||
|
||||
/// The viewport whose modal layer blocks `viewport`: of the other viewports whose top modal opened in a later frame
|
||||
/// than `viewport`'s own (any, when it has none), the one that opened last, the window a blocked press raises.
|
||||
/// The viewport whose modal blocks `viewport`: of the other viewports whose top modal opened in a later frame than
|
||||
/// `viewport`'s own (any, when it has none), the one that opened last, the window a blocked press raises.
|
||||
pub(crate) fn modal_viewport(ctx: &Context, viewport: ViewportId) -> Option<ViewportId> {
|
||||
let own = with_persist(ctx, viewport, |persist| persist.modal);
|
||||
let own = modal_viewports(ctx).find(|(shown, _)| *shown == viewport).map(|(_, opened)| opened);
|
||||
modal_viewports(ctx)
|
||||
.filter(|(other, opened)| *other != viewport && own.is_none_or(|own| *opened > own))
|
||||
.max_by_key(|(_, opened)| *opened)
|
||||
.map(|(other, _)| other)
|
||||
}
|
||||
|
||||
/// The viewport at the top of the modal stack: the window that blocks the app's other windows.
|
||||
/// The viewport at the top of the modal stack (`modal_viewports`): the window that blocks the app's other windows.
|
||||
pub(crate) fn app_modal_viewport(ctx: &Context) -> Option<ViewportId> {
|
||||
modal_viewports(ctx).max_by_key(|(_, opened)| *opened).map(|(viewport, _)| viewport)
|
||||
}
|
||||
|
||||
@@ -201,6 +201,12 @@ impl Frames {
|
||||
passes
|
||||
}
|
||||
|
||||
/// One frame with `events`, as [`frame`](Self::frame); returns whether the frame sent a window a close command.
|
||||
pub fn frame_closing(&mut self, events: Vec<Event>, ui: impl FnMut(&mut Ui)) -> bool {
|
||||
set_input(&self.ctx, self.input());
|
||||
self.run(egui::ViewportId::ROOT, events, ui)
|
||||
}
|
||||
|
||||
/// One frame with no `set_input`, as an app that never calls it would drive it: the root values and the
|
||||
/// interface scale stay as they were. Returns whether the frame sent a close command.
|
||||
pub fn frame_without_input(&mut self, events: Vec<Event>, ui: impl FnMut(&mut Ui)) -> bool {
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
//! Trials of the keys and presses a host's own egui widgets keep while the runtime is installed on the whole window.
|
||||
|
||||
use crate::contract::{Common, Component, Container, ContainerProps, Cx, Mount, Overlay, Props as _, Role, ShowContainer as _};
|
||||
use crate::runtime::commands::{AppCatalog, Binding, CommandDef, CommandInput, CommandSet as _, EditCommands, NavCommand, Scope, TypingRule};
|
||||
use crate::runtime::commands::{
|
||||
AppCatalog, Binding, CommandDef, CommandInput, CommandSet as _, EditCommands, NavCommand, QuitCommand, Scope, TypingRule,
|
||||
};
|
||||
use crate::runtime::drag::{self, DragPreview};
|
||||
use crate::runtime::egui::{areas, fixture};
|
||||
use crate::runtime::env::{Env, RootEnv};
|
||||
@@ -509,6 +511,66 @@ fn a_host_canvas_reads_the_clipboard_of_its_edit_set_with_nothing_focused() {
|
||||
assert!(!clipboard_with_canvas(KeyUse::CANVAS, chord).1.is_empty(), "a canvas without the command: the chord fires the app's Paste");
|
||||
}
|
||||
|
||||
/// What a host canvas with GridCraft's keys saw of a copy and an Escape while it held egui focus: whether the copy
|
||||
/// reached egui's input with no command fired, the keys that reached egui and the window cancels, and egui's focus
|
||||
/// after the Escape. `app_focus` gives it egui focus by the app's own request, else by the framework's `request`.
|
||||
fn focused_host_canvas_keys(app_focus: bool) -> (bool, (Vec<Key>, usize), Option<Id>) {
|
||||
const KEYS: KeyUse = KeyUse::CANVAS.with_keep(KeepKeys::Tab).with_edits(EditSet::ALL);
|
||||
let canvas = named_id("host canvas");
|
||||
let events = Rc::new(RefCell::new(Vec::new()));
|
||||
let seen_events = Rc::clone(&events);
|
||||
let (host, mut base) = host_window();
|
||||
let mut show = move |ui: &mut Ui| {
|
||||
seen_events.borrow_mut().extend(ui.input(|input| input.events.clone()));
|
||||
base(ui);
|
||||
widget(ui, canvas);
|
||||
host_canvas(ui.ctx(), canvas, KEYS);
|
||||
};
|
||||
let mut frames = Frames::new();
|
||||
frames.frame(Vec::new(), &mut show);
|
||||
if app_focus {
|
||||
fixture::host_focus(&frames.ctx, canvas);
|
||||
} else {
|
||||
request(&frames.ctx, FocusTarget::Id(canvas));
|
||||
}
|
||||
frames.frame(Vec::new(), &mut show);
|
||||
assert_eq!(egui_focused(&frames.ctx), Some(canvas), "the canvas holds egui focus");
|
||||
take_output(&frames.ctx);
|
||||
seen(&host);
|
||||
events.borrow_mut().clear();
|
||||
frames.frame(vec![Event::Copy], &mut show);
|
||||
frames.frame(Vec::new(), &mut show);
|
||||
let copied = events.borrow().contains(&Event::Copy) && take_output(&frames.ctx).fired.is_empty();
|
||||
press_key(&mut frames, &mut show, Key::Escape);
|
||||
let escape = seen(&host);
|
||||
frames.frame(Vec::new(), &mut show);
|
||||
(copied, escape, egui_focused(&frames.ctx))
|
||||
}
|
||||
|
||||
/// A host canvas holding egui focus is the app's own focused widget: its clipboard events and Escape stay in egui's
|
||||
/// input, and no window cancel comes of the Escape. With nothing focused, Escape is the window's cancel.
|
||||
#[trial]
|
||||
fn a_host_canvas_with_egui_focus_reads_escape_and_the_clipboard_from_egui() {
|
||||
let canvas = named_id("host canvas");
|
||||
let (copied, escape, focused) = focused_host_canvas_keys(false);
|
||||
assert!(copied, "the copy of a canvas the framework focused stays in egui and fires nothing");
|
||||
assert_eq!(escape, (vec![Key::Escape], 0), "its Escape is egui's, and no window cancel");
|
||||
assert_eq!(focused, Some(canvas), "egui keeps the framework's focus on the canvas over its Escape");
|
||||
let (copied, escape, _) = focused_host_canvas_keys(true);
|
||||
assert!(copied, "the copy of a canvas the app focused stays in egui and fires nothing");
|
||||
assert_eq!(escape, (vec![Key::Escape], 0), "and its Escape");
|
||||
let (host, mut base) = host_window();
|
||||
let mut show = move |ui: &mut Ui| {
|
||||
base(ui);
|
||||
widget(ui, canvas);
|
||||
host_canvas(ui.ctx(), canvas, KeyUse::CANVAS.with_keep(KeepKeys::Tab).with_edits(EditSet::ALL));
|
||||
};
|
||||
let mut frames = Frames::new();
|
||||
frames.frame(Vec::new(), &mut show);
|
||||
press_key(&mut frames, &mut show, Key::Escape);
|
||||
assert_eq!(seen(&host), (Vec::new(), 1), "with nothing focused, Escape is the window's cancel");
|
||||
}
|
||||
|
||||
/// Which of the arrow keys, Home and End reached egui's input, one press each, in a window whose host declares a canvas;
|
||||
/// with `focus_field` the host's text field has the focus; and whether Left moved the field's caret.
|
||||
fn navigation_keys_with_canvas(focus_field: bool) -> (Vec<Key>, bool) {
|
||||
@@ -594,17 +656,22 @@ fn a_pasted_image_runs_the_paste_a_pasted_text_runs() {
|
||||
|
||||
/// What an F6 press did under `overrides`: whether it reached egui, and the ids of the commands it fired.
|
||||
fn f6_under(overrides: Option<craft_keymap::Overrides>) -> (bool, Vec<String>) {
|
||||
let (host, mut show) = host_window();
|
||||
let (host, show) = host_window();
|
||||
f6_in(&host, show, overrides)
|
||||
}
|
||||
|
||||
/// What an F6 press did under `overrides` in the window `show` draws, whose host records what reached egui in `host`.
|
||||
fn f6_in(host: &RefCell<Host>, mut show: impl FnMut(&mut Ui), overrides: Option<craft_keymap::Overrides>) -> (bool, Vec<String>) {
|
||||
let mut frames = Frames::new();
|
||||
if let Some(overrides) = overrides {
|
||||
frames.commands(CommandInput::new().overrides(Arc::new(overrides)));
|
||||
}
|
||||
frames.frame(Vec::new(), &mut show);
|
||||
take_output(&frames.ctx);
|
||||
seen(&host);
|
||||
seen(host);
|
||||
press_key(&mut frames, &mut show, Key::F6);
|
||||
let fired = take_output(&frames.ctx).fired.into_iter().map(|fired| fired.command.id).collect();
|
||||
(seen(&host).0.contains(&Key::F6), fired)
|
||||
(seen(host).0.contains(&Key::F6), fired)
|
||||
}
|
||||
|
||||
#[trial]
|
||||
@@ -618,6 +685,62 @@ fn an_app_binding_on_f6_beats_the_pane_move() {
|
||||
assert_eq!(f6_under(Some(unbound)), (true, Vec::new()), "with the pane move unbound, F6 is egui's");
|
||||
}
|
||||
|
||||
/// What a ⌘Q (Ctrl+Q off the Mac) did in the host window under `overrides`: how many frames sent a close command, the
|
||||
/// app taking each frame's output before the next as `embed::before_input` does, and the ids of the commands it fired.
|
||||
fn quit_under(overrides: Option<craft_keymap::Overrides>) -> (usize, Vec<String>) {
|
||||
let (_, mut show) = host_window();
|
||||
let mut frames = Frames::new();
|
||||
if let Some(overrides) = overrides {
|
||||
frames.commands(CommandInput::new().overrides(Arc::new(overrides)));
|
||||
}
|
||||
frames.frame(Vec::new(), &mut show);
|
||||
take_output(&frames.ctx);
|
||||
let mut closes = usize::from(frames.frame_closing(vec![key_press(Key::Q, Modifiers::COMMAND)], &mut show));
|
||||
let mut fired = Vec::new();
|
||||
for _ in 0..3 {
|
||||
fired.extend(take_output(&frames.ctx).fired.into_iter().map(|fired| fired.command.id));
|
||||
closes += usize::from(frames.frame_closing(Vec::new(), &mut show));
|
||||
}
|
||||
(closes, fired)
|
||||
}
|
||||
|
||||
/// egui's own quit shortcut is cleared at install; the runtime's Quit command takes its place, through the root window's
|
||||
/// close path, and an app's own binding of the chord replaces it.
|
||||
#[trial]
|
||||
fn quit_asks_the_root_window_to_close_once_and_an_app_binding_replaces_it() {
|
||||
assert_eq!(quit_under(None), (1, vec![QuitCommand::Quit.id().to_owned()]), "the quit chord asks the root window to close once");
|
||||
let mut bound = craft_keymap::Overrides::default();
|
||||
bound.insert(EditCommands::Delete.id(), vec!["Cmd+Q".to_owned()]);
|
||||
assert_eq!(quit_under(Some(bound)), (0, vec![EditCommands::Delete.id().to_owned()]), "a command bound to the chord takes it");
|
||||
let mut unbound = craft_keymap::Overrides::default();
|
||||
unbound.insert(QuitCommand::Quit.id(), Vec::new());
|
||||
assert_eq!(quit_under(Some(unbound)), (0, Vec::new()), "with Quit unbound, nothing closes the window");
|
||||
}
|
||||
|
||||
/// The Alt+digit chords the hosted canvas of `an_unbound_f6_reaches_a_host_canvas_with_claims` claims.
|
||||
const CANVAS_CLAIMS: [craft_keymap::Chord; 2] = [
|
||||
craft_keymap::Chord::new(craft_keymap::Mods::ALT, craft_keymap::Key::Num1),
|
||||
craft_keymap::Chord::new(craft_keymap::Mods::ALT, craft_keymap::Key::Num2),
|
||||
];
|
||||
|
||||
/// A hosted app whose own egui canvas is the window's key target, with Tab, the edit chords and Alt+digit claims kept
|
||||
/// (SoundCraft's session view), and whose shortcut table uses F6: with both pane moves unbound, F6 reaches egui.
|
||||
#[trial]
|
||||
fn an_unbound_f6_reaches_a_host_canvas_with_claims() {
|
||||
const KEYS: KeyUse = KeyUse::CANVAS.with_keep(KeepKeys::Tab).with_edits(EditSet::ALL).with_claims(&CANVAS_CLAIMS);
|
||||
let canvas = named_id("host canvas");
|
||||
let (host, mut base) = host_window();
|
||||
let show = move |ui: &mut Ui| {
|
||||
base(ui);
|
||||
widget(ui, canvas);
|
||||
host_canvas(ui.ctx(), canvas, KEYS);
|
||||
};
|
||||
let mut unbound = craft_keymap::Overrides::default();
|
||||
unbound.insert(NavCommand::NextPane.id(), Vec::new());
|
||||
unbound.insert(NavCommand::PreviousPane.id(), Vec::new());
|
||||
assert_eq!(f6_in(&host, show, Some(unbound)), (true, Vec::new()), "the canvas's app reads F6 from egui");
|
||||
}
|
||||
|
||||
/// What a press of Escape with `mods` did with nothing focused, under `overrides`: the window cancels it raised and the
|
||||
/// ids of the commands it fired.
|
||||
fn escape_under(overrides: Option<craft_keymap::Overrides>, mods: Modifiers) -> (usize, Vec<String>) {
|
||||
|
||||
@@ -6,9 +6,10 @@ use craft_host::target::Os;
|
||||
use craft_ui::contract::{Common, Component, Cx, Input, PaintUi, PartsCx, Props as _, Role, Show as _};
|
||||
use craft_ui::primitives::{EditorLine, EditorPurpose, EditorRun, EditorState};
|
||||
use craft_ui::runtime::env::{AltCodePages, RootEnv};
|
||||
use craft_ui::runtime::focus::KeyUse;
|
||||
use craft_ui::runtime::focus::{FocusTarget, KeyUse, host_canvas, request};
|
||||
use craft_ui::runtime::frame::take_output;
|
||||
use craft_ui::style::StyleCx;
|
||||
use craft_ui::testing::focus::{named_id, widget};
|
||||
use craft_ui::testing::input::{key_press, key_repeat, text};
|
||||
use craft_ui::testing::pointer::click;
|
||||
use craft_ui::testing::{Frames, trial};
|
||||
@@ -248,3 +249,67 @@ fn an_alt_numpad_code_types_its_character_once() {
|
||||
assert!(!option.text.contains('é'), "macOS has no Alt codes: {option:?}");
|
||||
assert!(!option.lone_alt, "macOS has no lone Alt either");
|
||||
}
|
||||
|
||||
/// Alt with the digit 3, which the host canvas of the next trial claims.
|
||||
const ALT_3: craft_keymap::Chord = craft_keymap::Chord::new(craft_keymap::Mods::ALT, craft_keymap::Key::Num3);
|
||||
|
||||
/// An app's Alt+digit shortcut on Windows and Linux: the app's own egui canvas (`host_canvas`) claims Alt+3. With
|
||||
/// nothing focused the canvas is the window's key target, so Alt-code entry leaves the claimed press and egui's input
|
||||
/// keeps it for the app, while an unclaimed Alt+5 still folds into a code. With the canvas focused, the claimed press
|
||||
/// still reaches egui. A focused text field types Alt codes again, with the claimed digit among them.
|
||||
#[trial]
|
||||
fn an_alt_digit_a_host_canvas_claims_reaches_the_app_and_a_field_still_types_codes() {
|
||||
for os in [Os::Windows, Os::Linux] {
|
||||
let canvas = named_id("alt digit canvas");
|
||||
let typed = Rc::new(RefCell::new(String::new()));
|
||||
let reached = Rc::new(RefCell::new(Vec::<Key>::new()));
|
||||
let mut show = {
|
||||
let (typed, reached) = (Rc::clone(&typed), Rc::clone(&reached));
|
||||
move |ui: &mut egui::Ui| {
|
||||
let alt_digits: Vec<Key> = ui.input(|input| {
|
||||
input
|
||||
.events
|
||||
.iter()
|
||||
.filter_map(|event| match event {
|
||||
Event::Key { key, pressed: true, modifiers, .. } if modifiers.alt => Some(*key),
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
});
|
||||
reached.borrow_mut().extend(alt_digits);
|
||||
widget(ui, canvas);
|
||||
host_canvas(ui.ctx(), canvas, KeyUse::CANVAS.with_claims(&[ALT_3]));
|
||||
Probe::new(&typed).label("Text").id_salt("alt_code_field").show_at(ui, AT);
|
||||
}
|
||||
};
|
||||
let mut frames = Frames::new();
|
||||
craft_ui::testing::windows::set_os(&frames.ctx, os);
|
||||
frames.root(RootEnv::default().alt_code_pages(AltCodePages::new(1252, 437)));
|
||||
frames.idle(3, &mut show);
|
||||
// Plays `sequence`, then a frame with none; returns the Alt presses that reached egui and the field's text.
|
||||
let send = |frames: &mut Frames, show: &mut dyn FnMut(&mut egui::Ui), sequence: Vec<Vec<Event>>| {
|
||||
reached.borrow_mut().clear();
|
||||
typed.borrow_mut().clear();
|
||||
for events in sequence {
|
||||
frames.frame(events, &mut *show);
|
||||
}
|
||||
frames.frame(Vec::new(), &mut *show);
|
||||
(reached.take(), typed.take())
|
||||
};
|
||||
|
||||
let (keys, _) = send(&mut frames, &mut show, code("3"));
|
||||
assert!(keys.contains(&Key::Num3), "{os:?}: with nothing focused, the canvas's claimed Alt+3 reaches egui: {keys:?}");
|
||||
let (keys, _) = send(&mut frames, &mut show, code("5"));
|
||||
assert!(!keys.contains(&Key::Num5), "{os:?}: an unclaimed Alt+5 folds into an Alt code: {keys:?}");
|
||||
|
||||
request(&frames.ctx, FocusTarget::Id(canvas));
|
||||
let (keys, _) = send(&mut frames, &mut show, code("3"));
|
||||
assert!(keys.contains(&Key::Num3), "{os:?}: the focused canvas's claimed Alt+3 reaches egui: {keys:?}");
|
||||
|
||||
click(&mut frames, AT.center(), &mut show);
|
||||
frames.idle(1, &mut show);
|
||||
let (keys, text) = send(&mut frames, &mut show, code("0233"));
|
||||
assert_eq!(text, "é", "{os:?}: the focused field types the code, its 3 included");
|
||||
assert!(keys.is_empty(), "{os:?}: no digit of the code reaches egui: {keys:?}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -104,6 +104,13 @@ fn a_fractional_ctrl_wheel_is_a_pinch_and_a_whole_notch_stays_a_scroll() {
|
||||
assert!(native.len() == 1 && (native[0].zoom - 1.1).abs() < 1e-4, "{os:?}: a native pinch reaches the view as sent: {native:?}");
|
||||
let after_native = step(&mut fixture, vec![ctrl_lines(1.0)]);
|
||||
assert!(scrolled(&after_native), "{os:?}: a whole notch after a native pinch is a wheel notch: {after_native:?}");
|
||||
|
||||
// A host whose Ctrl+wheel does something else (Zoom with Trackpad Pinch off, or its own Ctrl-scroll zoom rate)
|
||||
// turns the fold off: the fractional step stays a wheel event.
|
||||
fixture.root(RootEnv::default().ctrl_wheel_pinch(false));
|
||||
fixture.advance(0.5);
|
||||
let unfolded = step(&mut fixture, vec![ctrl_lines(0.4)]);
|
||||
assert!(scrolled(&unfolded), "{os:?}: with `ctrl_wheel_pinch` off a fractional Ctrl+wheel is a wheel event: {unfolded:?}");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -381,6 +381,10 @@ pub struct DockGroup<'a, P: Clone + Hash + Send + Sync + 'static> {
|
||||
/// sides take no drop, and its top, bottom and middle zones reach across them.
|
||||
#[prop(flag)]
|
||||
in_window: bool,
|
||||
/// The shown panel's body is the app's own egui code (`PanelSpec::host_body`): a press on the body is the app's,
|
||||
/// and its widgets take egui focus themselves, so the press does not focus the group's tabs.
|
||||
#[prop(flag)]
|
||||
host_body: bool,
|
||||
/// The rows of the group menu, read while it is open: the panel menu button and a context request on a tab open
|
||||
/// it.
|
||||
#[prop(func = "FnMut() -> Vec<PanelRow>")]
|
||||
@@ -428,6 +432,7 @@ impl<'a, P: Clone + Hash + Send + Sync + PartialEq + Debug + 'static> DockGroup<
|
||||
dock: None,
|
||||
zones: ZoneRule::Fraction,
|
||||
in_window: false,
|
||||
host_body: false,
|
||||
menu: None,
|
||||
panel_menu_shown: true,
|
||||
panel_menu_icon: IconId::new("more"),
|
||||
@@ -449,7 +454,7 @@ impl<'a, P: Clone + Hash + Send + Sync + PartialEq + Debug + 'static> DockGroup<
|
||||
self
|
||||
}
|
||||
|
||||
/// The group takes key focus in this pass, as a click on its tabs gives it: its tab row's stop takes it while the
|
||||
/// The group takes key focus in this pass, as a press on its body gives it: its tab row's stop takes it while the
|
||||
/// row runs, so the keys of the next pass route through the group; a titled header, which has no tab row, focuses
|
||||
/// its drag band. A request of the pass.
|
||||
#[must_use]
|
||||
@@ -715,8 +720,11 @@ impl<P: Clone + Hash + Send + Sync + PartialEq + Debug + 'static> Container for
|
||||
})
|
||||
.inner;
|
||||
self.extra = extra;
|
||||
// A press on the group's empty body focuses its panel, as in Photoshop.
|
||||
if surface_pressed && let Some((strip, _)) = &strip {
|
||||
// A press on the group's empty body focuses its panel, as in Photoshop; an app's own egui body keeps its presses.
|
||||
if surface_pressed
|
||||
&& !self.host_body
|
||||
&& let Some((strip, _)) = &strip
|
||||
{
|
||||
focus::request(ui.ctx(), FocusTarget::Id(*strip));
|
||||
}
|
||||
if let Some((strip, tabs)) = &strip {
|
||||
@@ -814,8 +822,10 @@ fn tab_row<P: Clone + PartialEq + Debug + Hash + Send + Sync + 'static>(row: &mu
|
||||
let source = keyed(panels, |panel: &PanelTitle| panel.key).with_text(|panel| Cow::Borrowed(panel.title.as_str()));
|
||||
let closes = |panel: &PanelTitle| closable && panel.closable;
|
||||
let kind = if panels.iter().any(closes) { TabKind::Document } else { TabKind::Panel };
|
||||
// A press on a panel tab leaves key focus where it is, as in Photoshop: the document's keys keep working.
|
||||
let mut strip = TabStrip::new(name)
|
||||
.kind(kind)
|
||||
.keeps_focus()
|
||||
.panel_look(row.look)
|
||||
.shown(active)
|
||||
.tear_off()
|
||||
|
||||
@@ -69,7 +69,9 @@ pub trait DockPanels<P> {
|
||||
/// Shows `panel`'s body in `ui`: the group's body, inset from its edges by the panel padding. The group is the
|
||||
/// body's panel and its tab the body's title, so the body shows no framework `Panel` or padding of its own; content
|
||||
/// taller than the group scrolls in the body's own scrolling container. A document panel's body
|
||||
/// (`PanelSpec::window_kind` `Document`) gets the group's body edge to edge.
|
||||
/// (`PanelSpec::window_kind` `Document`) gets the group's body edge to edge. The body lays out with the group's
|
||||
/// spacing, or with the style of the `Ui` the dock was shown in where the panel's body is the app's own egui code
|
||||
/// (`PanelSpec::host_body`).
|
||||
fn body(&mut self, panel: &P, ui: &mut Ui, cx: &mut BodyCx<'_>);
|
||||
|
||||
/// Shows the fixed trailing controls of the rail containing `panel`, in top-to-bottom order. The dock calls this
|
||||
|
||||
@@ -191,6 +191,13 @@ pub struct PanelSpec {
|
||||
pub count: Option<usize>,
|
||||
/// A line of small faint text under the header row while the panel is the one its group shows ("2 replies").
|
||||
pub caption: Option<Label>,
|
||||
/// The panel's body is the app's own egui code: the dock hands `DockPanels::body`, `footer`, `group_header`,
|
||||
/// `rail_footer` and the group's `group_view` (while the panel is the one its group shows) a `Ui` with the style
|
||||
/// of the `Ui` the dock was shown in, so the code lays out as it does outside the dock, and runs them once per pass,
|
||||
/// in the pass's real run (a measuring run takes the size they last took). Other bodies lay out with
|
||||
/// the group's spacing, which framework components expect. An app moves onto the framework panel by panel by
|
||||
/// clearing it on each panel it ports.
|
||||
pub host_body: bool,
|
||||
}
|
||||
|
||||
impl PanelSpec {
|
||||
@@ -210,6 +217,7 @@ impl PanelSpec {
|
||||
footer: false,
|
||||
count: None,
|
||||
caption: None,
|
||||
host_body: false,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -290,6 +298,13 @@ impl PanelSpec {
|
||||
self
|
||||
}
|
||||
|
||||
/// The panel's body is the app's own egui code (`host_body`).
|
||||
#[must_use]
|
||||
pub fn host_body(mut self) -> Self {
|
||||
self.host_body = true;
|
||||
self
|
||||
}
|
||||
|
||||
/// The grid the panel lays its content in.
|
||||
#[must_use]
|
||||
pub fn grid(mut self, grid: DockGrid) -> Self {
|
||||
|
||||
@@ -63,14 +63,15 @@ fn a_held_escape_cancels_once() {
|
||||
}
|
||||
|
||||
/// Static claims hold in the frame after focus arrives; the chord is withheld from egui and read once through
|
||||
/// `take_claimed`, and a claimed Escape is no `Cancel`.
|
||||
/// `take_claimed`, and a claimed Escape is no `Cancel`. The stop is a canvas control, not the window's document canvas,
|
||||
/// whose claims hold with nothing focused too.
|
||||
#[trial]
|
||||
fn claimed_chords_hold_after_focus_arrives_and_a_claimed_escape_is_no_cancel() {
|
||||
const CLAIMS: &[Chord] = &[Chord::plain(craft_keymap::Key::Up), Chord::plain(craft_keymap::Key::Escape)];
|
||||
let mut frames = Frames::new();
|
||||
let reads = RefCell::new((Vec::new(), 0, true));
|
||||
let mut show = |ui: &mut egui::Ui| {
|
||||
stop_with(ui, "canvas", KeyUse::CANVAS.with_claims(CLAIMS));
|
||||
stop_with(ui, "canvas", KeyUse::CANVAS.with_chrome_key(false).with_claims(CLAIMS));
|
||||
let ctx = ui.ctx();
|
||||
let mut reads = reads.borrow_mut();
|
||||
reads.0.push((take_claimed(ctx, id("canvas"), CLAIMS[0]), take_claimed(ctx, id("canvas"), CLAIMS[1])));
|
||||
|
||||
@@ -20,6 +20,7 @@ use crate::docking::{
|
||||
};
|
||||
use crate::layout_components::Stack;
|
||||
use crate::menu::{GroupItem, MenuWords, PanelMenu, PanelRow};
|
||||
use crate::primitives::HostStyle;
|
||||
use crate::runtime::commands::{CommandRef, CommandSet as _, CommandState, Commands as _, focus_within};
|
||||
use crate::runtime::derived::derived;
|
||||
use crate::runtime::drag;
|
||||
@@ -158,13 +159,13 @@ pub struct DockArea<'a, P: Clone + Eq + Hash + Debug + Send + Sync + 'static> {
|
||||
/// nothing.
|
||||
#[prop(quantity = "panel and grab point")]
|
||||
continue_move: Option<(P, Vec2)>,
|
||||
/// Moves key focus to the group that shows the panel and picks its tab, as a click on the tab does: the group's
|
||||
/// stop takes focus in this pass, and the pick is one of the pass's `actions`. A floating window that holds the
|
||||
/// panel comes to the front of the windows it overlaps (`FloatingGroup::raise`); that order is the view's, and
|
||||
/// the workspace does not keep it. A request of the pass: a host that
|
||||
/// focuses a panel itself (it opened something in it) sets it for one pass. A panel the area does not show in this
|
||||
/// pass (hidden, pruned by a maximize, in a closed flyout, or in a group the host's `group_view` draws) takes
|
||||
/// neither; `DockAreaOutput::focused` tells the host where focus is.
|
||||
/// Moves key focus to the group that shows the panel, as a press on the group's body does, and picks its tab, as a
|
||||
/// click on the tab does (which leaves key focus where it was): the group's stop takes focus in this pass, and the
|
||||
/// pick is one of the pass's `actions`. A floating window that holds the panel comes to the front of the windows it
|
||||
/// overlaps (`FloatingGroup::raise`); that order is the view's, and the workspace does not keep it. A request of
|
||||
/// the pass: a host that focuses a panel itself (it opened something in it) sets it for one pass. A panel the area
|
||||
/// does not show in this pass (hidden, pruned by a maximize, in a closed flyout, or in a group the host's
|
||||
/// `group_view` draws) takes neither; `DockAreaOutput::focused` tells the host where focus is.
|
||||
#[prop]
|
||||
focus: Option<P>,
|
||||
/// Adds the host's fixed trailing controls to the docked rail containing `panel`. The panel identifies the
|
||||
@@ -341,6 +342,8 @@ struct Scene<'s, P> {
|
||||
/// The docked places floating panels left, for Dock Panel.
|
||||
floated: &'s [(P, Location<P>)],
|
||||
rail_footer: Option<&'s P>,
|
||||
/// The style of the `Ui` the area was shown in, which the bodies of `PanelSpec::host_body` panels lay out with.
|
||||
host_style: &'s HostStyle,
|
||||
}
|
||||
|
||||
/// The spec of `panel` in `specs`, or an unnamed one.
|
||||
@@ -378,7 +381,40 @@ impl<P: Clone + Eq + Hash> DockModel<P> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The parts of a group that show the host's code (`Scene::hosted`).
|
||||
#[derive(Clone, Copy, Debug, Hash)]
|
||||
enum HostPart {
|
||||
Body,
|
||||
Footer,
|
||||
Header,
|
||||
RailFooter,
|
||||
View,
|
||||
}
|
||||
|
||||
impl<P: Clone + Eq + Hash> Scene<'_, P> {
|
||||
/// Runs `run`, which shows host code of `panel` as its `part`, on `ui`. Where the panel's body is the app's own egui
|
||||
/// code (`PanelSpec::host_body`), it runs with the style of the `Ui` the area was shown in, and only in the pass's
|
||||
/// real run: a measuring run takes what its last real run took (`HostStyle::show`).
|
||||
fn hosted<R: Clone + Default + Send + Sync + 'static>(&self, panel: &P, part: HostPart, ui: &mut Ui, run: impl FnOnce(&mut Ui) -> R) -> R {
|
||||
if !self.host_body(panel) {
|
||||
return run(ui);
|
||||
}
|
||||
self.host_style.show(ui, self.dock.with(("host", part, PanelKey::of(panel))), run)
|
||||
}
|
||||
|
||||
/// Runs `run`, which measures `panel`'s host view at a width (`GroupAt::Measure`), on `ui`: with the style of the
|
||||
/// `Ui` the area was shown in where the panel's body is the app's own egui code.
|
||||
fn hosted_measure<R>(&self, panel: &P, ui: &mut Ui, run: impl FnOnce(&mut Ui) -> R) -> R {
|
||||
if !self.host_body(panel) {
|
||||
return run(ui);
|
||||
}
|
||||
self.host_style.run(ui, run)
|
||||
}
|
||||
|
||||
fn host_body(&self, panel: &P) -> bool {
|
||||
self.specs.get(panel).is_some_and(|spec| spec.host_body)
|
||||
}
|
||||
|
||||
fn spec(&self, panel: &P) -> PanelSpec {
|
||||
spec_in(self.specs, panel)
|
||||
}
|
||||
@@ -518,6 +554,7 @@ impl<'a, P: Clone + Eq + Hash + Debug + Send + Sync + 'static> DockArea<'a, P> {
|
||||
top_inset,
|
||||
} = self;
|
||||
let ctx = ui.ctx().clone();
|
||||
let host_style = HostStyle::of(ui);
|
||||
let (rtl, window) = {
|
||||
let env = Env::of(ui);
|
||||
(env.direction.is_rtl(), env.get::<ShellEntry>().0.map(|shell| shell.window().clone()))
|
||||
@@ -578,6 +615,7 @@ impl<'a, P: Clone + Eq + Hash + Debug + Send + Sync + 'static> DockArea<'a, P> {
|
||||
rtl,
|
||||
rail_footer: rail_footer.as_ref(),
|
||||
top_inset,
|
||||
host_style: &host_style,
|
||||
};
|
||||
let mut result = show_area(ui, body, &input, rights, &mut *panels, flyout.as_mut());
|
||||
for edit in &result.edit {
|
||||
@@ -686,6 +724,7 @@ struct Input<'i, P> {
|
||||
rtl: bool,
|
||||
rail_footer: Option<&'i P>,
|
||||
top_inset: f32,
|
||||
host_style: &'i HostStyle,
|
||||
}
|
||||
|
||||
/// `bounds` without its top `inset` points, never past its bottom.
|
||||
@@ -733,6 +772,7 @@ fn show_area<P: Clone + Eq + Hash + Debug + Send + Sync + 'static>(
|
||||
rtl,
|
||||
rail_footer,
|
||||
top_inset,
|
||||
host_style,
|
||||
} = *input;
|
||||
let shell = body.shell();
|
||||
let mut memory = body.memory::<AreaMemory<P>>().clone();
|
||||
@@ -759,6 +799,7 @@ fn show_area<P: Clone + Eq + Hash + Debug + Send + Sync + 'static>(
|
||||
rtl,
|
||||
floated: current.floated(),
|
||||
rail_footer,
|
||||
host_style,
|
||||
};
|
||||
let open = open_of(&mut flyout, body, &memory);
|
||||
let mut pass = Pass {
|
||||
@@ -1103,7 +1144,7 @@ impl<P: Clone + Eq + Hash + Debug + Send + Sync + 'static> Pass<'_, P> {
|
||||
// column bar, as the references' toolbar: the host's view takes the room under it.
|
||||
let grip = if members.get(active).is_some_and(|panel| scene.spec(panel).grid.is_some()) { scene.sizes.grip } else { 0.0 };
|
||||
if let GroupAt::Measure(_) = at
|
||||
&& let Some(height) = self.panels.group_view(members, active, ui, at, body)
|
||||
&& let Some(height) = scene.hosted_measure(&members[active], ui, |ui| self.panels.group_view(members, active, ui, at, body))
|
||||
{
|
||||
return Some(height + grip);
|
||||
}
|
||||
@@ -1149,7 +1190,7 @@ impl<P: Clone + Eq + Hash + Debug + Send + Sync + 'static> Pass<'_, P> {
|
||||
let words = &words;
|
||||
let GroupParts { titles, hosted, states } = parts_of();
|
||||
let mut group = DockGroup::new(anchor.clone(), titles.clone(), PanelKey::of(&members[at]))
|
||||
.extra(move |ui, body| panels.borrow_mut().group_header(members, at, ui, body))
|
||||
.extra(move |ui, body| scene.hosted(&members[at], HostPart::Header, ui, |ui| panels.borrow_mut().group_header(members, at, ui, body)))
|
||||
.dock(self.dock)
|
||||
.zones(scene.config.zone_rule())
|
||||
.movable(scene.permissions(shown).movable)
|
||||
@@ -1164,11 +1205,17 @@ impl<P: Clone + Eq + Hash + Debug + Send + Sync + 'static> Pass<'_, P> {
|
||||
let spec = scene.spec(&members[at]);
|
||||
if minimized {
|
||||
group = group.minimized();
|
||||
} else if !document(&spec) {
|
||||
} else if !document(&spec) && !spec.host_body {
|
||||
// The app's own egui body lays out in the whole body, as it did outside the dock.
|
||||
group = group.pad(Pad::Regular);
|
||||
}
|
||||
if spec.host_body {
|
||||
group = group.host_body();
|
||||
}
|
||||
if spec.footer {
|
||||
group = group.footer(move |ui, body| panels.borrow_mut().footer(&members[at], ui, body));
|
||||
group = group.footer(move |ui, body| {
|
||||
scene.hosted(&members[at], HostPart::Footer, ui, |ui| panels.borrow_mut().footer(&members[at], ui, body))
|
||||
});
|
||||
}
|
||||
if scene.config.tab_close_buttons {
|
||||
group = group.closable();
|
||||
@@ -1183,7 +1230,8 @@ impl<P: Clone + Eq + Hash + Debug + Send + Sync + 'static> Pass<'_, P> {
|
||||
};
|
||||
let rect = match at {
|
||||
GroupAt::Measure(width) => {
|
||||
let measured = make(active, look.minimized).measure_in(ui, Proposal::Width(width), |ui, body| panel_body(&panels, shown, ui, body));
|
||||
let measured =
|
||||
make(active, look.minimized).measure_in(ui, Proposal::Width(width), |ui, body| panel_body(scene, &panels, shown, ui, body));
|
||||
return Some(measured.y);
|
||||
}
|
||||
GroupAt::Show(rect) => rect,
|
||||
@@ -1197,13 +1245,17 @@ impl<P: Clone + Eq + Hash + Debug + Send + Sync + 'static> Pass<'_, P> {
|
||||
let output = ui
|
||||
.scope_builder(UiBuilder::new().max_rect(rect), |ui| {
|
||||
// The view is a layout room of its own: a view that fills takes the whole group.
|
||||
let taken = in_room(ui, view, |ui| panels.borrow_mut().group_view(members, active, ui, GroupAt::Show(view), body));
|
||||
let taken = in_room(ui, view, |ui| {
|
||||
scene.hosted(&members[active], HostPart::View, ui, |ui| {
|
||||
panels.borrow_mut().group_view(members, active, ui, GroupAt::Show(view), body)
|
||||
})
|
||||
});
|
||||
match taken {
|
||||
Some(_) => None,
|
||||
None => {
|
||||
let group = make(active, look.minimized);
|
||||
let group = if focus.is_some() { group.take_focus() } else { group };
|
||||
Some(group.show_at(ui, rect, |ui, body| panel_body(&panels, shown, ui, body)).output)
|
||||
Some(group.show_at(ui, rect, |ui, body| panel_body(scene, &panels, shown, ui, body)).output)
|
||||
}
|
||||
}
|
||||
})
|
||||
@@ -1229,7 +1281,7 @@ impl<P: Clone + Eq + Hash + Debug + Send + Sync + 'static> Pass<'_, P> {
|
||||
let at = members.iter().position(|member| member == panel).unwrap_or(active);
|
||||
let room = Vec2::new(rect.width(), scene.space.content_room());
|
||||
let measured = make(at, false).id(output.response.id).measure_in(ui, Proposal::Size(room), |ui, body| {
|
||||
panel_body(&panels, &members[at], ui, body);
|
||||
panel_body(scene, &panels, &members[at], ui, body);
|
||||
});
|
||||
Vec2::new(rect.width(), measured.y)
|
||||
};
|
||||
@@ -1435,7 +1487,9 @@ impl<P: Clone + Eq + Hash + Debug + Send + Sync + 'static> Pass<'_, P> {
|
||||
.pad(Pad::None)
|
||||
.footer(|ui, _| {
|
||||
// Compact rail controls leave room for the scrolling panel icons in short windows.
|
||||
Stack::new().fill_width().gap(Gap::None).show(ui, |ui, body| pass.borrow_mut().panels.rail_footer(panel, ui, body));
|
||||
Stack::new().fill_width().gap(Gap::None).show(ui, |ui, body| {
|
||||
scene.hosted(panel, HostPart::RailFooter, ui, |ui| pass.borrow_mut().panels.rail_footer(panel, ui, body))
|
||||
});
|
||||
})
|
||||
.show_at(ui, cell, |ui, _| {
|
||||
// design: allow[contract/allocate](the rail lays its icons out in a rect of its own: the panel body claims their height, so the host's footer sits under them)
|
||||
@@ -1842,9 +1896,24 @@ fn window_edit<P: Clone + Eq + Hash>(
|
||||
}
|
||||
}
|
||||
|
||||
/// Shows `panel`'s body in a group's body. It runs every pass the group shows; the host memoizes inside it.
|
||||
fn panel_body<'p, P: Hash>(panels: &RefCell<&mut (dyn DockPanels<P> + 'p)>, panel: &P, ui: &mut Ui, body: &mut BodyCx<'_>) {
|
||||
panels.borrow_mut().body(panel, ui, body);
|
||||
/// Shows `panel`'s body in a group's body, in the host's style and once per pass where the body is the app's own egui
|
||||
/// code (`Scene::hosted`). It runs every pass the group shows; the host memoizes inside it.
|
||||
fn panel_body<'p, P: Clone + Eq + Hash>(
|
||||
scene: &Scene<'_, P>,
|
||||
panels: &RefCell<&mut (dyn DockPanels<P> + 'p)>,
|
||||
panel: &P,
|
||||
ui: &mut Ui,
|
||||
body: &mut BodyCx<'_>,
|
||||
) {
|
||||
let host = scene.host_body(panel);
|
||||
scene.hosted(panel, HostPart::Body, ui, |ui| {
|
||||
// The app's own egui body keeps its background: the host's panel fill over the group's surface, as it showed
|
||||
// outside the dock.
|
||||
if host {
|
||||
scene.host_style.paint_panel(ui, ui.max_rect());
|
||||
}
|
||||
panels.borrow_mut().body(panel, ui, body);
|
||||
});
|
||||
}
|
||||
|
||||
/// The props of a tool rail's grip strip: the group it drags, its name, and the outbox the drag's start goes to, with
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
//! While the app's own egui code shows a modal (`FrameInput::app_modal`), a panel floated into a window of its own takes
|
||||
//! no press and no key, as under a framework app-modal layer.
|
||||
|
||||
use craft_behavior::dock::{Floating, Layout, Workspace};
|
||||
use craft_ui::contract::{Bind, BodyCx, PlainData, Tracked};
|
||||
use craft_ui::docking::{DockConfig, DockPanels, PanelSpec, PanelSpecs};
|
||||
use craft_ui::patterns::dock::DockArea;
|
||||
use craft_ui::testing::input::key_press;
|
||||
use craft_ui::testing::pointer::{moved, press, release};
|
||||
use craft_ui::testing::trial;
|
||||
use craft_ui_test_kit::windows::Windows;
|
||||
use egui::{Event, Key, Modifiers, Pos2, Rect, Ui, ViewportId, ViewportInfo};
|
||||
use std::sync::Arc;
|
||||
|
||||
const MAIN_AT: Rect = Rect { min: Pos2::new(100.0, 100.0), max: Pos2::new(900.0, 700.0) };
|
||||
const FLOAT_AT: Rect = Rect { min: Pos2::new(1000.0, 150.0), max: Pos2::new(1300.0, 350.0) };
|
||||
/// A point of the float's body, in its window's coordinates.
|
||||
const IN_BODY: Pos2 = Pos2::new(150.0, 120.0);
|
||||
|
||||
#[derive(PlainData)]
|
||||
struct Specs;
|
||||
|
||||
impl PanelSpecs<u32> for Specs {
|
||||
fn spec(&self, _: &u32) -> PanelSpec {
|
||||
PanelSpec::new("Palette").host_body()
|
||||
}
|
||||
}
|
||||
|
||||
/// The float's body: records whether a press or a key reached the egui input of a window of its own.
|
||||
#[derive(Default)]
|
||||
struct Probe {
|
||||
reached: bool,
|
||||
}
|
||||
|
||||
impl DockPanels<u32> for Probe {
|
||||
fn body(&mut self, _: &u32, ui: &mut Ui, _: &mut BodyCx<'_>) {
|
||||
if ui.ctx().viewport_id() == ViewportId::ROOT {
|
||||
return;
|
||||
}
|
||||
let pressed = |event: &Event| matches!(event, Event::PointerButton { pressed: true, .. } | Event::Key { pressed: true, .. });
|
||||
self.reached |= ui.ctx().input(|input| input.events.iter().any(pressed));
|
||||
}
|
||||
}
|
||||
|
||||
fn info(rect: Rect) -> ViewportInfo {
|
||||
ViewportInfo {
|
||||
focused: Some(true),
|
||||
inner_rect: Some(rect),
|
||||
outer_rect: Some(rect),
|
||||
native_pixels_per_point: Some(1.0),
|
||||
..ViewportInfo::default()
|
||||
}
|
||||
}
|
||||
|
||||
#[trial]
|
||||
fn a_native_float_takes_no_press_or_key_while_the_apps_own_modal_shows() {
|
||||
for modal in [None, Some(ViewportId::ROOT)] {
|
||||
let windows = Windows::new();
|
||||
windows.root_info(info(MAIN_AT));
|
||||
windows.child_info(info(FLOAT_AT));
|
||||
let float = Floating::single(100, vec![1], 0, Rect::from_min_size(Pos2::new(40.0, 40.0), FLOAT_AT.size()));
|
||||
let mut workspace = Arc::new(Workspace::new(Layout::new(None, vec![float])));
|
||||
let (specs, mut probe) = (Tracked::new(Specs), Probe::default());
|
||||
let mut frame = |child: Vec<Event>, probe: &mut Probe| {
|
||||
windows.frame(vec![], child, |ui| {
|
||||
let config = DockConfig::default().native_windows(true);
|
||||
let _ = DockArea::new("Dock", Bind::bound(&mut workspace), &specs, probe, config).show(ui);
|
||||
});
|
||||
};
|
||||
for _ in 0..3 {
|
||||
frame(vec![moved(IN_BODY)], &mut probe);
|
||||
}
|
||||
windows.app_modal(modal);
|
||||
frame(vec![], &mut probe);
|
||||
probe.reached = false;
|
||||
frame(vec![press(IN_BODY)], &mut probe);
|
||||
frame(vec![release(IN_BODY)], &mut probe);
|
||||
frame(vec![key_press(Key::A, Modifiers::NONE)], &mut probe);
|
||||
assert_eq!(probe.reached, modal.is_none(), "app modal in {modal:?}: a press or key reached the floating window");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
//! A dock's floating windows stack with the app's own egui windows in egui's area order: the window shown or pressed
|
||||
//! last is on top, so a dialog the app opens over a floating panel shows above it.
|
||||
|
||||
use super::Numbered;
|
||||
use craft_behavior::dock::{Floating, Layout, Node, Workspace};
|
||||
use craft_ui::contract::{Bind, BodyCx, Tracked};
|
||||
use craft_ui::docking::{DockConfig, DockPanels};
|
||||
use craft_ui::patterns::dock::DockArea;
|
||||
use craft_ui::testing::pointer::{moved, press, release};
|
||||
use craft_ui::testing::{Fixture, trial};
|
||||
use egui::{Pos2, Rect, Ui, Vec2};
|
||||
use std::cell::Cell;
|
||||
use std::rc::Rc;
|
||||
use std::sync::Arc;
|
||||
|
||||
const WINDOW_AT: Rect = Rect { min: Pos2::new(130.0, 90.0), max: Pos2::new(330.0, 210.0) };
|
||||
/// The app's dialog: it covers the floating window's right part.
|
||||
const DIALOG_AT: Pos2 = Pos2::new(220.0, 120.0);
|
||||
/// Inside both the floating window and the dialog.
|
||||
const BOTH: Pos2 = Pos2::new(260.0, 170.0);
|
||||
/// Inside the floating window only.
|
||||
const WINDOW_ONLY: Pos2 = Pos2::new(160.0, 190.0);
|
||||
|
||||
struct Panels;
|
||||
|
||||
impl DockPanels<usize> for Panels {
|
||||
fn body(&mut self, _: &usize, _: &mut Ui, _: &mut BodyCx<'_>) {}
|
||||
}
|
||||
|
||||
#[trial]
|
||||
fn an_app_dialog_opened_over_a_floating_window_shows_above_it_until_the_window_is_pressed() {
|
||||
let layout = Layout::new(Some(Node::tabs(vec![1], 0)), vec![Floating::single(100, vec![2], 0, WINDOW_AT)]);
|
||||
let mut workspace = Arc::new(Workspace::new(layout));
|
||||
let dialog = Rc::new(Cell::new(false));
|
||||
let shows = Rc::clone(&dialog);
|
||||
let specs = Tracked::new(Numbered);
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
DockArea::new("Dock", Bind::bound(&mut workspace), &specs, &mut Panels, DockConfig::default()).show(ui);
|
||||
if shows.get() {
|
||||
egui::Window::new("App dialog").fixed_pos(DIALOG_AT).fixed_size(Vec2::new(300.0, 200.0)).collapsible(false).show(ui.ctx(), |ui| {
|
||||
ui.label("Dialog");
|
||||
});
|
||||
}
|
||||
});
|
||||
fixture.room(Vec2::new(800.0, 600.0)).settle();
|
||||
let float = fixture.ctx().layer_id_at(BOTH).expect("the floating window shows");
|
||||
dialog.set(true);
|
||||
fixture.settle();
|
||||
let top = fixture.ctx().layer_id_at(BOTH).expect("a layer shows there");
|
||||
assert_ne!(top, float, "the dialog the app opened last is above the floating window");
|
||||
assert_eq!(fixture.ctx().layer_id_at(WINDOW_ONLY), Some(float), "the floating window still shows beside the dialog");
|
||||
fixture.frame(vec![moved(WINDOW_ONLY)]).frame(vec![press(WINDOW_ONLY)]).frame(vec![release(WINDOW_ONLY)]).settle();
|
||||
assert_eq!(fixture.ctx().layer_id_at(BOTH), Some(float), "a press raises the floating window above the dialog");
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
//! The host's focus request: `DockArea::focus` moves key focus to the group that shows a panel, as a click on its tab
|
||||
//! does.
|
||||
//! The host's focus request: `DockArea::focus` moves key focus to the group that shows a panel, as a press on the group's
|
||||
//! body does.
|
||||
|
||||
use super::Numbered;
|
||||
use craft_behavior::dock::{Action, Column, Floating, Group, Layout, Node, SplitSize, Workspace};
|
||||
@@ -51,19 +51,23 @@ fn two_groups(config: DockConfig) -> TwoGroups {
|
||||
(fixture, request, seen)
|
||||
}
|
||||
|
||||
/// With the user's focus on group A's tabs, the host's request for panel 2 of group B moves key focus to B's stop (the
|
||||
/// one a click on B's tabs focuses) and picks 2's tab; a key there reaches B. Guards against a request that picked the
|
||||
/// tab but left key focus, and so the keys, on the tabs the user clicked last.
|
||||
/// With the user's focus on group A, the host's request for panel 2 of group B moves key focus to B's stop (the one a
|
||||
/// press on B's body focuses) and picks 2's tab; a key there reaches B. Guards against a request that picked the tab
|
||||
/// but left key focus, and so the keys, in the group the user pressed last.
|
||||
#[trial]
|
||||
fn the_hosts_focus_request_moves_key_focus_to_the_panels_group_and_picks_its_tab() {
|
||||
let (mut fixture, request, seen) = two_groups(DockConfig::default());
|
||||
let tab = |fixture: &Fixture, name: &str| fixture.by_label(name).expect("a group's tab");
|
||||
let b_tab = tab(&fixture, "Panel 1");
|
||||
fixture.click(&b_tab).idle(1);
|
||||
let b_stop = fixture.focused_stop().expect("a click on B's tab focuses B's stop");
|
||||
let a_tab = tab(&fixture, "Panel 0");
|
||||
fixture.click(&a_tab).idle(1);
|
||||
assert_ne!(fixture.focused_stop(), Some(b_stop), "a click on A's tab moves focus to A's stop");
|
||||
// A point in the empty body below a group's tab.
|
||||
let body = |fixture: &Fixture, name: &str| {
|
||||
let tab = fixture.by_label(name).expect("a group's tab").rect;
|
||||
Pos2::new(tab.center().x, tab.bottom() + 200.0)
|
||||
};
|
||||
let b_body = body(&fixture, "Panel 1");
|
||||
fixture.click_at(b_body).idle(1);
|
||||
let b_stop = fixture.focused_stop().expect("a press on B's body focuses B's stop");
|
||||
let a_body = body(&fixture, "Panel 0");
|
||||
fixture.click_at(a_body).idle(1);
|
||||
assert_ne!(fixture.focused_stop(), Some(b_stop), "a press on A's body moves focus to A's stop");
|
||||
assert_eq!(seen.borrow().last().and_then(|seen| seen.focused), Some(0), "A holds the focus");
|
||||
seen.borrow_mut().clear();
|
||||
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
//! A panel whose body is the app's own egui code (`PanelSpec::host_body`) lays out with the style of the `Ui` the dock
|
||||
//! was shown in, on that style's panel fill and without the group's body padding; any other body keeps the group's
|
||||
//! spacing, padding and surface.
|
||||
|
||||
use craft_behavior::Axis;
|
||||
use craft_behavior::dock::{Layout, Node, SplitSize, Workspace};
|
||||
use craft_ui::contract::{Bind, BodyCx, PlainData, Tracked};
|
||||
use craft_ui::docking::{DockConfig, DockPanels, PanelSpec, PanelSpecs};
|
||||
use craft_ui::patterns::dock::DockArea;
|
||||
use craft_ui::testing::{Fixture, trial};
|
||||
use egui::{Color32, Rect, Shape, Ui, Vec2};
|
||||
use std::cell::RefCell;
|
||||
use std::rc::Rc;
|
||||
use std::sync::Arc;
|
||||
|
||||
/// The app's own egui panel; the other is a plain panel.
|
||||
const HOSTED: usize = 0;
|
||||
|
||||
#[derive(PlainData)]
|
||||
struct Specs;
|
||||
|
||||
impl PanelSpecs<usize> for Specs {
|
||||
fn spec(&self, panel: &usize) -> PanelSpec {
|
||||
let spec = PanelSpec::new(format!("Panel {panel}"));
|
||||
if *panel == HOSTED { spec.host_body() } else { spec }
|
||||
}
|
||||
}
|
||||
|
||||
/// The app's panel fill, which no theme surface has.
|
||||
const APP_FILL: Color32 = Color32::from_rgb(3, 140, 7);
|
||||
|
||||
/// What a body's `Ui` had: its item spacing and its room.
|
||||
type Seen = Option<(Vec2, Rect)>;
|
||||
|
||||
/// Records what each body's `Ui` had, by panel.
|
||||
struct Panels {
|
||||
seen: Rc<RefCell<[Seen; 2]>>,
|
||||
}
|
||||
|
||||
impl DockPanels<usize> for Panels {
|
||||
fn body(&mut self, panel: &usize, ui: &mut Ui, _: &mut BodyCx<'_>) {
|
||||
self.seen.borrow_mut()[*panel] = Some((ui.spacing().item_spacing, ui.max_rect()));
|
||||
}
|
||||
}
|
||||
|
||||
#[trial]
|
||||
fn a_host_body_lays_out_with_the_style_outside_the_dock_and_other_bodies_keep_the_groups() {
|
||||
let seen = Rc::new(RefCell::new([None; 2]));
|
||||
let outside = Rc::new(RefCell::new(None));
|
||||
let root = Node::split(Axis::X, SplitSize::Ratio(0.5), Node::tabs(vec![0], 0), Node::tabs(vec![1], 0));
|
||||
let mut workspace = Arc::new(Workspace::new(Layout::new(Some(root), Vec::new())));
|
||||
let (mut panels, specs) = (Panels { seen: seen.clone() }, Tracked::new(Specs));
|
||||
let outer = outside.clone();
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
ui.visuals_mut().panel_fill = APP_FILL;
|
||||
*outer.borrow_mut() = Some(ui.spacing().item_spacing);
|
||||
DockArea::new("Dock", Bind::bound(&mut workspace), &specs, &mut panels, DockConfig::default()).show(ui);
|
||||
});
|
||||
fixture.room(Vec2::new(1200.0, 600.0)).settle();
|
||||
fixture.record_paint().frame(Vec::new());
|
||||
let outside = outside.borrow().expect("the dock was shown");
|
||||
let [hosted, plain] = *seen.borrow();
|
||||
let (hosted, hosted_room) = hosted.expect("the hosted body was shown");
|
||||
let (plain, plain_room) = plain.expect("the plain body was shown");
|
||||
assert_eq!(hosted, outside, "the app's own egui body lays out as it does outside the dock");
|
||||
assert_ne!(plain, outside, "a framework body keeps the group's spacing");
|
||||
assert!(hosted_room.width() > plain_room.width(), "the app's body has the group's whole width, a framework body its padding less");
|
||||
|
||||
let mut paint = fixture.take_paint().expect("the frame recorded its paint");
|
||||
paint.textures_delta.clear();
|
||||
let filled = |room: Rect| {
|
||||
paint.shapes.iter().any(|clipped| matches!(&clipped.shape, Shape::Rect(rect) if rect.fill == APP_FILL && rect.rect.contains(room.center())))
|
||||
};
|
||||
assert!(filled(hosted_room), "the app's body shows on the app's panel fill");
|
||||
assert!(!filled(plain_room), "a framework body keeps the theme's surface");
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
//! An app that hosts its own egui UI in the dock: its canvas is a group the host draws (`group_view`) and the window's
|
||||
//! key target, and its other panels are its own egui code (`PanelSpec::host_body`). Keys its shortcut table reads reach
|
||||
//! egui's input.
|
||||
|
||||
use craft_behavior::Axis;
|
||||
use craft_behavior::dock::{Layout, Node, SplitSize, Workspace};
|
||||
use craft_keymap::{Chord, Key as KeyChord, Mods, Overrides};
|
||||
use craft_ui::contract::{Bind, BodyCx, PlainData, Tracked};
|
||||
use craft_ui::docking::{DockConfig, DockPanels, GroupAt, PanelSpec, PanelSpecs};
|
||||
use craft_ui::patterns::dock::DockArea;
|
||||
use craft_ui::runtime::commands::{CommandSet as _, NavCommand};
|
||||
use craft_ui::runtime::focus::{EditSet, KeepKeys, KeyUse, host_canvas};
|
||||
use craft_ui::testing::input::{key_press, key_reached};
|
||||
use craft_ui::testing::{Fixture, trial};
|
||||
use egui::{Id, Key, Modifiers, Sense, Ui, Vec2};
|
||||
use std::cell::Cell;
|
||||
use std::rc::Rc;
|
||||
use std::sync::Arc;
|
||||
|
||||
/// Panel 0 is the app's canvas; panels 1 and 2 are its own egui panels.
|
||||
const CANVAS: usize = 0;
|
||||
|
||||
/// The Alt+digit chords the canvas claims.
|
||||
const CLAIMS: [Chord; 2] = [Chord::new(Mods::ALT, KeyChord::Num1), Chord::new(Mods::ALT, KeyChord::Num2)];
|
||||
|
||||
/// The canvas's keys: Tab, the edit chords and its Alt+digit claims stay in egui's input for the app.
|
||||
const KEYS: KeyUse = KeyUse::CANVAS.with_keep(KeepKeys::Tab).with_edits(EditSet::ALL).with_claims(&CLAIMS);
|
||||
|
||||
#[derive(PlainData)]
|
||||
struct Specs;
|
||||
|
||||
impl PanelSpecs<usize> for Specs {
|
||||
fn spec(&self, panel: &usize) -> PanelSpec {
|
||||
let spec = PanelSpec::new(format!("Panel {panel}")).host_body();
|
||||
if *panel == CANVAS { spec.canvas() } else { spec }
|
||||
}
|
||||
}
|
||||
|
||||
/// The app's panels; `f6` records whether an F6 press reached egui's input in a pass the canvas ran in.
|
||||
struct Panels {
|
||||
f6: Rc<Cell<bool>>,
|
||||
}
|
||||
|
||||
impl DockPanels<usize> for Panels {
|
||||
fn body(&mut self, _: &usize, ui: &mut Ui, _: &mut BodyCx<'_>) {
|
||||
ui.label("rows");
|
||||
}
|
||||
|
||||
fn group_view(&mut self, panels: &[usize], _: usize, ui: &mut Ui, at: GroupAt, _: &mut BodyCx<'_>) -> Option<f32> {
|
||||
if !panels.contains(&CANVAS) {
|
||||
return None;
|
||||
}
|
||||
let GroupAt::Show(rect) = at else { return Some(0.0) };
|
||||
let id = Id::unique("app canvas");
|
||||
ui.interact(rect, id, Sense::click_and_drag());
|
||||
host_canvas(ui.ctx(), id, KEYS);
|
||||
if key_reached(ui.ctx(), Key::F6) {
|
||||
self.f6.set(true);
|
||||
}
|
||||
Some(rect.height())
|
||||
}
|
||||
}
|
||||
|
||||
/// With both pane moves unbound, F6 reaches the app's canvas in a dock of `host_body` panels.
|
||||
#[trial]
|
||||
fn an_unbound_f6_reaches_a_hosted_canvas_in_the_dock() {
|
||||
let f6 = Rc::new(Cell::new(false));
|
||||
let root = Node::split(
|
||||
Axis::X,
|
||||
SplitSize::Ratio(0.25),
|
||||
Node::tabs(vec![1], 0),
|
||||
Node::split(Axis::X, SplitSize::Ratio(0.7), Node::tabs(vec![CANVAS], 0), Node::tabs(vec![2], 0)),
|
||||
);
|
||||
let mut workspace = Arc::new(Workspace::new(Layout::new(Some(root), Vec::new())));
|
||||
let (mut panels, specs) = (Panels { f6: f6.clone() }, Tracked::new(Specs));
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
DockArea::new("Dock", Bind::bound(&mut workspace), &specs, &mut panels, DockConfig::default()).show(ui);
|
||||
});
|
||||
let mut unbound = Overrides::default();
|
||||
unbound.insert(NavCommand::NextPane.id(), Vec::new());
|
||||
unbound.insert(NavCommand::PreviousPane.id(), Vec::new());
|
||||
fixture.overrides(Arc::new(unbound)).room(Vec2::new(1200.0, 600.0)).settle();
|
||||
f6.set(false);
|
||||
fixture.frame(vec![key_press(Key::F6, Modifiers::NONE)]);
|
||||
assert!(f6.get(), "the app reads F6 from egui");
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
//! The app's own egui code in a dock (`PanelSpec::host_body`: a panel's body, or the view it takes its group with) runs
|
||||
//! once per pass, in the real run: a measuring run takes the size its last real run took. egui then sees each of the
|
||||
//! app's widgets once per pass, so it reports no id clash.
|
||||
|
||||
use craft_behavior::Axis;
|
||||
use craft_behavior::dock::{Layout, Node, SplitSize, Workspace};
|
||||
use craft_ui::contract::{Bind, BodyCx, PlainData, Tracked};
|
||||
use craft_ui::docking::{DockConfig, DockPanels, GroupAt, PanelSpec, PanelSpecs};
|
||||
use craft_ui::patterns::dock::DockArea;
|
||||
use craft_ui::runtime::measure;
|
||||
use craft_ui::testing::{Fixture, trial};
|
||||
use egui::{Id, Sense, Shape, Ui, Vec2};
|
||||
use std::cell::RefCell;
|
||||
use std::rc::Rc;
|
||||
use std::sync::Arc;
|
||||
|
||||
/// The app's egui panel, its canvas (a view that takes its group) and a framework panel.
|
||||
const HOSTED: usize = 0;
|
||||
const CANVAS: usize = 1;
|
||||
|
||||
#[derive(PlainData)]
|
||||
struct Specs;
|
||||
|
||||
impl PanelSpecs<usize> for Specs {
|
||||
fn spec(&self, panel: &usize) -> PanelSpec {
|
||||
let spec = PanelSpec::new(format!("Panel {panel}"));
|
||||
match *panel {
|
||||
HOSTED => spec.host_body(),
|
||||
CANVAS => spec.canvas().host_body(),
|
||||
_ => spec,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One run of the app's code: what ran, in which pass, and whether a measuring run was open.
|
||||
type Ran = (&'static str, u64, bool);
|
||||
|
||||
struct Panels {
|
||||
runs: Rc<RefCell<Vec<Ran>>>,
|
||||
}
|
||||
|
||||
impl DockPanels<usize> for Panels {
|
||||
fn body(&mut self, panel: &usize, ui: &mut Ui, _: &mut BodyCx<'_>) {
|
||||
if *panel != HOSTED {
|
||||
return;
|
||||
}
|
||||
self.runs.borrow_mut().push(("body", ui.ctx().cumulative_pass_nr(), measure::active(ui.ctx())));
|
||||
let _ = ui.button("Apply");
|
||||
egui::CollapsingHeader::new("Section").default_open(true).show(ui, |ui| {
|
||||
let _ = ui.button("Inside");
|
||||
});
|
||||
}
|
||||
|
||||
fn group_view(&mut self, panels: &[usize], _: usize, ui: &mut Ui, at: GroupAt, _: &mut BodyCx<'_>) -> Option<f32> {
|
||||
let GroupAt::Show(rect) = at else { return None };
|
||||
if !panels.contains(&CANVAS) {
|
||||
return None;
|
||||
}
|
||||
self.runs.borrow_mut().push(("view", ui.ctx().cumulative_pass_nr(), measure::active(ui.ctx())));
|
||||
let _ = ui.interact(rect, Id::unique("host canvas"), Sense::click_and_drag());
|
||||
Some(rect.height())
|
||||
}
|
||||
}
|
||||
|
||||
#[trial]
|
||||
fn the_apps_egui_code_in_a_dock_runs_once_per_pass_and_raises_no_id_clash() {
|
||||
let runs = Rc::new(RefCell::new(Vec::new()));
|
||||
let left = Node::split(Axis::Y, SplitSize::Ratio(0.5), Node::tabs(vec![HOSTED], 0), Node::tabs(vec![2], 0));
|
||||
let root = Node::split(Axis::X, SplitSize::Ratio(0.3), left, Node::tabs(vec![CANVAS], 0));
|
||||
let mut workspace = Arc::new(Workspace::new(Layout::new(Some(root), Vec::new())));
|
||||
let (mut panels, specs) = (Panels { runs: runs.clone() }, Tracked::new(Specs));
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
ui.ctx().options_mut(|options| options.warn_on_id_clash = true);
|
||||
DockArea::new("Dock", Bind::bound(&mut workspace), &specs, &mut panels, DockConfig::default()).show(ui);
|
||||
});
|
||||
// From the first frame on, through a new room, so the dock measures its groups again.
|
||||
fixture.room(Vec2::new(1200.0, 600.0)).settle();
|
||||
fixture.room(Vec2::new(1000.0, 700.0)).settle();
|
||||
fixture.record_paint().frame(Vec::new());
|
||||
|
||||
let runs = runs.borrow().clone();
|
||||
for part in ["body", "view"] {
|
||||
let ran: Vec<_> = runs.iter().filter(|(name, ..)| *name == part).collect();
|
||||
assert!(!ran.is_empty(), "the app's {part} ran");
|
||||
assert!(ran.iter().all(|(.., measuring)| !measuring), "the app's {part} ran in a measuring run: {ran:?}");
|
||||
let mut passes: Vec<_> = ran.iter().map(|(_, pass, _)| *pass).collect();
|
||||
passes.dedup();
|
||||
assert_eq!(passes.len(), ran.len(), "the app's {part} ran more than once in a pass: {ran:?}");
|
||||
}
|
||||
let paint = fixture.take_paint().expect("the frame recorded its paint");
|
||||
let clashes: Vec<String> = paint
|
||||
.shapes
|
||||
.iter()
|
||||
.filter_map(|clipped| match &clipped.shape {
|
||||
Shape::Text(text) if text.galley.job.text.contains("use of widget ID") => Some(text.galley.job.text.clone()),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
assert!(clashes.is_empty(), "egui reported id clashes: {clashes:?}");
|
||||
}
|
||||
@@ -16,15 +16,21 @@ pub(crate) mod drop;
|
||||
pub(crate) mod drop_preview;
|
||||
pub(crate) mod drop_session;
|
||||
|
||||
pub(crate) mod float_order;
|
||||
pub(crate) mod floating;
|
||||
pub(crate) mod floating_area;
|
||||
pub(crate) mod floating_rail;
|
||||
pub(crate) mod hidden;
|
||||
pub(crate) mod sources;
|
||||
|
||||
pub(crate) mod app_modal;
|
||||
pub(crate) mod columns;
|
||||
pub(crate) mod dock_back;
|
||||
pub(crate) mod group_view;
|
||||
pub(crate) mod host_body;
|
||||
pub(crate) mod host_keys;
|
||||
pub(crate) mod host_runs;
|
||||
pub(crate) mod tab_focus;
|
||||
pub(crate) mod workspace_dialogs;
|
||||
|
||||
pub(crate) mod native;
|
||||
|
||||
@@ -79,8 +79,9 @@ fn a_panel_menu_command_reaches_the_group_whose_button_opened_it() {
|
||||
*held.borrow_mut() = shown;
|
||||
});
|
||||
fixture.room(Vec2::new(1200.0, 600.0)).settle();
|
||||
let first = fixture.by_label("Panel 0").expect("the first group's tab");
|
||||
fixture.click(&first).idle(1);
|
||||
// Tab from nothing focuses the first group's tabs; a click on a tab leaves focus where it is.
|
||||
fixture.key(Key::Tab, Modifiers::NONE).idle(1);
|
||||
assert!(fixture.focused_stop().is_some(), "Tab focused the first group's tabs");
|
||||
let buttons: Vec<_> =
|
||||
fixture.by_role(Role::BUTTON).into_iter().filter(|button| fixture.tree().name_of(button.node) == Some("Panel Menu")).collect();
|
||||
assert_eq!(buttons.len(), 2, "each group shows its panel menu button");
|
||||
@@ -103,8 +104,9 @@ fn tab_reaches_the_tabs_then_the_drag_band_then_the_panel_menu_button() {
|
||||
DockArea::new("Dock", Bind::bound(&mut workspace), &specs, &mut Panels, DockConfig::default()).show(ui);
|
||||
});
|
||||
fixture.room(Vec2::new(800.0, 600.0)).settle();
|
||||
let tab = fixture.by_label("Panel 0").expect("the group's tab");
|
||||
fixture.click(&tab).idle(1);
|
||||
// Tab from nothing reaches the tabs first.
|
||||
fixture.key(Key::Tab, Modifiers::NONE).idle(1);
|
||||
assert!(fixture.focused_stop().is_some(), "Tab focused the tabs");
|
||||
let mut parts = Vec::new();
|
||||
for _ in 0..2 {
|
||||
fixture.key(Key::Tab, Modifiers::NONE).idle(1);
|
||||
|
||||
@@ -527,6 +527,14 @@ fn a_tab_picked_in_the_focused_group_is_the_focused_panel() {
|
||||
seen.borrow_mut().push((output.focused, output.picked));
|
||||
});
|
||||
fixture.room(Vec2::new(1200.0, 600.0)).settle().idle(1);
|
||||
// A click on a tab leaves key focus where it is: Tab moves it into the first group, whose shown panel is panel 0.
|
||||
for _ in 0..4 {
|
||||
if reported.borrow().last() == Some(&(Some(0), None)) {
|
||||
break;
|
||||
}
|
||||
fixture.key(egui::Key::Tab, egui::Modifiers::NONE).idle(1);
|
||||
}
|
||||
assert_eq!(reported.borrow().last(), Some(&(Some(0), None)), "Tab reaches the first group");
|
||||
let tab = |fixture: &Fixture, name: &str| fixture.by_label(name).expect("the first group's tab");
|
||||
let second = tab(&fixture, "Panel 1");
|
||||
fixture.click(&second).idle(3);
|
||||
|
||||
@@ -125,11 +125,13 @@ fn a_dock_area_reports_one_source_per_tab_bar_grip_and_divider_it_drew_and_the_s
|
||||
assert_eq!(*reported.borrow(), sources, "an idle pass, which replays the settled parts, reports the same sources");
|
||||
|
||||
let left_two = sources.iter().find(|source| source.kind == SourceKind::Tab(LEFT_TWO)).cloned().expect("the tab of the second panel");
|
||||
// A click on the tab picks it and leaves key focus; a press on the group's empty body then focuses its strip.
|
||||
fixture.click_at(left_two.rect.center()).settle();
|
||||
fixture.click_at(Pos2::new(left_two.rect.center().x, left_two.rect.bottom() + 60.0)).settle();
|
||||
assert_eq!(
|
||||
craft_ui::runtime::access::focused_node(fixture.ctx()),
|
||||
Some(left_two.id),
|
||||
"the clicked tab holds focus under the id its source reports"
|
||||
"the picked tab holds focus under the id its source reports"
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
//! A pointer press on a dock's panel tab leaves key focus where it was, so a hosted app's own shortcuts keep working
|
||||
//! after a tab click, a tab drag or the tab menu; a press on an app's own egui body is the app's.
|
||||
|
||||
use craft_behavior::Axis;
|
||||
use craft_behavior::dock::{Layout, Node, SplitSize, Workspace};
|
||||
use craft_ui::contract::{Bind, BodyCx, PlainData, Tracked};
|
||||
use craft_ui::docking::{DockConfig, DockPanels, PanelSpec, PanelSpecs};
|
||||
use craft_ui::patterns::dock::DockArea;
|
||||
use craft_ui::testing::pointer::moved;
|
||||
use craft_ui::testing::{Fixture, trial};
|
||||
use egui::{Event, Key, Modifiers, PointerButton, Pos2, Ui, Vec2};
|
||||
use std::cell::RefCell;
|
||||
use std::rc::Rc;
|
||||
use std::sync::Arc;
|
||||
|
||||
/// Panel 2's body is the app's own egui code; panels 0 and 1 are plain panels in the other group.
|
||||
const HOSTED: usize = 2;
|
||||
|
||||
#[derive(PlainData)]
|
||||
struct Specs;
|
||||
|
||||
impl PanelSpecs<usize> for Specs {
|
||||
fn spec(&self, panel: &usize) -> PanelSpec {
|
||||
let spec = PanelSpec::new(format!("Panel {panel}"));
|
||||
if *panel == HOSTED { spec.host_body() } else { spec }
|
||||
}
|
||||
}
|
||||
|
||||
struct Panels;
|
||||
|
||||
impl DockPanels<usize> for Panels {
|
||||
fn body(&mut self, _: &usize, _: &mut Ui, _: &mut BodyCx<'_>) {}
|
||||
}
|
||||
|
||||
/// A dock of the plain group [0, 1] beside the hosted group [2], and the workspace it edits.
|
||||
fn dock() -> (Fixture, Rc<RefCell<Arc<Workspace<usize>>>>) {
|
||||
let root = Node::split(Axis::X, SplitSize::Ratio(0.5), Node::tabs(vec![0, 1], 0), Node::tabs(vec![HOSTED], 0));
|
||||
let workspace = Rc::new(RefCell::new(Arc::new(Workspace::new(Layout::new(Some(root), Vec::new())))));
|
||||
let (held, specs) = (Rc::clone(&workspace), Tracked::new(Specs));
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let mut shown = held.borrow().clone();
|
||||
DockArea::new("Dock", Bind::bound(&mut shown), &specs, &mut Panels, DockConfig::default()).show(ui);
|
||||
*held.borrow_mut() = shown;
|
||||
});
|
||||
fixture.room(Vec2::new(1200.0, 600.0)).settle();
|
||||
(fixture, workspace)
|
||||
}
|
||||
|
||||
/// A secondary press and release at `at`, then an idle frame.
|
||||
fn secondary_click(fixture: &mut Fixture, at: Pos2) {
|
||||
let button = |pressed| Event::PointerButton { pos: at, button: PointerButton::Secondary, pressed, modifiers: Modifiers::NONE };
|
||||
fixture.frame(vec![moved(at)]).frame(vec![button(true)]).frame(vec![button(false)]).idle(1);
|
||||
}
|
||||
|
||||
#[trial]
|
||||
fn a_press_on_a_panel_tab_leaves_key_focus_where_it_was() {
|
||||
let (mut fixture, workspace) = dock();
|
||||
let tab = fixture.by_label("Panel 1").expect("the first group's second tab");
|
||||
fixture.click(&tab).idle(1);
|
||||
let shows_one =
|
||||
matches!(workspace.borrow().layout().root.as_ref(), Some(Node::Split { first, .. }) if matches!(&**first, Node::Tabs { active: 1, .. }));
|
||||
assert!(shows_one, "the click shows panel 1");
|
||||
assert!(fixture.focused_stop().is_none(), "a click on a tab takes no key focus");
|
||||
|
||||
let tab = fixture.by_label("Panel 1").expect("the tab to drag");
|
||||
let hosted = fixture.by_label("Panel 2").expect("the hosted group's tab").rect;
|
||||
let by = Pos2::new(hosted.center().x, hosted.bottom() + 100.0) - tab.center();
|
||||
fixture.drag(&tab, by).idle(2);
|
||||
assert!(fixture.focused_stop().is_none(), "a tab drag takes no key focus");
|
||||
|
||||
let tab = fixture.by_label("Panel 0").expect("a tab for the menu");
|
||||
secondary_click(&mut fixture, tab.center());
|
||||
assert!(fixture.by_label("Float").is_some(), "the tab menu opened");
|
||||
fixture.key(Key::Escape, Modifiers::NONE).idle(2);
|
||||
assert!(fixture.by_label("Float").is_none(), "Escape closed the menu");
|
||||
assert!(fixture.focused_stop().is_none(), "with the tab menu closed, no key focus is left behind");
|
||||
}
|
||||
|
||||
#[trial]
|
||||
fn a_press_on_an_app_body_is_the_apps_and_one_on_a_plain_body_focuses_its_panel() {
|
||||
let (mut fixture, _) = dock();
|
||||
let hosted = fixture.by_label("Panel 2").expect("the hosted group's tab").rect;
|
||||
fixture.click_at(Pos2::new(hosted.center().x, hosted.bottom() + 200.0)).idle(1);
|
||||
assert!(fixture.focused_stop().is_none(), "a press on the app's own body takes no framework focus");
|
||||
let plain = fixture.by_label("Panel 0").expect("the plain group's tab").rect;
|
||||
fixture.click_at(Pos2::new(plain.center().x, plain.bottom() + 200.0)).idle(1);
|
||||
assert!(fixture.focused_stop().is_some(), "a press on a framework panel's empty body focuses its panel");
|
||||
}
|
||||
@@ -281,6 +281,7 @@ pub struct Windows {
|
||||
pub ctx: Context,
|
||||
root_info: RefCell<ViewportInfo>,
|
||||
root: RefCell<RootEnv>,
|
||||
app_modal: Cell<Option<ViewportId>>,
|
||||
window_input: Cell<WindowInput>,
|
||||
}
|
||||
|
||||
@@ -314,6 +315,7 @@ impl Windows {
|
||||
ctx,
|
||||
root_info: RefCell::new(ViewportInfo::default()),
|
||||
root: RefCell::new(RootEnv::default()),
|
||||
app_modal: Cell::new(None),
|
||||
window_input: Cell::new(WindowInput::Live),
|
||||
}
|
||||
}
|
||||
@@ -329,6 +331,11 @@ impl Windows {
|
||||
with_facts(viewport, |info| info.clone())
|
||||
}
|
||||
|
||||
/// The window in which the app's own egui code shows a modal (`FrameInput::app_modal`), from the next frame on.
|
||||
pub fn app_modal(&self, viewport: Option<ViewportId>) {
|
||||
self.app_modal.set(viewport);
|
||||
}
|
||||
|
||||
/// The window-input policy every following frame's input gives, as a host's `FrameInput::window_input` does.
|
||||
pub fn window_input(&self, policy: WindowInput) {
|
||||
self.window_input.set(policy);
|
||||
@@ -371,7 +378,7 @@ impl Windows {
|
||||
CHILD_FILES.with(|files| *files.borrow_mut() = child_files);
|
||||
TREES.with(|kept| kept.borrow_mut().clear());
|
||||
SHAPES.with(|kept| kept.borrow_mut().clear());
|
||||
set_input(&self.ctx, FrameInput::new(self.root.borrow().clone()).window_input(self.window_input.get()));
|
||||
set_input(&self.ctx, FrameInput::new(self.root.borrow().clone()).app_modal(self.app_modal.get()).window_input(self.window_input.get()));
|
||||
let mut input = RawInput {
|
||||
screen_rect: Some(Rect::from_min_size(Pos2::ZERO, ROOT_SIZE)),
|
||||
events: root,
|
||||
|
||||
@@ -627,6 +627,14 @@ impl<'a, K: Clone + Eq + Hash + Send + Sync + std::fmt::Debug + 'static> TabStri
|
||||
.label(label)
|
||||
}
|
||||
|
||||
/// A pointer press on a tab (primary or secondary, a drag's press too) leaves key focus where it is; the keyboard
|
||||
/// still reaches the strip by Tab. A dock's panel tabs: clicking one leaves the document's keys working.
|
||||
#[must_use]
|
||||
pub fn keeps_focus(mut self) -> Self {
|
||||
self.items = self.items.focus_on_press(false);
|
||||
self
|
||||
}
|
||||
|
||||
/// A tab drag carries `map` of it, for the drop targets of type `P`; a tab the map gives `None` for does not drag
|
||||
/// unless a reorder rule is set. The drag stays one session with one ghost.
|
||||
#[must_use]
|
||||
|
||||
@@ -30,9 +30,9 @@ egui = { workspace = true, optional = true }
|
||||
craft-ui = { workspace = true, optional = true }
|
||||
# `Tone` for the dialogs' notices.
|
||||
craft-theme = { workspace = true, optional = true }
|
||||
# `Host::app`: the name the update dialogs show.
|
||||
# `Host::app` and `Host::icon_png`: the name and icon the update dialogs show.
|
||||
craft-host = { workspace = true, features = ["ui"], optional = true }
|
||||
# Decodes the app icon the update dialogs show (`App::icon_png`); PNG only.
|
||||
# Decodes the app icon the update dialogs show (`Host::icon_png`); PNG only.
|
||||
image = { version = "0.25", default-features = false, features = ["png"], optional = true }
|
||||
serde = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! The update dialogs on craft-ui's dialog host: [`UpdatePromptDialog`] (a release is available)
|
||||
//! and [`UpdateCheckDialog`] (the result of a manual check), on [`Dialog`], with the app's name from the
|
||||
//! host's `AppInfo` and the words from [`UpdateWords`].
|
||||
//! and [`UpdateCheckDialog`] (the result of a manual check), on [`Dialog`], with the app's name and icon from the
|
||||
//! host (`Host::app`, `Host::icon_png`) and the words from [`UpdateWords`].
|
||||
|
||||
use std::hash::{Hash as _, Hasher as _};
|
||||
use std::sync::{Arc, OnceLock};
|
||||
@@ -102,29 +102,36 @@ pub fn icon_image(png: &[u8]) -> Option<ColorImage> {
|
||||
/// The app's decoded icon, kept for the life of the dialog; `None` inside when it has none or it does not decode.
|
||||
type IconCell = OnceLock<Option<ColorImage>>;
|
||||
|
||||
/// The app the dialogs are for: the installed host's name and the suite entry that carries its icon and
|
||||
/// developer.
|
||||
/// The app the dialogs are for: the installed host's name and icon, and the suite entry that carries its developer.
|
||||
struct Subject {
|
||||
id: &'static str,
|
||||
name: &'static str,
|
||||
icon_png: Option<&'static [u8]>,
|
||||
app: Option<&'static App>,
|
||||
}
|
||||
|
||||
impl Subject {
|
||||
fn of(env: &Env) -> Self {
|
||||
let info = env.view().host().map(|host| host.app().clone());
|
||||
Self { name: info.as_ref().map_or("", |info| info.name), app: info.and_then(|info| App::by_id(info.id)) }
|
||||
let host = env.view().host();
|
||||
let info = host.map(|host| host.app().clone());
|
||||
Self {
|
||||
id: info.as_ref().map_or("", |info| info.id),
|
||||
name: info.as_ref().map_or("", |info| info.name),
|
||||
icon_png: host.and_then(|host| host.icon_png()),
|
||||
app: info.and_then(|info| App::by_id(info.id)),
|
||||
}
|
||||
}
|
||||
|
||||
/// The icon, the name, the developer and `version_line`, as the head of both dialogs. An app without a
|
||||
/// decodable icon shows its initial in the icon's place.
|
||||
fn head(&self, ui: &mut Ui, words: &UpdateWords, icon: &IconCell, version_line: &str) {
|
||||
let image = icon.get_or_init(|| self.app.and_then(|app| app.icon_png).and_then(icon_image)).as_ref();
|
||||
let image = icon.get_or_init(|| self.icon_png.and_then(icon_image)).as_ref();
|
||||
Row::new().show(ui, |ui, _| {
|
||||
match (image, self.app) {
|
||||
(Some(image), Some(app)) => {
|
||||
Picture::new("", icon_key(app), &|| image.clone()).extent(PictureSize::Icon).show(ui);
|
||||
match image {
|
||||
Some(image) => {
|
||||
Picture::new("", self.icon_key(), &|| image.clone()).extent(PictureSize::Icon).show(ui);
|
||||
}
|
||||
_ => {
|
||||
None => {
|
||||
Text::new(self.name.chars().next().map_or_else(|| "A".to_owned(), String::from)).show(ui);
|
||||
}
|
||||
}
|
||||
@@ -137,13 +144,13 @@ impl Subject {
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// The picture key of `app`'s icon.
|
||||
fn icon_key(app: &App) -> u64 {
|
||||
let mut hasher = std::hash::DefaultHasher::new();
|
||||
app.id.hash(&mut hasher);
|
||||
hasher.finish()
|
||||
/// The picture key of the app's icon.
|
||||
fn icon_key(&self) -> u64 {
|
||||
let mut hasher = std::hash::DefaultHasher::new();
|
||||
self.id.hash(&mut hasher);
|
||||
hasher.finish()
|
||||
}
|
||||
}
|
||||
|
||||
/// The spinner with the progress word, shown while an install runs.
|
||||
|
||||
@@ -21,12 +21,21 @@ fn newer() -> Release {
|
||||
Release { tag: "v9.0.0".into(), version: craft_update::parse_version("9.0.0"), ..Release::default() }
|
||||
}
|
||||
|
||||
fn photocraft() -> craft_host::HostBuilder {
|
||||
Host::builder(AppInfo { id: "photocraft", name: "PhotoCraft", version: "1.0" })
|
||||
}
|
||||
|
||||
/// A fixture running `dialogs` every pass for an app named PhotoCraft.
|
||||
fn rig(dialogs: DialogHost) -> (Fixture, Dialogs) {
|
||||
rig_for(dialogs, photocraft().build())
|
||||
}
|
||||
|
||||
/// A fixture running `dialogs` every pass for the app `host` names.
|
||||
fn rig_for(dialogs: DialogHost, host: Host) -> (Fixture, Dialogs) {
|
||||
let dialogs: Dialogs = Rc::new(RefCell::new(dialogs));
|
||||
let shown = dialogs.clone();
|
||||
let mut fixture = Fixture::new(move |ui| shown.borrow_mut().run(ui));
|
||||
fixture.host(Arc::new(Host::builder(AppInfo { id: "photocraft", name: "PhotoCraft", version: "1.0" }).build()));
|
||||
fixture.host(Arc::new(host));
|
||||
fixture.settle();
|
||||
(fixture, dialogs)
|
||||
}
|
||||
@@ -119,6 +128,42 @@ fn check_dialog_shows(status: Status, text: &str) -> bool {
|
||||
fixture.texts().iter().any(|t| t.text.contains(text)) || fixture.by_label(text).is_some()
|
||||
}
|
||||
|
||||
/// The check dialog's head for the app `host` names: how many textured shapes the dialog paints (the dialog's own
|
||||
/// chrome paints some), and whether it shows the app name's initial in the icon's place.
|
||||
fn check_dialog_head(host: Host) -> (usize, bool) {
|
||||
let mut dialog = UpdateCheckDialog::new("0.1.0");
|
||||
dialog.set_status(Status::UpToDate);
|
||||
let mut dialogs = DialogHost::new();
|
||||
dialogs.open(dialog);
|
||||
let (mut fixture, _) = rig_for(dialogs, host);
|
||||
let textured = fixture
|
||||
.frame_shapes()
|
||||
.iter()
|
||||
.filter(|shape| match shape {
|
||||
egui::Shape::Mesh(mesh) => mesh.texture_id != egui::TextureId::default(),
|
||||
egui::Shape::Rect(rect) => rect.brush.is_some(),
|
||||
_ => false,
|
||||
})
|
||||
.count();
|
||||
(textured, fixture.texts().iter().any(|t| t.text == "P"))
|
||||
}
|
||||
|
||||
/// The app gives its icon once, to its host beside its name, and the check dialog shows it in its head, which the
|
||||
/// prompt shares; an app without one shows its name's initial.
|
||||
#[trial]
|
||||
fn the_update_dialogs_show_the_icon_the_app_gives_its_host() {
|
||||
let mut png = Vec::new();
|
||||
image::RgbaImage::from_pixel(8, 8, image::Rgba([240, 122, 30, 255]))
|
||||
.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png)
|
||||
.unwrap_or_else(|error| panic!("the icon encodes: {error}"));
|
||||
let icon: &'static [u8] = Box::leak(png.into_boxed_slice());
|
||||
let (with_icon, initial_with_icon) = check_dialog_head(photocraft().icon_png(icon).build());
|
||||
let (without, initial_without) = check_dialog_head(photocraft().build());
|
||||
assert!(with_icon > without, "the icon paints a picture: {with_icon} textured shapes against {without}");
|
||||
assert!(!initial_with_icon, "the icon takes the initial's place");
|
||||
assert!(initial_without, "no icon: the initial");
|
||||
}
|
||||
|
||||
#[trial]
|
||||
fn the_check_dialog_words_a_rate_limit_itself_and_passes_other_reasons_through() {
|
||||
let words = UpdateWords::default();
|
||||
|
||||
@@ -152,18 +152,21 @@ An app with its own eframe `App` calls the hooks in `craft::ui::shell::embed`. `
|
||||
| What | Effect on the app's own egui code |
|
||||
| --- | --- |
|
||||
| Tab | Bare Tab moves framework focus and never reaches egui, unless the focused framework stop keeps Tab or an app's own widget has the focus (below), or nothing has the focus in a window that registered no focus stop: egui then moves its own focus into the app's widgets. A window with stops but no Tab entry (on the Mac, where Tab reaches only text fields by default) keeps the Tab from egui, which would otherwise focus framework controls the platform's rule skips. With `RootEnv::tab_toggles_chrome`, Tab toggles the chrome in a window that shows a document canvas, with nothing focused or the canvas focused, and arrives in `FrameOutput::chrome_toggles`. The canvas is a framework canvas, or the app's own egui canvas declared each pass with `ui::runtime::focus::host_canvas`. With nothing focused, the canvas is the key target: a canvas that keeps Tab (`KeyUse::CANVAS.with_keep(KeepKeys::Tab)`) gets the press in egui's input, as when it is focused, and nothing toggles. A focused canvas whose editor part keeps Tab reads Shift+Tab as `Intent::BackTab` (`EditorInput::BackTab`); no other stop gets it as an intent, and a text field keeps Shift+Tab as a focus move. |
|
||||
| F6 | F6 and Shift+F6 move between panes and never reach egui. They are the defaults of the commands `window.nextPane` and `window.previousPane` (`NavCommand`): a default chord that another command binds is that command's, and the overrides move or unbind them (`CommandInput::overrides`). An app whose own shortcut table keeps F6 unbinds them there. |
|
||||
| F6 | F6 and Shift+F6 move between panes and never reach egui. They are the defaults of the commands `NavCommand::NextPane` and `NavCommand::PreviousPane` (ids `window.next_pane` and `window.previous_pane`; name them by `NavCommand::NextPane.id()` in code): a default chord that another command binds is that command's, and the overrides move or unbind them (`CommandInput::overrides`). An app whose own shortcut table keeps F6 unbinds them there. |
|
||||
| Escape | Plain Escape (Alt and Shift may be held) goes to the focused framework stop and its scopes; with no framework stop focused, it goes to the window as `Intent::Cancel`. A held Escape cancels once: its repeats raise no `Cancel`. It reaches egui only while an app's own widget has the focus (below). An Escape the runtime takes outside a captured framework press also ends egui's own drag in that pass, as egui's Escape does. |
|
||||
| F10, Alt+letter | Taken while a framework menu bar is registered: F10 (`window.focusMenuBar`, bound and yielded as F6 is) focuses the bar, Alt+letter opens a menu (not on macOS) unless the keymap binds it to an enabled command, which runs instead. |
|
||||
| F10, Alt+letter | Taken while a framework menu bar is registered: F10 (`NavCommand::FocusMenuBar`, id `window.focus_menu_bar`, bound and yielded as F6 is) focuses the bar, Alt+letter opens a menu (not on macOS) unless the keymap binds it to an enabled command, which runs instead. |
|
||||
| Claimed chords | The chords the app's canvas claims (`KeyUse::CANVAS.with_claims(..)` in `host_canvas`) stay in egui's input for it while it has the focus and, with nothing focused, while it is the window's key target; no command fires with them. On Windows and Linux, Alt+numpad code entry takes every other Alt+digit (egui reports keypad and top-row digits alike), so an app's Alt+digit shortcut works only when its canvas claims the chord. |
|
||||
| Edit chords | Taken while a framework editor is focused. With nothing focused, the edit chords and egui's copy, cut and paste events of the commands in the window canvas's edit set (`KeyUse::edits`, `host_canvas`) stay in egui's input for it, and no command fires with them. Otherwise egui's copy, cut and paste events become the ⌘C/X/V chord for the app's commands, unless an app's own widget has the focus (below). While egui holds a label text selection, copy and cut stay egui's, and egui copies the selection. |
|
||||
| IME | Taken while a framework editor owns the IME: its events and `PlatformOutput.ime` are the runtime's. Otherwise they stay egui's, for the app's own `TextEdit` or IME code. |
|
||||
| An app's own focused widget | While egui focus is on a widget no framework component made, or an egui popup is open, and no framework press or drag is captured, Tab, Shift+Tab, Escape and egui's clipboard events stay in egui's input for it, and the runtime routes nothing for them. While egui focus is on such a widget, the arrows and Tab move egui focus among the app's widgets as egui does; while a framework stop has the focus, egui's arrow moves are off. |
|
||||
| Releases | The release of every key the runtime took is taken too. |
|
||||
| Focus surrender | The runtime moves its own focus on press (8.3): a press a framework component takes moves focus to it; a press no component takes drops the framework's focus. egui's click-away never takes the framework's focus. egui's surrender option (`InputOptions::surrender_focus_on`) stays the app's and governs the focus of the app's own widgets, as in egui alone: a press no component takes leaves that focus to egui's rule. |
|
||||
| Clicks | egui's click options (`InputOptions::max_click_dist`, `max_click_duration`) stay the app's, for its own widgets. A framework component clicks and drags by the framework's press lifecycle: a release within the slop (`HitSizes::slop`), whatever its duration. Read a component's click with `contract::clicked(&response)` or its output's `clicked()`; egui's `Response::clicked()` on a component's response also needs a click by egui's options. |
|
||||
| Zoom keys | egui's keyboard zoom is off. The interface scale is `RootEnv::scale`. |
|
||||
| Quit shortcuts | egui's quit shortcuts are cleared. Quit goes through the close path. |
|
||||
| Zoom keys | egui's keyboard zoom is off and nothing takes its place: the interface scale is `RootEnv::scale`, and an app whose ⌘= and ⌘- changed it binds them itself. |
|
||||
| Quit | egui's quit shortcuts are cleared. ⌘Q (Ctrl+Q on Windows and Linux) is the default of the command `QuitCommand::Quit` (id `window.quit`), which the runtime runs from any source: it asks the root window to close through the close path below, so the app's close decision asks about unsaved work. It fires with a modal open; the close path then refuses under an app-modal layer. Its default is bound and yielded as F6 is; an app whose own shortcut table reads its quit key from egui unbinds it there. |
|
||||
| Close path | The runtime's window host owns the root window's close request. `embed::logic` asks the app through its closure, then hands the close to the platform quit where there is one (macOS). |
|
||||
| Wheel | `RootEnv::wheel_speed` scales each wheel delta once; a Ctrl or Cmd wheel keeps the device's distance. The install's `WheelModifiers` set egui's zoom and sideways modifiers. On Windows and Linux, a Ctrl+wheel in fractions of a notch (a point-unit one on Linux) is a touchpad pinch and arrives as `Event::Zoom`, at egui's Ctrl-scroll zoom speed: Windows hands a precision touchpad's pinch to apps only that way. Whole notches stay wheel events, except within 0.25 s of a pinch step. An app whose Ctrl+wheel does something else, or zooms at its own rate, sets `RootEnv::ctrl_wheel_pinch(false)` and reads the wheel events itself. |
|
||||
| App modals | A modal the app draws with its own egui code blocks nothing outside egui by itself. While one shows, the app names its window each frame with `FrameInput::app_modal(Some(viewport))`: the app's other windows, panels floated into windows of their own among them, are then blocked as under a framework app-modal layer (their presses, keys, wheel and text are dropped, a press there brings the modal's window forward, and they refuse to close). |
|
||||
| Input pacing | One press per pass: extra presses in one frame wait for the next passes. A press outside an open framework menu closes the menu and goes no further. After an OS resize of the window, the held pointer is released. |
|
||||
|
||||
The window's keys are the ones the runtime routes to no component: an Escape or a plain Enter while no framework stop is focused, and the arrows' nudge. `with_window_intents` offers them to its closure while nothing has framework focus. The closure takes what it handles (`Intents::take(Intent::Cancel)`; `Intent` and the other types `Intents` reads are in `ui::runtime::keys`) and returns whether it took anything; the rest stays for later readers. A framework scope that ran earlier in the pass takes them first (an open dialog takes the Escape that closes it), so the app reads them last in its UI to see what no component took. App code that read `Key::Escape`, `Key::Tab`, F6 or F10 from egui while none of its own widgets had focus reads these intents and `FrameOutput::chrome_toggles` instead; its own focused widgets and popups keep reading Tab and Escape from egui.
|
||||
|
||||
+5
-1
@@ -56,7 +56,7 @@ The host keeps its panels' specs in a plain-data model that implements `PanelSpe
|
||||
|
||||
| Method | Does |
|
||||
| --- | --- |
|
||||
| `spec` | The panel's `PanelSpec`: label, icon, `SizeLimits`, `DockHeights`, float size, `allow_native`, `window_kind`, `canvas`, `grid`. |
|
||||
| `spec` | The panel's `PanelSpec`: label, icon, `SizeLimits`, `DockHeights`, float size, `allow_native`, `window_kind`, `canvas`, `grid`, `host_body`. |
|
||||
| `permissions` | The panel's `Permissions` (default `ALL`). |
|
||||
|
||||
The area reads them only when the model's revision, the workspace's revision or the lock changes (`runtime::derived`), and keeps what it read otherwise, so an idle pass reads no spec. A host changes a label or a limit by editing the model. A spec reads no style: a tool rail's grid is `DockGrid::rail(cells)`, which the dock sizes from its own tokens.
|
||||
@@ -70,6 +70,8 @@ The host implements `DockPanels<P>` for the views:
|
||||
| `group_header` | The host's controls in a group header, before the tab strip. |
|
||||
| `panel_rows` | The host's rows of a panel's menu, before the dock's own. |
|
||||
|
||||
A body lays out with the group's spacing, which framework components expect. A panel whose body is the app's own egui code sets `PanelSpec::host_body()`: the dock then hands its `body`, `footer`, `group_header`, `rail_footer` and, while it is the panel its group shows, its group's `group_view` a `Ui` with the style of the `Ui` the area was shown in, so that code lays out as it does outside the dock. Its body also keeps the app's background and room: the dock fills the body with that style's panel fill (`Visuals::panel_fill`) and gives it no body padding, and a press on the body is the app's, so it does not focus the group's tabs. That code runs once per pass, in the pass's real run: where the framework measures a group before it shows it, the code's parts take the size they took when they last ran, and egui sees each of the app's widgets once (`HostStyle::show`). The dock's own parts keep the framework style. An app hosting its old egui panels moves onto the framework panel by panel, clearing `host_body` on each panel it ports.
|
||||
|
||||
The binding decides who applies the edits. With `Bind::bound` the area writes every action to the workspace itself. With `Bind::given` it writes nothing, and the host applies `DockAreaOutput::actions` (or `edit`, the same changes as edit events) to its own copy: the actions hold every change of the pass, divider sizes and window moves included. `DockArea::read_only` shows a workspace locked, keyed by its revision.
|
||||
|
||||
A panel body, or code a body calls, changes the workspace during the pass with `docking::request_actions(ctx, actions)`, never by writing the workspace the area shows. The running area takes them unapplied and returns them in `DockAreaOutput::requested`, in order, for the host to apply after `actions` in the same frame. With no area over that panel type running, `request_actions` hands the actions back for the caller to apply.
|
||||
@@ -121,6 +123,8 @@ The theme's docking sizes (`DockSizes`) set the drop bands and zones. `DockWords
|
||||
- A floating window's id comes from a counter its layout owns (`Layout::fresh_window_id`). It starts above every id the layout is built or loaded with and only grows while the layout lives; `Workspace::replace` gives the incoming windows ids the replaced layout never gave out, and a dock area keeps the windows its actions add above every id it has shown, so a workspace an undo brings back draws no id twice (`Workspace::raise_window_floor`). An OS window never passes to another window.
|
||||
- A dock column's last open group fills the column: it takes the height the other groups leave and asks for its `DockHeights::fill`. The other groups keep the height the user gave them, or take their `DockHeights::default`, which shrinks towards `compact` before the filling group gets less than its fill. Groups that ask for no heights share the free height with the filling group.
|
||||
- Split handles are Tab stops, and the arrow keys move them. A divider drag is one gesture in `DockAreaOutput::edit`.
|
||||
- A pointer press on a panel tab (a click, a drag's press, the tab menu's secondary press) leaves key focus where it was, so the document's keys keep working; Tab still reaches the tab row.
|
||||
- Floating windows stack with the app's own egui windows in egui's area order: the one shown, pressed or raised last (`FloatingGroup::raise`, which the host's `DockArea::focus` request sets on the window holding the panel) is on top, so a dialog the app opens over a floating panel shows above it.
|
||||
- A panel command (`DockCommands`) acts on the shown panel of the group that takes it. A menu row, a key and the command palette run the same code: `actions` turns the command into `Action`s.
|
||||
|
||||
## Commands and workspaces
|
||||
|
||||
Reference in New Issue
Block a user