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());
108 /* :HACKHACK: If we're looking for a .txt, see if a .cfg also exists if our .txt does not. */
109 if (!g_LibSys.PathExists(path))
111 UTIL_ReplaceAll(path, sizeof(path), ".txt", ".cfg");
114 unsigned int line=0, col=0;
116 if ((err=g_TextParser.ParseFile_SMC(path, this, &line, &col)) != SMCParse_Okay)
118 const char *msg = g_TextParser.GetSMCErrorString(err);
121 msg = m_ParseError.c_str();
124 g_Logger.LogError("[SM] Fatal error encountered parsing translation file \"%s\"", m_File.c_str());
125 g_Logger.LogError("[SM] Error (line %d, column %d): %s", line, col, msg);
129 void CPhraseFile::ReadSMC_ParseStart()
132 m_ParseState = PPS_None;
134 m_FileLogged = false;
135 m_LastPhraseString.clear();
138 SMCParseResult CPhraseFile::ReadSMC_RawLine(const char *line, unsigned int curline)
142 return SMCParse_Continue;
145 SMCParseResult CPhraseFile::ReadSMC_NewSection(const char *name, bool opt_quotes)
147 bool recognized = false;
148 if (m_ParseState == PPS_None)
150 if (strcmp(name, "Phrases") == 0)
152 m_ParseState = PPS_Phrases;
155 } else if (m_ParseState == PPS_Phrases) {
156 m_ParseState = PPS_InPhrase;
160 m_CurPhrase = m_pMemory->CreateMem(sizeof(phrase_t), (void **)&pPhrase);
162 /* Create the reverse lookup */
163 if (!sm_trie_insert(m_pPhraseLookup, name, reinterpret_cast<void *>(m_CurPhrase)))
165 ParseWarning("Skipping duplicate phrase \"%s\" on line %d.", name, m_CurLine);
166 /* :IDEA: prevent memory waste by seeking backwards in memtable? */
169 /* Initialize new phrase */
172 pPhrase->fmt_count = 0;
173 pPhrase->fmt_list = -1;
175 int trans_tbl = m_pMemory->CreateMem(sizeof(trans_t) * m_LangCount, (void **)&pTrans);
176 /* Update the pointer! */
177 pPhrase = (phrase_t *)m_pMemory->GetAddress(m_CurPhrase);
178 pPhrase->trans_tbl = trans_tbl;
180 pPhrase->translations = 0;
181 pPhrase->fmt_bytes = 0;
183 for (unsigned int i=0; i<m_LangCount; i++)
185 pTrans[i].stridx = -1;
187 m_LastPhraseString.assign(name);
189 } else if (m_ParseState == PPS_InPhrase) {
190 ParseError("Phrase sections may not have sub-sections");
191 return SMCParse_HaltFail;
196 ParseWarning("Ignoring invalid section \"%s\" on line %d.", name, m_CurLine);
199 return SMCParse_Continue;
202 SMCParseResult CPhraseFile::ReadSMC_KeyValue(const char *key, const char *value, bool key_quotes, bool value_quotes)
204 /* See if we are ignoring a phrase */
205 if (m_CurPhrase == -1)
207 return SMCParse_Continue;
210 phrase_t *pPhrase = (phrase_t *)m_pMemory->GetAddress(m_CurPhrase);
212 if (key[0] == '#' && strcmp(key, "#format") == 0)
214 if (pPhrase->fmt_list != -1)
216 ParseWarning("Ignoring duplicated #format property on line %d", m_CurLine);
217 return SMCParse_Continue;
220 if (pPhrase->translations > 0)
222 ParseWarning("#format property should come before translations on line %d, ignoring", m_CurLine);
223 return SMCParse_Continue;
226 /* Do an initial browsing for error checking and what not */
234 ParseStates state = Parse_None;
236 const char *old_value = value;
237 const char *last_value = value;
238 while (*value != '\0')
240 if (state == Parse_None)
244 pPhrase->fmt_count++;
246 } else if (*value == ',') {
249 unsigned int bytes = g_TextParser.GetUTF8CharBytes(value);
250 if (bytes != 1 || !isalpha(*value))
252 ParseWarning("Invalid token '%c' in #format property on line %d.", *value, m_CurLine);
255 } else if (state == Parse_Index) {
258 state = Parse_Format;
259 if (value - last_value >= 15)
261 ParseWarning("Too many digits in format index on line %d, phrase will be ignored.", m_CurLine);
263 return SMCParse_Continue;
266 unsigned int bytes = g_TextParser.GetUTF8CharBytes(value);
267 if (bytes != 1 || !isdigit(*value))
269 ParseWarning("Token '%c' in #format property on line %d is not a digit, phrase will be ignored.",
273 return SMCParse_Continue;
276 } else if (state == Parse_Format) {
280 last_value = value + 1;
286 if (state != Parse_None)
288 /* Moose clam cow. */
289 ParseWarning("Unterminated format string on line %d, phrase will be ignored.", m_CurLine);
291 return SMCParse_Continue;
295 /* Allocate the format table */
298 pPhrase->fmt_list = m_pMemory->CreateMem(sizeof(int) * pPhrase->fmt_count, (void **)&fmt_list);
301 for (size_t i=0; i<pPhrase->fmt_count; i++)
306 /* Now we need to read again... this time into the format buffer */
307 const char *in_ptr = value;
308 const char *idx_ptr = NULL;
309 char *out_ptr = NULL;
310 unsigned int cur_idx = 0;
312 while (*in_ptr != '\0')
314 if (state == Parse_None)
321 } else if (state == Parse_Index) {
324 /* Check the number! */
327 ParseWarning("Format property contains unindexed format string on line %d, phrase will be ignored.", m_CurLine);
329 return SMCParse_Continue;
331 long idx = strtol(idx_ptr, NULL, 10);
332 if (idx < 1 || idx > (long)pPhrase->fmt_count)
334 ParseWarning("Format property contains invalid index '%d' on line %d, phrase will be ignored.", idx, m_CurLine);
336 return SMCParse_Continue;
337 } else if (fmt_list[idx - 1] != -1) {
338 ParseWarning("Format property contains duplicated index '%d' on line %d, phrase will be ignored.", idx, m_CurLine);
340 return SMCParse_Continue;
342 cur_idx = (unsigned int)idx;
343 state = Parse_Format;
345 } else if (!idx_ptr) {
348 } else if (state == Parse_Format) {
353 ParseWarning("Format property contains empty format string on line %d, phrase will be ignored.", m_CurLine);
355 return SMCParse_Continue;
359 /* Now, add this to our table */
360 fmt_list[cur_idx - 1] = m_pStringTab->AddString(fmt_buf);
361 pPhrase->fmt_bytes += strlen(fmt_buf);
368 /* Check length ... */
369 if ((unsigned)(out_ptr - fmt_buf) >= sizeof(fmt_buf) - 1)
371 ParseWarning("Format property contains format string that exceeds maximum length on line %d, phrase will be ignored.",
374 return SMCParse_Continue;
376 *out_ptr++ = *in_ptr;
382 /* If we've gotten here, we only accepted unique indexes in a range.
383 * Therefore, the list has to be completely filled. Double check anyway.
385 for (size_t i=0; i<pPhrase->fmt_count; i++)
387 if (fmt_list[i] == -1)
389 ParseWarning("Format property contains no string for index %d on line %d, phrase will be ignored.",
393 return SMCParse_Continue;
397 size_t len = strlen(key);
400 ParseWarning("Ignoring translation to invalid language \"%s\" on line %d.", key, m_CurLine);
401 return SMCParse_Continue;
405 if (!m_pTranslator->GetLanguageByCode(key, &lang))
407 /* Ignore if we don't have a language.
408 * :IDEA: issue a one-time alert?
410 return SMCParse_Continue;
413 /* See how many bytes we need for this string, then allocate.
414 * NOTE: THIS SHOULD GUARANTEE THAT WE DO NOT NEED TO NEED TO SIZE CHECK
416 len = strlen(value) + pPhrase->fmt_bytes + 1;
420 out_idx = m_pMemory->CreateMem(len, (void **)&out_buf);
423 int *fmt_list = (int *)m_pMemory->GetAddress(pPhrase->fmt_list);
424 trans_t *pTrans = (trans_t *)m_pMemory->GetAddress(pPhrase->trans_tbl);
426 pTrans = &pTrans[lang];
427 pTrans->stridx = out_idx;
429 bool params[MAX_TRANSLATE_PARAMS];
431 /* Build the format order list, if necessary */
434 pTrans->fmt_order = m_pMemory->CreateMem(pPhrase->fmt_count * sizeof(int), (void **)&fmt_order);
436 for (unsigned int i=0; i<pPhrase->fmt_count; i++)
440 memset(¶ms[0], 0, sizeof(params));
443 const char *in_ptr = value;
444 char *out_ptr = out_buf;
445 unsigned int order_idx = 0;
446 while (*in_ptr != '\0')
450 switch (*(in_ptr + 1))
465 /* Copy both bytes since we don't know what's going on */
466 *out_ptr++ = *in_ptr++;
467 *out_ptr++ = *in_ptr;
470 /* Skip past the last byte read */
472 } else if (*in_ptr == '{' && fmt_list != NULL) {
473 /* Search for parameters if this is a formatted string */
474 const char *scrap_in_point = in_ptr;
475 const char *digit_start = ++in_ptr;
477 while (*in_ptr != '\0')
479 bytes = g_TextParser.GetUTF8CharBytes(in_ptr);
486 /* Did we get an index? */
487 if (in_ptr == digit_start)
492 long idx = strtol(digit_start, NULL, 10);
493 if (idx < 1 || idx > (int)pPhrase->fmt_count)
502 /* We're safe to insert the string. First mark order. */
503 fmt_order[order_idx++] = (int)idx - 1;
504 /* Now concatenate */
505 out_ptr += sprintf(out_ptr, "%s", m_pStringTab->GetString(fmt_list[idx-1]));
507 params[idx-1] = true;
514 /* Pretend none of this ever happened. Move along now! */
515 in_ptr = scrap_in_point;
516 *out_ptr++ = *in_ptr;
518 *out_ptr++ = *in_ptr;
524 pPhrase->translations++;
527 return SMCParse_Continue;
530 SMCParseResult CPhraseFile::ReadSMC_LeavingSection()
532 if (m_ParseState == PPS_InPhrase)
534 if (m_CurPhrase == -1 && m_LastPhraseString.size())
536 sm_trie_delete(m_pPhraseLookup, m_LastPhraseString.c_str());
539 m_ParseState = PPS_Phrases;
540 m_LastPhraseString.assign("");
541 } else if (m_ParseState == PPS_Phrases) {
542 m_ParseState = PPS_None;
545 return SMCParse_Continue;
548 void CPhraseFile::ReadSMC_ParseEnd(bool halted, bool failed)
550 /* Check to see if we have any dangling phrases that weren't completed, and scrap them */
551 if ((halted || failed) && m_LastPhraseString.size())
553 sm_trie_delete(m_pPhraseLookup, m_LastPhraseString.c_str());
557 TransError CPhraseFile::GetTranslation(const char *szPhrase, unsigned int lang_id, Translation *pTrans)
559 if (lang_id >= m_LangCount)
561 return Trans_BadLanguage;
565 if (!sm_trie_retrieve(m_pPhraseLookup, szPhrase, &object))
567 return Trans_BadPhrase;
570 phrase_t *pPhrase = (phrase_t *)m_pMemory->GetAddress(reinterpret_cast<int>(object));
571 trans_t *trans = (trans_t *)m_pMemory->GetAddress(pPhrase->trans_tbl);
573 trans = &trans[lang_id];
575 if (trans->stridx == -1)
577 return Trans_BadPhraseLanguage;
580 pTrans->fmt_order = (int *)m_pMemory->GetAddress(trans->fmt_order);
581 pTrans->fmt_count = pPhrase->fmt_count;
583 pTrans->szPhrase = m_pStringTab->GetString(trans->stridx);
588 const char *CPhraseFile::GetFilename()
590 return m_File.c_str();
593 /**************************
594 ** MAIN TRANSLATOR CODE **
595 **************************/
597 Translator::Translator() : m_ServerLang(LANGUAGE_ENGLISH)
599 m_pStringTab = new BaseStringTable(2048);
600 m_pLCodeLookup = sm_trie_create();
601 strncopy(m_InitialLang, "en", sizeof(m_InitialLang));
604 Translator::~Translator()
606 for (size_t i=0; i<m_Files.size(); i++)
611 for (size_t i=0; i<m_Languages.size(); i++)
613 delete m_Languages[i];
616 sm_trie_destroy(m_pLCodeLookup);
621 ConfigResult Translator::OnSourceModConfigChanged(const char *key,
627 if (strcasecmp(key, "ServerLang") == 0)
629 if (source == ConfigSource_Console)
632 if (!GetLanguageByCode(value, &index))
634 UTIL_Format(error, maxlength, "Language code \"%s\" is not registered", value);
635 return ConfigResult_Reject;
638 m_ServerLang = index;
640 strncopy(m_InitialLang, value, sizeof(m_InitialLang));
643 return ConfigResult_Accept;
646 return ConfigResult_Ignore;
649 void Translator::OnSourceModLevelChange(const char *mapName)
651 /* Refresh language stuff */
652 char path[PLATFORM_MAX_PATH];
653 g_SourceMod.BuildPath(Path_SM, path, sizeof(path), "configs/languages.cfg");
654 RebuildLanguageDatabase(path);
657 void Translator::OnSourceModAllInitialized()
659 AddLanguage("en", "English");
663 /* hack -- if core.cfg exists, exec it instead. */
664 char path[PLATFORM_MAX_PATH];
665 g_SourceMod.BuildPath(Path_SM, path, sizeof(path), "translations/core.cfg");
667 if (g_LibSys.PathExists(path))
669 id = FindOrAddPhraseFile("core.cfg");
671 id = FindOrAddPhraseFile("core.phrases.txt");
674 g_pCorePhrases = GetFileByIndex(id);
677 bool Translator::GetLanguageByCode(const char *code, unsigned int *index)
681 if (!sm_trie_retrieve(m_pLCodeLookup, code, &_index))
688 *index = reinterpret_cast<unsigned int>(_index);
694 unsigned int Translator::GetLanguageCount()
696 return (unsigned int)m_Languages.size();
699 BaseStringTable *Translator::GetStringTable()
704 unsigned int Translator::FindOrAddPhraseFile(const char *phrase_file)
706 for (size_t i=0; i<m_Files.size(); i++)
708 if (strcmp(m_Files[i]->GetFilename(), phrase_file) == 0)
710 return (unsigned int)i;
714 CPhraseFile *pFile = new CPhraseFile(this, phrase_file);
715 unsigned int idx = (unsigned int)m_Files.size();
717 m_Files.push_back(pFile);
719 pFile->ReparseFile();
724 void Translator::RebuildLanguageDatabase(const char *lang_header_file)
726 /* Erase everything we have */
727 sm_trie_destroy(m_pLCodeLookup);
728 m_pLCodeLookup = sm_trie_create();
729 m_pStringTab->Reset();
731 for (size_t i=0; i<m_Languages.size(); i++)
733 delete m_Languages[i];
739 unsigned int line=0, col=0;
740 if ((err=g_TextParser.ParseFile_SMC(lang_header_file, this, &line, &col)) != SMCParse_Okay)
742 const char *str_err = g_TextParser.GetSMCErrorString(err);
745 str_err = m_CustomError.c_str();
748 g_Logger.LogError("[SM] Failed to parse language header file: \"%s\"", lang_header_file);
749 g_Logger.LogError("[SM] Parse error (line %d, column %d): %s", line, col, str_err);
754 if (!sm_trie_retrieve(m_pLCodeLookup, m_InitialLang, &serverLang))
756 g_Logger.LogError("Server language was set to bad language \"%s\" -- reverting to English", m_InitialLang);
758 strncopy(m_InitialLang, "en", sizeof(m_InitialLang));
759 m_ServerLang = LANGUAGE_ENGLISH;
762 m_ServerLang = reinterpret_cast<unsigned int>(serverLang);
764 if (!m_Languages.size())
766 g_Logger.LogError("[SM] Fatal error, no languages found! Translation will not work.");
769 for (size_t i=0; i<m_Files.size(); i++)
771 m_Files[i]->ReparseFile();
775 void Translator::ReadSMC_ParseStart()
777 m_InLanguageSection = false;
778 m_CustomError.clear();
781 SMCParseResult Translator::ReadSMC_NewSection(const char *name, bool opt_quotes)
783 if (!m_InLanguageSection)
785 if (strcmp(name, "Languages") == 0)
787 m_InLanguageSection = true;
791 if (!m_InLanguageSection)
793 g_Logger.LogError("[SM] Warning: Unrecognized section \"%s\" in languages.cfg", name);
796 return SMCParse_Continue;
799 SMCParseResult Translator::ReadSMC_LeavingSection()
801 m_InLanguageSection = false;
803 return SMCParse_Continue;
806 SMCParseResult Translator::ReadSMC_KeyValue(const char *key, const char *value, bool key_quotes, bool value_quotes)
808 size_t len = strlen(key);
812 g_Logger.LogError("[SM] Warning encountered parsing languages.cfg file.");
813 g_Logger.LogError("[SM] Invalid language code \"%s\" is being ignored.", key);
816 AddLanguage(key, value);
818 return SMCParse_Continue;
821 bool Translator::AddLanguage(const char *langcode, const char *description)
823 if (sm_trie_retrieve(m_pLCodeLookup, langcode, NULL))
828 Language *pLanguage = new Language;
829 unsigned int idx = m_Languages.size();
831 pLanguage->m_code2[0] = langcode[0];
832 pLanguage->m_code2[1] = langcode[1];
833 pLanguage->m_code2[2] = langcode[2];
834 pLanguage->m_FullName = m_pStringTab->AddString(description);
836 sm_trie_insert(m_pLCodeLookup, langcode, reinterpret_cast<void *>(idx));
838 m_Languages.push_back(pLanguage);
843 CPhraseFile *Translator::GetFileByIndex(unsigned int index)
845 if (index >= m_Files.size())
850 return m_Files[index];
853 size_t Translator::Translate(char *buffer, size_t maxlength, void **params, const Translation *pTrans)
855 void *new_params[MAX_TRANSLATE_PARAMS];
857 /* Rewrite the parameter order */
858 for (unsigned int i=0; i<pTrans->fmt_count; i++)
860 new_params[i] = params[pTrans->fmt_order[i]];
863 return gnprintf(buffer, maxlength, pTrans->szPhrase, new_params);
866 TransError Translator::CoreTrans(int client,
873 /* :TODO: do language stuff here */
877 return Trans_BadPhraseFile;
883 /* Using server lang temporarily until client lang stuff is implemented */
884 if ((err=g_pCorePhrases->GetTranslation(phrase, m_ServerLang, &trans)) != Trans_Okay)
889 size_t len = Translate(buffer, maxlength, params, &trans);
899 unsigned int Translator::GetServerLanguage()