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
)
20 m_Hash
= str_quickhash(m_pDefaultStr
);
24 void CLocConstString::Reload()
26 m_Version
= g_Localization
.Version();
27 const char *pNewStr
= g_Localization
.FindString(m_Hash
);
28 m_pCurrentStr
= pNewStr
;
30 m_pCurrentStr
= m_pDefaultStr
;
33 CLocalizationDatabase::CLocalizationDatabase()
39 void CLocalizationDatabase::AddString(const char *pOrgStr
, const char *pNewStr
)
42 s
.m_Hash
= str_quickhash(pOrgStr
);
43 s
.m_Replacement
= *pNewStr
? pNewStr
: pOrgStr
;
47 bool CLocalizationDatabase::Load(const char *pFilename
, IStorage
*pStorage
, IConsole
*pConsole
)
49 // empty string means unload
57 IOHANDLE IoHandle
= pStorage
->OpenFile(pFilename
, IOFLAG_READ
, IStorage::TYPE_ALL
);
62 str_format(aBuf
, sizeof(aBuf
), "loaded '%s'", pFilename
);
63 pConsole
->Print(IConsole::OUTPUT_LEVEL_ADDINFO
, "localization", aBuf
);
67 CLineReader LineReader
;
68 LineReader
.Init(IoHandle
);
70 while((pLine
= LineReader
.Get()))
72 if(!str_length(pLine
))
75 if(pLine
[0] == '#') // skip comments
78 str_copy(aOrigin
, pLine
, sizeof(aOrigin
));
79 char *pReplacement
= LineReader
.Get();
82 pConsole
->Print(IConsole::OUTPUT_LEVEL_ADDINFO
, "localization", "unexpected end of file");
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
);
94 AddString(aOrigin
, pReplacement
);
98 m_CurrentVersion
= ++m_VersionCounter
;
102 const char *CLocalizationDatabase::FindString(unsigned Hash
)
105 String
.m_Hash
= Hash
;
106 sorted_array
<CString
>::range r
= ::find_binary(m_Strings
.all(), String
);
109 return r
.front().m_Replacement
;
112 CLocalizationDatabase g_Localization
;