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