Skip to main content

nexus\api/
localization.rs

1//! Localization of strings.
2
3use crate::{
4    AddonApi, LocalizationApi,
5    ffi::{str_to_c, string_from_c},
6};
7use std::ffi::c_char;
8
9pub type RawLocalizationTranslate =
10    unsafe extern "C-unwind" fn(identifier: *const c_char) -> *const c_char;
11
12pub type RawLocalizationTranslateTo = unsafe extern "C-unwind" fn(
13    identifier: *const c_char,
14    language_identifier: *const c_char,
15) -> *const c_char;
16
17pub type RawLocalizationSet = unsafe extern "C-unwind" fn(
18    identifier: *const c_char,
19    language_identifier: *const c_char,
20    string: *const c_char,
21);
22
23/// Attempts to translate the identifier into the current active language.
24/// Returns the same identifier if not available.
25#[inline]
26pub fn translate(identifier: impl AsRef<str>) -> Option<String> {
27    let LocalizationApi { translate, .. } = AddonApi::get().localization;
28    let identifier = str_to_c(identifier).expect("failed to convert translation identifier");
29    unsafe { string_from_c(translate(identifier.as_ptr())) }
30}
31
32/// Attempts to translate the identifier into the given language.
33/// Returns the same identifier if not available.
34#[inline]
35pub fn translate_to(
36    identifier: impl AsRef<str>,
37    language_identifier: impl AsRef<str>,
38) -> Option<String> {
39    let LocalizationApi { translate_to, .. } = AddonApi::get().localization;
40    let identifier = str_to_c(identifier).expect("failed to convert translation identifier");
41    let language =
42        str_to_c(language_identifier).expect("failed to convert translation language identifier");
43    unsafe { string_from_c(translate_to(identifier.as_ptr(), language.as_ptr())) }
44}
45
46/// Attempts to set a translated string for the given identifier and language at runtime.
47#[inline]
48pub fn set_translation(
49    identifier: impl AsRef<str>,
50    language_identifier: impl AsRef<str>,
51    string: impl AsRef<str>,
52) {
53    let LocalizationApi { set, .. } = AddonApi::get().localization;
54    let identifier = str_to_c(identifier).expect("failed to convert translation identifier");
55    let language =
56        str_to_c(language_identifier).expect("failed to convert translation language identifier");
57    let string = str_to_c(string).expect("failed to convert translation string");
58    unsafe { set(identifier.as_ptr(), language.as_ptr(), string.as_ptr()) }
59}