forked from z1dev/zkanji
-
Notifications
You must be signed in to change notification settings - Fork 0
/
import.cpp
4358 lines (3633 loc) · 139 KB
/
import.cpp
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
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
** Copyright 2007-2013, 2017-2018 Sólyom Zoltán
** This file is part of zkanji, a free software released under the terms of the
** GNU General Public License version 3. See the file LICENSE for details.
**/
#include <QtEvents>
#include <QMessageBox>
#include <QInputDialog>
#include <QDir>
#include <QtEndian>
#include <set>
#include "import.h"
#include "ui_import.h"
#include "treebuilder.h"
#include "words.h"
#include "sentences.h"
#include "kanji.h"
#include "grammar_enums.h"
#include "romajizer.h"
#include "zkanjimain.h"
#include "zui.h"
#include "zevents.h"
#include "zstrings.h"
#include "groups.h"
#include "jlptreplaceform.h"
#include "generalsettings.h"
#include "globalui.h"
#include "checked_cast.h"
extern char ZKANJI_PROGRAM_VERSION[];
static char ZKANJI_EXAMPLES_FILE_VERSION[] = "002";
// When changed: also update exportDictionary() in words.cpp.
static const char JMDictInfoText[] = "This program uses a compilation of the <a href=\"http://www.edrdg.org/jmdict/j_jmdict.html\">JMdict</a> "
"and <a href=\"http://nihongo.monash.edu/kanjidic.html\">KANJIDIC</a> dictionary files "
"and <a href=\"http://nihongo.monash.edu/kradinf.html\">RADKFILE</a>, "
"which are the property of The Electronic Dictionary Research and Development Group, Monash University.\n"
"The files are made available under a Creative Commons Attribution-ShareAlike Licence (V3.0).\n"
"The group can be found at: <a href=\"http://www.edrdg.org/\">http://www.edrdg.org/</a>\n"
"\n"
"Additional conditions applying to KANJIDIC:\n"
"The following people have granted permission for material in KANJIDIC, for which they hold copyright "
"to be included in the file while retaining their copyright over that material:\n"
"Jack HALPERN: The SKIP codes. (More information below)\n"
"Christian WITTERN and Koichi YASUOKA: The Pinyin information.\n"
"Urs APP: the Four Corner codes and the Morohashi information.\n"
"Mark SPAHN and Wolfgang HADAMITZKY: the kanji descriptors from their dictionary.\n"
"Charles MULLER: the Korean readings.\n"
"Joseph DE ROO: the De Roo codes.\n"
"\n"
"The SKIP(System of Kanji Indexing by Patterns) system for ordering kanji was developed by Jack Halpern "
"(Kanji Dictionary Publishing Society at <a href=\"http://www.kanji.org/\">http://www.kanji.org/</a>), and is used with his permission. "
"The SKIP coding system and all established SKIP codes have been placed under a Creative Commons Attribution-ShareAlike 4.0 International license.";
//-------------------------------------------------------------
ImportFileHandlerGuard::ImportFileHandlerGuard(ImportFileHandler &file) : file(&file)
{
file.addGuard(this);
}
ImportFileHandlerGuard::~ImportFileHandlerGuard()
{
if (file != nullptr)
file->guardClose(this);
}
void ImportFileHandlerGuard::disable()
{
if (file != nullptr)
file->disableGuard(this);
file = nullptr;
}
//-------------------------------------------------------------
ImportFileHandler::ImportFileHandler() : fail(false), f(nullptr), ownfile(true), linenum(0), skipread(false)
{
}
ImportFileHandler::ImportFileHandler(QString fname) : fail(false), f(nullptr), ownfile(true), linenum(0), skipread(false)
{
open(fname);
}
ImportFileHandler::~ImportFileHandler()
{
disableGuards();
if (ownfile)
close();
f = nullptr;
ownfile = true;
}
bool ImportFileHandler::open(QString fname, const char *codec)
{
disableGuards();
if (f != nullptr && ownfile)
close();
f = new QFile();
ownfile = true;
f->setFileName(fname);
if (!f->exists() || !f->open(QIODevice::ReadOnly | QIODevice::Text))
{
delete f;
f = nullptr;
fail = true;
return false;
}
fail = false;
stream.setDevice(f);
if (codec == nullptr)
stream.setCodec("UTF-8");
else
stream.setCodec(codec);
return true;
}
void ImportFileHandler::setFile(QFile &file, const char *codec)
{
if (f == &file)
return;
disableGuards();
if (f != nullptr && ownfile)
close();
ownfile = false;
f = &file;
fail = false;
stream.setDevice(f);
if (codec == nullptr)
stream.setCodec("UTF-8");
else
stream.setCodec(codec);
}
void ImportFileHandler::close()
{
disableGuards();
if (f == nullptr)
return;
f->close();
if (ownfile)
delete f;
f = nullptr;
fail = false;
linenum = 0;
skipread = false;
line = QString();
}
bool ImportFileHandler::isOpen() const
{
return !fail && f != nullptr && f->isOpen();
}
QString ImportFileHandler::fileName() const
{
return f == nullptr ? QString() : f->fileName();
}
int ImportFileHandler::lineNumber() const
{
return linenum;
}
void ImportFileHandler::repeat()
{
skipread = true;
}
bool ImportFileHandler::error() const
{
return fail;
}
qint64 ImportFileHandler::size() const
{
return fail || f == nullptr ? 0 : f->size();
}
int ImportFileHandler::pos() const
{
return fail || f == nullptr ? -1 : f->pos();
}
bool ImportFileHandler::getLine(QString &result)
{
if (fail || f == nullptr)
return false;
if (skipread)
{
result = line;
skipread = false;
return true;
}
line = stream.readLine();
if (line.isNull())
{
fail = true;
result = QString();
return false;
}
++linenum;
result = line;
return true;
}
QString ImportFileHandler::lastLine() const
{
return line;
}
//bool ImportFileHandler::atEnd() const
//{
// return fail || f == nullptr || (!skipread && stream.atEnd());
//}
void ImportFileHandler::addGuard(ImportFileHandlerGuard *guard)
{
guards.insert(guard);
}
void ImportFileHandler::disableGuard(ImportFileHandlerGuard *guard)
{
auto it = guards.find(guard);
if (it == guards.end())
return;
guards.erase(it);
}
void ImportFileHandler::disableGuards()
{
QSet<ImportFileHandlerGuard*> tmp = guards;
guards.clear();
for (ImportFileHandlerGuard* g : tmp)
g->disable();
}
void ImportFileHandler::guardClose(ImportFileHandlerGuard *guard)
{
auto it = guards.find(guard);
if (it == guards.end())
return;
guards.erase(it);
if (guards.empty())
close();
}
//-------------------------------------------------------------
DictImport::DictImport(QWidget *parent) : base(parent, false), ui(new Ui::DictImport), modified(false), stepcnt(0), step(1), kcurrent(nullptr), rcurrent(nullptr), scurrent(nullptr),
/*entryr(0), entrys(0),*/ counter(0)
{
ui->setupUi(this);
QString s1 = tr("Importing dictionary. This can take several minutes, please wait...");
QString s2 = tr("You can stop the import if you close this window. No data will be lost or updated.");
ui->progressLabel->setText(QString("<html><head/><body><p><span style=\"font-size:%1pt;\">%2</span></p><p><span style=\"font-size:%3pt;\">%4</span></p></body></html>").arg(Settings::scaled(12)).arg(s1).arg(Settings::scaled(9)).arg(s2));
ui->finishButton->setEnabled(false);
connect(ui->finishButton, &QPushButton::clicked, this, &DictImport::closeAfterImport);
gUI->scaleWidget(this);
}
DictImport::~DictImport()
{
delete ui;
}
Dictionary* DictImport::importDict(QString p, bool full)
{
mode = Modes::Dictionary;
stepcnt = full ? 8 : 6;
path = p;
//outpath = o;
//lang = l;
lang.clear();
fullimport = full;
dict = nullptr;
setMainText(tr("Importing dictionary. This can take several minutes, please wait..."));
show();
adjustSize();
setFixedSize(size());
qApp->postEvent(this, new StartEvent());
showModal();
//loop.exec();
return dict;
}
Dictionary* DictImport::importFromExport(QString p)
{
mode = Modes::Export;
stepcnt = 5;
path = p;
//outpath = o;
//lang = l;
dict = nullptr;
setMainText(tr("Importing dictionary. This can take several minutes, please wait..."));
show();
adjustSize();
setFixedSize(size());
qApp->postEvent(this, new StartEvent());
showModal();
//loop.exec();
return dict;
}
bool DictImport::importFromExportPartial(QString p, Dictionary *dest, WordGroup *worddest, KanjiGroup *kanjidest)
{
mode = Modes::Partial;
stepcnt = 3;
path = p;
dict = dest;
wordgroup = worddest;
kanjigroup = kanjidest;
setMainText(tr("Importing partial dictionary. This can take several minutes, please wait..."));
show();
adjustSize();
setFixedSize(size());
qApp->postEvent(this, new StartEvent());
showModal();
//loop.exec();
return step != -1;
}
void DictImport::setMainText(const QString &str)
{
QString secondary = !modified ? tr("You can stop the import if you close this window. No data will be lost or updated.") : tr("You can stop the import if you close this window. Some data has already been updated, and will remain.");
ui->progressLabel->setText(QString("<html><head/><body><p><span style=\"font-size:%1pt;\">%2</span></p><p><span style=\"font-size:%3pt;\">%4</span></p></body></html>").arg(Settings::scaled(12)).arg(str).arg(Settings::scaled(9)).arg(secondary));
}
void DictImport::setModifiedText(const QString &str)
{
modified = true;
setMainText(str);
}
bool DictImport::importExamples(QString p, QString o, Dictionary *d)
{
mode = Modes::Examples;
path = p;
outpath = o;
dict = d;
setMainText(tr("Importing example sentences. This can take several minutes, please wait..."));
show();
adjustSize();
setFixedSize(size());
qApp->postEvent(this, new StartEvent());
showModal();
//loop.exec();
return step != -1;
}
bool DictImport::importUserData(const QString &p, Dictionary *d, KanjiGroupCategory *kroot, WordGroupCategory *wroot, bool kanjiexamples, bool wordsmeanings)
{
mode = Modes::User;
stepcnt = 1;
path = p;
kanjiroot = kroot;
wordsroot = wroot;
dict = d;
kanjiex = kanjiexamples;
studymeanings = wordsmeanings;
setMainText(tr("Importing example sentences. This can take several minutes, please wait..."));
show();
adjustSize();
setFixedSize(size());
qApp->postEvent(this, new StartEvent());
showModal();
//loop.exec();
return step != -1;
}
bool DictImport::nextUpdate(int progress, bool forced)
{
if (!forced && ++counter != 100 && (progress == -1 || progress == ui->progressBar->value() || (progress != ui->progressBar->maximum() && ui->progressBar->maximum() / (progress - ui->progressBar->value()) < 2)))
return true;
counter = 0;
if (progress != -1)
ui->progressBar->setValue(progress);
qApp->processEvents();
//loop.processEvents();
return isVisible(); // loop.isRunning();
}
void DictImport::closeEvent(QCloseEvent *e)
{
if (isVisible() /*loop.isRunning()*/ && !ui->finishButton->isEnabled())
{
QString msg = !modified ? tr("Do you want to abort the import?") : tr("Some data has been modified and it will be kept even if you abort the import.\n\nDo you want to abort?");
if (QMessageBox::warning(nullptr, "zkanji", msg, QMessageBox::Yes | QMessageBox::No, QMessageBox::No) == QMessageBox::No)
{
e->ignore();
base::closeEvent(e);
return;
}
}
e->accept();
base::closeEvent(e);
//if (!e->isAccepted())
// return;
//// Notifies the event loop that makes this window behave like a dialog.
//loop.quit();
}
bool DictImport::event(QEvent *e)
{
if (e->type() == StartEvent::Type())
{
switch (mode)
{
case Modes::Dictionary:
if (!doImportDict())
{
if (fullimport)
{
ZKanji::kanjis.clear();
ZKanji::validkanji.clear();
ZKanji::radklist.clear();
ZKanji::radlist.clear();
ZKanji::radkcnt.clear();
ZKanji::radlist.clear();
ZKanji::commons.clearJLPTData();
}
step = -1;
if (/*loop.isRunning()*/isVisible())
{
ui->finishButton->setText(tr("Abort"));
ui->finishButton->setEnabled(true);
}
}
else
{
ZKanji::setNoData(false);
QString s1 = tr("Import finished.");
QString s2 = tr("Press \"%1\" to close the importer and continue starting the program.").arg(tr("Finish"));
ui->progressLabel->setText(QString("<html><head/><body><p><span style=\"font-size:%1pt;\">%2</span></p><p><span style=\"font-size:%3pt;\">%4</span></p></body></html>").arg(Settings::scaled(12)).arg(s1).arg(Settings::scaled(9)).arg(s2));
ui->infoEdit->appendPlainText(tr("Dictionary import done."));
ui->finishButton->setText(tr("Finish"));
ui->finishButton->setEnabled(true);
}
break;
case Modes::Export:
if (!doImportFromExport())
{
step = -1;
if (isVisible() /*loop.isRunning()*/ && !ui->finishButton->isEnabled())
{
ui->finishButton->setText(tr("Abort"));
ui->finishButton->setEnabled(true);
}
}
else
{
QString s1 = tr("Import finished.");
QString s2 = tr("Press \"%1\" to close the importer.").arg(tr("Finish"));
ui->progressLabel->setText(QString("<html><head/><body><p><span style=\"font-size:%1pt;\">%2</span></p><p><span style=\"font-size:%3pt;\">%4</span></p></body></html>").arg(Settings::scaled(12)).arg(s1).arg(Settings::scaled(9)).arg(s2));
ui->infoEdit->appendPlainText(tr("Dictionary import done."));
ui->finishButton->setText(tr("Finish"));
ui->finishButton->setEnabled(true);
}
break;
case Modes::Partial:
if (!doImportFromExportPartial())
{
step = -1;
if (isVisible() /*loop.isRunning()*/ && !ui->finishButton->isEnabled())
{
ui->finishButton->setText(tr("Abort"));
ui->finishButton->setEnabled(true);
}
}
else
{
QString s1 = tr("Import finished.");
QString s2 = tr("Press \"%1\" to close the importer.").arg(tr("Finish"));
ui->progressLabel->setText(QString("<html><head/><body><p><span style=\"font-size:%1pt;\">%2</span></p><p><span style=\"font-size:%3pt;\">%4</span></p></body></html>").arg(Settings::scaled(12)).arg(s1).arg(Settings::scaled(9)).arg(s2));
ui->infoEdit->appendPlainText(tr("Dictionary import done."));
ui->finishButton->setText(tr("Finish"));
ui->finishButton->setEnabled(true);
}
break;
case Modes::Examples:
if (!doImportExamples())
{
step = -1;
if (isVisible() /*loop.isRunning()*/ && !ui->finishButton->isEnabled())
{
ui->finishButton->setText(tr("Abort"));
ui->finishButton->setEnabled(true);
}
}
else
{
QString s1 = tr("Import finished.");
QString s2 = tr("Press \"%1\" to close the importer and continue starting the program.").arg(tr("Finish"));
ui->progressLabel->setText(QString("<html><head/><body><p><span style=\"font-size:%1pt;\">%2</span></p><p><span style=\"font-size:%3pt;\">%4</span></p></body></html>").arg(Settings::scaled(12)).arg(s1).arg(Settings::scaled(9)).arg(s2));
ui->infoEdit->appendPlainText(tr("Example database import done."));
ui->finishButton->setText(tr("Finish"));
ui->finishButton->setEnabled(true);
}
break;
case Modes::User:
if (!doImportUserData())
{
step = -1;
if (isVisible() /*loop.isRunning()*/ && !ui->finishButton->isEnabled())
{
ui->finishButton->setText(tr("Abort"));
ui->finishButton->setEnabled(true);
}
}
else
{
QString s1 = tr("Import finished.");
QString s2 = tr("Press \"%1\" to close the importer.").arg(tr("Finish"));
ui->progressLabel->setText(QString("<html><head/><body><p><span style=\"font-size:%1pt;\">%2</span></p><p><span style=\"font-size:%3pt;\">%4</span></p></body></html>").arg(Settings::scaled(12)).arg(s1).arg(Settings::scaled(9)).arg(s2));
ui->infoEdit->appendPlainText(tr("User data import done."));
ui->finishButton->setText(tr("Finish"));
ui->finishButton->setEnabled(true);
}
break;
}
return true;
}
return base::event(e);
}
void DictImport::closeAfterImport()
{
setAttribute(Qt::WA_QuitOnClose, false);
close();
}
bool DictImport::doImportExamples()
{
// examples.utf file format:
//
// # is for comments.
// There are A and B lines starting with the characters "A:" or "B:". A lines contain the
// example sentences, Japanese first, followed by the TAB character and the English
// sentence. At the end of the line the #ID=XXXX_XXXX string represents a unique id.
// The first part of the ID is the English sentence identifier, the second part is the
// Japanese sentence identifier.
// B lines paired with the A lines contain the Japanese words found in the previous
// sentence. Each word can be followed by some data in () or [] or {}. Data in [] is
// ignored. Text inside () is the kana form of the word where necessary. Data in {} is the
// form of the word as found in the previous sentence. When a word is followed by the ~
// character, that means it's a checked and good example sentence.
// examples.zkj notes:
//
// Warning: file versions before 2018 are not supported.
//
// The file starts with a short header describing the file version, and the time the file
// was written. After this a 32 bit integer holding the number of bytes taken up by the
// example sentences data, then the data.
// The example sentences data is written in blocks, each block holds at most 100
// sentences. (Exactly 100 apart from the last block.) Each block of data is compressed
// separately with zLib via Qt's QByteArray::qCompress. The resulting compressed data is
// prepended by a 32bit unsigned integer in little-endian order which is the size in bytes
// of the compressed data. (This is done by qCompress.) A sentence in a data block
// contains the Japanese and the English version, and a list of words in the Japanese
// sentence. A single word in the sentence is represented by the word's position, length
// as found in the sentence, paired with one or more kanji and kana. After the sentences
// blocks is a list of the block positions and their compressed sizes. This is followed by
// the word data written in the word commons tree. These are compressed the same way.
// After the end of the positions is a compressed list of sentence IDs in the order they
// are in the blocks.
//
// See details in sentences.cpp.
if (!setInfoText(tr("Opening examples.utf...")))
return false;
if (!file.open(path + "/examples.utf"))
{
setErrorText(tr("Couldn't open examples.utf."));
return false;
}
ImportFileHandlerGuard fileguard(file);
if (!setInfoText(tr("Opened file...")))
return false;
QFile of;
of.setFileName(outpath);
if (!of.open(QIODevice::ReadWrite | QIODevice::Truncate))
return false;
ZKanji::commons.clearExamplesData();
QDataStream ostream(&of);
ostream.setVersion(QDataStream::Qt_5_5);
ostream.setByteOrder(QDataStream::LittleEndian);
ostream.writeRawData("zex", 3);
ostream.writeRawData(ZKANJI_EXAMPLES_FILE_VERSION, 3);
QDateTime tempnow = QDateTime::currentDateTimeUtc();
ostream << make_zdate(tempnow);
QString tempverstr = QString::fromLatin1(ZKANJI_PROGRAM_VERSION);
ostream << make_zstr(tempverstr, ZStrFormat::Byte);
// Position of the next value saved, so we can seek back here later.
int startpos = of.pos();
// Writing empty 4 bytes which will be replaced by the size of blocks to skip. Will write
// quint32 later.
ostream.writeRawData(" ", 4);
// Buffer that collects at most 100 sentences data. Its contents will be compressed and
// written to file.
std::vector<uchar> buff;
qint64 s = file.size();
ui->progressBar->setMaximum(s);
QString line;
bool Aline = true;
// The Japanese sentence
QString jpn;
// Japanese sentence id
int id_jp = 0;
// The English sentence
QString trans;
// English sentence id
int id_tr = 0;
// Japanese and English id pairs in order they are found in the imported and created data.
std::vector<std::pair<int, int>> ids;
// Index of the current block. Incremented at every 100 sentences.
ushort blockix = 0;
// Index of the current sentence in the current block.
uchar sentenceix = 0;
// Index of the current word in the current sentence.
uchar wordix = 0;
// A list of block positions written to file.
std::vector<int> blockpos;
if (!setInfoText(tr("Processing data...")))
return false;
QSet<std::pair<int, int>> idtaken;
while (file.getLine(line))
{
if (!nextUpdate(file.pos()))
return false;
if (line.isEmpty() || line.at(0) == '#')
continue;
int tabpos = -1;
// Skip errors.
if (line.size() < 4 || line.at(1) != ':' || (line.at(0) != 'A' && line.at(0) != 'B') || line.at(2) != ' ' ||
(line.at(0) == 'A' && !Aline) || (line.at(0) == 'B' && Aline) || (Aline && (tabpos = line.indexOf('\t')) < 4))
{
// Back to looking for A line because the next B line might not be a good match.
Aline = true;
continue;
}
line.remove(0, 3);
if (Aline)
{
tabpos -= 3;
jpn = line.left(tabpos);
int idpos = line.indexOf("#ID=");
trans = line.mid(tabpos + 1, idpos - tabpos - 1);
bool ok = false;
QVector<QStringRef> lineids = line.midRef(idpos + 4).split('_');
if (lineids.size() == 2)
{
// In the WWWJDIC format the Japanese id comes second. When switching to the
// Tatoeba format, swap the ids.
id_jp = lineids.at(1).toInt(&ok);
if (ok)
id_tr = lineids.at(0).toInt(&ok);
}
if (!jpn.isEmpty() && !trans.isEmpty() && ok && !idtaken.contains(std::make_pair(id_jp, id_tr)))
Aline = false;
continue;
}
Aline = true;
int jpnpos = 0;
int jpnsiz = jpn.size();
QCharTokenizer tokens(line.constData(), line.size(), qcharisspace);
std::vector<ExampleWordsData> exwords;
while (tokens.next() && jpnpos < jpnsiz)
{
// Check every word in the line for an equivalent in the Japanese sentence.
const QChar *tok = tokens.token();
int tsiz = tokens.tokenSize();
int wsiz = -1;
// The length of the actual word might be less than tsiz, when the extra data is
// removed.
for (int ix = 0; ix != tsiz && wsiz == -1; ++ix)
if (tok[ix] == '[' || tok[ix] == '{' || tok[ix] == '~' || tok[ix] == '(')
wsiz = ix;
if (wsiz == -1)
wsiz = tsiz;
// Current word.
ushort wordpos = 0;
ushort wordlen = 0;
std::vector<ExampleWordsData::Form> wordforms;
// The written form of the word as specified.
const QChar *kanjiform = nullptr;
// The kana form of the word if specified or if the word consist only of kana.
const QChar *kanaform = nullptr;
// The form of the word as found in the example sentence.
const QChar *exform = nullptr;
int kanjisiz = 0;
int kanasiz = 0;
int exsiz = 0;
kanjiform = tok;
kanjisiz = wsiz;
// Position of the word in the example sentence.
int expos = -1;
// Look for kanji in the word. If not found, the kana and kanji form is the same.
// If found and there's a kana representation between (), that's the hiragana
// form.
bool haskanji = false;
for (int ix = 0; ix != kanjisiz && !haskanji; ++ix)
haskanji = !KANA(kanjiform[ix].unicode());
if (!haskanji)
{
kanaform = kanjiform;
kanasiz = kanjisiz;
}
// Kana representation and form in the example sentence when specified.
for (int ix = wsiz; ix != tsiz && (kanaform == nullptr || exform == nullptr); ++ix)
{
if (tok[ix] == '(' || tok[ix] == '{')
{
for (int iy = ix + 1; iy != tsiz; ++iy)
{
if (tok[iy] == ')' && tok[ix] == '(')
{
if (kanaform == nullptr)
{
kanaform = tok + ix + 1;
kanasiz = iy - (ix + 1);
}
ix = iy;
break;
}
if (tok[iy] == '}' && tok[ix] == '{')
{
if (exform == nullptr)
{
exform = tok + ix + 1;
exsiz = iy - (ix + 1);
}
ix = iy;
break;
}
}
}
} // For-loop end of kana representation or example form.
if (exform == nullptr)
{
exform = kanjiform;
exsiz = kanjisiz;
}
wordlen = exsiz;
const QChar *jpndat = jpn.constData();
// Find the position of the word in the Japanese sentence. Note: Using < instead
// of != because ix might be over the size.
for (int ix = jpnpos; ix < jpnsiz - exsiz + 1 && expos == -1; ++ix)
{
if (qcharncmp(exform, jpndat + ix, exsiz) == 0)
{
expos = ix;
wordpos = expos;
jpnpos = expos + exsiz;
}
}
if (expos == -1 || (kanjisiz == 0 && kanasiz == 0))
continue;
// Found everything needed from the sentences. Look in the dictionary for matching
// words. Words are matching if:
// - Both kanji and kana form are specified. A word is written even if nothing is
// found in the dictionary.
// - Both kanji and kana form are specified, the matching word has a different
// kanji form but the kana form is the same, and the word definition exactly
// matches the specified word.
// - Only kanji form is found. Every word matches that has the same kanji.
// Look for a word entry in the dictionary having the same kanji and kana.
std::vector<int> wordsfound;
if (kanaform != nullptr)
{
int wix = dict->findKanjiKanaWord(kanjiform, kanaform, nullptr, kanjisiz, kanasiz, -1);
if (wix != -1)
{
WordEntry *e = dict->wordEntry(wix);
dict->findKanaWords(wordsfound, QString(kanaform, kanasiz), 0, true, nullptr, nullptr);
// Only use words that have the exact same definition that e has.
for (int ix = tosigned(wordsfound.size()) - 1; ix != -1; --ix)
{
WordEntry *we = dict->wordEntry(wordsfound[ix]);
if (!definitionsMatch(e, we))
wordsfound.erase(wordsfound.begin() + ix);
}
}
}
else
{
dict->findKanjiWords(wordsfound, QString(kanjiform, kanjisiz), 0, true, nullptr, nullptr);
// No words found and no kana form is specified.
if (wordsfound.empty())
continue;
}
QCharString kanjidat;
QCharString kanadat;
if (wordsfound.empty())
{
kanjidat.copy(kanjiform, kanjisiz);
kanadat.copy(kanaform, kanasiz);
if (ZKanji::commons.addExample(kanjidat.data(), kanadat.data(), { blockix, sentenceix, wordix }) != -1)
wordforms.push_back({ std::move(kanjidat), std::move(kanadat) });
}
else
{
for (int ix = 0, siz = tosigned(wordsfound.size()); ix != siz; ++ix)
{
WordEntry *we = dict->wordEntry(wordsfound[ix]);
kanjidat = we->kanji;
kanadat = we->kana;
if (ZKanji::commons.addExample(kanjidat.data(), kanadat.data(), { blockix, sentenceix, wordix }) != -1)
wordforms.push_back({ std::move(kanjidat), std::move(kanadat) });
}
}
// Unlikely but if no word data were added to the commons, skip the word.
// Otherwise add it.
if (!wordforms.empty() && wordix < UCHAR_MAX)
{
ExampleWordsData wdata;
wdata.pos = wordpos;
wdata.len = wordlen;
wdata.forms.resize((quint16)wordforms.size());
for (int ix = 0, siz = tosigned(wordforms.size()); ix != siz; ++ix)
wdata.forms[ix] = std::move(wordforms[ix]);
exwords.push_back(std::move(wdata));
++wordix;
}
}
wordix = 0;
// At most 255 words are supported.
if (exwords.empty() || exwords.size() > 255)
continue;
std::pair<int, int> sid = std::make_pair(id_jp, id_tr);
idtaken.insert(sid);
ids.push_back(sid);
doImportExamplesSentenceHelper(buff, jpn, trans, exwords);
exwords.clear();
++sentenceix;
if (sentenceix == 100)
{
// Compress the buffer and empty it.
QByteArray dat = qCompress(buff.data(), tosigned(buff.size()));
blockpos.push_back(of.pos());
ostream.writeRawData(dat.constData(), dat.size());
buff.clear();
sentenceix = 0;
wordix = 0;
if (blockix == USHRT_MAX)
throw ZException("More than 6 million sentences in the example database.");
++blockix;
}
}
file.close();
// There's remaining data to write. Do the same as above.
if (sentenceix != 0)
{
// Compress the buffer and empty it.
QByteArray dat = qCompress(buff.data(), tosigned(buff.size()));
blockpos.push_back(of.pos());