3 #include "CTranslator.h"
5 #include "CTextParsers.h"
6 #include "LibrarySys.h"
7 #include "sm_stringutil.h"
10 CTranslator g_Translator;
21 unsigned int fmt_count;
22 unsigned int fmt_bytes;
24 unsigned int translations;
27 CPhraseFile::CPhraseFile(CTranslator *pTranslator, const char *file)
29 m_pStringTab = pTranslator->GetStringTable();
30 m_pMemory = m_pStringTab->GetMemTable();
31 m_LangCount = pTranslator->GetLanguageCount();
33 m_pTranslator = pTranslator;
34 m_pPhraseLookup = NULL;
37 CPhraseFile::~CPhraseFile()
41 sm_trie_destroy(m_pPhraseLookup);
45 void CPhraseFile::ParseError(const char *message, ...)
49 va_start(ap, message);
50 vsnprintf(buffer, sizeof(buffer), message, ap);
53 m_ParseError.assign(buffer);
56 void CPhraseFile::ParseWarning(const char *message, ...)
60 va_start(ap, message);
61 vsnprintf(buffer, sizeof(buffer), message, ap);
66 g_Logger.LogError("[SM] Warning(s) encountered in translation file \"%s\"", m_File.c_str());
70 g_Logger.LogError("[SM] %s", message);
73 void CPhraseFile::ReparseFile()
77 sm_trie_destroy(m_pPhraseLookup);
79 m_pPhraseLookup = sm_trie_create();
81 m_LangCount = m_pTranslator->GetLanguageCount();
89 char path[PLATFORM_MAX_PATH+1];
90 g_SourceMod.BuildPath(Path_SM, path, PLATFORM_MAX_PATH, "translations/%s", m_File.c_str());
91 unsigned int line=0, col=0;
93 if ((err=g_TextParser.ParseFile_SMC(path, this, &line, &col)) != SMCParse_Okay)
95 const char *msg = g_TextParser.GetSMCErrorString(err);
98 msg = m_ParseError.c_str();
101 g_Logger.LogError("[SM] Fatal error encountered parsing translation file \"%s\"", m_File.c_str());
102 g_Logger.LogError("[SM] Error (line %d, column %d): %s", line, col, msg);
106 void CPhraseFile::ReadSMC_ParseStart()
109 m_ParseState = PPS_None;
111 m_FileLogged = false;
112 m_LastPhraseString.clear();
115 SMCParseResult CPhraseFile::ReadSMC_RawLine(const char *line, unsigned int curline)
119 return SMCParse_Continue;
122 SMCParseResult CPhraseFile::ReadSMC_NewSection(const char *name, bool opt_quotes)
124 bool recognized = false;
125 if (m_ParseState == PPS_None)
127 if (strcmp(name, "Phrases") == 0)
129 m_ParseState = PPS_Phrases;
132 } else if (m_ParseState == PPS_Phrases) {
133 m_ParseState = PPS_InPhrase;
137 m_CurPhrase = m_pMemory->CreateMem(sizeof(phrase_t), (void **)&pPhrase);
139 /* Create the reverse lookup */
140 if (!sm_trie_insert(m_pPhraseLookup, name, reinterpret_cast<void *>(m_CurPhrase)))
142 ParseWarning("Skipping duplicate phrase \"%s\" on line %d.", name, m_CurLine);
143 /* :IDEA: prevent memory waste by seeking backwards in memtable? */
146 /* Initialize new phrase */
149 pPhrase->fmt_count = 0;
150 pPhrase->fmt_list = -1;
151 pPhrase->trans_tbl = m_pMemory->CreateMem(sizeof(trans_t) * m_LangCount, (void **)&pTrans);
152 pPhrase->translations = 0;
153 pPhrase->fmt_bytes = 0;
155 for (unsigned int i=0; i<m_LangCount; i++)
157 pTrans[i].stridx = -1;
159 m_LastPhraseString.assign(name);
161 } else if (m_ParseState == PPS_InPhrase) {
162 ParseError("Phrase sections may not have sub-sections");
163 return SMCParse_HaltFail;
168 ParseWarning("Ignoring invalid section \"%s\" on line %d.", name, m_CurLine);
171 return SMCParse_Continue;
174 SMCParseResult CPhraseFile::ReadSMC_KeyValue(const char *key, const char *value, bool key_quotes, bool value_quotes)
176 /* See if we are ignoring a phrase */
179 return SMCParse_Continue;
182 phrase_t *pPhrase = (phrase_t *)m_pMemory->GetAddress(m_CurPhrase);
184 if (key[0] == '#' && strcmp(key, "#format") == 0)
186 if (pPhrase->fmt_list != -1)
188 ParseWarning("Ignoring duplicated #format property on line %d", m_CurLine);
189 return SMCParse_Continue;
192 if (pPhrase->translations > 0)
194 ParseWarning("#format property should come before translations on line %d, ignoring", m_CurLine);
195 return SMCParse_Continue;
198 /* Do an initial browsing for error checking and what not */
206 ParseStates state = Parse_None;
208 const char *old_value = value;
209 while (*value != '\0')
211 if (state == Parse_None)
215 pPhrase->fmt_count++;
217 } else if (*value == ',') {
220 unsigned int bytes = g_TextParser.GetUTF8CharBytes(value);
221 if (bytes != 1 || !isalpha(*value))
223 ParseWarning("Invalid token '%c' in #format property on line %d.", *value, m_CurLine);
226 } else if (state == Parse_Index) {
229 state = Parse_Format;
230 if (value - old_value >= 15)
232 ParseWarning("Too many digits in format index on line %d, phrase will be ignored.", m_CurLine);
234 return SMCParse_Continue;
237 unsigned int bytes = g_TextParser.GetUTF8CharBytes(value);
238 if (bytes != 1 || !isdigit(*value))
240 ParseWarning("Token '%c' in #format property on line %d is not a digit, phrase will be ignored.",
244 return SMCParse_Continue;
247 } else if (state == Parse_Format) {
256 if (state != Parse_None)
258 /* Moose clam cow. */
259 ParseWarning("Unterminated format string on line %d, phrase will be ignored.", m_CurLine);
261 return SMCParse_Continue;
265 /* Allocate the format table */
268 pPhrase->fmt_list = m_pMemory->CreateMem(sizeof(int) * pPhrase->fmt_count, (void **)&fmt_list);
271 for (size_t i=0; i<pPhrase->fmt_count; i++)
276 /* Now we need to read again... this time into the format buffer */
277 const char *in_ptr = value;
278 const char *idx_ptr = NULL;
279 char *out_ptr = NULL;
280 unsigned int cur_idx = 0;
282 while (*in_ptr != '\0')
284 if (state == Parse_None)
291 } else if (state == Parse_Index) {
294 /* Check the number! */
297 ParseWarning("Format property contains unindexed format string on line %d, phrase will be ignored.", m_CurLine);
299 return SMCParse_Continue;
301 long idx = strtol(idx_ptr, NULL, 10);
302 if (idx < 1 || idx > (long)pPhrase->fmt_count)
304 ParseWarning("Format property contains invalid index '%d' on line %d, phrase will be ignored.", idx, m_CurLine);
306 return SMCParse_Continue;
307 } else if (fmt_list[idx - 1] != -1) {
308 ParseWarning("Format property contains duplicated index '%d' on line %d, phrase will be ignored.", idx, m_CurLine);
310 return SMCParse_Continue;
312 cur_idx = (unsigned int)idx;
313 state = Parse_Format;
315 } else if (!idx_ptr) {
318 } else if (state == Parse_Format) {
323 ParseWarning("Format property contains empty format string on line %d, phrase will be ignored.", m_CurLine);
325 return SMCParse_Continue;
329 /* Now, add this to our table */
330 fmt_list[cur_idx - 1] = m_pStringTab->AddString(fmt_buf);
331 pPhrase->fmt_bytes += strlen(fmt_buf);
338 /* Check length ... */
339 if (out_ptr - fmt_buf >= sizeof(fmt_buf) - 1)
341 ParseWarning("Format property contains format string that exceeds maximum length on line %d, phrase will be ignored.",
344 return SMCParse_Continue;
346 *out_ptr++ = *in_ptr;
352 /* If we've gotten here, we only accepted unique indexes in a range.
353 * Therefore, the list has to be completely filled. Double check anyway.
355 for (size_t i=0; i<pPhrase->fmt_count; i++)
357 if (fmt_list[i] == -1)
359 ParseWarning("Format property contains no string for index %d on line %d, phrase will be ignored.",
363 return SMCParse_Continue;
367 size_t len = strlen(key);
370 ParseWarning("Ignoring translation to invalid language \"%s\" on line %d.", key, m_CurLine);
371 return SMCParse_Continue;
375 if (!m_pTranslator->GetLanguageByCode(key, &lang))
377 /* Ignore if we don't have a language.
378 * :IDEA: issue a one-time alert?
380 return SMCParse_Continue;
383 /* See how many bytes we need for this string, then allocate.
384 * NOTE: THIS SHOULD GUARANTEE THAT WE DO NOT NEED TO NEED TO SIZE CHECK
386 len = strlen(value) + pPhrase->fmt_bytes + 1;
390 out_idx = m_pMemory->CreateMem(len, (void **)&out_buf);
393 int *fmt_list = (int *)m_pMemory->GetAddress(pPhrase->fmt_list);
394 trans_t *pTrans = (trans_t *)m_pMemory->GetAddress(pPhrase->trans_tbl);
396 pTrans = &pTrans[lang];
397 pTrans->stridx = out_idx;
399 bool params[MAX_TRANSLATE_PARAMS];
401 /* Build the format order list, if necessary */
404 pTrans->fmt_order = m_pMemory->CreateMem(pPhrase->fmt_count * sizeof(int), (void **)&fmt_order);
406 for (unsigned int i=0; i<pPhrase->fmt_count; i++)
410 memset(¶ms[0], 0, sizeof(params));
413 const char *in_ptr = value;
414 char *out_ptr = out_buf;
415 unsigned int order_idx = 0;
416 while (*in_ptr != '\0')
420 switch (*(in_ptr + 1))
435 /* Copy both bytes since we don't know what's going on */
436 *out_ptr++ = *in_ptr++;
437 *out_ptr++ = *in_ptr;
440 /* Skip past the last byte read */
442 } else if (*in_ptr == '{' && fmt_list != NULL) {
443 /* Search for parameters if this is a formatted string */
444 const char *scrap_in_point = in_ptr;
445 const char *digit_start = ++in_ptr;
447 while (*in_ptr != '\0')
449 bytes = g_TextParser.GetUTF8CharBytes(in_ptr);
456 /* Did we get an index? */
457 if (in_ptr == digit_start)
462 long idx = strtol(digit_start, NULL, 10);
463 if (idx < 1 || idx > (int)pPhrase->fmt_count)
472 /* We're safe to insert the string. First mark order. */
473 fmt_order[order_idx++] = (int)idx - 1;
474 /* Now concatenate */
475 out_ptr += sprintf(out_ptr, "%s", m_pStringTab->GetString(fmt_list[idx-1]));
477 params[idx-1] = true;
484 /* Pretend none of this ever happened. Move along now! */
485 in_ptr = scrap_in_point;
486 *out_ptr++ = *in_ptr;
488 *out_ptr++ = *in_ptr;
494 pPhrase->translations++;
497 return SMCParse_Continue;
500 SMCParseResult CPhraseFile::ReadSMC_LeavingSection()
502 if (m_ParseState == PPS_InPhrase)
504 if (m_CurPhrase == -1 && m_LastPhraseString.size())
506 sm_trie_delete(m_pPhraseLookup, m_LastPhraseString.c_str());
509 m_ParseState = PPS_Phrases;
510 m_LastPhraseString.assign("");
511 } else if (m_ParseState == PPS_Phrases) {
512 m_ParseState = PPS_None;
515 return SMCParse_Continue;
518 void CPhraseFile::ReadSMC_ParseEnd(bool halted, bool failed)
520 /* Check to see if we have any dangling phrases that weren't completed, and scrap them */
521 if ((halted || failed) && m_LastPhraseString.size())
523 sm_trie_delete(m_pPhraseLookup, m_LastPhraseString.c_str());
527 const char *CPhraseFile::GetTranslation(const Translation *pTrans, int **fmt_order, unsigned int *fmt_count)
529 if (pTrans->lang_id >= m_LangCount)
535 if (!sm_trie_retrieve(m_pPhraseLookup, pTrans->szPhrase, &object))
540 phrase_t *pPhrase = (phrase_t *)m_pMemory->GetAddress(reinterpret_cast<int>(object));
541 trans_t *trans = (trans_t *)m_pMemory->GetAddress(pPhrase->trans_tbl);
543 trans = &trans[pTrans->lang_id];
545 if (trans->stridx == -1)
550 *fmt_order = (int *)m_pMemory->GetAddress(trans->fmt_order);
551 *fmt_count = pPhrase->fmt_count;
553 return m_pStringTab->GetString(trans->stridx);
556 const char *CPhraseFile::GetFilename()
558 return m_File.c_str();
561 CTranslator::CTranslator()
563 m_pStringTab = new BaseStringTable(2048);
564 m_pLCodeLookup = sm_trie_create();
567 CTranslator::~CTranslator()
569 for (size_t i=0; i<m_Files.size(); i++)
574 for (size_t i=0; i<m_Languages.size(); i++)
576 delete m_Languages[i];
579 sm_trie_destroy(m_pLCodeLookup);
584 bool CTranslator::GetLanguageByCode(const char *code, unsigned int *index)
588 if (!sm_trie_retrieve(m_pLCodeLookup, code, &_index))
595 *index = reinterpret_cast<unsigned int>(_index);
601 unsigned int CTranslator::GetLanguageCount()
603 return (unsigned int)m_Languages.size();
606 BaseStringTable *CTranslator::GetStringTable()
611 unsigned int CTranslator::FindOrAddPhraseFile(const char *phrase_file)
613 for (size_t i=0; i<m_Files.size(); i++)
615 if (strcmp(m_Files[i]->GetFilename(), phrase_file) == 0)
617 return (unsigned int)i;
621 CPhraseFile *pFile = new CPhraseFile(this, phrase_file);
622 unsigned int idx = (unsigned int)m_Files.size();
624 m_Files.push_back(pFile);
626 pFile->ReparseFile();
631 void CTranslator::RebuildLanguageDatabase(const char *lang_header_file)
633 /* Erase everything we have */
634 sm_trie_destroy(m_pLCodeLookup);
635 m_pLCodeLookup = sm_trie_create();
636 m_pStringTab->Reset();
638 for (size_t i=0; i<m_Languages.size(); i++)
640 delete m_Languages[i];
646 unsigned int line=0, col=0;
647 if ((err=g_TextParser.ParseFile_SMC(lang_header_file, this, &line, &col)) != SMCParse_Okay)
649 const char *str_err = g_TextParser.GetSMCErrorString(err);
652 str_err = m_CustomError.c_str();
655 g_Logger.LogError("[SM] Failed to parse language header file: \"%s\"", lang_header_file);
656 g_Logger.LogError("[SM] Parse error (line %d, column %d): %s", line, col, str_err);
659 if (!m_Languages.size())
661 g_Logger.LogError("[SM] Fatal error, no languages found! Translation will not work.");
664 for (size_t i=0; i<m_Files.size(); i++)
666 m_Files[i]->ReparseFile();
670 void CTranslator::ReadSMC_ParseStart()
672 m_InLanguageSection = false;
673 m_CustomError.clear();
676 SMCParseResult CTranslator::ReadSMC_NewSection(const char *name, bool opt_quotes)
678 if (!m_InLanguageSection)
680 if (strcmp(name, "Languages") == 0)
682 m_InLanguageSection = true;
686 if (!m_InLanguageSection)
688 g_Logger.LogError("[SM] Warning: Unrecognized section \"%s\" in languages.cfg", name);
691 return SMCParse_Continue;
694 SMCParseResult CTranslator::ReadSMC_LeavingSection()
696 m_InLanguageSection = false;
698 return SMCParse_Continue;
701 SMCParseResult CTranslator::ReadSMC_KeyValue(const char *key, const char *value, bool key_quotes, bool value_quotes)
703 size_t len = strlen(key);
707 g_Logger.LogError("[SM] Warning encountered parsing languages.cfg file.");
708 g_Logger.LogError("[SM] Invalid language code \"%s\" is being ignored.", key);
711 Language *pLanguage = new Language;
712 unsigned int idx = m_Languages.size();
714 strcpy(pLanguage->m_code2, key);
715 pLanguage->m_FullName = m_pStringTab->AddString(value);
717 sm_trie_insert(m_pLCodeLookup, key, reinterpret_cast<void *>(idx));
719 m_Languages.push_back(pLanguage);
721 return SMCParse_Continue;
724 size_t CTranslator::Translate(char *buffer, size_t maxlength, const Translation *pTrans)
726 if (pTrans->file_id >= m_Files.size())
731 CPhraseFile *pFile = m_Files[pTrans->file_id];
736 if ((str=pFile->GetTranslation(pTrans, &order_table, &count)) == NULL)
741 void *params[MAX_TRANSLATE_PARAMS];
743 /* Rewrite the parameter order */
744 for (unsigned int i=0; i<count; i++)
746 params[i] = pTrans->params[order_table[i]];
749 return gnprintf(buffer, maxlength, str, params);