es_fluent_manager_embedded/lib.rs
1#![doc = include_str!("../README.md")]
2
3use es_fluent::set_shared_context;
4use es_fluent_manager_core::FluentManager;
5use std::sync::{Arc, OnceLock, RwLock};
6use unic_langid::LanguageIdentifier;
7
8#[cfg(feature = "macros")]
9pub use es_fluent_manager_macros::define_embedded_i18n_module as define_i18n_module;
10
11static GENERIC_MANAGER: OnceLock<Arc<RwLock<FluentManager>>> = OnceLock::new();
12
13/// Initializes the embedded singleton `FluentManager`.
14///
15/// This function discovers all embedded i18n modules linked into the binary,
16/// creates a `FluentManager` with them, and sets it as a global embedded singleton.
17/// It also registers this manager with the `es-fluent` crate's central context,
18/// allowing the `es_fluent::localize!` macro to work.
19///
20/// This function should be called once at the beginning of your application's
21/// lifecycle.
22///
23/// # Panics
24///
25/// This function will not panic if called more than once, but it will log a
26/// warning and have no effect after the first successful call.
27pub fn init() {
28 let manager = FluentManager::new_with_discovered_modules();
29 let manager_arc = Arc::new(RwLock::new(manager));
30 if GENERIC_MANAGER.set(manager_arc.clone()).is_ok() {
31 set_shared_context(manager_arc);
32 } else {
33 log::warn!("Generic fluent manager already initialized.");
34 }
35}
36
37/// Selects the active language for the embedded singleton `FluentManager`.
38///
39/// After a language is selected, all subsequent calls to localization functions
40/// will use the bundles for this language.
41///
42/// # Errors
43///
44/// This function will log an error if the embedded singleton has not been initialized by
45/// calling `init()` first.
46pub fn select_language(lang: &LanguageIdentifier) {
47 if let Some(manager_arc) = GENERIC_MANAGER.get() {
48 let mut manager = manager_arc.write().unwrap();
49 manager.select_language(lang);
50 } else {
51 log::error!("Generic fluent manager not initialized. Call init() first.");
52 }
53}