2 * vim: set ts=4 sw=4 tw=99 noet:
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>.
32 #include "common_logic.h"
36 #include <sm_platform.h>
37 #include "Translator.h"
38 #include <IPlayerHelpers.h>
39 #include <ISourceMod.h>
40 #include <ILibrarySys.h>
41 #include "PhraseCollection.h"
42 #include "stringutil.h"
44 Translator g_Translator;
45 IPhraseCollection *g_pCorePhrases = NULL;
46 unsigned int g_pCorePhraseID = 0;
48 using namespace SourceMod;
59 unsigned int fmt_count;
60 unsigned int fmt_bytes;
62 unsigned int translations;
65 CPhraseFile::CPhraseFile(Translator *pTranslator, const char *file)
67 m_pStringTab = pTranslator->GetStringTable();
68 m_pMemory = m_pStringTab->GetMemTable();
69 m_LangCount = pTranslator->GetLanguageCount();
71 m_pTranslator = pTranslator;
74 CPhraseFile::~CPhraseFile()
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 smcore.LogError("[SM] Warning(s) encountered in translation file \"%s\"", m_File.c_str());
103 smcore.LogError("[SM] %s", buffer);
106 void CPhraseFile::ReparseFile()
108 m_PhraseLookup.clear();
110 m_LangCount = m_pTranslator->GetLanguageCount();
118 char path[PLATFORM_MAX_PATH];
119 g_pSM->BuildPath(Path_SM, path, PLATFORM_MAX_PATH, "translations/%s", m_File.c_str());
121 //backwards compatibility shim
122 /* :HACKHACK: Change .cfg/.txt and vice versa for compatibility */
123 if (!libsys->PathExists(path))
125 if (m_File.compare("common.cfg") == 0)
127 UTIL_ReplaceAll(path, sizeof(path), "common.cfg", "common.phrases.txt", true);
128 } else if (strstr(path, ".cfg")) {
129 UTIL_ReplaceAll(path, sizeof(path), ".cfg", ".txt", true);
130 } else if (strstr(path, ".txt")) {
131 UTIL_ReplaceAll(path, sizeof(path), ".txt", ".cfg", true);
137 if ((err=textparsers->ParseFile_SMC(path, this, &states)) != SMCError_Okay)
139 const char *msg = textparsers->GetSMCErrorString(err);
142 msg = m_ParseError.c_str();
145 smcore.LogError("[SM] Fatal error encountered parsing translation file \"%s\"", m_File.c_str());
146 smcore.LogError("[SM] Error (line %d, column %d): %s", states.line, states.col, msg);
150 for (unsigned int i = 1; i < m_LangCount; i++)
152 if (!m_pTranslator->GetLanguageInfo(i, &code, NULL))
157 g_pSM->BuildPath(Path_SM,
160 "translations/%s/%s",
164 /* Speculatively load these. */
165 if (!libsys->PathExists(path))
170 if ((err=textparsers->ParseFile_SMC(path, this, &states)) != SMCError_Okay)
172 const char *msg = textparsers->GetSMCErrorString(err);
175 msg = m_ParseError.c_str();
178 smcore.LogError("[SM] Fatal error encountered parsing translation file \"%s/%s\"",
181 smcore.LogError("[SM] Error (line %d, column %d): %s",
189 void CPhraseFile::ReadSMC_ParseStart()
192 m_ParseState = PPS_None;
193 m_FileLogged = false;
194 m_LastPhraseString.clear();
197 SMCResult CPhraseFile::ReadSMC_NewSection(const SMCStates *states, const char *name)
199 bool recognized = false;
200 if (m_ParseState == PPS_None)
202 if (strcmp(name, "Phrases") == 0)
204 m_ParseState = PPS_Phrases;
208 else if (m_ParseState == PPS_Phrases)
210 m_ParseState = PPS_InPhrase;
213 if (!m_PhraseLookup.retrieve(name, &m_CurPhrase))
217 m_CurPhrase = m_pMemory->CreateMem(sizeof(phrase_t), (void **)&pPhrase);
218 m_PhraseLookup.insert(name, m_CurPhrase);
220 /* Initialize new phrase */
223 pPhrase->fmt_count = 0;
224 pPhrase->fmt_list = -1;
226 int trans_tbl = m_pMemory->CreateMem(sizeof(trans_t) * m_LangCount, (void **)&pTrans);
227 pPhrase = (phrase_t *)m_pMemory->GetAddress(m_CurPhrase);
228 pPhrase->trans_tbl = trans_tbl;
230 pPhrase->translations = 0;
231 pPhrase->fmt_bytes = 0;
233 for (unsigned int i=0; i<m_LangCount; i++)
235 pTrans[i].stridx = -1;
239 m_LastPhraseString.assign(name);
241 else if (m_ParseState == PPS_InPhrase)
243 ParseError("Phrase sections may not have sub-sections");
244 return SMCResult_HaltFail;
249 ParseWarning("Ignoring invalid section \"%s\" on line %d.", name, states->line);
252 return SMCResult_Continue;
255 SMCResult CPhraseFile::ReadSMC_KeyValue(const SMCStates *states, const char *key, const char *value)
257 /* See if we are ignoring a phrase */
258 if (m_CurPhrase == -1)
260 return SMCResult_Continue;
263 phrase_t *pPhrase = (phrase_t *)m_pMemory->GetAddress(m_CurPhrase);
265 /* Duplicate format keys get silently ignored. */
267 && strcmp(key, "#format") == 0
268 && pPhrase->fmt_list == -1)
270 if (pPhrase->translations > 0)
272 ParseWarning("#format property should come before translations on line %d, ignoring", states->line);
273 return SMCResult_Continue;
276 /* Do an initial browsing for error checking and what not */
284 ParseStates state = Parse_None;
286 const char *old_value = value;
287 const char *last_value = value;
288 while (*value != '\0')
290 if (state == Parse_None)
294 pPhrase->fmt_count++;
297 else if (*value == ',')
303 unsigned int bytes = textparsers->GetUTF8CharBytes(value);
304 if (bytes != 1 || !isalpha(*value))
306 ParseWarning("Invalid token '%c' in #format property on line %d.", *value, states->line);
310 else if (state == Parse_Index)
314 state = Parse_Format;
315 if (value - last_value >= 15)
317 ParseWarning("Too many digits in format index on line %d, phrase will be ignored.", states->line);
319 return SMCResult_Continue;
324 unsigned int bytes = textparsers->GetUTF8CharBytes(value);
325 if (bytes != 1 || !isdigit(*value))
327 ParseWarning("Token '%c' in #format property on line %d is not a digit, phrase will be ignored.",
331 return SMCResult_Continue;
335 else if (state == Parse_Format)
340 last_value = value + 1;
346 if (state != Parse_None)
348 /* Moose clam cow. */
349 ParseWarning("Unterminated format string on line %d, phrase will be ignored.", states->line);
351 return SMCResult_Continue;
355 /* Allocate the format table */
358 int tmp = m_pMemory->CreateMem(sizeof(int) * pPhrase->fmt_count, (void **)&fmt_list);
360 /* Update the phrase pointer in case it changed */
361 pPhrase = (phrase_t *)m_pMemory->GetAddress(m_CurPhrase);
362 pPhrase->fmt_list = tmp;
365 for (size_t i=0; i<pPhrase->fmt_count; i++)
370 /* Now we need to read again... this time into the format buffer */
371 const char *in_ptr = value;
372 const char *idx_ptr = NULL;
373 char *out_ptr = NULL;
374 unsigned int cur_idx = 0;
376 while (*in_ptr != '\0')
378 if (state == Parse_None)
386 else if (state == Parse_Index)
390 /* Check the number! */
393 ParseWarning("Format property contains unindexed format string on line %d, phrase will be ignored.", states->line);
395 return SMCResult_Continue;
397 long idx = strtol(idx_ptr, NULL, 10);
398 if (idx < 1 || idx > (long)pPhrase->fmt_count)
400 ParseWarning("Format property contains invalid index '%d' on line %d, phrase will be ignored.", idx, states->line);
402 return SMCResult_Continue;
404 else if (fmt_list[idx - 1] != -1)
406 ParseWarning("Format property contains duplicated index '%d' on line %d, phrase will be ignored.", idx, states->line);
408 return SMCResult_Continue;
410 cur_idx = (unsigned int)idx;
411 state = Parse_Format;
419 else if (state == Parse_Format)
425 ParseWarning("Format property contains empty format string on line %d, phrase will be ignored.", states->line);
427 return SMCResult_Continue;
431 /* Now, add this to our table */
432 int tmp_idx = m_pStringTab->AddString(fmt_buf);
433 /* Update pointers and update necessary variables */
434 pPhrase = (phrase_t *)m_pMemory->GetAddress(m_CurPhrase);
435 pPhrase->fmt_bytes += strlen(fmt_buf);
436 fmt_list = (int *)m_pMemory->GetAddress(pPhrase->fmt_list);
437 fmt_list[cur_idx - 1] = tmp_idx;
446 /* Check length ... */
447 if ((unsigned)(out_ptr - fmt_buf) >= sizeof(fmt_buf) - 1)
449 ParseWarning("Format property contains format string that exceeds maximum length on line %d, phrase will be ignored.",
452 return SMCResult_Continue;
454 *out_ptr++ = *in_ptr;
460 /* If we've gotten here, we only accepted unique indexes in a range.
461 * Therefore, the list has to be completely filled. Double check anyway.
463 for (size_t i=0; i<pPhrase->fmt_count; i++)
465 if (fmt_list[i] == -1)
467 ParseWarning("Format property contains no string for index %d on line %d, phrase will be ignored.",
471 return SMCResult_Continue;
477 size_t len = strlen(key);
478 if (len < 2 || len > 3)
480 ParseWarning("Ignoring translation to invalid language \"%s\" on line %d.", key, states->line);
481 return SMCResult_Continue;
485 if (!m_pTranslator->GetLanguageByCode(key, &lang))
487 /* Ignore if we don't have a language.
488 * :IDEA: issue a one-time alert?
490 return SMCResult_Continue;
493 /* See how many bytes we need for this string, then allocate.
494 * NOTE: THIS SHOULD GUARANTEE THAT WE DO NOT NEED TO NEED TO SIZE CHECK
496 len = strlen(value) + pPhrase->fmt_bytes + 1;
500 out_idx = m_pMemory->CreateMem(len, (void **)&out_buf);
503 pPhrase = (phrase_t *)m_pMemory->GetAddress(m_CurPhrase);
506 int *fmt_list = (int *)m_pMemory->GetAddress(pPhrase->fmt_list);
507 trans_t *pTrans = (trans_t *)m_pMemory->GetAddress(pPhrase->trans_tbl);
509 pTrans = &pTrans[lang];
510 pTrans->stridx = out_idx;
512 bool params[MAX_TRANSLATE_PARAMS];
514 /* Build the format order list, if necessary */
517 int tmp = m_pMemory->CreateMem(pPhrase->fmt_count * sizeof(int), (void **)&fmt_order);
519 /* Update pointers */
520 pPhrase = (phrase_t *)m_pMemory->GetAddress(m_CurPhrase);
521 pTrans = (trans_t *)m_pMemory->GetAddress(pPhrase->trans_tbl);
522 fmt_list = (int *)m_pMemory->GetAddress(pPhrase->fmt_list);
523 out_buf = (char *)m_pMemory->GetAddress(out_idx);
524 pTrans = &pTrans[lang];
526 /* Now it's safe to save the index */
527 pTrans->fmt_order = tmp;
529 for (unsigned int i=0; i<pPhrase->fmt_count; i++)
533 memset(¶ms[0], 0, sizeof(params));
536 const char *in_ptr = value;
537 char *out_ptr = out_buf;
538 unsigned int order_idx = 0;
539 while (*in_ptr != '\0')
543 switch (*(in_ptr + 1))
558 /* Copy both bytes since we don't know what's going on */
559 *out_ptr++ = *in_ptr++;
560 *out_ptr++ = *in_ptr;
563 /* Skip past the last byte read */
566 else if (*in_ptr == '{' && fmt_list != NULL)
568 /* Search for parameters if this is a formatted string */
569 const char *scrap_in_point = in_ptr;
570 const char *digit_start = ++in_ptr;
572 while (*in_ptr != '\0')
574 bytes = textparsers->GetUTF8CharBytes(in_ptr);
581 /* Did we get an index? */
582 if (in_ptr == digit_start)
587 long idx = strtol(digit_start, NULL, 10);
588 if (idx < 1 || idx > (int)pPhrase->fmt_count)
597 /* We're safe to insert the string. First mark order. */
598 fmt_order[order_idx++] = (int)idx - 1;
599 /* Now concatenate */
600 out_ptr += sprintf(out_ptr, "%s", m_pStringTab->GetString(fmt_list[idx-1]));
602 params[idx-1] = true;
609 /* Pretend none of this ever happened. Move along now! */
610 in_ptr = scrap_in_point;
611 *out_ptr++ = *in_ptr;
613 *out_ptr++ = *in_ptr;
619 pPhrase->translations++;
622 return SMCResult_Continue;
625 SMCResult CPhraseFile::ReadSMC_LeavingSection(const SMCStates *states)
627 if (m_ParseState == PPS_InPhrase)
629 if (m_CurPhrase == -1 && m_LastPhraseString.size())
630 m_PhraseLookup.remove(m_LastPhraseString.c_str());
632 m_ParseState = PPS_Phrases;
633 m_LastPhraseString.assign("");
635 else if (m_ParseState == PPS_Phrases)
637 m_ParseState = PPS_None;
640 return SMCResult_Continue;
643 void CPhraseFile::ReadSMC_ParseEnd(bool halted, bool failed)
645 /* Check to see if we have any dangling phrases that weren't completed, and scrap them */
646 if ((halted || failed) && m_LastPhraseString.size())
647 m_PhraseLookup.remove(m_LastPhraseString.c_str());
650 TransError CPhraseFile::GetTranslation(const char *szPhrase, unsigned int lang_id, Translation *pTrans)
652 if (lang_id >= m_LangCount)
654 return Trans_BadLanguage;
658 if (!m_PhraseLookup.retrieve(szPhrase, &address))
659 return Trans_BadPhrase;
661 phrase_t *pPhrase = (phrase_t *)m_pMemory->GetAddress(address);
662 trans_t *trans = (trans_t *)m_pMemory->GetAddress(pPhrase->trans_tbl);
664 trans = &trans[lang_id];
666 if (trans->stridx == -1)
668 return Trans_BadPhraseLanguage;
671 pTrans->fmt_count = pPhrase->fmt_count;
672 pTrans->fmt_order = pTrans->fmt_count > 0 ? (int *)m_pMemory->GetAddress(trans->fmt_order) : NULL;
673 pTrans->szPhrase = m_pStringTab->GetString(trans->stridx);
678 const char *CPhraseFile::GetFilename()
680 return m_File.c_str();
683 /**************************
684 ** MAIN TRANSLATOR CODE **
685 **************************/
687 Translator::Translator() : m_ServerLang(SOURCEMOD_LANGUAGE_ENGLISH)
689 m_pStringTab = new BaseStringTable(2048);
690 strncopy(m_InitialLang, "en", sizeof(m_InitialLang));
693 Translator::~Translator()
695 for (size_t i=0; i<m_Files.size(); i++)
700 for (size_t i=0; i<m_Languages.size(); i++)
702 delete m_Languages[i];
708 ConfigResult Translator::OnSourceModConfigChanged(const char *key,
714 if (strcasecmp(key, "ServerLang") == 0)
716 if (source == ConfigSource_Console)
719 if (!GetLanguageByCode(value, &index))
721 smcore.Format(error, maxlength, "Language code \"%s\" is not registered", value);
722 return ConfigResult_Reject;
725 m_ServerLang = index;
727 smcore.strncopy(m_InitialLang, value, sizeof(m_InitialLang));
730 return ConfigResult_Accept;
733 return ConfigResult_Ignore;
736 void Translator::OnSourceModLevelChange(const char *mapName)
738 /* Refresh language stuff */
739 char path[PLATFORM_MAX_PATH];
740 g_pSM->BuildPath(Path_SM, path, sizeof(path), "configs/languages.cfg");
741 RebuildLanguageDatabase(path);
744 void Translator::OnSourceModAllInitialized()
746 AddLanguage("en", "English");
748 const char* lang = smcore.GetCoreConfigValue("ServerLang");
751 strncpy(m_InitialLang, lang, sizeof(m_InitialLang));
754 g_pCorePhrases = CreatePhraseCollection();
755 g_pCorePhrases->AddPhraseFile("core.phrases");
757 sharesys->AddInterface(NULL, this);
760 void Translator::OnSourceModShutdown()
762 g_pCorePhrases->Destroy();
765 bool Translator::GetLanguageByCode(const char *code, unsigned int *index)
767 return m_LCodeLookup.retrieve(code, index);
770 bool Translator::GetLanguageByName(const char *name, unsigned int *index)
773 size_t len = strlen(name);
774 if (len > 255) len = 255;
775 for (size_t i = 0; i < len; i++)
777 if (name[i] >= 'A' && name[i] <= 'Z')
778 lower[i] = tolower(name[i]);
784 return m_LAliases.retrieve(lower, index);
787 unsigned int Translator::GetLanguageCount()
789 return (unsigned int)m_Languages.size();
792 BaseStringTable *Translator::GetStringTable()
797 unsigned int Translator::FindOrAddPhraseFile(const char *phrase_file)
799 for (size_t i=0; i<m_Files.size(); i++)
801 if (strcmp(m_Files[i]->GetFilename(), phrase_file) == 0)
803 return (unsigned int)i;
807 CPhraseFile *pFile = new CPhraseFile(this, phrase_file);
808 unsigned int idx = (unsigned int)m_Files.size();
810 m_Files.push_back(pFile);
812 pFile->ReparseFile();
817 void Translator::RebuildLanguageDatabase(const char *lang_header_file)
819 /* Erase everything we have */
820 m_LCodeLookup.clear();
822 m_pStringTab->Reset();
824 for (size_t i=0; i<m_Languages.size(); i++)
826 delete m_Languages[i];
833 if ((err=textparsers->ParseFile_SMC(lang_header_file, this, &states)) != SMCError_Okay)
835 const char *str_err = textparsers->GetSMCErrorString(err);
838 str_err = m_CustomError.c_str();
841 smcore.LogError("[SM] Failed to parse language header file: \"%s\"", lang_header_file);
842 smcore.LogError("[SM] Parse error (line %d, column %d): %s", states.line, states.col, str_err);
845 if (!m_LCodeLookup.retrieve(m_InitialLang, &m_ServerLang))
847 smcore.LogError("Server language was set to bad language \"%s\" -- reverting to English", m_InitialLang);
849 smcore.strncopy(m_InitialLang, "en", sizeof(m_InitialLang));
850 m_ServerLang = SOURCEMOD_LANGUAGE_ENGLISH;
853 if (!m_Languages.size())
855 smcore.LogError("[SM] Fatal error, no languages found! Translation will not work.");
858 for (size_t i=0; i<m_Files.size(); i++)
860 m_Files[i]->ReparseFile();
864 void Translator::ReadSMC_ParseStart()
866 m_InLanguageSection = false;
867 m_CustomError.clear();
870 SMCResult Translator::ReadSMC_NewSection(const SMCStates *states, const char *name)
872 if (!m_InLanguageSection)
874 if (strcmp(name, "Languages") == 0)
876 m_InLanguageSection = true;
880 if (!m_InLanguageSection)
882 smcore.LogError("[SM] Warning: Unrecognized section \"%s\" in languages.cfg", name);
885 return SMCResult_Continue;
888 SMCResult Translator::ReadSMC_LeavingSection(const SMCStates *states)
890 m_InLanguageSection = false;
892 return SMCResult_Continue;
895 SMCResult Translator::ReadSMC_KeyValue(const SMCStates *states, const char *key, const char *value)
897 size_t len = strlen(key);
899 if (len < 2 || len > 3)
901 smcore.LogError("[SM] Warning encountered parsing languages.cfg file.");
902 smcore.LogError("[SM] Invalid language code \"%s\" is being ignored.", key);
905 AddLanguage(key, value);
907 return SMCResult_Continue;
910 bool Translator::AddLanguage(const char *langcode, const char *description)
913 size_t len = strlen(description);
914 if (len > 255) len = 255;
915 for (size_t i = 0; i < len; i++)
917 if (description[i] >= 'A' && description[i] <= 'Z')
918 lower[i] = tolower(description[i]);
920 lower[i] = description[i];
924 if (m_LAliases.contains(lower))
928 if (!m_LCodeLookup.retrieve(langcode, &idx))
930 Language *pLanguage = new Language;
931 idx = m_Languages.size();
933 smcore.Format(pLanguage->m_code2, sizeof(pLanguage->m_code2), "%s", langcode);
934 pLanguage->m_CanonicalName = m_pStringTab->AddString(lower);
936 m_LCodeLookup.insert(langcode, idx);
938 m_Languages.push_back(pLanguage);
941 m_LAliases.insert(lower, idx);
946 CPhraseFile *Translator::GetFileByIndex(unsigned int index)
948 if (index >= m_Files.size())
953 return m_Files[index];
956 unsigned int Translator::GetServerLanguage()
961 unsigned int Translator::GetClientLanguage(int client)
963 IGamePlayer *pPlayer = playerhelpers->GetGamePlayer(client);
964 return pPlayer->GetLanguageId();
967 bool Translator::GetLanguageInfo(unsigned int number, const char **code, const char **name)
969 if (number >= GetLanguageCount())
974 Language *l = m_Languages[number];
981 *name = m_pStringTab->GetString(l->m_CanonicalName);
987 const char *Translator::GetInterfaceName()
989 return SMINTERFACE_TRANSLATOR_NAME;
992 unsigned int Translator::GetInterfaceVersion()
994 return SMINTERFACE_TRANSLATOR_VERSION;
997 IPhraseCollection *Translator::CreatePhraseCollection()
999 return new CPhraseCollection();
1002 int Translator::SetGlobalTarget(int index)
1004 return g_pSM->SetGlobalTarget(index);
1007 int Translator::GetGlobalTarget() const
1009 return g_pSM->GetGlobalTarget();
1012 bool CoreTranslate(char *buffer, size_t maxlength, const char *format, unsigned int numparams,
1013 size_t *pOutLength, ...)
1017 const char *fail_phrase;
1018 void *params[MAX_TRANSLATE_PARAMS];
1020 if (numparams > MAX_TRANSLATE_PARAMS)
1026 va_start(ap, pOutLength);
1027 for (i = 0; i < numparams; i++)
1029 params[i] = va_arg(ap, void *);
1033 if (!g_pCorePhrases->FormatString(buffer,
1041 if (fail_phrase != NULL)
1043 smcore.LogError("[SM] Could not find core phrase: %s", fail_phrase);
1047 smcore.LogError("[SM] Unknown fatal error while translating a core phrase.");
1056 bool Translator::FormatString(char *buffer,
1059 IPhraseCollection *pPhrases,
1061 unsigned int numparams,
1063 const char **pFailPhrase)
1068 if (!smcore.gnprintf(buffer, maxlength, format, pPhrases, params, numparams, arg, pOutLength, pFailPhrase))
1073 if (arg != numparams)
1075 if (pFailPhrase != NULL)
1077 *pFailPhrase = NULL;