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 */
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 while (*value != '\0')
232 if (state == Parse_None)
236 pPhrase->fmt_count++;
238 } else if (*value == ',') {
241 unsigned int bytes = g_TextParser.GetUTF8CharBytes(value);
242 if (bytes != 1 || !isalpha(*value))
244 ParseWarning("Invalid token '%c' in #format property on line %d.", *value, m_CurLine);
247 } else if (state == Parse_Index) {
250 state = Parse_Format;
251 if (value - old_value >= 15)
253 ParseWarning("Too many digits in format index on line %d, phrase will be ignored.", m_CurLine);
255 return SMCParse_Continue;
258 unsigned int bytes = g_TextParser.GetUTF8CharBytes(value);
259 if (bytes != 1 || !isdigit(*value))
261 ParseWarning("Token '%c' in #format property on line %d is not a digit, phrase will be ignored.",
265 return SMCParse_Continue;
268 } else if (state == Parse_Format) {
277 if (state != Parse_None)
279 /* Moose clam cow. */
280 ParseWarning("Unterminated format string on line %d, phrase will be ignored.", m_CurLine);
282 return SMCParse_Continue;
286 /* Allocate the format table */
289 pPhrase->fmt_list = m_pMemory->CreateMem(sizeof(int) * pPhrase->fmt_count, (void **)&fmt_list);
292 for (size_t i=0; i<pPhrase->fmt_count; i++)
297 /* Now we need to read again... this time into the format buffer */
298 const char *in_ptr = value;
299 const char *idx_ptr = NULL;
300 char *out_ptr = NULL;
301 unsigned int cur_idx = 0;
303 while (*in_ptr != '\0')
305 if (state == Parse_None)
312 } else if (state == Parse_Index) {
315 /* Check the number! */
318 ParseWarning("Format property contains unindexed format string on line %d, phrase will be ignored.", m_CurLine);
320 return SMCParse_Continue;
322 long idx = strtol(idx_ptr, NULL, 10);
323 if (idx < 1 || idx > (long)pPhrase->fmt_count)
325 ParseWarning("Format property contains invalid index '%d' on line %d, phrase will be ignored.", idx, m_CurLine);
327 return SMCParse_Continue;
328 } else if (fmt_list[idx - 1] != -1) {
329 ParseWarning("Format property contains duplicated index '%d' on line %d, phrase will be ignored.", idx, m_CurLine);
331 return SMCParse_Continue;
333 cur_idx = (unsigned int)idx;
334 state = Parse_Format;
336 } else if (!idx_ptr) {
339 } else if (state == Parse_Format) {
344 ParseWarning("Format property contains empty format string on line %d, phrase will be ignored.", m_CurLine);
346 return SMCParse_Continue;
350 /* Now, add this to our table */
351 fmt_list[cur_idx - 1] = m_pStringTab->AddString(fmt_buf);
352 pPhrase->fmt_bytes += strlen(fmt_buf);
359 /* Check length ... */
360 if ((unsigned)(out_ptr - fmt_buf) >= sizeof(fmt_buf) - 1)
362 ParseWarning("Format property contains format string that exceeds maximum length on line %d, phrase will be ignored.",
365 return SMCParse_Continue;
367 *out_ptr++ = *in_ptr;
373 /* If we've gotten here, we only accepted unique indexes in a range.
374 * Therefore, the list has to be completely filled. Double check anyway.
376 for (size_t i=0; i<pPhrase->fmt_count; i++)
378 if (fmt_list[i] == -1)
380 ParseWarning("Format property contains no string for index %d on line %d, phrase will be ignored.",
384 return SMCParse_Continue;
388 size_t len = strlen(key);
391 ParseWarning("Ignoring translation to invalid language \"%s\" on line %d.", key, m_CurLine);
392 return SMCParse_Continue;
396 if (!m_pTranslator->GetLanguageByCode(key, &lang))
398 /* Ignore if we don't have a language.
399 * :IDEA: issue a one-time alert?
401 return SMCParse_Continue;
404 /* See how many bytes we need for this string, then allocate.
405 * NOTE: THIS SHOULD GUARANTEE THAT WE DO NOT NEED TO NEED TO SIZE CHECK
407 len = strlen(value) + pPhrase->fmt_bytes + 1;
411 out_idx = m_pMemory->CreateMem(len, (void **)&out_buf);
414 int *fmt_list = (int *)m_pMemory->GetAddress(pPhrase->fmt_list);
415 trans_t *pTrans = (trans_t *)m_pMemory->GetAddress(pPhrase->trans_tbl);
417 pTrans = &pTrans[lang];
418 pTrans->stridx = out_idx;
420 bool params[MAX_TRANSLATE_PARAMS];
422 /* Build the format order list, if necessary */
425 pTrans->fmt_order = m_pMemory->CreateMem(pPhrase->fmt_count * sizeof(int), (void **)&fmt_order);
427 for (unsigned int i=0; i<pPhrase->fmt_count; i++)
431 memset(¶ms[0], 0, sizeof(params));
434 const char *in_ptr = value;
435 char *out_ptr = out_buf;
436 unsigned int order_idx = 0;
437 while (*in_ptr != '\0')
441 switch (*(in_ptr + 1))
456 /* Copy both bytes since we don't know what's going on */
457 *out_ptr++ = *in_ptr++;
458 *out_ptr++ = *in_ptr;
461 /* Skip past the last byte read */
463 } else if (*in_ptr == '{' && fmt_list != NULL) {
464 /* Search for parameters if this is a formatted string */
465 const char *scrap_in_point = in_ptr;
466 const char *digit_start = ++in_ptr;
468 while (*in_ptr != '\0')
470 bytes = g_TextParser.GetUTF8CharBytes(in_ptr);
477 /* Did we get an index? */
478 if (in_ptr == digit_start)
483 long idx = strtol(digit_start, NULL, 10);
484 if (idx < 1 || idx > (int)pPhrase->fmt_count)
493 /* We're safe to insert the string. First mark order. */
494 fmt_order[order_idx++] = (int)idx - 1;
495 /* Now concatenate */
496 out_ptr += sprintf(out_ptr, "%s", m_pStringTab->GetString(fmt_list[idx-1]));
498 params[idx-1] = true;
505 /* Pretend none of this ever happened. Move along now! */
506 in_ptr = scrap_in_point;
507 *out_ptr++ = *in_ptr;
509 *out_ptr++ = *in_ptr;
515 pPhrase->translations++;
518 return SMCParse_Continue;
521 SMCParseResult CPhraseFile::ReadSMC_LeavingSection()
523 if (m_ParseState == PPS_InPhrase)
525 if (m_CurPhrase == -1 && m_LastPhraseString.size())
527 sm_trie_delete(m_pPhraseLookup, m_LastPhraseString.c_str());
530 m_ParseState = PPS_Phrases;
531 m_LastPhraseString.assign("");
532 } else if (m_ParseState == PPS_Phrases) {
533 m_ParseState = PPS_None;
536 return SMCParse_Continue;
539 void CPhraseFile::ReadSMC_ParseEnd(bool halted, bool failed)
541 /* Check to see if we have any dangling phrases that weren't completed, and scrap them */
542 if ((halted || failed) && m_LastPhraseString.size())
544 sm_trie_delete(m_pPhraseLookup, m_LastPhraseString.c_str());
548 TransError CPhraseFile::GetTranslation(const char *szPhrase, unsigned int lang_id, Translation *pTrans)
550 if (lang_id >= m_LangCount)
552 return Trans_BadLanguage;
556 if (!sm_trie_retrieve(m_pPhraseLookup, szPhrase, &object))
558 return Trans_BadPhrase;
561 phrase_t *pPhrase = (phrase_t *)m_pMemory->GetAddress(reinterpret_cast<int>(object));
562 trans_t *trans = (trans_t *)m_pMemory->GetAddress(pPhrase->trans_tbl);
564 trans = &trans[lang_id];
566 if (trans->stridx == -1)
568 return Trans_BadPhraseLanguage;
571 pTrans->fmt_order = (int *)m_pMemory->GetAddress(trans->fmt_order);
572 pTrans->fmt_count = pPhrase->fmt_count;
574 pTrans->szPhrase = m_pStringTab->GetString(trans->stridx);
579 const char *CPhraseFile::GetFilename()
581 return m_File.c_str();
584 /**************************
585 ** MAIN TRANSLATOR CODE **
586 **************************/
588 Translator::Translator() : m_ServerLang(LANGUAGE_ENGLISH)
590 m_pStringTab = new BaseStringTable(2048);
591 m_pLCodeLookup = sm_trie_create();
592 strncopy(m_InitialLang, "en", sizeof(m_InitialLang));
595 Translator::~Translator()
597 for (size_t i=0; i<m_Files.size(); i++)
602 for (size_t i=0; i<m_Languages.size(); i++)
604 delete m_Languages[i];
607 sm_trie_destroy(m_pLCodeLookup);
612 ConfigResult Translator::OnSourceModConfigChanged(const char *key,
618 if (strcasecmp(key, "ServerLang") == 0)
620 if (source == ConfigSource_Console)
623 if (!GetLanguageByCode(value, &index))
625 UTIL_Format(error, maxlength, "Language code \"%s\" is not registered", value);
626 return ConfigResult_Reject;
629 m_ServerLang = index;
631 strncopy(m_InitialLang, value, sizeof(m_InitialLang));
634 return ConfigResult_Accept;
637 return ConfigResult_Ignore;
640 void Translator::OnSourceModLevelChange(const char *mapName)
642 /* Refresh language stuff */
643 char path[PLATFORM_MAX_PATH];
644 g_SourceMod.BuildPath(Path_SM, path, sizeof(path), "configs/languages.cfg");
645 RebuildLanguageDatabase(path);
648 void Translator::OnSourceModAllInitialized()
650 AddLanguage("en", "English");
651 unsigned int id = FindOrAddPhraseFile("core.cfg");
652 g_pCorePhrases = GetFileByIndex(id);
655 bool Translator::GetLanguageByCode(const char *code, unsigned int *index)
659 if (!sm_trie_retrieve(m_pLCodeLookup, code, &_index))
666 *index = reinterpret_cast<unsigned int>(_index);
672 unsigned int Translator::GetLanguageCount()
674 return (unsigned int)m_Languages.size();
677 BaseStringTable *Translator::GetStringTable()
682 unsigned int Translator::FindOrAddPhraseFile(const char *phrase_file)
684 for (size_t i=0; i<m_Files.size(); i++)
686 if (strcmp(m_Files[i]->GetFilename(), phrase_file) == 0)
688 return (unsigned int)i;
692 CPhraseFile *pFile = new CPhraseFile(this, phrase_file);
693 unsigned int idx = (unsigned int)m_Files.size();
695 m_Files.push_back(pFile);
697 pFile->ReparseFile();
702 void Translator::RebuildLanguageDatabase(const char *lang_header_file)
704 /* Erase everything we have */
705 sm_trie_destroy(m_pLCodeLookup);
706 m_pLCodeLookup = sm_trie_create();
707 m_pStringTab->Reset();
709 for (size_t i=0; i<m_Languages.size(); i++)
711 delete m_Languages[i];
717 unsigned int line=0, col=0;
718 if ((err=g_TextParser.ParseFile_SMC(lang_header_file, this, &line, &col)) != SMCParse_Okay)
720 const char *str_err = g_TextParser.GetSMCErrorString(err);
723 str_err = m_CustomError.c_str();
726 g_Logger.LogError("[SM] Failed to parse language header file: \"%s\"", lang_header_file);
727 g_Logger.LogError("[SM] Parse error (line %d, column %d): %s", line, col, str_err);
732 if (!sm_trie_retrieve(m_pLCodeLookup, m_InitialLang, &serverLang))
734 g_Logger.LogError("Server language was set to bad language \"%s\" -- reverting to English", m_InitialLang);
736 strncopy(m_InitialLang, "en", sizeof(m_InitialLang));
737 m_ServerLang = LANGUAGE_ENGLISH;
740 m_ServerLang = reinterpret_cast<unsigned int>(serverLang);
742 if (!m_Languages.size())
744 g_Logger.LogError("[SM] Fatal error, no languages found! Translation will not work.");
747 for (size_t i=0; i<m_Files.size(); i++)
749 m_Files[i]->ReparseFile();
753 void Translator::ReadSMC_ParseStart()
755 m_InLanguageSection = false;
756 m_CustomError.clear();
759 SMCParseResult Translator::ReadSMC_NewSection(const char *name, bool opt_quotes)
761 if (!m_InLanguageSection)
763 if (strcmp(name, "Languages") == 0)
765 m_InLanguageSection = true;
769 if (!m_InLanguageSection)
771 g_Logger.LogError("[SM] Warning: Unrecognized section \"%s\" in languages.cfg", name);
774 return SMCParse_Continue;
777 SMCParseResult Translator::ReadSMC_LeavingSection()
779 m_InLanguageSection = false;
781 return SMCParse_Continue;
784 SMCParseResult Translator::ReadSMC_KeyValue(const char *key, const char *value, bool key_quotes, bool value_quotes)
786 size_t len = strlen(key);
790 g_Logger.LogError("[SM] Warning encountered parsing languages.cfg file.");
791 g_Logger.LogError("[SM] Invalid language code \"%s\" is being ignored.", key);
794 AddLanguage(key, value);
796 return SMCParse_Continue;
799 bool Translator::AddLanguage(const char *langcode, const char *description)
801 if (sm_trie_retrieve(m_pLCodeLookup, langcode, NULL))
806 Language *pLanguage = new Language;
807 unsigned int idx = m_Languages.size();
809 pLanguage->m_code2[0] = langcode[0];
810 pLanguage->m_code2[1] = langcode[1];
811 pLanguage->m_code2[2] = langcode[2];
812 pLanguage->m_FullName = m_pStringTab->AddString(description);
814 sm_trie_insert(m_pLCodeLookup, langcode, reinterpret_cast<void *>(idx));
816 m_Languages.push_back(pLanguage);
821 CPhraseFile *Translator::GetFileByIndex(unsigned int index)
823 if (index >= m_Files.size())
828 return m_Files[index];
831 size_t Translator::Translate(char *buffer, size_t maxlength, void **params, const Translation *pTrans)
833 void *new_params[MAX_TRANSLATE_PARAMS];
835 /* Rewrite the parameter order */
836 for (unsigned int i=0; i<pTrans->fmt_count; i++)
838 new_params[i] = params[pTrans->fmt_order[i]];
841 return gnprintf(buffer, maxlength, pTrans->szPhrase, new_params);
844 TransError Translator::CoreTrans(int client,
851 /* :TODO: do language stuff here */
855 return Trans_BadPhraseFile;
861 /* Using server lang temporarily until client lang stuff is implemented */
862 if ((err=g_pCorePhrases->GetTranslation(phrase, m_ServerLang, &trans)) != Trans_Okay)
867 size_t len = Translate(buffer, maxlength, params, &trans);
877 unsigned int Translator::GetServerLanguage()