VirtualBox

source: vbox/trunk/src/VBox/Main/src-all/VirtualBoxTranslator.cpp@ 99425

Last change on this file since 99425 was 98103, checked in by vboxsync, 2 years ago

Copyright year updates by scm.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 19.1 KB
Line 
1/* $Id: VirtualBoxTranslator.cpp 98103 2023-01-17 14:15:46Z vboxsync $ */
2/** @file
3 * VirtualBox Translator class.
4 */
5
6/*
7 * Copyright (C) 2006-2023 Oracle and/or its affiliates.
8 *
9 * This file is part of VirtualBox base platform packages, as
10 * available from https://www.virtualbox.org.
11 *
12 * This program is free software; you can redistribute it and/or
13 * modify it under the terms of the GNU General Public License
14 * as published by the Free Software Foundation, in version 3 of the
15 * License.
16 *
17 * This program is distributed in the hope that it will be useful, but
18 * WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
20 * General Public License for more details.
21 *
22 * You should have received a copy of the GNU General Public License
23 * along with this program; if not, see <https://www.gnu.org/licenses>.
24 *
25 * SPDX-License-Identifier: GPL-3.0-only
26 */
27
28
29/*********************************************************************************************************************************
30* Header Files *
31*********************************************************************************************************************************/
32#define LOG_GROUP LOG_GROUP_MAIN_VIRTUALBOXCLIENT /** @todo add separate logging group! */
33#include "LoggingNew.h"
34
35#include <iprt/asm.h>
36#include <iprt/ctype.h>
37#include <iprt/env.h>
38#include <iprt/err.h>
39#include <iprt/locale.h>
40#include <iprt/once.h>
41#include <iprt/path.h>
42#include <iprt/string.h>
43#include <iprt/thread.h>
44#include <iprt/strcache.h>
45
46#ifdef RT_OS_DARWIN
47#include <CoreFoundation/CFLocale.h>
48#include <CoreFoundation/CFString.h>
49#endif
50
51#include "Global.h"
52#include "VirtualBoxBase.h"
53#include "QMTranslator.h"
54#include "VirtualBoxTranslator.h"
55
56
57/*********************************************************************************************************************************
58* Defined Constants And Macros *
59*********************************************************************************************************************************/
60#define TRANSLATOR_CACHE_SIZE 32
61
62
63/*********************************************************************************************************************************
64* Global Variables *
65*********************************************************************************************************************************/
66/** Init once for the critical section. */
67static RTONCE g_Once = RTONCE_INITIALIZER;
68RTCRITSECTRW VirtualBoxTranslator::s_instanceRwLock;
69VirtualBoxTranslator *VirtualBoxTranslator::s_pInstance = NULL;
70/** TLS index that points to the translated text. */
71static RTTLS g_idxTlsTr = NIL_RTTLS;
72/** TLS index that points to the original text. */
73static RTTLS g_idxTlsSrc = NIL_RTTLS;
74
75
76/**
77 * @callback_method_impl{FNRTONCE}
78 */
79static DECLCALLBACK(int32_t) initLock(void *pvUser)
80{
81 RT_NOREF(pvUser);
82 return VirtualBoxTranslator::initCritSect();
83}
84
85
86/**
87 * Obtains the user language code in ll_CC form depending on platform
88 *
89 * @returns VBox status code
90 * @param pszName The buffer for storing user language code
91 * @param cbName Size of the pszName buffer
92 */
93static int vboxGetDefaultUserLanguage(char *pszName, size_t cbName)
94{
95 AssertReturn(pszName, VERR_INVALID_PARAMETER);
96 AssertReturn(cbName >= 6, VERR_INVALID_PARAMETER); /* 5 chars for language + null termination */
97
98#ifdef RT_OS_WINDOWS
99 if ( GetLocaleInfoA(GetUserDefaultLCID(), LOCALE_SISO639LANGNAME, pszName, (int)cbName) == 3
100 && GetLocaleInfoA(GetUserDefaultLCID(), LOCALE_SISO3166CTRYNAME, &pszName[3], (int)cbName - 4) == 3)
101 {
102 pszName[2] = '_';
103 Assert(RTLOCALE_IS_LANGUAGE2_UNDERSCORE_COUNTRY2(pszName));
104 return VINF_SUCCESS;
105 }
106#elif RT_OS_DARWIN
107 CFLocaleRef locale = CFLocaleCopyCurrent();
108 CFTypeRef localeId = CFLocaleGetValue (locale, kCFLocaleIdentifier);
109 char szLocale[256] = { 0 };
110 if (CFGetTypeID(localeId) == CFStringGetTypeID())
111 CFStringGetCString((CFStringRef)localeId, szLocale, sizeof(szLocale), kCFStringEncodingUTF8);
112 /* Some cleanup */
113 CFRelease(locale);
114 if (szLocale[0] == '\0')
115 {
116 pszName[0] = 'C';
117 pszName[1] = 0;
118 return VINF_SUCCESS;
119 }
120 else
121 return RTStrCopy(pszName, cbName, szLocale);
122
123#elif defined(RT_OS_LINUX) || defined(RT_OS_FREEBSD) || defined(RT_OS_NETBSD) || defined(RT_OS_OPENBSD) || defined(RT_OS_SOLARIS)
124 const char *pszValue = RTEnvGet("LC_ALL");
125 if (pszValue == 0)
126 pszValue = RTEnvGet("LC_MESSAGES");
127 if (pszValue == 0)
128 pszValue = RTEnvGet("LANG");
129 if (pszValue != 0)
130 {
131 /* ignore codepage part, i.e. ignore ".UTF-8" in "ru_RU.UTF-8" */
132 const char *pszDot = strchr(pszValue, '.');
133 size_t cbValue = strlen(pszValue);
134 if (pszDot != NULL)
135 cbValue = RT_MIN(cbValue, (size_t)(pszDot - pszValue));
136
137 if ( ( cbValue == 2
138 && RT_C_IS_LOWER(pszValue[0])
139 && RT_C_IS_LOWER(pszValue[1]))
140 || ( cbValue == 5
141 && RTLOCALE_IS_LANGUAGE2_UNDERSCORE_COUNTRY2(pszValue)))
142 return RTStrCopyEx(pszName, cbName, pszValue, cbValue);
143 }
144#endif
145 return RTLocaleQueryNormalizedBaseLocaleName(pszName, cbName);
146}
147
148VirtualBoxTranslator::VirtualBoxTranslator()
149 : util::RWLockHandle(util::LOCKCLASS_TRANSLATOR)
150 , m_cInstanceRefs(0)
151 , m_pDefaultComponent(NULL)
152 , m_strLanguage("C")
153 , m_hStrCache(NIL_RTSTRCACHE)
154{
155 g_idxTlsTr = RTTlsAlloc();
156 g_idxTlsSrc = RTTlsAlloc();
157 int vrc = RTStrCacheCreate(&m_hStrCache, "API Translation");
158 m_rcCache = vrc;
159 if (RT_FAILURE(vrc))
160 m_hStrCache = NIL_RTSTRCACHE; /* (loadLanguage will fail) */
161 LogFlowFunc(("m_rcCache=%Rrc g_idxTlsTr=%#x g_idxTlsSrc=%#x\n", m_rcCache, g_idxTlsTr, g_idxTlsSrc));
162}
163
164
165VirtualBoxTranslator::~VirtualBoxTranslator()
166{
167 LogFlowFunc(("enter\n"));
168
169 /* Write-lock the object as we could be racing language change
170 notifications processing during XPCOM shutdown. (risky?) */
171 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
172
173 RTTlsFree(g_idxTlsTr);
174 g_idxTlsTr = NIL_RTTLS;
175 RTTlsFree(g_idxTlsSrc);
176 g_idxTlsSrc = NIL_RTTLS;
177
178 m_pDefaultComponent = NULL;
179
180 for (TranslatorList::iterator it = m_lTranslators.begin();
181 it != m_lTranslators.end();
182 ++it)
183 {
184 if (it->pTranslator != NULL)
185 delete it->pTranslator;
186 it->pTranslator = NULL;
187 }
188 if (m_hStrCache != NIL_RTSTRCACHE)
189 {
190 RTStrCacheDestroy(m_hStrCache);
191 m_hStrCache = NIL_RTSTRCACHE;
192 m_rcCache = VERR_WRONG_ORDER;
193 }
194 LogFlowFunc(("returns\n"));
195}
196
197
198/**
199 * Get or create a translator instance (singelton), referenced.
200 *
201 * The main reference is held by the main VBox singelton objects (VirtualBox,
202 * VirtualBoxClient) tying it's lifetime to theirs.
203 */
204/* static */
205VirtualBoxTranslator *VirtualBoxTranslator::instance()
206{
207 int vrc = RTOnce(&g_Once, initLock, NULL);
208 if (RT_SUCCESS(vrc))
209 {
210 RTCritSectRwEnterShared(&s_instanceRwLock);
211 VirtualBoxTranslator *pInstance = s_pInstance;
212 if (RT_LIKELY(pInstance != NULL))
213 {
214 uint32_t cRefs = ASMAtomicIncU32(&pInstance->m_cInstanceRefs);
215 Assert(cRefs > 1); Assert(cRefs < _8K); RT_NOREF(cRefs);
216 RTCritSectRwLeaveShared(&s_instanceRwLock);
217 return pInstance;
218 }
219
220 /* Maybe create the instance: */
221 RTCritSectRwLeaveShared(&s_instanceRwLock);
222 RTCritSectRwEnterExcl(&s_instanceRwLock);
223 pInstance = s_pInstance;
224 if (pInstance == NULL)
225 s_pInstance = pInstance = new VirtualBoxTranslator();
226 ASMAtomicIncU32(&pInstance->m_cInstanceRefs);
227 RTCritSectRwLeaveExcl(&s_instanceRwLock);
228 return pInstance;
229 }
230 return NULL;
231}
232
233
234/* static */
235VirtualBoxTranslator *VirtualBoxTranslator::tryInstance() RT_NOEXCEPT
236{
237 int vrc = RTOnce(&g_Once, initLock, NULL);
238 if (RT_SUCCESS(vrc))
239 {
240 RTCritSectRwEnterShared(&s_instanceRwLock);
241 VirtualBoxTranslator *pInstance = s_pInstance;
242 if (RT_LIKELY(pInstance != NULL))
243 {
244 uint32_t cRefs = ASMAtomicIncU32(&pInstance->m_cInstanceRefs);
245 Assert(cRefs > 1); Assert(cRefs < _8K); RT_NOREF(cRefs);
246 }
247 RTCritSectRwLeaveShared(&s_instanceRwLock);
248 return pInstance;
249 }
250 return NULL;
251}
252
253
254/**
255 * Release translator reference previous obtained via instance() or
256 * tryinstance().
257 */
258void VirtualBoxTranslator::release()
259{
260 RTCritSectRwEnterShared(&s_instanceRwLock);
261 uint32_t cRefs = ASMAtomicDecU32(&m_cInstanceRefs);
262 Assert(cRefs < _8K);
263 if (RT_LIKELY(cRefs > 0))
264 RTCritSectRwLeaveShared(&s_instanceRwLock);
265 else
266 {
267 /* Looks like we've got the last reference. Must switch to exclusive
268 mode for safe cleanup. */
269 ASMAtomicIncU32(&m_cInstanceRefs);
270 RTCritSectRwLeaveShared(&s_instanceRwLock);
271 RTCritSectRwEnterExcl(&s_instanceRwLock);
272 cRefs = ASMAtomicDecU32(&m_cInstanceRefs);
273 Assert(cRefs < _8K);
274 if (cRefs == 0)
275 {
276 s_pInstance = NULL;
277 delete this;
278 }
279 RTCritSectRwLeaveExcl(&s_instanceRwLock);
280 }
281}
282
283
284HRESULT VirtualBoxTranslator::loadLanguage(ComPtr<IVirtualBox> aVirtualBox)
285{
286 AssertReturn(aVirtualBox, E_INVALIDARG);
287
288 ComPtr<ISystemProperties> pSystemProperties;
289 HRESULT hrc = aVirtualBox->COMGETTER(SystemProperties)(pSystemProperties.asOutParam());
290 if (SUCCEEDED(hrc))
291 {
292 com::Bstr bstrLocale;
293 hrc = pSystemProperties->COMGETTER(LanguageId)(bstrLocale.asOutParam());
294 if (SUCCEEDED(hrc))
295 {
296 int vrc = i_loadLanguage(com::Utf8Str(bstrLocale).c_str());
297 if (RT_FAILURE(vrc))
298 hrc = Global::vboxStatusCodeToCOM(vrc);
299 }
300 }
301 return hrc;
302}
303
304
305com::Utf8Str VirtualBoxTranslator::language()
306{
307 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
308
309 return m_strLanguage;
310}
311
312
313int VirtualBoxTranslator::i_loadLanguage(const char *pszLang)
314{
315 LogFlowFunc(("pszLang=%s\n", pszLang));
316 int vrc = VINF_SUCCESS;
317 char szLocale[256];
318 if (pszLang == NULL || *pszLang == '\0')
319 {
320 vrc = vboxGetDefaultUserLanguage(szLocale, sizeof(szLocale));
321 if (RT_SUCCESS(vrc))
322 pszLang = szLocale;
323 }
324 else
325 {
326 /* check the pszLang looks like language code, i.e. {ll} or {ll}_{CC} */
327 size_t cbLang = strlen(pszLang);
328 if ( !(cbLang == 1 && pszLang[0] == 'C')
329 && !(cbLang == 2 && RT_C_IS_LOWER(pszLang[0]) && RT_C_IS_LOWER(pszLang[1]))
330 && !(cbLang == 5 && RTLOCALE_IS_LANGUAGE2_UNDERSCORE_COUNTRY2(pszLang)))
331 vrc = VERR_INVALID_PARAMETER;
332 }
333 if (RT_SUCCESS(vrc))
334 {
335 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
336
337 m_strLanguage = pszLang;
338
339 for (TranslatorList::iterator it = m_lTranslators.begin();
340 it != m_lTranslators.end();
341 ++it)
342 {
343 /* ignore errors from particular translator allowing the use of others */
344 i_loadLanguageForComponent(&(*it), pszLang);
345 }
346 }
347 return vrc;
348}
349
350
351int VirtualBoxTranslator::i_loadLanguageForComponent(TranslatorComponent *aComponent, const char *aLang)
352{
353 AssertReturn(aComponent, VERR_INVALID_PARAMETER);
354 LogFlow(("aComponent=%s aLang=%s\n", aComponent->strPath.c_str(), aLang));
355
356 int vrc;
357 if (strcmp(aLang, "C") != 0)
358 {
359 /* Construct the base filename for the translations: */
360 char szNlsPath[RTPATH_MAX];
361 /* Try load language file on form 'VirtualBoxAPI_ll_CC.qm' if it exists
362 where 'll_CC' could for example be 'en_US' or 'de_CH': */
363 ssize_t cchOkay = RTStrPrintf2(szNlsPath, sizeof(szNlsPath), "%s_%s.qm",
364 aComponent->strPath.c_str(), aLang);
365 if (cchOkay > 0)
366 vrc = i_setLanguageFile(aComponent, szNlsPath);
367 else
368 vrc = VERR_FILENAME_TOO_LONG;
369 if (RT_FAILURE(vrc))
370 {
371 /* No luck, drop the country part, i.e. 'VirtualBoxAPI_de.qm' or 'VirtualBoxAPI_en.qm': */
372 const char *pszDash = strchr(aLang, '_');
373 if (pszDash && pszDash != aLang)
374 {
375 cchOkay = RTStrPrintf2(szNlsPath, sizeof(szNlsPath), "%s_%.*s.qm",
376 aComponent->strPath.c_str(), pszDash - aLang, aLang);
377 if (cchOkay > 0)
378 vrc = i_setLanguageFile(aComponent, szNlsPath);
379 }
380 }
381 }
382 else
383 {
384 /* No translator needed for 'C' */
385 delete aComponent->pTranslator;
386 aComponent->pTranslator = NULL;
387 vrc = VINF_SUCCESS;
388 }
389 return vrc;
390}
391
392
393int VirtualBoxTranslator::i_setLanguageFile(TranslatorComponent *aComponent, const char *aFileName)
394{
395 AssertReturn(aComponent, VERR_INVALID_PARAMETER);
396
397 int vrc = m_rcCache;
398 if (m_hStrCache != NIL_RTSTRCACHE)
399 {
400 QMTranslator *pNewTranslator;
401 try { pNewTranslator = new QMTranslator(); }
402 catch (std::bad_alloc &) { pNewTranslator = NULL; }
403 if (pNewTranslator)
404 {
405 vrc = pNewTranslator->load(aFileName, m_hStrCache);
406 if (RT_SUCCESS(vrc))
407 {
408 if (aComponent->pTranslator)
409 delete aComponent->pTranslator;
410 aComponent->pTranslator = pNewTranslator;
411 }
412 else
413 delete pNewTranslator;
414 }
415 else
416 vrc = VERR_NO_MEMORY;
417 }
418 else
419 Assert(RT_FAILURE_NP(vrc));
420 return vrc;
421}
422
423
424int VirtualBoxTranslator::registerTranslation(const char *aTranslationPath,
425 bool aDefault,
426 PTRCOMPONENT *aComponent)
427{
428 VirtualBoxTranslator *pCurrInstance = VirtualBoxTranslator::tryInstance();
429 int vrc = VERR_GENERAL_FAILURE;
430 if (pCurrInstance != NULL)
431 {
432 vrc = pCurrInstance->i_registerTranslation(aTranslationPath, aDefault, aComponent);
433 pCurrInstance->release();
434 }
435 return vrc;
436}
437
438
439int VirtualBoxTranslator::i_registerTranslation(const char *aTranslationPath,
440 bool aDefault,
441 PTRCOMPONENT *aComponent)
442{
443 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
444 TranslatorComponent *pComponent;
445 for (TranslatorList::iterator it = m_lTranslators.begin();
446 it != m_lTranslators.end();
447 ++it)
448 {
449 if (it->strPath == aTranslationPath)
450 {
451 pComponent = &(*it);
452 if (aDefault)
453 m_pDefaultComponent = pComponent;
454 *aComponent = (PTRCOMPONENT)pComponent;
455 return VINF_SUCCESS;
456 }
457 }
458
459 try
460 {
461 m_lTranslators.push_back(TranslatorComponent());
462 pComponent = &m_lTranslators.back();
463 }
464 catch(std::bad_alloc &)
465 {
466 return VERR_NO_MEMORY;
467 }
468
469 pComponent->strPath = aTranslationPath;
470 if (aDefault)
471 m_pDefaultComponent = pComponent;
472 *aComponent = (PTRCOMPONENT)pComponent;
473 /* ignore the error during loading because path
474 * could contain no translation for current language */
475 i_loadLanguageForComponent(pComponent, m_strLanguage.c_str());
476 return VINF_SUCCESS;
477}
478
479
480int VirtualBoxTranslator::unregisterTranslation(PTRCOMPONENT aComponent)
481{
482 int vrc;
483 if (aComponent != NULL)
484 {
485 VirtualBoxTranslator *pCurrInstance = VirtualBoxTranslator::tryInstance();
486 if (pCurrInstance != NULL)
487 {
488 vrc = pCurrInstance->i_unregisterTranslation(aComponent);
489 pCurrInstance->release();
490 }
491 else
492 vrc = VERR_GENERAL_FAILURE;
493 }
494 else
495 vrc = VWRN_NOT_FOUND;
496 return vrc;
497}
498
499
500int VirtualBoxTranslator::i_unregisterTranslation(PTRCOMPONENT aComponent)
501{
502 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
503
504 if (aComponent == m_pDefaultComponent)
505 m_pDefaultComponent = NULL;
506
507 for (TranslatorList::iterator it = m_lTranslators.begin();
508 it != m_lTranslators.end();
509 ++it)
510 {
511 if (&(*it) == aComponent)
512 {
513 delete aComponent->pTranslator;
514 m_lTranslators.erase(it);
515 return VINF_SUCCESS;
516 }
517 }
518
519 return VERR_NOT_FOUND;
520}
521
522
523const char *VirtualBoxTranslator::translate(PTRCOMPONENT aComponent,
524 const char *aContext,
525 const char *aSourceText,
526 const char *aComment,
527 const size_t aNum) RT_NOEXCEPT
528{
529 VirtualBoxTranslator *pCurrInstance = VirtualBoxTranslator::tryInstance();
530 const char *pszTranslation = aSourceText;
531 if (pCurrInstance != NULL)
532 {
533 pszTranslation = pCurrInstance->i_translate(aComponent, aContext, aSourceText, aComment, aNum);
534 pCurrInstance->release();
535 }
536 return pszTranslation;
537}
538
539
540const char *VirtualBoxTranslator::i_translate(PTRCOMPONENT aComponent,
541 const char *aContext,
542 const char *aSourceText,
543 const char *aComment,
544 const size_t aNum) RT_NOEXCEPT
545{
546 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
547
548 if (aComponent == NULL)
549 aComponent = m_pDefaultComponent;
550
551 if ( aComponent == NULL
552 || aComponent->pTranslator == NULL)
553 return aSourceText;
554
555 const char *pszSafeSource = NULL;
556 const char *pszTranslation = aComponent->pTranslator->translate(aContext, aSourceText, &pszSafeSource, aComment, aNum);
557 if (pszSafeSource && g_idxTlsSrc != NIL_RTTLS && g_idxTlsTr != NIL_RTTLS)
558 {
559 RTTlsSet(g_idxTlsTr, (void *)pszTranslation);
560 RTTlsSet(g_idxTlsSrc, (void *)pszSafeSource);
561 }
562
563 return pszTranslation;
564}
565
566
567const char *VirtualBoxTranslator::trSource(const char *aTranslation) RT_NOEXCEPT
568{
569 const char *pszSource = aTranslation;
570 VirtualBoxTranslator *pCurInstance = VirtualBoxTranslator::tryInstance(); /* paranoia */
571 if (pCurInstance != NULL)
572 {
573 if (g_idxTlsSrc != NIL_RTTLS && g_idxTlsTr != NIL_RTTLS)
574 {
575 const char * const pszTranslationTls = (const char *)RTTlsGet(g_idxTlsTr);
576 const char * const pszSourceTls = (const char *)RTTlsGet(g_idxTlsSrc);
577 if ( pszSourceTls != NULL
578 && pszTranslationTls != NULL
579 && ( pszTranslationTls == aTranslation
580 || strcmp(pszTranslationTls, aTranslation) == 0))
581 pszSource = pszSourceTls;
582 }
583 pCurInstance->release();
584 }
585 return pszSource;
586}
587
588
589int32_t VirtualBoxTranslator::initCritSect()
590{
591 return RTCritSectRwInit(&s_instanceRwLock);
592}
593/* vi: set tabstop=4 shiftwidth=4 expandtab: */
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