fixed inheritance not being used in the base menu style when removing clients from the watch list
3 * ===============================================================
4 * SourceMod (C)2004-2007 AlliedModders LLC. All rights reserved.
5 * ===============================================================
7 * This file is not open source and may not be copied without explicit
8 * written permission of AlliedModders LLC. This file may not be redistributed
9 * in whole or significant part.
10 * For information, see LICENSE.txt or http://www.sourcemod.net/license.php
18 #include "Translator.h"
20 #include "TextParsers.h"
21 #include "LibrarySys.h"
22 #include "sm_stringutil.h"
23 #include "sourcemod.h"
25 Translator g_Translator;
26 CPhraseFile *g_pCorePhrases = NULL;
37 unsigned int fmt_count;
38 unsigned int fmt_bytes;
40 unsigned int translations;
43 CPhraseFile::CPhraseFile(Translator *pTranslator, const char *file)
45 m_pStringTab = pTranslator->GetStringTable();
46 m_pMemory = m_pStringTab->GetMemTable();
47 m_LangCount = pTranslator->GetLanguageCount();
49 m_pTranslator = pTranslator;
50 m_pPhraseLookup = NULL;
53 CPhraseFile::~CPhraseFile()
57 sm_trie_destroy(m_pPhraseLookup);
61 void CPhraseFile::ParseError(const char *message, ...)
65 va_start(ap, message);
66 vsnprintf(buffer, sizeof(buffer), message, ap);
69 m_ParseError.assign(buffer);
72 void CPhraseFile::ParseWarning(const char *message, ...)
76 va_start(ap, message);
77 vsnprintf(buffer, sizeof(buffer), message, ap);
82 g_Logger.LogError("[SM] Warning(s) encountered in translation file \"%s\"", m_File.c_str());
86 g_Logger.LogError("[SM] %s", message);
89 void CPhraseFile::ReparseFile()
93 sm_trie_destroy(m_pPhraseLookup);
95 m_pPhraseLookup = sm_trie_create();
97 m_LangCount = m_pTranslator->GetLanguageCount();
105 char path[PLATFORM_MAX_PATH];
106 g_SourceMod.BuildPath(Path_SM, path, PLATFORM_MAX_PATH, "translations/%s", m_File.c_str());
107 unsigned int line=0, col=0;
109 if ((err=g_TextParser.ParseFile_SMC(path, this, &line, &col)) != SMCParse_Okay)
111 const char *msg = g_TextParser.GetSMCErrorString(err);
114 msg = m_ParseError.c_str();
117 g_Logger.LogError("[SM] Fatal error encountered parsing translation file \"%s\"", m_File.c_str());
118 g_Logger.LogError("[SM] Error (line %d, column %d): %s", line, col, msg);
122 void CPhraseFile::ReadSMC_ParseStart()
125 m_ParseState = PPS_None;
127 m_FileLogged = false;
128 m_LastPhraseString.clear();
131 SMCParseResult CPhraseFile::ReadSMC_RawLine(const char *line, unsigned int curline)
135 return SMCParse_Continue;
138 SMCParseResult CPhraseFile::ReadSMC_NewSection(const char *name, bool opt_quotes)
140 bool recognized = false;
141 if (m_ParseState == PPS_None)
143 if (strcmp(name, "Phrases") == 0)
145 m_ParseState = PPS_Phrases;
148 } else if (m_ParseState == PPS_Phrases) {
149 m_ParseState = PPS_InPhrase;
153 m_CurPhrase = m_pMemory->CreateMem(sizeof(phrase_t), (void **)&pPhrase);
155 /* Create the reverse lookup */
156 if (!sm_trie_insert(m_pPhraseLookup, name, reinterpret_cast<void *>(m_CurPhrase)))
158 ParseWarning("Skipping duplicate phrase \"%s\" on line %d.", name, m_CurLine);
159 /* :IDEA: prevent memory waste by seeking backwards in memtable? */
162 /* Initialize new phrase */
165 pPhrase->fmt_count = 0;
166 pPhrase->fmt_list = -1;
167 pPhrase->trans_tbl = m_pMemory->CreateMem(sizeof(trans_t) * m_LangCount, (void **)&pTrans);
168 pPhrase->translations = 0;
169 pPhrase->fmt_bytes = 0;
171 for (unsigned int i=0; i<m_LangCount; i++)
173 pTrans[i].stridx = -1;
175 m_LastPhraseString.assign(name);
177 } else if (m_ParseState == PPS_InPhrase) {
178 ParseError("Phrase sections may not have sub-sections");
179 return SMCParse_HaltFail;
184 ParseWarning("Ignoring invalid section \"%s\" on line %d.", name, m_CurLine);
187 return SMCParse_Continue;
190 SMCParseResult CPhraseFile::ReadSMC_KeyValue(const char *key, const char *value, bool key_quotes, bool value_quotes)
192 /* See if we are ignoring a phrase */
195 return SMCParse_Continue;
198 phrase_t *pPhrase = (phrase_t *)m_pMemory->GetAddress(m_CurPhrase);
200 if (key[0] == '#' && strcmp(key, "#format") == 0)
202 if (pPhrase->fmt_list != -1)
204 ParseWarning("Ignoring duplicated #format property on line %d", m_CurLine);
205 return SMCParse_Continue;
208 if (pPhrase->translations > 0)
210 ParseWarning("#format property should come before translations on line %d, ignoring", m_CurLine);
211 return SMCParse_Continue;
214 /* Do an initial browsing for error checking and what not */
222 ParseStates state = Parse_None;
224 const char *old_value = value;
225 while (*value != '\0')
227 if (state == Parse_None)
231 pPhrase->fmt_count++;
233 } else if (*value == ',') {
236 unsigned int bytes = g_TextParser.GetUTF8CharBytes(value);
237 if (bytes != 1 || !isalpha(*value))
239 ParseWarning("Invalid token '%c' in #format property on line %d.", *value, m_CurLine);
242 } else if (state == Parse_Index) {
245 state = Parse_Format;
246 if (value - old_value >= 15)
248 ParseWarning("Too many digits in format index on line %d, phrase will be ignored.", m_CurLine);
250 return SMCParse_Continue;
253 unsigned int bytes = g_TextParser.GetUTF8CharBytes(value);
254 if (bytes != 1 || !isdigit(*value))
256 ParseWarning("Token '%c' in #format property on line %d is not a digit, phrase will be ignored.",
260 return SMCParse_Continue;
263 } else if (state == Parse_Format) {
272 if (state != Parse_None)
274 /* Moose clam cow. */
275 ParseWarning("Unterminated format string on line %d, phrase will be ignored.", m_CurLine);
277 return SMCParse_Continue;
281 /* Allocate the format table */
284 pPhrase->fmt_list = m_pMemory->CreateMem(sizeof(int) * pPhrase->fmt_count, (void **)&fmt_list);
287 for (size_t i=0; i<pPhrase->fmt_count; i++)
292 /* Now we need to read again... this time into the format buffer */
293 const char *in_ptr = value;
294 const char *idx_ptr = NULL;
295 char *out_ptr = NULL;
296 unsigned int cur_idx = 0;
298 while (*in_ptr != '\0')
300 if (state == Parse_None)
307 } else if (state == Parse_Index) {
310 /* Check the number! */
313 ParseWarning("Format property contains unindexed format string on line %d, phrase will be ignored.", m_CurLine);
315 return SMCParse_Continue;
317 long idx = strtol(idx_ptr, NULL, 10);
318 if (idx < 1 || idx > (long)pPhrase->fmt_count)
320 ParseWarning("Format property contains invalid index '%d' on line %d, phrase will be ignored.", idx, m_CurLine);
322 return SMCParse_Continue;
323 } else if (fmt_list[idx - 1] != -1) {
324 ParseWarning("Format property contains duplicated index '%d' on line %d, phrase will be ignored.", idx, m_CurLine);
326 return SMCParse_Continue;
328 cur_idx = (unsigned int)idx;
329 state = Parse_Format;
331 } else if (!idx_ptr) {
334 } else if (state == Parse_Format) {
339 ParseWarning("Format property contains empty format string on line %d, phrase will be ignored.", m_CurLine);
341 return SMCParse_Continue;
345 /* Now, add this to our table */
346 fmt_list[cur_idx - 1] = m_pStringTab->AddString(fmt_buf);
347 pPhrase->fmt_bytes += strlen(fmt_buf);
354 /* Check length ... */
355 if ((unsigned)(out_ptr - fmt_buf) >= sizeof(fmt_buf) - 1)
357 ParseWarning("Format property contains format string that exceeds maximum length on line %d, phrase will be ignored.",
360 return SMCParse_Continue;
362 *out_ptr++ = *in_ptr;
368 /* If we've gotten here, we only accepted unique indexes in a range.
369 * Therefore, the list has to be completely filled. Double check anyway.
371 for (size_t i=0; i<pPhrase->fmt_count; i++)
373 if (fmt_list[i] == -1)
375 ParseWarning("Format property contains no string for index %d on line %d, phrase will be ignored.",
379 return SMCParse_Continue;
383 size_t len = strlen(key);
386 ParseWarning("Ignoring translation to invalid language \"%s\" on line %d.", key, m_CurLine);
387 return SMCParse_Continue;
391 if (!m_pTranslator->GetLanguageByCode(key, &lang))
393 /* Ignore if we don't have a language.
394 * :IDEA: issue a one-time alert?
396 return SMCParse_Continue;
399 /* See how many bytes we need for this string, then allocate.
400 * NOTE: THIS SHOULD GUARANTEE THAT WE DO NOT NEED TO NEED TO SIZE CHECK
402 len = strlen(value) + pPhrase->fmt_bytes + 1;
406 out_idx = m_pMemory->CreateMem(len, (void **)&out_buf);
409 int *fmt_list = (int *)m_pMemory->GetAddress(pPhrase->fmt_list);
410 trans_t *pTrans = (trans_t *)m_pMemory->GetAddress(pPhrase->trans_tbl);
412 pTrans = &pTrans[lang];
413 pTrans->stridx = out_idx;
415 bool params[MAX_TRANSLATE_PARAMS];
417 /* Build the format order list, if necessary */
420 pTrans->fmt_order = m_pMemory->CreateMem(pPhrase->fmt_count * sizeof(int), (void **)&fmt_order);
422 for (unsigned int i=0; i<pPhrase->fmt_count; i++)
426 memset(¶ms[0], 0, sizeof(params));
429 const char *in_ptr = value;
430 char *out_ptr = out_buf;
431 unsigned int order_idx = 0;
432 while (*in_ptr != '\0')
436 switch (*(in_ptr + 1))
451 /* Copy both bytes since we don't know what's going on */
452 *out_ptr++ = *in_ptr++;
453 *out_ptr++ = *in_ptr;
456 /* Skip past the last byte read */
458 } else if (*in_ptr == '{' && fmt_list != NULL) {
459 /* Search for parameters if this is a formatted string */
460 const char *scrap_in_point = in_ptr;
461 const char *digit_start = ++in_ptr;
463 while (*in_ptr != '\0')
465 bytes = g_TextParser.GetUTF8CharBytes(in_ptr);
472 /* Did we get an index? */
473 if (in_ptr == digit_start)
478 long idx = strtol(digit_start, NULL, 10);
479 if (idx < 1 || idx > (int)pPhrase->fmt_count)
488 /* We're safe to insert the string. First mark order. */
489 fmt_order[order_idx++] = (int)idx - 1;
490 /* Now concatenate */
491 out_ptr += sprintf(out_ptr, "%s", m_pStringTab->GetString(fmt_list[idx-1]));
493 params[idx-1] = true;
500 /* Pretend none of this ever happened. Move along now! */
501 in_ptr = scrap_in_point;
502 *out_ptr++ = *in_ptr;
504 *out_ptr++ = *in_ptr;
510 pPhrase->translations++;
513 return SMCParse_Continue;
516 SMCParseResult CPhraseFile::ReadSMC_LeavingSection()
518 if (m_ParseState == PPS_InPhrase)
520 if (m_CurPhrase == -1 && m_LastPhraseString.size())
522 sm_trie_delete(m_pPhraseLookup, m_LastPhraseString.c_str());
525 m_ParseState = PPS_Phrases;
526 m_LastPhraseString.assign("");
527 } else if (m_ParseState == PPS_Phrases) {
528 m_ParseState = PPS_None;
531 return SMCParse_Continue;
534 void CPhraseFile::ReadSMC_ParseEnd(bool halted, bool failed)
536 /* Check to see if we have any dangling phrases that weren't completed, and scrap them */
537 if ((halted || failed) && m_LastPhraseString.size())
539 sm_trie_delete(m_pPhraseLookup, m_LastPhraseString.c_str());
543 TransError CPhraseFile::GetTranslation(const char *szPhrase, unsigned int lang_id, Translation *pTrans)
545 if (lang_id >= m_LangCount)
547 return Trans_BadLanguage;
551 if (!sm_trie_retrieve(m_pPhraseLookup, szPhrase, &object))
553 return Trans_BadPhrase;
556 phrase_t *pPhrase = (phrase_t *)m_pMemory->GetAddress(reinterpret_cast<int>(object));
557 trans_t *trans = (trans_t *)m_pMemory->GetAddress(pPhrase->trans_tbl);
559 trans = &trans[lang_id];
561 if (trans->stridx == -1)
563 return Trans_BadPhraseLanguage;
566 pTrans->fmt_order = (int *)m_pMemory->GetAddress(trans->fmt_order);
567 pTrans->fmt_count = pPhrase->fmt_count;
569 pTrans->szPhrase = m_pStringTab->GetString(trans->stridx);
574 const char *CPhraseFile::GetFilename()
576 return m_File.c_str();
579 /**************************
580 ** MAIN TRANSLATOR CODE **
581 **************************/
583 Translator::Translator() : m_ServerLang(LANGUAGE_ENGLISH)
585 m_pStringTab = new BaseStringTable(2048);
586 m_pLCodeLookup = sm_trie_create();
587 strncopy(m_InitialLang, "en", sizeof(m_InitialLang));
590 Translator::~Translator()
592 for (size_t i=0; i<m_Files.size(); i++)
597 for (size_t i=0; i<m_Languages.size(); i++)
599 delete m_Languages[i];
602 sm_trie_destroy(m_pLCodeLookup);
607 ConfigResult Translator::OnSourceModConfigChanged(const char *key,
613 if (strcasecmp(key, "ServerLang") == 0)
615 if (source == ConfigSource_Console)
618 if (!GetLanguageByCode(value, &index))
620 UTIL_Format(error, maxlength, "Language code \"%s\" is not registered", value);
621 return ConfigResult_Reject;
624 m_ServerLang = index;
626 strncopy(m_InitialLang, value, sizeof(m_InitialLang));
629 return ConfigResult_Accept;
632 return ConfigResult_Ignore;
635 void Translator::OnSourceModLevelChange(const char *mapName)
637 /* Refresh language stuff */
638 char path[PLATFORM_MAX_PATH];
639 g_SourceMod.BuildPath(Path_SM, path, sizeof(path), "configs/languages.cfg");
640 RebuildLanguageDatabase(path);
643 void Translator::OnSourceModAllInitialized()
645 AddLanguage("en", "English");
646 unsigned int id = FindOrAddPhraseFile("core.cfg");
647 g_pCorePhrases = GetFileByIndex(id);
650 bool Translator::GetLanguageByCode(const char *code, unsigned int *index)
654 if (!sm_trie_retrieve(m_pLCodeLookup, code, &_index))
661 *index = reinterpret_cast<unsigned int>(_index);
667 unsigned int Translator::GetLanguageCount()
669 return (unsigned int)m_Languages.size();
672 BaseStringTable *Translator::GetStringTable()
677 unsigned int Translator::FindOrAddPhraseFile(const char *phrase_file)
679 for (size_t i=0; i<m_Files.size(); i++)
681 if (strcmp(m_Files[i]->GetFilename(), phrase_file) == 0)
683 return (unsigned int)i;
687 CPhraseFile *pFile = new CPhraseFile(this, phrase_file);
688 unsigned int idx = (unsigned int)m_Files.size();
690 m_Files.push_back(pFile);
692 pFile->ReparseFile();
697 void Translator::RebuildLanguageDatabase(const char *lang_header_file)
699 /* Erase everything we have */
700 sm_trie_destroy(m_pLCodeLookup);
701 m_pLCodeLookup = sm_trie_create();
702 m_pStringTab->Reset();
704 for (size_t i=0; i<m_Languages.size(); i++)
706 delete m_Languages[i];
712 unsigned int line=0, col=0;
713 if ((err=g_TextParser.ParseFile_SMC(lang_header_file, this, &line, &col)) != SMCParse_Okay)
715 const char *str_err = g_TextParser.GetSMCErrorString(err);
718 str_err = m_CustomError.c_str();
721 g_Logger.LogError("[SM] Failed to parse language header file: \"%s\"", lang_header_file);
722 g_Logger.LogError("[SM] Parse error (line %d, column %d): %s", line, col, str_err);
727 if (!sm_trie_retrieve(m_pLCodeLookup, m_InitialLang, &serverLang))
729 g_Logger.LogError("Server language was set to bad language \"%s\" -- reverting to English", m_InitialLang);
731 strncopy(m_InitialLang, "en", sizeof(m_InitialLang));
732 m_ServerLang = LANGUAGE_ENGLISH;
735 m_ServerLang = reinterpret_cast<unsigned int>(serverLang);
737 if (!m_Languages.size())
739 g_Logger.LogError("[SM] Fatal error, no languages found! Translation will not work.");
742 for (size_t i=0; i<m_Files.size(); i++)
744 m_Files[i]->ReparseFile();
748 void Translator::ReadSMC_ParseStart()
750 m_InLanguageSection = false;
751 m_CustomError.clear();
754 SMCParseResult Translator::ReadSMC_NewSection(const char *name, bool opt_quotes)
756 if (!m_InLanguageSection)
758 if (strcmp(name, "Languages") == 0)
760 m_InLanguageSection = true;
764 if (!m_InLanguageSection)
766 g_Logger.LogError("[SM] Warning: Unrecognized section \"%s\" in languages.cfg", name);
769 return SMCParse_Continue;
772 SMCParseResult Translator::ReadSMC_LeavingSection()
774 m_InLanguageSection = false;
776 return SMCParse_Continue;
779 SMCParseResult Translator::ReadSMC_KeyValue(const char *key, const char *value, bool key_quotes, bool value_quotes)
781 size_t len = strlen(key);
785 g_Logger.LogError("[SM] Warning encountered parsing languages.cfg file.");
786 g_Logger.LogError("[SM] Invalid language code \"%s\" is being ignored.", key);
789 AddLanguage(key, value);
791 return SMCParse_Continue;
794 bool Translator::AddLanguage(const char *langcode, const char *description)
796 if (sm_trie_retrieve(m_pLCodeLookup, langcode, NULL))
801 Language *pLanguage = new Language;
802 unsigned int idx = m_Languages.size();
804 pLanguage->m_code2[0] = langcode[0];
805 pLanguage->m_code2[1] = langcode[1];
806 pLanguage->m_code2[2] = langcode[2];
807 pLanguage->m_FullName = m_pStringTab->AddString(description);
809 sm_trie_insert(m_pLCodeLookup, langcode, reinterpret_cast<void *>(idx));
811 m_Languages.push_back(pLanguage);
816 CPhraseFile *Translator::GetFileByIndex(unsigned int index)
818 if (index >= m_Files.size())
823 return m_Files[index];
826 size_t Translator::Translate(char *buffer, size_t maxlength, void **params, const Translation *pTrans)
828 void *new_params[MAX_TRANSLATE_PARAMS];
830 /* Rewrite the parameter order */
831 for (unsigned int i=0; i<pTrans->fmt_count; i++)
833 new_params[i] = params[pTrans->fmt_order[i]];
836 return gnprintf(buffer, maxlength, pTrans->szPhrase, new_params);
839 TransError Translator::CoreTrans(int client,
846 /* :TODO: do language stuff here */
850 return Trans_BadPhraseFile;
856 /* Using server lang temporarily until client lang stuff is implemented */
857 if ((err=g_pCorePhrases->GetTranslation(phrase, m_ServerLang, &trans)) != Trans_Okay)
862 size_t len = Translate(buffer, maxlength, params, &trans);
872 unsigned int Translator::GetServerLanguage()