1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
|
#include "TranslationsModel.h"
#include <QCoreApplication>
#include <QTranslator>
#include <QLocale>
#include <QDir>
#include <QLibraryInfo>
#include <QDebug>
#include <FileSystem.h>
#include <net/NetJob.h>
#include <net/ChecksumValidator.h>
#include <Env.h>
#include <net/URLConstants.h>
#include "Json.h"
#include "POTranslator.h"
const static QLatin1Literal defaultLangCode("en");
enum class FileType
{
NONE,
QM,
PO
};
struct Language
{
Language()
{
updated = true;
}
Language(const QString & _key)
{
key = _key;
locale = QLocale(key);
updated = (key == defaultLangCode);
}
float percentTranslated() const
{
if (total == 0)
{
return 100.0f;
}
return 100.0f * float(translated) / float(total);
}
void setTranslationStats(unsigned _translated, unsigned _untranslated, unsigned _fuzzy)
{
translated = _translated;
untranslated = _untranslated;
fuzzy = _fuzzy;
total = translated + untranslated + fuzzy;
}
bool isOfSameNameAs(const Language& other) const
{
return key == other.key;
}
bool isIdenticalTo(const Language& other) const
{
return
(
key == other.key &&
file_name == other.file_name &&
file_size == other.file_size &&
file_sha1 == other.file_sha1 &&
translated == other.translated &&
fuzzy == other.fuzzy &&
total == other.fuzzy &&
localFileType == other.localFileType
);
}
Language & apply(Language & other)
{
if(!isOfSameNameAs(other))
{
return *this;
}
file_name = other.file_name;
file_size = other.file_size;
file_sha1 = other.file_sha1;
translated = other.translated;
fuzzy = other.fuzzy;
total = other.total;
localFileType = other.localFileType;
return *this;
}
QString key;
QLocale locale;
bool updated;
QString file_name = QString();
std::size_t file_size = 0;
QString file_sha1 = QString();
unsigned translated = 0;
unsigned untranslated = 0;
unsigned fuzzy = 0;
unsigned total = 0;
FileType localFileType = FileType::NONE;
};
struct TranslationsModel::Private
{
QDir m_dir;
// initial state is just english
QVector<Language> m_languages = {Language (defaultLangCode)};
QString m_selectedLanguage = defaultLangCode;
std::unique_ptr<QTranslator> m_qt_translator;
std::unique_ptr<QTranslator> m_app_translator;
std::shared_ptr<Net::Download> m_index_task;
QString m_downloadingTranslation;
NetJobPtr m_dl_job;
NetJobPtr m_index_job;
QString m_nextDownload;
std::unique_ptr<POTranslator> m_po_translator;
QFileSystemWatcher *watcher;
};
TranslationsModel::TranslationsModel(QString path, QObject* parent): QAbstractListModel(parent)
{
d.reset(new Private);
d->m_dir.setPath(path);
reloadLocalFiles();
d->watcher = new QFileSystemWatcher(this);
connect(d->watcher, &QFileSystemWatcher::directoryChanged, this, &TranslationsModel::translationDirChanged);
d->watcher->addPath(d->m_dir.canonicalPath());
}
TranslationsModel::~TranslationsModel()
{
}
void TranslationsModel::translationDirChanged(const QString& path)
{
qDebug() << "Dir changed:" << path;
reloadLocalFiles();
selectLanguage(selectedLanguage());
}
void TranslationsModel::indexRecieved()
{
qDebug() << "Got translations index!";
d->m_index_job.reset();
if(d->m_selectedLanguage != defaultLangCode)
{
downloadTranslation(d->m_selectedLanguage);
}
}
namespace {
void readIndex(const QString & path, QMap<QString, Language>& languages)
{
QByteArray data;
try
{
data = FS::read(path);
}
catch (const Exception &e)
{
qCritical() << "Translations Download Failed: index file not readable";
return;
}
int index = 1;
try
{
auto doc = Json::requireObject(Json::requireDocument(data));
auto file_type = Json::requireString(doc, "file_type");
if(file_type != "MMC-TRANSLATION-INDEX")
{
qCritical() << "Translations Download Failed: index file is of unknown file type" << file_type;
return;
}
auto version = Json::requireInteger(doc, "version");
if(version > 2)
{
qCritical() << "Translations Download Failed: index file is of unknown format version" << file_type;
return;
}
auto langObjs = Json::requireObject(doc, "languages");
for(auto iter = langObjs.begin(); iter != langObjs.end(); iter++)
{
Language lang(iter.key());
auto langObj = Json::requireObject(iter.value());
lang.setTranslationStats(
Json::ensureInteger(langObj, "translated", 0),
Json::ensureInteger(langObj, "untranslated", 0),
Json::ensureInteger(langObj, "fuzzy", 0)
);
lang.file_name = Json::requireString(langObj, "file");
lang.file_sha1 = Json::requireString(langObj, "sha1");
lang.file_size = Json::requireInteger(langObj, "size");
languages.insert(lang.key, lang);
index++;
}
}
catch (Json::JsonException & e)
{
qCritical() << "Translations Download Failed: index file could not be parsed as json";
}
}
}
void TranslationsModel::reloadLocalFiles()
{
QMap<QString, Language> languages = {{defaultLangCode, Language(defaultLangCode)}};
readIndex(d->m_dir.absoluteFilePath("index_v2.json"), languages);
auto entries = d->m_dir.entryInfoList({"mmc_*.qm", "*.po"}, QDir::Files | QDir::NoDotAndDotDot);
for(auto & entry: entries)
{
auto completeSuffix = entry.completeSuffix();
QString langCode;
FileType fileType = FileType::NONE;
if(completeSuffix == "qm")
{
langCode = entry.baseName().remove(0,4);
fileType = FileType::QM;
}
else if(completeSuffix == "po")
{
langCode = entry.baseName();
fileType = FileType::PO;
}
else
{
continue;
}
auto langIter = languages.find(langCode);
if(langIter != languages.end())
{
auto & language = *langIter;
if(int(fileType) > int(language.localFileType))
{
language.localFileType = fileType;
}
}
else
{
if(fileType == FileType::PO)
{
Language localFound(langCode);
localFound.localFileType = FileType::PO;
languages.insert(langCode, localFound);
}
}
}
// changed and removed languages
for(auto iter = d->m_languages.begin(); iter != d->m_languages.end();)
{
auto &language = *iter;
auto row = iter - d->m_languages.begin();
auto updatedLanguageIter = languages.find(language.key);
if(updatedLanguageIter != languages.end())
{
if(language.isIdenticalTo(*updatedLanguageIter))
{
languages.remove(language.key);
}
else
{
language.apply(*updatedLanguageIter);
emit dataChanged(index(row), index(row));
languages.remove(language.key);
}
iter++;
}
else
{
beginRemoveRows(QModelIndex(), row, row);
iter = d->m_languages.erase(iter);
endRemoveRows();
}
}
// added languages
if(languages.isEmpty())
{
return;
}
beginInsertRows(QModelIndex(), d->m_languages.size(), d->m_languages.size() + languages.size() - 1);
for(auto & language: languages)
{
d->m_languages.append(language);
}
endInsertRows();
}
namespace {
enum class Column
{
Language,
Quality
};
}
QVariant TranslationsModel::data(const QModelIndex& index, int role) const
{
if (!index.isValid())
return QVariant();
int row = index.row();
auto column = static_cast<Column>(index.column());
if (row < 0 || row >= d->m_languages.size())
return QVariant();
auto & lang = d->m_languages[row];
switch (role)
{
case Qt::DisplayRole:
{
switch(column)
{
case Column::Language:
{
return d->m_languages[row].locale.nativeLanguageName();
}
case Column::Quality:
{
QString text;
text.sprintf("%3.1f %%", lang.percentTranslated());
return text;
}
}
}
case Qt::ToolTipRole:
{
return tr("%1:\n%2 translated\n%3 fuzzy\n%4 total").arg(lang.key, QString::number(lang.translated), QString::number(lang.fuzzy), QString::number(lang.total));
}
case Qt::UserRole:
return d->m_languages[row].key;
default:
return QVariant();
}
}
QVariant TranslationsModel::headerData(int section, Qt::Orientation orientation, int role) const
{
auto column = static_cast<Column>(section);
if(role == Qt::DisplayRole)
{
switch(column)
{
case Column::Language:
{
return tr("Language");
}
case Column::Quality:
{
return tr("Quality");
}
}
}
else if(role == Qt::ToolTipRole)
{
switch(column)
{
case Column::Language:
{
return tr("The native language name.");
}
case Column::Quality:
{
return tr("Quality is the percentage of fully translated strings, not counting automatically guessed ones.");
}
}
}
return QAbstractListModel::headerData(section, orientation, role);
}
int TranslationsModel::rowCount(const QModelIndex& parent) const
{
return d->m_languages.size();
}
int TranslationsModel::columnCount(const QModelIndex& parent) const
{
return 2;
}
Language * TranslationsModel::findLanguage(const QString& key)
{
auto found = std::find_if(d->m_languages.begin(), d->m_languages.end(), [&](Language & lang)
{
return lang.key == key;
});
if(found == d->m_languages.end())
{
return nullptr;
}
else
{
return found;
}
}
bool TranslationsModel::selectLanguage(QString key)
{
QString &langCode = key;
auto langPtr = findLanguage(key);
if(!langPtr)
{
qWarning() << "Selected invalid language" << key << ", defaulting to" << defaultLangCode;
langCode = defaultLangCode;
}
else
{
langCode = langPtr->key;
}
// uninstall existing translators if there are any
if (d->m_app_translator)
{
QCoreApplication::removeTranslator(d->m_app_translator.get());
d->m_app_translator.reset();
}
if (d->m_qt_translator)
{
QCoreApplication::removeTranslator(d->m_qt_translator.get());
d->m_qt_translator.reset();
}
/*
* FIXME: potential source of crashes:
* In a multithreaded application, the default locale should be set at application startup, before any non-GUI threads are created.
* This function is not reentrant.
*/
QLocale locale(langCode);
QLocale::setDefault(locale);
// if it's the default UI language, finish
if(langCode == defaultLangCode)
{
d->m_selectedLanguage = langCode;
return true;
}
// otherwise install new translations
bool successful = false;
// FIXME: this is likely never present. FIX IT.
d->m_qt_translator.reset(new QTranslator());
if (d->m_qt_translator->load("qt_" + langCode, QLibraryInfo::location(QLibraryInfo::TranslationsPath)))
{
qDebug() << "Loading Qt Language File for" << langCode.toLocal8Bit().constData() << "...";
if (!QCoreApplication::installTranslator(d->m_qt_translator.get()))
{
qCritical() << "Loading Qt Language File failed.";
d->m_qt_translator.reset();
}
else
{
successful = true;
}
}
else
{
d->m_qt_translator.reset();
}
if(langPtr->localFileType == FileType::PO)
{
qDebug() << "Loading Application Language File for" << langCode.toLocal8Bit().constData() << "...";
auto poTranslator = new POTranslator(FS::PathCombine(d->m_dir.path(), langCode + ".po"));
if(!poTranslator->isEmpty())
{
if (!QCoreApplication::installTranslator(poTranslator))
{
delete poTranslator;
qCritical() << "Installing Application Language File failed.";
}
else
{
d->m_app_translator.reset(poTranslator);
successful = true;
}
}
else
{
qCritical() << "Loading Application Language File failed.";
d->m_app_translator.reset();
}
}
else if(langPtr->localFileType == FileType::QM)
{
d->m_app_translator.reset(new QTranslator());
if (d->m_app_translator->load("mmc_" + langCode, d->m_dir.path()))
{
qDebug() << "Loading Application Language File for" << langCode.toLocal8Bit().constData() << "...";
if (!QCoreApplication::installTranslator(d->m_app_translator.get()))
{
qCritical() << "Installing Application Language File failed.";
d->m_app_translator.reset();
}
else
{
successful = true;
}
}
else
{
d->m_app_translator.reset();
}
}
else
{
d->m_app_translator.reset();
}
d->m_selectedLanguage = langCode;
return successful;
}
QModelIndex TranslationsModel::selectedIndex()
{
auto found = findLanguage(d->m_selectedLanguage);
if(found)
{
// QVector iterator freely converts to pointer to contained type
return index(found - d->m_languages.begin(), 0, QModelIndex());
}
return QModelIndex();
}
QString TranslationsModel::selectedLanguage()
{
return d->m_selectedLanguage;
}
void TranslationsModel::downloadIndex()
{
if(d->m_index_job || d->m_dl_job)
{
return;
}
qDebug() << "Downloading Translations Index...";
d->m_index_job.reset(new NetJob("Translations Index"));
MetaEntryPtr entry = ENV.metacache()->resolveEntry("translations", "index_v2.json");
entry->setStale(true);
d->m_index_task = Net::Download::makeCached(QUrl("https://files.multimc.org/translations/index_v2.json"), entry);
d->m_index_job->addNetAction(d->m_index_task);
connect(d->m_index_job.get(), &NetJob::failed, this, &TranslationsModel::indexFailed);
connect(d->m_index_job.get(), &NetJob::succeeded, this, &TranslationsModel::indexRecieved);
d->m_index_job->start();
}
void TranslationsModel::updateLanguage(QString key)
{
if(key == defaultLangCode)
{
qWarning() << "Cannot update builtin language" << key;
return;
}
auto found = findLanguage(key);
if(!found)
{
qWarning() << "Cannot update invalid language" << key;
return;
}
if(!found->updated)
{
downloadTranslation(key);
}
}
void TranslationsModel::downloadTranslation(QString key)
{
if(d->m_dl_job)
{
d->m_nextDownload = key;
return;
}
auto lang = findLanguage(key);
if(!lang)
{
qWarning() << "Will not download an unknown translation" << key;
return;
}
d->m_downloadingTranslation = key;
MetaEntryPtr entry = ENV.metacache()->resolveEntry("translations", "mmc_" + key + ".qm");
entry->setStale(true);
auto dl = Net::Download::makeCached(QUrl(URLConstants::TRANSLATIONS_BASE_URL + lang->file_name), entry);
auto rawHash = QByteArray::fromHex(lang->file_sha1.toLatin1());
dl->addValidator(new Net::ChecksumValidator(QCryptographicHash::Sha1, rawHash));
dl->m_total_progress = lang->file_size;
d->m_dl_job.reset(new NetJob("Translation for " + key));
d->m_dl_job->addNetAction(dl);
connect(d->m_dl_job.get(), &NetJob::succeeded, this, &TranslationsModel::dlGood);
connect(d->m_dl_job.get(), &NetJob::failed, this, &TranslationsModel::dlFailed);
d->m_dl_job->start();
}
void TranslationsModel::downloadNext()
{
if(!d->m_nextDownload.isEmpty())
{
downloadTranslation(d->m_nextDownload);
d->m_nextDownload.clear();
}
}
void TranslationsModel::dlFailed(QString reason)
{
qCritical() << "Translations Download Failed:" << reason;
d->m_dl_job.reset();
downloadNext();
}
void TranslationsModel::dlGood()
{
qDebug() << "Got translation:" << d->m_downloadingTranslation;
if(d->m_downloadingTranslation == d->m_selectedLanguage)
{
selectLanguage(d->m_selectedLanguage);
}
d->m_dl_job.reset();
downloadNext();
}
void TranslationsModel::indexFailed(QString reason)
{
qCritical() << "Translations Index Download Failed:" << reason;
d->m_index_job.reset();
}
|