core/Translator.cpp
author David Anderson <dvander@alliedmods.net>
Tue Jul 03 20:46:17 2007 +0000 (2007-07-03)
changeset 1036 2a073d5b3454
parent 1013 4225e70fba06
child 1105 ce907ba50921
permissions -rw-r--r--
added amb505
     1 /**
     2  * vim: set ts=4 :
     3  * ===============================================================
     4  * SourceMod (C)2004-2007 AlliedModders LLC.  All rights reserved.
     5  * ===============================================================
     6  *
     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
    11  *
    12  * Version: $Id$
    13  */
    14 
    15 #include <stdarg.h>
    16 #include <stdlib.h>
    17 #include <ctype.h>
    18 #include "Translator.h"
    19 #include "Logger.h"
    20 #include "TextParsers.h"
    21 #include "LibrarySys.h"
    22 #include "sm_stringutil.h"
    23 #include "sourcemod.h"
    24 
    25 Translator g_Translator;
    26 CPhraseFile *g_pCorePhrases = NULL;
    27 
    28 struct trans_t
    29 {
    30 	int stridx;
    31 	int fmt_order;
    32 };
    33 
    34 struct phrase_t
    35 {
    36 	int fmt_list;
    37 	unsigned int fmt_count;
    38 	unsigned int fmt_bytes;
    39 	int trans_tbl;
    40 	unsigned int translations;
    41 };
    42 
    43 CPhraseFile::CPhraseFile(Translator *pTranslator, const char *file)
    44 {
    45 	m_pStringTab = pTranslator->GetStringTable();
    46 	m_pMemory = m_pStringTab->GetMemTable();
    47 	m_LangCount = pTranslator->GetLanguageCount();
    48 	m_File.assign(file);
    49 	m_pTranslator = pTranslator;
    50 	m_pPhraseLookup = NULL;
    51 }
    52 
    53 CPhraseFile::~CPhraseFile()
    54 {
    55 	if (m_pPhraseLookup)
    56 	{
    57 		sm_trie_destroy(m_pPhraseLookup);
    58 	}
    59 }
    60 
    61 void CPhraseFile::ParseError(const char *message, ...)
    62 {
    63 	char buffer[1024];
    64 	va_list ap;
    65 	va_start(ap, message);
    66 	vsnprintf(buffer, sizeof(buffer), message, ap);
    67 	va_end(ap);
    68 
    69 	m_ParseError.assign(buffer);
    70 }
    71 
    72 void CPhraseFile::ParseWarning(const char *message, ...)
    73 {
    74 	char buffer[1024];
    75 	va_list ap;
    76 	va_start(ap, message);
    77 	vsnprintf(buffer, sizeof(buffer), message, ap);
    78 	va_end(ap);
    79 
    80 	if (!m_FileLogged)
    81 	{
    82 		g_Logger.LogError("[SM] Warning(s) encountered in translation file \"%s\"", m_File.c_str());
    83 		m_FileLogged = true;
    84 	}
    85 
    86 	g_Logger.LogError("[SM] %s", message);
    87 }
    88 
    89 void CPhraseFile::ReparseFile()
    90 {
    91 	if (m_pPhraseLookup)
    92 	{
    93 		sm_trie_destroy(m_pPhraseLookup);
    94 	}
    95 	m_pPhraseLookup = sm_trie_create();
    96 
    97 	m_LangCount = m_pTranslator->GetLanguageCount();
    98 
    99 	if (!m_LangCount)
   100 	{
   101 		return;
   102 	}
   103 
   104 	SMCParseError err;
   105 	char path[PLATFORM_MAX_PATH];
   106 	g_SourceMod.BuildPath(Path_SM, path, PLATFORM_MAX_PATH, "translations/%s", m_File.c_str());
   107 
   108 	//backwards compatibility shim
   109 	/* :HACKHACK: Change .cfg/.txt and vice versa for compatibility */
   110 	if (!g_LibSys.PathExists(path))
   111 	{
   112 		if (m_File.compare("common.cfg") == 0)
   113 		{
   114 			UTIL_ReplaceAll(path, sizeof(path), "common.cfg", "common.phrases.txt");
   115 		} else if (strstr(path, ".cfg")) {
   116 			UTIL_ReplaceAll(path, sizeof(path), ".cfg", ".txt");
   117 		} else if (strstr(path, ".txt")) {
   118 			UTIL_ReplaceAll(path, sizeof(path), ".txt", ".cfg");
   119 		}
   120 	}
   121 
   122 	unsigned int line=0, col=0;
   123 
   124 	if ((err=g_TextParser.ParseFile_SMC(path, this, &line, &col)) != SMCParse_Okay)
   125 	{
   126 		const char *msg = g_TextParser.GetSMCErrorString(err);
   127 		if (!msg)
   128 		{
   129 			msg = m_ParseError.c_str();
   130 		}
   131 
   132 		g_Logger.LogError("[SM] Fatal error encountered parsing translation file \"%s\"", m_File.c_str());
   133 		g_Logger.LogError("[SM] Error (line %d, column %d): %s", line, col, msg);
   134 	}
   135 }
   136 
   137 void CPhraseFile::ReadSMC_ParseStart()
   138 {
   139 	m_CurPhrase = -1;
   140 	m_ParseState = PPS_None;
   141 	m_CurLine = 0;
   142 	m_FileLogged = false;
   143 	m_LastPhraseString.clear();
   144 }
   145 
   146 SMCParseResult CPhraseFile::ReadSMC_RawLine(const char *line, unsigned int curline)
   147 {
   148 	m_CurLine = curline;
   149 
   150 	return SMCParse_Continue;
   151 }
   152 
   153 SMCParseResult CPhraseFile::ReadSMC_NewSection(const char *name, bool opt_quotes)
   154 {
   155 	bool recognized = false;
   156 	if (m_ParseState == PPS_None)
   157 	{
   158 		if (strcmp(name, "Phrases") == 0)
   159 		{
   160 			m_ParseState = PPS_Phrases;
   161 			recognized = true;
   162 		}
   163 	} else if (m_ParseState == PPS_Phrases) {
   164 		m_ParseState = PPS_InPhrase;
   165 		recognized = true;
   166 
   167 		phrase_t *pPhrase;
   168 		m_CurPhrase = m_pMemory->CreateMem(sizeof(phrase_t), (void **)&pPhrase);
   169 
   170 		/* Create the reverse lookup */
   171 		if (!sm_trie_insert(m_pPhraseLookup, name, reinterpret_cast<void *>(m_CurPhrase)))
   172 		{
   173 			ParseWarning("Skipping duplicate phrase \"%s\" on line %d.", name, m_CurLine);
   174 			/* :IDEA: prevent memory waste by seeking backwards in memtable? */
   175 			m_CurPhrase = -1;
   176 		} else {
   177 			/* Initialize new phrase */
   178 			trans_t *pTrans;
   179 	
   180 			pPhrase->fmt_count = 0;
   181 			pPhrase->fmt_list = -1;
   182 
   183 			int trans_tbl = m_pMemory->CreateMem(sizeof(trans_t) * m_LangCount, (void **)&pTrans);
   184 			/* Update the pointer! */
   185 			pPhrase = (phrase_t *)m_pMemory->GetAddress(m_CurPhrase);
   186 			pPhrase->trans_tbl = trans_tbl;
   187 
   188 			pPhrase->translations = 0;
   189 			pPhrase->fmt_bytes = 0;
   190 	
   191 			for (unsigned int i=0; i<m_LangCount; i++)
   192 			{
   193 				pTrans[i].stridx = -1;
   194 			}
   195 			m_LastPhraseString.assign(name);
   196 		}
   197 	} else if (m_ParseState == PPS_InPhrase) {
   198 		ParseError("Phrase sections may not have sub-sections");
   199 		return SMCParse_HaltFail;
   200 	}
   201 
   202 	if (!recognized)
   203 	{
   204 		ParseWarning("Ignoring invalid section \"%s\" on line %d.", name, m_CurLine);
   205 	}
   206 
   207 	return SMCParse_Continue;
   208 }
   209 
   210 SMCParseResult CPhraseFile::ReadSMC_KeyValue(const char *key, const char *value, bool key_quotes, bool value_quotes)
   211 {
   212 	/* See if we are ignoring a phrase */
   213 	if (m_CurPhrase == -1)
   214 	{
   215 		return SMCParse_Continue;
   216 	}
   217 
   218 	phrase_t *pPhrase = (phrase_t *)m_pMemory->GetAddress(m_CurPhrase);
   219 	
   220 	if (key[0] == '#' && strcmp(key, "#format") == 0)
   221 	{
   222 		if (pPhrase->fmt_list != -1)
   223 		{
   224 			ParseWarning("Ignoring duplicated #format property on line %d", m_CurLine);
   225 			return SMCParse_Continue;
   226 		}
   227 
   228 		if (pPhrase->translations > 0)
   229 		{
   230 			ParseWarning("#format property should come before translations on line %d, ignoring", m_CurLine);
   231 			return SMCParse_Continue;
   232 		}
   233 
   234 		/* Do an initial browsing for error checking and what not */
   235 		enum ParseStates
   236 		{
   237 			Parse_None,
   238 			Parse_Index,
   239 			Parse_Format,
   240 		};
   241 
   242 		ParseStates state = Parse_None;
   243 
   244 		const char *old_value = value;
   245 		const char *last_value = value;
   246 		while (*value != '\0')
   247 		{
   248 			if (state == Parse_None)
   249 			{
   250 				if (*value == '{')
   251 				{
   252 					pPhrase->fmt_count++;
   253 					state = Parse_Index;
   254 				} else if (*value == ',') {
   255 					/* Do nothing */
   256 				} else {
   257 					unsigned int bytes = g_TextParser.GetUTF8CharBytes(value);
   258 					if (bytes != 1 || !isalpha(*value))
   259 					{
   260 						ParseWarning("Invalid token '%c' in #format property on line %d.", *value, m_CurLine);
   261 					}
   262 				}
   263 			} else if (state == Parse_Index) {
   264 				if (*value == ':')
   265 				{
   266 					state = Parse_Format;
   267 					if (value - last_value >= 15)
   268 					{
   269 						ParseWarning("Too many digits in format index on line %d, phrase will be ignored.", m_CurLine);
   270 						m_CurPhrase = -1;
   271 						return SMCParse_Continue;
   272 					}
   273 				} else {
   274 					unsigned int bytes = g_TextParser.GetUTF8CharBytes(value);
   275 					if (bytes != 1 || !isdigit(*value))
   276 					{
   277 						ParseWarning("Token '%c' in #format property on line %d is not a digit, phrase will be ignored.",
   278 									*value,
   279 									m_CurLine);
   280 						m_CurPhrase = -1;
   281 						return SMCParse_Continue;
   282 					}
   283 				}
   284 			} else if (state == Parse_Format) {
   285 				if (*value == '}')
   286 				{
   287 					state = Parse_None;
   288 					last_value = value + 1;
   289 				}
   290 			}
   291 			value++;
   292 		}
   293 
   294 		if (state != Parse_None)
   295 		{
   296 			/* Moose clam cow. */
   297 			ParseWarning("Unterminated format string on line %d, phrase will be ignored.", m_CurLine);
   298 			m_CurPhrase = -1;
   299 			return SMCParse_Continue;
   300 		}
   301 		value = old_value;
   302 
   303 		/* Allocate the format table */
   304 		char fmt_buf[16];
   305 		int *fmt_list;
   306 		pPhrase->fmt_list = m_pMemory->CreateMem(sizeof(int) * pPhrase->fmt_count, (void **)&fmt_list);
   307 
   308 		/* Initialize */
   309 		for (size_t i=0; i<pPhrase->fmt_count; i++)
   310 		{
   311 			fmt_list[i] = -1;
   312 		}
   313 
   314 		/* Now we need to read again... this time into the format buffer */
   315 		const char *in_ptr = value;
   316 		const char *idx_ptr = NULL;
   317 		char *out_ptr = NULL;
   318 		unsigned int cur_idx = 0;
   319 		state = Parse_None;
   320 		while (*in_ptr != '\0')
   321 		{
   322 			if (state == Parse_None)
   323 			{
   324 				if (*in_ptr == '{')
   325 				{
   326 					state = Parse_Index;
   327 					idx_ptr = NULL;
   328 				}
   329 			} else if (state == Parse_Index) {
   330 				if (*in_ptr == ':')
   331 				{
   332 					/* Check the number! */
   333 					if (!idx_ptr)
   334 					{
   335 						ParseWarning("Format property contains unindexed format string on line %d, phrase will be ignored.", m_CurLine);
   336 						m_CurPhrase = -1;
   337 						return SMCParse_Continue;
   338 					}
   339 					long idx = strtol(idx_ptr, NULL, 10);
   340 					if (idx < 1 || idx > (long)pPhrase->fmt_count)
   341 					{
   342 						ParseWarning("Format property contains invalid index '%d' on line %d, phrase will be ignored.", idx, m_CurLine);
   343 						m_CurPhrase = -1;
   344 						return SMCParse_Continue;
   345 					} else if (fmt_list[idx - 1] != -1) {
   346 						ParseWarning("Format property contains duplicated index '%d' on line %d, phrase will be ignored.", idx, m_CurLine);
   347 						m_CurPhrase = -1;
   348 						return SMCParse_Continue;
   349 					}
   350 					cur_idx = (unsigned int)idx;
   351 					state = Parse_Format;
   352 					out_ptr = NULL;
   353 				} else if (!idx_ptr) {
   354 					idx_ptr = in_ptr;
   355 				}
   356 			} else if (state == Parse_Format) {
   357 				if (*in_ptr == '}')
   358 				{
   359 					if (!out_ptr)
   360 					{
   361 						ParseWarning("Format property contains empty format string on line %d, phrase will be ignored.", m_CurLine);
   362 						m_CurPhrase = -1;
   363 						return SMCParse_Continue;
   364 					}
   365 					*out_ptr = '\0';
   366 					state = Parse_None;
   367 					/* Now, add this to our table */
   368 					fmt_list[cur_idx - 1] = m_pStringTab->AddString(fmt_buf);
   369 					pPhrase->fmt_bytes += strlen(fmt_buf);
   370 				} else {
   371 					if (!out_ptr)
   372 					{
   373 						out_ptr = fmt_buf;
   374 						*out_ptr++ = '%';
   375 					}
   376 					/* Check length ... */
   377 					if ((unsigned)(out_ptr - fmt_buf) >= sizeof(fmt_buf) - 1)
   378 					{
   379 						ParseWarning("Format property contains format string that exceeds maximum length on line %d, phrase will be ignored.",
   380 									 m_CurLine);
   381 						m_CurPhrase = -1;
   382 						return SMCParse_Continue;
   383 					}
   384 					*out_ptr++ = *in_ptr;
   385 				}
   386 			}
   387 			in_ptr++;
   388 		}
   389 
   390 		/* If we've gotten here, we only accepted unique indexes in a range.
   391 		 * Therefore, the list has to be completely filled.  Double check anyway.
   392 		 */
   393 		for (size_t i=0; i<pPhrase->fmt_count; i++)
   394 		{
   395 			if (fmt_list[i] == -1)
   396 			{
   397 				ParseWarning("Format property contains no string for index %d on line %d, phrase will be ignored.",
   398 							 i + 1,
   399 							 m_CurLine);
   400 				m_CurPhrase = -1;
   401 				return SMCParse_Continue;
   402 			}
   403 		}
   404 	} else {
   405 		size_t len = strlen(key);
   406 		if (len != 2)
   407 		{
   408 			ParseWarning("Ignoring translation to invalid language \"%s\" on line %d.", key, m_CurLine);
   409 			return SMCParse_Continue;
   410 		}
   411 
   412 		unsigned int lang;
   413 		if (!m_pTranslator->GetLanguageByCode(key, &lang))
   414 		{
   415 			/* Ignore if we don't have a language.
   416 			 * :IDEA: issue a one-time alert?
   417 			 */
   418 			return SMCParse_Continue;
   419 		}
   420 
   421 		/* See how many bytes we need for this string, then allocate.
   422 		 * NOTE: THIS SHOULD GUARANTEE THAT WE DO NOT NEED TO NEED TO SIZE CHECK 
   423 		 */
   424 		len = strlen(value) + pPhrase->fmt_bytes + 1;
   425 		char *out_buf;
   426 		int out_idx;
   427 
   428 		out_idx = m_pMemory->CreateMem(len, (void **)&out_buf);
   429 
   430 		int *fmt_order;
   431 		int *fmt_list = (int *)m_pMemory->GetAddress(pPhrase->fmt_list);
   432 		trans_t *pTrans = (trans_t *)m_pMemory->GetAddress(pPhrase->trans_tbl);
   433 
   434 		pTrans = &pTrans[lang];
   435 		pTrans->stridx = out_idx;
   436 
   437 		bool params[MAX_TRANSLATE_PARAMS];
   438 
   439 		/* Build the format order list, if necessary */
   440 		if (fmt_list)
   441 		{
   442 			pTrans->fmt_order = m_pMemory->CreateMem(pPhrase->fmt_count * sizeof(int), (void **)&fmt_order);
   443 
   444 			for (unsigned int i=0; i<pPhrase->fmt_count; i++)
   445 			{
   446 				fmt_order[i] = -1;
   447 			}
   448 			memset(&params[0], 0, sizeof(params));
   449 		}
   450 
   451 		const char *in_ptr = value;
   452 		char *out_ptr = out_buf;
   453 		unsigned int order_idx = 0;
   454 		while (*in_ptr != '\0')
   455 		{
   456 			if (*in_ptr == '\\')
   457 			{
   458 				switch (*(in_ptr + 1))
   459 				{
   460 				case '\n':
   461 					*out_ptr++ = '\n';
   462 					break;
   463 				case '\t':
   464 					*out_ptr++ = '\t';
   465 					break;
   466 				case '\r':
   467 					*out_ptr++ = '\r';
   468 					break;
   469 				case '{':
   470 					*out_ptr++ = '{';
   471 					break;
   472 				default:
   473 					/* Copy both bytes since we don't know what's going on */
   474 					*out_ptr++ = *in_ptr++;
   475 					*out_ptr++ = *in_ptr;
   476 					break;
   477 				}
   478 				/* Skip past the last byte read */
   479 				in_ptr++;
   480 			} else if (*in_ptr == '{' && fmt_list != NULL) {
   481 				/* Search for parameters if this is a formatted string */
   482 				const char *scrap_in_point = in_ptr;
   483 				const char *digit_start = ++in_ptr;
   484 				unsigned int bytes;
   485 				while (*in_ptr != '\0')
   486 				{
   487 					bytes = g_TextParser.GetUTF8CharBytes(in_ptr);
   488 					if (bytes != 1)
   489 					{
   490 						goto scrap_point;
   491 					}
   492 					if (*in_ptr == '}')
   493 					{
   494 						/* Did we get an index? */
   495 						if (in_ptr == digit_start)
   496 						{
   497 							goto scrap_point;
   498 						}
   499 						/* Is it valid? */
   500 						long idx = strtol(digit_start, NULL, 10);
   501 						if (idx < 1 || idx > (int)pPhrase->fmt_count)
   502 						{
   503 							goto scrap_point;
   504 						}
   505 						if (params[idx-1])
   506 						{
   507 							goto scrap_point;
   508 						}
   509 
   510 						/* We're safe to insert the string.  First mark order. */
   511 						fmt_order[order_idx++] = (int)idx - 1;
   512 						/* Now concatenate */
   513 						out_ptr += sprintf(out_ptr, "%s", m_pStringTab->GetString(fmt_list[idx-1]));
   514 						/* Mark as used */
   515 						params[idx-1] = true;
   516 
   517 						goto cont_loop;
   518 					}
   519 					in_ptr++;
   520 				}
   521 scrap_point:
   522 				/* Pretend none of this ever happened.  Move along now! */
   523 				in_ptr = scrap_in_point;
   524 				*out_ptr++ = *in_ptr;
   525 			} else {
   526 				*out_ptr++ = *in_ptr;
   527 			}
   528 cont_loop:
   529 			in_ptr++;
   530 		}
   531 		*out_ptr = '\0';
   532 		pPhrase->translations++;
   533 	}
   534 
   535 	return SMCParse_Continue;
   536 }
   537 
   538 SMCParseResult CPhraseFile::ReadSMC_LeavingSection()
   539 {
   540 	if (m_ParseState == PPS_InPhrase)
   541 	{
   542 		if (m_CurPhrase == -1 && m_LastPhraseString.size())
   543 		{
   544 			sm_trie_delete(m_pPhraseLookup, m_LastPhraseString.c_str());
   545 		}
   546 		m_CurPhrase = -1;
   547 		m_ParseState = PPS_Phrases;
   548 		m_LastPhraseString.assign("");
   549 	} else if (m_ParseState == PPS_Phrases) {
   550 		m_ParseState = PPS_None;
   551 	}
   552 
   553 	return SMCParse_Continue;
   554 }
   555 
   556 void CPhraseFile::ReadSMC_ParseEnd(bool halted, bool failed)
   557 {
   558 	/* Check to see if we have any dangling phrases that weren't completed, and scrap them */
   559 	if ((halted || failed) && m_LastPhraseString.size())
   560 	{
   561 		sm_trie_delete(m_pPhraseLookup, m_LastPhraseString.c_str());
   562 	}
   563 }
   564 
   565 TransError CPhraseFile::GetTranslation(const char *szPhrase, unsigned int lang_id, Translation *pTrans)
   566 {
   567 	if (lang_id >= m_LangCount)
   568 	{
   569 		return Trans_BadLanguage;
   570 	}
   571 
   572 	void *object;
   573 	if (!sm_trie_retrieve(m_pPhraseLookup, szPhrase, &object))
   574 	{
   575 		return Trans_BadPhrase;
   576 	}
   577 
   578 	phrase_t *pPhrase = (phrase_t *)m_pMemory->GetAddress(reinterpret_cast<int>(object));
   579 	trans_t *trans = (trans_t *)m_pMemory->GetAddress(pPhrase->trans_tbl);
   580 
   581 	trans = &trans[lang_id];
   582 
   583 	if (trans->stridx == -1)
   584 	{
   585 		return Trans_BadPhraseLanguage;
   586 	}
   587 
   588 	pTrans->fmt_order = (int *)m_pMemory->GetAddress(trans->fmt_order);
   589 	pTrans->fmt_count = pPhrase->fmt_count;
   590 
   591 	pTrans->szPhrase = m_pStringTab->GetString(trans->stridx);
   592 
   593 	return Trans_Okay;
   594 }
   595 
   596 const char *CPhraseFile::GetFilename()
   597 {
   598 	return m_File.c_str();
   599 }
   600 
   601 /**************************
   602  ** MAIN TRANSLATOR CODE **
   603  **************************/
   604 
   605 Translator::Translator() : m_ServerLang(LANGUAGE_ENGLISH)
   606 {
   607 	m_pStringTab = new BaseStringTable(2048);
   608 	m_pLCodeLookup = sm_trie_create();
   609 	strncopy(m_InitialLang, "en", sizeof(m_InitialLang));
   610 }
   611 
   612 Translator::~Translator()
   613 {
   614 	for (size_t i=0; i<m_Files.size(); i++)
   615 	{
   616 		delete m_Files[i];
   617 	}
   618 
   619 	for (size_t i=0; i<m_Languages.size(); i++)
   620 	{
   621 		delete m_Languages[i];
   622 	}
   623 
   624 	sm_trie_destroy(m_pLCodeLookup);
   625 
   626 	delete m_pStringTab;
   627 }
   628 
   629 ConfigResult Translator::OnSourceModConfigChanged(const char *key, 
   630 									  const char *value, 
   631 									  ConfigSource source, 
   632 									  char *error, 
   633 									  size_t maxlength)
   634 {
   635 	if (strcasecmp(key, "ServerLang") == 0)
   636 	{
   637 		if (source == ConfigSource_Console)
   638 		{
   639 			unsigned int index;
   640 			if (!GetLanguageByCode(value, &index))
   641 			{
   642 				UTIL_Format(error, maxlength, "Language code \"%s\" is not registered", value);
   643 				return ConfigResult_Reject;
   644 			}
   645 
   646 			m_ServerLang = index;
   647 		} else {
   648 			strncopy(m_InitialLang, value, sizeof(m_InitialLang));
   649 		}
   650 
   651 		return ConfigResult_Accept;
   652 	}
   653 
   654 	return ConfigResult_Ignore;
   655 }
   656 
   657 void Translator::OnSourceModLevelChange(const char *mapName)
   658 {
   659 	/* Refresh language stuff */
   660 	char path[PLATFORM_MAX_PATH];
   661 	g_SourceMod.BuildPath(Path_SM, path, sizeof(path), "configs/languages.cfg");
   662 	RebuildLanguageDatabase(path);
   663 }
   664 
   665 void Translator::OnSourceModAllInitialized()
   666 {
   667 	AddLanguage("en", "English");
   668 
   669 	unsigned int id;
   670 
   671 	//backwards compatibility shim
   672 	/* hack -- if core.cfg exists, exec it instead. */
   673 	char path[PLATFORM_MAX_PATH];
   674 	g_SourceMod.BuildPath(Path_SM, path, sizeof(path), "translations/core.cfg");
   675 	
   676 	if (g_LibSys.PathExists(path))
   677 	{
   678 		id = FindOrAddPhraseFile("core.cfg");
   679 	} else {
   680 		id = FindOrAddPhraseFile("core.phrases.txt");
   681 	}
   682 
   683 	g_pCorePhrases = GetFileByIndex(id);
   684 }
   685 
   686 bool Translator::GetLanguageByCode(const char *code, unsigned int *index)
   687 {
   688 	void *_index;
   689 
   690 	if (!sm_trie_retrieve(m_pLCodeLookup, code, &_index))
   691 	{
   692 		return false;
   693 	}
   694 
   695 	if (index)
   696 	{
   697 		*index = reinterpret_cast<unsigned int>(_index);
   698 	}
   699 
   700 	return true;
   701 }
   702 
   703 unsigned int Translator::GetLanguageCount()
   704 {
   705 	return (unsigned int)m_Languages.size();
   706 }
   707 
   708 BaseStringTable *Translator::GetStringTable()
   709 {
   710 	return m_pStringTab;
   711 }
   712 
   713 unsigned int Translator::FindOrAddPhraseFile(const char *phrase_file)
   714 {
   715 	for (size_t i=0; i<m_Files.size(); i++)
   716 	{
   717 		if (strcmp(m_Files[i]->GetFilename(), phrase_file) == 0)
   718 		{
   719 			return (unsigned int)i;
   720 		}
   721 	}
   722 
   723 	CPhraseFile *pFile = new CPhraseFile(this, phrase_file);
   724 	unsigned int idx = (unsigned int)m_Files.size();
   725 	
   726 	m_Files.push_back(pFile);
   727 
   728 	pFile->ReparseFile();
   729 
   730 	return idx;
   731 }
   732 
   733 void Translator::RebuildLanguageDatabase(const char *lang_header_file)
   734 {
   735 	/* Erase everything we have */
   736 	sm_trie_destroy(m_pLCodeLookup);
   737 	m_pLCodeLookup = sm_trie_create();
   738 	m_pStringTab->Reset();
   739 
   740 	for (size_t i=0; i<m_Languages.size(); i++)
   741 	{
   742 		delete m_Languages[i];
   743 	}
   744 	m_Languages.clear();
   745 
   746 	/* Start anew */
   747 	SMCParseError err;
   748 	unsigned int line=0, col=0;
   749 	if ((err=g_TextParser.ParseFile_SMC(lang_header_file, this, &line, &col)) != SMCParse_Okay)
   750 	{
   751 		const char *str_err = g_TextParser.GetSMCErrorString(err);
   752 		if (!str_err)
   753 		{
   754 			str_err = m_CustomError.c_str();
   755 		}
   756 
   757 		g_Logger.LogError("[SM] Failed to parse language header file: \"%s\"", lang_header_file);
   758 		g_Logger.LogError("[SM] Parse error (line %d, column %d): %s", line, col, str_err);
   759 	}
   760 
   761 	void *serverLang;
   762 
   763 	if (!sm_trie_retrieve(m_pLCodeLookup, m_InitialLang, &serverLang))
   764 	{
   765 		g_Logger.LogError("Server language was set to bad language \"%s\" -- reverting to English", m_InitialLang);
   766 
   767 		strncopy(m_InitialLang, "en", sizeof(m_InitialLang));
   768 		m_ServerLang = LANGUAGE_ENGLISH;
   769 	}
   770 
   771 	m_ServerLang = reinterpret_cast<unsigned int>(serverLang);
   772 
   773 	if (!m_Languages.size())
   774 	{
   775 		g_Logger.LogError("[SM] Fatal error, no languages found! Translation will not work.");
   776 	}
   777 
   778 	for (size_t i=0; i<m_Files.size(); i++)
   779 	{
   780 		m_Files[i]->ReparseFile();
   781 	}
   782 }
   783 
   784 void Translator::ReadSMC_ParseStart()
   785 {
   786 	m_InLanguageSection = false;
   787 	m_CustomError.clear();
   788 }
   789 
   790 SMCParseResult Translator::ReadSMC_NewSection(const char *name, bool opt_quotes)
   791 {
   792 	if (!m_InLanguageSection)
   793 	{
   794 		if (strcmp(name, "Languages") == 0)
   795 		{
   796 			m_InLanguageSection = true;
   797 		}
   798 	}
   799 
   800 	if (!m_InLanguageSection)
   801 	{
   802 		g_Logger.LogError("[SM] Warning: Unrecognized section \"%s\" in languages.cfg", name);
   803 	}
   804 
   805 	return SMCParse_Continue;
   806 }
   807 
   808 SMCParseResult Translator::ReadSMC_LeavingSection()
   809 {
   810 	m_InLanguageSection = false;
   811 
   812 	return SMCParse_Continue;
   813 }
   814 
   815 SMCParseResult Translator::ReadSMC_KeyValue(const char *key, const char *value, bool key_quotes, bool value_quotes)
   816 {
   817 	size_t len = strlen(key);
   818 
   819 	if (len != 2)
   820 	{
   821 		g_Logger.LogError("[SM] Warning encountered parsing languages.cfg file.");
   822 		g_Logger.LogError("[SM] Invalid language code \"%s\" is being ignored.", key);
   823 	}
   824 
   825 	AddLanguage(key, value);
   826 
   827 	return SMCParse_Continue;
   828 }
   829 
   830 bool Translator::AddLanguage(const char *langcode, const char *description)
   831 {
   832 	if (sm_trie_retrieve(m_pLCodeLookup, langcode, NULL))
   833 	{
   834 		return false;
   835 	}
   836 
   837 	Language *pLanguage = new Language;
   838 	unsigned int idx = m_Languages.size();
   839 
   840 	pLanguage->m_code2[0] = langcode[0];
   841 	pLanguage->m_code2[1] = langcode[1];
   842 	pLanguage->m_code2[2] = langcode[2];
   843 	pLanguage->m_FullName = m_pStringTab->AddString(description);
   844 
   845 	sm_trie_insert(m_pLCodeLookup, langcode, reinterpret_cast<void *>(idx));
   846 
   847 	m_Languages.push_back(pLanguage);
   848 
   849 	return true;
   850 }
   851 
   852 CPhraseFile *Translator::GetFileByIndex(unsigned int index)
   853 {
   854 	if (index >= m_Files.size())
   855 	{
   856 		return NULL;
   857 	}
   858 
   859 	return m_Files[index];
   860 }
   861 
   862 size_t Translator::Translate(char *buffer, size_t maxlength, void **params, const Translation *pTrans)
   863 {
   864 	void *new_params[MAX_TRANSLATE_PARAMS];
   865 
   866 	/* Rewrite the parameter order */
   867 	for (unsigned int i=0; i<pTrans->fmt_count; i++)
   868 	{
   869 		new_params[i] = params[pTrans->fmt_order[i]];
   870 	}
   871 
   872 	return gnprintf(buffer, maxlength, pTrans->szPhrase, new_params);
   873 }
   874 
   875 TransError Translator::CoreTrans(int client, 
   876 								  char *buffer, 
   877 								  size_t maxlength, 
   878 								  const char *phrase, 
   879 								  void **params, 
   880 								  size_t *outlen)
   881 {
   882 	/* :TODO: do language stuff here */
   883 
   884 	if (!g_pCorePhrases)
   885 	{
   886 		return Trans_BadPhraseFile;
   887 	}
   888 
   889 	Translation trans;
   890 	TransError err;
   891 	
   892 	/* Using server lang temporarily until client lang stuff is implemented */
   893 	if ((err=g_pCorePhrases->GetTranslation(phrase, m_ServerLang, &trans)) != Trans_Okay)
   894 	{
   895 		return err;
   896 	}
   897 
   898 	size_t len = Translate(buffer, maxlength, params, &trans);
   899 
   900 	if (outlen)
   901 	{
   902 		*outlen = len;
   903 	}
   904 
   905 	return Trans_Okay;
   906 }
   907 
   908 unsigned int Translator::GetServerLanguage()
   909 {
   910 	return m_ServerLang;
   911 }