forked from goldendict/goldendict
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathzipsounds.cc
517 lines (390 loc) · 14.5 KB
/
zipsounds.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
/* This file is (c) 2008-2012 Konstantin Isakov <[email protected]>
* Part of GoldenDict. Licensed under GPLv3 or later, see the LICENSE file */
#include "zipsounds.hh"
#include "file.hh"
#include "folding.hh"
#include "utf8.hh"
#include "btreeidx.hh"
#include "fsencoding.hh"
#include "audiolink.hh"
#include "indexedzip.hh"
#include "filetype.hh"
#include "gddebug.hh"
#include "chunkedstorage.hh"
#include "htmlescape.hh"
#include <set>
#include <string>
#include <QFile>
#include <QDir>
#include <QDebug>
#ifdef _MSC_VER
#include <stub_msvc.h>
#endif
#include "qt4x5.hh"
namespace ZipSounds {
using std::string;
using gd::wstring;
using std::map;
using std::multimap;
using std::set;
using BtreeIndexing::WordArticleLink;
using BtreeIndexing::IndexedWords;
using BtreeIndexing::IndexInfo;
namespace {
DEF_EX( exInvalidData, "Invalid data encountered", Dictionary::Ex )
enum
{
Signature = 0x5350495a, // ZIPS on little-endian, SPIZ on big-endian
CurrentFormatVersion = 5 + BtreeIndexing::FormatVersion
};
struct IdxHeader
{
uint32_t signature; // First comes the signature, ZIPS
uint32_t formatVersion; // File format version, currently 1.
uint32_t soundsCount; // Total number of sounds, for informative purposes only
uint32_t indexBtreeMaxElements; // Two fields from IndexInfo
uint32_t indexRootOffset;
uint32_t chunksOffset; // The offset to chunks' storage
}
#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;
}
wstring stripExtension( string const & str )
{
wstring name;
try
{
name = Utf8::decode( str );
}
catch( Utf8::exCantDecode )
{
return name;
}
if( Filetype::isNameOfSound( str ) )
{
wstring::size_type pos = name.rfind( L'.' );
if ( pos != wstring::npos )
name.erase( pos );
// Strip spaces at the end of name
string::size_type n = name.length();
while( n && name.at( n - 1 ) == L' ' )
n--;
if( n != name.length() )
name.erase( n );
}
return name;
}
class ZipSoundsDictionary: public BtreeIndexing::BtreeDictionary
{
Mutex idxMutex;
File::Class idx;
IdxHeader idxHeader;
sptr< ChunkedStorage::Reader > chunks;
IndexedZip zipsFile;
public:
ZipSoundsDictionary( string const & id, string const & indexFile,
vector< string > const & dictionaryFiles );
virtual string getName() throw();
virtual map< Dictionary::Property, string > getProperties() throw()
{ return map< Dictionary::Property, string >(); }
virtual unsigned long getArticleCount() throw()
{ return idxHeader.soundsCount; }
virtual unsigned long getWordCount() throw()
{ return getArticleCount(); }
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 );
protected:
virtual void loadIcon() throw();
};
ZipSoundsDictionary::ZipSoundsDictionary( string const & id,
string const & indexFile,
vector< string > const & dictionaryFiles ):
BtreeDictionary( id, dictionaryFiles ),
idx( indexFile, "rb" ),
idxHeader( idx.read< IdxHeader >() )
{
chunks = new ChunkedStorage::Reader( idx, idxHeader.chunksOffset );
// Initialize the index
openIndex( IndexInfo( idxHeader.indexBtreeMaxElements,
idxHeader.indexRootOffset ),
idx, idxMutex );
QString zipName = QDir::fromNativeSeparators(
FsEncoding::decode( getDictionaryFilenames()[ 0 ].c_str() ) );
zipsFile.openZipFile( zipName );
zipsFile.openIndex( IndexInfo( idxHeader.indexBtreeMaxElements,
idxHeader.indexRootOffset ),
idx, idxMutex );
}
string ZipSoundsDictionary::getName() throw()
{
string result = FsEncoding::basename( getDictionaryFilenames()[ 0 ] );
// Strip the extension
result.erase( result.rfind( '.' ) );
return result;
}
sptr< Dictionary::DataRequest > ZipSoundsDictionary::getArticle( wstring const & word,
vector< wstring > const & alts,
wstring const & )
throw( std::exception )
{
vector< WordArticleLink > chain = findArticles( word );
for( unsigned x = 0; x < alts.size(); ++x )
{
/// Make an additional query for each alt
vector< WordArticleLink > altChain = findArticles( alts[ x ] );
chain.insert( chain.end(), altChain.begin(), altChain.end() );
}
multimap< wstring, uint32_t > mainArticles, alternateArticles;
set< uint32_t > articlesIncluded; // Some synonims make it that the articles
// appear several times. We combat this
// by only allowing them to appear once.
wstring wordCaseFolded = Folding::applySimpleCaseOnly( word );
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.
// 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 ) );
multimap< wstring, uint32_t > & mapToUse =
( wordCaseFolded == headwordStripped ) ?
mainArticles : alternateArticles;
mapToUse.insert( std::pair< wstring, uint32_t >(
Folding::applySimpleCaseOnly( Utf8::decode( chain[ x ].word ) ), chain[ x ].articleOffset ) );
articlesIncluded.insert( chain[ x ].articleOffset );
}
if ( mainArticles.empty() && alternateArticles.empty() )
return new Dictionary::DataRequestInstant( false ); // No such word
string result;
multimap< wstring, uint32_t >::const_iterator i;
result += "<table class=\"lsa_play\">";
vector< char > chunk;
char * nameBlock;
for( i = mainArticles.begin(); i != mainArticles.end(); ++i )
{
try
{
Mutex::Lock _( idxMutex );
nameBlock = chunks->getBlock( i->second, chunk );
if ( nameBlock >= &chunk.front() + chunk.size() )
{
// chunks reader thinks it's okay since zero-sized records can exist,
// but we don't allow that.
throw ChunkedStorage::exAddressOutOfRange();
}
}
catch( ChunkedStorage::exAddressOutOfRange & )
{
// Bad address
continue;
}
uint16_t sz;
memcpy( &sz, nameBlock, sizeof( uint16_t ) );
nameBlock += sizeof( uint16_t );
string name( nameBlock, sz );
nameBlock += sz;
string displayedName = mainArticles.size() + alternateArticles.size() > 1 ?
name : Utf8::encode( stripExtension( name ) );
result += "<tr>";
QUrl url;
url.setScheme( "gdau" );
url.setHost( QString::fromUtf8( getId().c_str() ) );
url.setPath( Qt4x5::Url::ensureLeadingSlash( QString::fromUtf8( name.c_str() ) ) );
string ref = string( "\"" ) + url.toEncoded().data() + "\"";
result += addAudioLink( ref, getId() );
result += "<td><a href=" + ref + "><img src=\"qrcx://localhost/icons/playsound.png\" border=\"0\" alt=\"Play\"/></a></td>";
result += "<td><a href=" + ref + ">" + Html::escape( displayedName ) + "</a></td>";
result += "</tr>";
}
for( i = alternateArticles.begin(); i != alternateArticles.end(); ++i )
{
try
{
Mutex::Lock _( idxMutex );
nameBlock = chunks->getBlock( i->second, chunk );
if ( nameBlock >= &chunk.front() + chunk.size() )
{
// chunks reader thinks it's okay since zero-sized records can exist,
// but we don't allow that.
throw ChunkedStorage::exAddressOutOfRange();
}
}
catch( ChunkedStorage::exAddressOutOfRange & )
{
// Bad address
continue;
}
uint16_t sz;
memcpy( &sz, nameBlock, sizeof( uint16_t ) );
nameBlock += sizeof( uint16_t );
string name( nameBlock, sz );
nameBlock += sz;
string displayedName = mainArticles.size() + alternateArticles.size() > 1 ?
name : Utf8::encode( stripExtension( name ) );
result += "<tr>";
QUrl url;
url.setScheme( "gdau" );
url.setHost( QString::fromUtf8( getId().c_str() ) );
url.setPath( Qt4x5::Url::ensureLeadingSlash( QString::fromUtf8( name.c_str() ) ) );
string ref = string( "\"" ) + url.toEncoded().data() + "\"";
result += addAudioLink( ref, getId() );
result += "<td><a href=" + ref + "><img src=\"qrcx://localhost/icons/playsound.png\" border=\"0\" alt=\"Play\"/></a></td>";
result += "<td><a href=" + ref + ">" + Html::escape( displayedName ) + "</a></td>";
result += "</tr>";
}
result += "</table>";
Dictionary::DataRequestInstant * ret =
new Dictionary::DataRequestInstant( true );
ret->getData().resize( result.size() );
memcpy( &(ret->getData().front()), result.data(), result.size() );
return ret;
}
sptr< Dictionary::DataRequest > ZipSoundsDictionary::getResource( string const & name )
throw( std::exception )
{
// Remove extension for sound files (like in sound dirs)
wstring strippedName = stripExtension( name );
vector< WordArticleLink > chain = findArticles( strippedName );
if ( chain.empty() )
return new Dictionary::DataRequestInstant( false ); // No such resource
// Find sound
uint32_t dataOffset = 0;
for( int x = chain.size() - 1; x >= 0 ; x-- )
{
vector< char > chunk;
char * nameBlock = chunks->getBlock( chain[ x ].articleOffset, chunk );
uint16_t sz;
memcpy( &sz, nameBlock, sizeof( uint16_t ) );
nameBlock += sizeof( uint16_t );
string fileName( nameBlock, sz );
nameBlock += sz;
memcpy( &dataOffset, nameBlock, sizeof( uint32_t ) );
if( name.compare( fileName ) == 0 )
break;
}
sptr< Dictionary::DataRequestInstant > dr = new
Dictionary::DataRequestInstant( true );
if ( zipsFile.loadFile( dataOffset, dr->getData() ) )
return dr;
return new Dictionary::DataRequestInstant( false );
}
void ZipSoundsDictionary::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/playsound.png");
}
dictionaryIconLoaded = true;
}
}
vector< sptr< Dictionary::Class > > makeDictionaries(
vector< string > const & fileNames,
string const & indicesDir,
Dictionary::Initializing & initializing )
throw( std::exception )
{
(void) initializing;
vector< sptr< Dictionary::Class > > dictionaries;
for( vector< string >::const_iterator i = fileNames.begin(); i != fileNames.end();
++i )
{
/// Only allow .zips extension
if ( i->size() < 5 || strcasecmp( i->c_str() + ( i->size() - 5 ), ".zips" ) != 0 )
continue;
try
{
vector< string > dictFiles( 1, *i );
string dictId = Dictionary::makeDictionaryId( dictFiles );
string indexFile = indicesDir + dictId;
if ( Dictionary::needToRebuildIndex( dictFiles, indexFile ) ||
indexIsOldOrBad( indexFile ) )
{
gdDebug( "Zips: Building the index for dictionary: %s\n", i->c_str() );
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 names, zipFileNames;
ChunkedStorage::Writer chunks( idx );
quint32 namesCount;
IndexedZip zipFile;
if( zipFile.openZipFile( QDir::fromNativeSeparators(
FsEncoding::decode( i->c_str() ) ) ) )
zipFile.indexFile( zipFileNames, &namesCount );
if( !zipFileNames.empty() )
{
for( IndexedWords::iterator i = zipFileNames.begin(); i != zipFileNames.end(); ++i )
{
vector< WordArticleLink > links = i->second;
for( unsigned x = 0; x < links.size(); x++ )
{
// Save original name
uint32_t offset = chunks.startNewBlock();
uint16_t sz = links[ x ].word.size();
chunks.addToBlock( &sz, sizeof(uint16_t) );
chunks.addToBlock( links[ x ].word.c_str(), sz );
chunks.addToBlock( &links[ x ].articleOffset, sizeof( uint32_t ) );
// Remove extension for sound files (like in sound dirs)
wstring word = stripExtension( links[ x ].word );
if( !word.empty() )
names.addSingleWord( word, offset );
}
}
// Finish with the chunks
idxHeader.chunksOffset = chunks.finish();
// Build the resulting zip file index
IndexInfo idxInfo = BtreeIndexing::buildIndex( names, idx );
// That concludes it. Update the header.
idxHeader.indexBtreeMaxElements = idxInfo.btreeMaxElements;
idxHeader.indexRootOffset = idxInfo.rootOffset;
idxHeader.signature = Signature;
idxHeader.formatVersion = CurrentFormatVersion;
idxHeader.soundsCount = namesCount;
idx.rewind();
idx.write( &idxHeader, sizeof( idxHeader ) );
}
else
{
idx.close();
QFile::remove( QDir::fromNativeSeparators(
FsEncoding::decode( indexFile.c_str() ) ) );
throw exInvalidData();
}
}
dictionaries.push_back( new ZipSoundsDictionary( dictId,
indexFile,
dictFiles ) );
}
catch( std::exception & e )
{
gdWarning( "Zipped sounds pack reading failed: %s, error: %s\n",
i->c_str(), e.what() );
}
}
return dictionaries;
}
}