Update CS:GO team score gamedata.
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;
478 if (!m_pTranslator->GetLanguageByCode(key, &lang))
480 /* Ignore if we don't have a language.
481 * :IDEA: issue a one-time alert?
483 return SMCResult_Continue;
486 /* See how many bytes we need for this string, then allocate.
487 * NOTE: THIS SHOULD GUARANTEE THAT WE DO NOT NEED TO NEED TO SIZE CHECK
489 size_t len = strlen(value) + pPhrase->fmt_bytes + 1;
493 out_idx = m_pMemory->CreateMem(len, (void **)&out_buf);
496 pPhrase = (phrase_t *)m_pMemory->GetAddress(m_CurPhrase);
499 int *fmt_list = (int *)m_pMemory->GetAddress(pPhrase->fmt_list);
500 trans_t *pTrans = (trans_t *)m_pMemory->GetAddress(pPhrase->trans_tbl);
502 pTrans = &pTrans[lang];
503 pTrans->stridx = out_idx;
505 bool params[MAX_TRANSLATE_PARAMS];
507 /* Build the format order list, if necessary */
510 int tmp = m_pMemory->CreateMem(pPhrase->fmt_count * sizeof(int), (void **)&fmt_order);
512 /* Update pointers */
513 pPhrase = (phrase_t *)m_pMemory->GetAddress(m_CurPhrase);
514 pTrans = (trans_t *)m_pMemory->GetAddress(pPhrase->trans_tbl);
515 fmt_list = (int *)m_pMemory->GetAddress(pPhrase->fmt_list);
516 out_buf = (char *)m_pMemory->GetAddress(out_idx);
517 pTrans = &pTrans[lang];
519 /* Now it's safe to save the index */
520 pTrans->fmt_order = tmp;
522 for (unsigned int i=0; i<pPhrase->fmt_count; i++)
526 memset(¶ms[0], 0, sizeof(params));
529 const char *in_ptr = value;
530 char *out_ptr = out_buf;
531 unsigned int order_idx = 0;
532 while (*in_ptr != '\0')
536 switch (*(in_ptr + 1))
551 /* Copy both bytes since we don't know what's going on */
552 *out_ptr++ = *in_ptr++;
553 *out_ptr++ = *in_ptr;
556 /* Skip past the last byte read */
559 else if (*in_ptr == '{' && fmt_list != NULL)
561 /* Search for parameters if this is a formatted string */
562 const char *scrap_in_point = in_ptr;
563 const char *digit_start = ++in_ptr;
565 while (*in_ptr != '\0')
567 bytes = textparsers->GetUTF8CharBytes(in_ptr);
574 /* Did we get an index? */
575 if (in_ptr == digit_start)
580 long idx = strtol(digit_start, NULL, 10);
581 if (idx < 1 || idx > (int)pPhrase->fmt_count)
590 /* We're safe to insert the string. First mark order. */
591 fmt_order[order_idx++] = (int)idx - 1;
592 /* Now concatenate */
593 out_ptr += sprintf(out_ptr, "%s", m_pStringTab->GetString(fmt_list[idx-1]));
595 params[idx-1] = true;
602 /* Pretend none of this ever happened. Move along now! */
603 in_ptr = scrap_in_point;
604 *out_ptr++ = *in_ptr;
606 *out_ptr++ = *in_ptr;
612 pPhrase->translations++;
615 return SMCResult_Continue;
618 SMCResult CPhraseFile::ReadSMC_LeavingSection(const SMCStates *states)
620 if (m_ParseState == PPS_InPhrase)
622 if (m_CurPhrase == -1 && m_LastPhraseString.size())
623 m_PhraseLookup.remove(m_LastPhraseString.c_str());
625 m_ParseState = PPS_Phrases;
626 m_LastPhraseString.assign("");
628 else if (m_ParseState == PPS_Phrases)
630 m_ParseState = PPS_None;
633 return SMCResult_Continue;
636 void CPhraseFile::ReadSMC_ParseEnd(bool halted, bool failed)
638 /* Check to see if we have any dangling phrases that weren't completed, and scrap them */
639 if ((halted || failed) && m_LastPhraseString.size())
640 m_PhraseLookup.remove(m_LastPhraseString.c_str());
643 TransError CPhraseFile::GetTranslation(const char *szPhrase, unsigned int lang_id, Translation *pTrans)
645 if (lang_id >= m_LangCount)
647 return Trans_BadLanguage;
651 if (!m_PhraseLookup.retrieve(szPhrase, &address))
652 return Trans_BadPhrase;
654 phrase_t *pPhrase = (phrase_t *)m_pMemory->GetAddress(address);
655 trans_t *trans = (trans_t *)m_pMemory->GetAddress(pPhrase->trans_tbl);
657 trans = &trans[lang_id];
659 if (trans->stridx == -1)
661 return Trans_BadPhraseLanguage;
664 pTrans->fmt_count = pPhrase->fmt_count;
665 pTrans->fmt_order = pTrans->fmt_count > 0 ? (int *)m_pMemory->GetAddress(trans->fmt_order) : NULL;
666 pTrans->szPhrase = m_pStringTab->GetString(trans->stridx);
671 const char *CPhraseFile::GetFilename()
673 return m_File.c_str();
676 /**************************
677 ** MAIN TRANSLATOR CODE **
678 **************************/
680 Translator::Translator() : m_ServerLang(SOURCEMOD_LANGUAGE_ENGLISH)
682 m_pStringTab = new BaseStringTable(2048);
683 strncopy(m_InitialLang, "en", sizeof(m_InitialLang));
686 Translator::~Translator()
688 for (size_t i=0; i<m_Files.size(); i++)
693 for (size_t i=0; i<m_Languages.size(); i++)
695 delete m_Languages[i];
701 ConfigResult Translator::OnSourceModConfigChanged(const char *key,
707 if (strcasecmp(key, "ServerLang") == 0)
709 if (source == ConfigSource_Console)
712 if (!GetLanguageByCode(value, &index))
714 smcore.Format(error, maxlength, "Language code \"%s\" is not registered", value);
715 return ConfigResult_Reject;
718 m_ServerLang = index;
720 smcore.strncopy(m_InitialLang, value, sizeof(m_InitialLang));
723 return ConfigResult_Accept;
726 return ConfigResult_Ignore;
729 void Translator::OnSourceModLevelChange(const char *mapName)
731 RebuildLanguageDatabase();
734 void Translator::OnSourceModAllInitialized()
736 AddLanguage("en", "English");
738 const char* lang = smcore.GetCoreConfigValue("ServerLang");
741 strncpy(m_InitialLang, lang, sizeof(m_InitialLang));
744 g_pCorePhrases = CreatePhraseCollection();
745 g_pCorePhrases->AddPhraseFile("core.phrases");
747 sharesys->AddInterface(NULL, this);
750 void Translator::OnSourceModShutdown()
752 g_pCorePhrases->Destroy();
755 bool Translator::GetLanguageByCode(const char *code, unsigned int *index)
757 return m_LCodeLookup.retrieve(code, index);
760 bool Translator::GetLanguageByName(const char *name, unsigned int *index)
763 size_t len = strlen(name);
764 if (len > 255) len = 255;
765 for (size_t i = 0; i < len; i++)
767 if (name[i] >= 'A' && name[i] <= 'Z')
768 lower[i] = tolower(name[i]);
774 return m_LAliases.retrieve(lower, index);
777 unsigned int Translator::GetLanguageCount()
779 return (unsigned int)m_Languages.size();
782 BaseStringTable *Translator::GetStringTable()
787 unsigned int Translator::FindOrAddPhraseFile(const char *phrase_file)
789 for (size_t i=0; i<m_Files.size(); i++)
791 if (strcmp(m_Files[i]->GetFilename(), phrase_file) == 0)
793 return (unsigned int)i;
797 CPhraseFile *pFile = new CPhraseFile(this, phrase_file);
798 unsigned int idx = (unsigned int)m_Files.size();
800 m_Files.push_back(pFile);
802 pFile->ReparseFile();
807 void Translator::RebuildLanguageDatabase()
809 /* Erase everything we have */
810 m_LCodeLookup.clear();
812 m_pStringTab->Reset();
814 for (size_t i=0; i<m_Languages.size(); i++)
816 delete m_Languages[i];
821 char path[PLATFORM_MAX_PATH];
822 g_pSM->BuildPath(Path_SM, path, sizeof(path), "configs/languages.cfg");
826 if ((err=textparsers->ParseFile_SMC(path, this, &states)) != SMCError_Okay)
828 const char *str_err = textparsers->GetSMCErrorString(err);
831 str_err = m_CustomError.c_str();
834 smcore.LogError("[SM] Failed to parse language header file: \"%s\"", path);
835 smcore.LogError("[SM] Parse error (line %d, column %d): %s", states.line, states.col, str_err);
838 if (!m_LCodeLookup.retrieve(m_InitialLang, &m_ServerLang))
840 smcore.LogError("Server language was set to bad language \"%s\" -- reverting to English", m_InitialLang);
842 smcore.strncopy(m_InitialLang, "en", sizeof(m_InitialLang));
843 m_ServerLang = SOURCEMOD_LANGUAGE_ENGLISH;
846 if (!m_Languages.size())
848 smcore.LogError("[SM] Fatal error, no languages found! Translation will not work.");
851 for (size_t i=0; i<m_Files.size(); i++)
853 m_Files[i]->ReparseFile();
857 void Translator::ReadSMC_ParseStart()
859 m_InLanguageSection = false;
860 m_CustomError.clear();
863 SMCResult Translator::ReadSMC_NewSection(const SMCStates *states, const char *name)
865 if (!m_InLanguageSection)
867 if (strcmp(name, "Languages") == 0)
869 m_InLanguageSection = true;
873 if (!m_InLanguageSection)
875 smcore.LogError("[SM] Warning: Unrecognized section \"%s\" in languages.cfg", name);
878 return SMCResult_Continue;
881 SMCResult Translator::ReadSMC_LeavingSection(const SMCStates *states)
883 m_InLanguageSection = false;
885 return SMCResult_Continue;
888 SMCResult Translator::ReadSMC_KeyValue(const SMCStates *states, const char *key, const char *value)
890 AddLanguage(key, value);
892 return SMCResult_Continue;
895 bool Translator::AddLanguage(const char *langcode, const char *description)
898 size_t len = strlen(description);
899 if (len > 255) len = 255;
900 for (size_t i = 0; i < len; i++)
902 if (description[i] >= 'A' && description[i] <= 'Z')
903 lower[i] = tolower(description[i]);
905 lower[i] = description[i];
909 if (m_LAliases.contains(lower))
913 if (!m_LCodeLookup.retrieve(langcode, &idx))
915 Language *pLanguage = new Language;
916 idx = m_Languages.size();
918 smcore.Format(pLanguage->m_code2, sizeof(pLanguage->m_code2), "%s", langcode);
919 pLanguage->m_CanonicalName = m_pStringTab->AddString(lower);
921 m_LCodeLookup.insert(langcode, idx);
923 m_Languages.push_back(pLanguage);
926 m_LAliases.insert(lower, idx);
931 CPhraseFile *Translator::GetFileByIndex(unsigned int index)
933 if (index >= m_Files.size())
938 return m_Files[index];
941 unsigned int Translator::GetServerLanguage()
946 unsigned int Translator::GetClientLanguage(int client)
948 IGamePlayer *pPlayer = playerhelpers->GetGamePlayer(client);
949 return pPlayer->GetLanguageId();
952 bool Translator::GetLanguageInfo(unsigned int number, const char **code, const char **name)
954 if (number >= GetLanguageCount())
959 Language *l = m_Languages[number];
966 *name = m_pStringTab->GetString(l->m_CanonicalName);
972 const char *Translator::GetInterfaceName()
974 return SMINTERFACE_TRANSLATOR_NAME;
977 unsigned int Translator::GetInterfaceVersion()
979 return SMINTERFACE_TRANSLATOR_VERSION;
982 IPhraseCollection *Translator::CreatePhraseCollection()
984 return new CPhraseCollection();
987 int Translator::SetGlobalTarget(int index)
989 return g_pSM->SetGlobalTarget(index);
992 int Translator::GetGlobalTarget() const
994 return g_pSM->GetGlobalTarget();
997 bool CoreTranslate(char *buffer, size_t maxlength, const char *format, unsigned int numparams,
998 size_t *pOutLength, ...)
1002 const char *fail_phrase;
1003 void *params[MAX_TRANSLATE_PARAMS];
1005 if (numparams > MAX_TRANSLATE_PARAMS)
1011 va_start(ap, pOutLength);
1012 for (i = 0; i < numparams; i++)
1014 params[i] = va_arg(ap, void *);
1018 if (!g_pCorePhrases->FormatString(buffer,
1026 if (fail_phrase != NULL)
1028 smcore.LogError("[SM] Could not find core phrase: %s", fail_phrase);
1032 smcore.LogError("[SM] Unknown fatal error while translating a core phrase.");
1041 bool Translator::FormatString(char *buffer,
1044 IPhraseCollection *pPhrases,
1046 unsigned int numparams,
1048 const char **pFailPhrase)
1053 if (!smcore.gnprintf(buffer, maxlength, format, pPhrases, params, numparams, arg, pOutLength, pFailPhrase))
1058 if (arg != numparams)
1060 if (pFailPhrase != NULL)
1062 *pFailPhrase = NULL;