1 /* Translator.cpp */
2 
3 /* Copyright (C) 2011-2020 Michael Lugmair (Lucio Carreras)
4  *
5  * This file is part of sayonara player
6  *
7  * This program is free software: you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License as published by
9  * the Free Software Foundation, either version 3 of the License, or
10  * (at your option) any later version.
11 
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU General Public License for more details.
16 
17  * You should have received a copy of the GNU General Public License
18  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
19  */
20 
21 #include "Translator.h"
22 
23 #include "Utils/Utils.h"
24 #include "Utils/Language/LanguageUtils.h"
25 #include "Utils/Logger/Logger.h"
26 #include "Utils/StandardPaths.h"
27 
28 #include <QTranslator>
29 #include <QApplication>
30 #include <QList>
31 #include <QDir>
32 
33 struct Translator::Private
34 {
35 	QList<QTranslator*> translators;
36 };
37 
Translator()38 Translator::Translator()
39 {
40 	m = Pimpl::make<Private>();
41 }
42 
43 Translator::~Translator() = default;
44 
switchTranslator(QObject * parent,const QString & fourLetter)45 bool Translator::switchTranslator(QObject* parent, const QString& fourLetter)
46 {
47 	if(!m->translators.isEmpty())
48 	{
49 		for(QTranslator* t : m->translators)
50 		{
51 			QApplication::removeTranslator(t);
52 			t->deleteLater();
53 		}
54 
55 		m->translators.clear();
56 	}
57 
58 	const QString languageFile = Util::Language::getUsedLanguageFile(fourLetter);
59 	const QString languageDir = Util::translationsSharePath();
60 
61 	QStringList filenames;
62 	filenames << QDir(languageDir).absoluteFilePath(languageFile)
63 	          << Util::Language::getCurrentQtTranslationPaths();
64 
65 	for(const QString& filename : filenames)
66 	{
67 		auto* translator = new QTranslator(parent);
68 		bool loaded = translator->load(filename);
69 		if(!loaded)
70 		{
71 			translator->deleteLater();
72 			spLog(Log::Debug, this) << "Translator " << filename << " could not be loaded";
73 			continue;
74 		}
75 
76 		if(translator->isEmpty())
77 		{
78 			translator->deleteLater();
79 			spLog(Log::Debug, this) << "Translator is empty";
80 			continue;
81 		}
82 
83 		bool installed = QApplication::installTranslator(translator);
84 		if(!installed)
85 		{
86 			translator->deleteLater();
87 			spLog(Log::Debug, this) << "Translator " << filename << " could not be installed";
88 			continue;
89 		}
90 
91 		m->translators << translator;
92 	}
93 
94 	return (!m->translators.isEmpty());
95 }
96 
changeLanguage(QObject * parent,const QString & fourLetter)97 void Translator::changeLanguage(QObject* parent, const QString& fourLetter)
98 {
99 	switchTranslator(parent, fourLetter);
100 }
101