VirtualBox

source: vbox/trunk/src/VBox/Main/src-all/QMTranslatorImpl.cpp@ 79849

Last change on this file since 79849 was 76553, checked in by vboxsync, 6 years ago

scm --update-copyright-year

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 12.8 KB
Line 
1/* $Id: QMTranslatorImpl.cpp 76553 2019-01-01 01:45:53Z vboxsync $ */
2/** @file
3 * VirtualBox API translation handling class
4 */
5
6/*
7 * Copyright (C) 2014-2019 Oracle Corporation
8 *
9 * This file is part of VirtualBox Open Source Edition (OSE), as
10 * available from http://www.virtualbox.org. This file is free software;
11 * you can redistribute it and/or modify it under the terms of the GNU
12 * General Public License (GPL) as published by the Free Software
13 * Foundation, in version 2 as it comes in the "COPYING" file of the
14 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
15 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
16 */
17
18#include <vector>
19#include <set>
20#include <algorithm>
21#include <iterator>
22#include <iprt/errcore.h>
23#include <iprt/file.h>
24#include <iprt/asm.h>
25#include <VBox/com/string.h>
26#include <VBox/log.h>
27#include <QMTranslator.h>
28
29/* QM File Magic Number */
30static const size_t MagicLength = 16;
31static const uint8_t Magic[MagicLength] =
32{
33 0x3c, 0xb8, 0x64, 0x18, 0xca, 0xef, 0x9c, 0x95,
34 0xcd, 0x21, 0x1c, 0xbf, 0x60, 0xa1, 0xbd, 0xdd
35};
36
37/* Used internally */
38class QMException : public std::exception
39{
40 const char *m_str;
41public:
42 QMException(const char *str) : m_str(str) {}
43 virtual const char *what() const throw() { return m_str; }
44};
45
46/* Bytes stream. Used by the parser to iterate through the data */
47class QMBytesStream
48{
49 size_t m_cbSize;
50 const uint8_t * const m_dataStart;
51 const uint8_t *m_iter;
52 const uint8_t *m_end;
53
54 /* Function stub for transform method */
55 static uint16_t func_BE2H_U16(uint16_t value)
56 {
57 return RT_BE2H_U16(value);
58 }
59
60public:
61
62 QMBytesStream(const uint8_t *const dataStart, size_t cbSize) :
63 m_cbSize(dataStart ? cbSize : 0),
64 m_dataStart(dataStart),
65 m_iter(dataStart)
66 {
67 setEnd();
68 }
69
70 /* Sets end pointer
71 * Used in message reader to detect the end of message block */
72 inline void setEnd(size_t pos = 0)
73 {
74 m_end = m_dataStart + (pos && pos < m_cbSize ? pos : m_cbSize);
75 }
76
77 inline uint8_t read8()
78 {
79 checkSize(1);
80 return *m_iter++;
81 }
82
83 inline uint32_t read32()
84 {
85 checkSize(4);
86 uint32_t result = *reinterpret_cast<const uint32_t *>(m_iter);
87 m_iter += 4;
88 return RT_BE2H_U32(result);
89 }
90
91 /* Reads string in UTF16 and converts it into a UTF8 string */
92 inline com::Utf8Str readUtf16String()
93 {
94 uint32_t size = read32();
95 checkSize(size);
96 if (size & 1) throw QMException("Incorrect string size");
97 std::vector<uint16_t> wstr;
98 wstr.reserve(size / 2);
99
100 /* We cannot convert to host endianess without copying the data
101 * since the file might be mapped to the memory and any memory
102 * change will lead to the change of the file. */
103 std::transform(reinterpret_cast<const uint16_t *>(m_iter),
104 reinterpret_cast<const uint16_t *>(m_iter + size),
105 std::back_inserter(wstr),
106 func_BE2H_U16);
107 m_iter += size;
108 return com::Utf8Str((CBSTR) &wstr.front(), wstr.size());
109 }
110
111 /* Reads string in one-byte encoding
112 * The string is assumed to be in ISO-8859-1 encoding */
113 inline com::Utf8Str readString()
114 {
115 uint32_t size = read32();
116 checkSize(size);
117 com::Utf8Str result(reinterpret_cast<const char *>(m_iter), size);
118 m_iter += size;
119 return result;
120 }
121
122 /* Checks the magic number
123 * Should be called when in the beginning of the data */
124 inline void checkMagic()
125 {
126 checkSize(MagicLength);
127 if (memcmp(&(*m_iter), Magic, MagicLength)) throw QMException("Wrong magic number");
128 m_iter += MagicLength;
129 }
130
131 /* Has we reached the end pointer? */
132 inline bool hasFinished() { return m_iter == m_end; }
133
134 /* Returns current stream position */
135 inline size_t tellPos() { return m_iter - m_dataStart; }
136
137 /* Moves current pointer to a desired position */
138 inline void seek(int pos) { m_iter += pos; }
139
140 /* Checks whether stream has enough data to read size bytes */
141 inline void checkSize(int size)
142 {
143 if (m_end - m_iter < size) throw QMException("Incorrect item size");
144 }
145};
146
147/* Internal QMTranslator implementation */
148class QMTranslator_Impl
149{
150 struct QMMessage
151 {
152 /* Everything is in UTF-8 */
153 com::Utf8Str strContext;
154 com::Utf8Str strTranslation;
155 com::Utf8Str strComment;
156 com::Utf8Str strSource;
157 uint32_t hash;
158 QMMessage() : hash(0) {}
159 };
160
161 struct HashOffset
162 {
163 uint32_t hash;
164 uint32_t offset;
165
166 HashOffset(uint32_t _hash = 0, uint32_t _offs = 0) : hash(_hash), offset(_offs) {}
167
168 bool operator<(const HashOffset &obj) const
169 {
170 return (hash != obj.hash ? hash < obj.hash : offset < obj.offset);
171 }
172
173 };
174
175 typedef std::set<HashOffset> QMHashSet;
176 typedef QMHashSet::const_iterator QMHashSetConstIter;
177 typedef std::vector<QMMessage> QMMessageArray;
178
179 QMHashSet m_hashSet;
180 QMMessageArray m_messageArray;
181
182public:
183
184 QMTranslator_Impl() {}
185
186 const char *translate(const char *pszContext,
187 const char *pszSource,
188 const char *pszDisamb) const
189 {
190 QMHashSetConstIter iter;
191 QMHashSetConstIter lowerIter, upperIter;
192
193 do {
194 uint32_t hash = calculateHash(pszSource, pszDisamb);
195 lowerIter = m_hashSet.lower_bound(HashOffset(hash, 0));
196 upperIter = m_hashSet.upper_bound(HashOffset(hash, UINT32_MAX));
197
198 for (iter = lowerIter; iter != upperIter; ++iter)
199 {
200 const QMMessage &message = m_messageArray[iter->offset];
201 if ((!pszContext || !*pszContext || message.strContext == pszContext) &&
202 message.strSource == pszSource &&
203 ((pszDisamb && !*pszDisamb) || message.strComment == pszDisamb))
204 break;
205 }
206
207 /* Try without disambiguating comment if it isn't empty */
208 if (pszDisamb)
209 {
210 if (!*pszDisamb) pszDisamb = 0;
211 else pszDisamb = "";
212 }
213
214 } while (iter == upperIter && pszDisamb);
215
216 return (iter != upperIter ? m_messageArray[iter->offset].strTranslation.c_str() : "");
217 }
218
219 void load(QMBytesStream &stream)
220 {
221 /* Load into local variables. If we failed during the load,
222 * it would allow us to keep the object in a valid (previous) state. */
223 QMHashSet hashSet;
224 QMMessageArray messageArray;
225
226 stream.checkMagic();
227
228 while (!stream.hasFinished())
229 {
230 uint32_t sectionCode = stream.read8();
231 uint32_t sLen = stream.read32();
232
233 /* Hashes and Context sections are ignored. They contain hash tables
234 * to speed-up search which is not useful since we recalculate all hashes
235 * and don't perform context search by hash */
236 switch (sectionCode)
237 {
238 case Messages:
239 parseMessages(stream, &hashSet, &messageArray, sLen);
240 break;
241 case Hashes:
242 /* Only get size information to speed-up vector filling
243 * if Hashes section goes in the file before Message section */
244 m_messageArray.reserve(sLen >> 3);
245 RT_FALL_THRU();
246 case Context:
247 stream.seek(sLen);
248 break;
249 default:
250 throw QMException("Unkown section");
251 }
252 }
253 /* Store the data into member variables.
254 * The following functions never generate exceptions */
255 m_hashSet.swap(hashSet);
256 m_messageArray.swap(messageArray);
257 }
258
259private:
260
261 /* Some QM stuff */
262 enum SectionType
263 {
264 Hashes = 0x42,
265 Messages = 0x69,
266 Contexts = 0x2f
267 };
268
269 enum MessageType
270 {
271 End = 1,
272 SourceText16 = 2,
273 Translation = 3,
274 Context16 = 4,
275 Hash = 5,
276 SourceText = 6,
277 Context = 7,
278 Comment = 8
279 };
280
281 /* Read messages from the stream. */
282 static void parseMessages(QMBytesStream &stream, QMHashSet * const hashSet, QMMessageArray * const messageArray, size_t cbSize)
283 {
284 stream.setEnd(stream.tellPos() + cbSize);
285 uint32_t cMessage = 0;
286 while (!stream.hasFinished())
287 {
288 QMMessage message;
289 HashOffset hashOffs;
290
291 parseMessageRecord(stream, &message);
292 if (!message.hash)
293 message.hash = calculateHash(message.strSource.c_str(), message.strComment.c_str());
294
295 hashOffs.hash = message.hash;
296 hashOffs.offset = cMessage++;
297
298 hashSet->insert(hashOffs);
299 messageArray->push_back(message);
300 }
301 stream.setEnd();
302 }
303
304 /* Parse one message from the stream */
305 static void parseMessageRecord(QMBytesStream &stream, QMMessage * const message)
306 {
307 while (!stream.hasFinished())
308 {
309 uint8_t type = stream.read8();
310 switch (type)
311 {
312 case End:
313 return;
314 /* Ignored as obsolete */
315 case Context16:
316 case SourceText16:
317 stream.seek(stream.read32());
318 break;
319 case Translation:
320 {
321 com::Utf8Str str = stream.readUtf16String();
322 message->strTranslation.swap(str);
323 break;
324 }
325 case Hash:
326 message->hash = stream.read32();
327 break;
328
329 case SourceText:
330 {
331 com::Utf8Str str = stream.readString();
332 message->strSource.swap(str);
333 break;
334 }
335
336 case Context:
337 {
338 com::Utf8Str str = stream.readString();
339 message->strContext.swap(str);
340 break;
341 }
342
343 case Comment:
344 {
345 com::Utf8Str str = stream.readString();
346 message->strComment.swap(str);
347 break;
348 }
349
350 default:
351 /* Ignore unknown block */
352 LogRel(("QMTranslator::parseMessageRecord(): Unkown message block %x\n", type));
353 break;
354 }
355 }
356 }
357
358 /* Defines the so called `hashpjw' function by P.J. Weinberger
359 [see Aho/Sethi/Ullman, COMPILERS: Principles, Techniques and Tools,
360 1986, 1987 Bell Telephone Laboratories, Inc.] */
361 static uint32_t calculateHash(const char *pszStr1, const char *pszStr2 = 0)
362 {
363 uint32_t hash = 0, g;
364
365 for (const char *pszStr = pszStr1; pszStr != pszStr2; pszStr = pszStr2)
366 for (; pszStr && *pszStr; pszStr++)
367 {
368 hash = (hash << 4) + static_cast<uint8_t>(*pszStr);
369
370 if ((g = hash & 0xf0000000ul) != 0)
371 {
372 hash ^= g >> 24;
373 hash ^= g;
374 }
375 }
376
377 return (hash != 0 ? hash : 1);
378 }
379};
380
381/* Inteface functions implementation */
382QMTranslator::QMTranslator() : _impl(new QMTranslator_Impl) {}
383
384QMTranslator::~QMTranslator() { delete _impl; }
385
386const char *QMTranslator::translate(const char *pszContext, const char *pszSource, const char *pszDisamb) const throw()
387{
388 return _impl->translate(pszContext, pszSource, pszDisamb);
389}
390
391/* The function is noexcept for now but it may be changed
392 * to throw exceptions if required to catch them in another
393 * place. */
394int QMTranslator::load(const char *pszFilename) throw()
395{
396 /* To free safely the file in case of exception */
397 struct FileLoader
398 {
399 uint8_t *data;
400 size_t cbSize;
401 int rc;
402 FileLoader(const char *pszFname)
403 {
404 rc = RTFileReadAll(pszFname, (void**) &data, &cbSize);
405 }
406
407 ~FileLoader()
408 {
409 if (isSuccess())
410 RTFileReadAllFree(data, cbSize);
411 }
412 bool isSuccess() { return RT_SUCCESS(rc); }
413 };
414
415 try
416 {
417 FileLoader loader(pszFilename);
418 if (loader.isSuccess())
419 {
420 QMBytesStream stream(loader.data, loader.cbSize);
421 _impl->load(stream);
422 }
423 return loader.rc;
424 }
425 catch(std::exception &e)
426 {
427 LogRel(("QMTranslator::load() failed to load file '%s', reason: %s\n", pszFilename, e.what()));
428 return VERR_INTERNAL_ERROR;
429 }
430 catch(...)
431 {
432 LogRel(("QMTranslator::load() failed to load file '%s'\n", pszFilename));
433 return VERR_GENERAL_FAILURE;
434 }
435}
Note: See TracBrowser for help on using the repository browser.

© 2024 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette