forked from goldendict/goldendict
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathslob.cc
1582 lines (1204 loc) · 41.2 KB
/
slob.cc
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
/* This file is (c) 2015 Abs62
* Part of GoldenDict. Licensed under GPLv3 or later, see the LICENSE file */
#ifdef MAKE_ZIM_SUPPORT
#include "slob.hh"
#include "btreeidx.hh"
#include "fsencoding.hh"
#include "folding.hh"
#include "gddebug.hh"
#include "utf8.hh"
#include "decompress.hh"
#include "langcoder.hh"
#include "wstring.hh"
#include "wstring_qt.hh"
#include "ftshelpers.hh"
#include "htmlescape.hh"
#include "filetype.hh"
#include "tiff.hh"
#include "qt4x5.hh"
#ifdef _MSC_VER
#include <stub_msvc.h>
#endif
#include <QString>
#include <QFile>
#include <QFileInfo>
#include <QDir>
#include <QTextCodec>
#include <QMap>
#include <QPair>
#include <QRegExp>
#include <QProcess>
#include <string>
#include <vector>
#include <map>
#include <set>
namespace Slob {
using std::string;
using std::map;
using std::vector;
using std::multimap;
using std::pair;
using std::set;
using gd::wstring;
using BtreeIndexing::WordArticleLink;
using BtreeIndexing::IndexedWords;
using BtreeIndexing::IndexInfo;
DEF_EX_STR( exNotSlobFile, "Not an Slob file", Dictionary::Ex )
DEF_EX_STR( exCantReadFile, "Can't read file", Dictionary::Ex )
DEF_EX_STR( exCantDecodeFile, "Can't decode file", Dictionary::Ex )
DEF_EX_STR( exNoCodecFound, "No text codec found", Dictionary::Ex )
DEF_EX( exUserAbort, "User abort", Dictionary::Ex )
DEF_EX( exNoResource, "No resource found", Dictionary::Ex )
#pragma pack( push, 1 )
enum
{
Signature = 0x58424C53, // SLBX on little-endian, XBLS on big-endian
CurrentFormatVersion = 2 + BtreeIndexing::FormatVersion + Folding::Version
};
struct IdxHeader
{
quint32 signature; // First comes the signature, SLBX
quint32 formatVersion; // File format version (CurrentFormatVersion)
quint32 indexBtreeMaxElements; // Two fields from IndexInfo
quint32 indexRootOffset;
quint32 resourceIndexBtreeMaxElements; // Two fields from IndexInfo
quint32 resourceIndexRootOffset;
quint32 wordCount;
quint32 articleCount;
quint32 langFrom; // Source language
quint32 langTo; // Target language
}
#ifndef _MSC_VER
__attribute__((packed))
#endif
;
#pragma pack( pop )
const char SLOB_MAGIC[ 8 ] = { 0x21, 0x2d, 0x31, 0x53, 0x4c, 0x4f, 0x42, 0x1f };
struct RefEntry
{
QString key;
quint32 itemIndex;
quint16 binIndex;
QString fragment;
};
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 SlobFile
{
enum Compressions
{ UNKNOWN = 0, ZLIB, BZ2, LZMA2 };
QFile file;
QString fileName, dictionaryName;
Compressions compression;
QString encoding;
unsigned char uuid[ 16 ];
QTextCodec *codec;
QMap< QString, QString > tags;
QVector< QString > contentTypes;
quint32 blobCount;
quint64 storeOffset, fileSize, refsOffset;
quint32 refsCount, itemsCount;
quint64 itemsOffset, itemsDataOffset;
quint32 currentItem;
quint32 contentTypesCount;
string currentItemData;
QString readTinyText();
QString readText();
QString readLargeText();
QString readString( unsigned lenght );
public:
SlobFile() :
compression( UNKNOWN )
, codec( 0 )
, blobCount( 0 )
, storeOffset( 0 )
, fileSize( 0 )
, refsOffset( 0 )
, refsCount( 0 )
, itemsCount( 0 )
, itemsOffset( 0 )
, itemsDataOffset( 0 )
, currentItem( 0xFFFFFFFF )
, contentTypesCount( 0 )
{}
~SlobFile();
Compressions getCompression() const
{ return compression; }
QString const & getEncoding() const
{ return encoding; }
QString const & getDictionaryName() const
{ return dictionaryName; }
quint32 blobsCount() const
{ return blobCount; }
quint64 dataOffset() const
{ return storeOffset; }
quint32 getRefsCount() const
{ return refsCount; }
quint32 getContentTypesCount() const
{ return contentTypesCount; }
QTextCodec * getCodec() const
{ return codec; }
QString getContentType( quint8 content_id ) const
{ return content_id < contentTypes.size() ? contentTypes[ content_id ] : QString(); }
QMap< QString, QString > const & getTags() const
{ return tags; }
void open( const QString & name );
void getRefEntry( quint32 ref_nom, RefEntry & entry );
quint8 getItem( RefEntry const & entry, string * data );
};
SlobFile::~SlobFile()
{
file.close();
}
QString SlobFile::readString( unsigned length )
{
QByteArray data = file.read( length );
QString str;
if( codec != 0 && !data.isEmpty() )
str = codec->toUnicode( data );
else
str = QString( data );
char term = 0;
int n = str.indexOf( term );
if( n >= 0 )
str.resize( n );
return str;
}
QString SlobFile::readTinyText()
{
unsigned char len;
if( !file.getChar( ( char * )&len ) )
{
QString error = fileName + ": " + file.errorString();
throw exCantReadFile( string( error.toUtf8().data() ) );
}
return readString( len );
}
QString SlobFile::readText()
{
quint16 len;
if( file.read( ( char * )&len, sizeof( len ) ) != sizeof( len ) )
{
QString error = fileName + ": " + file.errorString();
throw exCantReadFile( string( error.toUtf8().data() ) );
}
return readString( qFromBigEndian( len ) );
}
QString SlobFile::readLargeText()
{
quint32 len;
if( file.read( ( char * )&len, sizeof( len ) ) != sizeof( len ) )
{
QString error = fileName + ": " + file.errorString();
throw exCantReadFile( string( error.toUtf8().data() ) );
}
return readString( qFromBigEndian( len ) );
}
void SlobFile::open( const QString & name )
{
QString error( name + ": " );
if( file.isOpen() )
file.close();
fileName = name;
file.setFileName( name );
{
QFileInfo fi( name );
dictionaryName = fi.fileName();
}
for( ; ; )
{
if( !file.open( QFile::ReadOnly ) )
break;
char magic[ 8 ];
if( file.read( magic, sizeof( magic ) ) != sizeof( magic ) )
break;
if( memcmp( magic, SLOB_MAGIC, sizeof( magic ) ) != 0 )
throw exNotSlobFile( string( name.toUtf8().data() ) );
if( file.read( ( char * )uuid, sizeof( uuid ) ) != sizeof( uuid ) )
break;
// Read encoding
encoding = readTinyText();
codec = QTextCodec::codecForName( encoding.toLatin1() );
if( codec == 0 )
{
error = QString( "for encoding \"") + encoding + "\"";
throw exNoCodecFound( string( error.toUtf8().data() ) );
}
// Read compression type
QString compr = readTinyText();
if( compr.compare( "zlib", Qt::CaseInsensitive ) == 0 )
compression = ZLIB;
else
if( compr.compare( "bz2", Qt::CaseInsensitive ) == 0 )
compression = BZ2;
else
if( compr.compare( "lzma2", Qt::CaseInsensitive ) == 0 )
compression = LZMA2;
// Read tags
unsigned char count;
if( !file.getChar( ( char * )&count ) )
break;
for( unsigned i = 0; i < count; i++ )
{
QString key = readTinyText();
QString value = readTinyText();
tags[ key ] = value;
if( key.compare( "label", Qt::CaseInsensitive ) == 0
|| key.compare( "name", Qt::CaseInsensitive ) == 0)
dictionaryName = value;
}
// Read content types
if( !file.getChar( ( char * )&count ) )
break;
for( unsigned i = 0; i < count; i++ )
{
QString type = readText();
contentTypes.append( type );
}
contentTypesCount = count;
// Read data parameters
quint32 cnt;
if( file.read( ( char * )&cnt, sizeof( cnt ) ) != sizeof( cnt ) )
break;
blobCount = qFromBigEndian( cnt );
quint64 tmp;
if( file.read( ( char * )&tmp, sizeof( tmp ) ) != sizeof( tmp ) )
break;
storeOffset = qFromBigEndian( tmp );
if( file.read( ( char * )&tmp, sizeof( tmp ) ) != sizeof( tmp ) )
break;
fileSize = qFromBigEndian( tmp );
if( file.read( ( char * )&cnt, sizeof( cnt ) ) != sizeof( cnt ) )
break;
refsCount = qFromBigEndian( cnt );
refsOffset = file.pos();
if( !file.seek( storeOffset ) )
break;
if( file.read( ( char * )&cnt, sizeof( cnt ) ) != sizeof( cnt ) )
break;
itemsCount = qFromBigEndian( cnt );
itemsOffset = storeOffset + sizeof( itemsCount );
itemsDataOffset = itemsOffset + itemsCount * sizeof( quint64 );
return;
}
error += file.errorString();
throw exCantReadFile( string( error.toUtf8().data() ) );
}
void SlobFile::getRefEntry( quint32 ref_nom, RefEntry & entry )
{
quint64 pos = refsOffset + ref_nom * sizeof( quint64 );
quint64 offset, tmp;
for( ; ; )
{
if( !file.seek( pos ) || file.read( ( char * )&tmp, sizeof( tmp ) ) != sizeof( tmp ) )
break;
offset = qFromBigEndian( tmp ) + refsOffset + refsCount * sizeof( quint64 );
if( !file.seek( offset ) )
break;
entry.key = readText();
quint32 index;
if( file.read( ( char * )&index, sizeof( index ) ) != sizeof( index ) )
break;
entry.itemIndex = qFromBigEndian( index );
quint16 binIndex;
if( file.read( ( char * )&binIndex, sizeof( binIndex ) ) != sizeof( binIndex ) )
break;
entry.binIndex = qFromBigEndian( binIndex );
entry.fragment = readTinyText();
return;
}
QString error = fileName + ": " + file.errorString();
throw exCantReadFile( string( error.toUtf8().data() ) );
}
quint8 SlobFile::getItem( RefEntry const & entry, string * data )
{
quint64 pos = itemsOffset + entry.itemIndex * sizeof( quint64 );
quint64 offset, tmp;
for( ; ; )
{
// Read item data types
if( !file.seek( pos ) || file.read( ( char * )&tmp, sizeof( tmp ) ) != sizeof( tmp ) )
break;
offset = qFromBigEndian( tmp ) + itemsDataOffset;
if( !file.seek( offset ) )
break;
quint32 bins, bins_be;
if( file.read( ( char * )&bins_be, sizeof( bins_be ) ) != sizeof( bins_be ) )
break;
bins = qFromBigEndian( bins_be );
if( entry.binIndex >= bins )
return 0xFF;
QVector< quint8 > ids;
ids.resize( bins );
if( file.read( ( char * )ids.data(), bins ) != bins )
break;
quint8 id = ids[ entry.binIndex ];
if( id >= (unsigned)contentTypes.size() )
return 0xFF;
if( data != 0 )
{
// Read item data
if( currentItem != entry.itemIndex )
{
currentItemData.clear();
quint32 length, length_be;
if( file.read( ( char * )&length_be, sizeof( length_be ) ) != sizeof( length_be ) )
break;
length = qFromBigEndian( length_be );
QByteArray compressedData = file.read( length );
if( compression == ZLIB )
currentItemData = decompressZlib( compressedData.data(), length );
else
if( compression == BZ2 )
currentItemData = decompressBzip2( compressedData.data(), length );
else
currentItemData = decompressLzma2( compressedData.data(), length, true );
if( currentItemData.empty() )
{
currentItem = 0xFFFFFFFF;
return 0xFF;
}
currentItem = entry.itemIndex;
}
// Find bin data inside item
const char * ptr = currentItemData.c_str();
quint32 pos = entry.binIndex * sizeof( quint32 );
if( pos >= currentItemData.length() - sizeof( quint32 ) )
return 0xFF;
quint32 offset, offset_be;
memcpy( &offset_be, ptr + pos, sizeof( offset_be ) );
offset = qFromBigEndian( offset_be );
pos = bins * sizeof( quint32 ) + offset;
if( pos >= currentItemData.length() - sizeof( quint32 ) )
return 0xFF;
quint32 length, len_be;
memcpy( &len_be, ptr + pos, sizeof( len_be ) );
length = qFromBigEndian( len_be );
*data = currentItemData.substr( pos + sizeof( len_be ), length );
}
return ids[ entry.binIndex ];
}
QString error = fileName + ": " + file.errorString();
throw exCantReadFile( string( error.toUtf8().data() ) );
}
// SlobDictionary
class SlobDictionary: public BtreeIndexing::BtreeDictionary
{
Mutex idxMutex;
Mutex slobMutex, idxResourceMutex;
File::Class idx;
BtreeIndex resourceIndex;
IdxHeader idxHeader;
string dictionaryName;
SlobFile sf;
QString texCgiPath, texCachePath;
public:
SlobDictionary( string const & id, string const & indexFile,
vector< string > const & dictionaryFiles );
~SlobDictionary();
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; }
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 & )
throw( std::exception );
virtual sptr< Dictionary::DataRequest > getResource( string const & name )
throw( std::exception );
virtual QString const& getDescription();
/// Loads the resource.
void loadResource( std::string &resourceName, string & data );
virtual sptr< Dictionary::DataRequest > getSearchResults( QString const & searchString,
int searchMode, bool matchCase,
int distanceBetweenWords,
int maxResults );
virtual 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( "SLOB", Qt::CaseInsensitive )
&& ( fts.maxDictionarySize == 0 || getArticleCount() <= fts.maxDictionarySize );
}
virtual uint32_t getFtsIndexVersion()
{ return 2; }
protected:
virtual void loadIcon() throw();
private:
/// Loads the article.
void loadArticle( quint32 address,
string & articleText );
quint32 readArticle( quint32 address,
string & articleText,
RefEntry & entry );
string convert( string const & in_data, RefEntry const & entry );
void removeDirectory( QString const & directory );
friend class SlobArticleRequest;
friend class SlobResourceRequest;
};
SlobDictionary::SlobDictionary( string const & id,
string const & indexFile,
vector< string > const & dictionaryFiles ):
BtreeDictionary( id, dictionaryFiles ),
idx( indexFile, "rb" ),
idxHeader( idx.read< IdxHeader >() )
{
// Open data file
try
{
sf.open( FsEncoding::decode( dictionaryFiles[ 0 ].c_str() ) );
}
catch( std::exception & e )
{
gdWarning( "Slob dictionary initializing failed: %s, error: %s\n",
dictionaryFiles[ 0 ].c_str(), e.what() );
}
// Initialize the indexes
openIndex( IndexInfo( idxHeader.indexBtreeMaxElements,
idxHeader.indexRootOffset ),
idx, idxMutex );
resourceIndex.openIndex( IndexInfo( idxHeader.resourceIndexBtreeMaxElements,
idxHeader.resourceIndexRootOffset ),
idx, idxResourceMutex );
// Read dictionary name
dictionaryName = string( sf.getDictionaryName().toUtf8().constData() );
if( dictionaryName.empty() )
{
QString name = QDir::fromNativeSeparators( FsEncoding::decode( dictionaryFiles[ 0 ].c_str() ) );
int n = name.lastIndexOf( '/' );
dictionaryName = string( name.mid( n + 1 ).toUtf8().constData() );
}
// Full-text search parameters
can_FTS = true;
ftsIdxName = indexFile + "_FTS";
if( !Dictionary::needToRebuildIndex( dictionaryFiles, ftsIdxName )
&& !FtsHelpers::ftsIndexIsOldOrBad( ftsIdxName, this ) )
FTS_index_completed.ref();
texCgiPath = Config::getProgramDataDir() + "/mimetex.cgi";
if( QFileInfo( texCgiPath ).exists() )
{
QString dirName = QString::fromStdString( getId() );
QDir( QDir::tempPath() ).mkdir( dirName );
texCachePath = QDir::tempPath() + "/" + dirName;
}
else
texCgiPath.clear();
}
SlobDictionary::~SlobDictionary()
{
if( !texCachePath.isEmpty() )
removeDirectory( texCachePath );
}
void SlobDictionary::removeDirectory( QString const & directory )
{
QDir dir( directory );
Q_FOREACH( QFileInfo info, dir.entryInfoList( QDir::NoDotAndDotDot
| QDir::AllDirs
| QDir::Files,
QDir::DirsFirst))
{
if( info.isDir() )
removeDirectory( info.absoluteFilePath() );
else
QFile::remove( info.absoluteFilePath() );
}
dir.rmdir( directory );
}
void SlobDictionary::loadIcon() throw()
{
if ( dictionaryIconLoaded )
return;
QString fileName =
QDir::fromNativeSeparators( FsEncoding::decode( getDictionaryFilenames()[ 0 ].c_str() ) );
// Remove the extension
fileName.chop( 4 );
if( !loadIconFromFile( fileName ) )
{
// Load failed -- use default icons
dictionaryNativeIcon = dictionaryIcon = QIcon(":/icons/icon32_slob.png");
}
dictionaryIconLoaded = true;
}
QString const& SlobDictionary::getDescription()
{
if( !dictionaryDescription.isEmpty() )
return dictionaryDescription;
QMap< QString, QString > const & tags = sf.getTags();
QMap< QString, QString >::const_iterator it;
for( it = tags.begin(); it != tags.end(); ++it )
{
if( it != tags.begin() )
dictionaryDescription += "\n\n";
dictionaryDescription += it.key() + ": " +it.value();
}
return dictionaryDescription;
}
void SlobDictionary::loadArticle( quint32 address,
string & articleText )
{
articleText.clear();
RefEntry entry;
readArticle( address, articleText, entry );
if( !articleText.empty() )
{
articleText = convert( articleText, entry );
}
else
articleText = string( QObject::tr( "Article decoding error" ).toUtf8().constData() );
// See Issue #271: A mechanism to clean-up invalid HTML cards.
string cleaner = "</font>""</font>""</font>""</font>""</font>""</font>"
"</font>""</font>""</font>""</font>""</font>""</font>"
"</b></b></b></b></b></b></b></b>"
"</i></i></i></i></i></i></i></i>"
"</a></a></a></a></a></a></a></a>";
string prefix( "<div class=\"slobdict\"" );
if( isToLanguageRTL() )
prefix += " dir=\"rtl\"";
prefix += ">";
articleText = prefix + articleText + cleaner + "</div>";
}
string SlobDictionary::convert( const string & in, RefEntry const & entry )
{
QString text = QString::fromUtf8( in.c_str() );
// pattern of img and script
text.replace( QRegExp( "<\\s*(img|script)\\s*([^>]*)src=\"(?!(?:data|https?|ftp):)(|/)([^\"]*)\"" ),
QString( "<\\1 \\2src=\"bres://%1/\\4\"").arg( getId().c_str() ) );
// pattern <link... href="..." ...>
text.replace( QRegExp( "<\\s*link\\s*([^>]*)href=\"(?!(?:data|https?|ftp):)" ),
QString( "<link \\1href=\"bres://%1/").arg( getId().c_str() ) );
// pattern <a href="..." ...>, excluding any known protocols such as http://, mailto:, #(comment)
// these links will be translated into local definitions
QRegExp rxLink( "<\\s*a\\s+([^>]*)href=\"(?!(\\w+://|#|mailto:|tel:))(/|)([^\"]*)\"\\s*(title=\"[^\"]*\")?[^>]*>",
Qt::CaseSensitive,
QRegExp::RegExp2 );
QString anchor;
int pos = 0;
while( (pos = rxLink.indexIn( text, pos )) >= 0 )
{
QStringList list = rxLink.capturedTexts();
QString tag = list[3];
if ( !list[4].isEmpty() )
tag = list[4].split("\"")[1];
// Find anchor
int n = list[ 3 ].indexOf( '#' );
if( n > 0 )
anchor = QString( "?gdanchor=" ) + list[ 3 ].mid( n + 1 );
else
anchor.clear();
tag.remove( QRegExp(".*/") ).
remove( QRegExp( "\\.(s|)htm(l|)$", Qt::CaseInsensitive ) ).
replace( "_", "%20" ).
prepend( "<a href=\"gdlookup://localhost/" ).
append( anchor + "\" " + list[4] + ">" );
text.replace( pos, list[0].length(), tag );
pos += tag.length() + 1;
}
// Handle TeX formulas via mimetex.cgi
if( !texCgiPath.isEmpty() )
{
QRegExp texImage( "<\\s*img\\s*class=\"([^\"]+)\"\\s*([^>]*)alt=\"([^\"]+)\"[^>]*>",
Qt::CaseSensitive,
QRegExp::RegExp2 );
pos = 0;
unsigned texCount = 0;
QString imgName;
QRegExp regFrac = QRegExp( "\\\\[dt]frac" );
while( (pos = texImage.indexIn( text, pos )) >= 0 )
{
QStringList list = texImage.capturedTexts();
if( list[ 1 ].compare( "tex" ) == 0
|| list[ 1 ].compare( "mwe-math-fallback-image-inline" ) == 0
|| list[ 1 ].endsWith( " tex" ) )
{
QString name;
name.sprintf( "%04X%04X%04X.gif", entry.itemIndex, entry.binIndex, texCount );
imgName = texCachePath + "/" + name;
if( !QFileInfo( imgName ).exists() )
{
// Replace some TeX commands which don't support by mimetex.cgi
QString tex = list[ 3 ];
tex.replace( regFrac, "\\frac" );
tex.replace( "\\leqslant", "\\leq" );
tex.replace( "\\geqslant", "\\geq" );
tex.replace( "\\infin", "\\infty" );
tex.replace( "\\iff", "\\Longleftrightarrow" );
tex.replace( "\\tbinom", "\\binom" );
tex.replace( "\\implies", "\\Longrightarrow" );
tex.replace( "{aligned}", "{align*}" );
QString command = texCgiPath + " -e " + imgName
+ " \"" + tex + "\"";
QProcess::execute( command );
}
QString tag = QString( "<img class=\"imgtex\" src=\"file://" )
#ifdef Q_OS_WIN32
+ "/"
#endif
+ imgName + "\" alt=\"" + list[ 3 ] + "\">";
text.replace( pos, list[0].length(), tag );
pos += tag.length() + 1;
texCount += 1;
}
else
pos += list[ 0 ].length();
}
}
// Fix outstanding elements
text += "<br style=\"clear:both;\" />";
return text.toUtf8().data();
}
void SlobDictionary::loadResource( std::string & resourceName, string & data )
{
vector< WordArticleLink > link;
string resData;
RefEntry entry;
link = resourceIndex.findArticles( Utf8::decode( resourceName ) );
if( link.empty() )
return;
readArticle( link[ 0 ].articleOffset, data, entry );
}
quint32 SlobDictionary::readArticle( quint32 articleNumber, std::string & result,
RefEntry & entry )
{
string data;
quint8 contentId;
{
Mutex::Lock _( slobMutex );
if( entry.key.isEmpty() )
sf.getRefEntry( articleNumber, entry );
contentId = sf.getItem( entry, &data );
}
if( contentId == 0xFF )
return 0xFFFFFFFF;
QString contentType = sf.getContentType( contentId );
if( contentType.contains( "text/html", Qt::CaseInsensitive )
|| contentType.contains( "text/plain", Qt::CaseInsensitive )
|| contentType.contains( "/css", Qt::CaseInsensitive )
|| contentType.contains( "/javascript", Qt::CaseInsensitive )
|| contentType.contains( "/json", Qt::CaseInsensitive ))
{
QTextCodec *codec = sf.getCodec();
QString content = codec->toUnicode( data.c_str(), data.size() );
result = string( content.toUtf8().data() );
}
else
result = data;
return contentId;
}
void SlobDictionary::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( "Slob: Building the full-text index for dictionary: %s\n",
getName().c_str() );
try
{
Mutex::Lock _( getFtsMutex() );
File::Class ftsIdx( ftsIndexName(), "wb" );
FtsHelpers::FtsIdxHeader ftsIdxHeader;
memset( &ftsIdxHeader, 0, sizeof( ftsIdxHeader ) );
// We write a dummy header first. At the end of the process the header
// will be rewritten with the right values.
ftsIdx.write( ftsIdxHeader );
ChunkedStorage::Writer chunks( ftsIdx );
BtreeIndexing::IndexedWords indexedWords;
QSet< uint32_t > setOfOffsets;
findArticleLinks( 0, &setOfOffsets, 0, &isCancelled );
if( Qt4x5::AtomicInt::loadAcquire( isCancelled ) )
throw exUserAbort();
QVector< uint32_t > offsets;
offsets.resize( setOfOffsets.size() );
uint32_t * ptr = &offsets.front();
for( QSet< uint32_t >::ConstIterator it = setOfOffsets.constBegin();
it != setOfOffsets.constEnd(); ++it )
{
*ptr = *it;
ptr++;
}
// Free memory
setOfOffsets.clear();
if( Qt4x5::AtomicInt::loadAcquire( isCancelled ) )
throw exUserAbort();
qSort( offsets );
if( Qt4x5::AtomicInt::loadAcquire( isCancelled ) )
throw exUserAbort();
QMap< QString, QVector< uint32_t > > ftsWords;
set< quint64 > indexedArticles;
RefEntry entry;
string articleText;
quint32 htmlType = 0xFFFFFFFF;
for( unsigned i = 0; i < sf.getContentTypesCount(); i++ )
{
if( sf.getContentType( i ).startsWith( "text/html", Qt::CaseInsensitive ) )
{
htmlType = i;
break;
}
}
// index articles for full-text search
for( int i = 0; i < offsets.size(); i++ )
{
if( Qt4x5::AtomicInt::loadAcquire( isCancelled ) )
throw exUserAbort();
QString articleStr;
quint32 articleNom = offsets.at( i );
sf.getRefEntry( articleNom, entry );
quint64 articleID = ( ( (quint64)entry.itemIndex ) << 32 ) | entry.binIndex;
set< quint64 >::iterator it = indexedArticles.find( articleID );
if( it != indexedArticles.end() )
continue;