1use std::collections::BTreeMap;
46use std::sync::Arc;
47
48use egui::Context;
49
50use crate::state::Slot;
51
52#[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");
80pub const NO_VALUE: StrKey = StrKey::new("egui-pop-value-missing", "no value at `{ $path }`");
82pub 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");
86pub const EXIT_FULLSCREEN: StrKey =
88 StrKey::new("egui-pop-frame-exit-fullscreen", "Exit full screen");
89pub const SLIDER_ENTRY: StrKey = StrKey::new("egui-pop-slider-entry", "{ $label }, typed value");
92pub 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");
95pub const SLIDER_TYPE_VALUE: StrKey = StrKey::new("egui-pop-slider-type-value", "Type a value");
97pub 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 }");
100pub 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
108pub const BUSY: StrKey = StrKey::new("egui-pop-busy", "Busy");
110pub const LOADING: StrKey = StrKey::new("egui-pop-loading", "Loading");
112pub 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
118pub 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");
133pub 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 }");
138pub const INPUT_CLEAR: StrKey = StrKey::new("egui-pop-input-clear", "Clear { $label }");
140pub const INPUT_CHOICES: StrKey = StrKey::new("egui-pop-input-choices", "{ $label }, choices");
142pub const INPUT_MORE: StrKey = StrKey::new("egui-pop-input-more", "{ $label }, more");
144pub const SECTION_RESIZE: StrKey = StrKey::new("egui-pop-section-resize", "Resize { $section }");
147pub 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 }");
150pub 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 }");
162pub const RATING: StrKey = StrKey::new("egui-pop-rating", "Rating");
164pub const RATING_VALUE: StrKey = StrKey::new("egui-pop-rating-value", "{ $stars } of 5");
166pub const RATING_SET: StrKey = StrKey::new("egui-pop-rating-set", "Set { $stars } of 5");
168pub const RATING_CLEAR: StrKey = StrKey::new("egui-pop-rating-clear", "Clear rating");
170pub const SEGMENTED_MORE: StrKey =
172 StrKey::new("egui-pop-segmented-more", "More choices: { $control }");
173pub const NOTE_COPY: StrKey = StrKey::new("egui-pop-note-copy", "Copy");
175pub const NOTE_COPIED: StrKey = StrKey::new("egui-pop-note-copied", "Copied.");
177pub const NOTE_DETAILS: StrKey = StrKey::new("egui-pop-note-details", "Details");
179pub const NOTE_INFO: StrKey = StrKey::new("egui-pop-note-info", "Information");
181pub const NOTE_SUCCESS: StrKey = StrKey::new("egui-pop-note-success", "Success");
183pub const NOTE_WARNING: StrKey = StrKey::new("egui-pop-note-warning", "Warning");
185pub const NOTE_ERROR: StrKey = StrKey::new("egui-pop-note-error", "Error");
187
188pub 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#[derive(Clone, Copy, Debug, PartialEq)]
268pub enum Arg<'a> {
269 Str(&'a str),
271 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 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
309fn 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
314pub trait Strings: Send + Sync {
316 fn get(&self, key: &str) -> Option<String>;
318
319 fn get_args(&self, key: &str, args: &[(&str, Arg<'_>)]) -> Option<String> {
327 self.get(key).map(|t| fill_with(&t, args))
328 }
329
330 fn language(&self) -> &str {
332 "en"
333 }
334
335 fn number(&self, value: f64, decimals: usize) -> Option<String> {
340 let _ = (value, decimals);
341 None
342 }
343
344 fn quantity(&self, number: &str, unit: &str) -> Option<String> {
349 let _ = (number, unit);
350 None
351 }
352}
353
354#[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#[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
395const PROVIDER: Slot<Arc<dyn Strings>> = Slot::opaque("core.strings.provider");
397
398pub fn install(ctx: &Context, strings: Arc<dyn Strings>) {
400 PROVIDER.set(ctx, strings);
401}
402
403pub fn provider_id(ctx: &Context) -> Option<usize> {
407 PROVIDER
408 .get(ctx)
409 .map(|s| Arc::as_ptr(&s).cast::<()>() as usize)
410}
411
412pub fn provider(ctx: &Context) -> Arc<dyn Strings> {
414 PROVIDER.get(ctx).unwrap_or_else(|| Arc::new(English))
415}
416
417pub 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
430pub 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
448fn english(key: &str, fallback: &str) -> String {
451 if fallback.is_empty() {
452 key.to_string()
453 } else {
454 fallback.to_string()
455 }
456}
457
458pub fn tr(ctx: &Context, key: &StrKey) -> String {
460 lookup(ctx, key.key, key.fallback)
461}
462
463pub fn tr_args(ctx: &Context, key: &StrKey, args: &[(&str, &str)]) -> String {
468 lookup_args(ctx, key.key, key.fallback, args)
469}
470
471pub fn tr_with(ctx: &Context, key: &StrKey, args: &[(&str, Arg<'_>)]) -> String {
483 lookup_with(ctx, key.key, key.fallback, args)
484}
485
486pub fn lookup(ctx: &Context, key: &str, fallback: &str) -> String {
489 provider(ctx)
490 .get(key)
491 .unwrap_or_else(|| english(key, fallback))
492}
493
494pub fn lookup_args(ctx: &Context, key: &str, fallback: &str, args: &[(&str, &str)]) -> String {
496 lookup_with(ctx, key, fallback, &text_args(args))
497}
498
499pub 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
506pub fn fill(text: &str, args: &[(&str, &str)]) -> String {
508 fill_with(text, &text_args(args))
509}
510
511pub 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
524pub 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
540pub 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 pub const FRAME: &str = "frame";
550 pub const CLIP: &str = "clip";
552}
553
554pub 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
563pub 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#[derive(Clone, Debug, PartialEq)]
574pub struct PanelCommand {
575 pub title: StrKey,
576 pub description: StrKey,
577 pub panel: String,
579 pub panel_title: String,
581}
582
583pub type PanelCommands = Arc<BTreeMap<String, PanelCommand>>;
585
586const PANEL_COMMANDS: Slot<PanelCommands> = Slot::new("core.strings.panel_commands");
587
588pub fn set_panel_commands(ctx: &Context, commands: PanelCommands) {
592 PANEL_COMMANDS.set(ctx, commands);
593}
594
595pub fn panel_commands(ctx: &Context) -> Option<PanelCommands> {
597 PANEL_COMMANDS.get(ctx)
598}
599
600pub fn panel_command(ctx: &Context, command: &str) -> Option<PanelCommand> {
602 panel_commands(ctx).and_then(|m| m.get(command).cloned())
603}
604
605fn 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
623pub 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
632pub fn application(ctx: &Context) -> String {
634 APPLICATION.get(ctx).unwrap_or_default()
635}
636
637pub 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
661pub 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
680pub 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
691pub fn category_key(english: &str) -> String {
694 declared_key(kind::CATEGORY, &english.to_lowercase(), None)
695}
696
697pub fn category(ctx: &Context, english: &str) -> String {
699 lookup(ctx, &category_key(english), english)
700}
701
702pub fn panel_title(ctx: &Context, id: &str, english: &str) -> String {
704 declared(ctx, kind::PANEL, id, Some("title"), english)
705}
706
707pub fn menu_label(ctx: &Context, id: &str, english: &str) -> String {
709 declared(ctx, kind::MENU, id, Some("label"), english)
710}
711
712pub fn setting_label(ctx: &Context, id: &str, english: &str) -> String {
714 declared(ctx, kind::SETTING, id, Some("label"), english)
715}
716
717pub 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
725pub 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
734pub fn setting_choice(ctx: &Context, id: &str, value: &str) -> String {
737 lookup(ctx, &setting_choice_key(id, value), value)
738}
739
740pub fn plugin_title(ctx: &Context, id: &str, english: &str) -> String {
742 declared(ctx, kind::PLUGIN, id, Some("title"), english)
743}
744
745pub 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}