3 * ===============================================================
4 * SourceMod (C)2004-2007 AlliedModders LLC. All rights reserved.
5 * ===============================================================
7 * This file is not open source and may not be copied without explicit
8 * written permission of AlliedModders LLC. This file may not be redistributed
9 * in whole or significant part.
10 * For information, see LICENSE.txt or http://www.sourcemod.net/license.php
18 #include "Translator.h"
20 #include "TextParsers.h"
21 #include "LibrarySys.h"
22 #include "sm_stringutil.h"
23 #include "sourcemod.h"
25 Translator g_Translator;
26 CPhraseFile *g_pCorePhrases = NULL;
37 unsigned int fmt_count;
38 unsigned int fmt_bytes;
40 unsigned int translations;
43 CPhraseFile::CPhraseFile(Translator *pTranslator, const char *file)
45 m_pStringTab = pTranslator->GetStringTable();
46 m_pMemory = m_pStringTab->GetMemTable();
47 m_LangCount = pTranslator->GetLanguageCount();
49 m_pTranslator = pTranslator;
50 m_pPhraseLookup = NULL;
53 CPhraseFile::~CPhraseFile()
57 sm_trie_destroy(m_pPhraseLookup);
61 void CPhraseFile::ParseError(const char *message, ...)
65 va_start(ap, message);
66 vsnprintf(buffer, sizeof(buffer), message, ap);
69 m_ParseError.assign(buffer);
72 void CPhraseFile::ParseWarning(const char *message, ...)
76 va_start(ap, message);
77 vsnprintf(buffer, sizeof(buffer), message, ap);
82 g_Logger.LogError("[SM] Warning(s) encountered in translation file \"%s\"", m_File.c_str());
86 g_Logger.LogError("[SM] %s", message);
89 void CPhraseFile::ReparseFile()
93 sm_trie_destroy(m_pPhraseLookup);
95 m_pPhraseLookup = sm_trie_create();
97 m_LangCount = m_pTranslator->GetLanguageCount();
105 char path[PLATFORM_MAX_PATH];
106 g_SourceMod.BuildPath(Path_SM, path, PLATFORM_MAX_PATH, "translations/%s", m_File.c_str());
107 unsigned int line=0, col=0;
109 if ((err=g_TextParser.ParseFile_SMC(path, this, &line, &col)) != SMCParse_Okay)
111 const char *msg = g_TextParser.GetSMCErrorString(err);
114 msg = m_ParseError.c_str();
117 g_Logger.LogError("[SM] Fatal error encountered parsing translation file \"%s\"", m_File.c_str());
118 g_Logger.LogError("[SM] Error (line %d, column %d): %s", line, col, msg);
122 void CPhraseFile::ReadSMC_ParseStart()
125 m_ParseState = PPS_None;
127 m_FileLogged = false;
128 m_LastPhraseString.clear();
131 SMCParseResult CPhraseFile::ReadSMC_RawLine(const char *line, unsigned int curline)
135 return SMCParse_Continue;
138 SMCParseResult CPhraseFile::ReadSMC_NewSection(const char *name, bool opt_quotes)
140 bool recognized = false;
141 if (m_ParseState == PPS_None)
143 if (strcmp(name, "Phrases") == 0)
145 m_ParseState = PPS_Phrases;
148 } else if (m_ParseState == PPS_Phrases) {
149 m_ParseState = PPS_InPhrase;
153 m_CurPhrase = m_pMemory->CreateMem(sizeof(phrase_t), (void **)&pPhrase);
155 /* Create the reverse lookup */
156 if (!sm_trie_insert(m_pPhraseLookup, name, reinterpret_cast<void *>(m_CurPhrase)))
158 ParseWarning("Skipping duplicate phrase \"%s\" on line %d.", name, m_CurLine);
159 /* :IDEA: prevent memory waste by seeking backwards in memtable? */
162 /* Initialize new phrase */
165 pPhrase->fmt_count = 0;
166 pPhrase->fmt_list = -1;
168 int trans_tbl = m_pMemory->CreateMem(sizeof(trans_t) * m_LangCount, (void **)&pTrans);
169 /* Update the pointer! */
170 pPhrase = (phrase_t *)m_pMemory->GetAddress(m_CurPhrase);
171 pPhrase->trans_tbl = trans_tbl;
173 pPhrase->translations = 0;
174 pPhrase->fmt_bytes = 0;
176 for (unsigned int i=0; i<m_LangCount; i++)
178 pTrans[i].stridx = -1;
180 m_LastPhraseString.assign(name);
182 } else if (m_ParseState == PPS_InPhrase) {
183 ParseError("Phrase sections may not have sub-sections");
184 return SMCParse_HaltFail;
189 ParseWarning("Ignoring invalid section \"%s\" on line %d.", name, m_CurLine);
192 return SMCParse_Continue;
195 SMCParseResult CPhraseFile::ReadSMC_KeyValue(const char *key, const char *value, bool key_quotes, bool value_quotes)
197 /* See if we are ignoring a phrase */
198 if (m_CurPhrase == -1)
200 return SMCParse_Continue;
203 phrase_t *pPhrase = (phrase_t *)m_pMemory->GetAddress(m_CurPhrase);
205 if (key[0] == '#' && strcmp(key, "#format") == 0)
207 if (pPhrase->fmt_list != -1)
209 ParseWarning("Ignoring duplicated #format property on line %d", m_CurLine);
210 return SMCParse_Continue;
213 if (pPhrase->translations > 0)
215 ParseWarning("#format property should come before translations on line %d, ignoring", m_CurLine);
216 return SMCParse_Continue;
219 /* Do an initial browsing for error checking and what not */
227 ParseStates state = Parse_None;
229 const char *old_value = value;
230 const char *last_value = value;
231 while (*value != '\0')
233 if (state == Parse_None)
237 pPhrase->fmt_count++;
239 } else if (*value == ',') {
242 unsigned int bytes = g_TextParser.GetUTF8CharBytes(value);
243 if (bytes != 1 || !isalpha(*value))
245 ParseWarning("Invalid token '%c' in #format property on line %d.", *value, m_CurLine);
248 } else if (state == Parse_Index) {
251 state = Parse_Format;
252 if (value - last_value >= 15)
254 ParseWarning("Too many digits in format index on line %d, phrase will be ignored.", m_CurLine);
256 return SMCParse_Continue;
259 unsigned int bytes = g_TextParser.GetUTF8CharBytes(value);
260 if (bytes != 1 || !isdigit(*value))
262 ParseWarning("Token '%c' in #format property on line %d is not a digit, phrase will be ignored.",
266 return SMCParse_Continue;
269 } else if (state == Parse_Format) {
273 last_value = value + 1;
279 if (state != Parse_None)
281 /* Moose clam cow. */
282 ParseWarning("Unterminated format string on line %d, phrase will be ignored.", m_CurLine);
284 return SMCParse_Continue;
288 /* Allocate the format table */
291 pPhrase->fmt_list = m_pMemory->CreateMem(sizeof(int) * pPhrase->fmt_count, (void **)&fmt_list);
294 for (size_t i=0; i<pPhrase->fmt_count; i++)
299 /* Now we need to read again... this time into the format buffer */
300 const char *in_ptr = value;
301 const char *idx_ptr = NULL;
302 char *out_ptr = NULL;
303 unsigned int cur_idx = 0;
305 while (*in_ptr != '\0')
307 if (state == Parse_None)
314 } else if (state == Parse_Index) {
317 /* Check the number! */
320 ParseWarning("Format property contains unindexed format string on line %d, phrase will be ignored.", m_CurLine);
322 return SMCParse_Continue;
324 long idx = strtol(idx_ptr, NULL, 10);
325 if (idx < 1 || idx > (long)pPhrase->fmt_count)
327 ParseWarning("Format property contains invalid index '%d' on line %d, phrase will be ignored.", idx, m_CurLine);
329 return SMCParse_Continue;
330 } else if (fmt_list[idx - 1] != -1) {
331 ParseWarning("Format property contains duplicated index '%d' on line %d, phrase will be ignored.", idx, m_CurLine);
333 return SMCParse_Continue;
335 cur_idx = (unsigned int)idx;
336 state = Parse_Format;
338 } else if (!idx_ptr) {
341 } else if (state == Parse_Format) {
346 ParseWarning("Format property contains empty format string on line %d, phrase will be ignored.", m_CurLine);
348 return SMCParse_Continue;
352 /* Now, add this to our table */
353 fmt_list[cur_idx - 1] = m_pStringTab->AddString(fmt_buf);
354 pPhrase->fmt_bytes += strlen(fmt_buf);
361 /* Check length ... */
362 if ((unsigned)(out_ptr - fmt_buf) >= sizeof(fmt_buf) - 1)
364 ParseWarning("Format property contains format string that exceeds maximum length on line %d, phrase will be ignored.",
367 return SMCParse_Continue;
369 *out_ptr++ = *in_ptr;
375 /* If we've gotten here, we only accepted unique indexes in a range.
376 * Therefore, the list has to be completely filled. Double check anyway.
378 for (size_t i=0; i<pPhrase->fmt_count; i++)
380 if (fmt_list[i] == -1)
382 ParseWarning("Format property contains no string for index %d on line %d, phrase will be ignored.",
386 return SMCParse_Continue;
390 size_t len = strlen(key);
393 ParseWarning("Ignoring translation to invalid language \"%s\" on line %d.", key, m_CurLine);
394 return SMCParse_Continue;
398 if (!m_pTranslator->GetLanguageByCode(key, &lang))
400 /* Ignore if we don't have a language.
401 * :IDEA: issue a one-time alert?
403 return SMCParse_Continue;
406 /* See how many bytes we need for this string, then allocate.
407 * NOTE: THIS SHOULD GUARANTEE THAT WE DO NOT NEED TO NEED TO SIZE CHECK
409 len = strlen(value) + pPhrase->fmt_bytes + 1;
413 out_idx = m_pMemory->CreateMem(len, (void **)&out_buf);
416 int *fmt_list = (int *)m_pMemory->GetAddress(pPhrase->fmt_list);
417 trans_t *pTrans = (trans_t *)m_pMemory->GetAddress(pPhrase->trans_tbl);
419 pTrans = &pTrans[lang];
420 pTrans->stridx = out_idx;
422 bool params[MAX_TRANSLATE_PARAMS];
424 /* Build the format order list, if necessary */
427 pTrans->fmt_order = m_pMemory->CreateMem(pPhrase->fmt_count * sizeof(int), (void **)&fmt_order);
429 for (unsigned int i=0; i<pPhrase->fmt_count; i++)
433 memset(¶ms[0], 0, sizeof(params));
436 const char *in_ptr = value;
437 char *out_ptr = out_buf;
438 unsigned int order_idx = 0;
439 while (*in_ptr != '\0')
443 switch (*(in_ptr + 1))
458 /* Copy both bytes since we don't know what's going on */
459 *out_ptr++ = *in_ptr++;
460 *out_ptr++ = *in_ptr;
463 /* Skip past the last byte read */
465 } else if (*in_ptr == '{' && fmt_list != NULL) {
466 /* Search for parameters if this is a formatted string */
467 const char *scrap_in_point = in_ptr;
468 const char *digit_start = ++in_ptr;
470 while (*in_ptr != '\0')
472 bytes = g_TextParser.GetUTF8CharBytes(in_ptr);
479 /* Did we get an index? */
480 if (in_ptr == digit_start)
485 long idx = strtol(digit_start, NULL, 10);
486 if (idx < 1 || idx > (int)pPhrase->fmt_count)
495 /* We're safe to insert the string. First mark order. */
496 fmt_order[order_idx++] = (int)idx - 1;
497 /* Now concatenate */
498 out_ptr += sprintf(out_ptr, "%s", m_pStringTab->GetString(fmt_list[idx-1]));
500 params[idx-1] = true;
507 /* Pretend none of this ever happened. Move along now! */
508 in_ptr = scrap_in_point;
509 *out_ptr++ = *in_ptr;
511 *out_ptr++ = *in_ptr;
517 pPhrase->translations++;
520 return SMCParse_Continue;
523 SMCParseResult CPhraseFile::ReadSMC_LeavingSection()
525 if (m_ParseState == PPS_InPhrase)
527 if (m_CurPhrase == -1 && m_LastPhraseString.size())
529 sm_trie_delete(m_pPhraseLookup, m_LastPhraseString.c_str());
532 m_ParseState = PPS_Phrases;
533 m_LastPhraseString.assign("");
534 } else if (m_ParseState == PPS_Phrases) {
535 m_ParseState = PPS_None;
538 return SMCParse_Continue;
541 void CPhraseFile::ReadSMC_ParseEnd(bool halted, bool failed)
543 /* Check to see if we have any dangling phrases that weren't completed, and scrap them */
544 if ((halted || failed) && m_LastPhraseString.size())
546 sm_trie_delete(m_pPhraseLookup, m_LastPhraseString.c_str());
550 TransError CPhraseFile::GetTranslation(const char *szPhrase, unsigned int lang_id, Translation *pTrans)
552 if (lang_id >= m_LangCount)
554 return Trans_BadLanguage;
558 if (!sm_trie_retrieve(m_pPhraseLookup, szPhrase, &object))
560 return Trans_BadPhrase;
563 phrase_t *pPhrase = (phrase_t *)m_pMemory->GetAddress(reinterpret_cast<int>(object));
564 trans_t *trans = (trans_t *)m_pMemory->GetAddress(pPhrase->trans_tbl);
566 trans = &trans[lang_id];
568 if (trans->stridx == -1)
570 return Trans_BadPhraseLanguage;
573 pTrans->fmt_order = (int *)m_pMemory->GetAddress(trans->fmt_order);
574 pTrans->fmt_count = pPhrase->fmt_count;
576 pTrans->szPhrase = m_pStringTab->GetString(trans->stridx);
581 const char *CPhraseFile::GetFilename()
583 return m_File.c_str();
586 /**************************
587 ** MAIN TRANSLATOR CODE **
588 **************************/
590 Translator::Translator() : m_ServerLang(LANGUAGE_ENGLISH)
592 m_pStringTab = new BaseStringTable(2048);
593 m_pLCodeLookup = sm_trie_create();
594 strncopy(m_InitialLang, "en", sizeof(m_InitialLang));
597 Translator::~Translator()
599 for (size_t i=0; i<m_Files.size(); i++)
604 for (size_t i=0; i<m_Languages.size(); i++)
606 delete m_Languages[i];
609 sm_trie_destroy(m_pLCodeLookup);
614 ConfigResult Translator::OnSourceModConfigChanged(const char *key,
620 if (strcasecmp(key, "ServerLang") == 0)
622 if (source == ConfigSource_Console)
625 if (!GetLanguageByCode(value, &index))
627 UTIL_Format(error, maxlength, "Language code \"%s\" is not registered", value);
628 return ConfigResult_Reject;
631 m_ServerLang = index;
633 strncopy(m_InitialLang, value, sizeof(m_InitialLang));
636 return ConfigResult_Accept;
639 return ConfigResult_Ignore;
642 void Translator::OnSourceModLevelChange(const char *mapName)
644 /* Refresh language stuff */
645 char path[PLATFORM_MAX_PATH];
646 g_SourceMod.BuildPath(Path_SM, path, sizeof(path), "configs/languages.cfg");
647 RebuildLanguageDatabase(path);
650 void Translator::OnSourceModAllInitialized()
652 AddLanguage("en", "English");
653 unsigned int id = FindOrAddPhraseFile("core.cfg");
654 g_pCorePhrases = GetFileByIndex(id);
657 bool Translator::GetLanguageByCode(const char *code, unsigned int *index)
661 if (!sm_trie_retrieve(m_pLCodeLookup, code, &_index))
668 *index = reinterpret_cast<unsigned int>(_index);
674 unsigned int Translator::GetLanguageCount()
676 return (unsigned int)m_Languages.size();
679 BaseStringTable *Translator::GetStringTable()
684 unsigned int Translator::FindOrAddPhraseFile(const char *phrase_file)
686 for (size_t i=0; i<m_Files.size(); i++)
688 if (strcmp(m_Files[i]->GetFilename(), phrase_file) == 0)
690 return (unsigned int)i;
694 CPhraseFile *pFile = new CPhraseFile(this, phrase_file);
695 unsigned int idx = (unsigned int)m_Files.size();
697 m_Files.push_back(pFile);
699 pFile->ReparseFile();
704 void Translator::RebuildLanguageDatabase(const char *lang_header_file)
706 /* Erase everything we have */
707 sm_trie_destroy(m_pLCodeLookup);
708 m_pLCodeLookup = sm_trie_create();
709 m_pStringTab->Reset();
711 for (size_t i=0; i<m_Languages.size(); i++)
713 delete m_Languages[i];
719 unsigned int line=0, col=0;
720 if ((err=g_TextParser.ParseFile_SMC(lang_header_file, this, &line, &col)) != SMCParse_Okay)
722 const char *str_err = g_TextParser.GetSMCErrorString(err);
725 str_err = m_CustomError.c_str();
728 g_Logger.LogError("[SM] Failed to parse language header file: \"%s\"", lang_header_file);
729 g_Logger.LogError("[SM] Parse error (line %d, column %d): %s", line, col, str_err);
734 if (!sm_trie_retrieve(m_pLCodeLookup, m_InitialLang, &serverLang))
736 g_Logger.LogError("Server language was set to bad language \"%s\" -- reverting to English", m_InitialLang);
738 strncopy(m_InitialLang, "en", sizeof(m_InitialLang));
739 m_ServerLang = LANGUAGE_ENGLISH;
742 m_ServerLang = reinterpret_cast<unsigned int>(serverLang);
744 if (!m_Languages.size())
746 g_Logger.LogError("[SM] Fatal error, no languages found! Translation will not work.");
749 for (size_t i=0; i<m_Files.size(); i++)
751 m_Files[i]->ReparseFile();
755 void Translator::ReadSMC_ParseStart()
757 m_InLanguageSection = false;
758 m_CustomError.clear();
761 SMCParseResult Translator::ReadSMC_NewSection(const char *name, bool opt_quotes)
763 if (!m_InLanguageSection)
765 if (strcmp(name, "Languages") == 0)
767 m_InLanguageSection = true;
771 if (!m_InLanguageSection)
773 g_Logger.LogError("[SM] Warning: Unrecognized section \"%s\" in languages.cfg", name);
776 return SMCParse_Continue;
779 SMCParseResult Translator::ReadSMC_LeavingSection()
781 m_InLanguageSection = false;
783 return SMCParse_Continue;
786 SMCParseResult Translator::ReadSMC_KeyValue(const char *key, const char *value, bool key_quotes, bool value_quotes)
788 size_t len = strlen(key);
792 g_Logger.LogError("[SM] Warning encountered parsing languages.cfg file.");
793 g_Logger.LogError("[SM] Invalid language code \"%s\" is being ignored.", key);
796 AddLanguage(key, value);
798 return SMCParse_Continue;
801 bool Translator::AddLanguage(const char *langcode, const char *description)
803 if (sm_trie_retrieve(m_pLCodeLookup, langcode, NULL))
808 Language *pLanguage = new Language;
809 unsigned int idx = m_Languages.size();
811 pLanguage->m_code2[0] = langcode[0];
812 pLanguage->m_code2[1] = langcode[1];
813 pLanguage->m_code2[2] = langcode[2];
814 pLanguage->m_FullName = m_pStringTab->AddString(description);
816 sm_trie_insert(m_pLCodeLookup, langcode, reinterpret_cast<void *>(idx));
818 m_Languages.push_back(pLanguage);
823 CPhraseFile *Translator::GetFileByIndex(unsigned int index)
825 if (index >= m_Files.size())
830 return m_Files[index];
833 size_t Translator::Translate(char *buffer, size_t maxlength, void **params, const Translation *pTrans)
835 void *new_params[MAX_TRANSLATE_PARAMS];
837 /* Rewrite the parameter order */
838 for (unsigned int i=0; i<pTrans->fmt_count; i++)
840 new_params[i] = params[pTrans->fmt_order[i]];
843 return gnprintf(buffer, maxlength, pTrans->szPhrase, new_params);
846 TransError Translator::CoreTrans(int client,
853 /* :TODO: do language stuff here */
857 return Trans_BadPhraseFile;
863 /* Using server lang temporarily until client lang stuff is implemented */
864 if ((err=g_pCorePhrases->GetTranslation(phrase, m_ServerLang, &trans)) != Trans_Okay)
869 size_t len = Translate(buffer, maxlength, params, &trans);
879 unsigned int Translator::GetServerLanguage()