shortcuts-w4: net change of 1 commits

- shortcuts-w4: written by an agent
This commit is contained in:
bflatastic
2026-11-21 21:26:14 +07:00
parent 743ed8e7f6
commit 8a2636cd68
13 changed files with 644 additions and 130 deletions
+2 -1
View File
@@ -267,7 +267,8 @@ impl KeyboardState {
let platform = keymap.platform();
let mut map: Index = HashMap::new();
for b in keymap.catalog() {
for binding in keymap.bindings(&b.command) {
// The pane shows what a press of a key does; a hold does not change that, so the switch needs no new key.
for binding in keymap.bindings(&b.command).into_iter().filter(|x| !x.trigger.is_hold()) {
let scope = binding.scope_or(&b.scope).clone();
let holder = Holder { command: b.command.clone(), binding };
map.entry(holder.binding.trigger.chord.effective(platform)).or_default().push(KeyHolder { holder, scope });
+9 -7
View File
@@ -119,7 +119,7 @@ mod words;
pub use codec::ChordCodec;
pub use import_offer::{ImportOffer, ImportOfferWords, NoOffer, OfferAnswer, OfferRecord};
pub use pages::{DialogSnapshot, DialogTab};
pub use pages::{DialogSnapshot, DialogTab, ReviewCode, ReviewEntry, ReviewSnapshot};
pub use state::DialogState;
pub use words::{ShortcutWords, kys_error_text, trigger_text};
@@ -287,7 +287,7 @@ pub struct Options {
pub double_press: bool,
/// false: Backspace or Delete without modifiers removes the binding being recorded over.
pub backspace_clears: bool,
/// false: Enter when idle is OK.
/// false: Enter closes nothing; true: Enter when idle is OK.
pub enter_is_ok: bool,
/// false: rows sort by translated label instead of catalog order.
pub sort_by_label: bool,
@@ -387,19 +387,20 @@ pub struct ShortcutsDialog<'a> {
sets: Option<(&'a mut Profiles, &'a Builtins<'a>)>,
options: Option<&'a Options>,
tabs: Option<Box<dyn pages::TabSet + 'a>>,
holds: Option<&'a mut HoldSetting>,
}
impl<'a> ShortcutsDialog<'a> {
/// Shows the Hold Shortcuts switch, its delay and the explanation, and a Hold column recorded like the
/// shortcut column. Cancel restores the setting; the app saves it on [`Outcome::Ok`].
pub fn holds(self, holds: &'a mut HoldSetting) -> Self {
let _ = holds;
todo!("kb.C16a")
pub fn holds(mut self, holds: &'a mut HoldSetting) -> Self {
self.holds = Some(holds);
self
}
/// A dialog editing `keymap`; without further builder calls it has no sets and default options.
pub fn new(keymap: &'a mut Keymap) -> Self {
ShortcutsDialog { keymap, sets: None, options: None, tabs: None }
ShortcutsDialog { keymap, sets: None, options: None, tabs: None, holds: None }
}
/// Shows and edits named sets.
@@ -423,7 +424,8 @@ impl<'a> ShortcutsDialog<'a> {
&fallback
}
};
let mut env = Env { keymap: self.keymap, sets: self.sets, options, tabs: self.tabs.as_deref_mut().map(pages::shorten), text: say };
let mut env =
Env { keymap: self.keymap, sets: self.sets, options, tabs: self.tabs.as_deref_mut().map(pages::shorten), text: say, holds: self.holds };
f(&mut env)
}
+98 -5
View File
@@ -6,11 +6,13 @@
//! row's `.kys` export is an [`super::Options::export_formats`] entry the app writes with
//! [`craft_keymap::import::kys::write`].
use std::collections::BTreeMap;
use serde::Serialize;
use craft_keymap::{CommandDef, CommandKind, CommandRef, Keymap};
use super::state::Target;
use super::state::{Review, Target};
use super::view::area_key;
use super::{Area, DialogState, ShortcutsDialog};
@@ -130,6 +132,92 @@ pub struct DialogSnapshot {
pub holds: Option<bool>,
/// The command a hold is being recorded for.
pub recording_hold: Option<CommandRef>,
/// The import review, while it shows.
pub review: Option<ReviewSnapshot>,
}
/// The import review as automation reads it.
#[derive(Clone, Debug, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct ReviewSnapshot {
/// The new set's name.
pub name: String,
/// The set's entries, in source order.
pub entries: Vec<ReviewEntry>,
/// The undecided codes the plan decoded or the user answered.
pub codes: Vec<ReviewCode>,
/// How many entries are in each [`ReviewEntry::state`].
pub counts: BTreeMap<&'static str, usize>,
}
/// One entry of the set under review.
#[derive(Clone, Debug, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct ReviewEntry {
/// The source's path of the entry, as the set names it.
pub item: String,
/// The entry's line in the source file, when the reader gives one.
pub line: Option<usize>,
/// The command the entry is matched to.
pub target: Option<CommandRef>,
/// Whether the entry is imported.
pub included: bool,
/// `ready`, `unmatched`, `unreadable` or `leftOut`.
pub state: &'static str,
}
/// An undecided key or modifier code of the set under review.
#[derive(Clone, Debug, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct ReviewCode {
/// The code, as `key:N` or `mods:N`.
pub code: String,
/// The chord text the code stands for; `None`: No equivalent.
pub text: Option<String>,
}
impl ReviewSnapshot {
fn of(review: &Review) -> ReviewSnapshot {
let report = &review.plan.report;
let entries: Vec<ReviewEntry> = review
.set
.entries
.iter()
.enumerate()
.map(|(i, entry)| {
let (item, line) = (entry.item(), entry.line);
// Report rows name their entry by its item and line, as `Review::entry_at` finds it.
let here = |row_item: &str, row_line: Option<usize>| row_item == item && row_line == line;
let included = review.included.get(i).copied().unwrap_or(true);
let target = review
.plan
.commands
.iter()
.find(|p| here(&p.item, p.line) || p.bindings.iter().any(|b| here(&b.item, b.line)))
.map(|p| p.command.clone())
.or_else(|| report.matched_without_change.iter().find(|m| here(&m.item, m.line)).map(|m| m.command.clone()));
let state = if !included {
"leftOut"
} else if report.unreadable.iter().any(|u| here(&u.item, u.line)) {
"unreadable"
} else if target.is_none() || report.unmatched.iter().any(|u| here(&u.item, u.line)) {
"unmatched"
} else {
"ready"
};
ReviewEntry { item, line, target, included, state }
})
.collect();
let mut counts: BTreeMap<&'static str, usize> = BTreeMap::new();
for entry in &entries {
*counts.entry(entry.state).or_default() += 1;
}
let codes = report.codes.iter().map(|c| ReviewCode { code: c.code.clone(), text: c.text.clone() }).collect();
ReviewSnapshot { name: review.name.clone(), entries, codes, counts }
}
}
impl DialogState {
@@ -148,13 +236,18 @@ impl DialogState {
overrides: keymap.overrides().iter().filter_map(|(key, texts)| Some((command(key)?, texts.to_vec()))).collect(),
conflict: self.conflict.as_ref().map(|c| (c.binding.to_string(), c.holders.iter().map(|h| h.command.clone()).collect())),
recording: self.recording.as_ref().and_then(|r| match &r.target {
Target::Cell { command, .. } | Target::Field { command } => Some(command.clone()),
Target::Search => None,
Target::Cell { command, .. } | Target::HoldCell { command, .. } | Target::Field { command } => Some(command.clone()),
Target::Search | Target::Code { .. } => None,
}),
set: self.set.clone(),
can_undo: self.can_undo(),
holds: None,
recording_hold: None,
// The switch sets the setting and the keymap's holds in one step, so the keymap's flag is the setting's.
holds: self.holds_shown.then(|| keymap.holds()),
recording_hold: self.recording.as_ref().and_then(|r| match &r.target {
Target::HoldCell { command, .. } => Some(command.clone()),
_ => None,
}),
review: self.review.as_ref().map(ReviewSnapshot::of),
})
}
}
+32 -18
View File
@@ -6,7 +6,7 @@ use std::collections::{BTreeSet, HashMap, HashSet};
use craft_i18n::Folder;
use craft_keymap::chord::{Platform, Trigger};
use craft_keymap::command::CommandRef;
use craft_keymap::keymap::{Binding, CommandDef, CommandKind, ConflictKind, Keymap, Overrides};
use craft_keymap::keymap::{Binding, CommandDef, CommandKind, ConflictKind, Keymap, MAX_BINDINGS, Overrides};
use crate::shortcuts::Options;
use crate::shortcuts::words::{Say, around_chord};
@@ -82,7 +82,10 @@ pub(crate) struct Row {
pub label: String,
/// Translated path parts between the group header and the label, shown dim before it.
pub prefix: Vec<String>,
/// The shortcut column's bindings: single and double presses.
pub chips: Vec<Chip>,
/// The Hold column's bindings; empty while the keymap leaves holds out.
pub hold_chips: Vec<Chip>,
/// Override texts that do not parse, as written.
pub unparsed: Vec<String>,
/// An overrides entry exists.
@@ -93,6 +96,13 @@ pub(crate) struct Row {
pub conflict: bool,
}
impl Row {
/// The command has [`MAX_BINDINGS`] bindings, holds counted: neither column takes another.
pub(crate) fn full(&self) -> bool {
self.chips.len() + self.hold_chips.len() >= MAX_BINDINGS
}
}
/// A read-only row from [`Options::fixed`].
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct FixedLine {
@@ -146,9 +156,11 @@ struct Key {
collapsed: BTreeSet<String>,
overrides: Overrides,
platform: Platform,
/// The keymap's holds: the switch changes the bindings without changing the overrides.
holds: bool,
}
/// The built lines, rebuilt only when the view or the keymap's overrides change.
/// The built lines, rebuilt only when the view, the keymap's overrides or its holds change.
#[derive(Clone, Debug, Default)]
pub(crate) struct RowCache {
key: Option<Key>,
@@ -165,6 +177,7 @@ impl RowCache {
&& k.collapsed == *view.collapsed
&& k.platform == keymap.platform()
&& k.overrides == *keymap.overrides()
&& k.holds == keymap.holds()
});
if !fresh {
self.built = build(keymap, options, text, view);
@@ -176,6 +189,7 @@ impl RowCache {
collapsed: view.collapsed.clone(),
overrides: keymap.overrides().clone(),
platform: keymap.platform(),
holds: keymap.holds(),
});
}
&self.built
@@ -345,11 +359,12 @@ fn build(keymap: &Keymap, options: &Options, text: &Say, view: &View) -> Built {
}
let bindings: Vec<Vec<Binding>> = catalog.iter().map(|b| keymap.bindings(&b.command)).collect();
// How many tools of a group hold each effective trigger.
// How many tools of a group hold each effective trigger. A hold has no repeated press to cycle with, so holds
// are not counted.
let mut tool_keys: HashMap<(Option<&str>, Trigger), usize> = HashMap::new();
for (b, list) in catalog.iter().zip(&bindings) {
if let CommandKind::Tool { group } = &b.kind {
for x in list {
for x in list.iter().filter(|x| !x.trigger.is_hold()) {
*tool_keys.entry((group.as_deref().filter(|_| !keymap.shares_tool_keys()), x.trigger.effective(platform))).or_default() += 1;
}
}
@@ -382,26 +397,25 @@ fn build(keymap: &Keymap, options: &Options, text: &Say, view: &View) -> Built {
let path = b.paths.first().map(Vec::as_slice).unwrap_or_default();
let prefix = path.get(depth..path.len().saturating_sub(1)).unwrap_or_default().iter().map(|s| text.segment(s).into_owned()).collect();
let defaults = &b.defaults;
let chips = list
.iter()
.map(|x| {
let mut t = text.trigger(&x.trigger, platform);
if x.scope_or(&b.scope) != &b.scope {
let scope = text.segment(x.scope_or(&b.scope).as_str());
let s = text.words().chord_scope.fill(&[("chord", &t), ("scope", &scope)]);
t = around_chord(text.rtl(), &s, &t);
}
Chip { binding: x.clone(), text: t, changed: !defaults.contains(x) }
})
.collect();
let chip = |x: &Binding| {
let mut t = text.trigger(&x.trigger, platform);
if x.scope_or(&b.scope) != &b.scope {
let scope = text.segment(x.scope_or(&b.scope).as_str());
let s = text.words().chord_scope.fill(&[("chord", &t), ("scope", &scope)]);
t = around_chord(text.rtl(), &s, &t);
}
Chip { binding: x.clone(), text: t, changed: !defaults.contains(x) }
};
let chips = list.iter().filter(|x| !x.trigger.is_hold()).map(chip).collect();
let hold_chips = list.iter().filter(|x| x.trigger.is_hold()).map(chip).collect();
let cycles = match &b.kind {
CommandKind::Tool { group } => list.iter().any(|x| {
CommandKind::Tool { group } => list.iter().filter(|x| !x.trigger.is_hold()).any(|x| {
tool_keys.get(&(group.as_deref().filter(|_| !keymap.shares_tool_keys()), x.trigger.effective(platform))).is_some_and(|n| *n > 1)
}),
_ => false,
};
let unparsed = keymap.unparsed_texts(&b.command).into_iter().map(str::to_owned).collect();
let row = Row { index, command: b.command.clone(), key, label: text.command(b), prefix, chips, unparsed, changed, cycles, conflict };
let row = Row { index, command: b.command.clone(), key, label: text.command(b), prefix, chips, hold_chips, unparsed, changed, cycles, conflict };
match groups.iter_mut().find(|(r, h, _)| *r == rank && *h == header) {
Some((_, _, rows)) => rows.push(row),
None => groups.push((rank, header, vec![row])),
+143 -43
View File
@@ -4,7 +4,7 @@
use std::collections::BTreeSet;
use craft_keymap::editor::{self, DOUBLE_PRESS, EditSession, Recorded, Recorder};
use craft_keymap::import::{self, ForeignSet, ImportOptions, ImportPlan, ImportReport, Start};
use craft_keymap::import::{self, ForeignEntry, ForeignSet, ImportOptions, ImportPlan, ImportReport, Start};
use craft_keymap::profiles::{Builtins, ProfileError, Profiles, set_name};
use craft_keymap::{
AssignError, Assigned, Binding, BindingError, Chord, CommandRef, Holder, Key, Keymap, MAX_BINDINGS, Overrides, ParseError, Policy, Scope, Trigger,
@@ -14,7 +14,7 @@ use super::keyboard::KeyboardState;
use super::pages::TabSet;
use super::rows::{self, AreaEntry, AreaId, Built, Filter, RowCache, View};
use super::words::Say;
use super::{ConflictMode, JSON_FORMAT, Options, Outcome, summary};
use super::{ConflictMode, HoldSetting, JSON_FORMAT, Options, Outcome, summary};
/// What the dialog edits this frame.
pub(crate) struct Env<'e> {
@@ -23,6 +23,8 @@ pub(crate) struct Env<'e> {
pub options: &'e Options,
pub tabs: Option<&'e mut dyn TabSet>,
pub text: &'e Say,
/// The app's Hold Shortcuts setting; `None`: the dialog has no hold parts.
pub holds: Option<&'e mut HoldSetting>,
}
impl Env<'_> {
@@ -66,10 +68,23 @@ impl Env<'_> {
pub(crate) enum Target {
/// A row's shortcut cell: replaces `old`, or adds when `None`. Commits at once.
Cell { command: CommandRef, old: Option<Binding> },
/// A row's hold cell: the chord recorded becomes a hold that replaces the hold `old`, or adds one when `None`.
/// Commits at once.
HoldCell { command: CommandRef, old: Option<Binding> },
/// The detail pane's New Shortcut field: the chord waits for Assign.
Field { command: CommandRef },
/// Search by key: the chord's text becomes the query.
Search,
/// The import review's undecided key code `code` (`key:N`): the key pressed, without modifiers, answers it.
Code { code: String },
}
impl Target {
/// A single press waits for a second one ([`Options::double_press`]) only where a double press means something:
/// a hold or a code takes the chord alone.
fn takes_double(&self) -> bool {
!matches!(self, Target::HoldCell { .. } | Target::Code { .. })
}
}
#[derive(Clone, Debug, PartialEq)]
@@ -154,14 +169,34 @@ pub(crate) struct Review {
pub name: String,
/// After Import as New Set: the set's name and the report.
pub done: Option<(String, ImportReport)>,
/// Whether each entry of the set is imported.
#[allow(dead_code)] // P3(shortcuts-w4): kb.C12
/// Whether each entry of the set is imported, one flag per `set.entries`.
pub included: Vec<bool>,
/// The search over label, path and key text.
#[allow(dead_code)] // P3(shortcuts-w4): kb.C12
pub search: String,
}
impl Review {
/// The entry of the set named `item` at `line`: what a report row stands for.
pub(crate) fn entry_at(&self, item: &str, line: Option<usize>) -> Option<usize> {
self.set.entries.iter().position(|e| e.item() == item && e.line == line)
}
/// Plans the set again after a change of its options or of the entries left out.
fn replan(&mut self, keymap: &Keymap) {
self.plan = plan_included(&self.set, &self.included, keymap, &self.options);
}
}
/// The plan of the entries of `set` that `included` keeps; an entry left out is planned as if the set lacked it.
fn plan_included(set: &ForeignSet, included: &[bool], keymap: &Keymap, options: &ImportOptions) -> ImportPlan {
if included.iter().all(|on| *on) {
return import::plan(set, keymap, options);
}
let mut kept = set.clone();
kept.entries = set.entries.iter().enumerate().filter(|(i, _)| included.get(*i).copied().unwrap_or(true)).map(|(_, e)| e.clone()).collect();
import::plan(&kept, keymap, options)
}
/// The set row's inline form: New Set… or Rename….
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct SetForm {
@@ -184,6 +219,8 @@ pub(crate) enum SetFormKind {
struct Opened {
profiles: Option<Profiles>,
overrides: Overrides,
/// The hold setting as the app gave it, when it gave one.
holds: Option<HoldSetting>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
@@ -233,6 +270,8 @@ pub struct DialogState {
pub(crate) tab: Option<&'static str>,
/// The active set's name as of the last frame.
pub(crate) set: Option<String>,
/// The app gave the dialog its hold setting as of the last frame.
pub(crate) holds_shown: bool,
}
impl Default for DialogState {
@@ -274,6 +313,7 @@ impl DialogState {
keyboard: KeyboardState::default(),
tab: None,
set: None,
holds_shown: false,
}
}
@@ -290,9 +330,10 @@ impl DialogState {
self.phase != Phase::New
}
/// Records the active set's name for [`DialogState::snapshot`].
/// Records the active set's name and whether the hold setting is shown, for [`DialogState::snapshot`].
pub(crate) fn sync_set(&mut self, env: &Env) {
self.set = env.sets.as_ref().map(|(p, b)| p.active_name(b).to_string());
self.holds_shown = env.holds.is_some();
}
/// Shows an app tab (`None`: Keyboard Shortcuts); a chord being recorded is dropped.
@@ -342,13 +383,17 @@ impl DialogState {
// ---- Frame ----
/// The first frame: snapshot for Cancel, an edit session, the Show entries.
/// The first frame: snapshot for Cancel, the keymap's holds as the setting says, an edit session, the Show entries.
pub(crate) fn begin(&mut self, env: &mut Env) {
if self.phase != Phase::New {
return;
}
self.phase = Phase::Open;
self.opened = Some(Opened { profiles: env.sets.as_ref().map(|(p, _)| (**p).clone()), overrides: env.keymap.overrides().clone() });
let holds = env.holds.as_deref().cloned();
if let Some(setting) = &holds {
env.keymap.set_holds(setting.on);
}
self.opened = Some(Opened { profiles: env.sets.as_ref().map(|(p, _)| (**p).clone()), overrides: env.keymap.overrides().clone(), holds });
self.session = Some(EditSession::begin(env.keymap));
self.areas = rows::areas(env.keymap, env.options, env.text);
self.sync_set(env);
@@ -449,7 +494,7 @@ impl DialogState {
self.conflict = None;
self.message = None;
self.recorder.reset();
if let Target::Cell { command, .. } | Target::Field { command } = &target {
if let Target::Cell { command, .. } | Target::HoldCell { command, .. } | Target::Field { command } = &target {
self.select_row(command);
}
self.recording = Some(Recording { target, waiting: None, started: false });
@@ -477,7 +522,7 @@ impl DialogState {
let target = rec.target.clone();
self.stop_recording();
match target {
Target::Cell { command, old: Some(old) } => self.remove(env, &command, &old),
Target::Cell { command, old: Some(old) } | Target::HoldCell { command, old: Some(old) } => self.remove(env, &command, &old),
Target::Field { .. } => self.field = None,
_ => {}
}
@@ -485,7 +530,7 @@ impl DialogState {
}
match self.recorder.press(chord, now) {
Recorded::Cancel => self.stop_recording(),
Recorded::Single(t) if env.options.double_press => rec.waiting = Some((t, now)),
Recorded::Single(t) if env.options.double_press && rec.target.takes_double() => rec.waiting = Some((t, now)),
Recorded::Single(t) | Recorded::Double(t) => self.commit_recorded(env, t),
}
}
@@ -497,17 +542,29 @@ impl DialogState {
self.recorder.reset();
match rec.target {
Target::Search => self.query = env.chord_text(&trigger),
Target::Cell { command, old } => {
let binding = match old.as_ref().and_then(|o| o.scope.clone()) {
Some(scope) => Binding::in_scope(trigger, scope),
None => Binding::new(trigger),
};
self.commit(env, &command, old, binding);
}
Target::Cell { command, old } => self.commit_cell(env, &command, old, trigger),
// A double press held is the same hold: the cell takes the chord alone.
Target::HoldCell { command, old } => self.commit_cell(env, &command, old, Trigger::hold(trigger.chord)),
Target::Field { command } => self.set_field(env, command, trigger),
Target::Code { code } => {
if trigger.chord.mods.is_none() {
self.answer_code(env, code, Some(trigger.chord.key.name().to_owned()));
} else {
self.refuse(word!(env, press_a_key_without_modifiers));
}
}
}
}
/// Commits `trigger` to a row's cell in the scope of the binding it replaces.
fn commit_cell(&mut self, env: &mut Env, command: &CommandRef, old: Option<Binding>, trigger: Trigger) {
let binding = match old.as_ref().and_then(|o| o.scope.clone()) {
Some(scope) => Binding::in_scope(trigger, scope),
None => Binding::new(trigger),
};
self.commit(env, command, old, binding);
}
/// Puts a chord into the New Shortcut field with the chosen Context, and finds who holds it.
pub(crate) fn set_field(&mut self, env: &Env, command: CommandRef, trigger: Trigger) {
let binding = match &self.context {
@@ -742,6 +799,43 @@ impl DialogState {
self.session.as_ref().is_some_and(EditSession::can_redo)
}
// ---- Hold Shortcuts ----
/// The Hold Shortcuts switch: the setting and the keymap's holds in one step. The setting is not an override, so
/// Cancel restores it and Undo does not; a hold being recorded or waiting in the conflict bar is dropped when
/// holds go off.
pub(crate) fn set_holds_on(&mut self, env: &mut Env, on: bool) {
let Some(setting) = env.holds.as_deref_mut() else { return };
if setting.on == on {
return;
}
setting.on = on;
env.keymap.set_holds(on);
if !on {
if matches!(self.recording.as_ref().map(|r| &r.target), Some(Target::HoldCell { .. })) {
self.stop_recording();
}
if self.conflict.as_ref().is_some_and(|c| c.binding.trigger.is_hold()) {
self.conflict = None;
}
}
self.changed = true;
}
/// The hold delay, kept in the setting's range; Cancel restores it and Undo does not.
pub(crate) fn set_hold_delay(&mut self, env: &mut Env, delay: f64) {
let Some(setting) = env.holds.as_deref_mut() else { return };
if !delay.is_finite() {
return;
}
// `max` then `min` rather than `clamp`, which panics on a range given backwards.
let delay = delay.max(*setting.range.start()).min(*setting.range.end());
if delay != setting.delay {
setting.delay = delay;
self.changed = true;
}
}
// ---- OK, Cancel, Escape, Enter ----
/// OK: with sets, stores the overrides (a built-in's edits become a copy), then closes.
@@ -766,6 +860,11 @@ impl DialogState {
undone |= **p != profiles;
**p = profiles;
}
if let (Some(setting), Some(was)) = (env.holds.as_deref_mut(), opened.holds) {
undone |= *setting != was;
env.keymap.set_holds(was.on);
*setting = was;
}
}
self.close(Outcome::Cancel);
self.changed = undone;
@@ -1080,47 +1179,47 @@ impl DialogState {
let name = plan.report.set.clone().unwrap_or_else(|| word!(env, imported));
self.stop_recording();
self.conflict = None;
self.review = Some(Review { set, options, plan, name, done: None, included: Vec::new(), search: String::new() });
}
/// Picks candidate `candidate` for suggestion `suggestion`, re-plans, and reports the answers
/// for the app to keep.
pub(crate) fn pick_suggestion(&mut self, env: &Env, suggestion: usize, candidate: usize) {
let Some(r) = &mut self.review else { return };
let Some(s) = r.plan.report.suggestions.get(suggestion) else { return };
let Some(command) = s.candidates.get(candidate).cloned() else { return };
let Some(entry) = r.set.entries.iter().find(|e| e.item() == s.item && e.line == s.line) else { return };
r.options.remembered.insert(entry.remember_key(), Some(command)); // P3(shortcuts-w4): kb.C12
r.plan = import::plan(&r.set, env.keymap, &r.options);
self.outcome = Some(Outcome::Remembered { targets: r.options.remembered.clone(), codes: r.options.codes.clone() }); // P3(shortcuts-w4): kb.C29
let included = vec![true; set.entries.len()];
self.review = Some(Review { set, options, plan, name, done: None, included, search: String::new() });
}
/// Starts the review from `start` and re-plans.
#[allow(dead_code)] // P3(shortcuts-w4): kb.C12
pub(crate) fn set_start(&mut self, env: &Env, start: Start) {
let _ = (env, start);
todo!("kb.C12")
let Some(r) = &mut self.review else { return };
r.options.start = start;
r.replan(env.keymap);
}
/// Imports entry `entry` or leaves it out, and re-plans.
#[allow(dead_code)] // P3(shortcuts-w4): kb.C12
pub(crate) fn include(&mut self, env: &Env, entry: usize, on: bool) {
let _ = (env, entry, on);
todo!("kb.C12")
let Some(r) = &mut self.review else { return };
let Some(flag) = r.included.get_mut(entry) else { return };
*flag = on;
r.replan(env.keymap);
}
/// Picks `command` for entry `entry` (`None` is No equivalent), re-plans and reports the answer.
#[allow(dead_code)] // P3(shortcuts-w4): kb.C12
pub(crate) fn pick_target(&mut self, env: &Env, entry: usize, command: Option<CommandRef>) {
let _ = (env, entry, command);
todo!("kb.C12")
let Some(r) = &mut self.review else { return };
let Some(key) = r.set.entries.get(entry).map(ForeignEntry::remember_key) else { return };
r.options.remembered.insert(key, command);
r.replan(env.keymap);
self.report_answers();
}
/// Answers the undecided `code` (`None` is No equivalent), re-plans and reports the answer.
#[allow(dead_code)] // P3(shortcuts-w4): kb.C12
pub(crate) fn answer_code(&mut self, env: &Env, code: String, answer: Option<String>) {
let _ = (env, code, answer);
todo!("kb.C12")
let Some(r) = &mut self.review else { return };
r.options.codes.insert(code, answer);
r.replan(env.keymap);
self.report_answers();
}
/// Every answer the review holds, for the app to keep for later imports.
fn report_answers(&mut self) {
if let Some(r) = &self.review {
self.outcome = Some(Outcome::Remembered { targets: r.options.remembered.clone(), codes: r.options.codes.clone() });
}
}
/// Import as New Set (with sets), else applies the plan to the keymap as one undo step.
@@ -1165,6 +1264,7 @@ fn assign_error(env: &Env, e: &AssignError) -> String {
AssignError::Full => word!(env, too_many_shortcuts_are_assigned),
AssignError::UnknownCommand => word!(env, this_command_is_unknown),
AssignError::Taken(holders) => fill!(env, also_used_by_label, ("label", &env.holder_labels(holders))),
AssignError::NotHoldable(t) => fill!(env, not_holdable, ("chord", &env.chord_text(t))),
_ => e.to_string(),
}
}
+90 -6
View File
@@ -2,7 +2,7 @@
use craft_keymap::{
Binding, Chord, CommandDef, ContextRule, Flavor, ForeignEntry, ForeignKey, ForeignSet, ImportOptions, Key, Keymap, Overrides, Platform, Profiles,
Scope, Scopes,
Scope, Scopes, Trigger,
};
use craft_ui::contract::Show as _;
use craft_ui::display::Text;
@@ -11,7 +11,7 @@ use egui::Ui;
use super::state::{DialogState, Env, Target};
use super::words::Say;
use super::{DialogTab, Options, ShortcutsDialog};
use super::{DialogTab, HoldSetting, Options, ShortcutsDialog};
#[allow(clippy::panic, reason = "the story's own fixed chords are valid")]
fn binding(text: &str) -> Binding {
@@ -21,9 +21,13 @@ fn binding(text: &str) -> Binding {
/// A small app: file commands, two tools that both default to `M` (the conflict), and commands of the Timeline
/// panel.
pub(super) fn keymap() -> Keymap {
let path = |parts: &[&str]| parts.iter().map(|s| (*s).to_owned()).collect::<Vec<_>>();
keymap_with(Vec::new())
}
/// The stories' keymap with `extra` commands after its own.
fn keymap_with(extra: Vec<CommandDef>) -> Keymap {
let timeline = Scope::new("Timeline").unwrap_or_else(Scope::app);
let catalog = vec![
let mut catalog = vec![
CommandDef::new("file.save", "Save", Scope::app()).with_path(path(&["File", "Save"])).with_default(binding("Cmd+S")),
CommandDef::new("file.export", "Export", Scope::app()).with_path(path(&["File", "Export"])).with_default(binding("Cmd+E")),
CommandDef::new("tool.marquee", "Marquee Tool", Scope::app()).with_default(binding("M")),
@@ -31,9 +35,20 @@ pub(super) fn keymap() -> Keymap {
CommandDef::new("timeline.loop", "Loop", timeline.clone()).with_default(binding("L")),
CommandDef::new("timeline.play", "Play", timeline).with_default(binding("Space")),
];
catalog.extend(extra);
Keymap::new(catalog, Scopes::new().with_panel("Timeline"), Platform::Linux)
}
fn path(parts: &[&str]) -> Vec<String> {
parts.iter().map(|s| (*s).to_owned()).collect()
}
/// A second Export under File > Export, in the Timeline panel: an entry naming File > Export fits both.
fn twin_export() -> Vec<CommandDef> {
let timeline = Scope::new("Timeline").unwrap_or_else(Scope::app);
vec![CommandDef::new("timeline.export", "Export", timeline).with_path(path(&["File", "Export"])).with_default(binding("Cmd+Shift+E"))]
}
/// What a story sets up besides its options.
#[derive(Clone, Copy, Default)]
struct Setup {
@@ -41,21 +56,31 @@ struct Setup {
sets: bool,
/// The dialog has an app tab.
tabs: bool,
/// The dialog shows the Hold Shortcuts setting, on or off.
holds: Option<bool>,
/// The keymap has a second Export ([`twin_export`]).
twin_export: bool,
}
/// The delay the stories' hold setting starts at, in seconds.
const HOLD_DELAY: f64 = 0.4;
/// The delays the stories' hold setting accepts, in seconds.
const HOLD_DELAYS: std::ops::RangeInclusive<f64> = 0.1..=2.0;
/// The dialog in the state `prepare` leaves it in. The state is built each pass: the stories do not drive it.
fn scene(ui: &mut Ui, options: &Options, setup: Setup, prepare: impl FnOnce(&mut Env<'_>, &mut DialogState)) -> StoryOutput {
let mut keymap = keymap();
let mut keymap = keymap_with(if setup.twin_export { twin_export() } else { Vec::new() });
let mut profiles = Profiles::default();
let builtins = vec![("Defaults", Overrides::new())];
if setup.sets {
let _ = profiles.save_as("Mine", Overrides::new(), &builtins);
}
let mut holds = setup.holds.map(|on| HoldSetting { on, delay: HOLD_DELAY, range: HOLD_DELAYS });
let mut state = DialogState::new();
let say = Say::of(ui);
{
let sets = setup.sets.then(|| (&mut profiles, &builtins[..]));
let mut env = Env { keymap: &mut keymap, sets, options, tabs: None, text: &say };
let mut env = Env { keymap: &mut keymap, sets, options, tabs: None, text: &say, holds: holds.as_mut() };
state.begin(&mut env);
prepare(&mut env, &mut state);
}
@@ -70,6 +95,9 @@ fn scene(ui: &mut Ui, options: &Options, setup: Setup, prepare: impl FnOnce(&mut
if setup.tabs {
dialog = dialog.tabs(&mut tabs);
}
if let Some(holds) = holds.as_mut() {
dialog = dialog.holds(holds);
}
dialog.show(ui, &mut state).into()
}
@@ -140,3 +168,59 @@ fn named_sets(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
fn app_tabs(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
scene(ui, &Options::default(), Setup { tabs: true, ..Setup::default() }, |_, _| {})
}
#[story(ShortcutsDialog<'static>, covers = [], drive = Drive::Never)]
fn holds_off(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
scene(ui, &Options::default(), Setup { holds: Some(false), ..Setup::default() }, |_, _| {})
}
#[story(ShortcutsDialog<'static>, covers = [], drive = Drive::Never)]
fn holds_on(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
scene(ui, &Options::default(), Setup { holds: Some(true), ..Setup::default() }, |env, state| {
state.commit(env, &"file.save".into(), None, Binding::new(Trigger::hold(chord("K"))));
})
}
#[story(ShortcutsDialog<'static>, covers = [], drive = Drive::Never)]
fn hold_recording(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
scene(ui, &Options::default(), Setup { holds: Some(true), ..Setup::default() }, |env, state| {
state.record(env, Target::HoldCell { command: "file.save".into(), old: None });
})
}
/// The width the explanation under the switch wraps at.
const NARROW: f32 = 360.0;
/// The Hold Shortcuts row in a narrow room: the explanation wraps under the switch.
#[story(ShortcutsDialog<'static>, covers = [], drive = Drive::Never)]
fn hold_explanation(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
ui.set_max_width(NARROW.min(ui.available_width()));
scene(ui, &Options::default(), Setup { holds: Some(true), ..Setup::default() }, |_, _| {})
}
/// A key whose key code the reader left undecided, with no matched default to vote on what it stands for.
#[story(ShortcutsDialog<'static>, covers = [], drive = Drive::Never)]
fn import_review_keys(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
scene(ui, &Options::default(), Setup { sets: true, ..Setup::default() }, |env, state| {
let key = ForeignKey::code(Some("Default"), "Key 67", Some(67), None);
let set = ForeignSet::new(vec![ForeignEntry::new(Some("File"), ["Save"]).with_key(key).at_line(3)]).with_name("Theirs");
let options = ImportOptions { contexts: vec![("Default".into(), ContextRule::Home)], ..ImportOptions::default() };
state.review_import(env, set, options);
})
}
/// A matched entry, an unmatched one and one that fits both Exports, with suggestions to pick from.
#[story(ShortcutsDialog<'static>, covers = [], drive = Drive::Never)]
fn import_review_choices(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
scene(ui, &Options::default(), Setup { sets: true, twin_export: true, ..Setup::default() }, |env, state| {
let read = |text: &str| ForeignKey::read(Some("Default"), text, Flavor::Windows);
let set = ForeignSet::new(vec![
ForeignEntry::new(Some("File"), ["Save"]).with_key(read("Ctrl+Alt+S")).at_line(3),
ForeignEntry::new(Some("File"), ["Frobnicate"]).with_key(read("Ctrl+F")).at_line(4),
ForeignEntry::new(Some("File"), ["Export"]).with_key(read("Ctrl+Shift+X")).at_line(5),
])
.with_name("Theirs");
let options = ImportOptions { contexts: vec![("Default".into(), ContextRule::Home)], suggest: true, ..ImportOptions::default() };
state.review_import(env, set, options);
})
}
+37 -3
View File
@@ -1,13 +1,15 @@
//! The header: Show (a select, or tabs with `Options::area_tabs`), Filter, Search with Search by key, and the
//! keyboard pane's toggle.
//! The header: Show (a select, or tabs with `Options::area_tabs`), Filter, Search with Search by key, the
//! keyboard pane's toggle, and Hold Shortcuts when the app gives its hold setting.
use craft_ui::buttons::{IconButton, ToggleButton};
use craft_ui::choice::Switch;
use craft_ui::contract::{Bind, BodyCx, Entry, Props as _, Show as _, ShowContainer as _, Sizing, clicked};
use craft_ui::display::{Shade, Text};
use craft_ui::form::Field;
use craft_ui::layout_components::Row;
use craft_ui::pickers::Select;
use craft_ui::primitives::IconSpec;
use craft_ui::text::TextField;
use craft_ui::text::{NumberField, TextField};
use egui::Ui;
use crate::shortcuts::recorder::ChordRecorder;
@@ -15,6 +17,9 @@ use crate::shortcuts::rows::{AreaId, Filter};
use crate::shortcuts::state::{DialogState, Env, Target};
use crate::shortcuts::view::{recording_text, tab_strip};
/// What one arrow press or wheel notch changes the hold delay by, in seconds.
const HOLD_DELAY_STEP: f64 = 0.05;
/// The header for one pass.
pub(super) fn show(ui: &mut Ui, _cx: &mut BodyCx<'_>, now: f64, env: &mut Env<'_>, state: &mut DialogState) {
if env.options.area_tabs {
@@ -30,6 +35,35 @@ pub(super) fn show(ui: &mut Ui, _cx: &mut BodyCx<'_>, now: f64, env: &mut Env<'_
search(ui, now, env, state);
keyboard_toggle(ui, env, state);
});
holds(ui, env, state);
}
/// With the app's hold setting: the Hold Shortcuts switch, the delay while it is on, and the sentence that says what
/// a hold is.
fn holds(ui: &mut Ui, env: &mut Env<'_>, state: &mut DialogState) {
let Some(setting) = env.holds.as_deref() else { return };
let (was_on, was_delay, range) = (setting.on, setting.delay, setting.range.clone());
let words = env.text.words();
let mut on = was_on;
let mut delay = Some(was_delay);
Row::new().show(ui, |ui, _| {
Switch::new(Bind::bound(&mut on)).label(words.hold_shortcuts.clone()).id_salt("holds").show(ui);
if was_on {
let label = words.hold_delay.clone();
Field::new(label.clone()).id_salt("shortcuts.holdDelay").sizing(Sizing::Content).show(ui, |ui, _| {
NumberField::new(label.clone(), Bind::bound(&mut delay)).id_salt("holdDelay").range(range.clone()).step(HOLD_DELAY_STEP).show(ui);
});
}
});
Text::new(words.hold_explanation.clone()).shade(Shade::Faint).show(ui);
if on != was_on {
state.set_holds_on(env, on);
}
if let Some(delay) = delay
&& delay != was_delay
{
state.set_hold_delay(env, delay);
}
}
/// Show as tabs.
+1 -1
View File
@@ -15,7 +15,7 @@ fn scene(ui: &mut Ui, query: &str) -> StoryOutput {
let options = Options::default();
let say = Say::of(ui);
let mut state = DialogState::new();
let mut env = Env { keymap: &mut keymap, sets: None, options: &options, tabs: None, text: &say };
let mut env = Env { keymap: &mut keymap, sets: None, options: &options, tabs: None, text: &say, holds: None };
state.begin(&mut env);
state.set_query(query.to_owned());
table::show(ui, 0.0, &mut env, &mut state);
+91 -46
View File
@@ -1,5 +1,6 @@
//! The command table: command and shortcut columns over the lines `rows` builds, group headers that open and
//! close, and rows whose shortcut chips, add button and restore button are children of the row.
//! The command table: command and shortcut columns, and a Hold column while hold shortcuts are on, over the lines
//! `rows` builds, group headers that open and close, and rows whose chips, add buttons and restore button are
//! children of the row.
//!
//! A group header is a section row of the collection, which takes its press, keys and AccessKit node; the table paints
//! its look, a heading row with the disclosure triangle, over the row.
@@ -10,7 +11,7 @@ use craft_behavior::{
ColumnKey, ColumnWidth, DisplayOrder, Flow, Insets, ItemSource, Metrics, PartKey, Proposal, Selection, SelectionChange, Sense, SpanLayout,
};
use craft_keymap::chord::Chord;
use craft_keymap::keymap::{Binding, MAX_BINDINGS};
use craft_keymap::keymap::Binding;
use craft_ui::buttons::IconButton;
use craft_ui::contract::{
Access, Bind, BindMut, Collection, CollectionEvent, CollectionProps, CollectionResponse, ColumnSpec, Common, Component, ContainerProps, Cx,
@@ -33,9 +34,12 @@ use crate::shortcuts::view::{area_key, recording_text};
const COMMAND: ColumnKey = ColumnKey::new("command");
const SHORTCUT: ColumnKey = ColumnKey::new("shortcut");
const HOLD: ColumnKey = ColumnKey::new("hold");
/// The most of the table the shortcut column takes; it is as wide as its widest row of chips with the add and restore
/// buttons, and the command column takes the rest.
const SHORTCUT_MOST: f32 = 0.4;
/// The most of the table the Hold column takes; it is as wide as its widest row of hold chips with the add button.
const HOLD_MOST: f32 = 0.25;
const PATH_SEPARATOR: &str = " \u{203a} ";
/// The look of a group header, over its section row; the index is the header's line.
const HEADER: PartKey = PartKey::new("group_header");
@@ -47,6 +51,8 @@ const HEADER_DISCLOSURE: PartKey = PartKey::new("group_disclosure");
pub(crate) enum RowAct {
/// A chip (`Some`), or the add button (`None`), asked to record.
Record(Option<usize>),
/// A hold chip (`Some`), or the Hold column's add button (`None`), asked to record.
RecordHold(Option<usize>),
/// The restore button was pressed.
Reset,
/// The recording cell took these chords this pass.
@@ -295,6 +301,8 @@ impl ItemOutput<RowAct> for RowOut {
/// What a row needs of the dialog this pass.
pub(crate) struct RowEnv<'r> {
editable: bool,
/// The Hold column is shown.
holds: bool,
/// The cell the recorder replaces: the row's command, the chip it replaces (`None` adds one) and the text it
/// shows.
recording: Option<(&'r Target, String)>,
@@ -353,6 +361,35 @@ impl<'r> CommandRow<'r> {
fn cell(&self, column: ColumnKey) -> Rect {
self.cells.iter().find(|(key, _)| *key == column).map_or(Rect::NOTHING, |(_, rect)| *rect)
}
/// The recording in this row's shortcut cell, or its hold cell with `hold`: the binding it replaces (`None` adds
/// one) and the text it shows.
fn recording(&self, line: &Row, hold: bool) -> Option<(Option<Binding>, String)> {
let (target, shown) = self.env.recording.as_ref()?;
match target {
Target::Cell { command, old } if !hold && *command == line.command => Some((old.clone(), shown.clone())),
Target::HoldCell { command, old } if hold && *command == line.command => Some((old.clone(), shown.clone())),
_ => None,
}
}
/// The width of a cell's chips and of the recorder when it records into the cell, each measured as the child that
/// shows it.
fn measure_chips(&mut self, cx: &MeasureCx<'_, Self>, line: &Row, hold: bool) -> f32 {
let gap = cx.style.gap;
let mut cell = 0.0;
for chip in if hold { &line.hold_chips } else { &line.chips } {
let width = cx.child(("chip", &chip.text), &mut ChordChip::new(chip.text.clone()), Proposal::Ideal).x;
self.widths.insert((Shown::Chip, chip.text.clone()), width);
cell += width + gap;
}
if let Some((_, shown)) = self.recording(line, hold) {
let width = ChordRecorder::new(String::new(), true, shown.clone()).width(cx, ("record", &line.key));
self.widths.insert((Shown::Recording, shown), width);
cell += width + gap;
}
cell
}
}
/// A saved text that is not a shortcut, shown in the shortcut cell under `name`.
@@ -383,18 +420,13 @@ impl Component for CommandRow<'_> {
}
}
/// The row's height, and the width its shortcut cell takes for the shortcut column.
/// The row's height, and the widths its shortcut cell and its hold cell take for their columns.
fn measure(&mut self, cx: &MeasureCx<'_, Self>) -> Vec2 {
self.widths.clear();
let (gap, height) = (cx.style.gap, cx.style.height);
match self.line {
Line::Row(line) => {
let mut cell = 0.0;
for chip in &line.chips {
let width = cx.child(("chip", &chip.text), &mut ChordChip::new(chip.text.clone()), Proposal::Ideal).x;
self.widths.insert((Shown::Chip, chip.text.clone()), width);
cell += width + gap;
}
let mut cell = self.measure_chips(cx, line, false);
if line.chips.is_empty() {
cell += cx.child(("chip", "none"), &mut ChordChip::new(self.env.words.none.as_str().to_owned()), Proposal::Ideal).x + gap;
}
@@ -403,18 +435,15 @@ impl Component for CommandRow<'_> {
self.widths.insert((Shown::Unparsed, text.clone()), width);
cell += width + gap;
}
if let Some((Target::Cell { command, .. }, shown)) = &self.env.recording
&& *command == line.command
{
let width = ChordRecorder::new(String::new(), true, shown.clone()).width(cx, ("record", &line.key));
self.widths.insert((Shown::Recording, shown.clone()), width);
cell += width + gap;
}
let add = if self.env.editable && !line.full() { height + gap } else { 0.0 };
if self.env.editable {
let add = if line.chips.len() < MAX_BINDINGS { height + gap } else { 0.0 };
cell += add + height;
}
cx.cell_width(&SHORTCUT, cell);
if self.env.holds {
let cell = self.measure_chips(cx, line, true) + add;
cx.cell_width(&HOLD, cell);
}
}
Line::Fixed(fixed) => {
let keys = cx.layout(&TextRun::new(fixed.keys.as_str()).role(cx.style.label.role)).size().x;
@@ -431,7 +460,10 @@ impl Component for CommandRow<'_> {
match self.line {
Line::Row(line) => {
self.paint_label(ui, cx, command, line);
self.paint_shortcuts(ui, cx, rtl, line);
self.paint_cell(ui, cx, rtl, line, false);
if self.env.holds {
self.paint_cell(ui, cx, rtl, line, true);
}
}
Line::Fixed(fixed) => self.paint_fixed(ui, cx, rtl, command, fixed),
Line::Header { .. } => {}
@@ -488,30 +520,32 @@ impl CommandRow<'_> {
}
}
/// The chips in a row, the recording cell in place of the chip it replaces, the add button after them and the
/// restore button at the end of the cell.
fn paint_shortcuts(&mut self, ui: &mut PaintUi<'_>, cx: &Cx<'_, Self>, rtl: bool, line: &Row) {
/// The chips of the row's shortcut cell, or of its hold cell with `hold`: the recording cell in place of the chip
/// it replaces and the add button after them. The shortcut cell also shows None when it has no chip, the saved
/// texts that do not parse, and the restore button at its end.
fn paint_cell(&mut self, ui: &mut PaintUi<'_>, cx: &Cx<'_, Self>, rtl: bool, line: &Row, hold: bool) {
let words = self.env.words;
let cell = self.cell(SHORTCUT);
let cell = self.cell(if hold { HOLD } else { SHORTCUT });
let flow = Flow::new(cell, rtl);
let (gap, height) = (cx.style.gap, cx.style.height);
let editable = self.env.editable;
let chips = if hold { &line.hold_chips } else { &line.chips };
let record = |chip: Option<usize>| if hold { RowAct::RecordHold(chip) } else { RowAct::Record(chip) };
let salt = if hold { "hold" } else { "chip" };
let recording = self.recording(line, hold);
let widths = &self.widths;
let width_of = |kind: Shown, text: &str| widths.get(&(kind, text.to_owned())).copied().unwrap_or(0.0);
let recording = self.env.recording.as_ref().and_then(|(target, shown)| match target {
Target::Cell { command, old } if *command == line.command => Some((old.clone(), shown.clone())),
_ => None,
});
let reset_at = (cell.width() - height).max(0.0);
// The restore button ends the shortcut cell; the hold cell has none.
let reset_at = if hold { cell.width() } else { (cell.width() - height).max(0.0) };
let adding = matches!(&recording, Some((None, _)));
let adds = editable && line.chips.len() < MAX_BINDINGS && !adding;
let adds = editable && !line.full() && !adding;
// The add button keeps its place after the chips: they take the room before it and the reset button.
let chips_end = if adds { (reset_at - height - gap).max(0.0) } else { reset_at };
let mut at = 0.0;
let mut act = None;
let mut cells: Vec<(Option<&Chip>, bool)> =
line.chips.iter().map(|chip| (Some(chip), recording.as_ref().is_some_and(|(old, _)| old.as_ref() == Some(&chip.binding)))).collect();
if matches!(&recording, Some((None, _))) {
chips.iter().map(|chip| (Some(chip), recording.as_ref().is_some_and(|(old, _)| old.as_ref() == Some(&chip.binding)))).collect();
if adding {
cells.push((None, true));
}
for (n, (chip, recording_here)) in cells.iter().enumerate() {
@@ -538,12 +572,12 @@ impl CommandRow<'_> {
}
let Some(chip) = chip else { continue };
let name = words.label_chord.fill(&[("label", &line.label), ("chord", &chip.text)]);
let chip = ChordChip::new(chip.text.clone()).label(name).id_salt(("chip", line.key.as_str(), n)).enabled(editable);
if ui.child(("chip", line.key.as_str(), n), rect, chip).pressed {
act = Some(RowAct::Record(Some(n)));
let chip = ChordChip::new(chip.text.clone()).label(name).id_salt((salt, line.key.as_str(), n)).enabled(editable);
if ui.child((salt, line.key.as_str(), n), rect, chip).pressed {
act = Some(record(Some(n)));
}
}
if cells.is_empty() {
if cells.is_empty() && !hold {
let rect = band(&flow, cell, 0.0, chips_end.max(height));
let none = words.none.as_str();
let name = words.label_chord.fill(&[("label", &line.label), ("chord", none)]);
@@ -553,7 +587,8 @@ impl CommandRow<'_> {
}
at = chips_end.max(height) + gap;
}
for (n, text) in line.unparsed.iter().enumerate() {
let unparsed: &[String] = if hold { &[] } else { &line.unparsed };
for (n, text) in unparsed.iter().enumerate() {
let width = width_of(Shown::Unparsed, text).min((chips_end - at).max(0.0));
let rect = band(&flow, cell, at, width);
at += width + gap;
@@ -563,16 +598,18 @@ impl CommandRow<'_> {
}
if adds && at + height <= reset_at {
let rect = band(&flow, cell, at, height);
let name = words.add_a_shortcut_to_label.fill(&[("label", &line.label)]);
let add = IconButton::new(IconSpec::svg(craft_behavior::IconId::new("plus")))
.id_salt(("add", line.key.as_str()))
.label(name.clone())
.tooltip(name);
if clicked(&ui.child(("add", line.key.as_str()), rect, add)) {
act = Some(RowAct::Record(None));
let (name, add_salt) = if hold {
(words.add_a_hold_shortcut_to_label.fill(&[("label", &line.label)]), "addHold")
} else {
(words.add_a_shortcut_to_label.fill(&[("label", &line.label)]), "add")
};
let add =
IconButton::new(IconSpec::svg(craft_behavior::IconId::new("plus"))).id_salt((add_salt, line.key.as_str())).label(name.clone()).tooltip(name);
if clicked(&ui.child((add_salt, line.key.as_str()), rect, add)) {
act = Some(record(None));
}
}
if editable {
if editable && !hold {
let rect = band(&flow, cell, reset_at, height);
let name = words.restore_the_default_for_label.fill(&[("label", &line.label)]);
let reset = IconButton::new(IconSpec::svg(craft_behavior::IconId::new("reset")))
@@ -601,11 +638,15 @@ pub(super) fn show(ui: &mut Ui, now: f64, env: &mut Env<'_>, state: &mut DialogS
let editable = env.options.editable;
let shown = recording_text(env, state);
let start = state.recording.as_ref().is_some_and(|recording| !recording.started);
let row_env = RowEnv { editable, recording: state.recording.as_ref().map(|recording| (&recording.target, shown.clone())), start, words };
let columns = vec![
let holds = env.holds.as_deref().is_some_and(|setting| setting.on);
let row_env = RowEnv { editable, holds, recording: state.recording.as_ref().map(|recording| (&recording.target, shown.clone())), start, words };
let mut columns = vec![
ColumnSpec::new(COMMAND, words.command.clone(), ColumnWidth::fill(1.0)),
ColumnSpec::new(SHORTCUT, words.shortcut.clone(), ColumnWidth::Content).at_most(SHORTCUT_MOST),
];
if holds {
columns.push(ColumnSpec::new(HOLD, words.hold_column.clone(), ColumnWidth::Content).at_most(HOLD_MOST));
}
let mut selection = Selection::new(position.into_iter().collect(), position, position);
let reveal = if state.reveal { position } else { None };
let source = Lines(&built.lines);
@@ -670,6 +711,10 @@ fn apply(env: &mut Env<'_>, state: &mut DialogState, now: f64, lines: &[Line], o
state.record(env, Target::Cell { command: row.command.clone(), old });
state.chip = chip.unwrap_or(row.chips.len());
}
RowAct::RecordHold(chip) => {
let old: Option<Binding> = chip.and_then(|n| row.hold_chips.get(n)).map(|chip| chip.binding.clone());
state.record(env, Target::HoldCell { command: row.command.clone(), old });
}
RowAct::Reset => {
state.select_row(&row.command);
state.use_default(env, &row.command);
+24
View File
@@ -34,6 +34,13 @@ craft_ui::words! {
label_cycles: template "keyboardShortcuts.labelCycles" = "{label} (cycles)";
shares_a_shortcut: "keyboardShortcuts.sharesAShortcut" = "Shares a shortcut with another command";
label_changed: template "keyboardShortcuts.labelChanged" = "{label} (Changed)";
// Hold shortcuts.
hold_shortcuts: "keyboardShortcuts.holdShortcuts" = "Hold Shortcuts";
hold_delay: "keyboardShortcuts.holdDelay" = "Hold delay (seconds):";
hold_explanation: "keyboardShortcuts.holdExplanation" = "Hold down a key that types a character to use its command while the key is down; releasing the key goes back.";
hold_column: "keyboardShortcuts.holdColumn" = "Hold";
add_a_hold_shortcut_to_label: template "keyboardShortcuts.addAHoldShortcutToLabel" = "Add a hold shortcut to {label}";
not_holdable: template "keyboardShortcuts.notHoldable" = "{chord}: only a key that types a character, alone or with Shift, can be held";
// Table and detail pane.
command: "keyboardShortcuts.command" = "Command";
commands: "keyboardShortcuts.commands" = "Commands";
@@ -188,6 +195,23 @@ craft_ui::words! {
the_shortcuts_could_not_be_removed: "keyboardShortcuts.theShortcutsCouldNotBeRemoved" = "the shortcuts could not be removed";
copy_report: "keyboardShortcuts.copyReport" = "Copy Report";
done: "keyboardShortcuts.done" = "Done";
start_current: "keyboardShortcuts.startCurrent" = "Start from the current shortcuts";
start_defaults: "keyboardShortcuts.startDefaults" = "Start from the defaults";
include_entry: template "keyboardShortcuts.includeEntry" = "Import {item}";
search_entries: "keyboardShortcuts.searchEntries" = "Search entries";
no_equivalent: "keyboardShortcuts.noEquivalent" = "No equivalent";
not_read: "keyboardShortcuts.notRead" = "Not read";
keys_section: "keyboardShortcuts.keysSection" = "Keys";
record_a_key: "keyboardShortcuts.recordAKey" = "Record a Key";
press_a_key_without_modifiers: "keyboardShortcuts.pressAKeyWithoutModifiers" = "Press a key without modifiers";
undecided_key: template "keyboardShortcuts.undecidedKey" = "key code {n} is not known";
undecided_modifier: template "keyboardShortcuts.undecidedModifier" = "modifier code {n} is not known";
// The parts of a modifier combination the review composes.
mod_none: "keyboardShortcuts.modNone" = "No modifier";
mod_cmd: "keyboardShortcuts.modCmd" = "Cmd";
mod_ctrl: "keyboardShortcuts.modCtrl" = "Ctrl";
mod_alt: "keyboardShortcuts.modAlt" = "Alt";
mod_shift: "keyboardShortcuts.modShift" = "Shift";
// Why a `.kys` file is refused (`KysError`), and the tooltip of a saved text that is not a shortcut.
the_file_is_larger_than_a: "keyboardShortcuts.theFileIsLargerThanA" = "The file is larger than a keyboard shortcut set can be.";
the_file_is_not_a_photoshop: template "keyboardShortcuts.theFileIsNotAPhotoshop" = "The file is not a Photoshop keyboard shortcut set: {message}";
+85
View File
@@ -0,0 +1,85 @@
//! Hold shortcuts in the dialog: the switch, the Hold column, and what Cancel and OK leave of the setting.
use craft_keymap::{Binding, CommandRef, Platform, Policy};
use craft_menu::shortcuts::{HoldSetting, Outcome};
use craft_ui::contract::Role;
use craft_ui::testing::trial;
use egui::{Key, Modifiers};
use super::fixture::{self, Rig};
/// The setting a trial starts from, at a delay inside its range.
fn setting(on: bool) -> HoldSetting {
HoldSetting { on, delay: 0.5, range: 0.2..=2.0 }
}
/// The hold texts the keymap's overrides hold for the command `key`.
fn holds_of(rig: &Rig, key: &str) -> Vec<String> {
let shared = rig.shared.borrow();
shared.km.overrides().get(key).map(|texts| texts.iter().filter(|t| t.starts_with("Hold ")).cloned().collect()).unwrap_or_default()
}
/// Whether the message under the table says `part`.
fn says(rig: &Rig, part: &str) -> bool {
[Role::STATUS, Role::ALERT].into_iter().any(|role| !rig.names_with(role, part).is_empty())
}
#[trial]
fn the_hold_column_records_a_hold_and_cancel_restores_the_setting() {
let mut rig = Rig::with_holds(fixture::keymap(Platform::Mac), fixture::options(), setting(false));
assert!(!rig.has("Add a hold shortcut to Save"), "no Hold column while holds are off");
rig.click("Hold Shortcuts");
assert!(rig.shared.borrow().holds.as_ref().is_some_and(|h| h.on), "the switch turns the setting on");
assert!(rig.shared.borrow().km.holds(), "and the keymap's holds with it");
assert!(rig.has("Add a hold shortcut to Save"), "the Hold column shows");
rig.click("Add a hold shortcut to Save");
rig.press(Modifiers::NONE, Key::K);
assert_eq!(holds_of(&rig, "file.save"), ["Hold K"], "a letter recorded in the hold cell is a hold");
rig.click("Add a hold shortcut to Save");
rig.press(Modifiers::COMMAND, Key::K);
assert_eq!(holds_of(&rig, "file.save"), ["Hold K"], "Cmd+K cannot be held, so nothing is written");
assert!(says(&rig, "can be held"), "the refusal is said under the table");
let field = rig.find("Hold delay (seconds):");
rig.fixture.click(&field);
rig.press(Modifiers::COMMAND, Key::A);
rig.fixture.type_text("1.5");
rig.press(Modifiers::NONE, Key::Enter);
assert_eq!(rig.shared.borrow().holds.as_ref().map(|h| h.delay), Some(1.5), "the delay field edits the setting");
rig.click("Cancel");
{
let shared = rig.shared.borrow();
assert_eq!(shared.holds, Some(setting(false)), "Cancel puts the setting back, on and delay");
assert!(!shared.km.holds(), "and the keymap's holds");
assert!(shared.km.overrides().get("file.save").is_none(), "and drops the hold");
assert!(shared.outcomes.iter().any(|o| matches!(o, Outcome::Cancel)), "the dialog closed with Cancel");
}
let mut rig = Rig::with_holds(fixture::keymap(Platform::Mac), fixture::options(), setting(false));
rig.click("Hold Shortcuts");
rig.click("OK");
assert!(rig.has_outcome(|o| matches!(o, Outcome::Ok)), "the dialog closed with OK");
assert!(rig.shared.borrow().holds.as_ref().is_some_and(|h| h.on), "OK leaves the edited setting for the app to save");
assert!(rig.shared.borrow().km.holds(), "and the keymap's holds as the setting says");
}
/// The row cache is keyed on the overrides, which the switch does not change: the rows follow the switch all the
/// same.
#[trial]
fn toggling_holds_rebuilds_the_rows_and_the_keymap_view() {
let mut km = fixture::keymap(Platform::Mac);
km.set_holds(true);
km.assign(&CommandRef::from("file.save"), Binding::parse("Hold K").expect("a hold"), Policy::Keep).expect("assigns");
let mut rig = Rig::with_holds(km, fixture::options(), setting(true));
assert!(rig.has("Save: Hold K"), "the hold shows in Save's row");
rig.click("Hold Shortcuts");
assert!(!rig.has("Save: Hold K"), "switched off, the row shows no hold");
rig.click("Hold Shortcuts");
assert!(rig.has("Save: Hold K"), "switched on again, the hold is back");
}
+2
View File
@@ -1,6 +1,8 @@
//! The Keyboard Shortcuts dialog, driven pass by pass through `craft_ui::testing::Fixture`.
mod fixture;
mod hold;
mod import_offer;
mod recorder;
mod review;
mod rows;
mod sets;
+30
View File
@@ -4,6 +4,7 @@ use std::sync::Arc;
use craft_host::{AppInfo, Host};
use craft_keymap::{Binding, CommandDef, CommandRef, Keymap, Platform, Policy, Scope, Scopes};
use craft_menu::shortcuts::{HoldSetting, Outcome};
use craft_ui::contract::Role;
use craft_ui::testing::trial;
@@ -58,3 +59,32 @@ fn the_search_folds_dotted_capitals() {
assert_eq!(listed("ŞƏKİL ÖLÇÜSÜ"), (true, false), "capitals with the dotted İ");
assert_eq!(listed("IMAGE SIZE"), (true, false), "the English alias");
}
/// With holds on, Summarize… writes a hold binding in its command's line as its trigger text; with holds off the
/// summary leaves it out.
#[trial]
fn the_summary_lists_hold_bindings() {
let mut km = fixture::keymap(Platform::Mac);
km.set_holds(true);
km.assign(&CommandRef::from("file.save"), Binding::parse("Hold K").expect("a hold"), Policy::Keep).expect("assigns");
let mut rig = Rig::with_holds(km, fixture::options(), HoldSetting { on: true, delay: 0.5, range: 0.2..=2.0 });
let summarize = |rig: &mut Rig| {
rig.click("Summarize…");
rig.outcomes()
.into_iter()
.rev()
.find_map(|o| match o {
Outcome::Summary { text, html, .. } => Some((text, html)),
_ => None,
})
.expect("a summary")
};
let (text, html) = summarize(&mut rig);
assert!(text.lines().any(|line| line.contains("Save") && line.contains("Hold K")), "Save's line has its hold: {text}");
assert!(html.contains("Hold K"), "the HTML has the hold: {html}");
rig.click("Hold Shortcuts");
let (text, html) = summarize(&mut rig);
assert!(!text.contains("Hold K") && !html.contains("Hold K"), "with holds off the summary has no hold: {text}");
}