1#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
30pub enum Language {
31 #[default]
33 English,
34 French,
36 Spanish,
38 German,
40 Italian,
42 PortugueseBR,
44 PortuguesePT,
46 ChineseSimplified,
48}
49
50impl Language {
51 #[must_use]
67 pub const fn to_locale(self) -> &'static str {
68 match self {
69 Self::English => "en",
70 Self::French => "fr",
71 Self::Spanish => "es",
72 Self::German => "de",
73 Self::Italian => "it",
74 Self::PortugueseBR => "pt-BR",
75 Self::PortuguesePT => "pt-PT",
76 Self::ChineseSimplified => "zh-CN",
77 }
78 }
79}
80
81#[derive(Debug, Clone, Copy, Default)]
95pub struct Translations {
96 language: Language,
97}
98
99impl Translations {
100 #[must_use]
113 pub fn new(language: Language) -> Self {
114 rust_i18n::set_locale(language.to_locale());
115 Self { language }
116 }
117
118 #[must_use]
129 pub const fn language(&self) -> Language {
130 self.language
131 }
132
133 pub fn set_language(&mut self, language: Language) {
147 self.language = language;
148 rust_i18n::set_locale(language.to_locale());
149 }
150
151 #[must_use]
174 pub fn context_menu_reveal_in_file_manager(&self) -> String {
175 if cfg!(target_os = "macos") {
176 self.context_menu_reveal_in_finder()
177 } else if cfg!(target_os = "windows") {
178 self.context_menu_reveal_in_file_explorer()
179 } else {
180 self.context_menu_open_containing_folder()
181 }
182 }
183}
184
185macro_rules! translations {
201 ($($name:ident => $key:literal, $summary:literal, $english:literal;)*) => {
202 impl Translations {
203 $(
204 #[doc = $summary]
205 #[doc = ""]
206 #[doc = "# Examples"]
207 #[doc = ""]
208 #[doc = "```"]
209 #[doc = "use iced_code_editor::{Language, Translations};"]
210 #[doc = ""]
211 #[doc = concat!(
212 "assert_eq!(Translations::new(Language::English).",
213 stringify!($name),
214 "(), ",
215 stringify!($english),
216 ");"
217 )]
218 #[doc = "```"]
219 #[must_use]
220 pub fn $name(&self) -> String {
221 rust_i18n::t!($key, locale = self.language.to_locale())
222 .into_owned()
223 }
224 )*
225 }
226 };
227}
228
229translations! {
233 search_placeholder => "search.placeholder",
234 "Returns the placeholder text for the search input field.",
235 "Search...";
236 replace_placeholder => "replace.placeholder",
237 "Returns the placeholder text for the replace input field.",
238 "Replace...";
239 case_sensitive_label => "settings.case_sensitive_label",
240 "Returns the label text for the case sensitive checkbox.",
241 "Case sensitive";
242 previous_match_tooltip => "search.previous_match_tooltip",
243 "Returns the tooltip text for the previous match button.",
244 "Previous match (Shift+F3)";
245 next_match_tooltip => "search.next_match_tooltip",
246 "Returns the tooltip text for the next match button.",
247 "Next match (F3 / Enter)";
248 close_search_tooltip => "search.close_tooltip",
249 "Returns the tooltip text for the close search dialog button.",
250 "Close search dialog (Esc)";
251 replace_current_tooltip => "replace.current_tooltip",
252 "Returns the tooltip text for the replace current match button.",
253 "Replace current match";
254 replace_all_tooltip => "replace.all_tooltip",
255 "Returns the tooltip text for the replace all matches button.",
256 "Replace all matches";
257 context_menu_undo => "context_menu.undo",
258 "Returns the context-menu label for undo.",
259 "Undo";
260 context_menu_redo => "context_menu.redo",
261 "Returns the context-menu label for redo.",
262 "Redo";
263 context_menu_cut => "context_menu.cut",
264 "Returns the context-menu label for cut.",
265 "Cut";
266 context_menu_copy => "context_menu.copy",
267 "Returns the context-menu label for copy.",
268 "Copy";
269 context_menu_paste => "context_menu.paste",
270 "Returns the context-menu label for paste.",
271 "Paste";
272 context_menu_select_all => "context_menu.select_all",
273 "Returns the context-menu label for select all.",
274 "Select All";
275 context_menu_reveal_in_finder => "context_menu.reveal_in_finder",
276 "Returns the macOS context-menu label for revealing a file.",
277 "Reveal in Finder";
278 context_menu_reveal_in_file_explorer => "context_menu.reveal_in_file_explorer",
279 "Returns the Windows context-menu label for revealing a file.",
280 "Reveal in File Explorer";
281 context_menu_open_containing_folder => "context_menu.open_containing_folder",
282 "Returns the Linux context-menu label for opening a file's parent folder.",
283 "Open Containing Folder";
284 command_palette_placeholder => "command_palette.placeholder",
285 "Returns the command-palette label for the filter input's placeholder.",
286 "Type a command...";
287 command_palette_no_results => "command_palette.no_results",
288 "Returns the command-palette label for the empty-result message.",
289 "No matching command";
290 command_palette_save => "command_palette.save",
291 "Returns the command-palette label for saving the document.",
292 "Save";
293 command_palette_toggle_comment => "command_palette.toggle_comment",
294 "Returns the command-palette label for toggling the line comment.",
295 "Toggle Line Comment";
296 command_palette_move_line_up => "command_palette.move_line_up",
297 "Returns the command-palette label for moving the current line up.",
298 "Move Line Up";
299 command_palette_move_line_down => "command_palette.move_line_down",
300 "Returns the command-palette label for moving the current line down.",
301 "Move Line Down";
302 command_palette_duplicate_line_up => "command_palette.duplicate_line_up",
303 "Returns the command-palette label for duplicating the current line above.",
304 "Duplicate Line Up";
305 command_palette_duplicate_line_down => "command_palette.duplicate_line_down",
306 "Returns the command-palette label for duplicating the current line below.",
307 "Duplicate Line Down";
308 command_palette_goto_line => "command_palette.goto_line",
309 "Returns the command-palette label for jumping to a line.",
310 "Go to Line";
311 command_palette_add_cursor_above => "command_palette.add_cursor_above",
312 "Returns the command-palette label for adding a cursor on the line above.",
313 "Add Cursor Above";
314 command_palette_add_cursor_below => "command_palette.add_cursor_below",
315 "Returns the command-palette label for adding a cursor on the line below.",
316 "Add Cursor Below";
317 command_palette_select_next_occurrence => "command_palette.select_next_occurrence",
318 "Returns the command-palette label for selecting the next occurrence.",
319 "Select Next Occurrence";
320 command_palette_toggle_vim_mode => "command_palette.toggle_vim_mode",
321 "Returns the command-palette label for toggling Vim mode.",
322 "Toggle Vim Mode";
323 command_palette_find => "command_palette.find",
324 "Returns the command-palette label for opening the search dialog.",
325 "Find";
326 command_palette_replace => "command_palette.replace",
327 "Returns the command-palette label for opening the search-and-replace dialog.",
328 "Replace";
329 command_palette_fold_at_cursor => "command_palette.fold_at_cursor",
330 "Returns the command-palette label for folding the block at the cursor.",
331 "Toggle Fold at Cursor";
332 command_palette_fold_all => "command_palette.fold_all",
333 "Returns the command-palette label for folding every block.",
334 "Fold All";
335 command_palette_unfold_all => "command_palette.unfold_all",
336 "Returns the command-palette label for unfolding every block.",
337 "Unfold All";
338 command_palette_status_on => "command_palette.status_on",
339 "Returns the command-palette badge shown on an enabled toggle command.",
340 "On";
341 command_palette_status_off => "command_palette.status_off",
342 "Returns the command-palette badge shown on a disabled toggle command.",
343 "Off";
344}
345
346#[cfg(test)]
347mod tests {
348 use std::collections::BTreeSet;
349
350 use super::*;
351
352 const LOCALE_FILES: [(&str, &str); 8] = [
357 ("en", include_str!("../locales/en.yml")),
358 ("fr", include_str!("../locales/fr.yml")),
359 ("es", include_str!("../locales/es.yml")),
360 ("de", include_str!("../locales/de.yml")),
361 ("it", include_str!("../locales/it.yml")),
362 ("pt-BR", include_str!("../locales/pt-BR.yml")),
363 ("pt-PT", include_str!("../locales/pt-PT.yml")),
364 ("zh-CN", include_str!("../locales/zh-CN.yml")),
365 ];
366
367 fn locale_keys(yaml: &str) -> BTreeSet<String> {
374 let mut keys = BTreeSet::new();
375 let mut section = String::new();
376
377 for line in yaml.lines() {
378 let line = line.trim_end();
379 if line.trim_start().is_empty()
380 || line.trim_start().starts_with('#')
381 {
382 continue;
383 }
384
385 match line.strip_prefix(" ") {
386 Some(entry) => {
388 if let Some((name, _)) = entry.split_once(':') {
389 keys.insert(format!("{section}.{}", name.trim()));
390 }
391 }
392 None => {
394 if let Some((name, _)) = line.split_once(':') {
395 section = name.trim().to_string();
396 }
397 }
398 }
399 }
400
401 keys
402 }
403
404 #[test]
405 fn test_locale_keys_reads_the_section_and_entry_layout() {
406 let keys = locale_keys(
409 "# a comment\nsearch:\n placeholder: \"Search...\"\n\nreplace:\n all_tooltip: \"Replace all matches\"\n",
410 );
411
412 assert_eq!(
413 keys.iter().map(String::as_str).collect::<Vec<_>>(),
414 ["replace.all_tooltip", "search.placeholder"]
415 );
416 }
417
418 #[test]
419 fn test_every_locale_defines_exactly_the_keys_english_defines() {
420 let (_, english_source) = LOCALE_FILES[0];
426 let english = locale_keys(english_source);
427 assert!(
428 english.contains("command_palette.fold_all"),
429 "en.yml did not parse as expected"
430 );
431
432 for (name, source) in LOCALE_FILES {
433 let keys = locale_keys(source);
434 let missing: Vec<&String> = english.difference(&keys).collect();
435 let extra: Vec<&String> = keys.difference(&english).collect();
436
437 assert!(missing.is_empty(), "{name}.yml is missing {missing:?}");
438 assert!(
439 extra.is_empty(),
440 "{name}.yml defines {extra:?}, which en.yml does not"
441 );
442 }
443 }
444
445 #[test]
446 fn test_default_language() {
447 let translations = Translations::default();
448 assert_eq!(translations.language(), Language::English);
449 }
450
451 #[test]
452 fn test_new_with_language() {
453 let translations = Translations::new(Language::French);
454 assert_eq!(translations.language(), Language::French);
455 }
456
457 #[test]
458 fn test_set_language() {
459 let mut translations = Translations::new(Language::English);
460 translations.set_language(Language::Spanish);
461 assert_eq!(translations.language(), Language::Spanish);
462 }
463
464 #[test]
465 fn test_english_translations() {
466 let t = Translations::new(Language::English);
467 assert_eq!(t.search_placeholder(), "Search...");
468 assert_eq!(t.replace_placeholder(), "Replace...");
469 assert_eq!(t.case_sensitive_label(), "Case sensitive");
470 assert_eq!(t.previous_match_tooltip(), "Previous match (Shift+F3)");
471 assert_eq!(t.next_match_tooltip(), "Next match (F3 / Enter)");
472 assert_eq!(t.close_search_tooltip(), "Close search dialog (Esc)");
473 assert_eq!(t.replace_current_tooltip(), "Replace current match");
474 assert_eq!(t.replace_all_tooltip(), "Replace all matches");
475 }
476
477 #[test]
478 fn test_french_translations() {
479 let t = Translations::new(Language::French);
480 assert_eq!(t.search_placeholder(), "Rechercher...");
481 assert_eq!(t.replace_placeholder(), "Remplacer...");
482 assert_eq!(t.case_sensitive_label(), "Sensible à la casse");
483 assert_eq!(t.previous_match_tooltip(), "Résultat précédent (Maj+F3)");
484 assert_eq!(t.next_match_tooltip(), "Résultat suivant (F3 / Entrée)");
485 assert_eq!(t.close_search_tooltip(), "Fermer la recherche (Échap)");
486 assert_eq!(
487 t.replace_current_tooltip(),
488 "Remplacer l'occurrence actuelle"
489 );
490 assert_eq!(t.replace_all_tooltip(), "Tout remplacer");
491 }
492
493 #[test]
494 fn test_spanish_translations() {
495 let t = Translations::new(Language::Spanish);
496 assert_eq!(t.search_placeholder(), "Buscar...");
497 assert_eq!(t.replace_placeholder(), "Reemplazar...");
498 assert_eq!(t.case_sensitive_label(), "Distinguir mayúsculas");
499 assert_eq!(
500 t.previous_match_tooltip(),
501 "Coincidencia anterior (Mayús+F3)"
502 );
503 assert_eq!(
504 t.next_match_tooltip(),
505 "Siguiente coincidencia (F3 / Enter)"
506 );
507 assert_eq!(t.close_search_tooltip(), "Cerrar búsqueda (Esc)");
508 assert_eq!(
509 t.replace_current_tooltip(),
510 "Reemplazar coincidencia actual"
511 );
512 assert_eq!(t.replace_all_tooltip(), "Reemplazar todo");
513 }
514
515 #[test]
516 fn test_german_translations() {
517 let t = Translations::new(Language::German);
518 assert_eq!(t.search_placeholder(), "Suchen...");
519 assert_eq!(t.replace_placeholder(), "Ersetzen...");
520 assert_eq!(t.case_sensitive_label(), "Groß-/Kleinschreibung");
521 assert_eq!(
522 t.previous_match_tooltip(),
523 "Vorheriger Treffer (Umschalt+F3)"
524 );
525 assert_eq!(t.next_match_tooltip(), "Nächster Treffer (F3 / Enter)");
526 assert_eq!(t.close_search_tooltip(), "Suchdialog schließen (Esc)");
527 assert_eq!(t.replace_current_tooltip(), "Aktuellen Treffer ersetzen");
528 assert_eq!(t.replace_all_tooltip(), "Alle ersetzen");
529 }
530
531 #[test]
532 fn test_italian_translations() {
533 let t = Translations::new(Language::Italian);
534 assert_eq!(t.search_placeholder(), "Cerca...");
535 assert_eq!(t.replace_placeholder(), "Sostituisci...");
536 assert_eq!(t.case_sensitive_label(), "Distingui maiuscole");
537 assert_eq!(
538 t.previous_match_tooltip(),
539 "Risultato precedente (Maiusc+F3)"
540 );
541 assert_eq!(t.next_match_tooltip(), "Risultato successivo (F3 / Invio)");
542 assert_eq!(
543 t.close_search_tooltip(),
544 "Chiudi finestra di ricerca (Esc)"
545 );
546 assert_eq!(
547 t.replace_current_tooltip(),
548 "Sostituisci risultato corrente"
549 );
550 assert_eq!(t.replace_all_tooltip(), "Sostituisci tutto");
551 }
552
553 #[test]
554 fn test_portuguese_br_translations() {
555 let t = Translations::new(Language::PortugueseBR);
556 assert_eq!(t.search_placeholder(), "Pesquisar...");
557 assert_eq!(t.replace_placeholder(), "Substituir...");
558 assert_eq!(t.case_sensitive_label(), "Diferenciar maiúsculas");
559 assert_eq!(
560 t.previous_match_tooltip(),
561 "Correspondência anterior (Shift+F3)"
562 );
563 assert_eq!(
564 t.next_match_tooltip(),
565 "Próxima correspondência (F3 / Enter)"
566 );
567 assert_eq!(
568 t.close_search_tooltip(),
569 "Fechar diálogo de pesquisa (Esc)"
570 );
571 assert_eq!(
572 t.replace_current_tooltip(),
573 "Substituir correspondência atual"
574 );
575 assert_eq!(t.replace_all_tooltip(), "Substituir tudo");
576 }
577
578 #[test]
579 fn test_portuguese_pt_translations() {
580 let t = Translations::new(Language::PortuguesePT);
581 assert_eq!(t.search_placeholder(), "Pesquisar...");
582 assert_eq!(t.replace_placeholder(), "Substituir...");
583 assert_eq!(t.case_sensitive_label(), "Diferenciar maiúsculas");
584 assert_eq!(
585 t.previous_match_tooltip(),
586 "Correspondência anterior (Shift+F3)"
587 );
588 assert_eq!(
589 t.next_match_tooltip(),
590 "Próxima correspondência (F3 / Enter)"
591 );
592 assert_eq!(
593 t.close_search_tooltip(),
594 "Fechar diálogo de pesquisa (Esc)"
595 );
596 assert_eq!(
597 t.replace_current_tooltip(),
598 "Substituir correspondência actual"
599 );
600 assert_eq!(t.replace_all_tooltip(), "Substituir tudo");
601 }
602
603 #[test]
604 fn test_language_switching() {
605 let mut t = Translations::new(Language::English);
606 assert_eq!(t.search_placeholder(), "Search...");
607
608 t.set_language(Language::French);
609 assert_eq!(t.search_placeholder(), "Rechercher...");
610
611 t.set_language(Language::Spanish);
612 assert_eq!(t.search_placeholder(), "Buscar...");
613
614 t.set_language(Language::German);
615 assert_eq!(t.search_placeholder(), "Suchen...");
616
617 t.set_language(Language::Italian);
618 assert_eq!(t.search_placeholder(), "Cerca...");
619
620 t.set_language(Language::PortugueseBR);
621 assert_eq!(t.search_placeholder(), "Pesquisar...");
622
623 t.set_language(Language::PortuguesePT);
624 assert_eq!(t.search_placeholder(), "Pesquisar...");
625
626 t.set_language(Language::ChineseSimplified);
627 assert_eq!(t.search_placeholder(), "搜索...");
628 }
629
630 #[test]
631 fn test_context_menu_translations_cover_all_locales() {
632 let cases = [
633 (
634 Language::English,
635 [
636 "Undo",
637 "Redo",
638 "Cut",
639 "Copy",
640 "Paste",
641 "Select All",
642 "Reveal in Finder",
643 "Reveal in File Explorer",
644 "Open Containing Folder",
645 ],
646 ),
647 (
648 Language::French,
649 [
650 "Annuler",
651 "Rétablir",
652 "Couper",
653 "Copier",
654 "Coller",
655 "Tout sélectionner",
656 "Révéler dans le Finder",
657 "Afficher dans l'Explorateur de fichiers",
658 "Ouvrir le dossier contenant",
659 ],
660 ),
661 (
662 Language::Spanish,
663 [
664 "Deshacer",
665 "Rehacer",
666 "Cortar",
667 "Copiar",
668 "Pegar",
669 "Seleccionar todo",
670 "Mostrar en Finder",
671 "Mostrar en el Explorador de archivos",
672 "Abrir carpeta contenedora",
673 ],
674 ),
675 (
676 Language::German,
677 [
678 "Rückgängig",
679 "Wiederholen",
680 "Ausschneiden",
681 "Kopieren",
682 "Einfügen",
683 "Alle auswählen",
684 "Im Finder anzeigen",
685 "Im Datei-Explorer anzeigen",
686 "Übergeordneten Ordner öffnen",
687 ],
688 ),
689 (
690 Language::Italian,
691 [
692 "Annulla azione",
693 "Ripeti",
694 "Taglia",
695 "Copia",
696 "Incolla",
697 "Seleziona tutto",
698 "Visualizza in Finder",
699 "Visualizza in Esplora file",
700 "Apri cartella superiore",
701 ],
702 ),
703 (
704 Language::PortugueseBR,
705 [
706 "Desfazer",
707 "Refazer",
708 "Recortar",
709 "Copiar",
710 "Colar",
711 "Selecionar Tudo",
712 "Revelar no Finder",
713 "Revelar no Explorador de Arquivos",
714 "Abrir a Pasta Que Contém",
715 ],
716 ),
717 (
718 Language::PortuguesePT,
719 [
720 "Anular",
721 "Refazer",
722 "Cortar",
723 "Copiar",
724 "Colar",
725 "Selecionar tudo",
726 "Mostrar no Finder",
727 "Mostrar no Explorador de Ficheiros",
728 "Abrir pasta contentora",
729 ],
730 ),
731 (
732 Language::ChineseSimplified,
733 [
734 "撤消",
735 "恢复",
736 "剪切",
737 "复制",
738 "粘贴",
739 "选择全部",
740 "在访达中显示",
741 "在文件资源管理器中显示",
742 "打开所在的文件夹",
743 ],
744 ),
745 ];
746
747 for (language, expected) in cases {
748 let translations = Translations::new(language);
749 assert_eq!(translations.context_menu_undo(), expected[0]);
750 assert_eq!(translations.context_menu_redo(), expected[1]);
751 assert_eq!(translations.context_menu_cut(), expected[2]);
752 assert_eq!(translations.context_menu_copy(), expected[3]);
753 assert_eq!(translations.context_menu_paste(), expected[4]);
754 assert_eq!(translations.context_menu_select_all(), expected[5]);
755 assert_eq!(
756 translations.context_menu_reveal_in_finder(),
757 expected[6]
758 );
759 assert_eq!(
760 translations.context_menu_reveal_in_file_explorer(),
761 expected[7]
762 );
763 assert_eq!(
764 translations.context_menu_open_containing_folder(),
765 expected[8]
766 );
767 }
768 }
769
770 #[test]
771 fn test_every_command_palette_accessor_resolves_to_a_defined_key() {
772 let languages = [
783 Language::English,
784 Language::French,
785 Language::Spanish,
786 Language::German,
787 Language::Italian,
788 Language::PortugueseBR,
789 Language::PortuguesePT,
790 Language::ChineseSimplified,
791 ];
792
793 for language in languages {
794 let t = Translations::new(language);
795 let labels = [
796 t.command_palette_placeholder(),
797 t.command_palette_no_results(),
798 t.command_palette_save(),
799 t.command_palette_toggle_comment(),
800 t.command_palette_move_line_up(),
801 t.command_palette_move_line_down(),
802 t.command_palette_duplicate_line_up(),
803 t.command_palette_duplicate_line_down(),
804 t.command_palette_goto_line(),
805 t.command_palette_add_cursor_above(),
806 t.command_palette_add_cursor_below(),
807 t.command_palette_select_next_occurrence(),
808 t.command_palette_toggle_vim_mode(),
809 t.command_palette_find(),
810 t.command_palette_replace(),
811 t.command_palette_fold_at_cursor(),
812 t.command_palette_fold_all(),
813 t.command_palette_unfold_all(),
814 t.command_palette_status_on(),
815 t.command_palette_status_off(),
816 ];
817
818 for label in labels {
819 assert!(!label.is_empty(), "empty label for {language:?}");
820 assert!(
821 !label.starts_with("command_palette."),
822 "missing translation {label} for {language:?}"
823 );
824 }
825 }
826 }
827
828 #[test]
829 fn test_command_palette_labels_are_localized() {
830 let cases = [
831 (Language::English, "Fold All", "Go to Line"),
832 (Language::French, "Tout replier", "Aller à la ligne"),
833 (Language::Spanish, "Plegar todo", "Ir a la línea"),
834 (Language::German, "Alles falten", "Gehe zu Zeile"),
835 (Language::Italian, "Comprimi tutto", "Vai alla riga"),
836 (Language::PortugueseBR, "Dobrar tudo", "Ir para a linha"),
837 (Language::PortuguesePT, "Dobrar tudo", "Ir para a linha"),
838 (Language::ChineseSimplified, "全部折叠", "转到行"),
839 ];
840
841 for (language, fold_all, goto_line) in cases {
842 let t = Translations::new(language);
843 assert_eq!(t.command_palette_fold_all(), fold_all);
844 assert_eq!(t.command_palette_goto_line(), goto_line);
845 }
846 }
847}