BambuStudio学习笔记:I18N类
# I18N.hpp 代码分析
## 头文件结构
- **防止重复包含**: 使用 `#ifndef`/`#define` 标准宏防止重复包含
- **模块检查**:
```cpp
#ifdef SLIC3R_CURRENTLY_COMPILING_GUI_MODULE
#ifndef SLIC3R_ALLOW_LIBSLIC3R_I18N_IN_SLIC3R
#error ...
#endif
#endif
确保GUI模块不错误包含此头文件
核心功能
翻译机制
namespace Slic3r::I18N {
typedef std::string (*translate_fn_type)(const char*);
extern translate_fn_type translate_fn;
void set_translate_callback(translate_fn_type fn);
std::string translate(const std::string &s);
std::string translate(const char *ptr);
}
- 函数指针机制: 允许动态设置翻译函数
- 回调函数设计:
translate_fn
存储实际翻译函数set_translate_callback
用于注入翻译实现translate
方法作为统一入口
非GUI模块处理
#ifndef SLIC3R_CURRENTLY_COMPILING_GUI_MODULE
namespace {
[[maybe_unused]] const char* L(const char* s);
[[maybe_unused]] const char* L_CONTEXT(...);
[[maybe_unused]] std::string _u8L(...);
}
#endif
- 默认实现:
L
直接返回原始字符串(标记需要翻译的字符串)L_CONTEXT
上下文相关翻译占位_u8L
调用实际翻译函数
关键设计特点
-
模块隔离:
- GUI模块需使用自己的I18N实现
- 库模块提供基础翻译框架
-
扩展性设计:
- 通过函数指针支持多语言实现
- 允许运行时切换翻译引擎
-
UTF-8处理:
_u8L
专门处理UTF-8字符串翻译- 返回std::string保证编码正确性
-
上下文支持:
L_CONTEXT
为上下文相关翻译预留接口- 实际实现需在回调函数中处理上下文逻辑
典型使用场景
// 设置翻译回调
I18N::set_translate_callback([](const char* s) {
return gettext(s); // 使用gettext实现
});
// 使用翻译
std::string translated = I18N::translate("Print Settings");
注意事项
- GUI模块应使用专门的I18N实现
- 库模块的L宏仅作标记用途
- 实际翻译功能需要外部注入
- 多线程环境下需保证回调函数线程安全