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