Skip to content

PdfCraft: An open-source PDF reader and editor written by scratch in pure Rust

Print ▸ Properties…: the driver's options in the UI language

Dimitar Klaturova9320efd7aea
diff --git a/crates/print/src/spool.rs b/crates/print/src/spool.rs
index cf1c0cb76..eb7b82b4b 100644
--- a/crates/print/src/spool.rs
+++ b/crates/print/src/spool.rs
@@ -10,12 +10,20 @@ pub use craft_print::{
/// empty when it has none or on other platforms. Reads files and runs `lpoptions`, so call it
/// when the user asks, not every frame.
pub fn printer_options(printer: &str) -> Vec<PrinterOption> {
+ printer_options_in(printer, "en")
+}
+
+/// [`printer_options`] with the driver's own names in `lang` (a UI language code such as `bg`,
+/// `pt-br` or `zh-hans`) where its PPD has them (`*bg.Translation`, `*bg.InputSlot Tray2/…`);
+/// the driver's default names otherwise.
+pub fn printer_options_in(printer: &str, lang: &str) -> Vec<PrinterOption> {
#[cfg(all(unix, not(target_arch = "wasm32")))]
{
- printer_options_via(printer, std::path::Path::new("/etc/cups/ppd"), std::process::Command::new("lpoptions"))
+ printer_options_via(printer, std::path::Path::new("/etc/cups/ppd"), std::process::Command::new("lpoptions"), lang)
}
#[cfg(not(all(unix, not(target_arch = "wasm32"))))]
{
+ let _ = lang;
craft_print::printer_options(printer)
}
}
@@ -24,7 +32,7 @@ pub fn printer_options(printer: &str) -> Vec<PrinterOption> {
/// neither a system queue nor a physical printer. CUPS instances share their queue's PPD but
/// have their own defaults, queried with the complete `queue/instance` destination.
#[cfg(all(unix, not(target_arch = "wasm32")))]
-pub(crate) fn printer_options_via(printer: &str, ppd_dir: &std::path::Path, mut lpoptions: std::process::Command) -> Vec<PrinterOption> {
+pub(crate) fn printer_options_via(printer: &str, ppd_dir: &std::path::Path, mut lpoptions: std::process::Command, lang: &str) -> Vec<PrinterOption> {
let (queue, instance) = printer.split_once('/').map_or((printer, None), |(q, i)| (q, Some(i)));
// Retain the conservative name checks, applied to each component. Neither component is
// a path: reject dot components, backslashes and any additional separator before I/O.
@@ -43,7 +51,10 @@ pub(crate) fn printer_options_via(printer: &str, ppd_dir: &std::path::Path, mut
let mut bytes = Vec::new();
f.take(PPD_CAP).read_to_end(&mut bytes).ok().map(|_| bytes)
});
- let mut options = ppd.map(|b| parse_ppd(&ppd_text(&b))).unwrap_or_default();
+ let mut options = ppd.as_deref().map(|b| parse_ppd(&ppd_text(b))).unwrap_or_default();
+ if let Some(b) = &ppd {
+ localize(&mut options, b, lang);
+ }
let current = lpoptions.args(["-p", printer, "-l"]).output().map(|o| parse_lpoptions(&String::from_utf8_lossy(&o.stdout))).unwrap_or_default();
for (key, value) in current {
if let Some(o) = options.iter_mut().find(|o| o.key == key)
@@ -68,3 +79,77 @@ pub fn submit_with_progress(pdf: &[u8], job: &Job, progress: &mut dyn FnMut(usiz
pub fn open_printer_preferences(printer: &str) -> Result<(), crate::PrintError> {
craft_print::open_printer_preferences(printer).map_err(|e| crate::PrintError::Spool(e.to_string()))
}
+
+/// The PPD language codes (`*cupsLanguages`, the `ll` of `*ll.Translation`) to try for a UI
+/// language code, most specific first: `pt-br` → `pt_BR`, `pt`; `zh-hans` → `zh_CN`, `zh`.
+fn ppd_languages(lang: &str) -> Vec<String> {
+ let lang = lang.to_ascii_lowercase();
+ let mut parts = lang.split(['-', '_']).filter(|p| !p.is_empty());
+ let Some(primary) = parts.next() else { return Vec::new() };
+ let region = match (primary, parts.next()) {
+ ("zh", Some("hans")) => Some("CN".to_string()),
+ ("zh", Some("hant")) => Some("TW".to_string()),
+ (_, Some(r)) if r.len() == 2 => Some(r.to_ascii_uppercase()),
+ _ => None,
+ };
+ region.map(|r| format!("{primary}_{r}")).into_iter().chain(std::iter::once(primary.to_string())).collect()
+}
+
+/// Give `options` the driver's own names in `lang` from the PPD's localization lines
+/// (`*ll.Translation Key/Label: ""` for options and groups, `*ll.Key choice/Label: ""` for
+/// choices). Each line is read as UTF-8 on its own: drivers write them so in files whose other
+/// text is Latin-1. Names with no translation, or an empty one, stay as they are.
+pub(crate) fn localize(options: &mut [PrinterOption], ppd: &[u8], lang: &str) {
+ use std::collections::HashMap;
+ let Some(code) = ppd_languages(lang).into_iter().find(|code| {
+ let prefix = format!("*{code}.");
+ ppd.split(|b| *b == b'\n').any(|l| l.starts_with(prefix.as_bytes()))
+ }) else {
+ return;
+ };
+ if code == "en" {
+ return;
+ }
+ let prefix = format!("*{code}.");
+ let mut names: HashMap<String, String> = HashMap::new();
+ let mut choices: HashMap<(String, String), String> = HashMap::new();
+ let mut groups: HashMap<String, String> = HashMap::new();
+ for line in ppd.split(|b| *b == b'\n') {
+ let Some(text) = std::str::from_utf8(line).ok() else { continue };
+ let text = text.trim_end_matches('\r');
+ if let Some(rest) = text.strip_prefix("*OpenGroup:") {
+ // Group label → keyword, since options carry their group's label.
+ let rest = rest.trim();
+ if let Some((key, label)) = rest.split_once('/') {
+ groups.insert(label.trim().to_string(), key.trim().to_string());
+ }
+ continue;
+ }
+ let Some(rest) = text.strip_prefix(prefix.as_str()) else { continue };
+ let Some((head, _)) = rest.split_once(':') else { continue };
+ let Some((main, spec)) = head.split_once(' ') else { continue };
+ let Some((key, label)) = spec.split_once('/') else { continue };
+ let label = label.trim();
+ if label.is_empty() {
+ continue;
+ }
+ if main == "Translation" {
+ names.insert(key.trim().to_string(), label.to_string());
+ } else {
+ choices.insert((main.to_string(), key.trim().to_string()), label.to_string());
+ }
+ }
+ for o in options.iter_mut() {
+ if let Some(label) = names.get(&o.key) {
+ o.label = label.clone();
+ }
+ if let Some(label) = groups.get(&o.group).and_then(|key| names.get(key)) {
+ o.group = label.clone();
+ }
+ for (choice, label) in o.choices.iter_mut() {
+ if let Some(t) = choices.get(&(o.key.clone(), choice.clone())) {
+ *label = t.clone();
+ }
+ }
+ }
+}
diff --git a/crates/print/src/tests.rs b/crates/print/src/tests.rs
index d4b0c8ee1..35fdd5008 100644
--- a/crates/print/src/tests.rs
+++ b/crates/print/src/tests.rs
@@ -556,7 +556,7 @@ mod cups_options {
(boundary_queue.as_str(), "Tray2", "Tray2"),
(boundary_instance.as_str(), "Tray2", "Tray2"),
] {
- let options = spool::printer_options_via(destination, &dir, command(&dir, &format!("InputSlot/Paper tray: *{current}")));
+ let options = spool::printer_options_via(destination, &dir, command(&dir, &format!("InputSlot/Paper tray: *{current}")), "en");
assert_eq!(options.len(), 1, "{destination}: the queue's PPD must be read");
assert_eq!(options[0].default, expected, "{destination}: only valid instance choices override the PPD default");
assert_eq!(options[0].choices, [("Auto".into(), "Automatic".into()), ("Tray2".into(), "Tray 2".into())]);
@@ -597,7 +597,7 @@ mod cups_options {
long_queue_instance.as_str(),
long_instance.as_str(),
] {
- assert!(spool::printer_options_via(destination, &dir, command(&dir, "InputSlot: *Auto")).is_empty(), "{destination:?}");
+ assert!(spool::printer_options_via(destination, &dir, command(&dir, "InputSlot: *Auto"), "en").is_empty(), "{destination:?}");
assert!(!dir.join("args").exists(), "{destination:?}: rejected before spawning");
}
std::fs::remove_dir_all(dir).unwrap();
@@ -743,3 +743,33 @@ fn imposed_pages_preserve_large_user_unit_matrices() {
}
}
}
+
+#[test]
+fn driver_options_take_the_ppds_own_names_in_the_ui_language() {
+ use crate::spool::{PrinterOption, localize, parse_ppd, ppd_text};
+ // Latin-1 elsewhere (the é), UTF-8 in the localization lines, as drivers ship them.
+ let mut ppd = b"*cupsLanguages: \"bg pt_BR\"\n*OpenGroup: Finishing/Finishing Options\n*OpenUI *KMDuplex/Print Type: PickOne\n*DefaultKMDuplex: Single\n*KMDuplex Single/1-Sided: \"\"\n*KMDuplex Double/2-Sided: \"\"\n*CloseUI: *KMDuplex\n*OpenUI *Staple/Staple: PickOne\n*DefaultStaple: None\n*Staple None/None: \"\"\n*CloseUI: *Staple\n*CloseGroup: Finishing\n*fr.Translation KMDuplex/Type d'impression r".to_vec();
+ ppd.push(0xE9);
+ ppd.extend_from_slice("el: \"\"\n*bg.Translation Finishing/Довършителни операции: \"\"\n*bg.Translation KMDuplex/Тип печат: \"\"\n*bg.KMDuplex Single/Едностранен: \"\"\n*bg.KMDuplex Double/: \"\"\n*pt_BR.Translation KMDuplex/Tipo de impressão: \"\"\n".as_bytes());
+ let parsed = parse_ppd(&ppd_text(&ppd));
+ let label = |o: &[PrinterOption], key: &str| o.iter().find(|o| o.key == key).map(|o| o.label.clone()).unwrap();
+ let mut bg = parsed.clone();
+ localize(&mut bg, &ppd, "bg");
+ let duplex = bg.iter().find(|o| o.key == "KMDuplex").unwrap();
+ assert_eq!((duplex.label.as_str(), duplex.group.as_str()), ("Тип печат", "Довършителни операции"));
+ assert_eq!(
+ duplex.choices,
+ [("Single".to_string(), "Едностранен".to_string()), ("Double".to_string(), "2-Sided".to_string())],
+ "an empty translation keeps the driver's name"
+ );
+ assert_eq!(label(&bg, "Staple"), "Staple", "untranslated options keep theirs");
+ // Region-specific codes, then the language alone; languages the PPD lacks change nothing.
+ let mut pt = parsed.clone();
+ localize(&mut pt, &ppd, "pt-br");
+ assert_eq!(label(&pt, "KMDuplex"), "Tipo de impressão");
+ for lang in ["en", "de", "", "bg-"] {
+ let mut other = parsed.clone();
+ localize(&mut other, &ppd, lang);
+ assert_eq!(other == parsed, lang != "bg-", "{lang:?}");
+ }
+}
diff --git a/crates/ui-egui/src/print_ui.rs b/crates/ui-egui/src/print_ui.rs
index 4e0f06588..e42f1617e 100644
--- a/crates/ui-egui/src/print_ui.rs
+++ b/crates/ui-egui/src/print_ui.rs
@@ -855,7 +855,7 @@ pub(crate) fn body(
d.driver_error = spool::open_printer_preferences(&p).err().map(|e| e.to_string());
} else {
if d.driver_options.as_ref().is_none_or(|(read_for, _)| *read_for != p) {
- d.driver_options = Some((p.clone(), spool::printer_options(&p)));
+ d.driver_options = Some((p.clone(), spool::printer_options_in(&p, crate::i18n::current().code())));
d.driver_choices.clear();
}
d.show_driver_options = !d.show_driver_options;