6#include "GuiTextTranslator.h"
12#define HASHWORDBITS 32
14GuiTextTranslator::GuiTextTranslator() :
18GuiTextTranslator::~GuiTextTranslator() {
23uint32_t GuiTextTranslator::hashString(
const char *str_param) {
25 const char *str = str_param;
27 while (*str !=
'\0') {
29 hval += (uint8_t) * str++;
30 g = hval & ((uint32_t) 0xf << (HASHWORDBITS - 4));
32 hval ^= g >> (HASHWORDBITS - 8);
40char* GuiTextTranslator::expandEscape(
const char *str) {
44 retval = (
char*) malloc(strlen(str) + 1);
45 if (retval ==
nullptr)
50 while (cp[0] !=
'\0' && cp[0] !=
'\\')
103 int ch = *cp++ -
'0';
104 if (*cp >=
'0' && *cp <=
'7') {
108 if (*cp >=
'0' && *cp <=
'7') {
121 while (cp[0] !=
'\0' && cp[0] !=
'\\')
124 }
while (cp[0] !=
'\0');
126 terminate: *rp =
'\0';
130GuiTextTranslator::MSG* GuiTextTranslator::findMessage(uint32_t
id)
const {
131 for (MSG *msg = head; msg; msg = msg->next) {
138GuiTextTranslator::MSG* GuiTextTranslator::setMessage(
const char *msgid,
const char *msgstr) {
139 uint32_t
id = hashString(msgid);
140 MSG *msg = findMessage(
id);
145 msg->msgstr =
nullptr;
155 msg->msgstr = expandEscape(msgstr);
163 MSG *nextMsg = head->next;
171const char* GuiTextTranslator::memFGets(
char *dst,
int maxlen,
const char *src,
const char *eof)
const {
172 if (!src || !dst || maxlen <= 0 || src >= eof)
176 while (src + len < eof && src[len] !=
'\n' && len < maxlen - 1) {
183 if (src + len < eof && src[len] ==
'\n') {
184 return src + len + 1;
193 if (!buffer || size == 0)
197 char *lastID =
nullptr;
198 const char *ptr =
reinterpret_cast<const char*
>(buffer);
199 const char *eof = ptr + size;
201 while (ptr && ptr < eof) {
202 const char *nextPtr = memFGets(line,
sizeof(line), ptr, eof);
204 if (!nextPtr && ptr == nextPtr)
210 if (line[0] ==
'#' || line[0] ==
'\0')
213 if (strncmp(line,
"msgid \"", 7) == 0) {
219 char *msgid = &line[7];
220 char *end = strrchr(msgid,
'"');
221 if (end && (end - msgid) >= 0) {
223 lastID = strdup(msgid);
225 }
else if (strncmp(line,
"msgstr \"", 8) == 0) {
229 char *msgstr = &line[8];
230 char *end = strrchr(msgstr,
'"');
231 if (end && (end - msgstr) >= 0) {
233 setMessage(lastID, msgstr);
252 MSG *msg = findMessage(hashString(msgid));
254 if (msg && msg->msgstr && msg->msgstr[0] !=
'\0') {
const char * getText(const char *msgid) const
Retrieves the translated UTF-8 string for a given ASCII message ID.
bool loadLanguage(const uint8_t *buffer, size_t size)
Loads and parses a translation file from a memory buffer.
void clear()
Clears the current translation dictionary and frees memory.