Fixed #6304: xdxf plugin deletes cache files when beign removed from app
[mdictionary] / trunk / src / plugins / xdxf / src / xdxfplugin.cpp
1 /*******************************************************************************
2
3     This file is part of mDictionary.
4
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.
9
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.
14
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/>.
17
18     Copyright 2010 Comarch S.A.
19
20 *******************************************************************************/
21
22 /*! \file xdxfplugin.cpp
23 \author Jakub Jaszczynski <j.j.jaszczynski@gmail.com>
24 */
25
26 #include "xdxfplugin.h"
27 #include <QDebug>
28 #include "../../../includes/Notify.h"
29
30 XdxfPlugin::XdxfPlugin(QObject *parent) : CommonDictInterface(parent),
31                     _langFrom(tr("")), _langTo(tr("")),_name(tr("")),
32                     _type("xdxf"), _infoNote(tr("")) {
33     _wordsCount = -1;
34     _settings = new Settings();
35     _dictDialog = new XdxfDictDialog(this);
36     cachingDialog = new XdxfCachingDialog();
37
38     connect(cachingDialog, SIGNAL(cancelCaching()),
39             this, SLOT(stop()));
40
41     connect(this, SIGNAL(updateCachingProgress(int,int)),
42             cachingDialog, SLOT(updateCachingProgress(int,int)));
43
44     _settings->setValue("type","xdxf");
45
46     stopped = false;
47
48     _icon = QIcon(":/icons/xdxf.png");
49     initAccents();
50 }
51
52
53
54 XdxfPlugin::~XdxfPlugin() {
55     delete _settings;
56 }
57
58
59 QString XdxfPlugin::langFrom() const {   
60     return _langFrom;
61 }
62
63 QString XdxfPlugin::langTo() const {
64     return  _langTo;
65 }
66
67 QString XdxfPlugin::name() const {
68     return  _name;
69 }
70
71 QString XdxfPlugin::type() const {
72     return _type;
73 }
74
75 QString XdxfPlugin::infoNote() const {
76     return  _infoNote;
77 }
78
79 QList<Translation*> XdxfPlugin::searchWordList(QString word, int limit) {
80     if(word.indexOf("*")==-1 && word.indexOf("?")==-1 && word.indexOf("_")==-1
81        && word.indexOf("%")==-1)
82         word+="*";
83     if(isCached())
84         return searchWordListCache(word,limit);
85     return searchWordListFile(word, limit);
86 }
87
88 QList<Translation*> XdxfPlugin::searchWordListCache(QString word, int limit) {
89     int i=0;
90     QSet<Translation*> translations;
91
92     QString cacheFilePath = _settings->value("cache_path");
93     db.setDatabaseName(cacheFilePath);
94     if(!db.open()) {
95         qDebug() << "Database error" << db.lastError().text() << endl;
96         Q_EMIT notify(Notify::Warning, QString("Cache database cannot be "
97                 "opened for %1 dictionary. Searching in xdxf file. "
98                 "You may want to recache.").arg(name()));
99         return searchWordListFile(word, limit);
100     }
101
102     stopped = false;
103     word = word.toLower();
104     word = word.replace("*", "%");
105     word = word.replace("?", "_");
106
107     QSqlQuery cur(db);
108     if(limit !=0)
109         cur.prepare("select word from dict where word like ? or normalized like ? limit ?");
110     else
111         cur.prepare("select word from dict where word like ? or normalized like ?");
112     cur.addBindValue(word);
113     cur.addBindValue(word);
114     if(limit !=0)
115         cur.addBindValue(limit);
116     cur.exec();
117     bool in = false;
118     while(cur.next() && (i<limit || limit==0 ) ) {
119         in = true;
120         bool ok=true;
121         Translation *tran;
122         foreach(tran,translations) {
123             if(tran->key().toLower()==cur.value(0).toString().toLower())
124                     ok=false;
125         }
126         if(ok) {  /*add key word to list*/
127             translations.insert(new TranslationXdxf(
128                     cur.value(0).toString().toLower(),
129                     _infoNote, this));
130             i++;
131         }
132     }
133     db.close();
134     return translations.toList();
135 }
136
137 QList<Translation*> XdxfPlugin::searchWordListFile(QString word, int limit) {
138     QTime time;
139     time.start();
140     QSet<Translation*> translations;
141     QFile dictionaryFile(path);
142
143     word = word.toLower();
144     //word = removeAccents(word);
145
146     stopped = false;
147     QRegExp regWord(word);
148     regWord.setCaseSensitivity(Qt::CaseInsensitive);
149     regWord.setPatternSyntax(QRegExp::Wildcard);
150     if(!dictionaryFile.open(QFile::ReadOnly | QFile::Text)) {
151         qDebug()<<"Error: could not open file";
152         Q_EMIT notify(Notify::Warning,
153                 QString("Xdxf file cannot be read for %1").arg(name()));
154         return translations.toList();
155     }
156
157     QXmlStreamReader reader(&dictionaryFile);
158     /*search words list*/
159     QString a;
160
161     int i=0;
162     while(!reader.atEnd() && !stopped){
163         reader.readNextStartElement();
164         if(reader.name()=="ar") {
165             while(reader.name()!="k" && !reader.atEnd())
166                 reader.readNextStartElement();
167             if(!reader.atEnd())
168                 a = reader.readElementText();
169             if((regWord.exactMatch(a) || regWord.exactMatch(removeAccents(a))) &&
170                     (i<limit || limit==0)) {
171                 bool ok=true;
172                 Translation *tran;
173                 foreach(tran,translations) {
174                     if(tran->key().toLower()==a.toLower())
175                         ok=false;  /*if key word is in the dictionary more that one */
176                 }
177                 if(ok) {  /*add key word to list*/
178                     translations<<(new TranslationXdxf(a.toLower(),
179                                 _infoNote,this));
180                     i++;
181                 }
182                 if(i>=limit && limit!=0)
183                     break;
184             }
185         }
186         this->thread()->yieldCurrentThread();
187     }
188     stopped=false;
189     dictionaryFile.close();
190     qDebug() << time.elapsed();
191     return translations.toList();
192 }
193
194 QString XdxfPlugin::search(QString key) {
195 //    if(_settings->value("cached") == "true")
196     if(isCached())
197         return searchCache(key);
198     return searchFile(key);
199 }
200
201 QString XdxfPlugin::searchCache(QString key) {
202     QString result("");
203     QString cacheFilePath = _settings->value("cache_path");
204     db.setDatabaseName(cacheFilePath);
205     key = key.toLower();
206
207     if(!db.open()) {
208         qDebug() << "Database error" << db.lastError().text() << endl;
209         Q_EMIT notify(Notify::Warning, QString("Cache database cannot be "
210                 "opened for %1 dictionary. Searching in xdxf file. "
211                 "You may want to recache.").arg(name()));
212         return searchFile(key);
213     }
214
215     QSqlQuery cur(db);
216     cur.prepare("select translation from dict where word like ?");
217     cur.addBindValue(key);
218     cur.exec();
219     while(cur.next())
220         result += cur.value(0).toString();
221
222     db.close();
223
224     return result;
225
226 }
227
228 QString XdxfPlugin::searchFile(QString key) {
229     key = key.toLower();
230     QFile dictionaryFile(path);
231     QString resultString("");
232     if(!dictionaryFile.open(QFile::ReadOnly | QFile::Text)) {
233         Q_EMIT notify(Notify::Warning,
234                 QString("Xdxf file cannot be read for %1").arg(name()));
235         qDebug()<<"Error: could not open file";
236         return "";
237     }
238     QXmlStreamReader reader(&dictionaryFile);
239     QString a;
240
241     bool match =false;
242     stopped = false;
243     while (!reader.atEnd()&& !stopped) {
244         reader.readNext();
245         if(reader.tokenType() == QXmlStreamReader::StartElement) {
246             if(reader.name()=="k") {
247                 a = reader.readElementText();
248                 if(a.toLower()==key.toLower())
249                     match = true;
250             }
251         }
252         if(match) {
253             QString temp("");
254             while(reader.name()!="ar" && !reader.atEnd()) {
255                 if(reader.name()!="" && reader.name()!="k") {
256                     if(reader.tokenType()==QXmlStreamReader::EndElement)
257                         temp+=tr("</");
258                     if(reader.tokenType()==QXmlStreamReader::StartElement)
259                         temp+=tr("<");
260                     temp+=reader.name().toString();
261                     if(reader.name().toString()=="c" &&
262                             reader.tokenType()==QXmlStreamReader::StartElement)
263                        temp= temp + tr(" c=\"") + reader.attributes().
264                                value(tr("c")).toString() + tr("\"");
265                     temp+=tr(">");
266                 }
267                 temp+= reader.text().toString().replace("<","&lt;").
268                         replace(">","&gt;");
269                 reader.readNext();
270             }
271             if(temp.at(0)==QChar('\n'))
272                 temp.remove(0,1);
273             resultString+=tr("<key>") + a +tr("</key>");
274             resultString+=tr("<t>") + temp + tr("</t>");
275             match=false;
276         }
277         this->thread()->yieldCurrentThread();
278     }
279     stopped=false;
280     dictionaryFile.close();
281
282     return resultString;
283 }
284
285 void XdxfPlugin::stop() {
286     stopped=true;
287 }
288
289 DictDialog* XdxfPlugin::dictDialog() {
290      return _dictDialog;
291 }
292
293 void XdxfPlugin::setPath(QString path){
294     this->path=path;
295     _settings->setValue("path",path);
296     //getDictionaryInfo();
297 }
298
299 CommonDictInterface* XdxfPlugin::getNew(const Settings *settings) const {
300     XdxfPlugin *plugin = new XdxfPlugin();
301     if(settings){
302         plugin->setPath(settings->value("path"));
303         QStringList list = settings->keys();
304
305         plugin->db_name = plugin->_settings->value("type")
306                          + plugin->_settings->value("path");
307         plugin->db = QSqlDatabase::addDatabase("QSQLITE", plugin->db_name);
308
309         if(settings->value("cached").isEmpty() &&
310            settings->value("generateCache") == "true") {
311             plugin->makeCache("");
312         }
313         foreach(QString key, list)
314            if(key != "generateCache")
315                 plugin->settings()->setValue(key, settings->value(key));
316         delete settings;
317     }
318     plugin->getDictionaryInfo();
319     return  plugin;
320 }
321
322 bool XdxfPlugin::isAvailable() const {
323     return true;
324 }
325
326
327
328 void XdxfPlugin::setHash(uint _hash) {
329     this->_hash=_hash;
330 }
331
332
333
334 uint XdxfPlugin::hash() const {
335    return _hash;
336 }
337
338
339
340 Settings* XdxfPlugin::settings() {
341     return _settings;
342 }
343
344
345
346 bool XdxfPlugin::isCached() {
347     if(_settings->value("cached") == "true")
348         return true;
349     return false;
350 }
351
352
353
354 void XdxfPlugin::setSettings(Settings *settings) {
355
356     QString oldPath = _settings->value("path");
357     if(oldPath != settings->value("path")) {
358         setPath(settings->value("path"));
359     }
360
361    foreach(QString key, settings->keys())
362        if(key != "generateCache")
363            _settings->setValue(key, settings->value(key));
364
365     if((_settings->value("cached") == "false" ||
366             _settings->value("cached").isEmpty()) &&
367             settings->value("generateCache") == "true") {
368         makeCache("");
369     }
370     else if (settings->value("generateCache") != "true") {
371        _settings->setValue("cached", "false");
372     }
373
374
375     delete settings;
376
377     Q_EMIT settingsChanged();
378 }
379
380
381
382 void XdxfPlugin::getDictionaryInfo() {
383     QFile dictionaryFile(path);
384     if(!dictionaryFile.open(QFile::ReadOnly | QFile::Text)) {
385        Q_EMIT notify(Notify::Warning,
386                QString("Xdxf file cannot be read dictionary"));
387         qDebug()<<"Error: could not open file";
388         return;
389     }
390
391     QXmlStreamReader reader(&dictionaryFile);
392     reader.readNextStartElement();
393     if(reader.name()=="xdxf") {
394       if(reader.attributes().hasAttribute("lang_from"))
395         _langFrom = reader.attributes().value("lang_from").toString();
396       if(reader.attributes().hasAttribute("lang_to"))
397         _langTo = reader.attributes().value("lang_to").toString();
398     }
399     reader.readNextStartElement();
400     if(reader.name()=="full_name")
401         _name=reader.readElementText();
402     reader.readNextStartElement();
403     if(reader.name()=="description")
404         _infoNote=reader.readElementText();
405
406     QString format = "png";
407     QString initialPath = QDir::currentPath() + tr("/xdxf.") + format;
408
409     _infoNote="path=\""+initialPath+"\"> \n" + _name + " [" + _langFrom + "-" + _langTo + "] (" + _type + ")";
410     dictionaryFile.close();
411 }
412
413
414
415 QIcon* XdxfPlugin::icon() {
416     return &_icon;
417 }
418
419 int XdxfPlugin::countWords() {
420     if(_wordsCount > 0)
421         return _wordsCount;
422
423     QFile dictionaryFile(path);
424     if(!dictionaryFile.open(QFile::ReadOnly | QFile::Text)) {
425         Q_EMIT notify(Notify::Warning,
426                 QString("Xdxf file cannot be read for %1 dictionary")
427                 .arg(name()));
428         qDebug()<<"Error: could not open file";
429         return -1;
430     }
431
432     dictionaryFile.seek(0);
433
434     long wordsCount = 0;
435
436     QString line;
437     while(!dictionaryFile.atEnd()) {
438         line = dictionaryFile.readLine();
439         if(line.contains("<k>")) {
440             wordsCount++;
441         }
442     }
443     _wordsCount = wordsCount;
444     dictionaryFile.close();
445     return wordsCount;
446 }
447
448 bool XdxfPlugin::makeCache(QString dir) {
449     cachingDialog->setVisible(true);
450     QCoreApplication::processEvents();
451     stopped = false;
452     QFileInfo dictFileN(_settings->value("path"));
453     QString cachePathN;
454     cachePathN = QDir::homePath() + "/.mdictionary/"
455                  + dictFileN.completeBaseName() + ".cache";
456
457     QFile dictionaryFile(dictFileN.filePath());
458
459
460     if (!dictionaryFile.open(QFile::ReadOnly | QFile::Text)) {
461         Q_EMIT updateCachingProgress(100, 0);
462         Q_EMIT notify(Notify::Warning,
463                 QString("Xdxf file cannot be read for %1 dictionary")
464                 .arg(name()));
465         return 0;
466     }
467     QXmlStreamReader reader(&dictionaryFile);
468
469
470     db.setDatabaseName(cachePathN);
471     if(!db.open()) {
472         qDebug() << "Database error" << db.lastError().text() << endl;
473         Q_EMIT updateCachingProgress(100, 0);
474         Q_EMIT notify(Notify::Warning, QString("Cache database cannot be "
475                 "opened for %1 dictionary. Searching in xdxf file. "
476                 "You may want to recache.").arg(name()));
477         return false;
478     }
479     QCoreApplication::processEvents();
480     QSqlQuery cur(db);
481     cur.exec("PRAGMA synchronous = 0");
482     cur.exec("drop table dict");
483     QCoreApplication::processEvents();
484     cur.exec("create table dict(word text, normalized text ,translation text)");
485     int counter = 0;
486     cur.exec("BEGIN;");
487
488     QString a;
489     bool match = false;
490     QTime timer;
491     timer.start();
492     countWords();
493
494     int lastProg = -1;
495
496     QString stripAcc = settings()->value("strip_accents");
497     settings()->setValue("strip_accents", "true");
498
499
500     counter=0;
501     while (!reader.atEnd() && !stopped) {
502
503         QCoreApplication::processEvents();
504         reader.readNext();
505
506         if(reader.tokenType() == QXmlStreamReader::StartElement) {
507             if(reader.name()=="k"){
508                 a = reader.readElementText();
509                 match = true;
510             }
511         }
512         if(match) {
513             QString temp("");
514             while(reader.name()!="ar" && !reader.atEnd()) {
515                 if(reader.name()!="" && reader.name()!="k") {
516                     if(reader.tokenType()==QXmlStreamReader::EndElement)
517                         temp+=tr("</");
518                     if(reader.tokenType()==QXmlStreamReader::StartElement)
519                         temp+=tr("<");
520                     temp+=reader.name().toString();
521                     if(reader.name().toString()=="c" && reader.tokenType()==QXmlStreamReader::StartElement)
522                        temp= temp + tr(" c=\"") + reader.attributes().value(tr("c")).toString() + tr("\"");
523                     temp+=tr(">");
524                 }
525                 temp+= reader.text().toString().replace("<","&lt;").replace(">","&gt;");;
526                 reader.readNext();
527             }
528             if(temp.at(0)==QChar('\n'))
529                 temp.remove(0,1);
530             temp=tr("<key>") + a + tr("</key>") + tr("<t>") + temp+ tr("</t>");
531             match=false;
532             cur.prepare("insert into dict values(?,?,?)");
533             cur.addBindValue(a);
534             cur.addBindValue(removeAccents(a));
535             cur.addBindValue(temp);
536             cur.exec();
537             counter++;
538             int prog = counter*100/_wordsCount;
539             if(prog % 5 == 0 && lastProg != prog) {
540                 Q_EMIT updateCachingProgress(prog,
541                                              timer.restart());
542                 lastProg = prog;
543             }
544         }
545     }
546
547     cur.exec("END;");
548     cur.exec("select count(*) from dict");
549     settings()->setValue("strip_accents", stripAcc);
550
551     countWords();
552     cachingDialog->setVisible(false);
553
554     if(!cur.next() || countWords() != cur.value(0).toInt())
555     {
556         Q_EMIT updateCachingProgress(100, timer.restart());
557         Q_EMIT notify(Notify::Warning,
558                 QString("Database caching error, please try againg."));
559         db.close();
560         return false;
561     }
562     _settings->setValue("cache_path", cachePathN);
563     _settings->setValue("cached", "true");
564
565
566     db.close();
567     return true;
568 }
569
570
571
572 void XdxfPlugin::clean() {
573     if(settings()->value("cached") == "true")
574         QFile(settings()->value("cache_path")).remove();
575 }
576
577 Q_EXPORT_PLUGIN2(xdxf, XdxfPlugin)