ad8887c91046875c84f58f2edc7fddd14729d03d
[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 dictionaryReader(&dictionaryFile);
126     /*search words list*/
127     QString a;
128     int i=0;
129     while(!dictionaryReader.atEnd() && !stopped){
130         dictionaryReader.readNextStartElement();
131         if(dictionaryReader.name()=="ar"){
132             while(dictionaryReader.name()!="k" && !dictionaryReader.atEnd())
133                 dictionaryReader.readNextStartElement();
134             if(!dictionaryReader.atEnd())
135                 a = dictionaryReader.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 dictionaryReader(&dictionaryFile);
198
199
200     QString a;
201
202     bool match =false;
203     stopped = false;
204     while (!dictionaryReader.atEnd()&& !stopped) {
205         dictionaryReader.readNext();
206         if(dictionaryReader.tokenType() == QXmlStreamReader::StartElement) {
207             if(dictionaryReader.name()=="k") {
208                 a = dictionaryReader.readElementText();
209                 if(a==key)
210                     match = true;
211             }
212         }
213         else if(dictionaryReader.tokenType() == QXmlStreamReader::Characters) {
214             if(match) {
215  /*             QString temp(dictionaryReader.text().toString());
216                 if(temp=="\n")
217                     temp=dictionaryReader.readElementText();
218                 temp.replace("\n","");
219                 if(temp == ""){
220                     int i=0;
221                     while(dictionaryReader.name()!="ar"&&
222                                 !dictionaryReader.atEnd()){
223                         dictionaryReader.readNext();
224                         if(dictionaryReader.name()!="" &&
225                                          dictionaryReader.name()!="ar") {
226                             if(dictionaryReader.tokenType()==QXmlStreamReader::EndElement)
227                                 temp+=tr("</");
228                             if(dictionaryReader.tokenType()==QXmlStreamReader::StartElement)
229                                 temp+=tr("<");
230                             qDebug()<<dictionaryReader.tokenType();
231                             temp=temp+dictionaryReader.name().toString() + tr(">");
232                             i++;
233                         }
234                         temp+=dictionaryReader.text().toString();
235                     }
236                 }
237                 resultString+=temp.replace("\n","")+"\n";
238                 match=false;
239 */
240                 QString temp("");
241                 while(dictionaryReader.name()!="ar" && !dictionaryReader.atEnd()) {
242                     if(dictionaryReader.name()!="") {
243                         if(dictionaryReader.tokenType()==QXmlStreamReader::EndElement)
244                             temp+=tr("</");
245                         if(dictionaryReader.tokenType()==QXmlStreamReader::StartElement)
246                             temp+=tr("<");
247                         temp=temp+dictionaryReader.name().toString() + tr(">");
248                     }
249                     temp+= dictionaryReader.text().toString();
250                     dictionaryReader.readNext();
251                 }
252                 resultString+=tr("<t>") + temp.replace("\n","") + tr("</t>");
253                 match=false;
254             }
255         }
256         this->thread()->yieldCurrentThread();
257     }
258     stopped=false;
259     dictionaryFile.close();
260     return resultString;
261 }
262
263 void XdxfPlugin::stop() {
264     stopped=true;
265 }
266
267 DictDialog* XdxfPlugin::dictDialog() {
268      return _dictDialog;
269 }
270
271 void XdxfPlugin::setPath(QString path){
272     this->path=path;
273     _settings->setValue("path",path);
274     //getDictionaryInfo();
275 }
276
277
278 CommonDictInterface* XdxfPlugin::getNew(const Settings *settings) const {
279     XdxfPlugin *plugin = new XdxfPlugin();
280     if(settings){
281         plugin->setPath(settings->value("path"));
282
283         QStringList list = settings->keys();
284         foreach(QString key, list)
285             plugin->settings()->setValue(key, settings->value(key));
286
287
288         plugin->db_name = plugin->_settings->value("type")
289                + plugin->_settings->value("path");
290         plugin->db = QSqlDatabase::addDatabase("QSQLITE", plugin->db_name);
291
292         if(settings->value("cached").isEmpty() &&
293            settings->value("generateCache") == "true") {
294             plugin->makeCache("");
295         }
296     }
297
298     plugin->getDictionaryInfo();
299     return  plugin;
300 }
301
302 bool XdxfPlugin::isAvailable() const {
303     return true;
304 }
305
306 void XdxfPlugin::setHash(uint _hash)
307 {
308     this->_hash=_hash;
309 }
310
311 uint XdxfPlugin::hash() const
312 {
313    return _hash;
314 }
315
316 Settings* XdxfPlugin::settings() {
317     return _settings;
318 }
319
320 bool XdxfPlugin::isCached()
321 {
322     if(_settings->value("cached") == "true")
323         return true;
324     return false;
325 }
326
327 void XdxfPlugin::setSettings(Settings *settings) {
328
329     QString oldPath = _settings->value("path");
330     if(oldPath != settings->value("path")) {
331         setPath(settings->value("path"));
332     }
333
334     if((_settings->value("cached") == "false" ||
335         _settings->value("cached").isEmpty()) &&
336        settings->value("generateCache") == "true") {
337         makeCache("");
338     }
339     else {
340        _settings->setValue("cached", "false");
341     }
342
343     emit settingsChanged();
344 }
345
346
347 void XdxfPlugin::getDictionaryInfo() {
348     QFile dictionaryFile(path);
349     if(!dictionaryFile.open(QFile::ReadOnly | QFile::Text)) {
350         qDebug()<<"Error: could not open file";
351         return;
352     }
353
354     QXmlStreamReader dictionaryReader(&dictionaryFile);
355     dictionaryReader.readNextStartElement();
356     if(dictionaryReader.name()=="xdxf") {
357       if(dictionaryReader.attributes().hasAttribute("lang_from"))
358         _langFrom = dictionaryReader.attributes().value("lang_from").toString();
359       if(dictionaryReader.attributes().hasAttribute("lang_to"))
360         _langTo = dictionaryReader.attributes().value("lang_to").toString();
361     }
362     dictionaryReader.readNextStartElement();
363     if(dictionaryReader.name()=="full_name")
364         _name=dictionaryReader.readElementText();
365     dictionaryReader.readNextStartElement();
366     if(dictionaryReader.name()=="description")
367         _infoNote=dictionaryReader.readElementText();
368
369     dictionaryFile.close();
370 }
371
372 QString XdxfPlugin::removeAccents(QString string) {
373
374     string = string.replace(QString::fromUtf8("ł"), "l", Qt::CaseInsensitive);
375     QString normalized = string.normalized(QString::NormalizationForm_D);
376     normalized = normalized;
377     for(int i=0; i<normalized.size(); i++) {
378         if( !normalized[i].isLetterOrNumber() &&
379             !normalized[i].isSpace() &&
380             !normalized[i].isDigit() &&
381             normalized[i] != '*' &&
382             normalized[i] != '%' &&
383             normalized[i] != '_' &&
384             normalized[i] != '?' ) {
385             normalized.remove(i,1);
386         }
387     }
388     return normalized;
389 }
390
391 QIcon* XdxfPlugin::icon() {
392     return &_icon;
393 }
394
395 int XdxfPlugin::countWords() {
396     if(_wordsCount > 0)
397         return _wordsCount;
398
399     QFile dictionaryFile(path);
400     if(!dictionaryFile.open(QFile::ReadOnly | QFile::Text)) {
401         qDebug()<<"Error: could not open file";
402         return -1;
403     }
404
405     dictionaryFile.seek(0);
406
407     long wordsCount = 0;
408
409     QString line;
410     while(!dictionaryFile.atEnd()) {
411         line = dictionaryFile.readLine();
412         if(line.contains("<k>")) {
413             wordsCount++;
414         }
415     }
416     _wordsCount = wordsCount;
417     dictionaryFile.close();
418     return wordsCount;
419 }
420
421
422
423 bool XdxfPlugin::makeCache(QString dir) {
424     cachingDialog->setVisible(true);
425     QCoreApplication::processEvents();
426     stopped = false;
427     QFileInfo dictFileN(_settings->value("path"));
428     QString cachePathN;
429     cachePathN = QDir::homePath() + "/.mdictionary/"
430                  + dictFileN.completeBaseName() + ".cache";
431
432     QFile dictionaryFile(dictFileN.filePath());
433
434
435     if (!dictionaryFile.open(QFile::ReadOnly | QFile::Text)) {
436         return 0;
437     }
438
439     QXmlStreamReader reader(&dictionaryFile);
440
441
442     db.setDatabaseName(cachePathN);
443     if(!db.open()) {
444         qDebug() << "Database error" << endl;
445         return false;
446     }
447     QCoreApplication::processEvents();
448     QSqlQuery cur(db);
449     cur.exec("PRAGMA synchronous = 0");
450     cur.exec("drop table dict");
451     QCoreApplication::processEvents();
452     cur.exec("create table dict(word text ,translation text)");
453     int counter = 0;
454     cur.exec("BEGIN;");
455
456     QString a;
457     bool match = false;
458     QTime timer;
459     timer.start();
460     countWords();
461
462     int lastProg = -1;
463
464
465     counter=0;
466     while (!reader.atEnd() && !stopped) {
467
468         QCoreApplication::processEvents();
469        // usleep(50);
470         reader.readNext();
471
472         if(reader.tokenType() == QXmlStreamReader::StartElement) {
473             if(reader.name()=="k"){
474                 a = reader.readElementText();
475                 match = true;
476             }
477         }
478         else if(reader.tokenType() == QXmlStreamReader::Characters) {
479              if(match) {
480                 QString temp("");
481                 while(reader.name()!="ar" && !reader.atEnd()) {
482                     if(reader.name()!="") {
483                         if(reader.tokenType()==QXmlStreamReader::EndElement)
484                             temp+=tr("</");
485                         if(reader.tokenType()==QXmlStreamReader::StartElement)
486                             temp+=tr("<");
487                         temp=temp+reader.name().toString() + tr(">");
488                     }
489                     temp+= reader.text().toString();
490                     reader.readNext();
491                 }
492                 temp=tr("<t>") + temp.replace("\n","") + tr("</t>");
493                 match = false;
494                 cur.prepare("insert into dict values(?,?)");
495                 cur.addBindValue(a);
496                 cur.addBindValue(temp);
497                 cur.exec();
498                 counter++;
499                 int prog = counter*100/_wordsCount;
500                 if(prog % 5 == 0 && lastProg != prog) {
501                     Q_EMIT updateCachingProgress(prog,
502                                                  timer.restart());
503                     lastProg = prog;
504                 }
505             }
506
507         }
508     }
509
510     cur.exec("END;");
511     cur.exec("select count(*) from dict");
512
513     countWords();
514     cachingDialog->setVisible(false);
515
516     if(!cur.next() || countWords() != cur.value(0).toInt())
517         return false;
518     _settings->setValue("cache_path", cachePathN);
519     _settings->setValue("cached", "true");
520
521     return true;
522 }
523
524
525 Q_EXPORT_PLUGIN2(xdxf, XdxfPlugin)