1use std::collections::{BTreeMap, BTreeSet};
39use std::fmt::Write as _;
40use std::io;
41use std::path::Path;
42
43use egui_pop_api::AppHandle;
44use egui_pop_api::app::MENU_MAIN;
45use egui_pop_core::strings::{self, kind};
46use egui_pop_model::ids::MenuId;
47use egui_pop_model::menus::Item;
48use fluent_syntax::ast::{Entry, Identifier, Message, Pattern as FtlPattern, Resource};
49use serde::{Deserialize, Serialize};
50
51#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
53#[serde(tag = "kind", content = "text", rename_all = "snake_case")]
54pub enum English {
55 Plain(String),
58 Pattern(String),
60 None,
63}
64
65#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
67pub struct Found {
68 pub key: String,
69 pub english: English,
70 pub origin: String,
72}
73
74#[derive(Clone, Copy, Debug, PartialEq, Eq)]
76pub struct Pattern {
77 pub callee: &'static str,
81 pub key: usize,
83 pub english: Option<usize>,
85}
86
87impl Pattern {
88 pub const DEFAULTS: &'static [Pattern] = &[
92 Pattern {
93 callee: "tr!",
94 key: 0,
95 english: None,
96 },
97 Pattern {
98 callee: "t",
99 key: 1,
100 english: None,
101 },
102 Pattern {
103 callee: "text",
104 key: 1,
105 english: Some(2),
106 },
107 Pattern {
108 callee: "StrKey::new",
109 key: 0,
110 english: Some(1),
111 },
112 Pattern {
113 callee: "lookup",
114 key: 1,
115 english: Some(2),
116 },
117 Pattern {
118 callee: "lookup_args",
119 key: 1,
120 english: Some(2),
121 },
122 ];
123}
124
125pub fn valid_key(key: &str) -> bool {
127 let ident = |s: &str| {
128 let mut c = s.chars();
129 c.next().is_some_and(|f| f.is_ascii_alphabetic())
130 && c.all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_')
131 };
132 match key.split_once('.') {
133 Some((id, attr)) => ident(id) && ident(attr),
134 None => ident(key),
135 }
136}
137
138fn tokens(source: &str) -> Vec<Tok> {
141 let b = source.as_bytes();
142 let mut out = Vec::new();
143 let mut i = 0;
144 let mut line = 1;
145 while i < b.len() {
146 let c = b[i];
147 if c == b'\n' {
148 line += 1;
149 i += 1;
150 } else if b[i..].starts_with(b"//") {
151 while i < b.len() && b[i] != b'\n' {
152 i += 1;
153 }
154 } else if b[i..].starts_with(b"/*") {
155 i += 2;
156 while i < b.len() && !b[i..].starts_with(b"*/") {
157 if b[i] == b'\n' {
158 line += 1;
159 }
160 i += 1;
161 }
162 i += 2;
163 } else if c == b'"' || (c == b'r' && matches!(b.get(i + 1), Some(b'"' | b'#'))) {
164 let start_line = line;
165 let (text, end) = string_literal(source, i);
166 line += source[i..end].matches('\n').count();
167 out.push(Tok::Str(text, start_line));
168 i = end;
169 } else if c == b'\'' {
170 if b.get(i + 2) == Some(&b'\'') {
172 i += 3;
173 } else if b.get(i + 1) == Some(&b'\\') {
174 i += 2;
175 while i < b.len() && b[i] != b'\'' {
176 i += 1;
177 }
178 i += 1;
179 } else {
180 i += 1;
181 }
182 } else if c.is_ascii_alphabetic() || c == b'_' {
183 let start = i;
184 while i < b.len() && (b[i].is_ascii_alphanumeric() || b[i] == b'_') {
185 i += 1;
186 }
187 out.push(Tok::Ident(source[start..i].to_string(), line));
188 } else if c.is_ascii_whitespace() {
189 i += 1;
190 } else {
191 out.push(Tok::Punct(c as char));
192 i += 1;
193 }
194 }
195 out
196}
197
198#[derive(Clone, Debug, PartialEq)]
199enum Tok {
200 Ident(String, usize),
201 Str(String, usize),
202 Punct(char),
203}
204
205fn string_literal(source: &str, i: usize) -> (String, usize) {
207 let b = source.as_bytes();
208 if b[i] == b'r' {
209 let mut j = i + 1;
210 let mut hashes = 0;
211 while b.get(j) == Some(&b'#') {
212 hashes += 1;
213 j += 1;
214 }
215 let start = j + 1;
216 let close = format!("\"{}", "#".repeat(hashes));
217 let end = source[start..]
218 .find(&close)
219 .map_or(source.len(), |p| start + p);
220 return (
221 source[start..end].to_string(),
222 (end + close.len()).min(source.len()),
223 );
224 }
225 let mut out = String::new();
226 let mut j = i + 1;
227 let chars: Vec<(usize, char)> = source[j..].char_indices().collect();
228 let mut k = 0;
229 while k < chars.len() {
230 let (off, c) = chars[k];
231 match c {
232 '"' => return (out, j + off + 1),
233 '\\' => {
234 k += 1;
235 let Some(&(_, e)) = chars.get(k) else { break };
236 match e {
237 'n' => out.push('\n'),
238 't' => out.push('\t'),
239 '\\' => out.push('\\'),
240 '"' => out.push('"'),
241 '\'' => out.push('\''),
242 '0' => out.push('\0'),
243 '\n' => {
244 while chars.get(k + 1).is_some_and(|(_, c)| c.is_whitespace()) {
246 k += 1;
247 }
248 }
249 'u' => {
250 let hex: String = chars[k + 1..]
251 .iter()
252 .map(|(_, c)| *c)
253 .skip(1)
254 .take_while(|c| *c != '}')
255 .collect();
256 if let Some(c) = u32::from_str_radix(&hex, 16).ok().and_then(char::from_u32)
257 {
258 out.push(c);
259 }
260 k += hex.len() + 2;
261 }
262 other => out.push(other),
263 }
264 }
265 c => out.push(c),
266 }
267 k += 1;
268 }
269 j = source.len();
270 (out, j)
271}
272
273#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
277pub struct Unread {
278 pub callee: String,
280 pub origin: String,
282 pub reason: String,
284}
285
286impl std::fmt::Display for Unread {
287 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
288 write!(
289 f,
290 "{}: `{}(…)` not read: {}",
291 self.origin, self.callee, self.reason
292 )
293 }
294}
295
296#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
299pub struct Scan {
300 pub found: Vec<Found>,
301 pub unread: Vec<Unread>,
302}
303
304impl Scan {
305 pub fn extend(&mut self, other: Scan) {
307 self.found.extend(other.found);
308 self.unread.extend(other.unread);
309 }
310}
311
312fn names(callee: &str, pattern: &str) -> bool {
316 callee == pattern
317 || callee
318 .strip_suffix(pattern)
319 .is_some_and(|head| head.ends_with("::"))
320}
321
322fn constructor(pattern: &Pattern) -> bool {
326 pattern.callee.ends_with("::new")
327}
328
329pub fn scan(source: &str, file: &str, patterns: &[Pattern]) -> Scan {
342 let toks = tokens(source);
343 let mut out = Scan::default();
344 for (i, t) in toks.iter().enumerate() {
345 let Tok::Ident(name, line) = t else { continue };
346 let mut callee = name.clone();
348 let mut j = i + 1;
349 while matches!(toks.get(j), Some(Tok::Punct(':')))
350 && matches!(toks.get(j + 1), Some(Tok::Punct(':')))
351 {
352 match toks.get(j + 2) {
353 Some(Tok::Ident(n, _)) => {
354 callee.push_str("::");
355 callee.push_str(n);
356 j += 3;
357 }
358 _ => break,
359 }
360 }
361 if matches!(toks.get(j), Some(Tok::Punct('!'))) {
362 callee.push('!');
363 j += 1;
364 }
365 if !matches!(toks.get(j), Some(Tok::Punct('('))) {
366 continue;
367 }
368 if i > 0
370 && (matches!(toks.get(i - 1), Some(Tok::Punct('.')))
371 || matches!(toks.get(i - 1), Some(Tok::Ident(k, _)) if k == "fn"))
372 {
373 continue;
374 }
375 if i > 2
378 && matches!(toks.get(i - 1), Some(Tok::Punct(':')))
379 && matches!(toks.get(i - 2), Some(Tok::Punct(':')))
380 && matches!(toks.get(i - 3), Some(Tok::Ident(..)))
381 {
382 continue;
383 }
384 let Some(p) = patterns.iter().find(|p| names(&callee, p.callee)) else {
385 continue;
386 };
387 let args = arguments(&toks, j);
388 let literal = |n: usize| match args.get(n) {
389 Some(a) if a.len() == 1 => match &a[0] {
390 Tok::Str(s, _) => Some(s.clone()),
391 _ => None,
392 },
393 _ => None,
394 };
395 let origin = format!("{file}:{line}");
396 let mut unread = |reason: String| {
397 if constructor(p) {
398 let u = Unread {
399 callee: callee.clone(),
400 origin: origin.clone(),
401 reason,
402 };
403 log::warn!("i18n extraction: {u}");
404 out.unread.push(u);
405 }
406 };
407 let key = match literal(p.key) {
408 Some(k) if valid_key(&k) => k,
409 Some(k) => {
410 unread(format!("`{k}` is not a Fluent key"));
411 continue;
412 }
413 None => {
414 unread("the key is not a string literal".into());
415 continue;
416 }
417 };
418 let english = match p.english.map(|n| (n, literal(n))) {
419 Some((_, Some(e))) => English::Pattern(e),
420 Some((n, None)) => {
421 unread(format!(
422 "its English (argument {}) is not a string literal: `{key}` is kept without it",
423 n + 1
424 ));
425 English::None
426 }
427 None => English::None,
428 };
429 out.found.push(Found {
430 key,
431 english,
432 origin,
433 });
434 }
435 out
436}
437
438pub fn scan_source(source: &str, file: &str, patterns: &[Pattern]) -> Vec<Found> {
441 scan(source, file, patterns).found
442}
443
444fn arguments(toks: &[Tok], open: usize) -> Vec<Vec<Tok>> {
446 let mut out = vec![Vec::new()];
447 let mut depth = 0;
448 for t in &toks[open..] {
449 match t {
450 Tok::Punct('(' | '[' | '{') => {
451 depth += 1;
452 if depth == 1 {
453 continue;
454 }
455 }
456 Tok::Punct(')' | ']' | '}') => {
457 depth -= 1;
458 if depth == 0 {
459 break;
460 }
461 }
462 Tok::Punct(',') if depth == 1 => {
463 out.push(Vec::new());
464 continue;
465 }
466 _ => {}
467 }
468 if let Some(last) = out.last_mut() {
469 last.push(t.clone());
470 }
471 }
472 out
473}
474
475pub fn scan_tree(dir: &Path, patterns: &[Pattern]) -> io::Result<Scan> {
479 let mut files = Vec::new();
480 walk(dir, &mut files)?;
481 files.sort();
482 let mut out = Scan::default();
483 for f in files {
484 let source = std::fs::read_to_string(&f)?;
485 let name = f.strip_prefix(dir).unwrap_or(&f).display().to_string();
486 out.extend(scan(&source, &name, patterns));
487 }
488 Ok(out)
489}
490
491pub fn scan_dir(dir: &Path, patterns: &[Pattern]) -> io::Result<Vec<Found>> {
493 Ok(scan_tree(dir, patterns)?.found)
494}
495
496fn walk(dir: &Path, out: &mut Vec<std::path::PathBuf>) -> io::Result<()> {
497 for e in std::fs::read_dir(dir)? {
498 let p = e?.path();
499 let name = p.file_name().and_then(|n| n.to_str()).unwrap_or_default();
500 if p.is_dir() {
501 if name != "target" && !name.starts_with('.') {
502 walk(&p, out)?;
503 }
504 } else if p.extension().is_some_and(|e| e == "rs") {
505 out.push(p);
506 }
507 }
508 Ok(())
509}
510
511pub fn declarations(app: &AppHandle, menus: &[MenuId]) -> Vec<Found> {
518 let mut out = Vec::new();
519 let mut titles = Vec::new();
521 let mut push = |key: String, text: &str, origin: String| {
522 if !text.trim().is_empty() {
523 out.push(Found {
524 key,
525 english: English::Plain(text.to_string()),
526 origin,
527 });
528 }
529 };
530 let ctx = app.egui();
531 for (spec, _) in app.commands() {
532 let id = spec.id.as_str();
533 let origin = format!("command {id}");
534 if strings::panel_command(&ctx, id).is_none() {
537 if !spec.title.trim().is_empty() {
540 titles.push(Found {
541 key: strings::declared_key(kind::COMMAND, id, Some("title")),
542 english: plain_with(&spec.title, COMMAND_TITLE_VARIABLES),
543 origin: origin.clone(),
544 });
545 }
546 push(
547 strings::declared_key(kind::COMMAND, id, Some("description")),
548 &spec.description,
549 origin.clone(),
550 );
551 }
552 push(
553 strings::category_key(&spec.category),
554 &spec.category,
555 origin,
556 );
557 }
558 for p in app.panels() {
559 push(
560 strings::declared_key(kind::PANEL, p.id.as_str(), Some("title")),
561 &p.title,
562 format!("panel {}", p.id),
563 );
564 }
565 let mut seen = BTreeSet::new();
566 let mut todo: Vec<MenuId> = vec![MENU_MAIN];
567 todo.extend(menus.iter().cloned());
568 while let Some(menu) = todo.pop() {
569 if !seen.insert(menu.clone()) {
570 continue;
571 }
572 for item in app.menu(&menu) {
573 if let Item::Submenu { menu: sub, label } = &item.item {
574 push(
575 strings::declared_key(kind::MENU, sub.as_str(), Some("label")),
576 label,
577 format!("menu {sub}"),
578 );
579 todo.push(sub.clone());
580 }
581 }
582 }
583 for s in app.settings() {
584 let id = s.id.as_str();
585 let origin = format!("setting {id}");
586 push(
587 strings::declared_key(kind::SETTING, id, Some("label")),
588 &s.descriptor.label,
589 origin.clone(),
590 );
591 push(
592 strings::declared_key(kind::SETTING, id, Some("description")),
593 &s.descriptor.description,
594 origin.clone(),
595 );
596 for c in &s.descriptor.choices {
597 push(strings::setting_choice_key(id, c), c, origin.clone());
598 }
599 }
600 for p in app.plugins().into_iter().filter(|p| p.connected) {
601 push(
602 strings::declared_key(kind::PLUGIN, p.id.as_str(), Some("title")),
603 &p.title,
604 format!("plugin {}", p.id),
605 );
606 }
607 for (_, t) in egui_pop_api::clipboard::types(app) {
608 push(
609 egui_pop_api::clipboard::type_title_key(&t.format),
610 &t.title,
611 format!("clipboard type {}", t.format),
612 );
613 }
614 let frames = egui_pop_api::contexts::with_owner(app, |c| c.registry()).unwrap_or_default();
615 for f in frames.iter() {
616 push(
617 strings::declared_key(kind::FRAME, f.id.as_str(), Some("title")),
618 &f.title,
619 format!("frame {}", f.id),
620 );
621 }
622 out.extend(titles);
623 out
624}
625
626pub type Messages = BTreeMap<String, English>;
628
629pub fn messages(found: &[Found]) -> Result<Messages, String> {
633 let mut out: Messages = BTreeMap::new();
634 let mut origin: BTreeMap<&str, &str> = BTreeMap::new();
635 let mut errors = Vec::new();
636 for f in found {
637 match out.get(&f.key) {
638 None => {
639 out.insert(f.key.clone(), f.english.clone());
640 origin.insert(&f.key, &f.origin);
641 }
642 Some(English::None) => {
643 out.insert(f.key.clone(), f.english.clone());
644 }
645 Some(e) if *e == f.english || f.english == English::None => {}
646 Some(_) if f.key.starts_with("category-") => {}
647 Some(e) => errors.push(format!(
648 "`{}` has two English texts: {e:?} ({}) and {:?} ({})",
649 f.key,
650 origin.get(f.key.as_str()).unwrap_or(&"?"),
651 f.english,
652 f.origin
653 )),
654 }
655 }
656 if errors.is_empty() {
657 Ok(out)
658 } else {
659 Err(errors.join("\n"))
660 }
661}
662
663pub const COMMAND_TITLE_VARIABLES: &[&str] = &["application"];
666
667pub fn plain_with(text: &str, variables: &[&str]) -> English {
681 let mut pattern = escape(text);
682 let mut found = false;
683 for v in variables {
684 for (spaced, written) in [(true, format!("{{ ${v} }}")), (false, format!("{{${v}}}"))] {
685 let escaped = if spaced {
686 format!("{{\"{{\"}} ${v} {{\"}}\"}}")
687 } else {
688 format!("{{\"{{\"}}${v}{{\"}}\"}}")
689 };
690 if text.contains(&written) {
691 found = true;
692 pattern = pattern.replace(&escaped, &format!("{{ ${v} }}"));
693 }
694 }
695 }
696 if found {
697 English::Pattern(pattern)
698 } else {
699 English::Plain(text.to_string())
700 }
701}
702
703pub fn escape(text: &str) -> String {
707 let text = text.trim();
708 let mut out = String::new();
709 for (n, line) in text.split('\n').enumerate() {
710 if n > 0 {
711 out.push('\n');
712 }
713 let mut chars = line.trim_start().chars().peekable();
714 if n > 0 && matches!(chars.peek(), Some('[' | '*' | '.')) {
715 let c = chars.next().expect("peeked");
716 let _ = write!(out, "{{\"{c}\"}}");
717 }
718 for c in chars {
719 match c {
720 '{' => out.push_str("{\"{\"}"),
721 '}' => out.push_str("{\"}\"}"),
722 c => out.push(c),
723 }
724 }
725 }
726 out
727}
728
729fn indent(pattern: &str) -> String {
731 pattern.trim().replace('\n', "\n ")
732}
733
734fn existing(source: &str) -> BTreeMap<String, String> {
736 let resource = match fluent_syntax::parser::parse(source) {
737 Ok(r) | Err((r, _)) => r,
738 };
739 let mut out = BTreeMap::new();
740 for entry in &resource.body {
741 if let Entry::Message(m) = entry {
742 if let Some(v) = &m.value {
743 out.insert(m.id.name.to_string(), serialize(v));
744 }
745 for a in &m.attributes {
746 out.insert(format!("{}.{}", m.id.name, a.id.name), serialize(&a.value));
747 }
748 }
749 }
750 out
751}
752
753pub(crate) fn serialize(pattern: &FtlPattern<&str>) -> String {
755 let resource = Resource {
756 body: vec![Entry::Message(Message {
757 id: Identifier { name: "m" },
758 value: Some(pattern.clone()),
759 attributes: Vec::new(),
760 comment: None,
761 })],
762 };
763 let s = fluent_syntax::serializer::serialize(&resource);
764 let s = s.strip_prefix("m =").unwrap_or(&s);
765 s.trim_end()
767 .lines()
768 .map(|l| l.strip_prefix(" ").unwrap_or(l))
769 .collect::<Vec<_>>()
770 .join("\n")
771 .trim()
772 .to_string()
773}
774
775fn write(header: &str, patterns: &BTreeMap<String, String>) -> String {
778 let mut messages: BTreeMap<&str, (Option<&str>, BTreeMap<&str, &str>)> = BTreeMap::new();
779 for (key, pattern) in patterns {
780 let (id, attr) = crate::catalog::split_key(key);
781 let entry = messages.entry(id).or_default();
782 match attr {
783 Some(a) => {
784 entry.1.insert(a, pattern);
785 }
786 None => entry.0 = Some(pattern),
787 }
788 }
789 let mut out = String::from(header);
790 for (id, (value, attrs)) in messages {
791 if !out.is_empty() {
792 out.push('\n');
793 }
794 out.push_str(id);
795 out.push_str(" =");
796 if let Some(v) = value {
797 out.push(' ');
798 out.push_str(&indent(v));
799 }
800 out.push('\n');
801 for (a, v) in attrs {
802 let _ = writeln!(out, " .{a} = {}", indent(v).replace('\n', "\n "));
803 }
804 }
805 out
806}
807
808fn pattern_of(english: &English) -> Option<String> {
810 match english {
811 English::Plain(t) => Some(escape(t)),
812 English::Pattern(p) => Some(p.trim().to_string()),
813 English::None => None,
814 }
815}
816
817pub fn english(messages: &Messages, header: &str) -> String {
821 let patterns = messages
822 .iter()
823 .map(|(k, e)| (k.clone(), pattern_of(e).unwrap_or_else(|| k.clone())))
824 .collect();
825 write(header, &patterns)
826}
827
828#[derive(Clone, Debug, Default, PartialEq, Eq)]
830pub struct Updated {
831 pub source: String,
833 pub added: Vec<String>,
835 pub changed: Vec<String>,
837 pub unused: Vec<String>,
839}
840
841pub fn update(source: &str, messages: &Messages, header: &str, prune: bool) -> Updated {
846 let old = existing(source);
847 let mut out = Updated::default();
848 let mut patterns = BTreeMap::new();
849 for (key, english) in messages {
850 let new = pattern_of(english);
851 let pattern = match (old.get(key), new) {
852 (None, new) => {
853 out.added.push(key.clone());
854 new.unwrap_or_else(|| key.clone())
855 }
856 (Some(was), Some(new)) => {
857 if canonical(was) != canonical(&new) {
858 out.changed.push(key.clone());
859 }
860 new
861 }
862 (Some(was), None) => was.clone(),
863 };
864 patterns.insert(key.clone(), pattern);
865 }
866 for (key, was) in &old {
867 if !messages.contains_key(key) {
868 out.unused.push(key.clone());
869 if !prune {
870 patterns.insert(key.clone(), was.clone());
871 }
872 }
873 }
874 out.source = write(header, &patterns);
875 out
876}
877
878pub fn out_of_date(path: &str, current: &str, fresh: &str, unread: &[Unread]) -> Option<String> {
884 if current == fresh {
885 return None;
886 }
887 let mut out = format!("{path} is out of date");
888 if !unread.is_empty() {
889 out.push_str("; the extractor could not read these calls, their messages are missing:");
890 for u in unread {
891 let _ = write!(out, "\n {u}");
892 }
893 }
894 Some(out)
895}
896
897fn canonical(pattern: &str) -> String {
899 existing(&format!("m = {}\n", indent(pattern)))
900 .remove("m")
901 .unwrap_or_else(|| pattern.to_string())
902}
903
904#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize)]
906pub struct LocaleKeys {
907 pub locale: String,
908 pub missing: Vec<String>,
910 pub unused: Vec<String>,
912}
913
914pub fn report(catalogs: &crate::check::Catalogs, messages: &Messages) -> Vec<LocaleKeys> {
916 let mut keys: BTreeMap<&str, BTreeSet<String>> = BTreeMap::new();
917 for f in &catalogs.files {
918 keys.entry(&f.locale)
919 .or_default()
920 .extend(existing(&f.source).into_keys());
921 }
922 keys.into_iter()
923 .map(|(locale, theirs)| LocaleKeys {
924 locale: locale.to_string(),
925 missing: messages
926 .keys()
927 .filter(|k| !theirs.contains(*k))
928 .cloned()
929 .collect(),
930 unused: theirs
931 .iter()
932 .filter(|k| !messages.contains_key(*k))
933 .cloned()
934 .collect(),
935 })
936 .collect()
937}
938
939#[cfg(test)]
940mod tests {
941 use super::*;
942
943 #[test]
944 fn calls_are_found_with_their_english() {
945 let src = r##"
946 // tr!("in-a-comment")
947 fn t(x: &str) {}
948 let a = tr!("plain");
949 let b = egui_pop_i18n::t(&ctx, "with-path", &args![n = 1]);
950 let c = obj.t(&ctx, "a-method");
951 const K: StrKey = StrKey::new(
952 "multi-line",
953 "Line { $n }",
954 );
955 let d = strings::lookup(ui.ctx(), "lookup-key", r#"Raw "quoted""#);
956 let e = tr!(dynamic_key);
957 let f = tr!("not a key");
958 let g = text(ctx, "attr-key.title", "Esc\"aped\n", &[]);
959 "##;
960 let found = scan_source(src, "x.rs", Pattern::DEFAULTS);
961 let keys: Vec<(&str, &English)> =
962 found.iter().map(|f| (f.key.as_str(), &f.english)).collect();
963 assert_eq!(
964 keys,
965 [
966 ("plain", &English::None),
967 ("with-path", &English::None),
968 ("multi-line", &English::Pattern("Line { $n }".into())),
969 ("lookup-key", &English::Pattern("Raw \"quoted\"".into())),
970 ("attr-key.title", &English::Pattern("Esc\"aped\n".into())),
971 ]
972 );
973 assert_eq!(found[0].origin, "x.rs:4");
974 assert_eq!(found[2].origin, "x.rs:7");
975 }
976
977 const MESSAGE: &[Pattern] = &[
979 Pattern {
980 callee: "Message::new",
981 key: 0,
982 english: Some(1),
983 },
984 Pattern {
985 callee: "t",
986 key: 1,
987 english: None,
988 },
989 ];
990
991 #[test]
992 fn a_path_qualified_constructor_is_extracted() {
993 let src = r#"
994 const A: Message = Message::new("plain", "Plain");
995 const B: Message = app_core::Message::new("one-segment", "One");
996 const C: Message = crate::strings::Message::new("crate-path", "Crate");
997 const D: Message = ::app_core::Message::new("leading-colons", "Leading");
998 const E: StrKey = egui_pop::core::strings::StrKey::new("str-key", "Key");
999 const F: Other = app::NotMessage::new("not-ours", "No");
1000 "#;
1001 let mut patterns = MESSAGE.to_vec();
1002 patterns.extend_from_slice(Pattern::DEFAULTS);
1003 let s = scan(src, "x.rs", &patterns);
1004 let keys: Vec<&str> = s.found.iter().map(|f| f.key.as_str()).collect();
1005 assert_eq!(
1006 keys,
1007 [
1008 "plain",
1009 "one-segment",
1010 "crate-path",
1011 "leading-colons",
1012 "str-key"
1013 ]
1014 );
1015 assert_eq!(s.found[2].english, English::Pattern("Crate".into()));
1016 assert_eq!(s.found[3].origin, "x.rs:5");
1017 assert!(s.unread.is_empty(), "{:?}", s.unread);
1018 }
1019
1020 #[test]
1021 fn a_multi_line_qualified_constructor_is_extracted() {
1022 let src = "
1023 pub const READY: Message = app_core
1024 ::strings::
1025 Message // the status bar's
1026 ::new(
1027 \"status-ready\",
1028 \"Ready\",
1029 );
1030 ";
1031 let s = scan(src, "src/status.rs", MESSAGE);
1032 assert_eq!(
1033 s.found,
1034 [Found {
1035 key: "status-ready".into(),
1036 english: English::Pattern("Ready".into()),
1037 origin: "src/status.rs:2".into(),
1038 }]
1039 );
1040 assert!(s.unread.is_empty(), "{:?}", s.unread);
1041 }
1042
1043 #[test]
1044 fn an_unreadable_constructor_is_reported_with_its_file_and_line() {
1045 let src = r#"
1046 const OK: Message = Message::new("fine", "Fine");
1047 let dynamic = app::Message::new(id, "Text");
1048 let bad = Message::new("not a key", "Text");
1049 let computed = app::Message::new(
1050 "computed",
1051 concat!("Comp", "uted"),
1052 );
1053 // Not a constructor: a dynamic key stays silent.
1054 let looked_up = t(ctx, key);
1055 "#;
1056 let s = scan(src, "src/ui.rs", MESSAGE);
1057 let keys: Vec<(&str, &English)> = s
1058 .found
1059 .iter()
1060 .map(|f| (f.key.as_str(), &f.english))
1061 .collect();
1062 assert_eq!(
1063 keys,
1064 [
1065 ("fine", &English::Pattern("Fine".into())),
1066 ("computed", &English::None)
1067 ]
1068 );
1069 let places: Vec<(&str, &str)> = s
1070 .unread
1071 .iter()
1072 .map(|u| (u.origin.as_str(), u.callee.as_str()))
1073 .collect();
1074 assert_eq!(
1075 places,
1076 [
1077 ("src/ui.rs:3", "app::Message::new"),
1078 ("src/ui.rs:4", "Message::new"),
1079 ("src/ui.rs:5", "app::Message::new"),
1080 ]
1081 );
1082 assert_eq!(
1083 s.unread[0].to_string(),
1084 "src/ui.rs:3: `app::Message::new(…)` not read: the key is not a string literal"
1085 );
1086 let m = messages(&s.found).unwrap();
1088 let fresh = english(&m, "");
1089 assert_eq!(out_of_date("en/app.ftl", &fresh, &fresh, &s.unread), None);
1090 let failure = out_of_date("en/app.ftl", "", &fresh, &s.unread).unwrap();
1091 assert!(
1092 failure.starts_with("en/app.ftl is out of date"),
1093 "{failure}"
1094 );
1095 for u in &s.unread {
1096 assert!(failure.contains(&u.to_string()), "{failure}");
1097 }
1098 }
1099
1100 #[test]
1101 fn a_command_title_keeps_its_application_placeable() {
1102 let found = vec![Found {
1103 key: "command-about.title".into(),
1104 english: plain_with("About { $application }", COMMAND_TITLE_VARIABLES),
1105 origin: "command about".into(),
1106 }];
1107 let ftl = english(&messages(&found).unwrap(), "");
1108 assert_eq!(
1109 ftl.trim(),
1110 "command-about =\n .title = About { $application }"
1111 );
1112 let i = crate::I18n::new("en");
1113 i.add("en", &ftl).unwrap();
1114 assert_eq!(
1115 i.t("command-about.title", &[("application", "Helios".into())]),
1116 "About Helios"
1117 );
1118 assert_eq!(
1120 plain_with("{$application} {x}", COMMAND_TITLE_VARIABLES),
1121 English::Pattern("{ $application } {\"{\"}x{\"}\"}".into())
1122 );
1123 }
1124
1125 #[test]
1126 fn the_english_catalogue_is_sorted_and_round_trips() {
1127 let found = vec![
1128 Found {
1129 key: "command-b.title".into(),
1130 english: English::Plain("Use {braces}".into()),
1131 origin: "command b".into(),
1132 },
1133 Found {
1134 key: "a".into(),
1135 english: English::Pattern("Hi { $name }".into()),
1136 origin: "x.rs:1".into(),
1137 },
1138 Found {
1139 key: "command-b.description".into(),
1140 english: English::Plain("Two\nlines".into()),
1141 origin: "command b".into(),
1142 },
1143 ];
1144 let m = messages(&found).unwrap();
1145 let ftl = english(&m, "# Generated.\n");
1146 assert_eq!(
1147 ftl,
1148 "# Generated.\n\na = Hi { $name }\n\ncommand-b =\n .description = Two\n lines\n .title = Use {\"{\"}braces{\"}\"}\n"
1149 );
1150 let i = crate::I18n::new("en");
1151 i.add("en", &ftl).unwrap();
1152 assert_eq!(i.t("command-b.title", &[]), "Use {braces}");
1153 assert_eq!(i.t("command-b.description", &[]), "Two\nlines");
1154 let mut twice = found.clone();
1155 twice.push(Found {
1156 key: "a".into(),
1157 english: English::Pattern("Other".into()),
1158 origin: "y.rs:2".into(),
1159 });
1160 assert!(messages(&twice).unwrap_err().contains("x.rs:1"));
1161 }
1162
1163 #[test]
1164 fn update_keeps_written_english_and_reports_changes() {
1165 let old = "# h\n\nkept = Written by hand\nold = Gone\nchanged = Before\n";
1166 let mut m = Messages::new();
1167 m.insert("kept".into(), English::None);
1168 m.insert("changed".into(), English::Pattern("After".into()));
1169 m.insert("new".into(), English::None);
1170 let u = update(old, &m, "# h\n", false);
1171 assert_eq!(u.added, ["new"]);
1172 assert_eq!(u.changed, ["changed"]);
1173 assert_eq!(u.unused, ["old"]);
1174 assert!(u.source.contains("kept = Written by hand\n"));
1175 assert!(u.source.contains("new = new\n"));
1176 assert!(u.source.contains("old = Gone\n"));
1177 let pruned = update(old, &m, "# h\n", true);
1178 assert!(!pruned.source.contains("old ="));
1179 let again = update(&u.source, &m, "# h\n", false);
1181 assert_eq!(again.source, u.source);
1182 assert!(again.added.is_empty() && again.changed.is_empty());
1183 }
1184
1185 #[test]
1186 fn the_context_stack_frames_are_declarations() {
1187 use egui_pop_api::contexts::{self, ContextsPlugin, FrameSpec};
1188 use egui_pop_api::{Ctx, Plugin, PluginError};
1189 use egui_pop_model::ids::{FrameId, GroupId, PluginId};
1190 struct Frames;
1191 impl Plugin for Frames {
1192 fn id(&self) -> PluginId {
1193 PluginId::from_static("demo")
1194 }
1195 fn requires(&self) -> Vec<PluginId> {
1196 vec![contexts::PLUGIN]
1197 }
1198 fn connect(&mut self, ctx: &mut Ctx<'_>) -> Result<(), PluginError> {
1199 ctx.frame(FrameSpec::place(
1200 FrameId::from_static("demo.album"),
1201 "Album",
1202 ))?
1203 .frame(FrameSpec::mode(
1204 FrameId::from_static("demo.culling"),
1205 GroupId::from_static("orientation"),
1206 "Culling",
1207 ))?;
1208 Ok(())
1209 }
1210 }
1211 let app = egui_pop_api::App::builder()
1212 .plugin(ContextsPlugin::default())
1213 .plugin(Frames)
1214 .build(&egui::Context::default())
1215 .unwrap();
1216 let found = declarations(app.handle(), &[]);
1217 let frames: Vec<(&str, &English, &str)> = found
1218 .iter()
1219 .filter(|f| f.key.starts_with("frame-"))
1220 .map(|f| (f.key.as_str(), &f.english, f.origin.as_str()))
1221 .collect();
1222 assert_eq!(
1223 frames,
1224 [
1225 (
1226 "frame-demo-album.title",
1227 &English::Plain("Album".into()),
1228 "frame demo.album"
1229 ),
1230 (
1231 "frame-demo-culling.title",
1232 &English::Plain("Culling".into()),
1233 "frame demo.culling"
1234 ),
1235 ]
1236 );
1237 }
1238
1239 #[test]
1240 fn multi_line_patterns_survive_a_rewrite() {
1241 let old = "plural =\n { $n ->\n [one] one\n *[other] many\n }\n";
1242 let mut m = Messages::new();
1243 m.insert("plural".into(), English::None);
1244 let u = update(old, &m, "", false);
1245 let i = crate::I18n::new("en");
1246 i.add("en", &u.source).unwrap();
1247 assert_eq!(i.t("plural", &crate::args![n = 1]), "one");
1248 assert_eq!(i.t("plural", &crate::args![n = 5]), "many");
1249 }
1250}