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
|
/* This file is (c) 2008-2012 Konstantin Isakov <ikm@goldendict.org>
* Part of GoldenDict. Licensed under GPLv3 or later, see the LICENSE file */
#include <vector>
#include <algorithm>
#include <cstdio>
#include "dictionary.hh"
#include <QCryptographicHash>
// For needToRebuildIndex(), read below
#include <QFileInfo>
#include <QDateTime>
#include "config.hh"
#include <QDir>
#include <QFileInfo>
#include <QCryptographicHash>
#include <QDateTime>
#include "fsencoding.hh"
#include <QImage>
#include <QPainter>
#include <QRegularExpression>
#include "utils.hh"
#include "zipfile.hh"
namespace Dictionary {
bool Request::isFinished()
{
return Utils::AtomicInt::loadAcquire( isFinishedFlag );
}
void Request::update()
{
if ( !Utils::AtomicInt::loadAcquire( isFinishedFlag ) )
emit updated();
}
void Request::finish()
{
if ( !Utils::AtomicInt::loadAcquire( isFinishedFlag ) )
{
isFinishedFlag.ref();
emit finished();
}
}
void Request::setErrorString( QString const & str )
{
Mutex::Lock _( errorStringMutex );
errorString = str;
}
QString Request::getErrorString()
{
Mutex::Lock _( errorStringMutex );
return errorString;
}
///////// WordSearchRequest
size_t WordSearchRequest::matchesCount()
{
Mutex::Lock _( dataMutex );
return matches.size();
}
WordMatch WordSearchRequest::operator [] ( size_t index )
{
Mutex::Lock _( dataMutex );
if ( index >= matches.size() )
throw exIndexOutOfRange();
return matches[ index ];
}
vector< WordMatch > & WordSearchRequest::getAllMatches()
{
if ( !isFinished() )
throw exRequestUnfinished();
return matches;
}
void WordSearchRequest::addMatch( WordMatch const & match )
{
unsigned n;
for( n = 0; n < matches.size(); n++ )
if( matches[ n ].word.compare( match.word ) == 0 )
break;
if( n >= matches.size() )
matches.push_back( match );
}
////////////// DataRequest
long DataRequest::dataSize()
{
Mutex::Lock _( dataMutex );
return hasAnyData ? (long)data.size() : -1;
}
void DataRequest::getDataSlice( size_t offset, size_t size, void * buffer )
{
if ( size == 0 )
return;
Mutex::Lock _( dataMutex );
if ( offset + size > data.size() || !hasAnyData )
throw exSliceOutOfRange();
memcpy( buffer, &data[ offset ], size );
}
vector< char > & DataRequest::getFullData()
{
if ( !isFinished() )
throw exRequestUnfinished();
return data;
}
Class::Class( string const & id_, vector< string > const & dictionaryFiles_ ):
id( id_ ), dictionaryFiles( dictionaryFiles_ ), indexedFtsDoc(0)
, dictionaryIconLoaded( false ), can_FTS( false),FTS_index_completed( false )
{
}
void Class::deferredInit()
{
}
sptr< WordSearchRequest > Class::stemmedMatch( wstring const & /*str*/,
unsigned /*minLength*/,
unsigned /*maxSuffixVariation*/,
unsigned long /*maxResults*/ )
{
return std::make_shared<WordSearchRequestInstant>();
}
sptr< WordSearchRequest > Class::findHeadwordsForSynonym( wstring const & )
{
return std::make_shared<WordSearchRequestInstant>();
}
vector< wstring > Class::getAlternateWritings( wstring const & )
noexcept
{
return vector< wstring >();
}
sptr< DataRequest > Class::getResource( string const & /*name*/ )
{
return std::make_shared<DataRequestInstant>( false );
}
sptr< DataRequest > Class::getSearchResults(const QString &, int, bool, int, int, bool, bool )
{
return std::make_shared<DataRequestInstant>( false );
}
QString const& Class::getDescription()
{
return dictionaryDescription;
}
QString Class::getMainFilename()
{
return QString();
}
QIcon const & Class::getIcon() noexcept
{
if( !dictionaryIconLoaded )
loadIcon();
return dictionaryIcon;
}
QIcon const & Class::getNativeIcon() noexcept
{
if( !dictionaryIconLoaded )
loadIcon();
return dictionaryNativeIcon;
}
void Class::loadIcon() noexcept
{
dictionaryIconLoaded = true;
}
bool Class::loadIconFromFile( QString const & _filename, bool isFullName )
{
QFileInfo info;
QString fileName( _filename );
if( isFullName )
info = QFileInfo( fileName );
else
{
fileName += "bmp";
info = QFileInfo( fileName );
if ( !info.isFile() )
{
fileName.chop( 3 );
fileName += "png";
info = QFileInfo( fileName );
}
if ( !info.isFile() )
{
fileName.chop( 3 );
fileName += "jpg";
info = QFileInfo( fileName );
}
if ( !info.isFile() )
{
fileName.chop( 3 );
fileName += "ico";
info = QFileInfo( fileName );
}
}
if ( info.isFile() )
{
QImage img( fileName );
if ( !img.isNull() )
{
// Load successful
//some icon is very large ,will crash the application.
img = img.scaledToWidth( 64 );
// Apply the color key
#if (QT_VERSION >= QT_VERSION_CHECK(6,0,0))
img.setAlphaChannel( img.createMaskFromColor( QColor( 192, 192, 192 ).rgb(),
Qt::MaskOutColor ) );
#endif
dictionaryNativeIcon = QIcon( QPixmap::fromImage( img ));
// Transform it to be square
int max = img.width() > img.height() ? img.width() : img.height();
QImage result( max, max, QImage::Format_ARGB32 );
result.fill( 0 ); // Black transparent
QPainter painter( &result );
painter.setRenderHint(QPainter::RenderHint::Antialiasing);
painter.drawImage( QPoint( img.width() == max ? 0 : ( max - img.width() ) / 2,
img.height() == max ? 0 : ( max - img.height() ) / 2 ),
img );
painter.end();
dictionaryIcon = QIcon( QPixmap::fromImage( result ) );
return !dictionaryIcon.isNull();
}
}
return false;
}
bool Class::loadIconFromText( QString iconUrl, QString const & text )
{
if( text.isEmpty() )
return false;
QImage img( iconUrl );
if ( !img.isNull() )
{
int iconSize = 64;
//some icon is very large ,will crash the application.
img = img.scaledToWidth( iconSize );
QImage result( iconSize, iconSize, QImage::Format_ARGB32 );
result.fill( 0 ); // Black transparent
int max = img.width() > img.height() ? img.width() : img.height();
QPainter painter( &result );
painter.setRenderHint(QPainter::RenderHint::Antialiasing);
painter.drawImage( QPoint( img.width() == max ? 0 : ( max - img.width() ) / 2,
img.height() == max ? 0 : ( max - img.height() ) / 2 ),
img );
painter.setCompositionMode(QPainter::CompositionMode_SourceAtop);
QFont font = painter.font();
//the text should be a little smaller than the icon
font.setPixelSize( iconSize * 0.6 );
font.setWeight( QFont::Black );
painter.setFont( font );
const QRect rectangle = QRect( 0, 0, iconSize, iconSize );
//select a single char.
auto abbrName = getAbbrName( text );
painter.drawText( rectangle, Qt::AlignCenter, abbrName);
painter.end();
dictionaryNativeIcon = dictionaryIcon = QIcon( QPixmap::fromImage( result ) );
return !dictionaryIcon.isNull();
}
return false;
}
QString Class::getAbbrName( QString const & text )
{
if(text.isEmpty())
return QString();
//remove whitespace
QString simplified = text;
simplified.remove(QRegularExpression("\\s"));
int index = qHash( simplified ) % simplified.size();
QString abbrName;
if( !Utils::isCJKChar( simplified.at( index ).unicode() ) )
{
// take two chars.
abbrName = simplified.mid( index, 2 );
}
else
{
abbrName = simplified.mid( index, 1 );
}
return abbrName;
}
void Class::isolateCSS( QString & css, QString const & wrapperSelector )
{
if( css.isEmpty() )
return;
QRegularExpression reg1( R"(\/\*(?:.(?!\*\/))*.?\*\/)",
QRegularExpression::DotMatchesEverythingOption );
QRegularExpression reg2( R"([ \*\>\+,;:\[\{\]])" );
QRegularExpression reg3( "[,;\\{]" );
int currentPos = 0;
QString newCSS;
QString prefix( "#gdfrom-" );
prefix += QString::fromLatin1( getId().c_str() );
if ( !wrapperSelector.isEmpty() )
prefix += " " + wrapperSelector;
// Strip comments
css.replace( reg1, QString() );
for( ; ; )
{
if( currentPos >= css.length() )
break;
QChar ch = css[ currentPos ];
if( ch == '@' )
{
// @ rules
int n = currentPos;
if( css.mid( currentPos, 7 ).compare( "@import", Qt::CaseInsensitive ) == 0
|| css.mid( currentPos, 10 ).compare( "@font-face", Qt::CaseInsensitive ) == 0
|| css.mid( currentPos, 10 ).compare( "@namespace", Qt::CaseInsensitive ) == 0
|| css.mid( currentPos, 8 ).compare( "@charset", Qt::CaseInsensitive ) == 0 )
{
// Copy rule as is.
n = css.indexOf( ';', currentPos );
int n2 = css.indexOf( '{', currentPos );
if( n2 > 0 && n > n2 )
n = n2 - 1;
}
else
if( css.mid( currentPos, 6 ).compare( "@media", Qt::CaseInsensitive ) == 0 )
{
// We must to parse it content to isolate it.
// Copy all up to '{' and continue parse inside.
n = css.indexOf( '{', currentPos );
}
else
if( css.mid( currentPos, 5 ).compare( "@page", Qt::CaseInsensitive ) == 0 )
{
// Don't copy rule. GD use own page layout.
n = css.indexOf( '}', currentPos );
if( n < 0 )
break;
currentPos = n + 1;
continue;
}
else
{
// Copy rule as is.
n = css.indexOf( '}', currentPos );
}
newCSS.append( css.mid( currentPos, n < 0 ? n : n - currentPos + 1 ) );
if( n < 0 )
break;
currentPos = n + 1;
continue;
}
if( ch == '{' )
{
// Selector declaration block.
// We copy it up to '}' as is.
int n = css.indexOf( '}', currentPos );
newCSS.append( css.mid( currentPos, n == -1 ? n : n - currentPos + 1 ) );
if( n < 0 )
break;
currentPos = n + 1;
continue;
}
if( ch.isLetter() || ch == '.' || ch == '#' || ch == '*' || ch == '\\' || ch == ':' )
{
if( ch.isLetter() || ch == '*' )
{
// Check for namespace prefix
QChar chr;
for( int i = currentPos; i < css.length(); i++ )
{
chr = css[ i ];
if( chr.isLetterOrNumber() || chr.isMark() || chr == '_' || chr == '-'
|| ( chr == '*' && i == currentPos ) )
continue;
if( chr == '|' )
{
// Namespace prefix found, copy it as is
newCSS.append( css.mid( currentPos, i - currentPos + 1 ) );
currentPos = i + 1;
}
break;
}
if ( chr == '|' )
continue;
}
// This is some selector.
// We must to add the isolate prefix to it.
int n = css.indexOf( reg2, currentPos + 1 );
QString s = css.mid( currentPos, n < 0 ? n : n - currentPos );
if( n < 0 )
{
newCSS.append( s );
break;
}
QString trimmed = s.trimmed();
if( trimmed.compare( "body", Qt::CaseInsensitive ) == 0
|| trimmed.compare( "html", Qt::CaseInsensitive ) == 0 )
{
newCSS.append( s + " " + prefix + " " );
currentPos += 4;
}
else
{
newCSS.append( prefix + " " );
}
n = css.indexOf( reg3, currentPos );
s = css.mid( currentPos, n < 0 ? n : n - currentPos );
newCSS.append( s );
if( n < 0 )
break;
currentPos = n;
continue;
}
newCSS.append( ch );
++currentPos;
}
css = newCSS;
}
string makeDictionaryId( vector< string > const & dictionaryFiles ) noexcept
{
std::vector< string > sortedList;
if ( Config::isPortableVersion() )
{
// For portable version, we use relative paths
sortedList.reserve( dictionaryFiles.size() );
QDir dictionariesDir( Config::getPortableVersionDictionaryDir() );
for( unsigned x = 0; x < dictionaryFiles.size(); ++x )
{
string const & full( dictionaryFiles[ x ] );
QFileInfo fileInfo( FsEncoding::decode( full.c_str() ) );
if ( fileInfo.isAbsolute() )
sortedList.push_back( FsEncoding::encode( dictionariesDir.relativeFilePath( fileInfo.filePath() ) ) );
else
{
// Well, it's relative. We don't technically support those, but
// what the heck
sortedList.push_back( full );
}
}
}
else
sortedList = dictionaryFiles;
std::sort( sortedList.begin(), sortedList.end() );
QCryptographicHash hash( QCryptographicHash::Md5 );
for( std::vector< string >::const_iterator i = sortedList.begin();
i != sortedList.end(); ++i )
hash.addData( i->c_str(), i->size() + 1 );
return hash.result().toHex().data();
}
// While this file is not supposed to have any Qt stuff since it's used by
// the dictionary backends, there's no platform-independent way to get hold
// of a timestamp of the file, so we use here Qt anyway. It is supposed to
// be fixed in the future when it's needed.
bool needToRebuildIndex( vector< string > const & dictionaryFiles,
string const & indexFile ) noexcept
{
unsigned long lastModified = 0;
for( std::vector< string >::const_iterator i = dictionaryFiles.begin();
i != dictionaryFiles.end(); ++i )
{
QString name = FsEncoding::decode( i->c_str() );
QFileInfo fileInfo( name );
unsigned long ts;
if( fileInfo.isDir() )
continue;
if( name.toLower().endsWith( ".zip" ) )
{
ZipFile::SplitZipFile zf( name );
if( !zf.exists() )
return true;
ts = zf.lastModified().toSecsSinceEpoch();
}
else
{
if ( !fileInfo.exists() )
return true;
ts = fileInfo.lastModified().toSecsSinceEpoch();
}
if ( ts > lastModified )
lastModified = ts;
}
#ifndef USE_XAPIAN
QDir d(FsEncoding::decode( indexFile.c_str() ));
if(d.exists()){
d.removeRecursively();
}
#endif
QFileInfo fileInfo( FsEncoding::decode( indexFile.c_str() ) );
if ( !fileInfo.exists() )
return true;
return fileInfo.lastModified().toSecsSinceEpoch() < lastModified;
}
string getFtsSuffix(){
#ifdef USE_XAPIAN
return "_FTS_x";
#else
return "_FTS";
#endif
}
QString generateRandomDictionaryId()
{
return QString(
QCryptographicHash::hash(
QDateTime::currentDateTime().toString( "\"Random\"dd.MM.yyyy hh:mm:ss.zzz" ).toUtf8(),
QCryptographicHash::Md5 ).toHex() );
}
QMap< std::string, sptr< Dictionary::Class > >
dictToMap( std::vector< sptr< Dictionary::Class > > const & dicts )
{
QMap< std::string, sptr< Dictionary::Class > > dictMap;
for( auto dict : dicts )
{
dictMap.insert( dict.get()->getId(), dict );
}
return dictMap;
}
}
|