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