Merge branch 'master' into google
[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(tr("xdxf")), _infoNote(tr("")) {
33     _wordsCount = -1;
34     _settings = new Settings();
35     _dictDialog = new XdxfDictDialog(this);
36     cachingDialog = new XdxfCachingDialog(this);
37
38
39     connect(cachingDialog, SIGNAL(cancelCaching()),
40             this, SLOT(stop()));
41     connect(this, SIGNAL(updateCachingProgress(int,int)),
42             cachingDialog, SLOT(updateCachingProgress(int,int)));
43
44
45     _settings->setValue("type","xdxf");
46
47     stopped = false;
48
49     _icon = QIcon(":/icons/xdxf.png");
50     initAccents();
51 }
52
53
54
55 XdxfPlugin::~XdxfPlugin() {
56     delete _settings;
57     delete cachingDialog;
58 }
59
60
61 QString XdxfPlugin::langFrom() const {   
62     return _langFrom;
63 }
64
65 QString XdxfPlugin::langTo() const {
66     return  _langTo;
67 }
68
69 QString XdxfPlugin::name() const {
70     return  _name;
71 }
72
73 QString XdxfPlugin::type() const {
74     return _type;
75 }
76
77 QString XdxfPlugin::infoNote() const {
78     return  _infoNote;
79 }
80
81 QList<Translation*> XdxfPlugin::searchWordList(QString word, int limit) {
82     if(word.indexOf("*")==-1 && word.indexOf("?")==-1 && word.indexOf("_")==-1
83        && word.indexOf("%")==-1)
84         word+="*";
85     if(isCached())
86         return searchWordListCache(word,limit);
87     return searchWordListFile(word, limit);
88 }
89
90 QList<Translation*> XdxfPlugin::searchWordListCache(QString word, int limit) {
91     int i=0;
92     QSet<Translation*> translations;
93
94     QString cacheFilePath = _settings->value("cache_path");
95     db.setDatabaseName(cacheFilePath);
96     if(!db.open()) {
97         qDebug() << "Database error" << db.lastError().text() << endl;
98         Q_EMIT notify(Notify::Warning, QString("Cache database cannot be "
99                 "opened for %1 dictionary. Searching in xdxf file. "
100                 "You may want to recache.").arg(name()));
101         return searchWordListFile(word, limit);
102     }
103
104     stopped = false;
105     word = word.toLower();
106     word = word.replace("*", "%");
107     word = word.replace("?", "_");
108
109     QSqlQuery cur(db);
110     if(limit !=0)
111         cur.prepare("select word from dict where word like ? or normalized like ? limit ?");
112     else
113         cur.prepare("select word from dict where word like ? or normalized like ?");
114     cur.addBindValue(word);
115     cur.addBindValue(word);
116     if(limit !=0)
117         cur.addBindValue(limit);
118     cur.exec();
119     bool in = false;
120     while(cur.next() && (i<limit || limit==0 ) ) {
121         in = true;
122         bool ok=true;
123         Translation *tran;
124         foreach(tran,translations) {
125             if(tran->key().toLower()==cur.value(0).toString().toLower())
126                     ok=false;
127         }
128         if(ok) {  /*add key word to list*/
129             translations.insert(new TranslationXdxf(
130                     cur.value(0).toString().toLower(),
131                     _infoNote, this));
132             i++;
133         }
134     }
135     db.close();
136     return translations.toList();
137 }
138
139 QList<Translation*> XdxfPlugin::searchWordListFile(QString word, int limit) {
140     QTime time;
141     QSet<Translation*> translations;
142     QFile dictionaryFile(path);
143
144     word = word.toLower();
145     //word = removeAccents(word);
146
147     stopped = false;
148     QRegExp regWord(word);
149     regWord.setCaseSensitivity(Qt::CaseInsensitive);
150     regWord.setPatternSyntax(QRegExp::Wildcard);
151     if(!dictionaryFile.open(QFile::ReadOnly | QFile::Text)) {
152         qDebug()<<"Error: could not open file";
153         Q_EMIT notify(Notify::Warning,
154                 QString("Xdxf file cannot be read for %1").arg(name()));
155         return translations.toList();
156     }
157
158     QXmlStreamReader reader(&dictionaryFile);
159     /*search words list*/
160     QString a;
161
162     int i=0;
163     while(!reader.atEnd() && !stopped){
164         reader.readNextStartElement();
165         if(reader.name()=="ar") {
166             while(reader.name()!="k" && !reader.atEnd())
167                 reader.readNextStartElement();
168             if(!reader.atEnd())
169                 a = reader.readElementText();
170             if((regWord.exactMatch(a) || regWord.exactMatch(removeAccents(a))) &&
171                     (i<limit || limit==0)) {
172                 bool ok=true;
173                 Translation *tran;
174                 foreach(tran,translations) {
175                     if(tran->key().toLower()==a.toLower())
176                         ok=false;  /*if key word is in the dictionary more that one */
177                 }
178                 if(ok) {  /*add key word to list*/
179                     translations<<(new TranslationXdxf(a.toLower(),
180                                 _infoNote,this));
181                     i++;
182                 }
183                 if(i>=limit && limit!=0)
184                     break;
185             }
186         }
187         this->thread()->yieldCurrentThread();
188     }
189     stopped=false;
190     dictionaryFile.close();
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     if(settings)
356     {
357         QString oldPath = _settings->value("path");
358         if(oldPath != settings->value("path")) {
359             setPath(settings->value("path"));
360         }
361
362        foreach(QString key, settings->keys())
363            if(key != "generateCache")
364                _settings->setValue(key, settings->value(key));
365
366         if((_settings->value("cached") == "false" ||
367                 _settings->value("cached").isEmpty()) &&
368                 settings->value("generateCache") == "true") {
369             makeCache("");
370         }
371         else if (settings->value("generateCache") != "true") {
372            _settings->setValue("cached", "false");
373         }
374
375         getDictionaryInfo();
376         delete settings;
377     }
378     Q_EMIT settingsChanged();
379 }
380
381
382
383 void XdxfPlugin::getDictionaryInfo() {
384     QFile dictionaryFile(path);
385     if(!dictionaryFile.open(QFile::ReadOnly | QFile::Text)) {
386        Q_EMIT notify(Notify::Warning,
387                QString("Xdxf file cannot be read dictionary"));
388         qDebug()<<"Error: could not open file";
389         return;
390     }
391
392     QXmlStreamReader reader(&dictionaryFile);
393     reader.readNextStartElement();
394     if(reader.name()=="xdxf") {
395       if(reader.attributes().hasAttribute("lang_from"))
396         _langFrom = reader.attributes().value("lang_from").toString();
397       if(reader.attributes().hasAttribute("lang_to"))
398         _langTo = reader.attributes().value("lang_to").toString();
399     }
400     reader.readNextStartElement();
401     if(reader.name()=="full_name")
402         _name=reader.readElementText();
403     reader.readNextStartElement();
404     if(reader.name()=="description")
405         _infoNote=reader.readElementText();
406
407     QString format = "png";
408     QString initialPath = QDir::currentPath() + tr("/xdxf.") + format;
409
410     _infoNote="path=\""+initialPath+"\"> \n" + _name + " [" + _langFrom + "-" + _langTo + "] (" + _type + ")";
411     dictionaryFile.close();
412 }
413
414
415
416 QIcon* XdxfPlugin::icon() {
417     return &_icon;
418 }
419
420 int XdxfPlugin::countWords() {
421     if(_wordsCount > 0)
422         return _wordsCount;
423
424     QFile dictionaryFile(path);
425     if(!dictionaryFile.open(QFile::ReadOnly | QFile::Text)) {
426         Q_EMIT notify(Notify::Warning,
427                 QString("Xdxf file cannot be read for %1 dictionary")
428                 .arg(name()));
429         qDebug()<<"Error: could not open file";
430         return -1;
431     }
432
433     dictionaryFile.seek(0);
434
435     long wordsCount = 0;
436
437     QString line;
438     while(!dictionaryFile.atEnd()) {
439         line = dictionaryFile.readLine();
440         if(line.contains("<k>")) {
441             wordsCount++;
442         }
443     }
444     _wordsCount = wordsCount;
445     dictionaryFile.close();
446     return wordsCount;
447 }
448
449 bool XdxfPlugin::makeCache(QString) {
450     cachingDialog->setVisible(true);
451     QCoreApplication::processEvents();
452     stopped = false;
453     QFileInfo dictFileN(_settings->value("path"));
454     QString cachePathN;
455     cachePathN = QDir::homePath() + "/.mdictionary/"
456                  + dictFileN.completeBaseName() + ".cache";
457
458     QFile dictionaryFile(dictFileN.filePath());
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 Q_EXPORT_PLUGIN2(xdxf, XdxfPlugin)