Skip to content

Your Android phone and your Windows PC, working as one. Local-first, end-to-end encrypted, no account.

Windows: translate the text the app builds in Rust

Bee269af3b2b9a4
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index b0cc9fe..c4948ef 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -44,7 +44,9 @@ jobs:
run: cargo test --locked $CORE_CRATES
- name: Generated files are up to date
if: runner.os == 'Linux'
- run: cargo xtask tokens --check
+ run: |
+ cargo xtask tokens --check
+ cargo xtask strings --check
desktop:
name: Windows app (x64)
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 5aca078..9326987 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -61,8 +61,11 @@ These come from the plan and will grow into a full style guide:
- **One bridge.** Only `desktop/app/src/bridge` (cxx-qt) connects Rust to Qt.
- **Privacy first.** Never log notification text, message content, file names
or keys. No telemetry.
-- **All user-facing strings are translatable** (`qsTr` in QML, string
- resources on Android).
+- **All user-facing strings are translatable**: `qsTr` in QML,
+ `tr!("Context", "Sent to %1", name)` for text the desktop app builds in
+ Rust, string resources on Android. After changing Rust text, run
+ `cargo xtask strings`, then
+ `lupdate desktop/app/qml desktop/app/i18n/rust_strings.h -ts desktop/app/i18n/nectarlink_zh_CN.ts`.
- **Accessibility is not optional.** Labels for screen readers and full
keyboard navigation from day one.
- Format with `cargo fmt` and keep `cargo clippy` clean. Android code follows
diff --git a/desktop/app/i18n/rust_strings.h b/desktop/app/i18n/rust_strings.h
new file mode 100644
index 0000000..800d6d1
--- /dev/null
+++ b/desktop/app/i18n/rust_strings.h
@@ -0,0 +1,112 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+// Generated by `cargo xtask strings` from the tr! calls in desktop/app/src. Do not edit.
+// Never compiled: lupdate reads it with the QML, so the text the app builds
+// in Rust is translated like the rest (see desktop/app/src/i18n.rs).
+
+static const char *const nectarlink_rust_strings[] = {
+ QT_TRANSLATE_NOOP("App", "Already on clipboard."), // desktop/app/src/bridge/app.rs
+ QT_TRANSLATE_NOOP("App", "Copied to clipboard."), // desktop/app/src/bridge/app.rs
+ QT_TRANSLATE_NOOP("App", "Could not copy to the clipboard."), // desktop/app/src/bridge/app.rs
+ QT_TRANSLATE_NOOP("App", "No phone is paired yet."), // desktop/app/src/bridge/app.rs
+ QT_TRANSLATE_NOOP("App", "Send cancelled"), // desktop/app/src/bridge/app.rs
+ QT_TRANSLATE_NOOP("App", "Sending to %1…"), // desktop/app/src/bridge/app.rs
+ QT_TRANSLATE_NOOP("App", "Sent text to %1."), // desktop/app/src/bridge/app.rs
+ QT_TRANSLATE_NOOP("App", "Some history couldn't be cleared. Try again."), // desktop/app/src/bridge/app.rs
+ QT_TRANSLATE_NOOP("App", "Some messages couldn't be cleared. Try again."), // desktop/app/src/bridge/app.rs
+ QT_TRANSLATE_NOOP("App", "That file is no longer in its saved location."), // desktop/app/src/bridge/app.rs
+ QT_TRANSLATE_NOOP("App", "The photo couldn't be copied to the clipboard."), // desktop/app/src/bridge/app.rs
+ QT_TRANSLATE_NOOP("App", "The received file history couldn't be cleared. Try again."), // desktop/app/src/bridge/app.rs
+ QT_TRANSLATE_NOOP("Calls", "That call is over."), // desktop/app/src/calls.rs
+ QT_TRANSLATE_NOOP("Clipboard", "Copied from %1."), // desktop/app/src/clipboard.rs
+ QT_TRANSLATE_NOOP("Clipboard", "Copied to clipboard"), // desktop/app/src/clipboard.rs
+ QT_TRANSLATE_NOOP("Clipboard", "Sending copied files to %1…"), // desktop/app/src/clipboard.rs
+ QT_TRANSLATE_NOOP("Clipboard", "Sent to %1."), // desktop/app/src/clipboard.rs
+ QT_TRANSLATE_NOOP("Clipboard", "That clip is no longer in clipboard history."), // desktop/app/src/clipboard.rs
+ QT_TRANSLATE_NOOP("Clipboard", "That image can't be read."), // desktop/app/src/clipboard.rs
+ QT_TRANSLATE_NOOP("Clipboard", "That image is too large to send."), // desktop/app/src/clipboard.rs
+ QT_TRANSLATE_NOOP("Clipboard", "That's too much text to send at once."), // desktop/app/src/clipboard.rs
+ QT_TRANSLATE_NOOP("Clipboard", "The clipboard is turned off for %1."), // desktop/app/src/clipboard.rs
+ QT_TRANSLATE_NOOP("Clipboard", "There's no text, image, or file on the clipboard."), // desktop/app/src/clipboard.rs
+ QT_TRANSLATE_NOOP("Clipboard", "Update NectarLink on %1 to send it images."), // desktop/app/src/clipboard.rs
+ QT_TRANSLATE_NOOP("Clipboard", "What you copied is marked private by its app, so it wasn't sent."), // desktop/app/src/clipboard.rs
+ QT_TRANSLATE_NOOP("CommandPalette", "Calling %1 on %2…"), // desktop/app/src/command_palette.rs
+ QT_TRANSLATE_NOOP("CommandPalette", "Opened Recordings folder. Start a voice note in NectarLink on %1 to send it here."), // desktop/app/src/command_palette.rs
+ QT_TRANSLATE_NOOP("CommandPalette", "Ringing %1…"), // desktop/app/src/command_palette.rs
+ QT_TRANSLATE_NOOP("CommandPalette", "Starting phone webcam…"), // desktop/app/src/command_palette.rs
+ QT_TRANSLATE_NOOP("CommandPalette", "Stopped phone webcam."), // desktop/app/src/command_palette.rs
+ QT_TRANSLATE_NOOP("CommandPalette", "Syncing devices…"), // desktop/app/src/command_palette.rs
+ QT_TRANSLATE_NOOP("CommandPalette", "That file is no longer in its saved location."), // desktop/app/src/command_palette.rs
+ QT_TRANSLATE_NOOP("ContinuityCamera", "Couldn’t copy image to clipboard: %1"), // desktop/app/src/continuity_camera.rs
+ QT_TRANSLATE_NOOP("ContinuityCamera", "Image is on your clipboard. Press Ctrl+V in your target app."), // desktop/app/src/continuity_camera.rs
+ QT_TRANSLATE_NOOP("ContinuityCamera", "Pair your phone first to take a photo or scan a document."), // desktop/app/src/continuity_camera.rs
+ QT_TRANSLATE_NOOP("ContinuityCamera", "Pasted into %1"), // desktop/app/src/continuity_camera.rs
+ QT_TRANSLATE_NOOP("CoreHost", "Dropped %1 queued item(s) for %2 (device unpaired)."), // desktop/app/src/core_host.rs
+ QT_TRANSLATE_NOOP("Errors", "Something went wrong: %1"), // desktop/app/src/bridge/app.rs
+ QT_TRANSLATE_NOOP("Errors", "That device isn't paired anymore."), // desktop/app/src/bridge/app.rs
+ QT_TRANSLATE_NOOP("Errors", "The device declined."), // desktop/app/src/bridge/app.rs
+ QT_TRANSLATE_NOOP("Errors", "The device didn't answer in time."), // desktop/app/src/bridge/app.rs
+ QT_TRANSLATE_NOOP("Errors", "The device isn't connected right now."), // desktop/app/src/bridge/app.rs
+ QT_TRANSLATE_NOOP("Errors", "The device's app doesn't support that yet."), // desktop/app/src/bridge/app.rs
+ QT_TRANSLATE_NOOP("FolderSync", "Folders are up to date."), // desktop/app/src/folder_sync.rs
+ QT_TRANSLATE_NOOP("FolderSync", "Synced %1 file(s)."), // desktop/app/src/folder_sync.rs
+ QT_TRANSLATE_NOOP("Links", "%1: tap the notification on your phone to continue watching."), // desktop/app/src/links.rs
+ QT_TRANSLATE_NOOP("Links", "%1: tap the notification on your phone to open in Maps."), // desktop/app/src/links.rs
+ QT_TRANSLATE_NOOP("Links", "Copy a link or address first"), // desktop/app/src/links.rs
+ QT_TRANSLATE_NOOP("Links", "Copy a web link (https://…), geo: URI, or street address, then choose this again."), // desktop/app/src/links.rs
+ QT_TRANSLATE_NOOP("Links", "Copy a web link, video URL, or street address, then choose this again to open it on your phone."), // desktop/app/src/links.rs
+ QT_TRANSLATE_NOOP("Links", "Couldn't send it"), // desktop/app/src/links.rs
+ QT_TRANSLATE_NOOP("Links", "No phone to open it on"), // desktop/app/src/links.rs
+ QT_TRANSLATE_NOOP("Links", "Pair a phone first, or enable opening links on your phone."), // desktop/app/src/links.rs
+ QT_TRANSLATE_NOOP("Links", "Sent to %1"), // desktop/app/src/links.rs
+ QT_TRANSLATE_NOOP("Links", "Tap the notification on your phone to open it."), // desktop/app/src/links.rs
+ QT_TRANSLATE_NOOP("Links", "That's not a link or address"), // desktop/app/src/links.rs
+ QT_TRANSLATE_NOOP("Links", "Update NectarLink on %1."), // desktop/app/src/links.rs
+ QT_TRANSLATE_NOOP("Media", "Media is turned off for that device."), // desktop/app/src/media.rs
+ QT_TRANSLATE_NOOP("Media", "That player can't do that."), // desktop/app/src/media.rs
+ QT_TRANSLATE_NOOP("Media", "That player isn't playing anymore."), // desktop/app/src/media.rs
+ QT_TRANSLATE_NOOP("Messages", "Group texts can't be sent from the PC yet."), // desktop/app/src/messages.rs
+ QT_TRANSLATE_NOOP("Mirror", "Couldn't start recording."), // desktop/app/src/mirror.rs
+ QT_TRANSLATE_NOOP("Mirror", "Saved %1 to Downloads\\Nectarlink."), // desktop/app/src/mirror.rs
+ QT_TRANSLATE_NOOP("Mirror", "Screenshot copied to clipboard."), // desktop/app/src/mirror.rs
+ QT_TRANSLATE_NOOP("Mirror", "The screenshot couldn't be copied to the clipboard."), // desktop/app/src/mirror.rs
+ QT_TRANSLATE_NOOP("Mirror", "The screenshot couldn't be saved."), // desktop/app/src/mirror.rs
+ QT_TRANSLATE_NOOP("Mirror", "Wait for the screen to appear first."), // desktop/app/src/mirror.rs
+ QT_TRANSLATE_NOOP("Notifications", "Code copied"), // desktop/app/src/notifications.rs
+ QT_TRANSLATE_NOOP("PhoneMic", "Tap Start on %1 to use its microphone."), // desktop/app/src/phone_mic.rs
+ QT_TRANSLATE_NOOP("PhoneMic", "The microphone is turned off for this PC on %1."), // desktop/app/src/phone_mic.rs
+ QT_TRANSLATE_NOOP("PhoneMic", "Update NectarLink on %1 to use its microphone."), // desktop/app/src/phone_mic.rs
+ QT_TRANSLATE_NOOP("Photos", "Copied to clipboard."), // desktop/app/src/photos.rs
+ QT_TRANSLATE_NOOP("Photos", "No recent photos found on the phone."), // desktop/app/src/photos.rs
+ QT_TRANSLATE_NOOP("Photos", "Opening latest photo…"), // desktop/app/src/photos.rs
+ QT_TRANSLATE_NOOP("Photos", "Saved %1 items to %2."), // desktop/app/src/photos.rs
+ QT_TRANSLATE_NOOP("Photos", "Saved %1 to %2."), // desktop/app/src/photos.rs
+ QT_TRANSLATE_NOOP("Photos", "That photo isn't on the phone anymore."), // desktop/app/src/photos.rs
+ QT_TRANSLATE_NOOP("Photos", "The phone doesn't share photos or files with this PC."), // desktop/app/src/photos.rs
+ QT_TRANSLATE_NOOP("Photos", "The phone isn't connected right now."), // desktop/app/src/photos.rs
+ QT_TRANSLATE_NOOP("Photos", "The photo couldn't be copied to the clipboard."), // desktop/app/src/photos.rs
+ QT_TRANSLATE_NOOP("Photos", "The photo couldn't be copied. It's in Downloads\\Nectarlink."), // desktop/app/src/photos.rs
+ QT_TRANSLATE_NOOP("PlayOnPhone", "Connect your phone to play on it."), // desktop/app/src/play_on_phone.rs
+ QT_TRANSLATE_NOOP("PlayOnPhone", "Media is turned off for %1."), // desktop/app/src/play_on_phone.rs
+ QT_TRANSLATE_NOOP("PlayOnPhone", "Opening in %1 on %2. Tap the notification there."), // desktop/app/src/play_on_phone.rs
+ QT_TRANSLATE_NOOP("PlayOnPhone", "Sent to %1. Tap the notification there."), // desktop/app/src/play_on_phone.rs
+ QT_TRANSLATE_NOOP("PlayOnPhone", "Tap the notification on %1 to watch."), // desktop/app/src/play_on_phone.rs
+ QT_TRANSLATE_NOOP("PlayOnPhone", "Update NectarLink on %1 to play on it."), // desktop/app/src/play_on_phone.rs
+ QT_TRANSLATE_NOOP("Timeline", "Copied link to clipboard."), // desktop/app/src/bridge/timeline.rs
+ QT_TRANSLATE_NOOP("Timeline", "Copied to clipboard."), // desktop/app/src/bridge/timeline.rs
+ QT_TRANSLATE_NOOP("Timeline", "No phone is paired yet."), // desktop/app/src/bridge/timeline.rs
+ QT_TRANSLATE_NOOP("Timeline", "Phone microphone"), // desktop/app/src/i18n.rs
+ QT_TRANSLATE_NOOP("Timeline", "Phone webcam"), // desktop/app/src/i18n.rs
+ QT_TRANSLATE_NOOP("Timeline", "Screen mirroring"), // desktop/app/src/i18n.rs
+ QT_TRANSLATE_NOOP("Timeline", "Sending to %1…"), // desktop/app/src/bridge/timeline.rs
+ QT_TRANSLATE_NOOP("Timeline", "Sent clip to %1."), // desktop/app/src/bridge/timeline.rs
+ QT_TRANSLATE_NOOP("Timeline", "That clip is no longer in clipboard history."), // desktop/app/src/bridge/timeline.rs
+ QT_TRANSLATE_NOOP("Timeline", "That entry couldn't be removed. Try again."), // desktop/app/src/bridge/timeline.rs
+ QT_TRANSLATE_NOOP("Timeline", "That file was moved or deleted."), // desktop/app/src/bridge/timeline.rs
+ QT_TRANSLATE_NOOP("Timeline", "That isn't a web link."), // desktop/app/src/bridge/timeline.rs
+ QT_TRANSLATE_NOOP("Timeline", "That photo was moved or deleted."), // desktop/app/src/bridge/timeline.rs
+ QT_TRANSLATE_NOOP("Timeline", "The Timeline couldn't be cleared. Try again."), // desktop/app/src/bridge/timeline.rs
+ QT_TRANSLATE_NOOP("Timeline", "The photo couldn't be copied to the clipboard."), // desktop/app/src/bridge/timeline.rs
+ QT_TRANSLATE_NOOP("Transfers", "Files are turned off for that device."), // desktop/app/src/transfers.rs
+ QT_TRANSLATE_NOOP("Transfers", "That's too many files to send at once."), // desktop/app/src/transfers.rs
+ QT_TRANSLATE_NOOP("Transfers", "There's nothing to send in there."), // desktop/app/src/transfers.rs
+};
diff --git a/desktop/app/src/bridge/app.rs b/desktop/app/src/bridge/app.rs
index 4664b53..84d09c3 100644
--- a/desktop/app/src/bridge/app.rs
+++ b/desktop/app/src/bridge/app.rs
@@ -2,6 +2,7 @@
//! `AppController`: app-wide state and commands for QML (core status, this
//! PC, capabilities, ringing, appearance) plus the tray icon.
+use crate::i18n::tr;
use std::{
pin::Pin,
sync::{
@@ -687,13 +688,13 @@ pub(crate) fn open_dialer(device: DeviceId, number: &str) {
/// Explains a failed command in a sentence the user understands.
pub(crate) fn describe(error: &Error) -> String {
match error {
- Error::Offline => "The device isn't connected right now.".into(),
- Error::NotPaired => "That device isn't paired anymore.".into(),
- Error::Timeout => "The device didn't answer in time.".into(),
- Error::Denied | Error::Declined => "The device declined.".into(),
- Error::Unsupported => "The device's app doesn't support that yet.".into(),
+ Error::Offline => tr!("Errors", "The device isn't connected right now."),
+ Error::NotPaired => tr!("Errors", "That device isn't paired anymore."),
+ Error::Timeout => tr!("Errors", "The device didn't answer in time."),
+ Error::Denied | Error::Declined => tr!("Errors", "The device declined."),
+ Error::Unsupported => tr!("Errors", "The device's app doesn't support that yet."),
Error::QueueFull(msg) => msg.clone(),
- other => format!("Something went wrong: {other}"),
+ other => tr!("Errors", "Something went wrong: %1", other),
}
}
@@ -1390,7 +1391,7 @@ impl qobject::AppController {
} else {
crate::transfers::cancel_all_queued(Some(device));
}
- show_message("Send cancelled");
+ show_message(tr!("App", "Send cancelled"));
}
_ => crate::clipboard::run_last_suggestion(),
}
@@ -1775,7 +1776,7 @@ impl qobject::AppController {
pub fn clear_message_cache(self: Pin<&mut Self>) {
if let Some(Err(e)) = core_host::node().map(|node| node.clear_message_cache()) {
tracing::warn!(error = %e, "can't clear the message cache");
- show_message("Some messages couldn't be cleared. Try again.");
+ show_message(tr!("App", "Some messages couldn't be cleared. Try again."));
}
crate::messages::clear_cache();
core_host::host().hub.changed(Changes::DATA_RETENTION);
@@ -1791,7 +1792,7 @@ impl qobject::AppController {
pub fn clear_received_file_history(self: Pin<&mut Self>) {
if let Some(Err(e)) = core_host::node().map(|node| node.clear_received_file_history()) {
tracing::warn!(error = %e, "can't clear the received file history");
- show_message("The received file history couldn't be cleared. Try again.");
+ show_message(tr!("App", "The received file history couldn't be cleared. Try again."));
}
core_host::host()
.hub
@@ -1820,7 +1821,7 @@ impl qobject::AppController {
crate::photos::clear_cache();
self.as_mut().refresh_data_retention();
if failed {
- show_message("Some history couldn't be cleared. Try again.");
+ show_message(tr!("App", "Some history couldn't be cleared. Try again."));
} else {
self.toast(QString::from("Cleared all local history and caches"));
}
@@ -1910,7 +1911,7 @@ impl qobject::AppController {
pub fn drop_to_shelf(&self, urls: &QList<QVariant>, text: &QString) {
let (Some(device), device_name, online) = resolve_shelf_device(self.current_device) else {
- show_message("No phone is paired yet.");
+ show_message(tr!("App", "No phone is paired yet."));
return;
};
@@ -1953,7 +1954,7 @@ impl qobject::AppController {
if !paths.is_empty() {
crate::transfers::send(device, paths);
if online {
- show_message(format!("Sending to {device_name}…"));
+ show_message(tr!("App", "Sending to %1…", device_name));
}
return;
}
@@ -1971,7 +1972,7 @@ impl qobject::AppController {
match node.send_clipboard(device, dropped_text).await {
Ok(()) => {
if !show_offline_queued_toast(device, None) {
- show_message(format!("Sent text to {name}."));
+ show_message(tr!("App", "Sent text to %1.", name));
}
}
Err(e) => show_message(describe(&e)),
@@ -2006,8 +2007,10 @@ impl qobject::AppController {
.map_err(|e| e.to_string())
.and_then(|b| crate::win::clipboard::write_image(mime, &b))
{
- Ok(()) => show_message("Copied to clipboard."),
- Err(_) => show_message("The photo couldn't be copied to the clipboard."),
+ Ok(()) => show_message(tr!("App", "Copied to clipboard.")),
+ Err(_) => {
+ show_message(tr!("App", "The photo couldn't be copied to the clipboard."))
+ }
}
}
_ => crate::transfers::open(p),
@@ -2027,7 +2030,7 @@ impl qobject::AppController {
if !s.is_empty() {
crate::clipboard::copy_history_item(&s);
} else {
- show_message("Already on clipboard.");
+ show_message(tr!("App", "Already on clipboard."));
}
}
"file" => {
@@ -2039,7 +2042,7 @@ impl qobject::AppController {
crate::transfers::open(p);
}
} else {
- show_message("That file is no longer in its saved location.");
+ show_message(tr!("App", "That file is no longer in its saved location."));
}
}
_ => {}
@@ -2052,8 +2055,8 @@ impl qobject::AppController {
return;
}
match crate::win::clipboard::write(&s) {
- Ok(()) => show_message("Copied to clipboard."),
- Err(_) => show_message("Could not copy to the clipboard."),
+ Ok(()) => show_message(tr!("App", "Copied to clipboard.")),
+ Err(_) => show_message(tr!("App", "Could not copy to the clipboard.")),
}
}
diff --git a/desktop/app/src/bridge/native.rs b/desktop/app/src/bridge/native.rs
index 33c3df1..ecb8f05 100644
--- a/desktop/app/src/bridge/native.rs
+++ b/desktop/app/src/bridge/native.rs
@@ -41,5 +41,8 @@ pub mod ffi {
/// retranslate the open windows. Returns true when NectarLink's own
/// translation was installed.
fn install_translator(dir: &str, language: &str) -> bool;
+
+ /// `text` in the installed language (`QCoreApplication::translate`).
+ fn translate(context: &str, text: &str) -> String;
}
}
diff --git a/desktop/app/src/bridge/timeline.rs b/desktop/app/src/bridge/timeline.rs
index 421c3ea..29ce562 100644
--- a/desktop/app/src/bridge/timeline.rs
+++ b/desktop/app/src/bridge/timeline.rs
@@ -5,6 +5,7 @@
//! Loads 100 entries per page on demand so QML never instantiates all 5,000
//! retained entries at once.
+use crate::i18n::tr;
use std::{path::Path, pin::Pin};
use cxx_qt::{CxxQtType, Threading};
@@ -194,7 +195,7 @@ fn role_value(row: &Row, role: &str) -> QVariant {
"deviceName" => text(&row.device_name),
"timestamp" => QVariant::from(&(e.timestamp as f64)),
"prevTimestamp" => QVariant::from(&(row.prev_timestamp as f64)),
- "title" => text(&row.title),
+ "title" => text(&crate::i18n::timeline_title(&row.title)),
"subtitle" => text(&row.subtitle),
"sizeBytes" => QVariant::from(&(e.size_bytes as f64)),
"durationSecs" => QVariant::from(&(e.duration_secs as i32)),
@@ -347,7 +348,7 @@ impl qobject::TimelineModel {
if path.exists() {
crate::transfers::open(path);
} else {
- show_message("That file was moved or deleted.");
+ show_message(tr!("Timeline", "That file was moved or deleted."));
}
}
}
@@ -360,7 +361,7 @@ impl qobject::TimelineModel {
show_message(e);
}
}
- None => show_message("That isn't a web link."),
+ None => show_message(tr!("Timeline", "That isn't a web link.")),
}
}
TimelineKind::Clip | TimelineKind::Session => {}
@@ -374,7 +375,7 @@ impl qobject::TimelineModel {
if path.exists() {
crate::transfers::show_in_folder(path);
} else {
- show_message("That file was moved or deleted.");
+ show_message(tr!("Timeline", "That file was moved or deleted."));
}
}
}
@@ -390,14 +391,14 @@ impl qobject::TimelineModel {
TimelineKind::Link => {
let url = if row.entry.target.is_empty() { &row.entry.title } else { &row.entry.target };
match crate::win::clipboard::write(url) {
- Ok(()) => show_message("Copied link to clipboard."),
+ Ok(()) => show_message(tr!("Timeline", "Copied link to clipboard.")),
Err(e) => show_message(e),
}
}
TimelineKind::Photo => {
let path = Path::new(&row.primary_path);
if !path.exists() {
- return show_message("That photo was moved or deleted.");
+ return show_message(tr!("Timeline", "That photo was moved or deleted."));
}
let mime =
match path.extension().and_then(|e| e.to_str()).map(str::to_ascii_lowercase).as_deref() {
@@ -408,8 +409,8 @@ impl qobject::TimelineModel {
.map_err(|e| e.to_string())
.and_then(|bytes| crate::win::clipboard::write_image(mime, &bytes))
{
- Ok(()) => show_message("Copied to clipboard."),
- Err(_) => show_message("The photo couldn't be copied to the clipboard."),
+ Ok(()) => show_message(tr!("Timeline", "Copied to clipboard.")),
+ Err(_) => show_message(tr!("Timeline", "The photo couldn't be copied to the clipboard.")),
}
}
_ => {}
@@ -420,7 +421,7 @@ impl qobject::TimelineModel {
let Some(row) = self.find_row(entry_id) else { return };
let target_device = resolve_target_device(device, Some(row.entry.device_id));
let Some(target_device) = target_device else {
- return show_message("No phone is paired yet.");
+ return show_message(tr!("Timeline", "No phone is paired yet."));
};
let (device_name, is_online) = core_host::host().hub.read(|s| {
let name = s.name_of(&target_device).unwrap_or_else(|| "your phone".into());
@@ -432,11 +433,11 @@ impl qobject::TimelineModel {
TimelineKind::File | TimelineKind::Photo | TimelineKind::Recording => {
let paths = existing_paths(&row.entry.target);
if paths.is_empty() {
- return show_message("That file was moved or deleted.");
+ return show_message(tr!("Timeline", "That file was moved or deleted."));
}
crate::transfers::send(target_device, paths);
if is_online {
- show_message(format!("Sending to {device_name}…"));
+ show_message(tr!("Timeline", "Sending to %1…", device_name));
}
}
TimelineKind::Clip => {
@@ -446,10 +447,12 @@ impl qobject::TimelineModel {
match node.resend_clipboard_history(target_device, &clip_id).await {
Ok(()) => {
if !crate::bridge::app::show_offline_queued_toast(target_device, None) {
- show_message(format!("Sent clip to {device_name}."));
+ show_message(tr!("Timeline", "Sent clip to %1.", device_name));
}
}
- Err(Error::NotFound) => show_message("That clip is no longer in clipboard history."),
+ Err(Error::NotFound) => {
+ show_message(tr!("Timeline", "That clip is no longer in clipboard history."))
+ }
Err(e) => show_message(describe(&e)),
}
});
@@ -472,14 +475,14 @@ impl qobject::TimelineModel {
let Ok(id) = String::from(entry_id).parse::<i64>() else { return };
if let Some(Err(e)) = core_host::node().map(|node| node.delete_timeline_entry(id)) {
tracing::warn!(error = %e, "can't remove a Timeline entry");
- show_message("That entry couldn't be removed. Try again.");
+ show_message(tr!("Timeline", "That entry couldn't be removed. Try again."));
}
}
pub fn clear_all(self: Pin<&mut Self>) {
if let Some(Err(e)) = core_host::node().map(|node| node.clear_timeline()) {
tracing::warn!(error = %e, "can't clear the Timeline");
- show_message("The Timeline couldn't be cleared. Try again.");
+ show_message(tr!("Timeline", "The Timeline couldn't be cleared. Try again."));
}
}
@@ -753,7 +756,7 @@ pub fn preview_json() -> String {
"incoming": r.entry.incoming,
"deviceName": r.device_name,
"timestamp": r.entry.timestamp,
- "title": r.title,
+ "title": crate::i18n::timeline_title(&r.title),
"subtitle": r.subtitle,
"thumbUrl": r.thumb_url,
})
diff --git a/desktop/app/src/calls.rs b/desktop/app/src/calls.rs
index 13efe44..9dbb111 100644
--- a/desktop/app/src/calls.rs
+++ b/desktop/app/src/calls.rs
@@ -5,6 +5,7 @@
//! notification to mute or end it), and a notification for calls nobody
//! answered.
+use crate::i18n::tr;
use std::{
collections::{HashMap, HashSet},
path::PathBuf,
@@ -359,7 +360,7 @@ pub fn command(device: DeviceId, call: String, command: CallCommand) {
core_host::spawn(async move {
match node.call_command(device, call, command).await {
Ok(()) => {}
- Err(Error::NotFound) => show_message("That call is over."),
+ Err(Error::NotFound) => show_message(tr!("Calls", "That call is over.")),
Err(e) => show_message(describe(&e)),
}
});
@@ -431,7 +432,7 @@ pub fn on_toast(key: &str, action: &str) {
show_in_progress(device, &active);
}
}
- Err(Error::NotFound) => show_message("That call is over."),
+ Err(Error::NotFound) => show_message(tr!("Calls", "That call is over.")),
Err(e) => show_message(describe(&e)),
}
});
@@ -448,7 +449,7 @@ pub fn on_toast(key: &str, action: &str) {
}
}
Ok(()) => {}
- Err(Error::NotFound) => show_message("That call is over."),
+ Err(Error::NotFound) => show_message(tr!("Calls", "That call is over.")),
Err(e) => show_message(describe(&e)),
}
});
diff --git a/desktop/app/src/clipboard.rs b/desktop/app/src/clipboard.rs
index 31302a4..2710bd1 100644
--- a/desktop/app/src/clipboard.rs
+++ b/desktop/app/src/clipboard.rs
@@ -5,6 +5,7 @@
//! clipboard" sends it on demand, and what a phone sends lands on the
//! Windows clipboard.
+use crate::i18n::tr;
use std::{
collections::HashMap,
sync::{
@@ -171,7 +172,7 @@ fn make_thumbs(node: Node, ids: Vec<String>) {
pub fn copy_history_item(id: &str) {
let Some(node) = core_host::node() else { return };
match node.copy_clipboard_history(id) {
- Ok(()) => show_message("Copied to clipboard"),
+ Ok(()) => show_message(tr!("Clipboard", "Copied to clipboard")),
Err(e) => show_message(describe(&e)),
}
}
@@ -281,36 +282,41 @@ pub fn send_now(device: DeviceId) {
let image = matches!(clip, Clip::Image(_));
match clip {
Clip::Private => {
- return show_message("What you copied is marked private by its app, so it wasn't sent.");
+ return show_message(tr!(
+ "Clipboard",
+ "What you copied is marked private by its app, so it wasn't sent."
+ ));
}
Clip::Empty => {
if let Some(files) = clipboard::read_files() {
crate::transfers::send(device, files);
if is_online {
- show_message(format!("Sending copied files to {name}…"));
+ show_message(tr!("Clipboard", "Sending copied files to %1…", name));
}
return;
}
- return show_message("There's no text, image, or file on the clipboard.");
+ return show_message(tr!("Clipboard", "There's no text, image, or file on the clipboard."));
}
Clip::Text { .. } | Clip::Image(_) => {}
}
core_host::spawn(async move {
let Some(content) = Content::from_clip(clip).await else {
- return show_message("That image can't be read.");
+ return show_message(tr!("Clipboard", "That image can't be read."));
};
match content.send(&node, device).await {
Ok(()) => {
if !crate::bridge::app::show_offline_queued_toast(device, None) {
- show_message(format!("Sent to {name}."));
+ show_message(tr!("Clipboard", "Sent to %1.", name));
}
}
- Err(Error::TooLarge) if image => show_message("That image is too large to send."),
- Err(Error::TooLarge) => show_message("That's too much text to send at once."),
+ Err(Error::TooLarge) if image => {
+ show_message(tr!("Clipboard", "That image is too large to send."))
+ }
+ Err(Error::TooLarge) => show_message(tr!("Clipboard", "That's too much text to send at once.")),
Err(Error::Unsupported) if image => {
- show_message(format!("Update NectarLink on {name} to send it images."))
+ show_message(tr!("Clipboard", "Update NectarLink on %1 to send it images.", name))
}
- Err(Error::Denied) => show_message(format!("The clipboard is turned off for {name}.")),
+ Err(Error::Denied) => show_message(tr!("Clipboard", "The clipboard is turned off for %1.", name)),
Err(e) => show_message(describe(&e)),
}
});
@@ -325,10 +331,12 @@ pub fn send_history_item(device: DeviceId, id: &str) {
match node.resend_clipboard_history(device, &id).await {
Ok(()) => {
if !crate::bridge::app::show_offline_queued_toast(device, None) {
- show_message(format!("Sent to {name}."));
+ show_message(tr!("Clipboard", "Sent to %1.", name));
}
}
- Err(Error::NotFound) => show_message("That clip is no longer in clipboard history."),
+ Err(Error::NotFound) => {
+ show_message(tr!("Clipboard", "That clip is no longer in clipboard history."))
+ }
Err(e) => show_message(describe(&e)),
}
});
@@ -376,7 +384,7 @@ pub fn on_event(event: &NodeEvent) {
});
} else {
*LAST_SUGGESTION.lock().unwrap_or_else(|e| e.into_inner()) = None;
- show_message(format!("Copied from {name}."));
+ show_message(tr!("Clipboard", "Copied from %1.", name));
}
}
}
diff --git a/desktop/app/src/command_palette.rs b/desktop/app/src/command_palette.rs
index 1f851f4..501000c 100644
--- a/desktop/app/src/command_palette.rs
+++ b/desktop/app/src/command_palette.rs
@@ -9,6 +9,7 @@
//! - Closing drops the candidate vector (`shrink_to_fit`) so the palette costs
//! zero memory and zero CPU while closed.
+use crate::i18n::tr;
use std::{collections::HashSet, path::PathBuf, sync::Mutex, time::Instant};
use nectarlink_core::{ClipboardItemKind, DeviceId, LinkState, PhoneToggleValue, TimelineKind};
@@ -201,7 +202,7 @@ pub fn execute(id: &str) -> Option<PaletteUiAction> {
}
if id == "action:sync_now" {
if let Some(node) = core_host::node() {
- show_message("Syncing devices…");
+ show_message(tr!("CommandPalette", "Syncing devices…"));
core_host::spawn(async move { node.refresh().await });
}
return None;
@@ -282,11 +283,11 @@ pub fn execute(id: &str) -> Option<PaletteUiAction> {
match crate::webcam::phase() {
crate::webcam::Phase::Asking { .. } | crate::webcam::Phase::Streaming { .. } => {
crate::webcam::stop();
- show_message("Stopped phone webcam.");
+ show_message(tr!("CommandPalette", "Stopped phone webcam."));
}
_ => {
crate::webcam::start(Some(dev));
- show_message("Starting phone webcam…");
+ show_message(tr!("CommandPalette", "Starting phone webcam…"));
}
}
return None;
@@ -339,7 +340,7 @@ pub fn execute(id: &str) -> Option<PaletteUiAction> {
if crate::calls::can_dial(dev) {
crate::calls::dial_from_palette(dev, number);
let name = core_host::host().hub.read(|s| s.name_of(&dev)).unwrap_or_else(|| "phone".into());
- show_message(format!("Calling {number} on {name}…"));
+ show_message(tr!("CommandPalette", "Calling %1 on %2…", number, name));
return None;
}
return Some(PaletteUiAction::OpenDialer { device_id: dev.to_string(), number: number.to_owned() });
@@ -364,7 +365,7 @@ pub fn execute(id: &str) -> Option<PaletteUiAction> {
if path.exists() {
crate::transfers::open(&path);
} else {
- show_message("That file is no longer in its saved location.");
+ show_message(tr!("CommandPalette", "That file is no longer in its saved location."));
}
return None;
}
@@ -379,7 +380,7 @@ fn device_index_of(device: DeviceId) -> Option<usize> {
fn ring_device_from_palette(device: DeviceId) {
let Some(node) = core_host::node() else { return };
let name = core_host::host().hub.read(|s| s.name_of(&device)).unwrap_or_else(|| "your phone".into());
- show_message(format!("Ringing {name}…"));
+ show_message(tr!("CommandPalette", "Ringing %1…", name));
core_host::spawn(async move {
if let Err(e) = node.ring(device, true).await {
show_message(describe(&e));
@@ -395,8 +396,10 @@ fn open_voice_recordings(device: DeviceId) {
crate::transfers::open(&folder);
let phone_name =
core_host::host().hub.read(|s| s.name_of(&device)).unwrap_or_else(|| "your phone".into());
- show_message(format!(
- "Opened Recordings folder. Start a voice note in NectarLink on {phone_name} to send it here."
+ show_message(tr!(
+ "CommandPalette",
+ "Opened Recordings folder. Start a voice note in NectarLink on %1 to send it here.",
+ phone_name
));
}
diff --git a/desktop/app/src/continuity_camera.rs b/desktop/app/src/continuity_camera.rs
index 5e24814..50eb51a 100644
--- a/desktop/app/src/continuity_camera.rs
+++ b/desktop/app/src/continuity_camera.rs
@@ -6,6 +6,7 @@
//! clipboard on arrival, and either restores focus + synthesizes `Ctrl+V` into
//! the original target window or prompts the user if that window was closed.
+use crate::i18n::tr;
use std::{
sync::{
Mutex,
@@ -168,7 +169,10 @@ pub fn start_for_index(preferred_index: usize, mode_raw: &str) {
.map(|d| (d.id, d.info.name.clone(), matches!(d.link, LinkState::Online { .. })))
});
let Some((device_id, device_name, online)) = chosen else {
- crate::bridge::app::show_message("Pair your phone first to take a photo or scan a document.");
+ crate::bridge::app::show_message(tr!(
+ "ContinuityCamera",
+ "Pair your phone first to take a photo or scan a document."
+ ));
return;
};
@@ -264,9 +268,12 @@ pub fn confirm_paste() {
if let Some((hwnd, title)) = crate::win::tray::snapshot_target_window() {
spawn_focus_and_paste(hwnd);
let label = if title.is_empty() { "active window".to_owned() } else { title };
- crate::bridge::app::show_message(format!("Pasted into {label}"));
+ crate::bridge::app::show_message(tr!("ContinuityCamera", "Pasted into %1", label));
} else {
- crate::bridge::app::show_message("Image is on your clipboard. Press Ctrl+V in your target app.");
+ crate::bridge::app::show_message(tr!(
+ "ContinuityCamera",
+ "Image is on your clipboard. Press Ctrl+V in your target app."
+ ));
}
}
@@ -311,7 +318,11 @@ pub fn on_event(event: &NodeEvent) {
if let Err(e) = crate::win::clipboard::write_image(mime, data) {
tracing::warn!(error = %e, "can't copy continuity camera image to clipboard");
notify_continuity();
- crate::bridge::app::show_message(format!("Couldn’t copy image to clipboard: {e}"));
+ crate::bridge::app::show_message(tr!(
+ "ContinuityCamera",
+ "Couldn’t copy image to clipboard: %1",
+ e
+ ));
return;
}
diff --git a/desktop/app/src/core_host.rs b/desktop/app/src/core_host.rs
index 9128a2b..9b85c13 100644
--- a/desktop/app/src/core_host.rs
+++ b/desktop/app/src/core_host.rs
@@ -4,6 +4,7 @@
//! through [`spawn`]. The UI starts before the node, which comes up in the
//! background (startup is never blocked on the network).
+use crate::i18n::tr;
use std::{
future::Future,
path::PathBuf,
@@ -293,8 +294,11 @@ async fn run(data_dir: PathBuf, platform: Arc<dyn Platform>) {
&event
&& *dropped_count > 0
{
- crate::bridge::app::show_message(format!(
- "Dropped {dropped_count} queued item(s) for {peer_name} (device unpaired)."
+ crate::bridge::app::show_message(tr!(
+ "CoreHost",
+ "Dropped %1 queued item(s) for %2 (device unpaired).",
+ dropped_count,
+ peer_name
));
}
crate::notifications::apply(&event);
diff --git a/desktop/app/src/folder_sync.rs b/desktop/app/src/folder_sync.rs
index d328b08..2cb5f2a 100644
--- a/desktop/app/src/folder_sync.rs
+++ b/desktop/app/src/folder_sync.rs
@@ -4,6 +4,7 @@
//! `storage.read`, `storage.write`), with conflict-safe renaming so neither
//! side's edits are ever lost.
+use crate::i18n::tr;
use std::{
collections::HashMap,
path::{Path, PathBuf},
@@ -569,9 +570,9 @@ pub fn trigger_sync_now() {
if let Some(node) = core_host::node() {
let count = sync_now(&node).await;
if count > 0 {
- crate::bridge::app::show_message(format!("Synced {count} file(s)."));
+ crate::bridge::app::show_message(tr!("FolderSync", "Synced %1 file(s).", count));
} else {
- crate::bridge::app::show_message("Folders are up to date.");
+ crate::bridge::app::show_message(tr!("FolderSync", "Folders are up to date."));
}
}
});
diff --git a/desktop/app/src/i18n.rs b/desktop/app/src/i18n.rs
index 99115d3..fa04b45 100644
--- a/desktop/app/src/i18n.rs
+++ b/desktop/app/src/i18n.rs
@@ -1,5 +1,9 @@
// SPDX-License-Identifier: GPL-3.0-or-later
-//! The app's language: the system's or the one chosen in Settings.
+//! The app's language: the system's or the one chosen in Settings, for the
+//! QML (Qt's translators) and for the text the app builds in Rust, through
+//! [`tr!`]. `cargo xtask strings` collects every `tr!` text into
+//! `desktop/app/i18n/rust_strings.h`, which `lupdate` reads with the QML, so
+//! translators see them in the same `.ts` catalogue.
use std::path::{Path, PathBuf};
@@ -25,10 +29,89 @@ pub fn install(language: &str) {
tracing::debug!(language, installed, "translator");
}
+/// `text` (from `context`) in the app's language. Use [`tr!`], which also
+/// fills in `%1`, `%2`... and marks the text for `cargo xtask strings`.
+/// With no translation installed (or none for `text`), `text` itself.
+pub fn translate(context: &str, text: &str) -> String {
+ crate::bridge::native::ffi::translate(context, text)
+}
+
+/// Puts `args` in for `%1`, `%2`... in `text` (Qt's placeholders, which
+/// translators may reorder). `%%` is a literal `%`.
+pub fn fill(text: &str, args: &[&dyn std::fmt::Display]) -> String {
+ let mut out = String::with_capacity(text.len());
+ let mut chars = text.chars().peekable();
+ while let Some(c) = chars.next() {
+ if c != '%' {
+ out.push(c);
+ continue;
+ }
+ match chars.peek().copied() {
+ Some('%') => {
+ chars.next();
+ out.push('%');
+ }
+ Some(d @ '1'..='9') => {
+ chars.next();
+ match args.get(d as usize - '1' as usize) {
+ Some(arg) => out.push_str(&arg.to_string()),
+ None => {
+ out.push('%');
+ out.push(d);
+ }
+ }
+ }
+ _ => out.push('%'),
+ }
+ }
+ out
+}
+
+/// Text the app shows, in the user's language: `tr!("Context", "Sent to %1", name)`.
+/// The context and text must be literals (`cargo xtask strings` reads them).
+macro_rules! tr {
+ ($context:literal, $text:literal $(,)?) => {
+ $crate::i18n::translate($context, $text)
+ };
+ ($context:literal, $text:literal, $($arg:expr),+ $(,)?) => {
+ $crate::i18n::fill(&$crate::i18n::translate($context, $text), &[$(&$arg as &dyn std::fmt::Display),+])
+ };
+}
+pub(crate) use tr;
+
+/// A timeline entry's title in the app's language: the core names its
+/// sessions in English ("Phone webcam"); anything else (a file's or a
+/// person's name) stays as it is.
+pub fn timeline_title(title: &str) -> String {
+ match title {
+ "Phone webcam" => tr!("Timeline", "Phone webcam"),
+ "Screen mirroring" => tr!("Timeline", "Screen mirroring"),
+ "Phone microphone" => tr!("Timeline", "Phone microphone"),
+ other => other.to_owned(),
+ }
+}
+
#[cfg(test)]
mod tests {
use super::*;
+ #[test]
+ fn placeholders_fill_in_any_order() {
+ assert_eq!(fill("Sent to %1", &[&"Pixel"]), "Sent to Pixel");
+ assert_eq!(fill("%2 then %1", &[&"a", &"b"]), "b then a");
+ assert_eq!(fill("100%% of %1", &[&3]), "100% of 3");
+ // A placeholder without an argument stays, so the mistake shows.
+ assert_eq!(fill("%1 and %2", &[&"x"]), "x and %2");
+ assert_eq!(fill("50% off", &[]), "50% off");
+ }
+
+ #[test]
+ fn tr_fills_its_arguments() {
+ let name = "Pixel 9";
+ assert_eq!(tr!("Tests", "Sent to %1", name), "Sent to Pixel 9");
+ assert_eq!(tr!("Tests", "Done"), "Done");
+ }
+
#[test]
fn only_offered_languages_are_kept() {
assert!(is_known("") && is_known("zh_CN") && is_known("en"));
diff --git a/desktop/app/src/links.rs b/desktop/app/src/links.rs
index a1d03b0..c45309f 100644
--- a/desktop/app/src/links.rs
+++ b/desktop/app/src/links.rs
@@ -6,6 +6,7 @@
//! phone from the tray or Command Palette; a phone can lock this PC or put it
//! to sleep.
+use crate::i18n::tr;
use nectarlink_core::{
ClipKind, DeviceId, Error, FeatureState, HandoffKind, HandoffLink, LinkState, PowerAction,
address_to_geo_uri, classify_clip, extract_handoff_link, format_video_timestamp, geo_to_maps_https,
@@ -119,14 +120,20 @@ fn notice(title: &str, body: &str) {
pub fn open_copied_link_on_phone() {
let Clip::Text { .. } = clipboard::read() else {
return notice(
- "Copy a link or address first",
- "Copy a web link, video URL, or street address, then choose this again to open it on your phone.",
+ &tr!("Links", "Copy a link or address first"),
+ &tr!(
+ "Links",
+ "Copy a web link, video URL, or street address, then choose this again to open it on your phone."
+ ),
);
};
let Some(handoff) = handoff_from_clipboard() else {
return notice(
- "That's not a link or address",
- "Copy a web link (https://…), geo: URI, or street address, then choose this again.",
+ &tr!("Links", "That's not a link or address"),
+ &tr!(
+ "Links",
+ "Copy a web link (https://…), geo: URI, or street address, then choose this again."
+ ),
);
};
let node = core_host::node();
@@ -149,8 +156,8 @@ pub fn open_copied_link_on_phone() {
});
let Some((phone, name)) = phone else {
return notice(
- "No phone to open it on",
- "Pair a phone first, or enable opening links on your phone.",
+ &tr!("Links", "No phone to open it on"),
+ &tr!("Links", "Pair a phone first, or enable opening links on your phone."),
);
};
send(phone, name, handoff);
@@ -174,21 +181,23 @@ fn send(phone: DeviceId, name: String, handoff: HandoffLink) {
core_host::spawn(async move {
let body = match handoff.kind {
HandoffKind::MapLocation => {
- format!("{}: tap the notification on your phone to open in Maps.", handoff.label)
+ tr!("Links", "%1: tap the notification on your phone to open in Maps.", handoff.label)
}
HandoffKind::VideoLink if handoff.timestamp_secs.is_some() => {
- format!("{}: tap the notification on your phone to continue watching.", handoff.label)
+ tr!("Links", "%1: tap the notification on your phone to continue watching.", handoff.label)
}
- _ => "Tap the notification on your phone to open it.".into(),
+ _ => tr!("Links", "Tap the notification on your phone to open it."),
};
match node.open_link(phone, handoff.url).await {
Ok(()) => {
if !crate::bridge::app::show_offline_queued_toast(phone, None) {
- notice(&format!("Sent to {name}"), &body);
+ notice(&tr!("Links", "Sent to %1", name), &body);
}
}
- Err(Error::Unsupported) => notice("Couldn't send it", &format!("Update NectarLink on {name}.")),
- Err(e) => notice("Couldn't send it", &describe(&e)),
+ Err(Error::Unsupported) => {
+ notice(&tr!("Links", "Couldn't send it"), &tr!("Links", "Update NectarLink on %1.", name))
+ }
+ Err(e) => notice(&tr!("Links", "Couldn't send it"), &describe(&e)),
}
});
}
diff --git a/desktop/app/src/media.rs b/desktop/app/src/media.rs
index 7be8285..ac4eef5 100644
--- a/desktop/app/src/media.rs
+++ b/desktop/app/src/media.rs
@@ -4,6 +4,7 @@
//! it can be controlled; what plays on this PC goes to the phones (see
//! `win::media_sessions`).
+use crate::i18n::tr;
use std::{
collections::HashMap,
path::PathBuf,
@@ -194,9 +195,9 @@ fn send(device: DeviceId, player: String, action: MediaAction, position: Option<
let result = node.media_command(device, player, action, position).await;
let message = match result {
Ok(()) => return,
- Err(Error::NotFound) => "That player isn't playing anymore.".to_owned(),
- Err(Error::Unsupported) => "That player can't do that.".to_owned(),
- Err(Error::Denied) => "Media is turned off for that device.".to_owned(),
+ Err(Error::NotFound) => tr!("Media", "That player isn't playing anymore."),
+ Err(Error::Unsupported) => tr!("Media", "That player can't do that."),
+ Err(Error::Denied) => tr!("Media", "Media is turned off for that device."),
Err(e) => describe(&e),
};
tracing::debug!(message, "media command failed");
diff --git a/desktop/app/src/messages.rs b/desktop/app/src/messages.rs
index e526422..3f752fc 100644
--- a/desktop/app/src/messages.rs
+++ b/desktop/app/src/messages.rs
@@ -5,6 +5,7 @@
//! one inbox. Texts, MMS image attachments, and inline chat replies sent from
//! here go out through the phone.
+use crate::i18n::tr;
use std::{
collections::{HashMap, HashSet},
path::{Path, PathBuf},
@@ -1098,7 +1099,9 @@ pub fn send(body: String) {
});
match to {
Some(to) if to.len() == 1 => send_to(to, body),
- Some(_) => crate::bridge::app::show_message("Group texts can't be sent from the PC yet."),
+ Some(_) => {
+ crate::bridge::app::show_message(tr!("Messages", "Group texts can't be sent from the PC yet."))
+ }
None => {}
}
}
diff --git a/desktop/app/src/mirror.rs b/desktop/app/src/mirror.rs
index c0b75b4..b31f2b7 100644
--- a/desktop/app/src/mirror.rs
+++ b/desktop/app/src/mirror.rs
@@ -6,6 +6,7 @@
//! keyframe. The phone's sound, when it sends it, plays on the PC's
//! speakers.
+use crate::i18n::tr;
use std::{
collections::{HashMap, HashSet},
path::{Path, PathBuf},
@@ -396,7 +397,7 @@ fn free_path(dir: &Path, name: &str) -> PathBuf {
pub fn screenshot_clipboard(window: Window) {
let Some(bitmap) = latest_bitmap(&window) else {
set_notice(window, "Wait for the screen to appear first");
- show_message("Wait for the screen to appear first.");
+ show_message(tr!("Mirror", "Wait for the screen to appear first."));
return;
};
let copied = encode_png(&bitmap)
@@ -405,12 +406,12 @@ pub fn screenshot_clipboard(window: Window) {
match copied {
Ok(()) => {
set_notice(window, "Screenshot copied to clipboard");
- show_message("Screenshot copied to clipboard.");
+ show_message(tr!("Mirror", "Screenshot copied to clipboard."));
}
Err(e) => {
tracing::warn!(error = %e, "can't copy mirror screenshot");
set_notice(window, "Couldn't copy screenshot");
- show_message("The screenshot couldn't be copied to the clipboard.");
+ show_message(tr!("Mirror", "The screenshot couldn't be copied to the clipboard."));
}
}
}
@@ -419,7 +420,7 @@ pub fn screenshot_clipboard(window: Window) {
pub fn screenshot_file(window: Window) {
let Some(bitmap) = latest_bitmap(&window) else {
set_notice(window, "Wait for the screen to appear first");
- show_message("Wait for the screen to appear first.");
+ show_message(tr!("Mirror", "Wait for the screen to appear first."));
return;
};
let png = match encode_png(&bitmap) {
@@ -427,7 +428,7 @@ pub fn screenshot_file(window: Window) {
Err(e) => {
tracing::warn!(error = %e, "can't encode mirror screenshot");
set_notice(window, "Couldn't save screenshot");
- show_message("The screenshot couldn't be saved.");
+ show_message(tr!("Mirror", "The screenshot couldn't be saved."));
return;
}
};
@@ -436,14 +437,14 @@ pub fn screenshot_file(window: Window) {
if let Err(e) = std::fs::create_dir_all(&dir) {
tracing::warn!(error = %e, "can't create Downloads\\Nectarlink");
set_notice(window, "Couldn't save screenshot");
- show_message("The screenshot couldn't be saved.");
+ show_message(tr!("Mirror", "The screenshot couldn't be saved."));
return;
}
let path = free_path(&dir, &base_name);
if let Err(e) = std::fs::write(&path, &png) {
tracing::warn!(error = %e, "can't write mirror screenshot");
set_notice(window, "Couldn't save screenshot");
- show_message("The screenshot couldn't be saved.");
+ show_message(tr!("Mirror", "The screenshot couldn't be saved."));
return;
}
let file_name = path.file_name().and_then(|n| n.to_str()).unwrap_or(&base_name).to_owned();
@@ -477,7 +478,7 @@ pub fn screenshot_file(window: Window) {
call: false,
});
set_notice(window, format!("Saved {file_name}"));
- show_message(format!("Saved {file_name} to Downloads\\Nectarlink."));
+ show_message(tr!("Mirror", "Saved %1 to Downloads\\Nectarlink.", file_name));
}
/// Whether `window` is currently recording to an MP4 file.
@@ -511,7 +512,7 @@ pub fn toggle_recording(window: Window) {
}
if !matches!(phase(&window), Some(Phase::Showing)) {
set_notice(window, "Wait for the screen to appear first");
- show_message("Wait for the screen to appear first.");
+ show_message(tr!("Mirror", "Wait for the screen to appear first."));
return;
}
let base_name = local_timestamp_filename("Mirror", "mp4");
@@ -519,7 +520,7 @@ pub fn toggle_recording(window: Window) {
if let Err(e) = std::fs::create_dir_all(&dir) {
tracing::warn!(error = %e, "can't create Downloads\\Nectarlink");
set_notice(window, "Couldn't start recording");
- show_message("Couldn't start recording.");
+ show_message(tr!("Mirror", "Couldn't start recording."));
return;
}
let path = free_path(&dir, &base_name);
@@ -622,7 +623,7 @@ pub fn stop_recording(window: Window) {
call: false,
});
set_notice(window, format!("Saved {file_name}"));
- show_message(format!("Saved {file_name} to Downloads\\Nectarlink."));
+ show_message(tr!("Mirror", "Saved %1 to Downloads\\Nectarlink.", file_name));
}
Ok(Err(msg)) => {
set_notice(window, msg.clone());
diff --git a/desktop/app/src/notifications.rs b/desktop/app/src/notifications.rs
index 1589b89..4718e1f 100644
--- a/desktop/app/src/notifications.rs
+++ b/desktop/app/src/notifications.rs
@@ -4,6 +4,7 @@
//! them), and what the user does with a toast or the feed goes back to the
//! phone.
+use crate::i18n::tr;
use std::{
collections::{HashMap, HashSet},
sync::{
@@ -119,7 +120,7 @@ pub fn copy_otp(code: &str) {
return;
}
if crate::win::clipboard::write_private(trimmed).is_ok() {
- crate::bridge::app::show_message("Code copied");
+ crate::bridge::app::show_message(tr!("Notifications", "Code copied"));
}
}
diff --git a/desktop/app/src/phone_mic.rs b/desktop/app/src/phone_mic.rs
index 206386e..58d8266 100644
--- a/desktop/app/src/phone_mic.rs
+++ b/desktop/app/src/phone_mic.rs
@@ -6,6 +6,7 @@
//! listening in. A virtual microphone of NectarLink's own needs an audio
//! driver and is a later, separate step (GitHub #7).
+use crate::i18n::tr;
use std::sync::{
Arc, Mutex,
atomic::{AtomicU32, Ordering},
@@ -178,12 +179,14 @@ pub fn start(phone: DeviceId) {
set_phase(Phase::Asking(phone));
core_host::spawn(async move {
match node.mic_start(phone).await {
- Ok(()) => show_message(format!("Tap Start on {name} to use its microphone.")),
+ Ok(()) => show_message(tr!("PhoneMic", "Tap Start on %1 to use its microphone.", name)),
Err(e) => {
set_phase(Phase::Off);
show_message(match e {
- Error::Unsupported => format!("Update NectarLink on {name} to use its microphone."),
- Error::Denied => format!("The microphone is turned off for this PC on {name}."),
+ Error::Unsupported => {
+ tr!("PhoneMic", "Update NectarLink on %1 to use its microphone.", name)
+ }
+ Error::Denied => tr!("PhoneMic", "The microphone is turned off for this PC on %1.", name),
other => describe(&other),
});
}
diff --git a/desktop/app/src/photos.rs b/desktop/app/src/photos.rs
index 55f4b1d..c213004 100644
--- a/desktop/app/src/photos.rs
+++ b/desktop/app/src/photos.rs
@@ -7,6 +7,7 @@
//! folder or `Downloads\Nectarlink`), Copy to clipboard, and Open in the
//! Windows Photos app or default video player.
+use crate::i18n::tr;
use std::{
collections::{HashMap, HashSet},
path::{Path, PathBuf},
@@ -206,8 +207,10 @@ pub fn on_toast(key: &str, action: Option<&str>) {
core_host::spawn(async move {
match node.fetch_photo(device, photo_id).await {
Ok(transfer) => asked(transfer, intent),
- Err(Error::NotFound) => show_message("That photo isn't on the phone anymore."),
- Err(Error::Denied) => show_message("The phone doesn't share photos or files with this PC."),
+ Err(Error::NotFound) => show_message(tr!("Photos", "That photo isn't on the phone anymore.")),
+ Err(Error::Denied) => {
+ show_message(tr!("Photos", "The phone doesn't share photos or files with this PC."))
+ }
Err(e) => show_message(describe(&e)),
}
});
@@ -399,10 +402,10 @@ fn deliver(transfer_id: &str, intent: Intent, saved: &[PathBuf]) {
match final_paths.as_slice() {
[one] => {
let name = one.file_name().and_then(|n| n.to_str()).unwrap_or("Photo");
- show_message(format!("Saved {name} to {dest_label}."));
+ show_message(tr!("Photos", "Saved %1 to %2.", name, dest_label));
}
many if !many.is_empty() => {
- show_message(format!("Saved {} items to {dest_label}.", many.len()));
+ show_message(tr!("Photos", "Saved %1 items to %2.", many.len(), dest_label));
}
_ => {}
}
@@ -456,15 +459,15 @@ fn copy_file_to_clipboard(path: &Path, remove_after: bool, notify_ui: bool) {
let _ = std::fs::remove_file(path);
}
if notify_ui {
- show_message("Copied to clipboard.");
+ show_message(tr!("Photos", "Copied to clipboard."));
}
}
Err(reason) => {
tracing::warn!(reason, "can't copy a photo");
if remove_after {
- show_message("The photo couldn't be copied. It's in Downloads\\Nectarlink.");
+ show_message(tr!("Photos", "The photo couldn't be copied. It's in Downloads\\Nectarlink."));
} else {
- show_message("The photo couldn't be copied to the clipboard.");
+ show_message(tr!("Photos", "The photo couldn't be copied to the clipboard."));
}
}
}
@@ -1187,7 +1190,7 @@ pub fn open_latest_photo(device: DeviceId) {
let Some(node) = core_host::node() else { return };
if let Some((id, None)) = cached_or_first {
- show_message("Opening latest photo…");
+ show_message(tr!("Photos", "Opening latest photo…"));
core_host::spawn(async move {
match node.fetch_photo(device, id.clone()).await {
Ok(transfer) => asked(transfer, Intent::Open { item_id: Some(id) }),
@@ -1223,12 +1226,12 @@ pub fn open_latest_photo(device: DeviceId) {
if let Some(path) = timeline_fallback {
crate::transfers::open(&path);
} else {
- show_message("The phone isn't connected right now.");
+ show_message(tr!("Photos", "The phone isn't connected right now."));
}
return;
}
- show_message("Opening latest photo…");
+ show_message(tr!("Photos", "Opening latest photo…"));
core_host::spawn(async move {
match node.photo_list(device, None, None, 1).await {
Ok(items) => {
@@ -1236,7 +1239,7 @@ pub fn open_latest_photo(device: DeviceId) {
if let Some(path) = timeline_fallback {
crate::transfers::open(&path);
} else {
- show_message("No recent photos found on the phone.");
+ show_message(tr!("Photos", "No recent photos found on the phone."));
}
return;
};
@@ -1345,8 +1348,8 @@ pub fn save_items(ids: Vec<String>, folder: Option<PathBuf>) {
fn show_photo_error(error: &Error) {
match error {
- Error::NotFound => show_message("That photo isn't on the phone anymore."),
- Error::Denied => show_message("The phone doesn't share photos or files with this PC."),
+ Error::NotFound => show_message(tr!("Photos", "That photo isn't on the phone anymore.")),
+ Error::Denied => show_message(tr!("Photos", "The phone doesn't share photos or files with this PC.")),
other => show_message(describe(other)),
}
}
diff --git a/desktop/app/src/play_on_phone.rs b/desktop/app/src/play_on_phone.rs
index 167c1ff..f914312 100644
--- a/desktop/app/src/play_on_phone.rs
+++ b/desktop/app/src/play_on_phone.rs
@@ -6,6 +6,7 @@
#![allow(unsafe_code)]
+use crate::i18n::tr;
use std::{
sync::{
Arc, Mutex,
@@ -57,7 +58,7 @@ fn now_playing(player: &str) -> (String, Option<u32>) {
/// button on the PC's media card).
pub fn play(player: String) {
let Some((phone, name)) = phone() else {
- return show_message("Connect your phone to play on it.");
+ return show_message(tr!("PlayOnPhone", "Connect your phone to play on it."));
};
let spawned = std::thread::Builder::new().name("play-on-phone".into()).spawn(move || {
// SAFETY: COM for this short-lived thread (UI Automation).
@@ -75,14 +76,21 @@ pub fn play(player: String) {
PlayOnPhone::Open { url, service } => match node.open_link(phone, url).await {
Ok(()) => {
crate::media::command(crate::media::LOCAL_DEVICE, player, MediaAction::Pause, None);
- show_message(format!("Opening in {service} on {name}. Tap the notification there."));
+ show_message(tr!(
+ "PlayOnPhone",
+ "Opening in %1 on %2. Tap the notification there.",
+ service,
+ name
+ ));
}
Err(e) => show_message(failed(&e, &name)),
},
PlayOnPhone::Stream { open_instead } => {
let shown = (!title.is_empty()).then_some(title);
match node.offer_watch(phone, player.clone(), shown).await {
- Ok(()) => show_message(format!("Tap the notification on {name} to watch.")),
+ Ok(()) => {
+ show_message(tr!("PlayOnPhone", "Tap the notification on %1 to watch.", name))
+ }
// A phone that can't watch yet: the page opens there instead.
Err(Error::Unsupported) if let Some(url) = open_instead => {
match node.open_link(phone, url).await {
@@ -93,7 +101,11 @@ pub fn play(player: String) {
MediaAction::Pause,
None,
);
- show_message(format!("Sent to {name}. Tap the notification there."));
+ show_message(tr!(
+ "PlayOnPhone",
+ "Sent to %1. Tap the notification there.",
+ name
+ ));
}
Err(e) => show_message(failed(&e, &name)),
}
@@ -111,8 +123,8 @@ pub fn play(player: String) {
fn failed(error: &Error, phone: &str) -> String {
match error {
- Error::Unsupported => format!("Update NectarLink on {phone} to play on it."),
- Error::Denied => format!("Media is turned off for {phone}."),
+ Error::Unsupported => tr!("PlayOnPhone", "Update NectarLink on %1 to play on it.", phone),
+ Error::Denied => tr!("PlayOnPhone", "Media is turned off for %1.", phone),
other => describe(other),
}
}
diff --git a/desktop/app/src/transfers.rs b/desktop/app/src/transfers.rs
index 72f5676..21ca675 100644
--- a/desktop/app/src/transfers.rs
+++ b/desktop/app/src/transfers.rs
@@ -3,6 +3,7 @@
//! user picks or drops, opening what arrived, and a Windows notification
//! when files from a phone are saved.
+use crate::i18n::tr;
use std::path::{Path, PathBuf};
use nectarlink_core::{DeviceId, Direction, Error, NodeEvent, Transfer, TransferState};
@@ -50,8 +51,10 @@ fn send_with_mode(device: DeviceId, paths: Vec<PathBuf>, handoff: bool) {
core_host::spawn(async move {
let files = match tokio::task::spawn_blocking(move || nectarlink_core::outgoing_paths(&paths)).await {
Ok(Ok(files)) if !files.is_empty() => files,
- Ok(Ok(_)) => return show_message("There's nothing to send in there."),
- Ok(Err(Error::TooLarge)) => return show_message("That's too many files to send at once."),
+ Ok(Ok(_)) => return show_message(tr!("Transfers", "There's nothing to send in there.")),
+ Ok(Err(Error::TooLarge)) => {
+ return show_message(tr!("Transfers", "That's too many files to send at once."));
+ }
Ok(Err(e)) => return show_message(describe(&e)),
Err(_) => return,
};
@@ -64,7 +67,7 @@ fn send_with_mode(device: DeviceId, paths: Vec<PathBuf>, handoff: bool) {
Ok(transfer_id) => {
crate::bridge::app::show_offline_queued_toast(device, Some(transfer_id));
}
- Err(Error::Denied) => show_message("Files are turned off for that device."),
+ Err(Error::Denied) => show_message(tr!("Transfers", "Files are turned off for that device.")),
Err(e) => show_message(describe(&e)),
}
});
diff --git a/scripts/check.ps1 b/scripts/check.ps1
index 7ea4a2d..7abb13f 100644
--- a/scripts/check.ps1
+++ b/scripts/check.ps1
@@ -63,7 +63,7 @@ try {
Invoke-Step "QML tests" { & (Join-Path $PSScriptRoot "qml-tests.ps1") }
}
Invoke-Step "License headers" { & (Join-Path $PSScriptRoot "check-headers.ps1") }
- Invoke-Step "Generated files" { cargo xtask tokens --check }
+ Invoke-Step "Generated files" { cargo xtask tokens --check; if ($LASTEXITCODE -eq 0) { cargo xtask strings --check } }
if (-not $Fast) {
Invoke-Step "Dependency policy" {
if (-not (Get-Command cargo-deny -ErrorAction SilentlyContinue)) {
diff --git a/tools/xtask/src/main.rs b/tools/xtask/src/main.rs
index ce530bf..53b8531 100644
--- a/tools/xtask/src/main.rs
+++ b/tools/xtask/src/main.rs
@@ -6,8 +6,11 @@
//! `docs/design/tokens.json`, the single source of truth.
//! - `tokens --check`: fails if the generated files are out of date (CI).
//! - `notices <out>`: the third-party notices shipped with the Windows app.
+//! - `strings [--check]`: the Windows app's Rust-built text for Qt's
+//! translation tools (`desktop/app/i18n/rust_strings.h`).
mod notices;
+mod strings;
use std::{
fs,
@@ -28,8 +31,12 @@ fn main() -> ExitCode {
["tokens"] => tokens(false),
["tokens", "--check"] => tokens(true),
["notices", rest @ ..] => notices::run(rest),
+ ["strings"] => strings::run(false),
+ ["strings", "--check"] => strings::run(true),
_ => {
- eprintln!("usage: cargo xtask tokens [--check] | notices <out> [--target <triple>]");
+ eprintln!(
+ "usage: cargo xtask tokens [--check] | strings [--check] | notices <out> [--target <triple>]"
+ );
return ExitCode::from(2);
}
};
diff --git a/tools/xtask/src/strings.rs b/tools/xtask/src/strings.rs
new file mode 100644
index 0000000..fca5f4b
--- /dev/null
+++ b/tools/xtask/src/strings.rs
@@ -0,0 +1,186 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+//! `strings`: the text the Windows app builds in Rust, for Qt's translation
+//! tools. Every `tr!("Context", "Text", ...)` in `desktop/app/src` goes into
+//! `desktop/app/i18n/rust_strings.h` as a `QT_TRANSLATE_NOOP`, which `lupdate`
+//! reads along with the QML. `--check` fails when the file is out of date.
+
+use std::{
+ collections::BTreeMap,
+ fs,
+ path::{Path, PathBuf},
+};
+
+use anyhow::{Context, Result, bail};
+
+const SOURCES: &str = "desktop/app/src";
+const OUT: &str = "desktop/app/i18n/rust_strings.h";
+
+pub fn run(check: bool) -> Result<()> {
+ let root = crate::repo_root();
+ let mut files = Vec::new();
+ collect(&root.join(SOURCES), &mut files)?;
+ files.sort();
+ // (context, text) -> the file it first appears in (no line: a line
+ // moving would make the file stale).
+ let mut strings: BTreeMap<(String, String), String> = BTreeMap::new();
+ for file in &files {
+ let source = fs::read_to_string(file).with_context(|| format!("reading {}", file.display()))?;
+ let shown = file.strip_prefix(&root).unwrap_or(file).to_string_lossy().replace('\\', "/");
+ for (_, context, text) in find(&source).with_context(|| format!("in {shown}"))? {
+ // The unit tests' own strings aren't the app's.
+ if context != "Tests" {
+ strings.entry((context, text)).or_insert_with(|| shown.clone());
+ }
+ }
+ }
+ let content = render(&strings);
+ let out = root.join(OUT);
+ if check {
+ if fs::read_to_string(&out).unwrap_or_default() != content {
+ bail!("out of date: {OUT}; run `cargo xtask strings`");
+ }
+ println!("{OUT} is up to date ({} strings)", strings.len());
+ } else {
+ fs::write(&out, content).with_context(|| format!("writing {OUT}"))?;
+ println!("wrote {OUT} ({} strings)", strings.len());
+ }
+ Ok(())
+}
+
+fn collect(dir: &Path, files: &mut Vec<PathBuf>) -> Result<()> {
+ for entry in fs::read_dir(dir).with_context(|| format!("reading {}", dir.display()))? {
+ let path = entry?.path();
+ if path.is_dir() {
+ collect(&path, files)?;
+ } else if path.extension().is_some_and(|e| e == "rs") {
+ files.push(path);
+ }
+ }
+ Ok(())
+}
+
+/// Every `tr!("Context", "Text"` in `source`: its line, context and text.
+fn find(source: &str) -> Result<Vec<(usize, String, String)>> {
+ let mut found = Vec::new();
+ let mut rest = source;
+ let mut offset = 0;
+ while let Some(at) = rest.find("tr!(") {
+ // Not a longer name ending in "tr" (e.g. `str!(`).
+ let before = source[..offset + at].chars().next_back();
+ let start = offset + at + "tr!(".len();
+ offset = start;
+ rest = &source[start..];
+ if before.is_some_and(|c| c.is_alphanumeric() || c == '_') {
+ continue;
+ }
+ // Not in a comment (a doc example).
+ let line_start = source[..start].rfind('\n').map_or(0, |i| i + 1);
+ if source[line_start..start].contains("//") {
+ continue;
+ }
+ let line = source[..start].matches('\n').count() + 1;
+ let (context, after) =
+ literal(rest).with_context(|| format!("line {line}: tr! needs a context literal"))?;
+ let after = after.trim_start().strip_prefix(',').context("tr! needs a text")?;
+ let (text, _) = literal(after).with_context(|| format!("line {line}: tr! needs a text literal"))?;
+ found.push((line, context, text));
+ }
+ Ok(found)
+}
+
+/// A Rust string literal at the start of `s` (after whitespace), unescaped,
+/// and what follows it.
+fn literal(s: &str) -> Result<(String, &str)> {
+ let s = s.trim_start();
+ let body = s.strip_prefix('"').context("not a string literal")?;
+ let mut out = String::new();
+ let mut chars = body.char_indices();
+ while let Some((i, c)) = chars.next() {
+ match c {
+ '"' => return Ok((out, &body[i + 1..])),
+ '\\' => match chars.next().map(|(_, e)| e) {
+ Some('n') => out.push('\n'),
+ Some('t') => out.push('\t'),
+ Some('"') => out.push('"'),
+ Some('\'') => out.push('\''),
+ Some('\\') => out.push('\\'),
+ Some('\n') => {
+ // A line continuation: skip the next line's indentation.
+ while chars.clone().next().is_some_and(|(_, c)| c.is_whitespace()) {
+ chars.next();
+ }
+ }
+ other => bail!("unsupported escape {other:?}"),
+ },
+ c => out.push(c),
+ }
+ }
+ bail!("unterminated string literal")
+}
+
+fn c_string(s: &str) -> String {
+ let mut out = String::from("\"");
+ for c in s.chars() {
+ match c {
+ '"' => out.push_str("\\\""),
+ '\\' => out.push_str("\\\\"),
+ '\n' => out.push_str("\\n"),
+ '\t' => out.push_str("\\t"),
+ c => out.push(c),
+ }
+ }
+ out.push('"');
+ out
+}
+
+fn render(strings: &BTreeMap<(String, String), String>) -> String {
+ let mut out = String::from(
+ "// SPDX-License-Identifier: GPL-3.0-or-later\n\
+ // Generated by `cargo xtask strings` from the tr! calls in desktop/app/src. Do not edit.\n\
+ // Never compiled: lupdate reads it with the QML, so the text the app builds\n\
+ // in Rust is translated like the rest (see desktop/app/src/i18n.rs).\n\
+ \n\
+ static const char *const nectarlink_rust_strings[] = {\n",
+ );
+ for ((context, text), at) in strings {
+ out.push_str(&format!(" QT_TRANSLATE_NOOP({}, {}), // {at}\n", c_string(context), c_string(text)));
+ }
+ out.push_str("};\n");
+ out
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn finds_tr_calls_with_their_text() {
+ let source = r#"
+ show_message(tr!("Media", "That player can't do that."));
+ let x = tr!("Links", "Sent to %1", name);
+ let s = my_str!("not this");
+ /// An example: tr!("Docs", "not this either")
+ tr!(
+ "Mic",
+ "Plays into \"%1\"",
+ device
+ );
+ "#;
+ let found = find(source).unwrap();
+ assert_eq!(
+ found,
+ vec![
+ (2, "Media".into(), "That player can't do that.".into()),
+ (3, "Links".into(), "Sent to %1".into()),
+ (6, "Mic".into(), "Plays into \"%1\"".into()),
+ ]
+ );
+ }
+
+ #[test]
+ fn the_header_escapes_for_c() {
+ let mut strings = BTreeMap::new();
+ strings.insert(("Ctx".to_owned(), "Say \"hi\"\\".to_owned()), "a.rs".to_owned());
+ assert!(render(&strings).contains(r#"QT_TRANSLATE_NOOP("Ctx", "Say \"hi\"\\"), // a.rs"#));
+ }
+}