fixed editor zooming if gui is not active
[twcon.git] / src / game / localization.cpp
blob8ab8831d0d48d4a932145d5382750dc064e73a5e
1 /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */
2 /* If you are missing that file, acquire a complete release at teeworlds.com. */
4 #include "localization.h"
5 #include <base/tl/algorithm.h>
7 #include <engine/shared/linereader.h>
8 #include <engine/console.h>
9 #include <engine/storage.h>
11 const char *Localize(const char *pStr)
13 const char *pNewStr = g_Localization.FindString(str_quickhash(pStr));
14 return pNewStr ? pNewStr : pStr;
17 CLocConstString::CLocConstString(const char *pStr)
19 m_pDefaultStr = pStr;
20 m_Hash = str_quickhash(m_pDefaultStr);
21 m_Version = -1;
24 void CLocConstString::Reload()
26 m_Version = g_Localization.Version();
27 const char *pNewStr = g_Localization.FindString(m_Hash);
28 m_pCurrentStr = pNewStr;
29 if(!m_pCurrentStr)
30 m_pCurrentStr = m_pDefaultStr;
33 CLocalizationDatabase::CLocalizationDatabase()
35 m_VersionCounter = 0;
36 m_CurrentVersion = 0;
39 void CLocalizationDatabase::AddString(const char *pOrgStr, const char *pNewStr)
41 CString s;
42 s.m_Hash = str_quickhash(pOrgStr);
43 s.m_Replacement = *pNewStr ? pNewStr : pOrgStr;
44 m_Strings.add(s);
47 bool CLocalizationDatabase::Load(const char *pFilename, IStorage *pStorage, IConsole *pConsole)
49 // empty string means unload
50 if(pFilename[0] == 0)
52 m_Strings.clear();
53 m_CurrentVersion = 0;
54 return true;
57 IOHANDLE IoHandle = pStorage->OpenFile(pFilename, IOFLAG_READ, IStorage::TYPE_ALL);
58 if(!IoHandle)
59 return false;
61 char aBuf[256];
62 str_format(aBuf, sizeof(aBuf), "loaded '%s'", pFilename);
63 pConsole->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "localization", aBuf);
64 m_Strings.clear();
66 char aOrigin[512];
67 CLineReader LineReader;
68 LineReader.Init(IoHandle);
69 char *pLine;
70 while((pLine = LineReader.Get()))
72 if(!str_length(pLine))
73 continue;
75 if(pLine[0] == '#') // skip comments
76 continue;
78 str_copy(aOrigin, pLine, sizeof(aOrigin));
79 char *pReplacement = LineReader.Get();
80 if(!pReplacement)
82 pConsole->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "localization", "unexpected end of file");
83 break;
86 if(pReplacement[0] != '=' || pReplacement[1] != '=' || pReplacement[2] != ' ')
88 str_format(aBuf, sizeof(aBuf), "malform replacement line for '%s'", aOrigin);
89 pConsole->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "localization", aBuf);
90 continue;
93 pReplacement += 3;
94 AddString(aOrigin, pReplacement);
96 io_close(IoHandle);
98 m_CurrentVersion = ++m_VersionCounter;
99 return true;
102 const char *CLocalizationDatabase::FindString(unsigned Hash)
104 CString String;
105 String.m_Hash = Hash;
106 sorted_array<CString>::range r = ::find_binary(m_Strings.all(), String);
107 if(r.empty())
108 return 0;
109 return r.front().m_Replacement;
112 CLocalizationDatabase g_Localization;