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