nexus\api/
localization.rs

1//! Localization of strings.
2
3use crate::{
4    util::{str_to_c, string_from_c},
5    AddonApi, LocalizationApi,
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, "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, "failed to convert translation identifier");
41    let language = str_to_c(
42        language_identifier,
43        "failed to convert translation language identifier",
44    );
45    unsafe { string_from_c(translate_to(identifier.as_ptr(), language.as_ptr())) }
46}
47
48/// Attempts to set a translated string for the given identifier and language at runtime.
49#[inline]
50pub fn set_translation(
51    identifier: impl AsRef<str>,
52    language_identifier: impl AsRef<str>,
53    string: impl AsRef<str>,
54) {
55    let LocalizationApi { set, .. } = AddonApi::get().localization;
56    let identifier = str_to_c(identifier, "failed to convert translation identifier");
57    let language = str_to_c(
58        language_identifier,
59        "failed to convert translation language identifier",
60    );
61    let string = str_to_c(string, "failed to convert translation string");
62    unsafe { set(identifier.as_ptr(), language.as_ptr(), string.as_ptr()) }
63}