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