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