3 * =============================================================================
5 * Copyright (C) 2004-2007 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"
42 Translator g_Translator;
43 CPhraseFile *g_pCorePhrases = NULL;
54 unsigned int fmt_count;
55 unsigned int fmt_bytes;
57 unsigned int translations;
60 CPhraseFile::CPhraseFile(Translator *pTranslator, const char *file)
62 m_pStringTab = pTranslator->GetStringTable();
63 m_pMemory = m_pStringTab->GetMemTable();
64 m_LangCount = pTranslator->GetLanguageCount();
66 m_pTranslator = pTranslator;
67 m_pPhraseLookup = NULL;
70 CPhraseFile::~CPhraseFile()
74 sm_trie_destroy(m_pPhraseLookup);
78 void CPhraseFile::ParseError(const char *message, ...)
82 va_start(ap, message);
83 vsnprintf(buffer, sizeof(buffer), message, ap);
86 m_ParseError.assign(buffer);
89 void CPhraseFile::ParseWarning(const char *message, ...)
93 va_start(ap, message);
94 vsnprintf(buffer, sizeof(buffer), message, ap);
99 g_Logger.LogError("[SM] Warning(s) encountered in translation file \"%s\"", m_File.c_str());
103 g_Logger.LogError("[SM] %s", message);
106 void CPhraseFile::ReparseFile()
110 sm_trie_destroy(m_pPhraseLookup);
112 m_pPhraseLookup = sm_trie_create();
114 m_LangCount = m_pTranslator->GetLanguageCount();
122 char path[PLATFORM_MAX_PATH];
123 g_SourceMod.BuildPath(Path_SM, path, PLATFORM_MAX_PATH, "translations/%s", m_File.c_str());
125 //backwards compatibility shim
126 /* :HACKHACK: Change .cfg/.txt and vice versa for compatibility */
127 if (!g_LibSys.PathExists(path))
129 if (m_File.compare("common.cfg") == 0)
131 UTIL_ReplaceAll(path, sizeof(path), "common.cfg", "common.phrases.txt");
132 } else if (strstr(path, ".cfg")) {
133 UTIL_ReplaceAll(path, sizeof(path), ".cfg", ".txt");
134 } else if (strstr(path, ".txt")) {
135 UTIL_ReplaceAll(path, sizeof(path), ".txt", ".cfg");
139 unsigned int line=0, col=0;
141 if ((err=textparsers->ParseFile_SMC(path, this, &line, &col)) != SMCParse_Okay)
143 const char *msg = textparsers->GetSMCErrorString(err);
146 msg = m_ParseError.c_str();
149 g_Logger.LogError("[SM] Fatal error encountered parsing translation file \"%s\"", m_File.c_str());
150 g_Logger.LogError("[SM] Error (line %d, column %d): %s", line, col, msg);
154 void CPhraseFile::ReadSMC_ParseStart()
157 m_ParseState = PPS_None;
159 m_FileLogged = false;
160 m_LastPhraseString.clear();
163 SMCParseResult CPhraseFile::ReadSMC_RawLine(const char *line, unsigned int curline)
167 return SMCParse_Continue;
170 SMCParseResult CPhraseFile::ReadSMC_NewSection(const char *name, bool opt_quotes)
172 bool recognized = false;
173 if (m_ParseState == PPS_None)
175 if (strcmp(name, "Phrases") == 0)
177 m_ParseState = PPS_Phrases;
180 } else if (m_ParseState == PPS_Phrases) {
181 m_ParseState = PPS_InPhrase;
185 m_CurPhrase = m_pMemory->CreateMem(sizeof(phrase_t), (void **)&pPhrase);
187 /* Create the reverse lookup */
188 if (!sm_trie_insert(m_pPhraseLookup, name, reinterpret_cast<void *>(m_CurPhrase)))
190 ParseWarning("Skipping duplicate phrase \"%s\" on line %d.", name, m_CurLine);
191 /* :IDEA: prevent memory waste by seeking backwards in memtable? */
194 /* Initialize new phrase */
197 pPhrase->fmt_count = 0;
198 pPhrase->fmt_list = -1;
200 int trans_tbl = m_pMemory->CreateMem(sizeof(trans_t) * m_LangCount, (void **)&pTrans);
201 pPhrase = (phrase_t *)m_pMemory->GetAddress(m_CurPhrase);
202 pPhrase->trans_tbl = trans_tbl;
204 pPhrase->translations = 0;
205 pPhrase->fmt_bytes = 0;
207 for (unsigned int i=0; i<m_LangCount; i++)
209 pTrans[i].stridx = -1;
211 m_LastPhraseString.assign(name);
213 } else if (m_ParseState == PPS_InPhrase) {
214 ParseError("Phrase sections may not have sub-sections");
215 return SMCParse_HaltFail;
220 ParseWarning("Ignoring invalid section \"%s\" on line %d.", name, m_CurLine);
223 return SMCParse_Continue;
226 SMCParseResult CPhraseFile::ReadSMC_KeyValue(const char *key, const char *value, bool key_quotes, bool value_quotes)
228 /* See if we are ignoring a phrase */
229 if (m_CurPhrase == -1)
231 return SMCParse_Continue;
234 phrase_t *pPhrase = (phrase_t *)m_pMemory->GetAddress(m_CurPhrase);
236 if (key[0] == '#' && strcmp(key, "#format") == 0)
238 if (pPhrase->fmt_list != -1)
240 ParseWarning("Ignoring duplicated #format property on line %d", m_CurLine);
241 return SMCParse_Continue;
244 if (pPhrase->translations > 0)
246 ParseWarning("#format property should come before translations on line %d, ignoring", m_CurLine);
247 return SMCParse_Continue;
250 /* Do an initial browsing for error checking and what not */
258 ParseStates state = Parse_None;
260 const char *old_value = value;
261 const char *last_value = value;
262 while (*value != '\0')
264 if (state == Parse_None)
268 pPhrase->fmt_count++;
270 } else if (*value == ',') {
273 unsigned int bytes = textparsers->GetUTF8CharBytes(value);
274 if (bytes != 1 || !isalpha(*value))
276 ParseWarning("Invalid token '%c' in #format property on line %d.", *value, m_CurLine);
279 } else if (state == Parse_Index) {
282 state = Parse_Format;
283 if (value - last_value >= 15)
285 ParseWarning("Too many digits in format index on line %d, phrase will be ignored.", m_CurLine);
287 return SMCParse_Continue;
290 unsigned int bytes = textparsers->GetUTF8CharBytes(value);
291 if (bytes != 1 || !isdigit(*value))
293 ParseWarning("Token '%c' in #format property on line %d is not a digit, phrase will be ignored.",
297 return SMCParse_Continue;
300 } else if (state == Parse_Format) {
304 last_value = value + 1;
310 if (state != Parse_None)
312 /* Moose clam cow. */
313 ParseWarning("Unterminated format string on line %d, phrase will be ignored.", m_CurLine);
315 return SMCParse_Continue;
319 /* Allocate the format table */
322 int tmp = m_pMemory->CreateMem(sizeof(int) * pPhrase->fmt_count, (void **)&fmt_list);
324 /* Update the phrase pointer in case it changed */
325 pPhrase = (phrase_t *)m_pMemory->GetAddress(m_CurPhrase);
326 pPhrase->fmt_list = tmp;
329 for (size_t i=0; i<pPhrase->fmt_count; i++)
334 /* Now we need to read again... this time into the format buffer */
335 const char *in_ptr = value;
336 const char *idx_ptr = NULL;
337 char *out_ptr = NULL;
338 unsigned int cur_idx = 0;
340 while (*in_ptr != '\0')
342 if (state == Parse_None)
349 } else if (state == Parse_Index) {
352 /* Check the number! */
355 ParseWarning("Format property contains unindexed format string on line %d, phrase will be ignored.", m_CurLine);
357 return SMCParse_Continue;
359 long idx = strtol(idx_ptr, NULL, 10);
360 if (idx < 1 || idx > (long)pPhrase->fmt_count)
362 ParseWarning("Format property contains invalid index '%d' on line %d, phrase will be ignored.", idx, m_CurLine);
364 return SMCParse_Continue;
365 } else if (fmt_list[idx - 1] != -1) {
366 ParseWarning("Format property contains duplicated index '%d' on line %d, phrase will be ignored.", idx, m_CurLine);
368 return SMCParse_Continue;
370 cur_idx = (unsigned int)idx;
371 state = Parse_Format;
373 } else if (!idx_ptr) {
376 } else if (state == Parse_Format) {
381 ParseWarning("Format property contains empty format string on line %d, phrase will be ignored.", m_CurLine);
383 return SMCParse_Continue;
387 /* Now, add this to our table */
388 int tmp_idx = m_pStringTab->AddString(fmt_buf);
389 /* Update pointers and update necessary variables */
390 pPhrase = (phrase_t *)m_pMemory->GetAddress(m_CurPhrase);
391 pPhrase->fmt_bytes += strlen(fmt_buf);
392 fmt_list = (int *)m_pMemory->GetAddress(pPhrase->fmt_list);
393 fmt_list[cur_idx - 1] = tmp_idx;
400 /* Check length ... */
401 if ((unsigned)(out_ptr - fmt_buf) >= sizeof(fmt_buf) - 1)
403 ParseWarning("Format property contains format string that exceeds maximum length on line %d, phrase will be ignored.",
406 return SMCParse_Continue;
408 *out_ptr++ = *in_ptr;
414 /* If we've gotten here, we only accepted unique indexes in a range.
415 * Therefore, the list has to be completely filled. Double check anyway.
417 for (size_t i=0; i<pPhrase->fmt_count; i++)
419 if (fmt_list[i] == -1)
421 ParseWarning("Format property contains no string for index %d on line %d, phrase will be ignored.",
425 return SMCParse_Continue;
429 size_t len = strlen(key);
432 ParseWarning("Ignoring translation to invalid language \"%s\" on line %d.", key, m_CurLine);
433 return SMCParse_Continue;
437 if (!m_pTranslator->GetLanguageByCode(key, &lang))
439 /* Ignore if we don't have a language.
440 * :IDEA: issue a one-time alert?
442 return SMCParse_Continue;
445 /* See how many bytes we need for this string, then allocate.
446 * NOTE: THIS SHOULD GUARANTEE THAT WE DO NOT NEED TO NEED TO SIZE CHECK
448 len = strlen(value) + pPhrase->fmt_bytes + 1;
452 out_idx = m_pMemory->CreateMem(len, (void **)&out_buf);
455 pPhrase = (phrase_t *)m_pMemory->GetAddress(m_CurPhrase);
458 int *fmt_list = (int *)m_pMemory->GetAddress(pPhrase->fmt_list);
459 trans_t *pTrans = (trans_t *)m_pMemory->GetAddress(pPhrase->trans_tbl);
461 pTrans = &pTrans[lang];
462 pTrans->stridx = out_idx;
464 bool params[MAX_TRANSLATE_PARAMS];
466 /* Build the format order list, if necessary */
469 int tmp = m_pMemory->CreateMem(pPhrase->fmt_count * sizeof(int), (void **)&fmt_order);
471 /* Update pointers */
472 pPhrase = (phrase_t *)m_pMemory->GetAddress(m_CurPhrase);
473 pTrans = (trans_t *)m_pMemory->GetAddress(pPhrase->trans_tbl);
474 fmt_list = (int *)m_pMemory->GetAddress(pPhrase->fmt_list);
475 pTrans = &pTrans[lang];
477 /* Now it's safe to save the index */
478 pTrans->fmt_order = tmp;
480 for (unsigned int i=0; i<pPhrase->fmt_count; i++)
484 memset(¶ms[0], 0, sizeof(params));
487 const char *in_ptr = value;
488 char *out_ptr = out_buf;
489 unsigned int order_idx = 0;
490 while (*in_ptr != '\0')
494 switch (*(in_ptr + 1))
509 /* Copy both bytes since we don't know what's going on */
510 *out_ptr++ = *in_ptr++;
511 *out_ptr++ = *in_ptr;
514 /* Skip past the last byte read */
516 } else if (*in_ptr == '{' && fmt_list != NULL) {
517 /* Search for parameters if this is a formatted string */
518 const char *scrap_in_point = in_ptr;
519 const char *digit_start = ++in_ptr;
521 while (*in_ptr != '\0')
523 bytes = textparsers->GetUTF8CharBytes(in_ptr);
530 /* Did we get an index? */
531 if (in_ptr == digit_start)
536 long idx = strtol(digit_start, NULL, 10);
537 if (idx < 1 || idx > (int)pPhrase->fmt_count)
546 /* We're safe to insert the string. First mark order. */
547 fmt_order[order_idx++] = (int)idx - 1;
548 /* Now concatenate */
549 out_ptr += sprintf(out_ptr, "%s", m_pStringTab->GetString(fmt_list[idx-1]));
551 params[idx-1] = true;
558 /* Pretend none of this ever happened. Move along now! */
559 in_ptr = scrap_in_point;
560 *out_ptr++ = *in_ptr;
562 *out_ptr++ = *in_ptr;
568 pPhrase->translations++;
571 return SMCParse_Continue;
574 SMCParseResult CPhraseFile::ReadSMC_LeavingSection()
576 if (m_ParseState == PPS_InPhrase)
578 if (m_CurPhrase == -1 && m_LastPhraseString.size())
580 sm_trie_delete(m_pPhraseLookup, m_LastPhraseString.c_str());
583 m_ParseState = PPS_Phrases;
584 m_LastPhraseString.assign("");
585 } else if (m_ParseState == PPS_Phrases) {
586 m_ParseState = PPS_None;
589 return SMCParse_Continue;
592 void CPhraseFile::ReadSMC_ParseEnd(bool halted, bool failed)
594 /* Check to see if we have any dangling phrases that weren't completed, and scrap them */
595 if ((halted || failed) && m_LastPhraseString.size())
597 sm_trie_delete(m_pPhraseLookup, m_LastPhraseString.c_str());
601 TransError CPhraseFile::GetTranslation(const char *szPhrase, unsigned int lang_id, Translation *pTrans)
603 if (lang_id >= m_LangCount)
605 return Trans_BadLanguage;
609 if (!sm_trie_retrieve(m_pPhraseLookup, szPhrase, &object))
611 return Trans_BadPhrase;
614 phrase_t *pPhrase = (phrase_t *)m_pMemory->GetAddress(reinterpret_cast<int>(object));
615 trans_t *trans = (trans_t *)m_pMemory->GetAddress(pPhrase->trans_tbl);
617 trans = &trans[lang_id];
619 if (trans->stridx == -1)
621 return Trans_BadPhraseLanguage;
624 pTrans->fmt_order = (int *)m_pMemory->GetAddress(trans->fmt_order);
625 pTrans->fmt_count = pPhrase->fmt_count;
627 pTrans->szPhrase = m_pStringTab->GetString(trans->stridx);
632 const char *CPhraseFile::GetFilename()
634 return m_File.c_str();
637 /**************************
638 ** MAIN TRANSLATOR CODE **
639 **************************/
641 Translator::Translator() : m_ServerLang(LANGUAGE_ENGLISH)
643 m_pStringTab = new BaseStringTable(2048);
644 m_pLCodeLookup = sm_trie_create();
645 strncopy(m_InitialLang, "en", sizeof(m_InitialLang));
648 Translator::~Translator()
650 for (size_t i=0; i<m_Files.size(); i++)
655 for (size_t i=0; i<m_Languages.size(); i++)
657 delete m_Languages[i];
660 sm_trie_destroy(m_pLCodeLookup);
665 ConfigResult Translator::OnSourceModConfigChanged(const char *key,
671 if (strcasecmp(key, "ServerLang") == 0)
673 if (source == ConfigSource_Console)
676 if (!GetLanguageByCode(value, &index))
678 UTIL_Format(error, maxlength, "Language code \"%s\" is not registered", value);
679 return ConfigResult_Reject;
682 m_ServerLang = index;
684 strncopy(m_InitialLang, value, sizeof(m_InitialLang));
687 return ConfigResult_Accept;
690 return ConfigResult_Ignore;
693 void Translator::OnSourceModLevelChange(const char *mapName)
695 /* Refresh language stuff */
696 char path[PLATFORM_MAX_PATH];
697 g_SourceMod.BuildPath(Path_SM, path, sizeof(path), "configs/languages.cfg");
698 RebuildLanguageDatabase(path);
701 void Translator::OnSourceModAllInitialized()
703 AddLanguage("en", "English");
707 //backwards compatibility shim
708 /* hack -- if core.cfg exists, exec it instead. */
709 char path[PLATFORM_MAX_PATH];
710 g_SourceMod.BuildPath(Path_SM, path, sizeof(path), "translations/core.cfg");
712 if (g_LibSys.PathExists(path))
714 id = FindOrAddPhraseFile("core.cfg");
716 id = FindOrAddPhraseFile("core.phrases.txt");
719 g_pCorePhrases = GetFileByIndex(id);
722 bool Translator::GetLanguageByCode(const char *code, unsigned int *index)
726 if (!sm_trie_retrieve(m_pLCodeLookup, code, &_index))
733 *index = reinterpret_cast<unsigned int>(_index);
739 bool Translator::GetLanguageByName(const char *name, unsigned int *index)
741 CVector<Language *>::iterator iter;
744 for (iter=m_Languages.begin(); iter!=m_Languages.end(); iter++, id++)
746 if (strcasecmp(m_pStringTab->GetString((*iter)->m_FullName), name) == 0)
752 if (iter == m_Languages.end())
765 unsigned int Translator::GetLanguageCount()
767 return (unsigned int)m_Languages.size();
770 BaseStringTable *Translator::GetStringTable()
775 unsigned int Translator::FindOrAddPhraseFile(const char *phrase_file)
777 for (size_t i=0; i<m_Files.size(); i++)
779 if (strcmp(m_Files[i]->GetFilename(), phrase_file) == 0)
781 return (unsigned int)i;
785 CPhraseFile *pFile = new CPhraseFile(this, phrase_file);
786 unsigned int idx = (unsigned int)m_Files.size();
788 m_Files.push_back(pFile);
790 pFile->ReparseFile();
795 void Translator::RebuildLanguageDatabase(const char *lang_header_file)
797 /* Erase everything we have */
798 sm_trie_destroy(m_pLCodeLookup);
799 m_pLCodeLookup = sm_trie_create();
800 m_pStringTab->Reset();
802 for (size_t i=0; i<m_Languages.size(); i++)
804 delete m_Languages[i];
810 unsigned int line=0, col=0;
811 if ((err=textparsers->ParseFile_SMC(lang_header_file, this, &line, &col)) != SMCParse_Okay)
813 const char *str_err = textparsers->GetSMCErrorString(err);
816 str_err = m_CustomError.c_str();
819 g_Logger.LogError("[SM] Failed to parse language header file: \"%s\"", lang_header_file);
820 g_Logger.LogError("[SM] Parse error (line %d, column %d): %s", line, col, str_err);
825 if (!sm_trie_retrieve(m_pLCodeLookup, m_InitialLang, &serverLang))
827 g_Logger.LogError("Server language was set to bad language \"%s\" -- reverting to English", m_InitialLang);
829 strncopy(m_InitialLang, "en", sizeof(m_InitialLang));
830 m_ServerLang = LANGUAGE_ENGLISH;
833 m_ServerLang = reinterpret_cast<unsigned int>(serverLang);
835 if (!m_Languages.size())
837 g_Logger.LogError("[SM] Fatal error, no languages found! Translation will not work.");
840 for (size_t i=0; i<m_Files.size(); i++)
842 m_Files[i]->ReparseFile();
846 void Translator::ReadSMC_ParseStart()
848 m_InLanguageSection = false;
849 m_CustomError.clear();
852 SMCParseResult Translator::ReadSMC_NewSection(const char *name, bool opt_quotes)
854 if (!m_InLanguageSection)
856 if (strcmp(name, "Languages") == 0)
858 m_InLanguageSection = true;
862 if (!m_InLanguageSection)
864 g_Logger.LogError("[SM] Warning: Unrecognized section \"%s\" in languages.cfg", name);
867 return SMCParse_Continue;
870 SMCParseResult Translator::ReadSMC_LeavingSection()
872 m_InLanguageSection = false;
874 return SMCParse_Continue;
877 SMCParseResult Translator::ReadSMC_KeyValue(const char *key, const char *value, bool key_quotes, bool value_quotes)
879 size_t len = strlen(key);
883 g_Logger.LogError("[SM] Warning encountered parsing languages.cfg file.");
884 g_Logger.LogError("[SM] Invalid language code \"%s\" is being ignored.", key);
887 AddLanguage(key, value);
889 return SMCParse_Continue;
892 bool Translator::AddLanguage(const char *langcode, const char *description)
894 if (sm_trie_retrieve(m_pLCodeLookup, langcode, NULL))
899 Language *pLanguage = new Language;
900 unsigned int idx = m_Languages.size();
902 pLanguage->m_code2[0] = langcode[0];
903 pLanguage->m_code2[1] = langcode[1];
904 pLanguage->m_code2[2] = langcode[2];
905 pLanguage->m_FullName = m_pStringTab->AddString(description);
907 sm_trie_insert(m_pLCodeLookup, langcode, reinterpret_cast<void *>(idx));
909 m_Languages.push_back(pLanguage);
914 CPhraseFile *Translator::GetFileByIndex(unsigned int index)
916 if (index >= m_Files.size())
921 return m_Files[index];
924 size_t Translator::Translate(char *buffer, size_t maxlength, void **params, const Translation *pTrans)
926 void *new_params[MAX_TRANSLATE_PARAMS];
928 /* Rewrite the parameter order */
929 for (unsigned int i=0; i<pTrans->fmt_count; i++)
931 new_params[i] = params[pTrans->fmt_order[i]];
934 return gnprintf(buffer, maxlength, pTrans->szPhrase, new_params);
937 TransError Translator::CoreTrans(int client,
944 /* :TODO: do language stuff here */
948 return Trans_BadPhraseFile;
954 /* Using server lang temporarily until client lang stuff is implemented */
955 if ((err=g_pCorePhrases->GetTranslation(phrase, m_ServerLang, &trans)) != Trans_Okay)
960 size_t len = Translate(buffer, maxlength, params, &trans);
970 unsigned int Translator::GetServerLanguage()
975 unsigned int Translator::GetClientLanguage(int client)
977 CPlayer *pPlayer = g_Players.GetPlayerByIndex(client);
978 return pPlayer->GetLanguageId();
981 bool Translator::GetLanguageInfo(unsigned int number, const char **code, const char **name)
983 if (number >= GetLanguageCount())
988 Language *l = m_Languages[number];
995 *name = m_pStringTab->GetString(l->m_FullName);