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}
339
340#[cfg(test)]
341mod tests {
342 use std::collections::BTreeSet;
343
344 use super::*;
345
346 const LOCALE_FILES: [(&str, &str); 8] = [
351 ("en", include_str!("../locales/en.yml")),
352 ("fr", include_str!("../locales/fr.yml")),
353 ("es", include_str!("../locales/es.yml")),
354 ("de", include_str!("../locales/de.yml")),
355 ("it", include_str!("../locales/it.yml")),
356 ("pt-BR", include_str!("../locales/pt-BR.yml")),
357 ("pt-PT", include_str!("../locales/pt-PT.yml")),
358 ("zh-CN", include_str!("../locales/zh-CN.yml")),
359 ];
360
361 fn locale_keys(yaml: &str) -> BTreeSet<String> {
368 let mut keys = BTreeSet::new();
369 let mut section = String::new();
370
371 for line in yaml.lines() {
372 let line = line.trim_end();
373 if line.trim_start().is_empty()
374 || line.trim_start().starts_with('#')
375 {
376 continue;
377 }
378
379 match line.strip_prefix(" ") {
380 Some(entry) => {
382 if let Some((name, _)) = entry.split_once(':') {
383 keys.insert(format!("{section}.{}", name.trim()));
384 }
385 }
386 None => {
388 if let Some((name, _)) = line.split_once(':') {
389 section = name.trim().to_string();
390 }
391 }
392 }
393 }
394
395 keys
396 }
397
398 #[test]
399 fn test_locale_keys_reads_the_section_and_entry_layout() {
400 let keys = locale_keys(
403 "# a comment\nsearch:\n placeholder: \"Search...\"\n\nreplace:\n all_tooltip: \"Replace all matches\"\n",
404 );
405
406 assert_eq!(
407 keys.iter().map(String::as_str).collect::<Vec<_>>(),
408 ["replace.all_tooltip", "search.placeholder"]
409 );
410 }
411
412 #[test]
413 fn test_every_locale_defines_exactly_the_keys_english_defines() {
414 let (_, english_source) = LOCALE_FILES[0];
420 let english = locale_keys(english_source);
421 assert!(
422 english.contains("command_palette.fold_all"),
423 "en.yml did not parse as expected"
424 );
425
426 for (name, source) in LOCALE_FILES {
427 let keys = locale_keys(source);
428 let missing: Vec<&String> = english.difference(&keys).collect();
429 let extra: Vec<&String> = keys.difference(&english).collect();
430
431 assert!(missing.is_empty(), "{name}.yml is missing {missing:?}");
432 assert!(
433 extra.is_empty(),
434 "{name}.yml defines {extra:?}, which en.yml does not"
435 );
436 }
437 }
438
439 #[test]
440 fn test_default_language() {
441 let translations = Translations::default();
442 assert_eq!(translations.language(), Language::English);
443 }
444
445 #[test]
446 fn test_new_with_language() {
447 let translations = Translations::new(Language::French);
448 assert_eq!(translations.language(), Language::French);
449 }
450
451 #[test]
452 fn test_set_language() {
453 let mut translations = Translations::new(Language::English);
454 translations.set_language(Language::Spanish);
455 assert_eq!(translations.language(), Language::Spanish);
456 }
457
458 #[test]
459 fn test_english_translations() {
460 let t = Translations::new(Language::English);
461 assert_eq!(t.search_placeholder(), "Search...");
462 assert_eq!(t.replace_placeholder(), "Replace...");
463 assert_eq!(t.case_sensitive_label(), "Case sensitive");
464 assert_eq!(t.previous_match_tooltip(), "Previous match (Shift+F3)");
465 assert_eq!(t.next_match_tooltip(), "Next match (F3 / Enter)");
466 assert_eq!(t.close_search_tooltip(), "Close search dialog (Esc)");
467 assert_eq!(t.replace_current_tooltip(), "Replace current match");
468 assert_eq!(t.replace_all_tooltip(), "Replace all matches");
469 }
470
471 #[test]
472 fn test_french_translations() {
473 let t = Translations::new(Language::French);
474 assert_eq!(t.search_placeholder(), "Rechercher...");
475 assert_eq!(t.replace_placeholder(), "Remplacer...");
476 assert_eq!(t.case_sensitive_label(), "Sensible à la casse");
477 assert_eq!(t.previous_match_tooltip(), "Résultat précédent (Maj+F3)");
478 assert_eq!(t.next_match_tooltip(), "Résultat suivant (F3 / Entrée)");
479 assert_eq!(t.close_search_tooltip(), "Fermer la recherche (Échap)");
480 assert_eq!(
481 t.replace_current_tooltip(),
482 "Remplacer l'occurrence actuelle"
483 );
484 assert_eq!(t.replace_all_tooltip(), "Tout remplacer");
485 }
486
487 #[test]
488 fn test_spanish_translations() {
489 let t = Translations::new(Language::Spanish);
490 assert_eq!(t.search_placeholder(), "Buscar...");
491 assert_eq!(t.replace_placeholder(), "Reemplazar...");
492 assert_eq!(t.case_sensitive_label(), "Distinguir mayúsculas");
493 assert_eq!(
494 t.previous_match_tooltip(),
495 "Coincidencia anterior (Mayús+F3)"
496 );
497 assert_eq!(
498 t.next_match_tooltip(),
499 "Siguiente coincidencia (F3 / Enter)"
500 );
501 assert_eq!(t.close_search_tooltip(), "Cerrar búsqueda (Esc)");
502 assert_eq!(
503 t.replace_current_tooltip(),
504 "Reemplazar coincidencia actual"
505 );
506 assert_eq!(t.replace_all_tooltip(), "Reemplazar todo");
507 }
508
509 #[test]
510 fn test_german_translations() {
511 let t = Translations::new(Language::German);
512 assert_eq!(t.search_placeholder(), "Suchen...");
513 assert_eq!(t.replace_placeholder(), "Ersetzen...");
514 assert_eq!(t.case_sensitive_label(), "Groß-/Kleinschreibung");
515 assert_eq!(
516 t.previous_match_tooltip(),
517 "Vorheriger Treffer (Umschalt+F3)"
518 );
519 assert_eq!(t.next_match_tooltip(), "Nächster Treffer (F3 / Enter)");
520 assert_eq!(t.close_search_tooltip(), "Suchdialog schließen (Esc)");
521 assert_eq!(t.replace_current_tooltip(), "Aktuellen Treffer ersetzen");
522 assert_eq!(t.replace_all_tooltip(), "Alle ersetzen");
523 }
524
525 #[test]
526 fn test_italian_translations() {
527 let t = Translations::new(Language::Italian);
528 assert_eq!(t.search_placeholder(), "Cerca...");
529 assert_eq!(t.replace_placeholder(), "Sostituisci...");
530 assert_eq!(t.case_sensitive_label(), "Distingui maiuscole");
531 assert_eq!(
532 t.previous_match_tooltip(),
533 "Risultato precedente (Maiusc+F3)"
534 );
535 assert_eq!(t.next_match_tooltip(), "Risultato successivo (F3 / Invio)");
536 assert_eq!(
537 t.close_search_tooltip(),
538 "Chiudi finestra di ricerca (Esc)"
539 );
540 assert_eq!(
541 t.replace_current_tooltip(),
542 "Sostituisci risultato corrente"
543 );
544 assert_eq!(t.replace_all_tooltip(), "Sostituisci tutto");
545 }
546
547 #[test]
548 fn test_portuguese_br_translations() {
549 let t = Translations::new(Language::PortugueseBR);
550 assert_eq!(t.search_placeholder(), "Pesquisar...");
551 assert_eq!(t.replace_placeholder(), "Substituir...");
552 assert_eq!(t.case_sensitive_label(), "Diferenciar maiúsculas");
553 assert_eq!(
554 t.previous_match_tooltip(),
555 "Correspondência anterior (Shift+F3)"
556 );
557 assert_eq!(
558 t.next_match_tooltip(),
559 "Próxima correspondência (F3 / Enter)"
560 );
561 assert_eq!(
562 t.close_search_tooltip(),
563 "Fechar diálogo de pesquisa (Esc)"
564 );
565 assert_eq!(
566 t.replace_current_tooltip(),
567 "Substituir correspondência atual"
568 );
569 assert_eq!(t.replace_all_tooltip(), "Substituir tudo");
570 }
571
572 #[test]
573 fn test_portuguese_pt_translations() {
574 let t = Translations::new(Language::PortuguesePT);
575 assert_eq!(t.search_placeholder(), "Pesquisar...");
576 assert_eq!(t.replace_placeholder(), "Substituir...");
577 assert_eq!(t.case_sensitive_label(), "Diferenciar maiúsculas");
578 assert_eq!(
579 t.previous_match_tooltip(),
580 "Correspondência anterior (Shift+F3)"
581 );
582 assert_eq!(
583 t.next_match_tooltip(),
584 "Próxima correspondência (F3 / Enter)"
585 );
586 assert_eq!(
587 t.close_search_tooltip(),
588 "Fechar diálogo de pesquisa (Esc)"
589 );
590 assert_eq!(
591 t.replace_current_tooltip(),
592 "Substituir correspondência actual"
593 );
594 assert_eq!(t.replace_all_tooltip(), "Substituir tudo");
595 }
596
597 #[test]
598 fn test_language_switching() {
599 let mut t = Translations::new(Language::English);
600 assert_eq!(t.search_placeholder(), "Search...");
601
602 t.set_language(Language::French);
603 assert_eq!(t.search_placeholder(), "Rechercher...");
604
605 t.set_language(Language::Spanish);
606 assert_eq!(t.search_placeholder(), "Buscar...");
607
608 t.set_language(Language::German);
609 assert_eq!(t.search_placeholder(), "Suchen...");
610
611 t.set_language(Language::Italian);
612 assert_eq!(t.search_placeholder(), "Cerca...");
613
614 t.set_language(Language::PortugueseBR);
615 assert_eq!(t.search_placeholder(), "Pesquisar...");
616
617 t.set_language(Language::PortuguesePT);
618 assert_eq!(t.search_placeholder(), "Pesquisar...");
619
620 t.set_language(Language::ChineseSimplified);
621 assert_eq!(t.search_placeholder(), "搜索...");
622 }
623
624 #[test]
625 fn test_context_menu_translations_cover_all_locales() {
626 let cases = [
627 (
628 Language::English,
629 [
630 "Undo",
631 "Redo",
632 "Cut",
633 "Copy",
634 "Paste",
635 "Select All",
636 "Reveal in Finder",
637 "Reveal in File Explorer",
638 "Open Containing Folder",
639 ],
640 ),
641 (
642 Language::French,
643 [
644 "Annuler",
645 "Rétablir",
646 "Couper",
647 "Copier",
648 "Coller",
649 "Tout sélectionner",
650 "Révéler dans le Finder",
651 "Afficher dans l'Explorateur de fichiers",
652 "Ouvrir le dossier contenant",
653 ],
654 ),
655 (
656 Language::Spanish,
657 [
658 "Deshacer",
659 "Rehacer",
660 "Cortar",
661 "Copiar",
662 "Pegar",
663 "Seleccionar todo",
664 "Mostrar en Finder",
665 "Mostrar en el Explorador de archivos",
666 "Abrir carpeta contenedora",
667 ],
668 ),
669 (
670 Language::German,
671 [
672 "Rückgängig",
673 "Wiederholen",
674 "Ausschneiden",
675 "Kopieren",
676 "Einfügen",
677 "Alle auswählen",
678 "Im Finder anzeigen",
679 "Im Datei-Explorer anzeigen",
680 "Übergeordneten Ordner öffnen",
681 ],
682 ),
683 (
684 Language::Italian,
685 [
686 "Annulla azione",
687 "Ripeti",
688 "Taglia",
689 "Copia",
690 "Incolla",
691 "Seleziona tutto",
692 "Visualizza in Finder",
693 "Visualizza in Esplora file",
694 "Apri cartella superiore",
695 ],
696 ),
697 (
698 Language::PortugueseBR,
699 [
700 "Desfazer",
701 "Refazer",
702 "Recortar",
703 "Copiar",
704 "Colar",
705 "Selecionar Tudo",
706 "Revelar no Finder",
707 "Revelar no Explorador de Arquivos",
708 "Abrir a Pasta Que Contém",
709 ],
710 ),
711 (
712 Language::PortuguesePT,
713 [
714 "Anular",
715 "Refazer",
716 "Cortar",
717 "Copiar",
718 "Colar",
719 "Selecionar tudo",
720 "Mostrar no Finder",
721 "Mostrar no Explorador de Ficheiros",
722 "Abrir pasta contentora",
723 ],
724 ),
725 (
726 Language::ChineseSimplified,
727 [
728 "撤消",
729 "恢复",
730 "剪切",
731 "复制",
732 "粘贴",
733 "选择全部",
734 "在访达中显示",
735 "在文件资源管理器中显示",
736 "打开所在的文件夹",
737 ],
738 ),
739 ];
740
741 for (language, expected) in cases {
742 let translations = Translations::new(language);
743 assert_eq!(translations.context_menu_undo(), expected[0]);
744 assert_eq!(translations.context_menu_redo(), expected[1]);
745 assert_eq!(translations.context_menu_cut(), expected[2]);
746 assert_eq!(translations.context_menu_copy(), expected[3]);
747 assert_eq!(translations.context_menu_paste(), expected[4]);
748 assert_eq!(translations.context_menu_select_all(), expected[5]);
749 assert_eq!(
750 translations.context_menu_reveal_in_finder(),
751 expected[6]
752 );
753 assert_eq!(
754 translations.context_menu_reveal_in_file_explorer(),
755 expected[7]
756 );
757 assert_eq!(
758 translations.context_menu_open_containing_folder(),
759 expected[8]
760 );
761 }
762 }
763
764 #[test]
765 fn test_every_command_palette_accessor_resolves_to_a_defined_key() {
766 let languages = [
777 Language::English,
778 Language::French,
779 Language::Spanish,
780 Language::German,
781 Language::Italian,
782 Language::PortugueseBR,
783 Language::PortuguesePT,
784 Language::ChineseSimplified,
785 ];
786
787 for language in languages {
788 let t = Translations::new(language);
789 let labels = [
790 t.command_palette_placeholder(),
791 t.command_palette_no_results(),
792 t.command_palette_save(),
793 t.command_palette_toggle_comment(),
794 t.command_palette_move_line_up(),
795 t.command_palette_move_line_down(),
796 t.command_palette_duplicate_line_up(),
797 t.command_palette_duplicate_line_down(),
798 t.command_palette_goto_line(),
799 t.command_palette_add_cursor_above(),
800 t.command_palette_add_cursor_below(),
801 t.command_palette_select_next_occurrence(),
802 t.command_palette_toggle_vim_mode(),
803 t.command_palette_find(),
804 t.command_palette_replace(),
805 t.command_palette_fold_at_cursor(),
806 t.command_palette_fold_all(),
807 t.command_palette_unfold_all(),
808 ];
809
810 for label in labels {
811 assert!(!label.is_empty(), "empty label for {language:?}");
812 assert!(
813 !label.starts_with("command_palette."),
814 "missing translation {label} for {language:?}"
815 );
816 }
817 }
818 }
819
820 #[test]
821 fn test_command_palette_labels_are_localized() {
822 let cases = [
823 (Language::English, "Fold All", "Go to Line"),
824 (Language::French, "Tout replier", "Aller à la ligne"),
825 (Language::Spanish, "Plegar todo", "Ir a la línea"),
826 (Language::German, "Alles falten", "Gehe zu Zeile"),
827 (Language::Italian, "Comprimi tutto", "Vai alla riga"),
828 (Language::PortugueseBR, "Dobrar tudo", "Ir para a linha"),
829 (Language::PortuguesePT, "Dobrar tudo", "Ir para a linha"),
830 (Language::ChineseSimplified, "全部折叠", "转到行"),
831 ];
832
833 for (language, fold_all, goto_line) in cases {
834 let t = Translations::new(language);
835 assert_eq!(t.command_palette_fold_all(), fold_all);
836 assert_eq!(t.command_palette_goto_line(), goto_line);
837 }
838 }
839}