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