Internalize hack for dynamic translations change so that it also works for Rust apps

This commit is contained in:
Simon Hausmann 2024-06-03 16:19:47 +02:00 committed by Simon Hausmann
parent 66652cdc1d
commit 623bae7732
3 changed files with 14 additions and 6 deletions

View file

@ -1276,10 +1276,7 @@ inline SharedString translate(const SharedString &original, const SharedString &
/// Example /// Example
/// ```cpp /// ```cpp
/// my_ui->global<LanguageSettings>().on_french_selected([] { /// my_ui->global<LanguageSettings>().on_french_selected([] {
/// // trick from https://www.gnu.org/software/gettext/manual/html_node/gettext-grok.html
/// setenv("LANGUAGE", langs[l], true); /// setenv("LANGUAGE", langs[l], true);
/// extern int _nl_msg_cat_cntr;
/// ++_nl_msg_cat_cntr;
/// slint::update_all_translations(); /// slint::update_all_translations();
/// }); /// });
/// ``` /// ```

View file

@ -80,9 +80,6 @@ int main()
printer_demo->global<PrinterSettings>().on_change_language([](int l) { printer_demo->global<PrinterSettings>().on_change_language([](int l) {
static const char *langs[] = { "en", "fr" }; static const char *langs[] = { "en", "fr" };
setenv("LANGUAGE", langs[l], true); setenv("LANGUAGE", langs[l], true);
// trick from https://www.gnu.org/software/gettext/manual/html_node/gettext-grok.html
extern int _nl_msg_cat_cntr;
++_nl_msg_cat_cntr;
slint::update_all_translations(); slint::update_all_translations();
}); });
#endif #endif

View file

@ -225,6 +225,20 @@ fn translate_gettext(string: &str, ctx: &str, domain: &str, n: i32, plural: &str
} }
pub fn mark_all_translations_dirty() { pub fn mark_all_translations_dirty() {
#[cfg(all(feature = "gettext-rs", target_family = "unix"))]
{
// SAFETY: This trick from https://www.gnu.org/software/gettext/manual/html_node/gettext-grok.html
// is merely incrementing a generational counter that will invalidate gettext's internal cache for translations.
// If in the worst case it won't invalidate, then old translations are shown.
#[allow(unsafe_code)]
unsafe {
extern "C" {
static mut _nl_msg_cat_cntr: std::ffi::c_int;
}
_nl_msg_cat_cntr += 1;
}
}
crate::context::GLOBAL_CONTEXT.with(|ctx| { crate::context::GLOBAL_CONTEXT.with(|ctx| {
let Some(ctx) = ctx.get() else { return }; let Some(ctx) = ctx.get() else { return };
ctx.0.translations_dirty.mark_dirty(); ctx.0.translations_dirty.mark_dirty();