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