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
|
/**
This file is part of Kiten, a KDE Japanese Reference Tool...
Copyright (C) 2001 Jason Katz-Brown <[email protected]>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301
USA
**/
#include <kdebug.h>
#include <tdelocale.h>
#include <tdemessagebox.h>
#include <kprocess.h>
#include <kstandarddirs.h>
#include <tqfileinfo.h>
#include <tqregexp.h>
#include <tqtextcodec.h>
#include "dict.h"
#include <iostream>
#include <cassert>
#include <sys/mman.h>
#include <stdio.h>
namespace
{
void msgerr(const TQString &msg, const TQString &dict = TQString())
{
TQString output = msg;
if (!dict.isNull())
output = msg.arg(dict);
KMessageBox::error(0, output);
}
}
using namespace Dict;
TextType Dict::textType(const TQString &text)
{
ushort first = text.at(0).unicode();
if (first < 0x3000)
return Text_Latin;
// else if (first < 0x3040) // CJK Symbols and Punctuation
// return Text_Kana;
// else if (first < 0x30A0) // Hiragana
// return Text_Kana;
else if (first < 0x3100) // Katakana
return Text_Kana;
else /*if (first >= 0x3400 && first < 0x4DC0)*/ // CJK Unified Ideographs Extension A
return Text_Kanji;
}
File::File(TQString path, TQString n)
: myName(n)
, dictFile(path)
, dictPtr((const unsigned char *)MAP_FAILED)
, indexFile(TDEGlobal::dirs()->saveLocation("data", "kiten/xjdx/", true) + TQFileInfo(path).baseName() + ".xjdx")
, indexPtr((const uint32_t *)MAP_FAILED)
, valid(false)
{
bool forceUpdate = false;
bool indexFileExists = indexFile.exists();
if (indexFileExists)
{
// ### change this if need be!!
const int indexFileVersion = 14;
// this up-to-date code from xjdservcomm.c
// we need to check if the index needs to
// remade
int dictionaryLength;
TQFile dictionary(path);
dictionaryLength = dictionary.size();
dictionaryLength++;
//kdDebug() << "dictionaryLength = " << dictionaryLength << endl;
int32_t testWord[1];
fread(&testWord[0], sizeof(int32_t), 1, fopen(indexFile.name().latin1(), "rb"));
//kdDebug() << "testWord[0] = " << testWord[0] << endl;
if (testWord[0] != (dictionaryLength + indexFileVersion))
forceUpdate = true;
}
if (!indexFileExists || forceUpdate)
{
//kdDebug() << "creating " << indexFile.name() << endl;
// find the index generator executable
TDEProcess proc;
proc << TDEStandardDirs::findExe("kitengen") << path << indexFile.name();
// TODO: put up a status dialog and event loop instead of blocking
proc.start(TDEProcess::Block, TDEProcess::NoCommunication);
}
if (!dictFile.open(IO_ReadOnly))
{
msgerr(i18n("Could not open dictionary %1."), path);
return;
}
dictPtr = (const unsigned char *)mmap(0, dictFile.size(), PROT_READ, MAP_SHARED, dictFile.handle(), 0);
if (dictPtr == (unsigned char*) MAP_FAILED)
{
msgerr(i18n("Memory error when loading dictionary %1."), path);
return;
}
if (!indexFile.open(IO_ReadOnly))
{
msgerr(i18n("Could not open index for dictionary %1."), path);
return;
}
indexPtr = (const uint32_t*)mmap(0, indexFile.size(), PROT_READ, MAP_SHARED, indexFile.handle(), 0);
if (indexPtr == (uint32_t*) MAP_FAILED)
{
msgerr(i18n("Memory error when loading dictionary %1's index file."), path);
return;
}
valid = true;
}
File::~File(void)
{
if (dictPtr != (unsigned char*) MAP_FAILED)
munmap((char *)dictPtr, dictFile.size());
dictFile.close();
if (indexPtr != (uint32_t*) MAP_FAILED)
munmap((char *)indexPtr, indexFile.size());
indexFile.close();
}
TQString File::name(void)
{
return myName;
}
Array<const unsigned char> File::dict(void)
{
assert(valid);
return Array<const unsigned char>(dictPtr, dictFile.size());
}
Array<const uint32_t> File::index(void)
{
assert(valid);
return Array<const uint32_t>(indexPtr, indexFile.size());
}
int File::dictLength(void)
{
return dictFile.size();
}
int File::indexLength(void)
{
return indexFile.size();
}
bool File::isValid(void)
{
return valid;
}
// returns specified character from a dictionary
unsigned char File::lookup(unsigned i, int offset)
{
uint32_t pos = indexPtr[i] + offset - 1;
if (pos > dictFile.size()) return 10;
return dictPtr[pos];
}
TQCString File::lookup(unsigned i)
{
uint32_t start = indexPtr[i] - 1;
uint32_t pos = start;
const unsigned size = dictFile.size();
// get the whole word
while(pos <= size && dictPtr[pos] != 0 && dictPtr[pos] != 0x0a)
++pos;
// put the word in the TQCString
TQCString retval((const char *)(dictPtr + start), pos - start);
// tack on a null
char null = 0;
retval.append(&null);
// and away we go
return retval;
}
// And last, Index itself is the API presented to the rest of Kiten
Index::Index()
: TQObject()
{
dictFiles.setAutoDelete(true);
kanjiDictFiles.setAutoDelete(true);
}
Index::~Index()
{
}
void Index::setDictList(const TQStringList &list, const TQStringList &names)
{
loadDictList(dictFiles, list, names);
}
void Index::setKanjiDictList(const TQStringList &list, const TQStringList &names)
{
loadDictList(kanjiDictFiles, list, names);
}
void Index::loadDictList(TQPtrList<File> &fileList, const TQStringList &dictList, const TQStringList &dictNameList)
{
fileList.clear();
// check if we have a dict
if (dictList.size() < 1)
{
msgerr(i18n("No dictionaries in list!"));
return;
}
TQStringList::ConstIterator it;
TQStringList::ConstIterator dictIt;
for (it = dictList.begin(), dictIt = dictNameList.begin(); it != dictList.end(); ++it, ++dictIt)
{
File *f = new File(*it, *dictIt);
// our ugly substitute for exceptions
if (f->isValid())
fileList.append(f);
else
delete f;
}
}
TQStringList Index::doSearch(File &file, const TQString &text)
{
// Do a binary search to find an entry that matches text
TQTextCodec &codec = *TQTextCodec::codecForName("eucJP");
TQCString eucString = codec.fromUnicode(text);
TQString prevResult;
Array<const uint32_t> index = file.index();
Array<const unsigned char> dict = file.dict();
int lo = 0;
int hi = index.size() - 1;
unsigned cur;
int comp = 0;
do
{
cur = (hi + lo) / 2;
comp = stringCompare(file, cur, eucString);
if (comp < 0)
hi = cur - 1;
else if (comp > 0)
lo = cur + 1;
}
while(hi >= lo && comp != 0 && !(hi == 0 && lo == 0));
TQStringList results;
// A match?
if (comp == 0)
{
// wheel back to make sure we get the first matching entry
while(cur - 1 && 0 == stringCompare(file, cur - 1, eucString))
--cur;
// output every matching entry
while(cur < index.size() && 0 == stringCompare(file, cur, eucString))
{
// because the index doesn't point
// to the start of the line, find the
// start of the line:
int i = 0;
while(file.lookup(cur, i - 1) != 0x0a) --i;
TQByteArray bytes(0);
while(file.lookup(cur, i) != 0x0a) // get to end of our line
{
const char eucchar = file.lookup(cur, i);
bytes.resize(bytes.size() + 1);
bytes[bytes.size() - 1] = eucchar;
++i;
}
TQString result = codec.toUnicode(bytes) + TQString("\n");
if (prevResult != result)
{
results.append(result);
prevResult = result;
}
++cur;
}
}
// return all the entries found, or null if no match
return results;
}
SearchResult Index::scanResults(TQRegExp regexp, TQStringList results, bool common)
{
unsigned int num = 0;
unsigned int fullNum = 0;
SearchResult ret;
//ret.results = results; //not here..
for (TQStringList::Iterator itr = results.begin(); itr != results.end(); ++itr)
{
if ((*itr).left(5) == "DICT " || (*itr).left(8) == "HEADING ")
{
ret.list.append(parse(*itr));
continue;
}
int found = regexp.search(*itr);
if (found >= 0)
{
++fullNum;
if ((*itr).find(TQString("(P)")) >= 0 || !common)
{
// we append HERE, so we get the exact
// results we have in ret.list
ret.results.append(*itr);
ret.list.append(parse(*itr));
++num;
}
}
}
ret.count = num;
ret.outOf = fullNum;
ret.common = common;
return ret;
}
SearchResult Index::search(TQRegExp regexp, const TQString &text, bool common)
{
TQStringList results;
for (TQPtrListIterator<File> file(dictFiles); *file; ++file)
{
results.append(TQString("DICT ") + (*file)->name());
results += doSearch(**file, text);
}
SearchResult res = scanResults(regexp, results, common);
res.text = text;
return res;
}
SearchResult Index::scanKanjiResults(TQRegExp regexp, TQStringList results, bool common)
{
unsigned int num = 0;
unsigned int fullNum = 0;
const bool jmyCount = false; // don't count JinMeiYou as common
SearchResult ret;
ret.results = results;
for (TQStringList::Iterator itr = results.begin(); itr != results.end(); ++itr)
{
if ((*itr).left(5) == "DICT " || (*itr).left(8) == "HEADING ")
{
ret.list.append(kanjiParse(*itr));
continue;
}
int found = regexp.search(*itr);
if (found >= 0)
{
++fullNum;
// common entries have G[1-8] (jouyou)
TQRegExp comregexp(jmyCount ? "G[1-9]" : "G[1-8]");
if ((*itr).find(comregexp) >= 0 || !common)
{
ret.list.append(kanjiParse(*itr));
++num;
}
}
}
ret.count = num;
ret.outOf = fullNum;
ret.common = common;
return ret;
}
SearchResult Index::searchKanji(TQRegExp regexp, const TQString &text, bool common)
{
TQStringList results;
for (TQPtrListIterator<File> file(kanjiDictFiles); *file; ++file)
{
results.append(TQString("DICT ") + (*file)->name());
results += doSearch(**file, text);
}
SearchResult res = scanKanjiResults(regexp, results, common);
res.text = text;
return res;
}
SearchResult Index::searchPrevious(TQRegExp regexp, const TQString &text, SearchResult list, bool common)
{
SearchResult res;
if (firstEntry(list).extendedKanjiInfo())
res = scanKanjiResults(regexp, list.results, common);
else
res = scanResults(regexp, list.results, common);
res.text = text;
return res;
}
TQRegExp Dict::Index::createRegExp(SearchType type, const TQString &text, DictionaryType dictionaryType, bool caseSensitive)
{
TQString regExp;
switch (type)
{
case Search_Beginning:
switch (textType(text))
{
case Dict::Text_Latin:
regExp = "\\W%1";
break;
case Dict::Text_Kana:
if (dictionaryType == Kanjidict)
regExp = "\\W%1";
else // edict
regExp = "\\[%1";
break;
case Dict::Text_Kanji:
regExp = "^%1";
}
break;
case Search_FullWord:
switch (textType(text))
{
case Dict::Text_Latin:
regExp = "\\W%1\\W";
break;
case Dict::Text_Kana:
if (dictionaryType == Kanjidict)
regExp = " %1 ";
else // edict
regExp = "\\[%1\\]";
break;
case Dict::Text_Kanji:
regExp = "^%1\\W";
}
break;
case Search_Anywhere:
regExp = "%1";
}
return TQRegExp(regExp.arg(text), caseSensitive);
}
int Index::stringCompare(File &file, int index, TQCString str)
{
return eucStringCompare(file.lookup(index), str);
}
// effectively does a strnicmp on two "strings"
// except it will make katakana and hiragana match (EUC A4 & A5)
int Dict::eucStringCompare(const char *str, const char *str2)
{
for (unsigned i = 0; ; ++i)
{
unsigned char c = static_cast<unsigned char>(str[i]);
unsigned char c2 = static_cast<unsigned char>(str2[i]);
if ((c2 == '\0') || (c == '\0'))
return 0;
if ((i % 2) == 0)
{
if (c2 == 0xA5)
c2 = 0xA4;
if (c == 0xA5)
c = 0xA4;
}
if ((c2 >= 'A') && (c2 <= 'Z')) c2 |= 0x20; /*fix ucase*/
if ((c >= 'A') && (c <= 'Z')) c |= 0x20;
if (c2 != c)
return (int)c2 - (int)c;
}
return 0;
}
bool Dict::isEUC(unsigned char c)
{
return (c & 0x80);
}
Entry Dict::parse(const TQString &raw)
{
unsigned int length = raw.length();
if (raw.left(5) == "DICT ")
return Entry(raw.right(length - 5));
if (raw.left(8) == "HEADING ")
return Entry(raw.right(length - 8), true);
TQString reading;
TQString kanji;
TQStringList meanings;
TQString curmeaning;
bool firstmeaning = true;
TQCString parsemode("kanji");
unsigned int i;
for (i = 0; i < length; i++)
{
TQChar ichar(raw.at(i));
if (ichar == '[')
{
parsemode = "reading";
}
else if (ichar == ']')
{
// do nothing
}
else if (ichar == '/')
{
if (!firstmeaning)
{
meanings.append(curmeaning);
curmeaning = "";
}
else
{
firstmeaning = false;
parsemode = "meaning";
}
}
else if (ichar == ' ')
{
if (parsemode == "meaning") // only one that needs the space
curmeaning += ' ';
}
else if (parsemode == "kanji")
{
kanji += ichar;
}
else if (parsemode == "meaning")
{
curmeaning += ichar;
}
else if (parsemode == "reading")
{
reading += ichar;
}
}
return (Entry(kanji, reading, meanings));
}
Entry Dict::kanjiParse(const TQString &raw)
{
unsigned int length = raw.length();
if (raw.left(5) == "DICT ")
return Entry(raw.right(length - 5));
if (raw.left(8) == "HEADING ")
return Entry(raw.right(length - 8), true);
TQStringList readings;
TQString kanji;
TQStringList meanings;
TQString curmeaning;
TQString curreading;
TQString strfreq;
TQString strgrade;
TQString strstrokes;
TQString strmiscount = "";
bool prevwasspace = true;
TQChar detailname;
TQCString parsemode("kanji");
// if there are two S entries, second is common miscount
bool strokesset = false;
unsigned int i;
TQChar ichar;
for (i = 0; i < length; i++)
{
ichar = raw.at(i);
if (ichar == ' ')
{
if (parsemode == "reading")
{
readings.append(curreading);
curreading = "";
}
else if (parsemode == "kanji")
{
parsemode = "misc";
}
else if (parsemode == "detail")
{
if (detailname == 'S')
strokesset = true;
parsemode = "misc";
}
else if (parsemode == "meaning")
{
curmeaning += ichar;
}
prevwasspace = true;
}
else if (ichar == '{')
{
parsemode = "meaning";
}
else if (ichar == '}')
{
meanings.append(curmeaning);
curmeaning = "";
}
else if (parsemode == "detail")
{
if (detailname == 'G')
{
strgrade += ichar;
}
else if (detailname == 'F')
{
strfreq += ichar;
}
else if (detailname == 'S')
{
if (strokesset)
strmiscount += ichar;
else
strstrokes += ichar;
}
prevwasspace = false;
}
else if (parsemode == "kanji")
{
kanji += ichar;
}
else if (parsemode == "meaning")
{
curmeaning += ichar;
}
else if (parsemode == "reading")
{
curreading += ichar;
}
else if (parsemode == "misc" && prevwasspace)
{
if (TQRegExp("[A-Za-z0-9]").search(TQString(ichar)) >= 0)
// is non-japanese?
{
detailname = ichar;
parsemode = "detail";
}
else
{
curreading = TQString(ichar);
parsemode = "reading";
}
}
}
return (Entry(kanji, readings, meanings, strgrade.toUInt(), strfreq.toUInt(), strstrokes.toUInt(), strmiscount.toUInt()));
}
TQString Dict::prettyMeaning(TQStringList Meanings)
{
TQString meanings;
TQStringList::Iterator it;
for (it = Meanings.begin(); it != Meanings.end(); ++it)
meanings.append((*it).stripWhiteSpace()).append("; ");
meanings.truncate(meanings.length() - 2);
return meanings;
}
TQString Dict::prettyKanjiReading(TQStringList Readings)
{
TQStringList::Iterator it;
TQString html;
for (it = Readings.begin(); it != Readings.end(); ++it)
{
if ((*it) == "T1")
html += i18n("In names: ");
else
{
if ((*it) == "T2")
html += i18n("As radical: ");
else
{
html += (*it).stripWhiteSpace();
html += ", ";
}
}
}
html.truncate(html.length() - 2); // get rid of last ,
return html;
}
Dict::Entry Dict::firstEntry(Dict::SearchResult result)
{
for (TQValueListIterator<Dict::Entry> it = result.list.begin(); it != result.list.end(); ++it)
{
if ((*it).dictName() == "__NOTSET" && (*it).header() == "__NOTSET")
return (*it);
}
return Dict::Entry("__NOTHING");
}
TQString Dict::firstEntryText(Dict::SearchResult result)
{
for (TQStringList::Iterator it = result.results.begin(); it != result.results.end(); ++it)
{
if ((*it).left(5) != "DICT " && (*it).left(7) != "HEADER ")
return (*it);
}
return TQString("NONE ");
}
///////////////////////////////////////////////////////////////
Entry::Entry(const TQString & kanji, const TQString & reading, const TQStringList &meanings)
: DictName(TQString::fromLatin1("__NOTSET"))
, Header(TQString::fromLatin1("__NOTSET"))
, Meanings(meanings)
, Kanji(kanji)
, KanaOnly(reading.isEmpty())
, Readings(KanaOnly ? kanji : reading)
, ExtendedKanjiInfo(false)
, Grade(0)
, Strokes(0)
, Miscount(0)
, Freq(0)
{
}
Entry::Entry(const TQString &kanji, TQStringList &readings, TQStringList &meanings, unsigned int grade, unsigned int freq, unsigned int strokes, unsigned int miscount)
: DictName(TQString::fromLatin1("__NOTSET"))
, Header(TQString::fromLatin1("__NOTSET"))
, Meanings(meanings)
, Kanji(kanji)
, KanaOnly(false)
, Readings(readings)
, ExtendedKanjiInfo(true)
, Grade(grade)
, Strokes(strokes)
, Miscount(miscount)
, Freq(freq)
{
}
Entry::Entry(const TQString &dictname)
: KanaOnly(true)
, ExtendedKanjiInfo(false)
{
DictName = dictname;
}
Entry::Entry(const TQString &headername, bool)
: DictName(TQString::fromLatin1("__NOTSET"))
, Header(headername)
, KanaOnly(true)
, ExtendedKanjiInfo(false)
{
}
TQString Entry::dictName()
{
return DictName;
}
TQString Entry::header()
{
return Header;
}
bool Entry::kanaOnly()
{
return KanaOnly;
}
TQString Entry::kanji()
{
return Kanji;
}
TQStringList Entry::readings()
{
return Readings;
}
TQString Entry::firstReading()
{
return *Readings.at(0);
}
TQStringList Entry::meanings()
{
return Meanings;
}
unsigned int Entry::grade()
{
return Grade;
}
unsigned int Entry::freq()
{
return Freq;
}
unsigned int Entry::miscount()
{
return Miscount;
}
unsigned int Entry::strokes()
{
return Strokes;
}
bool Entry::extendedKanjiInfo()
{
return ExtendedKanjiInfo;
}
#include "dict.moc"
|