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