Skip to content

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

Windows: pick the app's language in Settings

Beeff5d76687705
diff --git a/desktop/app/cpp/app_helpers.cpp b/desktop/app/cpp/app_helpers.cpp
index 4ee99dc..687e759 100644
--- a/desktop/app/cpp/app_helpers.cpp
+++ b/desktop/app/cpp/app_helpers.cpp
@@ -42,17 +42,36 @@ QPointer<QQmlEngine> &qmlEngineRef()
static QPointer<QQmlEngine> engine;
return engine;
}
+
+// Every QML engine registered, for retranslating them all when the
+// language changes (gone ones drop out on their own).
+QList<QPointer<QQmlEngine>> &allEngines()
+{
+ static QList<QPointer<QQmlEngine>> engines;
+ return engines;
+}
+
+void remember(QQmlEngine *engine)
+{
+ auto &engines = allEngines();
+ engines.removeIf([](const QPointer<QQmlEngine> &e) { return e.isNull(); });
+ if (!engines.contains(engine))
+ engines.append(engine);
+}
} // namespace
void register_qml_engine(QQmlEngine *engine)
{
- if (engine)
+ if (engine) {
qmlEngineRef() = engine;
+ remember(engine);
+ }
}
void register_qml_app_engine(QQmlApplicationEngine &engine)
{
qmlEngineRef() = &engine;
+ remember(&engine);
}
#include <QtCore/QDateTime>
@@ -178,10 +197,37 @@ bool start_external_drag(rust::Str file_path, rust::Str text_fallback)
return drag.exec(Qt::CopyAction) != Qt::IgnoreAction;
}
-bool install_system_translator(rust::Str dir)
+namespace {
+// The translators installed now, replaced when the language changes.
+QPointer<QTranslator> &qtTranslator()
+{
+ static QPointer<QTranslator> t;
+ return t;
+}
+QPointer<QTranslator> &appTranslator()
+{
+ static QPointer<QTranslator> t;
+ return t;
+}
+
+void drop(QPointer<QTranslator> &translator)
+{
+ if (translator) {
+ QCoreApplication::removeTranslator(translator);
+ delete translator.data();
+ }
+ translator = nullptr;
+}
+} // namespace
+
+bool install_translator(rust::Str dir, rust::Str language)
{
const QString folder = QString::fromUtf8(dir.data(), static_cast<qsizetype>(dir.size()));
- const QLocale locale = QLocale::system();
+ const QString chosen = QString::fromUtf8(language.data(), static_cast<qsizetype>(language.size()));
+ const QLocale locale = chosen.isEmpty() ? QLocale::system() : QLocale(chosen);
+ QLocale::setDefault(locale);
+ drop(qtTranslator());
+ drop(appTranslator());
// Qt's own strings: file dialogs, context menus, the standard buttons.
// windeployqt stages a merged `qt_<locale>.qm` in `translations/` beside the
@@ -191,29 +237,44 @@ bool install_system_translator(rust::Str dir)
folder + QStringLiteral("/translations"),
QLibraryInfo::path(QLibraryInfo::TranslationsPath),
};
- bool qtInstalled = false;
for (const QString &qtDir : qtDirs) {
for (const char *name : {"qtbase", "qt"}) {
auto *qt = new QTranslator(QCoreApplication::instance());
if (qt->load(locale, QString::fromLatin1(name), QStringLiteral("_"), qtDir)) {
QCoreApplication::installTranslator(qt);
- qtInstalled = true;
+ qtTranslator() = qt;
break;
}
delete qt;
}
- if (qtInstalled)
+ if (qtTranslator())
break;
}
// NectarLink's own strings, staged beside the executable. A locale with no
- // translation (`nectarlink_es_ES.qm` missing) simply stays English.
+ // translation (`nectarlink_es_ES.qm` missing), or English, stays English.
+ bool installed = false;
auto *app = new QTranslator(QCoreApplication::instance());
- if (!app->load(locale, QStringLiteral("nectarlink"), QStringLiteral("_"), folder)) {
+ if (app->load(locale, QStringLiteral("nectarlink"), QStringLiteral("_"), folder)) {
+ installed = QCoreApplication::installTranslator(app);
+ appTranslator() = app;
+ } else {
delete app;
- return false;
}
- return QCoreApplication::installTranslator(app);
+
+ // Windows already open show the new language at once.
+ for (const QPointer<QQmlEngine> &engine : allEngines()) {
+ if (engine)
+ engine->retranslate();
+ }
+ return installed;
+}
+
+rust::String translate(rust::Str context, rust::Str text)
+{
+ const std::string c(context.data(), context.size());
+ const std::string t(text.data(), text.size());
+ return rust::String(QCoreApplication::translate(c.c_str(), t.c_str()).toStdString());
}
diff --git a/desktop/app/cpp/app_helpers.h b/desktop/app/cpp/app_helpers.h
index 527df11..f16d9fe 100644
--- a/desktop/app/cpp/app_helpers.h
+++ b/desktop/app/cpp/app_helpers.h
@@ -37,13 +37,18 @@ void register_qml_app_engine(QQmlApplicationEngine &engine);
// so items dragged out of the Shelf can be dropped into Explorer or any app.
bool start_external_drag(rust::Str file_path, rust::Str text_fallback);
-// Installs the NectarLink and Qt translations for the system locale. `dir` is
-// the folder holding the executable, where windeployqt and the packaging
-// script stage the .qm files. Call after QGuiApplication is created and before
-// the QML engine loads, so that every qsTr() resolves on the first pass and no
-// retranslation is needed. Returns true when NectarLink's own translation was
-// found and installed.
-bool install_system_translator(rust::Str dir);
+// Installs the NectarLink and Qt translations for `language` (a locale name
+// such as "zh_CN", or "" for the system's), replacing those installed before.
+// `dir` is the folder holding the executable, where windeployqt and the
+// packaging script stage the .qm files. Call after QGuiApplication is
+// created and before the QML engine loads, so that every qsTr() resolves on
+// the first pass; called again later, it retranslates the open windows.
+// Returns true when NectarLink's own translation was found and installed.
+bool install_translator(rust::Str dir, rust::Str language);
+
+// `text` in the installed language (Qt's translate), for the strings the app
+// builds in Rust; `text` itself when there is no translation.
+rust::String translate(rust::Str context, rust::Str text);
diff --git a/desktop/app/qml/pages/SettingsPage.qml b/desktop/app/qml/pages/SettingsPage.qml
index 8fdac64..a6f299a 100644
--- a/desktop/app/qml/pages/SettingsPage.qml
+++ b/desktop/app/qml/pages/SettingsPage.qml
@@ -882,6 +882,26 @@ Item {
Column {
width: parent.width
+ // Language: the system's, or one of those the app speaks
+ // (each named in its own language).
+ ListRow {
+ width: parent.width
+ iconPath: Icons.globe
+ title: qsTr("Language")
+ description: qsTr("NectarLink follows Windows unless you pick one.")
+ Segmented {
+ options: [
+ { value: "", label: qsTr("System") },
+ { value: "en", label: "English" },
+ { value: "zh_CN", label: "简体中文" }
+ ]
+ value: Preferences.language
+ onPicked: (v) => Preferences.language = v
+ }
+ }
+
+ Divider { width: parent.width }
+
// Row 1: Start with Windows | Stay in system tray
Item {
id: startupPairRow
diff --git a/desktop/app/src/bridge/native.rs b/desktop/app/src/bridge/native.rs
index c65bc1d..33c3df1 100644
--- a/desktop/app/src/bridge/native.rs
+++ b/desktop/app/src/bridge/native.rs
@@ -34,10 +34,12 @@ pub mod ffi {
/// Starts a native OS drag-and-drop operation for a local file or text.
fn start_external_drag(file_path: &str, text_fallback: &str) -> bool;
- /// Installs the NectarLink and Qt translations for the system locale,
- /// looking in `dir` for the .qm files. Must run after the
- /// `QGuiApplication` exists and before any QML engine loads. Returns
- /// true when NectarLink's own translation was installed.
- fn install_system_translator(dir: &str) -> bool;
+ /// Installs the NectarLink and Qt translations for `language` (a
+ /// locale name, or "" for the system's), looking in `dir` for the
+ /// .qm files and replacing those installed before. Run after the
+ /// `QGuiApplication` exists; before any QML engine loads, or later to
+ /// retranslate the open windows. Returns true when NectarLink's own
+ /// translation was installed.
+ fn install_translator(dir: &str, language: &str) -> bool;
}
}
diff --git a/desktop/app/src/bridge/prefs.rs b/desktop/app/src/bridge/prefs.rs
index dff2629..2afb498 100644
--- a/desktop/app/src/bridge/prefs.rs
+++ b/desktop/app/src/bridge/prefs.rs
@@ -60,6 +60,8 @@ pub mod qobject {
#[qproperty(bool, pause_media_on_call)]
/// Mute this PC while a phone watches its playback (Play on phone).
#[qproperty(bool, mute_while_watched, cxx_name = "muteWhileWatched")]
+ /// The app's language: "" for the system's, "en", "zh_CN".
+ #[qproperty(QString, language)]
/// Quiet phone notification pop-ups on the PC while the phone is in Do Not Disturb.
#[qproperty(bool, sync_dnd)]
/// Paired phones in Explorer's "Send to" menu.
@@ -262,6 +264,7 @@ pub struct PreferencesRust {
auto_copy_otp: bool,
pause_media_on_call: bool,
mute_while_watched: bool,
+ language: QString,
sync_dnd: bool,
send_to_menu: bool,
start_with_windows: bool,
@@ -334,6 +337,7 @@ impl cxx_qt::Initialize for qobject::Preferences {
crate::notifications::set_auto_copy_otp(settings.auto_copy_otp);
self.as_mut().set_pause_media_on_call(settings.pause_media_on_call);
self.as_mut().set_mute_while_watched(settings.mute_while_watched);
+ self.as_mut().set_language(QString::from(&settings.language));
crate::pc_mirror::set_mute_while_watched(settings.mute_while_watched);
crate::calls::set_pause_media_on_call(settings.pause_media_on_call);
self.as_mut().set_sync_dnd(settings.sync_dnd);
@@ -423,6 +427,12 @@ impl cxx_qt::Initialize for qobject::Preferences {
p.save();
})
.release();
+ self.as_mut()
+ .on_language_changed(|p| {
+ crate::i18n::install(&String::from(&p.language));
+ p.save();
+ })
+ .release();
self.as_mut()
.on_mute_while_watched_changed(|p| {
crate::pc_mirror::set_mute_while_watched(p.mute_while_watched);
@@ -877,6 +887,7 @@ impl qobject::Preferences {
auto_copy_otp: p.auto_copy_otp,
pause_media_on_call: p.pause_media_on_call,
mute_while_watched: p.mute_while_watched,
+ language: String::from(&p.language),
sync_dnd: p.sync_dnd,
send_to_menu: p.send_to_menu,
auto_update: p.auto_update,
diff --git a/desktop/app/src/i18n.rs b/desktop/app/src/i18n.rs
new file mode 100644
index 0000000..99115d3
--- /dev/null
+++ b/desktop/app/src/i18n.rs
@@ -0,0 +1,37 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+//! The app's language: the system's or the one chosen in Settings.
+
+use std::path::{Path, PathBuf};
+
+/// Languages the app speaks, as Settings offers them: a locale name ("" for
+/// the system's) and how the language calls itself.
+pub const LANGUAGES: &[(&str, &str)] = &[("", ""), ("en", "English"), ("zh_CN", "简体中文")];
+
+/// Whether `language` is one [`LANGUAGES`] offers.
+pub fn is_known(language: &str) -> bool {
+ LANGUAGES.iter().any(|(code, _)| *code == language)
+}
+
+fn exe_dir() -> Option<PathBuf> {
+ std::env::current_exe().ok().and_then(|exe| exe.parent().map(Path::to_path_buf))
+}
+
+/// Uses `language` ("" for the system's) from now on, retranslating the
+/// open windows. Call on the Qt thread, after the `QGuiApplication` exists.
+pub fn install(language: &str) {
+ let language = if is_known(language) { language } else { "" };
+ let Some(dir) = exe_dir() else { return };
+ let installed = crate::bridge::native::ffi::install_translator(&dir.to_string_lossy(), language);
+ tracing::debug!(language, installed, "translator");
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn only_offered_languages_are_kept() {
+ assert!(is_known("") && is_known("zh_CN") && is_known("en"));
+ assert!(!is_known("xx"));
+ }
+}
diff --git a/desktop/app/src/main.rs b/desktop/app/src/main.rs
index ed42945..359e9c0 100644
--- a/desktop/app/src/main.rs
+++ b/desktop/app/src/main.rs
@@ -19,6 +19,7 @@ mod core_host;
mod deck;
mod doctor;
mod folder_sync;
+mod i18n;
mod icons;
mod input_share;
mod launch;
@@ -392,19 +393,6 @@ fn install_panic_logging() {
}));
}
-/// Installs the translation for the system locale. Call after the
-/// `QGuiApplication` exists and before any QML engine loads: the QML is
-/// compiled ahead of time, so `qsTr()` is only resolved when a component is
-/// built, and installing first means every string is right on the first pass
-/// and nothing has to be retranslated.
-fn install_system_translator() {
- let Some(dir) = std::env::current_exe().ok().and_then(|exe| exe.parent().map(Path::to_path_buf)) else {
- return;
- };
- let installed = bridge::native::ffi::install_system_translator(&dir.to_string_lossy());
- tracing::debug!(installed, "system translator");
-}
-
/// The installer's or uninstaller's window: no core, no data folder, no log
/// file (removal deletes that folder).
fn run_setup_window(mode: setup::Mode) -> ExitCode {
@@ -425,7 +413,8 @@ fn run_setup_window(mode: setup::Mode) -> ExitCode {
app.as_mut().set_application_name(&QString::from("NectarLink Setup"));
app.as_mut().set_application_version(&QString::from(env!("CARGO_PKG_VERSION")));
}
- install_system_translator();
+ // Before any QML loads, so every string is right on the first pass.
+ i18n::install("");
bridge::native::ffi::load_bundled_fonts();
for size in [16, 20, 24, 32, 40, 48, 64, 256] {
bridge::native::ffi::add_app_icon_image(size, &mark::render(size as usize));
@@ -611,7 +600,8 @@ fn main() -> ExitCode {
app.as_mut().set_application_name(&QString::from("Nectarlink"));
app.as_mut().set_application_version(&QString::from(env!("CARGO_PKG_VERSION")));
}
- install_system_translator();
+ // Before any QML loads, so every string is right on the first pass.
+ i18n::install(&settings::Settings::load(&data_dir).language);
bridge::native::ffi::keep_running_without_windows();
// Text falls back to system fonts if these are missing, so it's not fatal.
let fonts = bridge::native::ffi::load_bundled_fonts();
diff --git a/desktop/app/src/settings.rs b/desktop/app/src/settings.rs
index 00b49b2..3b9f858 100644
--- a/desktop/app/src/settings.rs
+++ b/desktop/app/src/settings.rs
@@ -290,6 +290,9 @@ pub struct Settings {
/// Pause PC media playback while a phone call is ringing or active.
#[serde(alias = "pause_media_on_call", alias = "auto_pause_media")]
pub pause_media_on_call: bool,
+ /// The app's language: a locale name from `i18n::LANGUAGES`, or "" for
+ /// the system's.
+ pub language: String,
/// Play on phone: mute this PC's speakers while a phone watches its
/// playback (the phone still gets the sound).
pub mute_while_watched: bool,
@@ -434,6 +437,7 @@ impl Default for Settings {
auto_copy_otp: false,
pause_media_on_call: true,
mute_while_watched: true,
+ language: String::new(),
sync_dnd: false,
send_to_menu: true,
auto_update: true,
@@ -585,6 +589,7 @@ mod tests {
auto_copy_otp: true,
pause_media_on_call: false,
mute_while_watched: false,
+ language: "zh_CN".into(),
sync_dnd: true,
send_to_menu: false,
auto_update: false,