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