Fixed bug in load plugin dialog
[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
305     emit settingsChanged();
306 }
307
308
309 void XdxfPlugin::getDictionaryInfo() {
310     QFile dictionaryFile(path);
311     if(!dictionaryFile.open(QFile::ReadOnly | QFile::Text)) {
312         qDebug()<<"Error: could not open file";
313         return;
314     }
315
316     QXmlStreamReader dictionaryReader(&dictionaryFile);
317     dictionaryReader.readNextStartElement();
318     if(dictionaryReader.name()=="xdxf") {
319       if(dictionaryReader.attributes().hasAttribute("lang_from"))
320         _langFrom = dictionaryReader.attributes().value("lang_from").toString();
321       if(dictionaryReader.attributes().hasAttribute("lang_to"))
322         _langTo = dictionaryReader.attributes().value("lang_to").toString();
323     }
324     dictionaryReader.readNextStartElement();
325     if(dictionaryReader.name()=="full_name")
326         _name=dictionaryReader.readElementText();
327     dictionaryReader.readNextStartElement();
328     if(dictionaryReader.name()=="description")
329         _infoNote=dictionaryReader.readElementText();
330
331     dictionaryFile.close();
332 }
333
334 QString XdxfPlugin::removeAccents(QString string) {
335
336     string = string.replace(QString::fromUtf8("ł"), "l", Qt::CaseInsensitive);
337     QString normalized = string.normalized(QString::NormalizationForm_D);
338     normalized = normalized;
339     for(int i=0; i<normalized.size(); i++) {
340         if( !normalized[i].isLetterOrNumber() &&
341             !normalized[i].isSpace() &&
342             !normalized[i].isDigit() &&
343             normalized[i] != '*' &&
344             normalized[i] != '%') {
345             normalized.remove(i,1);
346         }
347     }
348     return normalized;
349 }
350
351 QIcon* XdxfPlugin::icon() {
352     return &_icon;
353 }
354
355 int XdxfPlugin::countWords() {
356     if(_wordsCount > 0)
357         return _wordsCount;
358
359     QFile dictionaryFile(path);
360     if(!dictionaryFile.open(QFile::ReadOnly | QFile::Text)) {
361         qDebug()<<"Error: could not open file";
362         return -1;
363     }
364
365     dictionaryFile.seek(0);
366
367     long wordsCount = 0;
368
369     QString line;
370     while(!dictionaryFile.atEnd()) {
371         line = dictionaryFile.readLine();
372         if(line.contains("<k>")) {
373             wordsCount++;
374         }
375     }
376     _wordsCount = wordsCount;
377     dictionaryFile.close();
378     return wordsCount;
379 }
380
381
382
383 bool XdxfPlugin::makeCache(QString dir) {
384     cachingDialog->setVisible(true);
385     QCoreApplication::processEvents();
386     stopped = false;
387     QFileInfo dictFileN(_settings->value("path"));
388     QString cachePathN;
389     cachePathN = QDir::homePath() + "/.mdictionary/"
390                  + dictFileN.completeBaseName() + ".cache";
391
392     QFile dictionaryFile(dictFileN.filePath());
393
394
395     if (!dictionaryFile.open(QFile::ReadOnly | QFile::Text)) {
396         return 0;
397     }
398
399     QXmlStreamReader reader(&dictionaryFile);
400
401
402     db.setDatabaseName(cachePathN);
403     if(!db.open()) {
404         qDebug() << "Database error" << endl;
405         return false;
406     }
407     QCoreApplication::processEvents();
408     QSqlQuery cur(db);
409     cur.exec("PRAGMA synchronous = 0");
410     cur.exec("drop table dict");
411     QCoreApplication::processEvents();
412     cur.exec("create table dict(word text ,translation text)");
413     int counter = 0;
414     cur.exec("BEGIN;");
415
416     QString a;
417     bool match = false;
418     QTime timer;
419     timer.start();
420     countWords();
421
422
423     counter=0;
424     while (!reader.atEnd() && !stopped) {
425
426         QCoreApplication::processEvents();
427         //usleep(50);
428         reader.readNext();
429
430         if(reader.tokenType() == QXmlStreamReader::StartElement) {
431             if(reader.name()=="k"){
432                 a = reader.readElementText();
433                 match = true;
434             }
435         }
436         else if(reader.tokenType() == QXmlStreamReader::Characters) {
437              if(match) {
438                 QString temp(reader.text().toString());
439                 temp.replace("\n","");
440                 if(temp == ""){
441                     while(reader.name()!="ar"&&
442                                 !reader.atEnd()){
443                         reader.readNext();
444                         temp+=reader.text().toString();
445                     }
446                 }
447                 match = false;
448                 cur.prepare("insert into dict values(?,?)");
449                 cur.addBindValue(a);
450                 cur.addBindValue(temp);
451                 cur.exec();
452                 counter++;
453                 int prog = counter*100/_wordsCount;
454                 if(prog % 5 == 0)
455                     Q_EMIT updateCachingProgress(prog);
456             }
457
458         }
459     }
460
461     cur.exec("END;");
462     cur.exec("select count(*) from dict");
463
464     countWords();
465     cachingDialog->setVisible(false);
466
467     if(!cur.next() || countWords() != cur.value(0).toInt())
468         return false;
469     _settings->setValue("cache_path", cachePathN);
470     _settings->setValue("cached", "true");
471
472     return true;
473 }
474
475
476 Q_EXPORT_PLUGIN2(xdxf, XdxfPlugin)