core/Translator.cpp
author David Anderson <dvander@alliedmods.net>
Sun May 06 06:15:48 2007 +0000 (2007-05-06)
changeset 743 a2804c2faba2
parent 673 fc1d50579d06
child 887 7a38baa4d85c
permissions -rw-r--r--
added request amb251
     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 	unsigned int line=0, col=0;
   108 
   109 	if ((err=g_TextParser.ParseFile_SMC(path, this, &line, &col)) != SMCParse_Okay)
   110 	{
   111 		const char *msg = g_TextParser.GetSMCErrorString(err);
   112 		if (!msg)
   113 		{
   114 			msg = m_ParseError.c_str();
   115 		}
   116 
   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);
   119 	}
   120 }
   121 
   122 void CPhraseFile::ReadSMC_ParseStart()
   123 {
   124 	m_CurPhrase = -1;
   125 	m_ParseState = PPS_None;
   126 	m_CurLine = 0;
   127 	m_FileLogged = false;
   128 	m_LastPhraseString.clear();
   129 }
   130 
   131 SMCParseResult CPhraseFile::ReadSMC_RawLine(const char *line, unsigned int curline)
   132 {
   133 	m_CurLine = curline;
   134 
   135 	return SMCParse_Continue;
   136 }
   137 
   138 SMCParseResult CPhraseFile::ReadSMC_NewSection(const char *name, bool opt_quotes)
   139 {
   140 	bool recognized = false;
   141 	if (m_ParseState == PPS_None)
   142 	{
   143 		if (strcmp(name, "Phrases") == 0)
   144 		{
   145 			m_ParseState = PPS_Phrases;
   146 			recognized = true;
   147 		}
   148 	} else if (m_ParseState == PPS_Phrases) {
   149 		m_ParseState = PPS_InPhrase;
   150 		recognized = true;
   151 
   152 		phrase_t *pPhrase;
   153 		m_CurPhrase = m_pMemory->CreateMem(sizeof(phrase_t), (void **)&pPhrase);
   154 
   155 		/* Create the reverse lookup */
   156 		if (!sm_trie_insert(m_pPhraseLookup, name, reinterpret_cast<void *>(m_CurPhrase)))
   157 		{
   158 			ParseWarning("Skipping duplicate phrase \"%s\" on line %d.", name, m_CurLine);
   159 			/* :IDEA: prevent memory waste by seeking backwards in memtable? */
   160 			m_CurPhrase = -1;
   161 		} else {
   162 			/* Initialize new phrase */
   163 			trans_t *pTrans;
   164 	
   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;
   170 	
   171 			for (unsigned int i=0; i<m_LangCount; i++)
   172 			{
   173 				pTrans[i].stridx = -1;
   174 			}
   175 			m_LastPhraseString.assign(name);
   176 		}
   177 	} else if (m_ParseState == PPS_InPhrase) {
   178 		ParseError("Phrase sections may not have sub-sections");
   179 		return SMCParse_HaltFail;
   180 	}
   181 
   182 	if (!recognized)
   183 	{
   184 		ParseWarning("Ignoring invalid section \"%s\" on line %d.", name, m_CurLine);
   185 	}
   186 
   187 	return SMCParse_Continue;
   188 }
   189 
   190 SMCParseResult CPhraseFile::ReadSMC_KeyValue(const char *key, const char *value, bool key_quotes, bool value_quotes)
   191 {
   192 	/* See if we are ignoring a phrase */
   193 	if (!m_CurPhrase)
   194 	{
   195 		return SMCParse_Continue;
   196 	}
   197 
   198 	phrase_t *pPhrase = (phrase_t *)m_pMemory->GetAddress(m_CurPhrase);
   199 	
   200 	if (key[0] == '#' && strcmp(key, "#format") == 0)
   201 	{
   202 		if (pPhrase->fmt_list != -1)
   203 		{
   204 			ParseWarning("Ignoring duplicated #format property on line %d", m_CurLine);
   205 			return SMCParse_Continue;
   206 		}
   207 
   208 		if (pPhrase->translations > 0)
   209 		{
   210 			ParseWarning("#format property should come before translations on line %d, ignoring", m_CurLine);
   211 			return SMCParse_Continue;
   212 		}
   213 
   214 		/* Do an initial browsing for error checking and what not */
   215 		enum ParseStates
   216 		{
   217 			Parse_None,
   218 			Parse_Index,
   219 			Parse_Format,
   220 		};
   221 
   222 		ParseStates state = Parse_None;
   223 
   224 		const char *old_value = value;
   225 		while (*value != '\0')
   226 		{
   227 			if (state == Parse_None)
   228 			{
   229 				if (*value == '{')
   230 				{
   231 					pPhrase->fmt_count++;
   232 					state = Parse_Index;
   233 				} else if (*value == ',') {
   234 					/* Do nothing */
   235 				} else {
   236 					unsigned int bytes = g_TextParser.GetUTF8CharBytes(value);
   237 					if (bytes != 1 || !isalpha(*value))
   238 					{
   239 						ParseWarning("Invalid token '%c' in #format property on line %d.", *value, m_CurLine);
   240 					}
   241 				}
   242 			} else if (state == Parse_Index) {
   243 				if (*value == ':')
   244 				{
   245 					state = Parse_Format;
   246 					if (value - old_value >= 15)
   247 					{
   248 						ParseWarning("Too many digits in format index on line %d, phrase will be ignored.", m_CurLine);
   249 						m_CurPhrase = -1;
   250 						return SMCParse_Continue;
   251 					}
   252 				} else {
   253 					unsigned int bytes = g_TextParser.GetUTF8CharBytes(value);
   254 					if (bytes != 1 || !isdigit(*value))
   255 					{
   256 						ParseWarning("Token '%c' in #format property on line %d is not a digit, phrase will be ignored.",
   257 									*value,
   258 									m_CurLine);
   259 						m_CurPhrase = -1;
   260 						return SMCParse_Continue;
   261 					}
   262 				}
   263 			} else if (state == Parse_Format) {
   264 				if (*value == '}')
   265 				{
   266 					state = Parse_None;
   267 				}
   268 			}
   269 			value++;
   270 		}
   271 
   272 		if (state != Parse_None)
   273 		{
   274 			/* Moose clam cow. */
   275 			ParseWarning("Unterminated format string on line %d, phrase will be ignored.", m_CurLine);
   276 			m_CurPhrase = -1;
   277 			return SMCParse_Continue;
   278 		}
   279 		value = old_value;
   280 
   281 		/* Allocate the format table */
   282 		char fmt_buf[16];
   283 		int *fmt_list;
   284 		pPhrase->fmt_list = m_pMemory->CreateMem(sizeof(int) * pPhrase->fmt_count, (void **)&fmt_list);
   285 
   286 		/* Initialize */
   287 		for (size_t i=0; i<pPhrase->fmt_count; i++)
   288 		{
   289 			fmt_list[i] = -1;
   290 		}
   291 
   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;
   297 		state = Parse_None;
   298 		while (*in_ptr != '\0')
   299 		{
   300 			if (state == Parse_None)
   301 			{
   302 				if (*in_ptr == '{')
   303 				{
   304 					state = Parse_Index;
   305 					idx_ptr = NULL;
   306 				}
   307 			} else if (state == Parse_Index) {
   308 				if (*in_ptr == ':')
   309 				{
   310 					/* Check the number! */
   311 					if (!idx_ptr)
   312 					{
   313 						ParseWarning("Format property contains unindexed format string on line %d, phrase will be ignored.", m_CurLine);
   314 						m_CurPhrase = -1;
   315 						return SMCParse_Continue;
   316 					}
   317 					long idx = strtol(idx_ptr, NULL, 10);
   318 					if (idx < 1 || idx > (long)pPhrase->fmt_count)
   319 					{
   320 						ParseWarning("Format property contains invalid index '%d' on line %d, phrase will be ignored.", idx, m_CurLine);
   321 						m_CurPhrase = -1;
   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);
   325 						m_CurPhrase = -1;
   326 						return SMCParse_Continue;
   327 					}
   328 					cur_idx = (unsigned int)idx;
   329 					state = Parse_Format;
   330 					out_ptr = NULL;
   331 				} else if (!idx_ptr) {
   332 					idx_ptr = in_ptr;
   333 				}
   334 			} else if (state == Parse_Format) {
   335 				if (*in_ptr == '}')
   336 				{
   337 					if (!out_ptr)
   338 					{
   339 						ParseWarning("Format property contains empty format string on line %d, phrase will be ignored.", m_CurLine);
   340 						m_CurPhrase = -1;
   341 						return SMCParse_Continue;
   342 					}
   343 					*out_ptr = '\0';
   344 					state = Parse_None;
   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);
   348 				} else {
   349 					if (!out_ptr)
   350 					{
   351 						out_ptr = fmt_buf;
   352 						*out_ptr++ = '%';
   353 					}
   354 					/* Check length ... */
   355 					if ((unsigned)(out_ptr - fmt_buf) >= sizeof(fmt_buf) - 1)
   356 					{
   357 						ParseWarning("Format property contains format string that exceeds maximum length on line %d, phrase will be ignored.",
   358 									 m_CurLine);
   359 						m_CurPhrase = -1;
   360 						return SMCParse_Continue;
   361 					}
   362 					*out_ptr++ = *in_ptr;
   363 				}
   364 			}
   365 			in_ptr++;
   366 		}
   367 
   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.
   370 		 */
   371 		for (size_t i=0; i<pPhrase->fmt_count; i++)
   372 		{
   373 			if (fmt_list[i] == -1)
   374 			{
   375 				ParseWarning("Format property contains no string for index %d on line %d, phrase will be ignored.",
   376 							 i + 1,
   377 							 m_CurLine);
   378 				m_CurPhrase = -1;
   379 				return SMCParse_Continue;
   380 			}
   381 		}
   382 	} else {
   383 		size_t len = strlen(key);
   384 		if (len != 2)
   385 		{
   386 			ParseWarning("Ignoring translation to invalid language \"%s\" on line %d.", key, m_CurLine);
   387 			return SMCParse_Continue;
   388 		}
   389 
   390 		unsigned int lang;
   391 		if (!m_pTranslator->GetLanguageByCode(key, &lang))
   392 		{
   393 			/* Ignore if we don't have a language.
   394 			 * :IDEA: issue a one-time alert?
   395 			 */
   396 			return SMCParse_Continue;
   397 		}
   398 
   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 
   401 		 */
   402 		len = strlen(value) + pPhrase->fmt_bytes + 1;
   403 		char *out_buf;
   404 		int out_idx;
   405 
   406 		out_idx = m_pMemory->CreateMem(len, (void **)&out_buf);
   407 
   408 		int *fmt_order;
   409 		int *fmt_list = (int *)m_pMemory->GetAddress(pPhrase->fmt_list);
   410 		trans_t *pTrans = (trans_t *)m_pMemory->GetAddress(pPhrase->trans_tbl);
   411 
   412 		pTrans = &pTrans[lang];
   413 		pTrans->stridx = out_idx;
   414 
   415 		bool params[MAX_TRANSLATE_PARAMS];
   416 
   417 		/* Build the format order list, if necessary */
   418 		if (fmt_list)
   419 		{
   420 			pTrans->fmt_order = m_pMemory->CreateMem(pPhrase->fmt_count * sizeof(int), (void **)&fmt_order);
   421 
   422 			for (unsigned int i=0; i<pPhrase->fmt_count; i++)
   423 			{
   424 				fmt_order[i] = -1;
   425 			}
   426 			memset(&params[0], 0, sizeof(params));
   427 		}
   428 
   429 		const char *in_ptr = value;
   430 		char *out_ptr = out_buf;
   431 		unsigned int order_idx = 0;
   432 		while (*in_ptr != '\0')
   433 		{
   434 			if (*in_ptr == '\\')
   435 			{
   436 				switch (*(in_ptr + 1))
   437 				{
   438 				case '\n':
   439 					*out_ptr++ = '\n';
   440 					break;
   441 				case '\t':
   442 					*out_ptr++ = '\t';
   443 					break;
   444 				case '\r':
   445 					*out_ptr++ = '\r';
   446 					break;
   447 				case '{':
   448 					*out_ptr++ = '{';
   449 					break;
   450 				default:
   451 					/* Copy both bytes since we don't know what's going on */
   452 					*out_ptr++ = *in_ptr++;
   453 					*out_ptr++ = *in_ptr;
   454 					break;
   455 				}
   456 				/* Skip past the last byte read */
   457 				in_ptr++;
   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;
   462 				unsigned int bytes;
   463 				while (*in_ptr != '\0')
   464 				{
   465 					bytes = g_TextParser.GetUTF8CharBytes(in_ptr);
   466 					if (bytes != 1)
   467 					{
   468 						goto scrap_point;
   469 					}
   470 					if (*in_ptr == '}')
   471 					{
   472 						/* Did we get an index? */
   473 						if (in_ptr == digit_start)
   474 						{
   475 							goto scrap_point;
   476 						}
   477 						/* Is it valid? */
   478 						long idx = strtol(digit_start, NULL, 10);
   479 						if (idx < 1 || idx > (int)pPhrase->fmt_count)
   480 						{
   481 							goto scrap_point;
   482 						}
   483 						if (params[idx-1])
   484 						{
   485 							goto scrap_point;
   486 						}
   487 
   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]));
   492 						/* Mark as used */
   493 						params[idx-1] = true;
   494 
   495 						goto cont_loop;
   496 					}
   497 					in_ptr++;
   498 				}
   499 scrap_point:
   500 				/* Pretend none of this ever happened.  Move along now! */
   501 				in_ptr = scrap_in_point;
   502 				*out_ptr++ = *in_ptr;
   503 			} else {
   504 				*out_ptr++ = *in_ptr;
   505 			}
   506 cont_loop:
   507 			in_ptr++;
   508 		}
   509 		*out_ptr = '\0';
   510 		pPhrase->translations++;
   511 	}
   512 
   513 	return SMCParse_Continue;
   514 }
   515 
   516 SMCParseResult CPhraseFile::ReadSMC_LeavingSection()
   517 {
   518 	if (m_ParseState == PPS_InPhrase)
   519 	{
   520 		if (m_CurPhrase == -1 && m_LastPhraseString.size())
   521 		{
   522 			sm_trie_delete(m_pPhraseLookup, m_LastPhraseString.c_str());
   523 		}
   524 		m_CurPhrase = -1;
   525 		m_ParseState = PPS_Phrases;
   526 		m_LastPhraseString.assign("");
   527 	} else if (m_ParseState == PPS_Phrases) {
   528 		m_ParseState = PPS_None;
   529 	}
   530 
   531 	return SMCParse_Continue;
   532 }
   533 
   534 void CPhraseFile::ReadSMC_ParseEnd(bool halted, bool failed)
   535 {
   536 	/* Check to see if we have any dangling phrases that weren't completed, and scrap them */
   537 	if ((halted || failed) && m_LastPhraseString.size())
   538 	{
   539 		sm_trie_delete(m_pPhraseLookup, m_LastPhraseString.c_str());
   540 	}
   541 }
   542 
   543 TransError CPhraseFile::GetTranslation(const char *szPhrase, unsigned int lang_id, Translation *pTrans)
   544 {
   545 	if (lang_id >= m_LangCount)
   546 	{
   547 		return Trans_BadLanguage;
   548 	}
   549 
   550 	void *object;
   551 	if (!sm_trie_retrieve(m_pPhraseLookup, szPhrase, &object))
   552 	{
   553 		return Trans_BadPhrase;
   554 	}
   555 
   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);
   558 
   559 	trans = &trans[lang_id];
   560 
   561 	if (trans->stridx == -1)
   562 	{
   563 		return Trans_BadPhraseLanguage;
   564 	}
   565 
   566 	pTrans->fmt_order = (int *)m_pMemory->GetAddress(trans->fmt_order);
   567 	pTrans->fmt_count = pPhrase->fmt_count;
   568 
   569 	pTrans->szPhrase = m_pStringTab->GetString(trans->stridx);
   570 
   571 	return Trans_Okay;
   572 }
   573 
   574 const char *CPhraseFile::GetFilename()
   575 {
   576 	return m_File.c_str();
   577 }
   578 
   579 /**************************
   580  ** MAIN TRANSLATOR CODE **
   581  **************************/
   582 
   583 Translator::Translator() : m_ServerLang(LANGUAGE_ENGLISH)
   584 {
   585 	m_pStringTab = new BaseStringTable(2048);
   586 	m_pLCodeLookup = sm_trie_create();
   587 	strncopy(m_InitialLang, "en", sizeof(m_InitialLang));
   588 }
   589 
   590 Translator::~Translator()
   591 {
   592 	for (size_t i=0; i<m_Files.size(); i++)
   593 	{
   594 		delete m_Files[i];
   595 	}
   596 
   597 	for (size_t i=0; i<m_Languages.size(); i++)
   598 	{
   599 		delete m_Languages[i];
   600 	}
   601 
   602 	sm_trie_destroy(m_pLCodeLookup);
   603 
   604 	delete m_pStringTab;
   605 }
   606 
   607 ConfigResult Translator::OnSourceModConfigChanged(const char *key, 
   608 									  const char *value, 
   609 									  ConfigSource source, 
   610 									  char *error, 
   611 									  size_t maxlength)
   612 {
   613 	if (strcasecmp(key, "ServerLang") == 0)
   614 	{
   615 		if (source == ConfigSource_Console)
   616 		{
   617 			unsigned int index;
   618 			if (!GetLanguageByCode(value, &index))
   619 			{
   620 				UTIL_Format(error, maxlength, "Language code \"%s\" is not registered", value);
   621 				return ConfigResult_Reject;
   622 			}
   623 
   624 			m_ServerLang = index;
   625 		} else {
   626 			strncopy(m_InitialLang, value, sizeof(m_InitialLang));
   627 		}
   628 
   629 		return ConfigResult_Accept;
   630 	}
   631 
   632 	return ConfigResult_Ignore;
   633 }
   634 
   635 void Translator::OnSourceModLevelChange(const char *mapName)
   636 {
   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);
   641 }
   642 
   643 void Translator::OnSourceModAllInitialized()
   644 {
   645 	AddLanguage("en", "English");
   646 	unsigned int id = FindOrAddPhraseFile("core.cfg");
   647 	g_pCorePhrases = GetFileByIndex(id);
   648 }
   649 
   650 bool Translator::GetLanguageByCode(const char *code, unsigned int *index)
   651 {
   652 	void *_index;
   653 
   654 	if (!sm_trie_retrieve(m_pLCodeLookup, code, &_index))
   655 	{
   656 		return false;
   657 	}
   658 
   659 	if (index)
   660 	{
   661 		*index = reinterpret_cast<unsigned int>(_index);
   662 	}
   663 
   664 	return true;
   665 }
   666 
   667 unsigned int Translator::GetLanguageCount()
   668 {
   669 	return (unsigned int)m_Languages.size();
   670 }
   671 
   672 BaseStringTable *Translator::GetStringTable()
   673 {
   674 	return m_pStringTab;
   675 }
   676 
   677 unsigned int Translator::FindOrAddPhraseFile(const char *phrase_file)
   678 {
   679 	for (size_t i=0; i<m_Files.size(); i++)
   680 	{
   681 		if (strcmp(m_Files[i]->GetFilename(), phrase_file) == 0)
   682 		{
   683 			return (unsigned int)i;
   684 		}
   685 	}
   686 
   687 	CPhraseFile *pFile = new CPhraseFile(this, phrase_file);
   688 	unsigned int idx = (unsigned int)m_Files.size();
   689 	
   690 	m_Files.push_back(pFile);
   691 
   692 	pFile->ReparseFile();
   693 
   694 	return idx;
   695 }
   696 
   697 void Translator::RebuildLanguageDatabase(const char *lang_header_file)
   698 {
   699 	/* Erase everything we have */
   700 	sm_trie_destroy(m_pLCodeLookup);
   701 	m_pLCodeLookup = sm_trie_create();
   702 	m_pStringTab->Reset();
   703 
   704 	for (size_t i=0; i<m_Languages.size(); i++)
   705 	{
   706 		delete m_Languages[i];
   707 	}
   708 	m_Languages.clear();
   709 
   710 	/* Start anew */
   711 	SMCParseError err;
   712 	unsigned int line=0, col=0;
   713 	if ((err=g_TextParser.ParseFile_SMC(lang_header_file, this, &line, &col)) != SMCParse_Okay)
   714 	{
   715 		const char *str_err = g_TextParser.GetSMCErrorString(err);
   716 		if (!str_err)
   717 		{
   718 			str_err = m_CustomError.c_str();
   719 		}
   720 
   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);
   723 	}
   724 
   725 	void *serverLang;
   726 
   727 	if (!sm_trie_retrieve(m_pLCodeLookup, m_InitialLang, &serverLang))
   728 	{
   729 		g_Logger.LogError("Server language was set to bad language \"%s\" -- reverting to English", m_InitialLang);
   730 
   731 		strncopy(m_InitialLang, "en", sizeof(m_InitialLang));
   732 		m_ServerLang = LANGUAGE_ENGLISH;
   733 	}
   734 
   735 	m_ServerLang = reinterpret_cast<unsigned int>(serverLang);
   736 
   737 	if (!m_Languages.size())
   738 	{
   739 		g_Logger.LogError("[SM] Fatal error, no languages found! Translation will not work.");
   740 	}
   741 
   742 	for (size_t i=0; i<m_Files.size(); i++)
   743 	{
   744 		m_Files[i]->ReparseFile();
   745 	}
   746 }
   747 
   748 void Translator::ReadSMC_ParseStart()
   749 {
   750 	m_InLanguageSection = false;
   751 	m_CustomError.clear();
   752 }
   753 
   754 SMCParseResult Translator::ReadSMC_NewSection(const char *name, bool opt_quotes)
   755 {
   756 	if (!m_InLanguageSection)
   757 	{
   758 		if (strcmp(name, "Languages") == 0)
   759 		{
   760 			m_InLanguageSection = true;
   761 		}
   762 	}
   763 
   764 	if (!m_InLanguageSection)
   765 	{
   766 		g_Logger.LogError("[SM] Warning: Unrecognized section \"%s\" in languages.cfg", name);
   767 	}
   768 
   769 	return SMCParse_Continue;
   770 }
   771 
   772 SMCParseResult Translator::ReadSMC_LeavingSection()
   773 {
   774 	m_InLanguageSection = false;
   775 
   776 	return SMCParse_Continue;
   777 }
   778 
   779 SMCParseResult Translator::ReadSMC_KeyValue(const char *key, const char *value, bool key_quotes, bool value_quotes)
   780 {
   781 	size_t len = strlen(key);
   782 
   783 	if (len != 2)
   784 	{
   785 		g_Logger.LogError("[SM] Warning encountered parsing languages.cfg file.");
   786 		g_Logger.LogError("[SM] Invalid language code \"%s\" is being ignored.", key);
   787 	}
   788 
   789 	AddLanguage(key, value);
   790 
   791 	return SMCParse_Continue;
   792 }
   793 
   794 bool Translator::AddLanguage(const char *langcode, const char *description)
   795 {
   796 	if (sm_trie_retrieve(m_pLCodeLookup, langcode, NULL))
   797 	{
   798 		return false;
   799 	}
   800 
   801 	Language *pLanguage = new Language;
   802 	unsigned int idx = m_Languages.size();
   803 
   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);
   808 
   809 	sm_trie_insert(m_pLCodeLookup, langcode, reinterpret_cast<void *>(idx));
   810 
   811 	m_Languages.push_back(pLanguage);
   812 
   813 	return true;
   814 }
   815 
   816 CPhraseFile *Translator::GetFileByIndex(unsigned int index)
   817 {
   818 	if (index >= m_Files.size())
   819 	{
   820 		return NULL;
   821 	}
   822 
   823 	return m_Files[index];
   824 }
   825 
   826 size_t Translator::Translate(char *buffer, size_t maxlength, void **params, const Translation *pTrans)
   827 {
   828 	void *new_params[MAX_TRANSLATE_PARAMS];
   829 
   830 	/* Rewrite the parameter order */
   831 	for (unsigned int i=0; i<pTrans->fmt_count; i++)
   832 	{
   833 		new_params[i] = params[pTrans->fmt_order[i]];
   834 	}
   835 
   836 	return gnprintf(buffer, maxlength, pTrans->szPhrase, new_params);
   837 }
   838 
   839 TransError Translator::CoreTrans(int client, 
   840 								  char *buffer, 
   841 								  size_t maxlength, 
   842 								  const char *phrase, 
   843 								  void **params, 
   844 								  size_t *outlen)
   845 {
   846 	/* :TODO: do language stuff here */
   847 
   848 	if (!g_pCorePhrases)
   849 	{
   850 		return Trans_BadPhraseFile;
   851 	}
   852 
   853 	Translation trans;
   854 	TransError err;
   855 	
   856 	/* Using server lang temporarily until client lang stuff is implemented */
   857 	if ((err=g_pCorePhrases->GetTranslation(phrase, m_ServerLang, &trans)) != Trans_Okay)
   858 	{
   859 		return err;
   860 	}
   861 
   862 	size_t len = Translate(buffer, maxlength, params, &trans);
   863 
   864 	if (outlen)
   865 	{
   866 		*outlen = len;
   867 	}
   868 
   869 	return Trans_Okay;
   870 }
   871 
   872 unsigned int Translator::GetServerLanguage()
   873 {
   874 	return m_ServerLang;
   875 }