Skip to main content

egui_pop_core/
strings.rs

1//! The strings egui-pop shows (Cancel, Retry, accessibility
2//! descriptions, the titles of what plugins declare), by key with English
3//! fallbacks. An application installs a [`Strings`] provider (the
4//! `egui-pop-i18n` plugin, for instance); without one, the fallbacks are
5//! used.
6//!
7//! Keys are Fluent message ids, with an optional attribute
8//! (`egui-pop-retry`, `command-app-quit.title`), so a provider can read
9//! them from `.ftl` catalogues as they are. Placeholders are written as
10//! Fluent writes them, `{ $name }`, and filled by [`tr_args`] with text
11//! kept as given (a folder named "2026" stays "2026"), or by [`tr_with`]
12//! with typed [`Arg`]s, where a number ([`Arg::Num`]) is written as the
13//! language writes numbers ("1,234", "1 234").
14//!
15//! What plugins declare (commands, panels, menus, settings, plugins,
16//! the context stack's frames) is
17//! translated through keys derived from its stable id, never from its
18//! English, so rewording English keeps the translations:
19//!
20//! | What | Key |
21//! |---|---|
22//! | a command's title, description | `command-<id>.title`, `.description` |
23//! | a command's category | `category-<english>` (categories have no id) |
24//! | a panel's title | `panel-<id>.title` |
25//! | a submenu's label | `menu-<id>.label` |
26//! | a setting's label, description | `setting-<id>.label`, `.description` |
27//! | one value of a choice setting | `setting-<id>-choice-<value>` |
28//! | a plugin's title (a settings section) | `plugin-<id>.title` |
29//! | a frame's title (a crumb, a mode chip) | `frame-<id>.title` |
30//!
31//! where every id is written with [`slug`] (a category's English in
32//! lower case).
33//!
34//! ```
35//! use std::sync::Arc;
36//! use egui_pop_core::strings::{self, MapStrings, RETRY};
37//!
38//! let ctx = egui::Context::default();
39//! assert_eq!(strings::tr(&ctx, &RETRY), "Retry");
40//! strings::install(&ctx, Arc::new(MapStrings::new("fr").with(RETRY.key, "Réessayer")));
41//! assert_eq!(strings::tr(&ctx, &RETRY), "Réessayer");
42//! assert_eq!(strings::command_title(&ctx, "app.quit", "Quit"), "Quit");
43//! ```
44
45use std::collections::BTreeMap;
46use std::sync::Arc;
47
48use egui::Context;
49
50use crate::state::Slot;
51
52/// A string's key and its English fallback. `{ $name }` placeholders are
53/// filled by [`tr_args`].
54#[derive(Clone, Copy, Debug, PartialEq, Eq)]
55pub struct StrKey {
56    pub key: &'static str,
57    pub fallback: &'static str,
58}
59
60impl StrKey {
61    pub const fn new(key: &'static str, fallback: &'static str) -> Self {
62        Self { key, fallback }
63    }
64}
65
66pub const OK: StrKey = StrKey::new("egui-pop-ok", "OK");
67pub const CANCEL: StrKey = StrKey::new("egui-pop-cancel", "Cancel");
68pub const CLOSE: StrKey = StrKey::new("egui-pop-close", "Close");
69pub const RESET: StrKey = StrKey::new("egui-pop-reset", "Reset");
70pub const RETRY: StrKey = StrKey::new("egui-pop-retry", "Retry");
71pub const SCROLLABLE_CONTENT: StrKey =
72    StrKey::new("egui-pop-scrollable-content", "Scrollable content");
73pub const FAULT_TITLE: StrKey = StrKey::new("egui-pop-fault-title", "{ $name } stopped working");
74pub const FAULT_BODY: StrKey = StrKey::new(
75    "egui-pop-fault-body",
76    "The rest of the application is fine. Retry, or report the message below.",
77);
78pub const HELD_BY: StrKey = StrKey::new("egui-pop-value-held-by", "Being changed by { $origin }");
79pub const READ_ONLY: StrKey = StrKey::new("egui-pop-value-read-only", "Read only");
80/// A bound widget's tooltip when its path holds no value.
81pub const NO_VALUE: StrKey = StrKey::new("egui-pop-value-missing", "no value at `{ $path }`");
82/// The window frame's buttons (the close button says [`CLOSE`]).
83pub const MINIMIZE: StrKey = StrKey::new("egui-pop-frame-minimize", "Minimize");
84pub const MAXIMIZE: StrKey = StrKey::new("egui-pop-frame-maximize", "Maximize");
85pub const RESTORE: StrKey = StrKey::new("egui-pop-frame-restore", "Restore");
86/// A full screen window's button in place of maximize.
87pub const EXIT_FULLSCREEN: StrKey =
88    StrKey::new("egui-pop-frame-exit-fullscreen", "Exit full screen");
89/// A slider's typed entry, open over its bar, as assistive technologies
90/// name it.
91pub const SLIDER_ENTRY: StrKey = StrKey::new("egui-pop-slider-entry", "{ $label }, typed value");
92/// A range slider's thumbs, as assistive technologies name them.
93pub const SLIDER_MINIMUM: StrKey = StrKey::new("egui-pop-slider-minimum", "{ $label }, minimum");
94pub const SLIDER_MAXIMUM: StrKey = StrKey::new("egui-pop-slider-maximum", "{ $label }, maximum");
95/// A slider's or a knob's menu item opening its typed entry.
96pub const SLIDER_TYPE_VALUE: StrKey = StrKey::new("egui-pop-slider-type-value", "Type a value");
97/// A number input's arrows, as assistive technologies name them.
98pub const NUMBER_INCREASE: StrKey = StrKey::new("egui-pop-number-increase", "Increase { $label }");
99pub const NUMBER_DECREASE: StrKey = StrKey::new("egui-pop-number-decrease", "Decrease { $label }");
100/// Why a number input refused a typed value.
101pub const NUMBER_NOT_A_NUMBER: StrKey = StrKey::new("egui-pop-number-not-a-number", "Not a number");
102pub const NUMBER_WHOLE: StrKey = StrKey::new("egui-pop-number-whole", "A whole number is expected");
103pub const NUMBER_OUT_OF_RANGE: StrKey = StrKey::new(
104    "egui-pop-number-out-of-range",
105    "Between { $min } and { $max }",
106);
107
108/// A busy indicator without a label of its own.
109pub const BUSY: StrKey = StrKey::new("egui-pop-busy", "Busy");
110/// A skeleton standing in for content that loads.
111pub const LOADING: StrKey = StrKey::new("egui-pop-loading", "Loading");
112/// A late value's placeholder, its spinner and its Retry button, as
113/// assistive technologies name them.
114pub const LATE_LOADING: StrKey = StrKey::new("egui-pop-late-loading", "Loading { $name }");
115pub const LATE_UPDATING: StrKey = StrKey::new("egui-pop-late-updating", "Updating { $name }");
116pub const LATE_RETRY: StrKey = StrKey::new("egui-pop-late-retry", "Retry { $name }");
117
118/// What an indicator means, when the application gives it no name of
119/// its own: an LED's state, a flag, a pip, a swatch.
120pub const INDICATOR_OFF: StrKey = StrKey::new("egui-pop-indicator-off", "Off");
121pub const INDICATOR_ON: StrKey = StrKey::new("egui-pop-indicator-on", "On");
122pub const INDICATOR_WARNING: StrKey = StrKey::new("egui-pop-indicator-warning", "Warning");
123pub const INDICATOR_ERROR: StrKey = StrKey::new("egui-pop-indicator-error", "Error");
124pub const INDICATOR_MODIFIED: StrKey = StrKey::new("egui-pop-indicator-modified", "Modified");
125pub const INDICATOR_PINNED: StrKey = StrKey::new("egui-pop-indicator-pinned", "Pinned");
126pub const INDICATOR_REQUIRED: StrKey = StrKey::new("egui-pop-indicator-required", "Required");
127pub const INDICATOR_INVALID: StrKey = StrKey::new("egui-pop-indicator-invalid", "Invalid");
128pub const INDICATOR_DONE: StrKey = StrKey::new("egui-pop-indicator-done", "Done");
129pub const INDICATOR_FAILED: StrKey = StrKey::new("egui-pop-indicator-failed", "Failed");
130pub const INDICATOR_PERCENT: StrKey = StrKey::new("egui-pop-indicator-percent", "{ $percent }%");
131pub const INDICATOR_NO_COLOR: StrKey = StrKey::new("egui-pop-indicator-no-color", "No colour");
132pub const INDICATOR_MIXED: StrKey = StrKey::new("egui-pop-indicator-mixed", "Mixed");
133/// A value's marks (`indicator::ValueMark`).
134pub const INDICATOR_CHANGED: StrKey =
135    StrKey::new("egui-pop-indicator-changed", "Changed from its default");
136pub const INDICATOR_HELD: StrKey = StrKey::new("egui-pop-indicator-held", "Held by { $by }");
137pub const INDICATOR_MOVED: StrKey = StrKey::new("egui-pop-indicator-moved", "Moved by { $by }");
138/// A decorated input's clear button.
139pub const INPUT_CLEAR: StrKey = StrKey::new("egui-pop-input-clear", "Clear { $label }");
140/// A decorated input's dropdown chevron.
141pub const INPUT_CHOICES: StrKey = StrKey::new("egui-pop-input-choices", "{ $label }, choices");
142/// A split button's chevron.
143pub const INPUT_MORE: StrKey = StrKey::new("egui-pop-input-more", "{ $label }, more");
144/// The boundary between two sections of a stack, named after the one
145/// above it (`sections::Sections`).
146pub const SECTION_RESIZE: StrKey = StrKey::new("egui-pop-section-resize", "Resize { $section }");
147/// A tree row's toggle, named after its row (`fold::TreeRow`).
148pub const FOLD_TOGGLE: StrKey = StrKey::new("egui-pop-fold-toggle", "Show or hide { $item }");
149pub const DIALOG_RESIZE: StrKey = StrKey::new("egui-pop-dialog-resize", "Resize { $dialog }");
150/// A field's states, as markers and assistive technologies say them.
151pub const FIELD_REQUIRED: StrKey = StrKey::new("egui-pop-field-required", "Required");
152pub const FIELD_MODIFIED_SAVED: StrKey =
153    StrKey::new("egui-pop-field-modified-saved", "Changed since saved");
154pub const FIELD_MODIFIED_DEFAULT: StrKey = StrKey::new(
155    "egui-pop-field-modified-default",
156    "Changed from the default",
157);
158pub const FIELD_RESET: StrKey = StrKey::new("egui-pop-field-reset", "Reset { $label } to default");
159pub const FIELD_PENDING: StrKey = StrKey::new("egui-pop-field-pending", "Being checked");
160pub const FIELD_DISABLED: StrKey =
161    StrKey::new("egui-pop-field-disabled", "Unavailable: { $reason }");
162/// Rating stars' accessible name (`rating::RatingStars`).
163pub const RATING: StrKey = StrKey::new("egui-pop-rating", "Rating");
164/// A rating as read aloud, and a shown rating's name: "3 of 5".
165pub const RATING_VALUE: StrKey = StrKey::new("egui-pop-rating-value", "{ $stars } of 5");
166/// A star's tooltip and name: what a click on it gives.
167pub const RATING_SET: StrKey = StrKey::new("egui-pop-rating-set", "Set { $stars } of 5");
168/// The tooltip and name of the star of the current rating: a click clears it.
169pub const RATING_CLEAR: StrKey = StrKey::new("egui-pop-rating-clear", "Clear rating");
170/// A segmented control's button holding the options that do not fit.
171pub const SEGMENTED_MORE: StrKey =
172    StrKey::new("egui-pop-segmented-more", "More choices: { $control }");
173/// A note's Copy button: its name and tooltip.
174pub const NOTE_COPY: StrKey = StrKey::new("egui-pop-note-copy", "Copy");
175/// Said beside a note's Copy button for a moment after a click.
176pub const NOTE_COPIED: StrKey = StrKey::new("egui-pop-note-copied", "Copied.");
177/// The title of a note's folded technical details.
178pub const NOTE_DETAILS: StrKey = StrKey::new("egui-pop-note-details", "Details");
179/// The name and tooltip of an information note's symbol.
180pub const NOTE_INFO: StrKey = StrKey::new("egui-pop-note-info", "Information");
181/// The name and tooltip of a success note's symbol.
182pub const NOTE_SUCCESS: StrKey = StrKey::new("egui-pop-note-success", "Success");
183/// The name and tooltip of a warning note's symbol.
184pub const NOTE_WARNING: StrKey = StrKey::new("egui-pop-note-warning", "Warning");
185/// The name and tooltip of an error note's symbol.
186pub const NOTE_ERROR: StrKey = StrKey::new("egui-pop-note-error", "Error");
187
188/// Every string egui-pop core shows, for catalogues and tests.
189pub const ALL: &[StrKey] = &[
190    OK,
191    CANCEL,
192    CLOSE,
193    RESET,
194    RETRY,
195    SCROLLABLE_CONTENT,
196    FAULT_TITLE,
197    FAULT_BODY,
198    HELD_BY,
199    READ_ONLY,
200    NO_VALUE,
201    MINIMIZE,
202    MAXIMIZE,
203    RESTORE,
204    EXIT_FULLSCREEN,
205    SLIDER_ENTRY,
206    SLIDER_MINIMUM,
207    SLIDER_MAXIMUM,
208    SLIDER_TYPE_VALUE,
209    NUMBER_INCREASE,
210    NUMBER_DECREASE,
211    NUMBER_NOT_A_NUMBER,
212    NUMBER_WHOLE,
213    NUMBER_OUT_OF_RANGE,
214    BUSY,
215    LOADING,
216    LATE_LOADING,
217    LATE_UPDATING,
218    LATE_RETRY,
219    INDICATOR_OFF,
220    INDICATOR_ON,
221    INDICATOR_WARNING,
222    INDICATOR_ERROR,
223    INDICATOR_MODIFIED,
224    INDICATOR_PINNED,
225    INDICATOR_REQUIRED,
226    INDICATOR_INVALID,
227    INDICATOR_DONE,
228    INDICATOR_FAILED,
229    INDICATOR_PERCENT,
230    INDICATOR_NO_COLOR,
231    INDICATOR_MIXED,
232    INDICATOR_CHANGED,
233    INDICATOR_HELD,
234    INDICATOR_MOVED,
235    INPUT_CLEAR,
236    INPUT_CHOICES,
237    INPUT_MORE,
238    SECTION_RESIZE,
239    FOLD_TOGGLE,
240    DIALOG_RESIZE,
241    FIELD_REQUIRED,
242    FIELD_MODIFIED_SAVED,
243    FIELD_MODIFIED_DEFAULT,
244    FIELD_RESET,
245    FIELD_PENDING,
246    FIELD_DISABLED,
247    RATING,
248    RATING_VALUE,
249    RATING_SET,
250    RATING_CLEAR,
251    SEGMENTED_MORE,
252    NOTE_COPY,
253    NOTE_COPIED,
254    NOTE_DETAILS,
255    NOTE_INFO,
256    NOTE_SUCCESS,
257    NOTE_WARNING,
258    NOTE_ERROR,
259];
260
261/// A value placed in a `{ $name }` placeholder.
262///
263/// Text is placed as it is, even when it looks like a number (a folder
264/// named "2026", a file named "1e3"); a number is written as the
265/// language writes numbers, its thousands grouped, and selects a plural
266/// form in a catalogue. Built with `into()` from text or a number.
267#[derive(Clone, Copy, Debug, PartialEq)]
268pub enum Arg<'a> {
269    /// Text, placed verbatim.
270    Str(&'a str),
271    /// A number, formatted for the language.
272    Num(f64),
273}
274
275impl<'a> From<&'a str> for Arg<'a> {
276    fn from(s: &'a str) -> Self {
277        Arg::Str(s)
278    }
279}
280
281impl<'a> From<&'a String> for Arg<'a> {
282    fn from(s: &'a String) -> Self {
283        Arg::Str(s)
284    }
285}
286
287macro_rules! arg_from_number {
288    ($($t:ty),*) => {$(
289        impl From<$t> for Arg<'_> {
290            fn from(n: $t) -> Self {
291                Arg::Num(n as f64)
292            }
293        }
294    )*};
295}
296arg_from_number!(f64, f32, usize, isize, u8, u16, u32, u64, i8, i16, i32, i64);
297
298impl Arg<'_> {
299    /// The value as plain text: text as it is, a number as Rust writes
300    /// it (`1234`, `0.5`), for a provider with no number formatting.
301    pub fn plain(&self) -> String {
302        match self {
303            Arg::Str(s) => (*s).to_string(),
304            Arg::Num(n) => n.to_string(),
305        }
306    }
307}
308
309/// Text arguments as [`Arg::Str`].
310fn text_args<'a>(args: &[(&'a str, &'a str)]) -> Vec<(&'a str, Arg<'a>)> {
311    args.iter().map(|(k, v)| (*k, Arg::Str(v))).collect()
312}
313
314/// Gives the text of a key in the current language, if it has one.
315pub trait Strings: Send + Sync {
316    /// The text for a key; `None` falls back to English.
317    fn get(&self, key: &str) -> Option<String>;
318
319    /// The text for a key with its arguments placed; `None` falls back
320    /// to English. By default [`Strings::get`] with its `{ $name }`
321    /// placeholders filled; a provider formatting its own (plurals,
322    /// numbers) overrides it.
323    ///
324    /// Text arguments ([`Arg::Str`]) are placed verbatim; only numbers
325    /// ([`Arg::Num`]) may be formatted.
326    fn get_args(&self, key: &str, args: &[(&str, Arg<'_>)]) -> Option<String> {
327        self.get(key).map(|t| fill_with(&t, args))
328    }
329
330    /// The language, as a BCP 47 tag.
331    fn language(&self) -> &str {
332        "en"
333    }
334
335    /// A number as the language writes it, with exactly `decimals`
336    /// digits after the separator and its thousands grouped; `None`
337    /// writes it as Rust does (`1234.50`). A provider that knows the
338    /// locale's separators overrides it.
339    fn number(&self, value: f64, decimals: usize) -> Option<String> {
340        let _ = (value, decimals);
341        None
342    }
343
344    /// A number already written (by [`Strings::number`]) followed by its
345    /// unit (`EV`, `px`, `%`), with the space the language puts between
346    /// them: French puts a narrow no-break space. `None` puts a plain
347    /// space, as English does.
348    fn quantity(&self, number: &str, unit: &str) -> Option<String> {
349        let _ = (number, unit);
350        None
351    }
352}
353
354/// No translations: every string is its English fallback.
355#[derive(Clone, Copy, Debug, Default)]
356pub struct English;
357
358impl Strings for English {
359    fn get(&self, _key: &str) -> Option<String> {
360        None
361    }
362}
363
364/// Translations from a map, for tests and small applications.
365#[derive(Clone, Debug, Default)]
366pub struct MapStrings {
367    language: String,
368    map: BTreeMap<String, String>,
369}
370
371impl MapStrings {
372    pub fn new(language: &str) -> Self {
373        Self {
374            language: language.into(),
375            map: BTreeMap::new(),
376        }
377    }
378
379    pub fn with(mut self, key: &str, text: &str) -> Self {
380        self.map.insert(key.into(), text.into());
381        self
382    }
383}
384
385impl Strings for MapStrings {
386    fn get(&self, key: &str) -> Option<String> {
387        self.map.get(key).cloned()
388    }
389
390    fn language(&self) -> &str {
391        &self.language
392    }
393}
394
395/// The installed provider.
396const PROVIDER: Slot<Arc<dyn Strings>> = Slot::opaque("core.strings.provider");
397
398/// Installs a provider for a context.
399pub fn install(ctx: &Context, strings: Arc<dyn Strings>) {
400    PROVIDER.set(ctx, strings);
401}
402
403/// Which provider is installed, as an identity that changes when another
404/// one is installed (`None`: the built-in English). A cache of translated
405/// texts keys on it.
406pub fn provider_id(ctx: &Context) -> Option<usize> {
407    PROVIDER
408        .get(ctx)
409        .map(|s| Arc::as_ptr(&s).cast::<()>() as usize)
410}
411
412/// The installed provider (English when none is).
413pub fn provider(ctx: &Context) -> Arc<dyn Strings> {
414    PROVIDER.get(ctx).unwrap_or_else(|| Arc::new(English))
415}
416
417/// A number in the interface's language, with exactly `decimals` digits
418/// after the separator (slider values, readouts):
419/// [`Strings::number`], else as Rust writes it.
420///
421/// ```
422/// assert_eq!(egui_pop_core::strings::number(&egui::Context::default(), 1234.5, 2), "1234.50");
423/// ```
424pub fn number(ctx: &Context, value: f64, decimals: usize) -> String {
425    provider(ctx)
426        .number(value, decimals)
427        .unwrap_or_else(|| format!("{value:.decimals$}"))
428}
429
430/// A number already written followed by its unit, in the interface's
431/// language: [`Strings::quantity`], else with a plain space between
432/// them. An empty unit gives the number alone.
433///
434/// ```
435/// let ctx = egui::Context::default();
436/// assert_eq!(egui_pop_core::strings::quantity(&ctx, "1.50", "EV"), "1.50 EV");
437/// assert_eq!(egui_pop_core::strings::quantity(&ctx, "3", ""), "3");
438/// ```
439pub fn quantity(ctx: &Context, number: &str, unit: &str) -> String {
440    if unit.is_empty() {
441        return number.to_string();
442    }
443    provider(ctx)
444        .quantity(number, unit)
445        .unwrap_or_else(|| format!("{number} {unit}"))
446}
447
448/// The English shown when a provider has nothing: the fallback, else
449/// the key itself.
450fn english(key: &str, fallback: &str) -> String {
451    if fallback.is_empty() {
452        key.to_string()
453    } else {
454        fallback.to_string()
455    }
456}
457
458/// The text of a key.
459pub fn tr(ctx: &Context, key: &StrKey) -> String {
460    lookup(ctx, key.key, key.fallback)
461}
462
463/// The text of a key with its `{ $name }` placeholders filled with
464/// text, placed verbatim even when it looks like a number. A count or a
465/// size to write as the language writes numbers goes through
466/// [`tr_with`].
467pub fn tr_args(ctx: &Context, key: &StrKey, args: &[(&str, &str)]) -> String {
468    lookup_args(ctx, key.key, key.fallback, args)
469}
470
471/// The text of a key with its `{ $name }` placeholders filled with typed
472/// arguments: text verbatim, numbers formatted for the language.
473///
474/// ```
475/// use egui_pop_core::strings::{self, StrKey};
476///
477/// const OPENED: StrKey = StrKey::new("opened", "{ $folder }: { $count } items");
478/// let ctx = egui::Context::default();
479/// let text = strings::tr_with(&ctx, &OPENED, &[("folder", "2026".into()), ("count", 3.into())]);
480/// assert_eq!(text, "2026: 3 items");
481/// ```
482pub fn tr_with(ctx: &Context, key: &StrKey, args: &[(&str, Arg<'_>)]) -> String {
483    lookup_with(ctx, key.key, key.fallback, args)
484}
485
486/// The text of any key, with the English to show without a translation
487/// (the key itself when `fallback` is empty).
488pub fn lookup(ctx: &Context, key: &str, fallback: &str) -> String {
489    provider(ctx)
490        .get(key)
491        .unwrap_or_else(|| english(key, fallback))
492}
493
494/// [`lookup`] with text arguments, placed verbatim.
495pub fn lookup_args(ctx: &Context, key: &str, fallback: &str, args: &[(&str, &str)]) -> String {
496    lookup_with(ctx, key, fallback, &text_args(args))
497}
498
499/// [`lookup`] with typed arguments (see [`tr_with`]).
500pub fn lookup_with(ctx: &Context, key: &str, fallback: &str, args: &[(&str, Arg<'_>)]) -> String {
501    provider(ctx)
502        .get_args(key, args)
503        .unwrap_or_else(|| fill_with(&english(key, fallback), args))
504}
505
506/// Fills `{ $name }` (and `{$name}`) placeholders with text.
507pub fn fill(text: &str, args: &[(&str, &str)]) -> String {
508    fill_with(text, &text_args(args))
509}
510
511/// Fills `{ $name }` (and `{$name}`) placeholders with typed arguments,
512/// numbers written plain ([`Arg::plain`]).
513pub fn fill_with(text: &str, args: &[(&str, Arg<'_>)]) -> String {
514    let mut text = text.to_string();
515    for (name, value) in args {
516        let value = value.plain();
517        text = text
518            .replace(&format!("{{ ${name} }}"), &value)
519            .replace(&format!("{{${name}}}"), &value);
520    }
521    text
522}
523
524/// A stable id written as part of a Fluent identifier: ASCII letters,
525/// digits and `-` are kept, every other character becomes `-`
526/// (`app.quit` gives `app-quit`). Two ids that differ only by those
527/// characters share a key.
528pub fn slug(id: &str) -> String {
529    id.chars()
530        .map(|c| {
531            if c.is_ascii_alphanumeric() || c == '-' {
532                c
533            } else {
534                '-'
535            }
536        })
537        .collect()
538}
539
540/// The kinds of declarations translated by derived keys.
541pub mod kind {
542    pub const COMMAND: &str = "command";
543    pub const CATEGORY: &str = "category";
544    pub const PANEL: &str = "panel";
545    pub const MENU: &str = "menu";
546    pub const SETTING: &str = "setting";
547    pub const PLUGIN: &str = "plugin";
548    /// A frame of the context stack: a place or a mode.
549    pub const FRAME: &str = "frame";
550    /// A type of clipboard item (its title: "a colour").
551    pub const CLIP: &str = "clip";
552}
553
554/// The key of a declaration's text: `<kind>-<slug(id)>`, then
555/// `.<attr>` when given.
556pub fn declared_key(kind: &str, id: &str, attr: Option<&str>) -> String {
557    match attr {
558        Some(a) => format!("{kind}-{}.{a}", slug(id)),
559        None => format!("{kind}-{}", slug(id)),
560    }
561}
562
563/// A declaration's text in the current language, else its English.
564pub fn declared(ctx: &Context, kind: &str, id: &str, attr: Option<&str>, english: &str) -> String {
565    lookup(ctx, &declared_key(kind, id, attr), english)
566}
567
568/// A command derived from a panel (`<panel>.focus`, `<panel>.toggle`):
569/// its title and description are shared texts with a `{ $panel }`
570/// placeholder, filled with the panel's title in the interface's
571/// language, so a catalogue translates them once for every panel. A
572/// translation under the command's own keys still wins.
573#[derive(Clone, Debug, PartialEq)]
574pub struct PanelCommand {
575    pub title: StrKey,
576    pub description: StrKey,
577    /// The panel's id.
578    pub panel: String,
579    /// The panel's English title.
580    pub panel_title: String,
581}
582
583/// The commands derived from panels, by command id.
584pub type PanelCommands = Arc<BTreeMap<String, PanelCommand>>;
585
586const PANEL_COMMANDS: Slot<PanelCommands> = Slot::new("core.strings.panel_commands");
587
588/// Installs the commands derived from panels for a context (see
589/// [`PanelCommand`]); the application does it for each context it is
590/// drawn in.
591pub fn set_panel_commands(ctx: &Context, commands: PanelCommands) {
592    PANEL_COMMANDS.set(ctx, commands);
593}
594
595/// The commands derived from panels installed for a context.
596pub fn panel_commands(ctx: &Context) -> Option<PanelCommands> {
597    PANEL_COMMANDS.get(ctx)
598}
599
600/// The panel a command is derived from, with its shared texts.
601pub fn panel_command(ctx: &Context, command: &str) -> Option<PanelCommand> {
602    panel_commands(ctx).and_then(|m| m.get(command).cloned())
603}
604
605/// A panel command's text: its own key when translated, else the shared
606/// text, `{ $panel }` filled.
607fn panel_command_text(
608    ctx: &Context,
609    id: &str,
610    attr: &str,
611    shared: &StrKey,
612    p: &PanelCommand,
613) -> String {
614    let panel = panel_title(ctx, &p.panel, &p.panel_title);
615    let args = [("panel", Arg::Str(&panel))];
616    provider(ctx)
617        .get_args(&declared_key(kind::COMMAND, id, Some(attr)), &args)
618        .unwrap_or_else(|| tr_with(ctx, shared, &args))
619}
620
621const APPLICATION: Slot<String> = Slot::new("core.strings.application");
622
623/// Sets the application's name for a context: what `{ $application }`
624/// says in a command's title ("About { $application }"). The
625/// application does it for each context it is drawn in.
626pub fn set_application(ctx: &Context, name: &str) {
627    if APPLICATION.get(ctx).as_deref() != Some(name) {
628        APPLICATION.set(ctx, name.to_string());
629    }
630}
631
632/// The application's name set for a context (empty when none was).
633pub fn application(ctx: &Context) -> String {
634    APPLICATION.get(ctx).unwrap_or_default()
635}
636
637/// A command's title. A title saying `{ $application }` (in English or
638/// in its translation) has it filled with the application's name
639/// ([`set_application`]).
640///
641/// ```
642/// use egui_pop_core::strings;
643///
644/// let ctx = egui::Context::default();
645/// strings::set_application(&ctx, "Helios");
646/// assert_eq!(strings::command_title(&ctx, "about", "About { $application }"), "About Helios");
647/// ```
648pub fn command_title(ctx: &Context, id: &str, english: &str) -> String {
649    if let Some(p) = panel_command(ctx, id) {
650        return panel_command_text(ctx, id, "title", &p.title, &p);
651    }
652    let name = application(ctx);
653    lookup_args(
654        ctx,
655        &declared_key(kind::COMMAND, id, Some("title")),
656        english,
657        &[("application", &name)],
658    )
659}
660
661/// A command's title as a menu, a toolbar or a tray shows it: without the
662/// trailing hint of its arguments (``Open a workspace (`path`)`` reads
663/// `Open a workspace`), which only the palette, where arguments are
664/// typed, keeps. It works on a translated title as on the English one.
665///
666/// ```
667/// use egui_pop_core::strings::without_argument_hint;
668///
669/// assert_eq!(without_argument_hint("Open a workspace (`path`)"), "Open a workspace");
670/// assert_eq!(without_argument_hint("Ouvrir (`chemin` : un dossier)"), "Ouvrir");
671/// assert_eq!(without_argument_hint("Zoom (fit)"), "Zoom (fit)");
672/// ```
673pub fn without_argument_hint(title: &str) -> &str {
674    match title.find(" (`") {
675        Some(i) if title.ends_with(')') => &title[..i],
676        _ => title,
677    }
678}
679
680/// A command's description (empty stays empty).
681pub fn command_description(ctx: &Context, id: &str, english: &str) -> String {
682    if english.is_empty() {
683        return String::new();
684    }
685    if let Some(p) = panel_command(ctx, id) {
686        return panel_command_text(ctx, id, "description", &p.description, &p);
687    }
688    declared(ctx, kind::COMMAND, id, Some("description"), english)
689}
690
691/// The key of a command category, derived from its English (categories
692/// have no id).
693pub fn category_key(english: &str) -> String {
694    declared_key(kind::CATEGORY, &english.to_lowercase(), None)
695}
696
697/// A command category.
698pub fn category(ctx: &Context, english: &str) -> String {
699    lookup(ctx, &category_key(english), english)
700}
701
702/// A panel's title.
703pub fn panel_title(ctx: &Context, id: &str, english: &str) -> String {
704    declared(ctx, kind::PANEL, id, Some("title"), english)
705}
706
707/// A submenu's label.
708pub fn menu_label(ctx: &Context, id: &str, english: &str) -> String {
709    declared(ctx, kind::MENU, id, Some("label"), english)
710}
711
712/// A setting's label.
713pub fn setting_label(ctx: &Context, id: &str, english: &str) -> String {
714    declared(ctx, kind::SETTING, id, Some("label"), english)
715}
716
717/// A setting's description (empty stays empty).
718pub fn setting_description(ctx: &Context, id: &str, english: &str) -> String {
719    if english.is_empty() {
720        return String::new();
721    }
722    declared(ctx, kind::SETTING, id, Some("description"), english)
723}
724
725/// The key of one value of a choice setting.
726pub fn setting_choice_key(id: &str, value: &str) -> String {
727    format!(
728        "{}-choice-{}",
729        declared_key(kind::SETTING, id, None),
730        slug(value)
731    )
732}
733
734/// One value of a choice setting, as shown (the value itself without a
735/// translation).
736pub fn setting_choice(ctx: &Context, id: &str, value: &str) -> String {
737    lookup(ctx, &setting_choice_key(id, value), value)
738}
739
740/// A plugin's title (the settings form's section).
741pub fn plugin_title(ctx: &Context, id: &str, english: &str) -> String {
742    declared(ctx, kind::PLUGIN, id, Some("title"), english)
743}
744
745/// A frame's title (a place's crumb, a mode's chip): `frame-<id>.title`.
746pub fn frame_title(ctx: &Context, id: &str, english: &str) -> String {
747    declared(ctx, kind::FRAME, id, Some("title"), english)
748}
749
750#[cfg(test)]
751mod tests {
752    use super::*;
753
754    #[test]
755    fn derived_keys_are_fluent_ids() {
756        assert_eq!(
757            declared_key(kind::COMMAND, "app.quit", Some("title")),
758            "command-app-quit.title"
759        );
760        assert_eq!(
761            setting_choice_key("appearance.focus", "hover"),
762            "setting-appearance-focus-choice-hover"
763        );
764        assert_eq!(category_key("View"), "category-view");
765        assert_eq!(slug("a b/é_c"), "a-b---c");
766    }
767
768    #[test]
769    fn every_key_is_a_unique_fluent_id() {
770        let mut seen = std::collections::BTreeSet::new();
771        for k in ALL {
772            assert!(seen.insert(k.key), "`{}` twice", k.key);
773            assert!(k.key.starts_with("egui-pop-"), "{}", k.key);
774            assert!(
775                k.key
776                    .chars()
777                    .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-'),
778                "{}",
779                k.key
780            );
781        }
782    }
783
784    #[test]
785    fn a_missing_text_shows_english_then_the_key() {
786        let ctx = Context::default();
787        assert_eq!(lookup(&ctx, "nowhere", ""), "nowhere");
788        assert_eq!(lookup(&ctx, "nowhere", "Here"), "Here");
789        assert_eq!(
790            lookup_args(&ctx, "k", "Hi { $who }, {$who}", &[("who", "Ada")]),
791            "Hi Ada, Ada"
792        );
793        assert_eq!(category(&ctx, "View"), "View");
794        assert_eq!(command_description(&ctx, "x", ""), "");
795    }
796
797    #[test]
798    fn only_a_trailing_argument_hint_is_stripped() {
799        assert_eq!(without_argument_hint("Open (`path`)"), "Open");
800        assert_eq!(without_argument_hint("Open (`a`, `b` (opt))"), "Open");
801        assert_eq!(
802            without_argument_hint("Open (`path`) now"),
803            "Open (`path`) now"
804        );
805        assert_eq!(without_argument_hint("Fit (100%)"), "Fit (100%)");
806        assert_eq!(without_argument_hint("(`x`)"), "(`x`)");
807        assert_eq!(without_argument_hint(""), "");
808    }
809}