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