File: dictdfiles.cc

package info (click to toggle)
goldendict 1.5.0~rc2%2Bgit20181207%2Bds-1
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 16,496 kB
  • sloc: cpp: 58,990; ansic: 11,311; xml: 488; makefile: 77; sh: 42
file content (812 lines) | stat: -rw-r--r-- 25,975 bytes parent folder | download
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
/* This file is (c) 2008-2012 Konstantin Isakov <ikm@goldendict.org>
 * Part of GoldenDict. Licensed under GPLv3 or later, see the LICENSE file */

#include "dictdfiles.hh"
#include "btreeidx.hh"
#include "folding.hh"
#include "utf8.hh"
#include "dictzip.h"
#include "htmlescape.hh"
#include "fsencoding.hh"
#include "langcoder.hh"
#include <map>
#include <set>
#include <string>
#include <vector>
#include <list>
#include <wctype.h>
#include <stdlib.h>
#include "gddebug.hh"
#include "ftshelpers.hh"
#include <QUrl>

#include <QDebug>

#if QT_VERSION >= QT_VERSION_CHECK( 5, 0, 0 )
#include <QRegularExpression>
#endif

#ifdef _MSC_VER
#include <stub_msvc.h>
#endif

namespace DictdFiles {

using std::map;
using std::multimap;
using std::pair;
using std::set;
using std::string;
using gd::wstring;
using std::vector;
using std::list;

using BtreeIndexing::WordArticleLink;
using BtreeIndexing::IndexedWords;
using BtreeIndexing::IndexInfo;

namespace {

DEF_EX_STR( exCantReadFile, "Can't read file", Dictionary::Ex )
DEF_EX( exFailedToReadLineFromIndex, "Failed to read line from index file", Dictionary::Ex )
DEF_EX( exMalformedIndexFileLine, "Malformed index file line encountered", Dictionary::Ex )
DEF_EX( exInvalidBase64, "Invalid base64 sequence encountered", Dictionary::Ex )
DEF_EX_STR( exDictzipError, "DICTZIP error", Dictionary::Ex )

enum
{
  Signature = 0x58444344, // DCDX on little-endian, XDCD on big-endian
  CurrentFormatVersion = 5 + BtreeIndexing::FormatVersion + Folding::Version
};

struct IdxHeader
{
  uint32_t signature; // First comes the signature, DCDX
  uint32_t formatVersion; // File format version (CurrentFormatVersion)
  uint32_t wordCount; // Total number of words
  uint32_t articleCount; // Total number of articles
  uint32_t indexBtreeMaxElements; // Two fields from IndexInfo
  uint32_t indexRootOffset;
  uint32_t langFrom;  // Source language
  uint32_t langTo;    // Target language
}
#ifndef _MSC_VER
__attribute__((packed))
#endif
;

bool indexIsOldOrBad( string const & indexFile )
{
  File::Class idx( indexFile, "rb" );

  IdxHeader header;

  return idx.readRecords( &header, sizeof( header ), 1 ) != 1 ||
         header.signature != Signature ||
         header.formatVersion != CurrentFormatVersion;
}

class DictdDictionary: public BtreeIndexing::BtreeDictionary
{
  Mutex idxMutex;
  File::Class idx, indexFile; // The later is .index file
  IdxHeader idxHeader;
  dictData * dz;
  string dictionaryName;
  Mutex indexFileMutex, dzMutex;

public:

  DictdDictionary( string const & id, string const & indexFile,
                   vector< string > const & dictionaryFiles );

  ~DictdDictionary();

  virtual string getName() throw()
  { return dictionaryName; }

  virtual map< Dictionary::Property, string > getProperties() throw()
  { return map< Dictionary::Property, string >(); }

  virtual unsigned long getArticleCount() throw()
  { return idxHeader.articleCount; }

  virtual unsigned long getWordCount() throw()
  { return idxHeader.wordCount; }

  virtual void loadIcon() throw();

  inline virtual quint32 getLangFrom() const
  { return idxHeader.langFrom; }

  inline virtual quint32 getLangTo() const
  { return idxHeader.langTo; }

  virtual sptr< Dictionary::DataRequest > getArticle( wstring const &,
                                                      vector< wstring > const & alts,
                                                      wstring const &,
                                                      bool ignoreDiacritics )
    THROW_SPEC( std::exception );

  virtual QString const& getDescription();

  virtual sptr< Dictionary::DataRequest > getSearchResults( QString const & searchString,
                                                            int searchMode, bool matchCase,
                                                            int distanceBetweenWords,
                                                            int maxResults,
                                                            bool ignoreWordsOrder,
                                                            bool ignoreDiacritics );
  void getArticleText( uint32_t articleAddress, QString & headword, QString & text );

  virtual void makeFTSIndex(QAtomicInt & isCancelled, bool firstIteration );

  virtual void setFTSParameters( Config::FullTextSearch const & fts )
  {
    can_FTS = fts.enabled
              && !fts.disabledTypes.contains( "DICTD", Qt::CaseInsensitive )
              && ( fts.maxDictionarySize == 0 || getArticleCount() <= fts.maxDictionarySize );
  }
};

DictdDictionary::DictdDictionary( string const & id,
                                  string const & indexFile,
                                  vector< string > const & dictionaryFiles ):
  BtreeDictionary( id, dictionaryFiles ),
  idx( indexFile, "rb" ),
  indexFile( dictionaryFiles[ 0 ], "rb" ),
  idxHeader( idx.read< IdxHeader >() )
{

  // Read the dictionary name
  idx.seek( sizeof( idxHeader ) );

  vector< char > dName( idx.read< uint32_t >() );
  idx.read( &dName.front(), dName.size() );
  dictionaryName = string( &dName.front(), dName.size() );

  // Open the .dict file

  DZ_ERRORS error;
  dz = dict_data_open( dictionaryFiles[ 1 ].c_str(), &error, 0 );

  if ( !dz )
    throw exDictzipError( string( dz_error_str( error ) )
                          + "(" + getDictionaryFilenames()[ 1 ] + ")" );

  // Initialize the index

  openIndex( IndexInfo( idxHeader.indexBtreeMaxElements,
                        idxHeader.indexRootOffset ),
             idx, idxMutex );

  // Full-text search parameters

  can_FTS = true;

  ftsIdxName = indexFile + "_FTS";

  if( !Dictionary::needToRebuildIndex( dictionaryFiles, ftsIdxName )
      && !FtsHelpers::ftsIndexIsOldOrBad( ftsIdxName, this ) )
    FTS_index_completed.ref();
}

DictdDictionary::~DictdDictionary()
{
  if ( dz )
    dict_data_close( dz );
}

string nameFromFileName( string const & indexFileName )
{
  if ( indexFileName.empty() )
    return string();

  char const * sep = strrchr( indexFileName.c_str(), FsEncoding::separator() );

  if ( !sep )
    sep = indexFileName.c_str();

  char const * dot = strrchr( sep, '.' );

  if ( !dot )
    dot = indexFileName.c_str() + indexFileName.size();

  return Utf8::encode( FsEncoding::decode( string( sep + 1, dot - sep - 1 ) ) );
}

void DictdDictionary::loadIcon() throw()
{
  if ( dictionaryIconLoaded )
    return;

  QString fileName =
    QDir::fromNativeSeparators( FsEncoding::decode( getDictionaryFilenames()[ 0 ].c_str() ) );

  // Remove the extension
  fileName.chop( 5 );

  if( !loadIconFromFile( fileName ) )
  {
    // Load failed -- use default icons
    dictionaryNativeIcon = dictionaryIcon = QIcon(":/icons/icon32_dictd.png");
  }

  dictionaryIconLoaded = true;
}

uint32_t decodeBase64( string const & str )
{
  static char const digits[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

  uint32_t number = 0;

  for( char const * next = str.c_str(); *next; ++next )
  {
    char const * d = strchr( digits, *next );

    if ( !d )
      throw exInvalidBase64();

    number = number * 64 + ( d - digits );
  }

  return number;
}

sptr< Dictionary::DataRequest > DictdDictionary::getArticle( wstring const & word,
                                                             vector< wstring > const & alts,
                                                             wstring const &,
                                                             bool ignoreDiacritics )
  THROW_SPEC( std::exception )
{
  try
  {
    vector< WordArticleLink > chain = findArticles( word, ignoreDiacritics );

    for( unsigned x = 0; x < alts.size(); ++x )
    {
      /// Make an additional query for each alt

      vector< WordArticleLink > altChain = findArticles( alts[ x ], ignoreDiacritics );

      chain.insert( chain.end(), altChain.begin(), altChain.end() );
    }

    multimap< wstring, string > mainArticles, alternateArticles;

    set< uint32_t > articlesIncluded; // Some synonyms make it that the articles
                                      // appear several times. We combat this
                                      // by only allowing them to appear once.

    wstring wordCaseFolded = Folding::applySimpleCaseOnly( word );
    if( ignoreDiacritics )
      wordCaseFolded = Folding::applyDiacriticsOnly( wordCaseFolded );

    char buf[ 16384 ];

    for( unsigned x = 0; x < chain.size(); ++x )
    {
      if ( articlesIncluded.find( chain[ x ].articleOffset ) != articlesIncluded.end() )
        continue; // We already have this article in the body.

      // Now load that article

      {
        Mutex::Lock _( indexFileMutex );
        indexFile.seek( chain[ x ].articleOffset );

        if ( !indexFile.gets( buf, sizeof( buf ), true ) )
          throw exFailedToReadLineFromIndex();
      }

      char * tab1 = strchr( buf, '\t' );

      if ( !tab1 )
        throw exMalformedIndexFileLine();

      char * tab2 = strchr( tab1 + 1, '\t' );

      if ( !tab2 )
        throw exMalformedIndexFileLine();

      // After tab1 should be article offset, after tab2 -- article size

      uint32_t articleOffset = decodeBase64( string( tab1 + 1, tab2 - tab1 - 1 ) );

      char * tab3 = strchr( tab2 + 1, '\t');

      uint32_t articleSize;
      if ( tab3 )
      {
         articleSize = decodeBase64( string( tab2 + 1, tab3 - tab2 - 1 ) );
      }
      else
      {
        articleSize = decodeBase64( tab2 + 1 );
      }

      string articleText;

      char * articleBody;
      {
        Mutex::Lock _( dzMutex );
        articleBody = dict_data_read_( dz, articleOffset, articleSize, 0, 0 );
      }

      if ( !articleBody )
      {
        articleText = string( "<div class=\"dictd_article\">DICTZIP error: " )
                      + dict_error_str( dz ) + "</div>";
      }
      else
      {
#if QT_VERSION >= QT_VERSION_CHECK( 5, 0, 0 )
        static QRegularExpression phonetic( "\\\\([^\\\\]+)\\\\",
                                            QRegularExpression::CaseInsensitiveOption ); // phonetics: \stuff\ ...
        static QRegularExpression refs( "\\{([^\\{\\}]+)\\}",
                                        QRegularExpression::CaseInsensitiveOption );     // links: {stuff}
        static QRegularExpression links( "<a href=\"gdlookup://localhost/([^\"]*)\">",
                                         QRegularExpression::CaseInsensitiveOption );
        static QRegularExpression tags( "<[^>]*>",
                                        QRegularExpression::CaseInsensitiveOption );
#else
        static QRegExp phonetic( "\\\\([^\\\\]+)\\\\", Qt::CaseInsensitive ); // phonetics: \stuff\ ...
        static QRegExp refs( "\\{([^\\{\\}]+)\\}", Qt::CaseInsensitive );     // links: {stuff}
        static QRegExp links( "<a href=\"gdlookup://localhost/([^\"]*)\">", Qt::CaseInsensitive );
        static QRegExp tags( "<[^>]*>", Qt::CaseInsensitive );
#endif

        articleText = string( "<div class=\"dictd_article\"" );
        if( isToLanguageRTL() )
          articleText += " dir=\"rtl\"";
        articleText += ">";

        string convertedText = Html::preformat( articleBody, isToLanguageRTL() );
        free( articleBody );

        QString articleString = QString::fromUtf8( convertedText.c_str() )
                                .replace(phonetic, "<span class=\"dictd_phonetic\">\\1</span>")
                                .replace(refs, "<a href=\"gdlookup://localhost/\\1\">\\1</a>");
        convertedText.erase();

        int pos = 0;
#if QT_VERSION >= QT_VERSION_CHECK( 5, 0, 0 )
        QString articleNewString;
        QRegularExpressionMatchIterator it = links.globalMatch( articleString );
        while( it.hasNext() )
        {
          QRegularExpressionMatch match = it.next();
          articleNewString += articleString.midRef( pos, match.capturedStart() - pos );
          pos = match.capturedEnd();

          QString link = match.captured( 1 );
          link.replace( tags, " " );
          link.replace( "&nbsp;", " " );

          QString newLink = match.captured();
          newLink.replace( 30, match.capturedLength( 1 ),
                           QString::fromUtf8( QUrl::toPercentEncoding( link.simplified() ) ) );
          articleNewString += newLink;
        }
        if( pos )
        {
          articleNewString += articleString.midRef( pos );
          articleString = articleNewString;
          articleNewString.clear();
        }
#else
        for( ; ; )
        {
          pos = articleString.indexOf( links, pos );
          if( pos < 0 )
            break;

          QString link = links.cap( 1 );
          link.replace( tags, " " );
          link.replace( "&nbsp;", " " );
          articleString.replace( pos + 30, links.cap( 1 ).length(),
                                 QString::fromUtf8( QUrl::toPercentEncoding( link.simplified() ) ) );
          pos += 30;
        }
#endif

        articleString += "</div>";

        articleText += articleString.toUtf8().data();
      }

      // Ok. Now, does it go to main articles, or to alternate ones? We list
      // main ones first, and alternates after.

      // We do the case-folded comparison here.

      wstring headwordStripped =
        Folding::applySimpleCaseOnly( Utf8::decode( chain[ x ].word ) );
      if( ignoreDiacritics )
        headwordStripped = Folding::applyDiacriticsOnly( headwordStripped );

      multimap< wstring, string > & mapToUse =
        ( wordCaseFolded == headwordStripped ) ?
          mainArticles : alternateArticles;

      mapToUse.insert( pair< wstring, string >(
        Folding::applySimpleCaseOnly( Utf8::decode( chain[ x ].word ) ),
        articleText ) );

      articlesIncluded.insert( chain[ x ].articleOffset );
    }

    if ( mainArticles.empty() && alternateArticles.empty() )
      return new Dictionary::DataRequestInstant( false );

    string result;

    multimap< wstring, string >::const_iterator i;

    for( i = mainArticles.begin(); i != mainArticles.end(); ++i )
      result += i->second;

    for( i = alternateArticles.begin(); i != alternateArticles.end(); ++i )
      result += i->second;

    sptr< Dictionary::DataRequestInstant > ret =
      new Dictionary::DataRequestInstant( true );

    ret->getData().resize( result.size() );

    memcpy( &(ret->getData().front()), result.data(), result.size() );

    return ret;
  }
  catch( std::exception & e )
  {
    return new Dictionary::DataRequestInstant( QString( e.what() ) );
  }
}

QString const& DictdDictionary::getDescription()
{
    if( !dictionaryDescription.isEmpty() )
        return dictionaryDescription;

    sptr< Dictionary::DataRequest > req = getArticle( GD_NATIVE_TO_WS( L"00databaseinfo" ),
                                                      vector< wstring >(), wstring(), false );

    if( req->dataSize() > 0 )
      dictionaryDescription = Html::unescape( QString::fromUtf8( req->getFullData().data(), req->getFullData().size() ), true );
    else
      dictionaryDescription = "NONE";

    return dictionaryDescription;
}

void DictdDictionary::makeFTSIndex( QAtomicInt & isCancelled, bool firstIteration )
{
  if( !( Dictionary::needToRebuildIndex( getDictionaryFilenames(), ftsIdxName )
         || FtsHelpers::ftsIndexIsOldOrBad( ftsIdxName, this ) ) )
    FTS_index_completed.ref();

  if( haveFTSIndex() )
    return;

  if( ensureInitDone().size() )
    return;

  if( firstIteration && getArticleCount() > FTS::MaxDictionarySizeForFastSearch )
    return;

  gdDebug( "DictD: Building the full-text index for dictionary: %s\n",
           getName().c_str() );

  try
  {
    FtsHelpers::makeFTSIndex( this, isCancelled );
    FTS_index_completed.ref();
  }
  catch( std::exception &ex )
  {
    gdWarning( "DictD: Failed building full-text search index for \"%s\", reason: %s\n", getName().c_str(), ex.what() );
    QFile::remove( FsEncoding::decode( ftsIdxName.c_str() ) );
  }
}

void DictdDictionary::getArticleText( uint32_t articleAddress, QString & headword, QString & text )
{
  try
  {
    char buf[ 16384 ];
    {
      Mutex::Lock _( indexFileMutex );
      indexFile.seek( articleAddress );

      if ( !indexFile.gets( buf, sizeof( buf ), true ) )
        throw exFailedToReadLineFromIndex();
    }

    char * tab1 = strchr( buf, '\t' );

    if ( !tab1 )
      throw exMalformedIndexFileLine();

    headword = QString::fromUtf8( buf, tab1 - buf );

    char * tab2 = strchr( tab1 + 1, '\t' );

    if ( !tab2 )
      throw exMalformedIndexFileLine();

    // After tab1 should be article offset, after tab2 -- article size

    uint32_t articleOffset = decodeBase64( string( tab1 + 1, tab2 - tab1 - 1 ) );

    char * tab3 = strchr( tab2 + 1, '\t');

    uint32_t articleSize;
    if ( tab3 )
    {
      articleSize = decodeBase64( string( tab2 + 1, tab3 - tab2 - 1 ) );
    }
    else
    {
      articleSize = decodeBase64( tab2 + 1 );
    }

    string articleText;

    char * articleBody;
    {
      Mutex::Lock _( dzMutex );
      articleBody = dict_data_read_( dz, articleOffset, articleSize, 0, 0 );
    }

    if ( !articleBody )
    {
      articleText = dict_error_str( dz );
    }
    else
    {
#if QT_VERSION >= QT_VERSION_CHECK( 5, 0, 0 )
      static QRegularExpression phonetic( "\\\\([^\\\\]+)\\\\",
                                          QRegularExpression::CaseInsensitiveOption ); // phonetics: \stuff\ ...
      static QRegularExpression refs( "\\{([^\\{\\}]+)\\}",
                                      QRegularExpression::CaseInsensitiveOption );     // links: {stuff}
#else
      static QRegExp phonetic( "\\\\([^\\\\]+)\\\\", Qt::CaseInsensitive ); // phonetics: \stuff\ ...
      static QRegExp refs( "\\{([^\\{\\}]+)\\}", Qt::CaseInsensitive );     // links: {stuff}
#endif

      string convertedText = Html::preformat( articleBody, isToLanguageRTL() );
      free( articleBody );

      text = QString::fromUtf8( convertedText.data(), convertedText.size() )
            .replace(phonetic, "<span class=\"dictd_phonetic\">\\1</span>")
            .replace(refs, "<a href=\"gdlookup://localhost/\\1\">\\1</a>");

      text = Html::unescape( text );
    }
  }
  catch( std::exception &ex )
  {
    gdWarning( "DictD: Failed retrieving article from \"%s\", reason: %s\n", getName().c_str(), ex.what() );
  }
}

sptr< Dictionary::DataRequest > DictdDictionary::getSearchResults( QString const & searchString,
                                                                   int searchMode, bool matchCase,
                                                                   int distanceBetweenWords,
                                                                   int maxResults,
                                                                   bool ignoreWordsOrder,
                                                                   bool ignoreDiacritics )
{
  return new FtsHelpers::FTSResultsRequest( *this, searchString,searchMode, matchCase, distanceBetweenWords, maxResults, ignoreWordsOrder, ignoreDiacritics );
}

} // anonymous namespace

vector< sptr< Dictionary::Class > > makeDictionaries(
                                      vector< string > const & fileNames,
                                      string const & indicesDir,
                                      Dictionary::Initializing & initializing )
  THROW_SPEC( std::exception )
{
  vector< sptr< Dictionary::Class > > dictionaries;

  for( vector< string >::const_iterator i = fileNames.begin(); i != fileNames.end();
       ++i )
  {
    // Only allow .index suffixes

    if ( i->size() < 6 ||
         strcasecmp( i->c_str() + ( i->size() - 6 ), ".index" ) != 0 )
      continue;

    try
    {
      vector< string > dictFiles( 1, *i );

      // Check if there is an 'abrv' file present
      string baseName( *i, 0, i->size() - 5 );

      dictFiles.push_back( string() );

      if ( !File::tryPossibleName( baseName + "dict", dictFiles[ 1 ] ) &&
           !File::tryPossibleName( baseName + "dict.dz", dictFiles[ 1 ] ) )
      {
        // No corresponding .dict file, skipping
        continue;
      }

      string dictId = Dictionary::makeDictionaryId( dictFiles );

      string indexFile = indicesDir + dictId;

      if ( Dictionary::needToRebuildIndex( dictFiles, indexFile ) ||
           indexIsOldOrBad( indexFile ) )
      {
        // Building the index
        string dictionaryName = nameFromFileName( dictFiles[ 0 ] );

        gdDebug( "DictD: Building the index for dictionary: %s\n", dictionaryName.c_str() );

        initializing.indexingDictionary( dictionaryName );

        File::Class idx( indexFile, "wb" );

        IdxHeader idxHeader;

        memset( &idxHeader, 0, sizeof( idxHeader ) );

        // We write a dummy header first. At the end of the process the header
        // will be rewritten with the right values.

        idx.write( idxHeader );

        IndexedWords indexedWords;

        File::Class indexFile( dictFiles[ 0 ], "rb" );

        // Read words from index until none's left.

        char buf[ 16384 ];

        do
        {
          uint32_t curOffset = indexFile.tell();

          if ( !indexFile.gets( buf, sizeof( buf ), true ) )
            break;

          // Check that there are exactly two or three tabs in the record.
          char * tab1 = strchr( buf, '\t' );
          if ( tab1 )
          {
            char * tab2 = strchr( tab1 + 1, '\t' );
            if ( tab2 )
            {
              char * tab3 = strchr( tab2 + 1, '\t');
              if ( tab3 )
              {
                char * tab4 = strchr( tab3 + 1, '\t');
                if ( tab4 )
                {
                  GD_DPRINTF( "Warning: too many tabs present, skipping: %s\n", buf );
                  continue;
                }

                // Handle the forth entry, if it exists. From dictfmt man:
                // When --index-keep-orig option is used fourth column is created
                // (if necessary) in .index file.
                indexedWords.addWord( Utf8::decode( string( tab3 + 1, strlen ( tab3 + 1 ) ) ), curOffset );
                ++idxHeader.wordCount;
              }
              indexedWords.addWord( Utf8::decode( string( buf, strchr( buf, '\t' ) - buf ) ), curOffset );
              ++idxHeader.wordCount;
              ++idxHeader.articleCount;

              // Check for proper dictionary name
              if ( !strncmp( buf, "00databaseshort", 15 ) || !strncmp( buf, "00-database-short", 17 ) )
              {
                // After tab1 should be article offset, after tab2 -- article size
                uint32_t articleOffset = decodeBase64( string( tab1 + 1, tab2 - tab1 - 1 ) );
                uint32_t articleSize = decodeBase64( tab2 + 1 );

                DZ_ERRORS error;
                dictData * dz = dict_data_open( dictFiles[ 1 ].c_str(), &error, 0 );

                if ( dz )
                {
                  char * articleBody = dict_data_read_( dz, articleOffset, articleSize, 0, 0 );
                  if ( articleBody )
                  {
                    char * eol;
                    if ( !strncmp( articleBody, "00databaseshort", 15 ) || !strncmp( articleBody, "00-database-short", 17 ) )
                      eol = strchr( articleBody, '\n'  ); // skip the first line (headword itself)
                    else
                      eol = articleBody; // No headword itself
                    if ( eol )
                    {
                      while( *eol && Utf8::isspace( *eol ) ) ++eol; // skip spaces

                      // use only the single line for the dictionary title
                      char * endEol = strchr( eol, '\n' );
                      if ( endEol )
                        *endEol = 0;

                      GD_DPRINTF( "DICT NAME: '%s'\n", eol );
                      dictionaryName = eol;
                    }
                  }
                  dict_data_close( dz );
                }
                else
                  throw exDictzipError( string( dz_error_str( error ) )
                                        + "(" + dictFiles[ 1 ] + ")" );
              }
            }
            else
            {
              GD_DPRINTF( "Warning: only a single tab present, skipping: %s\n", buf );
              continue;
            }
          }
          else
          {
            GD_DPRINTF( "Warning: no tabs present, skipping: %s\n", buf );
            continue;
          }


        } while( !indexFile.eof() );


        // Write dictionary name

        idx.write( (uint32_t) dictionaryName.size() );
        idx.write( dictionaryName.data(), dictionaryName.size() );

        // Build index

        IndexInfo idxInfo = BtreeIndexing::buildIndex( indexedWords, idx );

        idxHeader.indexBtreeMaxElements = idxInfo.btreeMaxElements;
        idxHeader.indexRootOffset = idxInfo.rootOffset;

        // That concludes it. Update the header.

        idxHeader.signature = Signature;
        idxHeader.formatVersion = CurrentFormatVersion;

        // read languages
        QPair<quint32,quint32> langs =
            LangCoder::findIdsForFilename( QString::fromStdString( dictFiles[ 0 ] ) );

        // if no languages found, try dictionary's name
        if ( langs.first == 0 || langs.second == 0 )
        {
          langs =
            LangCoder::findIdsForFilename( QString::fromStdString( nameFromFileName( dictFiles[ 0 ] ) ) );
        }

        idxHeader.langFrom = langs.first;
        idxHeader.langTo = langs.second;

        idx.rewind();

        idx.write( &idxHeader, sizeof( idxHeader ) );
      }

      dictionaries.push_back( new DictdDictionary( dictId,
                                                   indexFile,
                                                   dictFiles ) );
    }
    catch( std::exception & e )
    {
      gdWarning( "Dictd dictionary \"%s\" reading failed, error: %s\n",
                 i->c_str(), e.what() );
    }
  }

  return dictionaries;
}

}