1 /*******************************************************************************
3 This file is part of mDictionary.
5 mDictionary is free software: you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation, either version 3 of the License, or
8 (at your option) any later version.
10 mDictionary is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with mDictionary. If not, see <http://www.gnu.org/licenses/>.
18 Copyright 2010 Comarch S.A.
20 *******************************************************************************/
22 /*! \file xdxfplugin.cpp
23 \author Jakub Jaszczynski <j.j.jaszczynski@gmail.com>
26 #include "xdxfplugin.h"
28 #include "../../include/Notify.h"
30 XdxfPlugin::XdxfPlugin(QObject *parent) : CommonDictInterface(parent),
31 _langFrom(""), _langTo(""),_name(""), _infoNote("") {
32 _settings = new Settings();
33 _dictDialog = new XdxfDictDialog(this, this);
35 connect(_dictDialog, SIGNAL(notify(Notify::NotifyType,QString)),
36 this, SIGNAL(notify(Notify::NotifyType,QString)));
38 cachingDialog = new XdxfCachingDialog(this);
41 _settings->setValue("type","xdxf");
42 _icon = QIcon("/usr/share/mdictionary/xdxf.png");
46 connect(cachingDialog, SIGNAL(cancelCaching()),
48 connect(this, SIGNAL(updateCachingProgress(int,int)),
49 cachingDialog, SLOT(updateCachingProgress(int,int)));
53 void XdxfPlugin::retranslate() {
54 QString locale = QLocale::system().name();
56 QTranslator *translator = new QTranslator(this);
58 if(!translator->load(":/xdxf/translations/" + locale)) {
59 translator->load(":/xdxf/translations/en_US");
61 QCoreApplication::installTranslator(translator);
65 XdxfPlugin::~XdxfPlugin() {
72 QString XdxfPlugin::langFrom() const {
77 QString XdxfPlugin::langTo() const {
82 QString XdxfPlugin::name() const {
87 QString XdxfPlugin::type() const {
88 return QString("xdxf");
92 QString XdxfPlugin::infoNote() const {
97 QList<Translation*> XdxfPlugin::searchWordList(QString word, int limit) {
98 if( word.indexOf("*")==-1 && word.indexOf("?")==-1 &&
99 word.indexOf("_")==-1 && word.indexOf("%")==-1)
103 return searchWordListCache(word,limit);
104 return searchWordListFile(word, limit);
108 QList<Translation*> XdxfPlugin::searchWordListCache(QString word, int limit) {
110 QSet<Translation*> translations;
111 QString cacheFilePath = _settings->value("cache_path");
113 db.setDatabaseName(cacheFilePath);
114 if(!QFile::exists(cacheFilePath) || !db.open()) {
115 qDebug() << "Database error" << db.lastError().text() << endl;
116 Q_EMIT notify(Notify::Warning, QString(tr("Cache database cannot be "
117 "opened for %1 dictionary. Searching in XDXF file. "
118 "You may want to recache.").arg(name())));
119 _settings->setValue("cached","false");
120 return searchWordListFile(word, limit);
123 word = word.toLower();
124 word = word.replace("*", "%");
125 word = word.replace("?", "_");
129 cur.prepare("select word from dict where word like ? or normalized "
132 cur.prepare("select word from dict where word like ? or normalized "
134 cur.addBindValue(word);
135 cur.addBindValue(word);
137 cur.addBindValue(limit);
141 while(cur.next() && (i<limit || limit==0 ) ) {
145 foreach(tran,translations) {
146 if(tran->key().toLower()==cur.value(0).toString().toLower())
149 if(ok) { /*add key word to list*/
150 translations.insert(new TranslationXdxf(
151 cur.value(0).toString().toLower(),
152 _dictionaryInfo, this));
157 return translations.toList();
161 QList<Translation*> XdxfPlugin::searchWordListFile(QString word, int limit) {
162 QSet<Translation*> translations;
163 QFile dictionaryFile(_settings->value("path"));
164 word = word.toLower();
167 QRegExp regWord(word);
168 regWord.setCaseSensitivity(Qt::CaseInsensitive);
169 regWord.setPatternSyntax(QRegExp::Wildcard);
171 /*check xdxf file exist*/
172 if(!QFile::exists(_settings->value("path"))
173 || !dictionaryFile.open(QFile::ReadOnly | QFile::Text)) {
174 qDebug()<<"Error: could not open file";
175 Q_EMIT notify(Notify::Warning,
176 QString(tr("XDXF file cannot be read for %1").arg(name())));
177 return translations.toList();
180 QXmlStreamReader reader(&dictionaryFile);
184 /*search words list*/
185 while(!reader.atEnd() && !stopped){
186 reader.readNextStartElement();
187 if(reader.name()=="ar") {
188 while(reader.name()!="k" && !reader.atEnd())
189 reader.readNextStartElement();
191 readKey = reader.readElementText();
192 if((regWord.exactMatch(readKey)
193 || regWord.exactMatch(removeAccents(readKey)))
194 && (i<limit || limit==0)) {
197 foreach(tran,translations) {
198 if(tran->key().toLower()==readKey.toLower())
199 ok=false; /*if key is in the dictionary more that one */
201 if(ok) { /*add key word to list*/
202 translations<<(new TranslationXdxf(readKey.toLower(),
203 _dictionaryInfo,this));
206 if(i>=limit && limit!=0)
210 this->thread()->yieldCurrentThread();
213 dictionaryFile.close();
214 return translations.toList();
218 QString XdxfPlugin::search(QString key) {
220 return searchCache(key);
221 return searchFile(key);
225 QString XdxfPlugin::searchCache(QString key) {
227 QString cacheFilePath = _settings->value("cache_path");
228 db.setDatabaseName(cacheFilePath);
231 if(!QFile::exists(cacheFilePath) || !db.open()) {
232 qDebug() << "Database error" << db.lastError().text() << endl;
233 Q_EMIT notify(Notify::Warning, QString(tr("Cache database cannot be "
234 "opened for %1 dictionary. Searching in XDXF file. "
235 "You may want to recache.").arg(name())));
236 _settings->setValue("cached","false");
237 return searchFile(key);
242 cur.prepare("select translation from dict where word like ?");
243 cur.addBindValue(key);
246 result += cur.value(0).toString();
255 QString XdxfPlugin::searchFile(QString key) {
256 QFile dictionaryFile(_settings->value("path"));
257 QString resultString("");
260 /*check xdxf file exist*/
261 if(!QFile::exists(_settings->value("path"))
262 || !dictionaryFile.open(QFile::ReadOnly | QFile::Text)) {
263 Q_EMIT notify(Notify::Warning,
264 QString(tr("XDXF file cannot be read for %1").arg(name())));
265 qDebug()<<"Error: could not open file";
269 QXmlStreamReader reader(&dictionaryFile);
274 /*search translations for word*/
275 while (!reader.atEnd()&& !stopped) {
277 if(reader.tokenType() == QXmlStreamReader::StartElement) {
278 if(reader.name()=="k") {
279 readKey = reader.readElementText();
280 if(readKey.toLower()==key.toLower())
286 while(reader.name()!="ar" && !reader.atEnd()) {
287 if(reader.name()!="" && reader.name()!="k") {
288 if(reader.tokenType()==QXmlStreamReader::EndElement)
290 if(reader.tokenType()==QXmlStreamReader::StartElement)
292 temp+=reader.name().toString();
293 if(reader.name().toString()=="c" &&
294 reader.tokenType()==QXmlStreamReader::StartElement)
295 temp= temp + " c=\"" + reader.attributes().
296 value("c").toString() + "\"";
299 temp+= reader.text().toString().replace("<","<").
303 if(temp.at(0)==QChar('\n'))
305 resultString+="<key>" + readKey +"</key>";
306 resultString+="<t>" + temp + "</t>";
309 this->thread()->yieldCurrentThread();
312 dictionaryFile.close();
317 void XdxfPlugin::stop() {
322 DictDialog* XdxfPlugin::dictDialog() {
327 CommonDictInterface* XdxfPlugin::getNew(const Settings *settings) const {
328 XdxfPlugin *plugin = new XdxfPlugin();
330 if(settings && plugin->setSettings(settings)) {
340 bool XdxfPlugin::isAvailable() const {
345 Settings* XdxfPlugin::settings() {
350 bool XdxfPlugin::isCached() {
351 if(_settings->value("cached") == "true")
357 bool XdxfPlugin::setSettings(const Settings *settings) {
359 bool isPathChange=false;
360 QString oldPath = _settings->value("path");
361 Settings *oldSettings = new Settings ;
363 if(oldPath != settings->value("path")) {
364 if(oldPath!="" && _settings->value("cache_path")!="")
369 foreach(QString key, _settings->keys())
370 oldSettings->setValue(key, _settings->value(key));
372 foreach(QString key, settings->keys()) {
373 if(key != "generateCache")
374 _settings->setValue(key, settings->value(key));
377 if(!getDictionaryInfo()) {
378 Q_EMIT notify(Notify::Warning,
379 QString(tr("XDXF file is in wrong format")));
380 qDebug()<<"Error: xdxf file is in wrong format";
382 _settings=oldSettings;
389 _settings->setValue("cached","false");
390 if(_settings->value("cached")=="true"
391 && _settings->value("cache_path")!="") {
392 db_name = _settings->value("type")
393 + _settings->value("cache_path");
394 db = QSqlDatabase::addDatabase("QSQLITE",db_name);
398 if((_settings->value("cached") == "false" ||
399 _settings->value("cached").isEmpty()) &&
400 settings->value("generateCache") == "true") {
405 else if (settings->value("generateCache") == "false") {
406 _settings->setValue("cached", "false");
411 Q_EMIT settingsChanged();
416 bool XdxfPlugin::getDictionaryInfo() {
417 QFile dictionaryFile(_settings->value("path"));
418 if(!QFile::exists(_settings->value("path"))
419 || !dictionaryFile.open(QFile::ReadOnly | QFile::Text)) {
420 Q_EMIT notify(Notify::Warning,
421 QString(tr("XDXF dictionary cannot be read from file")));
422 qDebug()<<"Error: could not open file";
427 QXmlStreamReader reader(&dictionaryFile);
428 reader.readNextStartElement();
429 if(reader.name()=="xdxf") {
431 if(reader.attributes().hasAttribute("lang_from"))
432 _langFrom = reader.attributes().value("lang_from").toString();
433 if(reader.attributes().hasAttribute("lang_to"))
434 _langTo = reader.attributes().value("lang_to").toString();
436 reader.readNextStartElement();
437 if(reader.name()=="full_name")
438 _name=reader.readElementText();
439 reader.readNextStartElement();
440 if(reader.name()=="description")
441 _infoNote=reader.readElementText();
443 _dictionaryInfo= _name + " [" + _langFrom + "-"
446 dictionaryFile.close();
453 QIcon* XdxfPlugin::icon() {
458 int XdxfPlugin::countWords() {
461 QFile dictionaryFile(_settings->value("path"));
462 if(!QFile::exists(_settings->value("path"))
463 || !dictionaryFile.open(QFile::ReadOnly | QFile::Text)) {
464 Q_EMIT notify(Notify::Warning,
465 QString(tr("XDXF file cannot be read for %1 dictionary")
467 qDebug()<<"Error: could not open file";
471 dictionaryFile.seek(0);
476 while(!dictionaryFile.atEnd()) {
477 line = dictionaryFile.readLine();
478 if(line.contains("<k>")) {
482 _wordsCount = wordsCount;
483 dictionaryFile.close();
488 bool XdxfPlugin::makeCache(QString) {
490 cachingDialog->setVisible(true);
492 cachingDialog->show();
494 QCoreApplication::processEvents();
495 QFileInfo dictFileN(_settings->value("path"));
499 /*create cache file name*/
502 cachePathN = QDir::homePath() + "/.mdictionary/"
503 + dictFileN.completeBaseName()+"."
504 +QString::number(i) + ".cache";
506 } while(QFile::exists(cachePathN));
508 db_name = _settings->value("type") + cachePathN;
509 db = QSqlDatabase::addDatabase("QSQLITE",db_name);
511 /*checke errors (File open and db open)*/
512 QFile dictionaryFile(dictFileN.filePath());
513 if (!QFile::exists(_settings->value("path"))
514 || !dictionaryFile.open(QFile::ReadOnly | QFile::Text)) {
515 Q_EMIT updateCachingProgress(100, 0);
516 Q_EMIT notify(Notify::Warning,
517 QString(tr("XDXF file cannot be read for %1 dictionary")
521 QXmlStreamReader reader(&dictionaryFile);
522 db.setDatabaseName(cachePathN);
524 qDebug() << "Database error" << db.lastError().text() << endl;
525 Q_EMIT updateCachingProgress(100, 0);
526 Q_EMIT notify(Notify::Warning, QString(tr("Cache database cannot be "
527 "opened for %1 dictionary. Searching in XDXF file. "
528 "You may want to recache.").arg(name())));
533 QCoreApplication::processEvents();
535 cur.exec("PRAGMA synchronous = 0");
536 cur.exec("drop table dict");
537 QCoreApplication::processEvents();
538 cur.exec("create table dict(word text, normalized text ,translation text)");
548 _settings->setValue("strip_accents", "true");
551 /*add all words to db*/
552 while (!reader.atEnd() && !stopped) {
553 QCoreApplication::processEvents();
555 if(reader.tokenType() == QXmlStreamReader::StartElement) {
556 if(reader.name()=="k"){
557 readKey = reader.readElementText();
563 while(reader.name()!="ar" && !reader.atEnd()) {
564 if(reader.name()!="" && reader.name()!="k") {
565 if(reader.tokenType()==QXmlStreamReader::EndElement)
567 if(reader.tokenType()==QXmlStreamReader::StartElement)
569 temp+=reader.name().toString();
570 if(reader.name().toString()=="c"
571 && reader.tokenType()==QXmlStreamReader::StartElement) {
573 + reader.attributes().value("c").toString()
578 temp+= reader.text().toString().replace("<","<").replace(">"
582 if(temp.at(0)==QChar('\n'))
584 temp="<key>" + readKey + "</key>" + "<t>" + temp+ "</t>";
586 cur.prepare("insert into dict values(?,?,?)");
587 cur.addBindValue(readKey);
588 cur.addBindValue(removeAccents(readKey));
589 cur.addBindValue(temp);
592 int prog = counter*100/_wordsCount;
593 if(prog % 5 == 0 && lastProg != prog) {
594 Q_EMIT updateCachingProgress(prog,timer.restart());
600 cur.exec("select count(*) from dict");
601 //cachingDialog->hide();
603 /*checke errors (wrong number of added words)*/
605 if(!cur.next() || countWords() != cur.value(0).toInt()) {
606 Q_EMIT updateCachingProgress(100, timer.restart());
607 Q_EMIT notify(Notify::Warning,
608 QString(tr("Database caching error, please try again.")));
613 _settings->setValue("cache_path", cachePathN);
614 _settings->setValue("cached", "true");
621 void XdxfPlugin::clean() {
622 if(QFile::exists(_settings->value("cache_path"))) {
623 QFile(_settings->value("cache_path")).remove();
624 QSqlDatabase::removeDatabase(db_name);
629 Q_EXPORT_PLUGIN2(xdxf, XdxfPlugin)