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