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