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;
44 unsigned int g_pCorePhraseID = 0;
55 unsigned int fmt_count;
56 unsigned int fmt_bytes;
58 unsigned int translations;
61 CPhraseFile::CPhraseFile(Translator *pTranslator, const char *file)
63 m_pStringTab = pTranslator->GetStringTable();
64 m_pMemory = m_pStringTab->GetMemTable();
65 m_LangCount = pTranslator->GetLanguageCount();
67 m_pTranslator = pTranslator;
68 m_pPhraseLookup = NULL;
71 CPhraseFile::~CPhraseFile()
75 sm_trie_destroy(m_pPhraseLookup);
79 void CPhraseFile::ParseError(const char *message, ...)
83 va_start(ap, message);
84 vsnprintf(buffer, sizeof(buffer), message, ap);
87 m_ParseError.assign(buffer);
90 void CPhraseFile::ParseWarning(const char *message, ...)
94 va_start(ap, message);
95 vsnprintf(buffer, sizeof(buffer), message, ap);
100 g_Logger.LogError("[SM] Warning(s) encountered in translation file \"%s\"", m_File.c_str());
104 g_Logger.LogError("[SM] %s", message);
107 void CPhraseFile::ReparseFile()
111 sm_trie_destroy(m_pPhraseLookup);
113 m_pPhraseLookup = sm_trie_create();
115 m_LangCount = m_pTranslator->GetLanguageCount();
123 char path[PLATFORM_MAX_PATH];
124 g_SourceMod.BuildPath(Path_SM, path, PLATFORM_MAX_PATH, "translations/%s", m_File.c_str());
126 //backwards compatibility shim
127 /* :HACKHACK: Change .cfg/.txt and vice versa for compatibility */
128 if (!g_LibSys.PathExists(path))
130 if (m_File.compare("common.cfg") == 0)
132 UTIL_ReplaceAll(path, sizeof(path), "common.cfg", "common.phrases.txt");
133 } else if (strstr(path, ".cfg")) {
134 UTIL_ReplaceAll(path, sizeof(path), ".cfg", ".txt");
135 } else if (strstr(path, ".txt")) {
136 UTIL_ReplaceAll(path, sizeof(path), ".txt", ".cfg");
142 if ((err=textparsers->ParseFile_SMC(path, this, &states)) != SMCError_Okay)
144 const char *msg = textparsers->GetSMCErrorString(err);
147 msg = m_ParseError.c_str();
150 g_Logger.LogError("[SM] Fatal error encountered parsing translation file \"%s\"", m_File.c_str());
151 g_Logger.LogError("[SM] Error (line %d, column %d): %s", states.line, states.col, msg);
155 void CPhraseFile::ReadSMC_ParseStart()
158 m_ParseState = PPS_None;
159 m_FileLogged = false;
160 m_LastPhraseString.clear();
163 SMCResult CPhraseFile::ReadSMC_NewSection(const SMCStates *states, const char *name)
165 bool recognized = false;
166 if (m_ParseState == PPS_None)
168 if (strcmp(name, "Phrases") == 0)
170 m_ParseState = PPS_Phrases;
174 else if (m_ParseState == PPS_Phrases)
176 m_ParseState = PPS_InPhrase;
180 m_CurPhrase = m_pMemory->CreateMem(sizeof(phrase_t), (void **)&pPhrase);
182 /* Create the reverse lookup */
183 if (!sm_trie_insert(m_pPhraseLookup, name, reinterpret_cast<void *>(m_CurPhrase)))
185 ParseWarning("Skipping duplicate phrase \"%s\" on line %d.", name, states->line);
186 /* :IDEA: prevent memory waste by seeking backwards in memtable? */
191 /* Initialize new phrase */
194 pPhrase->fmt_count = 0;
195 pPhrase->fmt_list = -1;
197 int trans_tbl = m_pMemory->CreateMem(sizeof(trans_t) * m_LangCount, (void **)&pTrans);
198 pPhrase = (phrase_t *)m_pMemory->GetAddress(m_CurPhrase);
199 pPhrase->trans_tbl = trans_tbl;
201 pPhrase->translations = 0;
202 pPhrase->fmt_bytes = 0;
204 for (unsigned int i=0; i<m_LangCount; i++)
206 pTrans[i].stridx = -1;
208 m_LastPhraseString.assign(name);
211 else if (m_ParseState == PPS_InPhrase)
213 ParseError("Phrase sections may not have sub-sections");
214 return SMCResult_HaltFail;
219 ParseWarning("Ignoring invalid section \"%s\" on line %d.", name, states->line);
222 return SMCResult_Continue;
225 SMCResult CPhraseFile::ReadSMC_KeyValue(const SMCStates *states, const char *key, const char *value)
227 /* See if we are ignoring a phrase */
228 if (m_CurPhrase == -1)
230 return SMCResult_Continue;
233 phrase_t *pPhrase = (phrase_t *)m_pMemory->GetAddress(m_CurPhrase);
235 if (key[0] == '#' && strcmp(key, "#format") == 0)
237 if (pPhrase->fmt_list != -1)
239 ParseWarning("Ignoring duplicated #format property on line %d", states->line);
240 return SMCResult_Continue;
243 if (pPhrase->translations > 0)
245 ParseWarning("#format property should come before translations on line %d, ignoring", states->line);
246 return SMCResult_Continue;
249 /* Do an initial browsing for error checking and what not */
257 ParseStates state = Parse_None;
259 const char *old_value = value;
260 const char *last_value = value;
261 while (*value != '\0')
263 if (state == Parse_None)
267 pPhrase->fmt_count++;
270 else if (*value == ',')
276 unsigned int bytes = textparsers->GetUTF8CharBytes(value);
277 if (bytes != 1 || !isalpha(*value))
279 ParseWarning("Invalid token '%c' in #format property on line %d.", *value, states->line);
283 else if (state == Parse_Index)
287 state = Parse_Format;
288 if (value - last_value >= 15)
290 ParseWarning("Too many digits in format index on line %d, phrase will be ignored.", states->line);
292 return SMCResult_Continue;
297 unsigned int bytes = textparsers->GetUTF8CharBytes(value);
298 if (bytes != 1 || !isdigit(*value))
300 ParseWarning("Token '%c' in #format property on line %d is not a digit, phrase will be ignored.",
304 return SMCResult_Continue;
308 else if (state == Parse_Format)
313 last_value = value + 1;
319 if (state != Parse_None)
321 /* Moose clam cow. */
322 ParseWarning("Unterminated format string on line %d, phrase will be ignored.", states->line);
324 return SMCResult_Continue;
328 /* Allocate the format table */
331 int tmp = m_pMemory->CreateMem(sizeof(int) * pPhrase->fmt_count, (void **)&fmt_list);
333 /* Update the phrase pointer in case it changed */
334 pPhrase = (phrase_t *)m_pMemory->GetAddress(m_CurPhrase);
335 pPhrase->fmt_list = tmp;
338 for (size_t i=0; i<pPhrase->fmt_count; i++)
343 /* Now we need to read again... this time into the format buffer */
344 const char *in_ptr = value;
345 const char *idx_ptr = NULL;
346 char *out_ptr = NULL;
347 unsigned int cur_idx = 0;
349 while (*in_ptr != '\0')
351 if (state == Parse_None)
359 else if (state == Parse_Index)
363 /* Check the number! */
366 ParseWarning("Format property contains unindexed format string on line %d, phrase will be ignored.", states->line);
368 return SMCResult_Continue;
370 long idx = strtol(idx_ptr, NULL, 10);
371 if (idx < 1 || idx > (long)pPhrase->fmt_count)
373 ParseWarning("Format property contains invalid index '%d' on line %d, phrase will be ignored.", idx, states->line);
375 return SMCResult_Continue;
377 else if (fmt_list[idx - 1] != -1)
379 ParseWarning("Format property contains duplicated index '%d' on line %d, phrase will be ignored.", idx, states->line);
381 return SMCResult_Continue;
383 cur_idx = (unsigned int)idx;
384 state = Parse_Format;
392 else if (state == Parse_Format)
398 ParseWarning("Format property contains empty format string on line %d, phrase will be ignored.", states->line);
400 return SMCResult_Continue;
404 /* Now, add this to our table */
405 int tmp_idx = m_pStringTab->AddString(fmt_buf);
406 /* Update pointers and update necessary variables */
407 pPhrase = (phrase_t *)m_pMemory->GetAddress(m_CurPhrase);
408 pPhrase->fmt_bytes += strlen(fmt_buf);
409 fmt_list = (int *)m_pMemory->GetAddress(pPhrase->fmt_list);
410 fmt_list[cur_idx - 1] = tmp_idx;
419 /* Check length ... */
420 if ((unsigned)(out_ptr - fmt_buf) >= sizeof(fmt_buf) - 1)
422 ParseWarning("Format property contains format string that exceeds maximum length on line %d, phrase will be ignored.",
425 return SMCResult_Continue;
427 *out_ptr++ = *in_ptr;
433 /* If we've gotten here, we only accepted unique indexes in a range.
434 * Therefore, the list has to be completely filled. Double check anyway.
436 for (size_t i=0; i<pPhrase->fmt_count; i++)
438 if (fmt_list[i] == -1)
440 ParseWarning("Format property contains no string for index %d on line %d, phrase will be ignored.",
444 return SMCResult_Continue;
450 size_t len = strlen(key);
453 ParseWarning("Ignoring translation to invalid language \"%s\" on line %d.", key, states->line);
454 return SMCResult_Continue;
458 if (!m_pTranslator->GetLanguageByCode(key, &lang))
460 /* Ignore if we don't have a language.
461 * :IDEA: issue a one-time alert?
463 return SMCResult_Continue;
466 /* See how many bytes we need for this string, then allocate.
467 * NOTE: THIS SHOULD GUARANTEE THAT WE DO NOT NEED TO NEED TO SIZE CHECK
469 len = strlen(value) + pPhrase->fmt_bytes + 1;
473 out_idx = m_pMemory->CreateMem(len, (void **)&out_buf);
476 pPhrase = (phrase_t *)m_pMemory->GetAddress(m_CurPhrase);
479 int *fmt_list = (int *)m_pMemory->GetAddress(pPhrase->fmt_list);
480 trans_t *pTrans = (trans_t *)m_pMemory->GetAddress(pPhrase->trans_tbl);
482 pTrans = &pTrans[lang];
483 pTrans->stridx = out_idx;
485 bool params[MAX_TRANSLATE_PARAMS];
487 /* Build the format order list, if necessary */
490 int tmp = m_pMemory->CreateMem(pPhrase->fmt_count * sizeof(int), (void **)&fmt_order);
492 /* Update pointers */
493 pPhrase = (phrase_t *)m_pMemory->GetAddress(m_CurPhrase);
494 pTrans = (trans_t *)m_pMemory->GetAddress(pPhrase->trans_tbl);
495 fmt_list = (int *)m_pMemory->GetAddress(pPhrase->fmt_list);
496 out_buf = (char *)m_pMemory->GetAddress(out_idx);
497 pTrans = &pTrans[lang];
499 /* Now it's safe to save the index */
500 pTrans->fmt_order = tmp;
502 for (unsigned int i=0; i<pPhrase->fmt_count; i++)
506 memset(¶ms[0], 0, sizeof(params));
509 const char *in_ptr = value;
510 char *out_ptr = out_buf;
511 unsigned int order_idx = 0;
512 while (*in_ptr != '\0')
516 switch (*(in_ptr + 1))
531 /* Copy both bytes since we don't know what's going on */
532 *out_ptr++ = *in_ptr++;
533 *out_ptr++ = *in_ptr;
536 /* Skip past the last byte read */
539 else if (*in_ptr == '{' && fmt_list != NULL)
541 /* Search for parameters if this is a formatted string */
542 const char *scrap_in_point = in_ptr;
543 const char *digit_start = ++in_ptr;
545 while (*in_ptr != '\0')
547 bytes = textparsers->GetUTF8CharBytes(in_ptr);
554 /* Did we get an index? */
555 if (in_ptr == digit_start)
560 long idx = strtol(digit_start, NULL, 10);
561 if (idx < 1 || idx > (int)pPhrase->fmt_count)
570 /* We're safe to insert the string. First mark order. */
571 fmt_order[order_idx++] = (int)idx - 1;
572 /* Now concatenate */
573 out_ptr += sprintf(out_ptr, "%s", m_pStringTab->GetString(fmt_list[idx-1]));
575 params[idx-1] = true;
582 /* Pretend none of this ever happened. Move along now! */
583 in_ptr = scrap_in_point;
584 *out_ptr++ = *in_ptr;
586 *out_ptr++ = *in_ptr;
592 pPhrase->translations++;
595 return SMCResult_Continue;
598 SMCResult CPhraseFile::ReadSMC_LeavingSection(const SMCStates *states)
600 if (m_ParseState == PPS_InPhrase)
602 if (m_CurPhrase == -1 && m_LastPhraseString.size())
604 sm_trie_delete(m_pPhraseLookup, m_LastPhraseString.c_str());
607 m_ParseState = PPS_Phrases;
608 m_LastPhraseString.assign("");
610 else if (m_ParseState == PPS_Phrases)
612 m_ParseState = PPS_None;
615 return SMCResult_Continue;
618 void CPhraseFile::ReadSMC_ParseEnd(bool halted, bool failed)
620 /* Check to see if we have any dangling phrases that weren't completed, and scrap them */
621 if ((halted || failed) && m_LastPhraseString.size())
623 sm_trie_delete(m_pPhraseLookup, m_LastPhraseString.c_str());
627 TransError CPhraseFile::GetTranslation(const char *szPhrase, unsigned int lang_id, Translation *pTrans)
629 if (lang_id >= m_LangCount)
631 return Trans_BadLanguage;
635 if (!sm_trie_retrieve(m_pPhraseLookup, szPhrase, &object))
637 return Trans_BadPhrase;
640 phrase_t *pPhrase = (phrase_t *)m_pMemory->GetAddress(reinterpret_cast<int>(object));
641 trans_t *trans = (trans_t *)m_pMemory->GetAddress(pPhrase->trans_tbl);
643 trans = &trans[lang_id];
645 if (trans->stridx == -1)
647 return Trans_BadPhraseLanguage;
650 pTrans->fmt_count = pPhrase->fmt_count;
651 pTrans->fmt_order = pTrans->fmt_count > 0 ? (int *)m_pMemory->GetAddress(trans->fmt_order) : NULL;
652 pTrans->szPhrase = m_pStringTab->GetString(trans->stridx);
657 const char *CPhraseFile::GetFilename()
659 return m_File.c_str();
662 /**************************
663 ** MAIN TRANSLATOR CODE **
664 **************************/
666 Translator::Translator() : m_ServerLang(LANGUAGE_ENGLISH)
668 m_pStringTab = new BaseStringTable(2048);
669 m_pLCodeLookup = sm_trie_create();
670 strncopy(m_InitialLang, "en", sizeof(m_InitialLang));
673 Translator::~Translator()
675 for (size_t i=0; i<m_Files.size(); i++)
680 for (size_t i=0; i<m_Languages.size(); i++)
682 delete m_Languages[i];
685 sm_trie_destroy(m_pLCodeLookup);
690 ConfigResult Translator::OnSourceModConfigChanged(const char *key,
696 if (strcasecmp(key, "ServerLang") == 0)
698 if (source == ConfigSource_Console)
701 if (!GetLanguageByCode(value, &index))
703 UTIL_Format(error, maxlength, "Language code \"%s\" is not registered", value);
704 return ConfigResult_Reject;
707 m_ServerLang = index;
709 strncopy(m_InitialLang, value, sizeof(m_InitialLang));
712 return ConfigResult_Accept;
715 return ConfigResult_Ignore;
718 void Translator::OnSourceModLevelChange(const char *mapName)
720 /* Refresh language stuff */
721 char path[PLATFORM_MAX_PATH];
722 g_SourceMod.BuildPath(Path_SM, path, sizeof(path), "configs/languages.cfg");
723 RebuildLanguageDatabase(path);
726 void Translator::OnSourceModAllInitialized()
728 AddLanguage("en", "English");
732 id = FindOrAddPhraseFile("core.phrases.txt");
733 g_pCorePhraseID = id;
734 g_pCorePhrases = GetFileByIndex(id);
737 bool Translator::GetLanguageByCode(const char *code, unsigned int *index)
741 if (!sm_trie_retrieve(m_pLCodeLookup, code, &_index))
748 *index = reinterpret_cast<unsigned int>(_index);
754 bool Translator::GetLanguageByName(const char *name, unsigned int *index)
756 CVector<Language *>::iterator iter;
759 for (iter=m_Languages.begin(); iter!=m_Languages.end(); iter++, id++)
761 if (strcasecmp(m_pStringTab->GetString((*iter)->m_FullName), name) == 0)
767 if (iter == m_Languages.end())
780 unsigned int Translator::GetLanguageCount()
782 return (unsigned int)m_Languages.size();
785 BaseStringTable *Translator::GetStringTable()
790 unsigned int Translator::FindOrAddPhraseFile(const char *phrase_file)
792 for (size_t i=0; i<m_Files.size(); i++)
794 if (strcmp(m_Files[i]->GetFilename(), phrase_file) == 0)
796 return (unsigned int)i;
800 CPhraseFile *pFile = new CPhraseFile(this, phrase_file);
801 unsigned int idx = (unsigned int)m_Files.size();
803 m_Files.push_back(pFile);
805 pFile->ReparseFile();
810 void Translator::RebuildLanguageDatabase(const char *lang_header_file)
812 /* Erase everything we have */
813 sm_trie_destroy(m_pLCodeLookup);
814 m_pLCodeLookup = sm_trie_create();
815 m_pStringTab->Reset();
817 for (size_t i=0; i<m_Languages.size(); i++)
819 delete m_Languages[i];
826 if ((err=textparsers->ParseFile_SMC(lang_header_file, this, &states)) != SMCError_Okay)
828 const char *str_err = textparsers->GetSMCErrorString(err);
831 str_err = m_CustomError.c_str();
834 g_Logger.LogError("[SM] Failed to parse language header file: \"%s\"", lang_header_file);
835 g_Logger.LogError("[SM] Parse error (line %d, column %d): %s", states.line, states.col, str_err);
840 if (!sm_trie_retrieve(m_pLCodeLookup, m_InitialLang, &serverLang))
842 g_Logger.LogError("Server language was set to bad language \"%s\" -- reverting to English", m_InitialLang);
844 strncopy(m_InitialLang, "en", sizeof(m_InitialLang));
845 m_ServerLang = LANGUAGE_ENGLISH;
848 m_ServerLang = reinterpret_cast<unsigned int>(serverLang);
850 if (!m_Languages.size())
852 g_Logger.LogError("[SM] Fatal error, no languages found! Translation will not work.");
855 for (size_t i=0; i<m_Files.size(); i++)
857 m_Files[i]->ReparseFile();
861 void Translator::ReadSMC_ParseStart()
863 m_InLanguageSection = false;
864 m_CustomError.clear();
867 SMCResult Translator::ReadSMC_NewSection(const SMCStates *states, const char *name)
869 if (!m_InLanguageSection)
871 if (strcmp(name, "Languages") == 0)
873 m_InLanguageSection = true;
877 if (!m_InLanguageSection)
879 g_Logger.LogError("[SM] Warning: Unrecognized section \"%s\" in languages.cfg", name);
882 return SMCResult_Continue;
885 SMCResult Translator::ReadSMC_LeavingSection(const SMCStates *states)
887 m_InLanguageSection = false;
889 return SMCResult_Continue;
892 SMCResult Translator::ReadSMC_KeyValue(const SMCStates *states, const char *key, const char *value)
894 size_t len = strlen(key);
898 g_Logger.LogError("[SM] Warning encountered parsing languages.cfg file.");
899 g_Logger.LogError("[SM] Invalid language code \"%s\" is being ignored.", key);
902 AddLanguage(key, value);
904 return SMCResult_Continue;
907 bool Translator::AddLanguage(const char *langcode, const char *description)
909 if (sm_trie_retrieve(m_pLCodeLookup, langcode, NULL))
914 Language *pLanguage = new Language;
915 unsigned int idx = m_Languages.size();
917 pLanguage->m_code2[0] = langcode[0];
918 pLanguage->m_code2[1] = langcode[1];
919 pLanguage->m_code2[2] = langcode[2];
920 pLanguage->m_FullName = m_pStringTab->AddString(description);
922 sm_trie_insert(m_pLCodeLookup, langcode, reinterpret_cast<void *>(idx));
924 m_Languages.push_back(pLanguage);
929 CPhraseFile *Translator::GetFileByIndex(unsigned int index)
931 if (index >= m_Files.size())
936 return m_Files[index];
939 size_t Translator::Translate(char *buffer, size_t maxlength, void **params, const Translation *pTrans)
941 void *new_params[MAX_TRANSLATE_PARAMS];
943 /* Rewrite the parameter order */
944 for (unsigned int i=0; i<pTrans->fmt_count; i++)
946 new_params[i] = params[pTrans->fmt_order[i]];
949 return gnprintf(buffer, maxlength, pTrans->szPhrase, new_params);
952 TransError Translator::CoreTrans(int client,
959 /* :TODO: do language stuff here */
963 return Trans_BadPhraseFile;
969 /* Using server lang temporarily until client lang stuff is implemented */
970 if ((err=g_pCorePhrases->GetTranslation(phrase, m_ServerLang, &trans)) != Trans_Okay)
975 size_t len = Translate(buffer, maxlength, params, &trans);
985 unsigned int Translator::GetServerLanguage()
990 unsigned int Translator::GetClientLanguage(int client)
992 CPlayer *pPlayer = g_Players.GetPlayerByIndex(client);
993 return pPlayer->GetLanguageId();
996 bool Translator::GetLanguageInfo(unsigned int number, const char **code, const char **name)
998 if (number >= GetLanguageCount())
1003 Language *l = m_Languages[number];
1010 *name = m_pStringTab->GetString(l->m_FullName);