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