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 *******************************************************************************/
23 \brief Implementation of xdxf plugin's main class.
25 \author Jakub Jaszczynski <j.j.jaszczynski@gmail.com>
28 #include "xdxfplugin.h"
30 #include "../../include/Notify.h"
31 #include "DownloadDict.h"
32 #include "XdxfDictDownloader.h"
34 XdxfDictDownloader XdxfPlugin::dictDownloader;
37 bool XdxfPlugin::dictDownloaderInitialized = false;
40 XdxfPlugin::XdxfPlugin(QObject *parent) : CommonDictInterface(parent),
41 _langFrom(""), _langTo(""),_name(""), _infoNote("") {
42 _settings = new Settings();
43 _dictDialog = new XdxfDictDialog(this, this);
45 connect(_dictDialog, SIGNAL(notify(Notify::NotifyType,QString)),
46 this, SIGNAL(notify(Notify::NotifyType,QString)));
48 if(!dictDownloaderInitialized) {
49 connect(&dictDownloader, SIGNAL(notify(Notify::NotifyType,QString)),
50 this, SIGNAL(notify(Notify::NotifyType,QString)));
51 dictDownloaderInitialized = true;
54 _settings->setValue("type","xdxf");
55 _icon = QIcon("/usr/share/mdictionary/xdxf.png");
63 void XdxfPlugin::retranslate() {
64 QString locale = QLocale::system().name();
65 QTranslator *translator = new QTranslator(this);
67 if(!translator->load(":/xdxf/translations/" + locale)) {
68 translator->load(":/xdxf/translations/en_US");
70 QCoreApplication::installTranslator(translator);
74 XdxfPlugin::~XdxfPlugin() {
80 QString XdxfPlugin::langFrom() const {
85 QString XdxfPlugin::langTo() const {
90 QString XdxfPlugin::name() const {
95 QString XdxfPlugin::type() const {
96 return QString("xdxf");
100 QString XdxfPlugin::infoNote() const {
105 QList<Translation*> XdxfPlugin::searchWordList(QString word, int limit) {
106 if( word.indexOf("*")==-1 && word.indexOf("?")==-1 &&
107 word.indexOf("_")==-1 && word.indexOf("%")==-1)
111 return searchWordListCache(word,limit);
112 return searchWordListFile(word, limit);
116 QList<Translation*> XdxfPlugin::searchWordListCache(QString word, int limit) {
117 QSet<Translation*> translations;
118 QString cacheFilePath = _settings->value("cache_path");
120 db.setDatabaseName(cacheFilePath);
121 if(!QFile::exists(cacheFilePath) || !db.open()) {
122 qDebug() << "Database error" << db.lastError().text() << endl;
123 Q_EMIT notify(Notify::Warning, QString(tr("Cache database cannot be "
124 "opened for %1 dictionary. Searching in XDXF file. "
125 "You may want to recache.").arg(name())));
126 _settings->setValue("cached","false");
127 return searchWordListFile(word, limit);
131 word = word.toLower();
132 word = word.replace("*", "%");
133 word = word.replace("?", "_");
137 cur.prepare("select word from dict where word like ? or normalized "
140 cur.prepare("select word from dict where word like ? or normalized "
142 cur.addBindValue(word);
143 cur.addBindValue(word);
145 cur.addBindValue(limit);
148 while(cur.next() && (translations.size()<limit || limit==0)) {
149 translations.insert(new TranslationXdxf(
150 cur.value(0).toString(),
151 _dictionaryInfo, this));
154 return translations.toList();
158 QList<Translation*> XdxfPlugin::searchWordListFile(QString word, int limit) {
159 QSet<Translation*> translations;
160 QFile dictionaryFile(_settings->value("path"));
161 word = word.toLower();
164 QRegExp regWord(word);
165 regWord.setCaseSensitivity(Qt::CaseInsensitive);
166 regWord.setPatternSyntax(QRegExp::Wildcard);
168 /*check xdxf file exist*/
169 if(!QFile::exists(_settings->value("path"))
170 || !dictionaryFile.open(QFile::ReadOnly | QFile::Text)) {
171 qDebug()<<"Error: could not open file";
172 Q_EMIT notify(Notify::Warning,
173 QString(tr("XDXF file cannot be read for %1").arg(name())));
174 return translations.toList();
177 QXmlStreamReader reader(&dictionaryFile);
181 /*search words list*/
182 while(!reader.atEnd() && !stopped){
183 reader.readNextStartElement();
184 if(reader.name()=="ar") {
185 while(reader.name()!="k" && !reader.atEnd())
186 reader.readNextStartElement();
188 readKey = reader.readElementText();
189 if((regWord.exactMatch(readKey)
190 || regWord.exactMatch(removeAccents(readKey)))
191 && (i<limit || limit==0) && !reader.atEnd()) {
192 translations<<(new TranslationXdxf(readKey.toLower(),
193 _dictionaryInfo,this));
194 if(translations.size()==limit && limit!=0)
198 this->thread()->yieldCurrentThread();
201 dictionaryFile.close();
202 return translations.toList();
206 QString XdxfPlugin::search(QString key) {
208 return searchCache(key);
209 return searchFile(key);
213 QString XdxfPlugin::searchCache(QString key) {
215 QString cacheFilePath = _settings->value("cache_path");
216 db.setDatabaseName(cacheFilePath);
219 if(!QFile::exists(cacheFilePath) || !db.open()) {
220 qDebug() << "Database error" << db.lastError().text() << endl;
221 Q_EMIT notify(Notify::Warning, QString(tr("Cache database cannot be "
222 "opened for %1 dictionary. Searching in XDXF file. "
223 "You may want to recache.").arg(name())));
224 _settings->setValue("cached","false");
225 return searchFile(key);
230 cur.prepare("select translation from dict where word like ?");
231 cur.addBindValue(key);
234 result += cur.value(0).toString();
241 QString XdxfPlugin::searchFile(QString key) {
242 QFile dictionaryFile(_settings->value("path"));
243 QString resultString("");
246 /*check xdxf file exist*/
247 if(!QFile::exists(_settings->value("path"))
248 || !dictionaryFile.open(QFile::ReadOnly | QFile::Text)) {
249 Q_EMIT notify(Notify::Warning,
250 QString(tr("XDXF file cannot be read for %1").arg(name())));
251 qDebug()<<"Error: could not open file";
255 QXmlStreamReader reader(&dictionaryFile);
260 /*search translations for word*/
261 while (!reader.atEnd()&& !stopped) {
263 if(reader.tokenType() == QXmlStreamReader::StartElement) {
264 if(reader.name()=="k") {
265 readKey = reader.readElementText();
266 if(readKey.toLower()==key.toLower())
272 while(reader.name()!="ar" && !reader.atEnd()) {
273 if(reader.name()!="" && reader.name()!="k") {
274 if(reader.tokenType()==QXmlStreamReader::EndElement)
276 if(reader.tokenType()==QXmlStreamReader::StartElement)
278 temp+=reader.name().toString();
279 if(reader.name().toString()=="c" &&
280 reader.tokenType()==QXmlStreamReader::StartElement)
281 temp= temp + " c=\"" + reader.attributes().
282 value("c").toString() + "\"";
285 temp+= reader.text().toString().replace("<","<").
289 if(temp.at(0)==QChar('\n'))
291 resultString+="<key>" + readKey +"</key>";
292 resultString+="<t>" + temp + "</t>";
295 this->thread()->yieldCurrentThread();
298 dictionaryFile.close();
303 void XdxfPlugin::stop() {
308 DictDialog* XdxfPlugin::dictDialog() {
313 CommonDictInterface* XdxfPlugin::getNew(const Settings *settings) const {
314 XdxfPlugin *plugin = new XdxfPlugin();
316 connect(plugin, SIGNAL(notify(Notify::NotifyType,QString)),
317 this, SIGNAL(notify(Notify::NotifyType,QString)));
319 ((XdxfDictDialog*)plugin->dictDialog())->setLastDialogParent(_dictDialog->lastDialogParent());
321 if(settings && plugin->setSettings(settings)) {
322 disconnect(plugin, SIGNAL(notify(Notify::NotifyType,QString)),
323 this, SIGNAL(notify(Notify::NotifyType,QString)));
327 disconnect(plugin, SIGNAL(notify(Notify::NotifyType,QString)),
328 this, SIGNAL(notify(Notify::NotifyType,QString)));
335 bool XdxfPlugin::isAvailable() const {
340 Settings* XdxfPlugin::settings() {
345 bool XdxfPlugin::isCached() {
346 if(_settings->value("cached") == "true")
352 bool XdxfPlugin::setSettings(const Settings *settings) {
354 bool isPathChange=false;
355 QString oldPath = _settings->value("path");
356 Settings *oldSettings = new Settings ;
358 if(oldPath != settings->value("path")) {
359 if(oldPath!="" && _settings->value("cache_path")!="")
364 foreach(QString key, _settings->keys())
365 oldSettings->setValue(key, _settings->value(key));
367 foreach(QString key, settings->keys())
368 if(key != "generateCache")
369 _settings->setValue(key, settings->value(key));
371 if(!getDictionaryInfo()) {
372 Q_EMIT notify(Notify::Warning,
373 QString(tr("XDXF file is in wrong format")));
374 qDebug()<<"Error: xdxf file is in wrong format";
376 _settings=oldSettings;
383 _settings->setValue("cached","false");
384 if(_settings->value("cached")=="true"
385 && _settings->value("cache_path")!="") {
386 db_name = _settings->value("type")
387 + _settings->value("cache_path");
388 db = QSqlDatabase::addDatabase("QSQLITE",db_name);
392 if((_settings->value("cached") == "false" ||
393 _settings->value("cached").isEmpty()) &&
394 settings->value("generateCache") == "true") {
399 else if (settings->value("generateCache") == "false") {
400 _settings->setValue("cached", "false");
405 Q_EMIT settingsChanged();
410 bool XdxfPlugin::getDictionaryInfo() {
411 QFile dictionaryFile(_settings->value("path"));
412 if(!QFile::exists(_settings->value("path"))
413 || !dictionaryFile.open(QFile::ReadOnly | QFile::Text)) {
414 Q_EMIT notify(Notify::Warning,
415 QString(tr("XDXF dictionary cannot be read from file")));
416 qDebug()<<"Error: could not open file";
421 QXmlStreamReader reader(&dictionaryFile);
422 reader.readNextStartElement();
423 if(reader.name()=="xdxf") {
425 if(reader.attributes().hasAttribute("lang_from"))
426 _langFrom = reader.attributes().value("lang_from").toString();
427 if(reader.attributes().hasAttribute("lang_to"))
428 _langTo = reader.attributes().value("lang_to").toString();
430 reader.readNextStartElement();
431 if(reader.name()=="full_name")
432 _name=reader.readElementText();
434 qDebug()<<"no full_name";
435 reader.readNextStartElement();
436 if(reader.name()=="description")
437 _infoNote=reader.readElementText();
439 qDebug()<<"no description";
441 _dictionaryInfo= _name + " [" + _langFrom + "-"
444 dictionaryFile.close();
451 QIcon* XdxfPlugin::icon() {
456 int XdxfPlugin::countWords() {
459 QFile dictionaryFile(_settings->value("path"));
460 if(!QFile::exists(_settings->value("path"))
461 || !dictionaryFile.open(QFile::ReadOnly | QFile::Text)) {
462 Q_EMIT notify(Notify::Warning,
463 QString(tr("XDXF file cannot be read for %1 dictionary")
465 qDebug()<<"Error: could not open file";
469 dictionaryFile.seek(0);
473 while(!dictionaryFile.atEnd()) {
474 line = dictionaryFile.readLine();
475 if(line.contains("<k>")) {
479 _wordsCount = wordsCount;
480 dictionaryFile.close();
485 bool XdxfPlugin::makeCache(QString) {
486 XdxfCachingDialog d(_dictDialog->lastDialogParent());
488 connect(&d, SIGNAL(cancelCaching()),
490 connect(this, SIGNAL(updateCachingProgress(int,int)),
491 &d, SLOT(updateCachingProgress(int,int)));
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.toLower());
588 cur.addBindValue(removeAccents(readKey).toLower());
589 cur.addBindValue(temp);
592 int prog = counter*100/_wordsCount;
593 if(prog % 2 == 0 && lastProg != prog) {
594 Q_EMIT updateCachingProgress(prog,timer.restart());
600 cur.exec("select count(*) from dict");
602 /*checke errors (wrong number of added words)*/
604 if(!cur.next() || countWords() != cur.value(0).toInt()) {
605 Q_EMIT updateCachingProgress(100, timer.restart());
606 Q_EMIT notify(Notify::Warning,
607 QString(tr("Database caching error, please try again.")));
609 _settings->setValue("cache_path", cachePathN);
612 _settings->setValue("cache_path","");
616 _settings->setValue("cache_path", cachePathN);
617 _settings->setValue("cached", "true");
619 disconnect(&d, SIGNAL(cancelCaching()),
621 disconnect(this, SIGNAL(updateCachingProgress(int,int)),
622 &d, SLOT(updateCachingProgress(int,int)));
628 void XdxfPlugin::clean() {
629 if(QFile::exists(_settings->value("cache_path"))) {
630 QFile(_settings->value("cache_path")).remove();
631 QSqlDatabase::removeDatabase(db_name);
636 Q_EXPORT_PLUGIN2(xdxf, XdxfPlugin)