3 * =============================================================================
5 * Copyright (C) 2004-2008 AlliedModders LLC. All rights reserved.
6 * =============================================================================
8 * This program is free software; you can redistribute it and/or modify it under
9 * the terms of the GNU General Public License, version 3.0, as published by the
10 * Free Software Foundation.
12 * This program is distributed in the hope that it will be useful, but WITHOUT
13 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
14 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
17 * You should have received a copy of the GNU General Public License along with
18 * this program. If not, see <http://www.gnu.org/licenses/>.
20 * As a special exception, AlliedModders LLC gives you permission to link the
21 * code of this program (as well as its derivative works) to "Half-Life 2," the
22 * "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software
23 * by the Valve Corporation. You must obey the GNU General Public License in
24 * all respects for all other code used. Additionally, AlliedModders LLC grants
25 * this exception to all derivative works. AlliedModders LLC defines further
26 * exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007),
27 * or <http://www.sourcemod.net/license.php>.
35 #include "Translator.h"
37 #include "LibrarySys.h"
38 #include "sm_stringutil.h"
39 #include "sourcemod.h"
40 #include "PlayerManager.h"
41 #include "PhraseCollection.h"
44 Translator g_Translator;
45 IPhraseCollection *g_pCorePhrases = NULL;
46 unsigned int g_pCorePhraseID = 0;
57 unsigned int fmt_count;
58 unsigned int fmt_bytes;
60 unsigned int translations;
63 CPhraseFile::CPhraseFile(Translator *pTranslator, const char *file)
65 m_pStringTab = pTranslator->GetStringTable();
66 m_pMemory = m_pStringTab->GetMemTable();
67 m_LangCount = pTranslator->GetLanguageCount();
69 m_pTranslator = pTranslator;
70 m_pPhraseLookup = NULL;
73 CPhraseFile::~CPhraseFile()
77 sm_trie_destroy(m_pPhraseLookup);
81 void CPhraseFile::ParseError(const char *message, ...)
85 va_start(ap, message);
86 vsnprintf(buffer, sizeof(buffer), message, ap);
89 m_ParseError.assign(buffer);
92 void CPhraseFile::ParseWarning(const char *message, ...)
96 va_start(ap, message);
97 vsnprintf(buffer, sizeof(buffer), message, ap);
102 g_Logger.LogError("[SM] Warning(s) encountered in translation file \"%s\"", m_File.c_str());
106 g_Logger.LogError("[SM] %s", message);
109 void CPhraseFile::ReparseFile()
113 sm_trie_destroy(m_pPhraseLookup);
115 m_pPhraseLookup = sm_trie_create();
117 m_LangCount = m_pTranslator->GetLanguageCount();
125 char path[PLATFORM_MAX_PATH];
126 g_SourceMod.BuildPath(Path_SM, path, PLATFORM_MAX_PATH, "translations/%s", m_File.c_str());
128 //backwards compatibility shim
129 /* :HACKHACK: Change .cfg/.txt and vice versa for compatibility */
130 if (!g_LibSys.PathExists(path))
132 if (m_File.compare("common.cfg") == 0)
134 UTIL_ReplaceAll(path, sizeof(path), "common.cfg", "common.phrases.txt");
135 } else if (strstr(path, ".cfg")) {
136 UTIL_ReplaceAll(path, sizeof(path), ".cfg", ".txt");
137 } else if (strstr(path, ".txt")) {
138 UTIL_ReplaceAll(path, sizeof(path), ".txt", ".cfg");
144 if ((err=textparsers->ParseFile_SMC(path, this, &states)) != SMCError_Okay)
146 const char *msg = textparsers->GetSMCErrorString(err);
149 msg = m_ParseError.c_str();
152 g_Logger.LogError("[SM] Fatal error encountered parsing translation file \"%s\"", m_File.c_str());
153 g_Logger.LogError("[SM] Error (line %d, column %d): %s", states.line, states.col, msg);
157 void CPhraseFile::ReadSMC_ParseStart()
160 m_ParseState = PPS_None;
161 m_FileLogged = false;
162 m_LastPhraseString.clear();
165 SMCResult CPhraseFile::ReadSMC_NewSection(const SMCStates *states, const char *name)
167 bool recognized = false;
168 if (m_ParseState == PPS_None)
170 if (strcmp(name, "Phrases") == 0)
172 m_ParseState = PPS_Phrases;
176 else if (m_ParseState == PPS_Phrases)
178 m_ParseState = PPS_InPhrase;
182 m_CurPhrase = m_pMemory->CreateMem(sizeof(phrase_t), (void **)&pPhrase);
184 /* Create the reverse lookup */
185 if (!sm_trie_insert(m_pPhraseLookup, name, reinterpret_cast<void *>(m_CurPhrase)))
187 ParseWarning("Skipping duplicate phrase \"%s\" on line %d.", name, states->line);
188 /* :IDEA: prevent memory waste by seeking backwards in memtable? */
193 /* Initialize new phrase */
196 pPhrase->fmt_count = 0;
197 pPhrase->fmt_list = -1;
199 int trans_tbl = m_pMemory->CreateMem(sizeof(trans_t) * m_LangCount, (void **)&pTrans);
200 pPhrase = (phrase_t *)m_pMemory->GetAddress(m_CurPhrase);
201 pPhrase->trans_tbl = trans_tbl;
203 pPhrase->translations = 0;
204 pPhrase->fmt_bytes = 0;
206 for (unsigned int i=0; i<m_LangCount; i++)
208 pTrans[i].stridx = -1;
210 m_LastPhraseString.assign(name);
213 else if (m_ParseState == PPS_InPhrase)
215 ParseError("Phrase sections may not have sub-sections");
216 return SMCResult_HaltFail;
221 ParseWarning("Ignoring invalid section \"%s\" on line %d.", name, states->line);
224 return SMCResult_Continue;
227 SMCResult CPhraseFile::ReadSMC_KeyValue(const SMCStates *states, const char *key, const char *value)
229 /* See if we are ignoring a phrase */
230 if (m_CurPhrase == -1)
232 return SMCResult_Continue;
235 phrase_t *pPhrase = (phrase_t *)m_pMemory->GetAddress(m_CurPhrase);
237 if (key[0] == '#' && strcmp(key, "#format") == 0)
239 if (pPhrase->fmt_list != -1)
241 ParseWarning("Ignoring duplicated #format property on line %d", states->line);
242 return SMCResult_Continue;
245 if (pPhrase->translations > 0)
247 ParseWarning("#format property should come before translations on line %d, ignoring", states->line);
248 return SMCResult_Continue;
251 /* Do an initial browsing for error checking and what not */
259 ParseStates state = Parse_None;
261 const char *old_value = value;
262 const char *last_value = value;
263 while (*value != '\0')
265 if (state == Parse_None)
269 pPhrase->fmt_count++;
272 else if (*value == ',')
278 unsigned int bytes = textparsers->GetUTF8CharBytes(value);
279 if (bytes != 1 || !isalpha(*value))
281 ParseWarning("Invalid token '%c' in #format property on line %d.", *value, states->line);
285 else if (state == Parse_Index)
289 state = Parse_Format;
290 if (value - last_value >= 15)
292 ParseWarning("Too many digits in format index on line %d, phrase will be ignored.", states->line);
294 return SMCResult_Continue;
299 unsigned int bytes = textparsers->GetUTF8CharBytes(value);
300 if (bytes != 1 || !isdigit(*value))
302 ParseWarning("Token '%c' in #format property on line %d is not a digit, phrase will be ignored.",
306 return SMCResult_Continue;
310 else if (state == Parse_Format)
315 last_value = value + 1;
321 if (state != Parse_None)
323 /* Moose clam cow. */
324 ParseWarning("Unterminated format string on line %d, phrase will be ignored.", states->line);
326 return SMCResult_Continue;
330 /* Allocate the format table */
333 int tmp = m_pMemory->CreateMem(sizeof(int) * pPhrase->fmt_count, (void **)&fmt_list);
335 /* Update the phrase pointer in case it changed */
336 pPhrase = (phrase_t *)m_pMemory->GetAddress(m_CurPhrase);
337 pPhrase->fmt_list = tmp;
340 for (size_t i=0; i<pPhrase->fmt_count; i++)
345 /* Now we need to read again... this time into the format buffer */
346 const char *in_ptr = value;
347 const char *idx_ptr = NULL;
348 char *out_ptr = NULL;
349 unsigned int cur_idx = 0;
351 while (*in_ptr != '\0')
353 if (state == Parse_None)
361 else if (state == Parse_Index)
365 /* Check the number! */
368 ParseWarning("Format property contains unindexed format string on line %d, phrase will be ignored.", states->line);
370 return SMCResult_Continue;
372 long idx = strtol(idx_ptr, NULL, 10);
373 if (idx < 1 || idx > (long)pPhrase->fmt_count)
375 ParseWarning("Format property contains invalid index '%d' on line %d, phrase will be ignored.", idx, states->line);
377 return SMCResult_Continue;
379 else if (fmt_list[idx - 1] != -1)
381 ParseWarning("Format property contains duplicated index '%d' on line %d, phrase will be ignored.", idx, states->line);
383 return SMCResult_Continue;
385 cur_idx = (unsigned int)idx;
386 state = Parse_Format;
394 else if (state == Parse_Format)
400 ParseWarning("Format property contains empty format string on line %d, phrase will be ignored.", states->line);
402 return SMCResult_Continue;
406 /* Now, add this to our table */
407 int tmp_idx = m_pStringTab->AddString(fmt_buf);
408 /* Update pointers and update necessary variables */
409 pPhrase = (phrase_t *)m_pMemory->GetAddress(m_CurPhrase);
410 pPhrase->fmt_bytes += strlen(fmt_buf);
411 fmt_list = (int *)m_pMemory->GetAddress(pPhrase->fmt_list);
412 fmt_list[cur_idx - 1] = tmp_idx;
421 /* Check length ... */
422 if ((unsigned)(out_ptr - fmt_buf) >= sizeof(fmt_buf) - 1)
424 ParseWarning("Format property contains format string that exceeds maximum length on line %d, phrase will be ignored.",
427 return SMCResult_Continue;
429 *out_ptr++ = *in_ptr;
435 /* If we've gotten here, we only accepted unique indexes in a range.
436 * Therefore, the list has to be completely filled. Double check anyway.
438 for (size_t i=0; i<pPhrase->fmt_count; i++)
440 if (fmt_list[i] == -1)
442 ParseWarning("Format property contains no string for index %d on line %d, phrase will be ignored.",
446 return SMCResult_Continue;
452 size_t len = strlen(key);
455 ParseWarning("Ignoring translation to invalid language \"%s\" on line %d.", key, states->line);
456 return SMCResult_Continue;
460 if (!m_pTranslator->GetLanguageByCode(key, &lang))
462 /* Ignore if we don't have a language.
463 * :IDEA: issue a one-time alert?
465 return SMCResult_Continue;
468 /* See how many bytes we need for this string, then allocate.
469 * NOTE: THIS SHOULD GUARANTEE THAT WE DO NOT NEED TO NEED TO SIZE CHECK
471 len = strlen(value) + pPhrase->fmt_bytes + 1;
475 out_idx = m_pMemory->CreateMem(len, (void **)&out_buf);
478 pPhrase = (phrase_t *)m_pMemory->GetAddress(m_CurPhrase);
481 int *fmt_list = (int *)m_pMemory->GetAddress(pPhrase->fmt_list);
482 trans_t *pTrans = (trans_t *)m_pMemory->GetAddress(pPhrase->trans_tbl);
484 pTrans = &pTrans[lang];
485 pTrans->stridx = out_idx;
487 bool params[MAX_TRANSLATE_PARAMS];
489 /* Build the format order list, if necessary */
492 int tmp = m_pMemory->CreateMem(pPhrase->fmt_count * sizeof(int), (void **)&fmt_order);
494 /* Update pointers */
495 pPhrase = (phrase_t *)m_pMemory->GetAddress(m_CurPhrase);
496 pTrans = (trans_t *)m_pMemory->GetAddress(pPhrase->trans_tbl);
497 fmt_list = (int *)m_pMemory->GetAddress(pPhrase->fmt_list);
498 out_buf = (char *)m_pMemory->GetAddress(out_idx);
499 pTrans = &pTrans[lang];
501 /* Now it's safe to save the index */
502 pTrans->fmt_order = tmp;
504 for (unsigned int i=0; i<pPhrase->fmt_count; i++)
508 memset(¶ms[0], 0, sizeof(params));
511 const char *in_ptr = value;
512 char *out_ptr = out_buf;
513 unsigned int order_idx = 0;
514 while (*in_ptr != '\0')
518 switch (*(in_ptr + 1))
533 /* Copy both bytes since we don't know what's going on */
534 *out_ptr++ = *in_ptr++;
535 *out_ptr++ = *in_ptr;
538 /* Skip past the last byte read */
541 else if (*in_ptr == '{' && fmt_list != NULL)
543 /* Search for parameters if this is a formatted string */
544 const char *scrap_in_point = in_ptr;
545 const char *digit_start = ++in_ptr;
547 while (*in_ptr != '\0')
549 bytes = textparsers->GetUTF8CharBytes(in_ptr);
556 /* Did we get an index? */
557 if (in_ptr == digit_start)
562 long idx = strtol(digit_start, NULL, 10);
563 if (idx < 1 || idx > (int)pPhrase->fmt_count)
572 /* We're safe to insert the string. First mark order. */
573 fmt_order[order_idx++] = (int)idx - 1;
574 /* Now concatenate */
575 out_ptr += sprintf(out_ptr, "%s", m_pStringTab->GetString(fmt_list[idx-1]));
577 params[idx-1] = true;
584 /* Pretend none of this ever happened. Move along now! */
585 in_ptr = scrap_in_point;
586 *out_ptr++ = *in_ptr;
588 *out_ptr++ = *in_ptr;
594 pPhrase->translations++;
597 return SMCResult_Continue;
600 SMCResult CPhraseFile::ReadSMC_LeavingSection(const SMCStates *states)
602 if (m_ParseState == PPS_InPhrase)
604 if (m_CurPhrase == -1 && m_LastPhraseString.size())
606 sm_trie_delete(m_pPhraseLookup, m_LastPhraseString.c_str());
609 m_ParseState = PPS_Phrases;
610 m_LastPhraseString.assign("");
612 else if (m_ParseState == PPS_Phrases)
614 m_ParseState = PPS_None;
617 return SMCResult_Continue;
620 void CPhraseFile::ReadSMC_ParseEnd(bool halted, bool failed)
622 /* Check to see if we have any dangling phrases that weren't completed, and scrap them */
623 if ((halted || failed) && m_LastPhraseString.size())
625 sm_trie_delete(m_pPhraseLookup, m_LastPhraseString.c_str());
629 TransError CPhraseFile::GetTranslation(const char *szPhrase, unsigned int lang_id, Translation *pTrans)
631 if (lang_id >= m_LangCount)
633 return Trans_BadLanguage;
637 if (!sm_trie_retrieve(m_pPhraseLookup, szPhrase, &object))
639 return Trans_BadPhrase;
642 phrase_t *pPhrase = (phrase_t *)m_pMemory->GetAddress(reinterpret_cast<int>(object));
643 trans_t *trans = (trans_t *)m_pMemory->GetAddress(pPhrase->trans_tbl);
645 trans = &trans[lang_id];
647 if (trans->stridx == -1)
649 return Trans_BadPhraseLanguage;
652 pTrans->fmt_count = pPhrase->fmt_count;
653 pTrans->fmt_order = pTrans->fmt_count > 0 ? (int *)m_pMemory->GetAddress(trans->fmt_order) : NULL;
654 pTrans->szPhrase = m_pStringTab->GetString(trans->stridx);
659 const char *CPhraseFile::GetFilename()
661 return m_File.c_str();
664 /**************************
665 ** MAIN TRANSLATOR CODE **
666 **************************/
668 Translator::Translator() : m_ServerLang(SOURCEMOD_LANGUAGE_ENGLISH)
670 m_pStringTab = new BaseStringTable(2048);
671 m_pLCodeLookup = sm_trie_create();
672 strncopy(m_InitialLang, "en", sizeof(m_InitialLang));
675 Translator::~Translator()
677 for (size_t i=0; i<m_Files.size(); i++)
682 for (size_t i=0; i<m_Languages.size(); i++)
684 delete m_Languages[i];
687 sm_trie_destroy(m_pLCodeLookup);
692 ConfigResult Translator::OnSourceModConfigChanged(const char *key,
698 if (strcasecmp(key, "ServerLang") == 0)
700 if (source == ConfigSource_Console)
703 if (!GetLanguageByCode(value, &index))
705 UTIL_Format(error, maxlength, "Language code \"%s\" is not registered", value);
706 return ConfigResult_Reject;
709 m_ServerLang = index;
711 strncopy(m_InitialLang, value, sizeof(m_InitialLang));
714 return ConfigResult_Accept;
717 return ConfigResult_Ignore;
720 void Translator::OnSourceModLevelChange(const char *mapName)
722 /* Refresh language stuff */
723 char path[PLATFORM_MAX_PATH];
724 g_SourceMod.BuildPath(Path_SM, path, sizeof(path), "configs/languages.cfg");
725 RebuildLanguageDatabase(path);
728 void Translator::OnSourceModAllInitialized()
730 AddLanguage("en", "English");
732 g_pCorePhrases = CreatePhraseCollection();
733 g_pCorePhrases->AddPhraseFile("core.phrases");
735 g_ShareSys.AddInterface(NULL, this);
738 void Translator::OnSourceModShutdown()
740 g_pCorePhrases->Destroy();
743 bool Translator::GetLanguageByCode(const char *code, unsigned int *index)
747 if (!sm_trie_retrieve(m_pLCodeLookup, code, &_index))
754 *index = reinterpret_cast<unsigned int>(_index);
760 bool Translator::GetLanguageByName(const char *name, unsigned int *index)
762 CVector<Language *>::iterator iter;
765 for (iter=m_Languages.begin(); iter!=m_Languages.end(); iter++, id++)
767 if (strcasecmp(m_pStringTab->GetString((*iter)->m_FullName), name) == 0)
773 if (iter == m_Languages.end())
786 unsigned int Translator::GetLanguageCount()
788 return (unsigned int)m_Languages.size();
791 BaseStringTable *Translator::GetStringTable()
796 unsigned int Translator::FindOrAddPhraseFile(const char *phrase_file)
798 for (size_t i=0; i<m_Files.size(); i++)
800 if (strcmp(m_Files[i]->GetFilename(), phrase_file) == 0)
802 return (unsigned int)i;
806 CPhraseFile *pFile = new CPhraseFile(this, phrase_file);
807 unsigned int idx = (unsigned int)m_Files.size();
809 m_Files.push_back(pFile);
811 pFile->ReparseFile();
816 void Translator::RebuildLanguageDatabase(const char *lang_header_file)
818 /* Erase everything we have */
819 sm_trie_destroy(m_pLCodeLookup);
820 m_pLCodeLookup = sm_trie_create();
821 m_pStringTab->Reset();
823 for (size_t i=0; i<m_Languages.size(); i++)
825 delete m_Languages[i];
832 if ((err=textparsers->ParseFile_SMC(lang_header_file, this, &states)) != SMCError_Okay)
834 const char *str_err = textparsers->GetSMCErrorString(err);
837 str_err = m_CustomError.c_str();
840 g_Logger.LogError("[SM] Failed to parse language header file: \"%s\"", lang_header_file);
841 g_Logger.LogError("[SM] Parse error (line %d, column %d): %s", states.line, states.col, str_err);
846 if (!sm_trie_retrieve(m_pLCodeLookup, m_InitialLang, &serverLang))
848 g_Logger.LogError("Server language was set to bad language \"%s\" -- reverting to English", m_InitialLang);
850 strncopy(m_InitialLang, "en", sizeof(m_InitialLang));
851 m_ServerLang = SOURCEMOD_LANGUAGE_ENGLISH;
854 m_ServerLang = reinterpret_cast<unsigned int>(serverLang);
856 if (!m_Languages.size())
858 g_Logger.LogError("[SM] Fatal error, no languages found! Translation will not work.");
861 for (size_t i=0; i<m_Files.size(); i++)
863 m_Files[i]->ReparseFile();
867 void Translator::ReadSMC_ParseStart()
869 m_InLanguageSection = false;
870 m_CustomError.clear();
873 SMCResult Translator::ReadSMC_NewSection(const SMCStates *states, const char *name)
875 if (!m_InLanguageSection)
877 if (strcmp(name, "Languages") == 0)
879 m_InLanguageSection = true;
883 if (!m_InLanguageSection)
885 g_Logger.LogError("[SM] Warning: Unrecognized section \"%s\" in languages.cfg", name);
888 return SMCResult_Continue;
891 SMCResult Translator::ReadSMC_LeavingSection(const SMCStates *states)
893 m_InLanguageSection = false;
895 return SMCResult_Continue;
898 SMCResult Translator::ReadSMC_KeyValue(const SMCStates *states, const char *key, const char *value)
900 size_t len = strlen(key);
904 g_Logger.LogError("[SM] Warning encountered parsing languages.cfg file.");
905 g_Logger.LogError("[SM] Invalid language code \"%s\" is being ignored.", key);
908 AddLanguage(key, value);
910 return SMCResult_Continue;
913 bool Translator::AddLanguage(const char *langcode, const char *description)
915 if (sm_trie_retrieve(m_pLCodeLookup, langcode, NULL))
920 Language *pLanguage = new Language;
921 unsigned int idx = m_Languages.size();
923 pLanguage->m_code2[0] = langcode[0];
924 pLanguage->m_code2[1] = langcode[1];
925 pLanguage->m_code2[2] = langcode[2];
926 pLanguage->m_FullName = m_pStringTab->AddString(description);
928 sm_trie_insert(m_pLCodeLookup, langcode, reinterpret_cast<void *>(idx));
930 m_Languages.push_back(pLanguage);
935 CPhraseFile *Translator::GetFileByIndex(unsigned int index)
937 if (index >= m_Files.size())
942 return m_Files[index];
945 unsigned int Translator::GetServerLanguage()
950 unsigned int Translator::GetClientLanguage(int client)
952 CPlayer *pPlayer = g_Players.GetPlayerByIndex(client);
953 return pPlayer->GetLanguageId();
956 bool Translator::GetLanguageInfo(unsigned int number, const char **code, const char **name)
958 if (number >= GetLanguageCount())
963 Language *l = m_Languages[number];
970 *name = m_pStringTab->GetString(l->m_FullName);
976 const char *Translator::GetInterfaceName()
978 return SMINTERFACE_TRANSLATOR_NAME;
981 unsigned int Translator::GetInterfaceVersion()
983 return SMINTERFACE_TRANSLATOR_VERSION;
986 IPhraseCollection *Translator::CreatePhraseCollection()
988 return new CPhraseCollection();
991 int Translator::SetGlobalTarget(int index)
993 return g_SourceMod.SetGlobalTarget(index);
996 int Translator::GetGlobalTarget() const
998 return g_SourceMod.GetGlobalTarget();
1001 bool CoreTranslate(char *buffer,
1004 unsigned int numparams,
1010 const char *fail_phrase;
1011 void *params[MAX_TRANSLATE_PARAMS];
1013 if (numparams > MAX_TRANSLATE_PARAMS)
1019 va_start(ap, pOutLength);
1020 for (i = 0; i < numparams; i++)
1022 params[i] = va_arg(ap, void *);
1026 if (!g_pCorePhrases->FormatString(buffer,
1034 if (fail_phrase != NULL)
1036 g_Logger.LogError("[SM] Could not find core phrase: %s", fail_phrase);
1040 g_Logger.LogError("[SM] Unknown fatal error while translating a core phrase.");
1049 bool Translator::FormatString(char *buffer,
1052 IPhraseCollection *pPhrases,
1054 unsigned int numparams,
1056 const char **pFailPhrase)
1061 if (!gnprintf(buffer, maxlength, format, pPhrases, params, numparams, arg, pOutLength, pFailPhrase))
1066 if (arg != numparams)
1068 if (pFailPhrase != NULL)
1070 *pFailPhrase = NULL;