goldendict-ng/hunspell.cc

808 lines
19 KiB
C++
Raw Normal View History

2012-02-20 21:47:14 +00:00
/* This file is (c) 2008-2012 Konstantin Isakov <ikm@goldendict.org>
2009-04-09 14:15:01 +00:00
* Part of GoldenDict. Licensed under GPLv3 or later, see the LICENSE file */
#include "hunspell.hh"
#include "utf8.hh"
#include "htmlescape.hh"
#include "iconv.hh"
#include "folding.hh"
#include "wstring_qt.hh"
#include "language.hh"
#include "langcoder.hh"
2009-04-09 14:15:01 +00:00
#include <QRunnable>
#include <QThreadPool>
#include <QSemaphore>
#include <QRegExp>
#include <QDir>
#include <QCoreApplication>
#include <set>
#include <hunspell/hunspell.hxx>
#include "gddebug.hh"
#include "fsencoding.hh"
#include <QFileInfo>
2009-04-09 14:15:01 +00:00
namespace HunspellMorpho {
using namespace Dictionary;
using gd::wchar;
2009-04-09 14:15:01 +00:00
namespace {
class HunspellDictionary: public Dictionary::Class
{
string name;
Hunspell hunspell;
2009-04-21 20:09:02 +00:00
#ifdef Q_OS_WIN32
static string Utf8ToLocal8Bit( string const & name )
{
return string( QString::fromUtf8( name.c_str() ).toLocal8Bit().data() );
}
#endif
2009-04-09 14:15:01 +00:00
public:
/// files[ 0 ] should be .aff file, files[ 1 ] should be .dic file.
HunspellDictionary( string const & id, string const & name_,
vector< string > const & files ):
Dictionary::Class( id, files ),
name( name_ ),
#ifdef Q_OS_WIN32
hunspell( Utf8ToLocal8Bit( files[ 0 ] ).c_str(), Utf8ToLocal8Bit( files[ 1 ] ).c_str() )
#else
2009-04-09 14:15:01 +00:00
hunspell( files[ 0 ].c_str(), files[ 1 ].c_str() )
#endif
2009-04-09 14:15:01 +00:00
{
}
2009-04-21 20:09:02 +00:00
2009-04-09 14:15:01 +00:00
virtual string getName() throw()
{ return name; }
virtual map< Property, string > getProperties() throw()
{ return map< Property, string >(); }
virtual unsigned long getArticleCount() throw()
{ return 0; }
virtual unsigned long getWordCount() throw()
{ return 0; }
virtual sptr< WordSearchRequest > prefixMatch( wstring const &,
unsigned long maxResults )
throw( std::exception );
2009-04-09 14:15:01 +00:00
virtual sptr< WordSearchRequest > findHeadwordsForSynonym( wstring const & )
throw( std::exception );
virtual sptr< DataRequest > getArticle( wstring const &,
vector< wstring > const & alts,
wstring const & )
2009-04-09 14:15:01 +00:00
throw( std::exception );
virtual bool isLocalDictionary()
{ return true; }
protected:
virtual void loadIcon() throw();
private:
// We used to have a separate mutex for each Hunspell instance, assuming
// that its code was reentrant (though probably not thread-safe). However,
// crashes were discovered later when using several Hunspell dictionaries
// simultaneously, and we've switched to have a single mutex for all hunspell
// calls - evidently it's not really reentrant.
static Mutex & getHunspellMutex()
{
static Mutex mutex;
return mutex;
}
// Mutex hunspellMutex;
2009-04-09 14:15:01 +00:00
};
/// Encodes the given string to be passed to the hunspell object. May throw
/// Iconv::Ex
string encodeToHunspell( Hunspell &, wstring const & );
/// Decodes the given string returned by the hunspell object. May throw
/// Iconv::Ex
wstring decodeFromHunspell( Hunspell &, char const * );
/// Returns true if the string contains whitespace, false otherwise
bool containsWhitespace( wstring const & str )
{
wchar const * next = str.c_str();
2009-04-09 14:15:01 +00:00
for( ; *next; ++next )
if ( Folding::isWhitespace( *next ) )
return true;
return false;
}
void HunspellDictionary::loadIcon() throw()
{
if ( dictionaryIconLoaded )
return;
QString fileName =
QDir::fromNativeSeparators( FsEncoding::decode( getDictionaryFilenames()[ 0 ].c_str() ) );
// Remove the extension
fileName.chop( 3 );
if( !loadIconFromFile( fileName ) )
{
// Load failed -- use default icons
dictionaryNativeIcon = dictionaryIcon = QIcon(":/icons/icon32_hunspell.png");
}
dictionaryIconLoaded = true;
}
2009-04-09 14:15:01 +00:00
/// HunspellDictionary::getArticle()
class HunspellArticleRequest;
class HunspellArticleRequestRunnable: public QRunnable
{
HunspellArticleRequest & r;
QSemaphore & hasExited;
2009-04-21 20:09:02 +00:00
2009-04-09 14:15:01 +00:00
public:
HunspellArticleRequestRunnable( HunspellArticleRequest & r_,
QSemaphore & hasExited_ ): r( r_ ),
hasExited( hasExited_ )
{}
~HunspellArticleRequestRunnable()
{
hasExited.release();
}
2009-04-21 20:09:02 +00:00
2009-04-09 14:15:01 +00:00
virtual void run();
};
class HunspellArticleRequest: public Dictionary::DataRequest
{
friend class HunspellArticleRequestRunnable;
Mutex & hunspellMutex;
Hunspell & hunspell;
wstring word;
QAtomicInt isCancelled;
QSemaphore hasExited;
public:
HunspellArticleRequest( wstring const & word_,
Mutex & hunspellMutex_,
Hunspell & hunspell_ ):
hunspellMutex( hunspellMutex_ ),
hunspell( hunspell_ ),
word( word_ )
{
QThreadPool::globalInstance()->start(
new HunspellArticleRequestRunnable( *this, hasExited ) );
}
void run(); // Run from another thread by HunspellArticleRequestRunnable
virtual void cancel()
{
isCancelled.ref();
}
2009-04-21 20:09:02 +00:00
2009-04-09 14:15:01 +00:00
~HunspellArticleRequest()
{
isCancelled.ref();
hasExited.acquire();
}
};
void HunspellArticleRequestRunnable::run()
{
r.run();
}
void HunspellArticleRequest::run()
{
if ( isCancelled )
{
finish();
return;
}
// We'd need to free this if it gets allocated and an exception shows up
char ** suggestions = 0;
int suggestionsCount = 0;
try
{
wstring trimmedWord = Folding::trimWhitespaceOrPunct( word );
if ( containsWhitespace( trimmedWord ) )
{
// For now we don't analyze whitespace-containing phrases
finish();
return;
}
Mutex::Lock _( hunspellMutex );
string encodedWord = encodeToHunspell( hunspell, trimmedWord );
if ( hunspell.spell( encodedWord.c_str() ) )
{
// Good word -- no spelling suggestions then.
finish();
return;
}
suggestionsCount = hunspell.suggest( &suggestions, encodedWord.c_str() );
if ( suggestionsCount )
{
// There were some suggestions made for us. Make an appropriate output.
2009-04-21 20:09:02 +00:00
string result = "<div class=\"gdspellsuggestion\">" +
2009-04-09 14:15:01 +00:00
Html::escape( QCoreApplication::translate( "Hunspell", "Spelling suggestions: " ).toUtf8().data() );
wstring lowercasedWord = Folding::applySimpleCaseOnly( word );
for( int x = 0; x < suggestionsCount; ++x )
{
wstring suggestion = decodeFromHunspell( hunspell, suggestions[ x ] );
if ( Folding::applySimpleCaseOnly( suggestion ) == lowercasedWord )
{
// If among suggestions we see the same word just with the different
// case, we botch the search -- our searches are case-insensitive, and
// there's no need for suggestions on a good word.
2009-04-21 20:09:02 +00:00
2009-04-09 14:15:01 +00:00
finish();
hunspell.free_list( &suggestions, suggestionsCount );
return;
}
string suggestionUtf8 = Utf8::encode( suggestion );
result += "<a href=\"bword:";
2009-04-09 14:15:01 +00:00
result += Html::escape( suggestionUtf8 ) + "\">";
result += Html::escape( suggestionUtf8 ) + "</a>";
if ( x != suggestionsCount - 1 )
result += ", ";
}
result += "</div>";
Mutex::Lock _( dataMutex );
data.resize( result.size() );
memcpy( &data.front(), result.data(), result.size() );
hasAnyData = true;
}
}
catch( Iconv::Ex & e )
{
gdWarning( "Hunspell: charset convertion error, no processing's done: %s\n", e.what() );
2009-04-09 14:15:01 +00:00
}
2013-09-24 13:56:47 +00:00
catch( std::exception & e )
{
gdWarning( "Hunspell: error: %s\n", e.what() );
2013-09-24 13:56:47 +00:00
}
2009-04-09 14:15:01 +00:00
if ( suggestions )
{
Mutex::Lock _( hunspellMutex );
hunspell.free_list( &suggestions, suggestionsCount );
}
finish();
}
sptr< DataRequest > HunspellDictionary::getArticle( wstring const & word,
vector< wstring > const &,
wstring const & )
2009-04-09 14:15:01 +00:00
throw( std::exception )
{
return new HunspellArticleRequest( word, getHunspellMutex(), hunspell );
2009-04-09 14:15:01 +00:00
}
/// HunspellDictionary::findHeadwordsForSynonym()
class HunspellHeadwordsRequest;
class HunspellHeadwordsRequestRunnable: public QRunnable
{
HunspellHeadwordsRequest & r;
QSemaphore & hasExited;
2009-04-21 20:09:02 +00:00
2009-04-09 14:15:01 +00:00
public:
HunspellHeadwordsRequestRunnable( HunspellHeadwordsRequest & r_,
QSemaphore & hasExited_ ): r( r_ ),
hasExited( hasExited_ )
{}
~HunspellHeadwordsRequestRunnable()
{
hasExited.release();
}
2009-04-21 20:09:02 +00:00
2009-04-09 14:15:01 +00:00
virtual void run();
};
class HunspellHeadwordsRequest: public Dictionary::WordSearchRequest
{
friend class HunspellHeadwordsRequestRunnable;
Mutex & hunspellMutex;
Hunspell & hunspell;
wstring word;
QAtomicInt isCancelled;
QSemaphore hasExited;
public:
HunspellHeadwordsRequest( wstring const & word_,
Mutex & hunspellMutex_,
Hunspell & hunspell_ ):
hunspellMutex( hunspellMutex_ ),
hunspell( hunspell_ ),
word( word_ )
{
QThreadPool::globalInstance()->start(
new HunspellHeadwordsRequestRunnable( *this, hasExited ) );
}
void run(); // Run from another thread by HunspellHeadwordsRequestRunnable
virtual void cancel()
{
isCancelled.ref();
}
2009-04-21 20:09:02 +00:00
2009-04-09 14:15:01 +00:00
~HunspellHeadwordsRequest()
{
isCancelled.ref();
hasExited.acquire();
}
private:
/// Generates suggestions via hunspell
QVector< wstring > suggest( wstring & word );
2009-04-09 14:15:01 +00:00
};
void HunspellHeadwordsRequestRunnable::run()
{
r.run();
}
void HunspellHeadwordsRequest::run()
{
if ( isCancelled )
{
finish();
return;
}
wstring trimmedWord = Folding::trimWhitespaceOrPunct( word );
2009-04-09 14:15:01 +00:00
if ( trimmedWord.size() > 80 )
2009-04-09 14:15:01 +00:00
{
// We won't do anything for overly long sentences since that would probably
// only waste time.
finish();
return;
}
2009-04-09 14:15:01 +00:00
if ( containsWhitespace( trimmedWord ) )
{
// Analyze each word separately and use the first suggestion, if any.
// This is useful for compound expressions where one of the words is
// in different form, e.g. "dozing off" -> "doze off".
// In this mode, we only provide a single suggestion at most.
wstring result;
wstring word;
for( wchar const * c = trimmedWord.c_str(); ; ++c )
2009-04-09 14:15:01 +00:00
{
if ( !*c || Folding::isPunct( *c ) || Folding::isWhitespace( * c ) )
{
if ( word.size() )
{
QVector< wstring > suggestions = suggest( word );
if ( suggestions.size() )
result += suggestions[ 0 ];
else
result += word;
word.clear();
}
if ( *c )
result.push_back( *c );
else
break;
}
else
word.push_back( *c );
}
if ( word.size() )
{
QVector< wstring > suggestions = suggest( trimmedWord );
if ( suggestions.size() )
result += suggestions[ 0 ];
else
result += word;
2009-04-09 14:15:01 +00:00
}
if ( result != trimmedWord )
{
Mutex::Lock _( dataMutex );
matches.push_back( result );
}
}
else
{
QVector< wstring > suggestions = suggest( trimmedWord );
if ( !suggestions.empty() )
{
Mutex::Lock _( dataMutex );
for( int x = 0; x < suggestions.size(); ++x )
matches.push_back( suggestions[ x ] );
}
}
finish();
}
QVector< wstring > HunspellHeadwordsRequest::suggest( wstring & word )
{
QVector< wstring > result;
// We'd need to free this if it gets allocated and an exception shows up
char ** suggestions = 0;
int suggestionsCount = 0;
try
{
2009-04-09 14:15:01 +00:00
Mutex::Lock _( hunspellMutex );
string encodedWord = encodeToHunspell( hunspell, word );
2009-04-09 14:15:01 +00:00
suggestionsCount = hunspell.analyze( &suggestions, encodedWord.c_str() );
if ( suggestionsCount )
{
// There were some suggestions made for us. Make an appropriate output.
wstring lowercasedWord = Folding::applySimpleCaseOnly( word );
static QRegExp cutStem( "^\\s*st:(((\\s+(?!\\w{2}:))|\\S+)+)" );
2009-04-09 14:15:01 +00:00
for( int x = 0; x < suggestionsCount; ++x )
{
QString suggestion = gd::toQString( decodeFromHunspell( hunspell, suggestions[ x ] ) );
2009-04-09 14:15:01 +00:00
DPRINTF( ">>>Sugg: %s\n", suggestion.toLocal8Bit().data() );
2009-04-09 14:15:01 +00:00
if ( cutStem.indexIn( suggestion ) != -1 )
{
wstring alt = gd::toWString( cutStem.cap( 1 ) );
2009-04-09 14:15:01 +00:00
if ( Folding::applySimpleCaseOnly( alt ) != lowercasedWord ) // No point in providing same word
{
#ifdef QT_DEBUG
qDebug() << ">>>>>Alt:" << gd::toQString( alt );
#endif
result.append( alt );
2009-04-09 14:15:01 +00:00
}
}
}
}
}
catch( Iconv::Ex & e )
{
gdWarning( "Hunspell: charset convertion error, no processing's done: %s\n", e.what() );
2009-04-09 14:15:01 +00:00
}
if ( suggestions )
{
Mutex::Lock _( hunspellMutex );
hunspell.free_list( &suggestions, suggestionsCount );
}
return result;
2009-04-09 14:15:01 +00:00
}
2009-04-09 14:15:01 +00:00
sptr< WordSearchRequest > HunspellDictionary::findHeadwordsForSynonym( wstring const & word )
throw( std::exception )
{
return new HunspellHeadwordsRequest( word, getHunspellMutex(), hunspell );
2009-04-09 14:15:01 +00:00
}
/// HunspellDictionary::prefixMatch()
class HunspellPrefixMatchRequest;
class HunspellPrefixMatchRequestRunnable: public QRunnable
{
HunspellPrefixMatchRequest & r;
QSemaphore & hasExited;
2009-04-21 20:09:02 +00:00
public:
HunspellPrefixMatchRequestRunnable( HunspellPrefixMatchRequest & r_,
QSemaphore & hasExited_ ): r( r_ ),
hasExited( hasExited_ )
{}
~HunspellPrefixMatchRequestRunnable()
{
hasExited.release();
}
2009-04-21 20:09:02 +00:00
virtual void run();
};
class HunspellPrefixMatchRequest: public Dictionary::WordSearchRequest
{
friend class HunspellPrefixMatchRequestRunnable;
Mutex & hunspellMutex;
Hunspell & hunspell;
wstring word;
QAtomicInt isCancelled;
QSemaphore hasExited;
public:
HunspellPrefixMatchRequest( wstring const & word_,
Mutex & hunspellMutex_,
Hunspell & hunspell_ ):
hunspellMutex( hunspellMutex_ ),
hunspell( hunspell_ ),
word( word_ )
{
QThreadPool::globalInstance()->start(
new HunspellPrefixMatchRequestRunnable( *this, hasExited ) );
}
void run(); // Run from another thread by HunspellPrefixMatchRequestRunnable
virtual void cancel()
{
isCancelled.ref();
}
2009-04-21 20:09:02 +00:00
~HunspellPrefixMatchRequest()
{
isCancelled.ref();
hasExited.acquire();
}
};
void HunspellPrefixMatchRequestRunnable::run()
{
r.run();
}
void HunspellPrefixMatchRequest::run()
{
if ( isCancelled )
{
finish();
return;
}
try
{
wstring trimmedWord = Folding::trimWhitespaceOrPunct( word );
if ( trimmedWord.empty() || containsWhitespace( trimmedWord ) )
{
// For now we don't analyze whitespace-containing phrases
finish();
return;
}
Mutex::Lock _( hunspellMutex );
string encodedWord = encodeToHunspell( hunspell, trimmedWord );
if ( hunspell.spell( encodedWord.c_str() ) )
{
// Known word -- add it to the result
2009-04-21 20:09:02 +00:00
Mutex::Lock _( dataMutex );
matches.push_back( WordMatch( trimmedWord, 1 ) );
}
}
catch( Iconv::Ex & e )
{
gdWarning( "Hunspell: charset convertion error, no processing's done: %s\n", e.what() );
}
finish();
}
sptr< WordSearchRequest > HunspellDictionary::prefixMatch( wstring const & word,
unsigned long /*maxResults*/ )
throw( std::exception )
{
return new HunspellPrefixMatchRequest( word, getHunspellMutex(), hunspell );
}
2009-04-09 14:15:01 +00:00
string encodeToHunspell( Hunspell & hunspell, wstring const & str )
{
Iconv conv( hunspell.get_dic_encoding(), Iconv::GdWchar );
2009-04-09 14:15:01 +00:00
void const * in = str.data();
size_t inLeft = str.size() * sizeof( wchar );
2009-04-09 14:15:01 +00:00
vector< char > result( str.size() * 4 + 1 ); // +1 isn't actually needed,
// but then iconv complains on empty
// words
void * out = &result.front();
size_t outLeft = result.size();
if ( conv.convert( in, inLeft, out, outLeft ) != Iconv::Success )
throw Iconv::Ex();
return string( &result.front(), result.size() - outLeft );
}
wstring decodeFromHunspell( Hunspell & hunspell, char const * str )
{
Iconv conv( Iconv::GdWchar, hunspell.get_dic_encoding() );
2009-04-09 14:15:01 +00:00
void const * in = str;
size_t inLeft = strlen( str );
vector< wchar > result( inLeft + 1 ); // +1 isn't needed, but see above
2009-04-09 14:15:01 +00:00
void * out = &result.front();
size_t outLeft = result.size() * sizeof( wchar );
2009-04-09 14:15:01 +00:00
if ( conv.convert( in, inLeft, out, outLeft ) != Iconv::Success )
throw Iconv::Ex();
return wstring( &result.front(), result.size() - outLeft/sizeof( wchar ) );
2009-04-09 14:15:01 +00:00
}
}
vector< sptr< Dictionary::Class > > makeDictionaries( Config::Hunspell const & cfg )
throw( std::exception )
{
vector< sptr< Dictionary::Class > > result;
vector< DataFiles > dataFiles = findDataFiles( cfg.dictionariesPath );
2012-12-10 12:49:45 +00:00
for( int x = 0; x < cfg.enabledDictionaries.size(); ++x )
2009-04-09 14:15:01 +00:00
{
for( unsigned d = dataFiles.size(); d--; )
{
if ( dataFiles[ d ].dictId == cfg.enabledDictionaries[ x ] )
{
// Found it
vector< string > dictFiles;
dictFiles.push_back(
FsEncoding::encode( QDir::toNativeSeparators( dataFiles[ d ].affFileName ) ) );
2009-04-09 14:15:01 +00:00
dictFiles.push_back(
FsEncoding::encode( QDir::toNativeSeparators( dataFiles[ d ].dicFileName ) ) );
2009-04-09 14:15:01 +00:00
result.push_back(
new HunspellDictionary( Dictionary::makeDictionaryId( dictFiles ),
dataFiles[ d ].dictName.toUtf8().data(),
dictFiles ) );
break;
}
}
}
return result;
}
vector< DataFiles > findDataFiles( QString const & path )
{
// Empty path means unconfigured directory
if ( path.isEmpty() )
return vector< DataFiles >();
QDir dir( path );
// Find all affix files
QFileInfoList affixFiles = dir.entryInfoList( ( QStringList() << "*.aff" << "*.AFF" ), QDir::Files );
vector< DataFiles > result;
std::set< QString > presentNames;
for( QFileInfoList::const_iterator i = affixFiles.constBegin();
i != affixFiles.constEnd(); ++i )
{
QString affFileName = i->absoluteFilePath();
// See if there's a corresponding .dic file
QString dicFileNameBase = affFileName.mid( 0, affFileName.size() - 3 );
QString dicFileName = dicFileNameBase + "dic";
if ( !QFile( dicFileName ).exists() )
{
dicFileName = dicFileNameBase + "DIC";
if ( !QFile( dicFileName ).exists() )
continue; // No dic file
}
QString dictId = i->fileName();
dictId.chop( 4 );
QString dictBaseId = dictId.size() < 3 ? dictId :
( ( dictId[ 2 ] == '-' || dictId[ 2 ] == '_' ) ? dictId.mid( 0, 2 ) : QString() );
dictBaseId = dictBaseId.toLower();
// Try making up good readable name from dictBaseId
QString localizedName;
2009-04-09 14:15:01 +00:00
if ( dictBaseId.size() == 2 )
localizedName = Language::localizedNameForId( LangCoder::code2toInt( dictBaseId.toLatin1().data() ) );
2009-04-09 14:15:01 +00:00
QString dictName = dictId;
if ( localizedName.size() )
2009-04-09 14:15:01 +00:00
{
dictName = localizedName;
2009-04-09 14:15:01 +00:00
if ( dictId.size() > 2 && ( dictId[ 2 ] == '-' || dictId[ 2 ] == '_' ) &&
dictId.mid( 3 ).toLower() != dictBaseId )
dictName += " (" + dictId.mid( 3 ) + ")";
2009-04-09 14:15:01 +00:00
}
dictName = QCoreApplication::translate( "Hunspell", "%1 Morphology" ).arg( dictName );
if ( presentNames.insert( dictName ).second )
{
// Only include dictionaries with unique names. This combats stuff
// like symlinks en-US->en_US and such
2009-04-21 20:09:02 +00:00
2009-04-09 14:15:01 +00:00
result.push_back( DataFiles( affFileName, dicFileName, dictId, dictName ) );
}
}
return result;
}
}