clear and add "tr"
[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     _settings->setValue("type","xdxf");
45
46     stopped = false;
47
48     _icon = QIcon(":/icons/xdxf.png");
49     initAccents();
50 }
51
52
53 XdxfPlugin::~XdxfPlugin() {
54     delete _settings;
55     delete cachingDialog;
56 }
57
58 QString XdxfPlugin::langFrom() const {   
59     return _langFrom;
60 }
61
62 QString XdxfPlugin::langTo() const {
63     return  _langTo;
64 }
65
66 QString XdxfPlugin::name() const {
67     return  _name;
68 }
69
70 QString XdxfPlugin::type() const {
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
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(tr("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     QSet<Translation*> translations;
140     QFile dictionaryFile(path);
141
142     word = word.toLower();
143     //word = removeAccents(word);
144
145     stopped = false;
146     QRegExp regWord(word);
147     regWord.setCaseSensitivity(Qt::CaseInsensitive);
148     regWord.setPatternSyntax(QRegExp::Wildcard);
149     if(!dictionaryFile.open(QFile::ReadOnly | QFile::Text)) {
150         qDebug()<<"Error: could not open file";
151         Q_EMIT notify(Notify::Warning,
152                 QString(tr("Xdxf file cannot be read for %1").arg(name())));
153         return translations.toList();
154     }
155
156     QXmlStreamReader reader(&dictionaryFile);
157     /*search words list*/
158     QString a;
159     int i=0;
160     while(!reader.atEnd() && !stopped){
161         reader.readNextStartElement();
162         if(reader.name()=="ar") {
163             while(reader.name()!="k" && !reader.atEnd())
164                 reader.readNextStartElement();
165             if(!reader.atEnd())
166                 a = reader.readElementText();
167             if((regWord.exactMatch(a) || regWord.exactMatch(removeAccents(a))) &&
168                     (i<limit || limit==0)) {
169                 bool ok=true;
170                 Translation *tran;
171                 foreach(tran,translations) {
172                     if(tran->key().toLower()==a.toLower())
173                         ok=false;  /*if key word is in the dictionary more that one */
174                 }
175                 if(ok) {  /*add key word to list*/
176                     translations<<(new TranslationXdxf(a.toLower(),
177                                 _infoNote,this));
178                     i++;
179                 }
180                 if(i>=limit && limit!=0)
181                     break;
182             }
183         }
184         this->thread()->yieldCurrentThread();
185     }
186     stopped=false;
187     dictionaryFile.close();
188     return translations.toList();
189 }
190
191 QString XdxfPlugin::search(QString key) {
192 //    if(_settings->value("cached") == "true")
193     if(isCached())
194         return searchCache(key);
195     return searchFile(key);
196 }
197
198 QString XdxfPlugin::searchCache(QString key) {
199     QString result("");
200     QString cacheFilePath = _settings->value("cache_path");
201     db.setDatabaseName(cacheFilePath);
202     key = key.toLower();
203
204     if(!db.open()) {
205         qDebug() << "Database error" << db.lastError().text() << endl;
206         Q_EMIT notify(Notify::Warning, QString(tr("Cache database cannot be "
207                 "opened for %1 dictionary. Searching in xdxf file. "
208                 "You may want to recache.").arg(name())));
209         return searchFile(key);
210     }
211
212     QSqlQuery cur(db);
213     cur.prepare("select translation from dict where word like ?");
214     cur.addBindValue(key);
215     cur.exec();
216     while(cur.next())
217         result += cur.value(0).toString();
218
219     db.close();
220
221     return result;
222
223 }
224
225 QString XdxfPlugin::searchFile(QString key) {
226     key = key.toLower();
227     QFile dictionaryFile(path);
228     QString resultString("");
229     if(!dictionaryFile.open(QFile::ReadOnly | QFile::Text)) {
230         Q_EMIT notify(Notify::Warning,
231                 QString(tr("Xdxf file cannot be read for %1").arg(name())));
232         qDebug()<<"Error: could not open file";
233         return "";
234     }
235     QXmlStreamReader reader(&dictionaryFile);
236     QString a;
237
238     bool match =false;
239     stopped = false;
240     while (!reader.atEnd()&& !stopped) {
241         reader.readNext();
242         if(reader.tokenType() == QXmlStreamReader::StartElement) {
243             if(reader.name()=="k") {
244                 a = reader.readElementText();
245                 if(a.toLower()==key.toLower())
246                     match = true;
247             }
248         }
249         if(match) {
250             QString temp("");
251             while(reader.name()!="ar" && !reader.atEnd()) {
252                 if(reader.name()!="" && reader.name()!="k") {
253                     if(reader.tokenType()==QXmlStreamReader::EndElement)
254                         temp+="</";
255                     if(reader.tokenType()==QXmlStreamReader::StartElement)
256                         temp+="<";
257                     temp+=reader.name().toString();
258                     if(reader.name().toString()=="c" &&
259                             reader.tokenType()==QXmlStreamReader::StartElement)
260                        temp= temp + " c=\"" + reader.attributes().
261                                value("c").toString() + "\"";
262                     temp+=">";
263                 }
264                 temp+= reader.text().toString().replace("<","&lt;").
265                         replace(">","&gt;");
266                 reader.readNext();
267             }
268             if(temp.at(0)==QChar('\n'))
269                 temp.remove(0,1);
270             resultString+="<key>" + a +"</key>";
271             resultString+="<t>" + temp + "</t>";
272             match=false;
273         }
274         this->thread()->yieldCurrentThread();
275     }
276     stopped=false;
277     dictionaryFile.close();
278
279     return resultString;
280 }
281
282 void XdxfPlugin::stop() {
283     stopped=true;
284 }
285
286 DictDialog* XdxfPlugin::dictDialog() {
287      return _dictDialog;
288 }
289
290 void XdxfPlugin::setPath(QString path){
291     if(this->path!=path && this->path!="" && _settings->value("cache_path")!="");
292         clean();
293     this->path=path;
294     _settings->setValue("path",path);
295     //getDictionaryInfo();
296 }
297
298 CommonDictInterface* XdxfPlugin::getNew(const Settings *settings) const {
299     XdxfPlugin *plugin = new XdxfPlugin();
300     if(settings){
301         plugin->setPath(settings->value("path"));
302         QStringList list = settings->keys();
303
304         plugin->db_name = plugin->_settings->value("type")
305                          + plugin->_settings->value("path");
306         plugin->db = QSqlDatabase::addDatabase("QSQLITE", plugin->db_name);
307
308         if(settings->value("cached").isEmpty() &&
309            settings->value("generateCache") == "true") {
310             plugin->makeCache("");
311         }
312         foreach(QString key, list)
313            if(key != "generateCache")
314                 plugin->settings()->setValue(key, settings->value(key));
315         delete settings;
316     }
317     plugin->getDictionaryInfo();
318     return  plugin;
319 }
320
321 bool XdxfPlugin::isAvailable() const {
322     return true;
323 }
324
325
326
327 void XdxfPlugin::setHash(uint _hash) {
328     this->_hash=_hash;
329 }
330
331
332
333 uint XdxfPlugin::hash() const {
334    return _hash;
335 }
336
337
338
339 Settings* XdxfPlugin::settings() {
340     return _settings;
341 }
342
343
344
345 bool XdxfPlugin::isCached() {
346     if(_settings->value("cached") == "true")
347         return true;
348     return false;
349 }
350
351
352
353 void XdxfPlugin::setSettings(Settings *settings) {
354     if(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         getDictionaryInfo();
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(tr("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() + "/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(tr("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) {
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     if (!dictionaryFile.open(QFile::ReadOnly | QFile::Text)) {
460         Q_EMIT updateCachingProgress(100, 0);
461         Q_EMIT notify(Notify::Warning,
462                 QString(tr("Xdxf file cannot be read for %1 dictionary")
463                 .arg(name())));
464         return 0;
465     }
466     QXmlStreamReader reader(&dictionaryFile);
467
468
469     db.setDatabaseName(cachePathN);
470     if(!db.open()) {
471         qDebug() << "Database error" << db.lastError().text() << endl;
472         Q_EMIT updateCachingProgress(100, 0);
473         Q_EMIT notify(Notify::Warning, QString(tr("Cache database cannot be "
474                 "opened for %1 dictionary. Searching in xdxf file. "
475                 "You may want to recache.").arg(name())));
476         return false;
477     }
478     QCoreApplication::processEvents();
479     QSqlQuery cur(db);
480     cur.exec("PRAGMA synchronous = 0");
481     cur.exec("drop table dict");
482     QCoreApplication::processEvents();
483     cur.exec("create table dict(word text, normalized text ,tanslation text)");
484     int counter = 0;
485     cur.exec("BEGIN;");
486
487     QString a;
488     bool match = false;
489     QTime timer;
490     timer.start();
491     countWords();
492
493     int lastProg = -1;
494
495     QString stripAcc = settings()->value("strip_accents");
496     settings()->setValue("strip_accents", "true");
497
498
499     counter=0;
500     while (!reader.atEnd() && !stopped) {
501
502         QCoreApplication::processEvents();
503         reader.readNext();
504
505         if(reader.tokenType() == QXmlStreamReader::StartElement) {
506             if(reader.name()=="k"){
507                 a = reader.readElementText();
508                 match = true;
509             }
510         }
511         if(match) {
512             QString temp("");
513             while(reader.name()!="ar" && !reader.atEnd()) {
514                 if(reader.name()!="" && reader.name()!="k") {
515                     if(reader.tokenType()==QXmlStreamReader::EndElement)
516                         temp+="</";
517                     if(reader.tokenType()==QXmlStreamReader::StartElement)
518                         temp+="<";
519                     temp+=reader.name().toString();
520                     if(reader.name().toString()=="c" && reader.tokenType()==QXmlStreamReader::StartElement)
521                        temp= temp + " c=\"" + reader.attributes().value("c").toString() + "\"";
522                     temp+=">";
523                 }
524                 temp+= reader.text().toString().replace("<","&lt;").replace(">","&gt;");;
525                 reader.readNext();
526             }
527             if(temp.at(0)==QChar('\n'))
528                 temp.remove(0,1);
529             temp="<key>" + a + "</key>" + "<t>" + temp+ "</t>";
530             match=false;
531             cur.prepare("insert into dict values(?,?,?)");
532             cur.addBindValue(a);
533             cur.addBindValue(removeAccents(a));
534             cur.addBindValue(temp);
535             cur.exec();
536             counter++;
537             int prog = counter*100/_wordsCount;
538             if(prog % 5 == 0 && lastProg != prog) {
539                 Q_EMIT updateCachingProgress(prog,
540                                              timer.restart());
541                 lastProg = prog;
542             }
543         }
544     }
545
546     cur.exec("END;");
547     cur.exec("select count(*) from dict");
548     settings()->setValue("strip_accents", stripAcc);
549
550     countWords();
551     cachingDialog->setVisible(false);
552
553     if(!cur.next() || countWords() != cur.value(0).toInt())
554     {
555         Q_EMIT updateCachingProgress(100, timer.restart());
556         Q_EMIT notify(Notify::Warning,
557                 QString(tr("Database caching error, please try againg.")));
558         db.close();
559         return false;
560     }
561     _settings->setValue("cache_path", cachePathN);
562     _settings->setValue("cached", "true");
563
564
565     db.close();
566     return true;
567 }
568
569
570
571 void XdxfPlugin::clean() {
572     if(settings()->value("cached") == "true")
573         QFile(settings()->value("cache_path")).remove();
574 }
575
576 Q_EXPORT_PLUGIN2(xdxf, XdxfPlugin)