Added isBookmark() to translation and other changes to inform gui about
[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.toLower();
93         word = word.replace("*", "%");
94         word = word.replace("?", "_");
95         word = removeAccents(word);
96         qDebug() << word;
97
98         QSqlQuery cur(db);
99         cur.prepare("select word from dict where word like ? limit ?");
100         cur.addBindValue(word);
101         cur.addBindValue(limit);
102         cur.exec();
103         while(cur.next())
104             translations.insert(new TranslationXdxf(
105                         cur.value(0).toString().toLower(),
106                         _infoNote, this));
107         return translations.toList();
108 }
109
110
111
112 QList<Translation*> XdxfPlugin::searchWordListFile(QString word, int limit) {
113     QSet<Translation*> translations;
114     QFile dictionaryFile(path);
115
116     word = word.toLower();
117     word = removeAccents(word);
118
119     stopped = false;
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                     if(tran->key()==a)
144                         ok=false;  /*if key word is in the dictionary more that one */
145                 }
146                 if(ok)  /*add key word to list*/
147                     translations<<(new TranslationXdxf(a.toLower(),
148                                 _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     if(isCached())
164         return searchCache(key);
165     return searchFile(key);
166 }
167
168
169
170 QString XdxfPlugin::searchCache(QString key) {
171     QString result;
172     QString cacheFilePath = _settings->value("cache_path");
173     db.setDatabaseName(cacheFilePath);
174     key = key.toLower();
175
176     if(!db.open()) {
177         qDebug() << "Database error" << db.lastError().text() << endl;
178         return searchFile(key);
179     }
180
181     QSqlQuery cur(db);
182     cur.prepare("select translation from dict where word like ? limit 1");
183     cur.addBindValue(key);
184     cur.exec();
185     if(cur.next())
186         result = cur.value(0).toString();
187     return result;
188
189 }
190
191
192
193
194 QString XdxfPlugin::searchFile(QString key) {
195     key = key.toLower();
196     QFile dictionaryFile(path);
197     QString resultString("");
198     if(!dictionaryFile.open(QFile::ReadOnly | QFile::Text)) {
199         qDebug()<<"Error: could not open file";
200         return "";
201     }
202     QXmlStreamReader dictionaryReader(&dictionaryFile);
203
204
205     QString a;
206
207     bool match =false;
208     stopped = false;
209     while (!dictionaryReader.atEnd()&& !stopped) {
210         dictionaryReader.readNext();
211         if(dictionaryReader.tokenType() == QXmlStreamReader::StartElement) {
212             if(dictionaryReader.name()=="k") {
213                 a = dictionaryReader.readElementText();
214                 if(a==key)
215                     match = true;
216             }
217         }
218         else if(dictionaryReader.tokenType() == QXmlStreamReader::Characters) {
219             if(match) {
220                 QString temp(dictionaryReader.text().toString());
221                 temp.replace("\n","");
222                 if(temp == ""){
223                     while(dictionaryReader.name()!="ar"&&
224                                 !dictionaryReader.atEnd()){
225                         dictionaryReader.readNext();
226                         temp+=dictionaryReader.text().toString();
227                     }
228                 }
229                 resultString+=temp.replace("\n","")+"\n";
230                 match=false;
231             }
232         }
233         this->thread()->yieldCurrentThread();
234     }
235     stopped=false;
236     dictionaryFile.close();
237     return resultString;
238 }
239
240 void XdxfPlugin::stop() {
241     stopped=true;
242 }
243
244 DictDialog* XdxfPlugin::dictDialog() {
245      return _dictDialog;
246 }
247
248 void XdxfPlugin::setPath(QString path){
249     this->path=path;
250     _settings->setValue("path",path);
251     //getDictionaryInfo();
252 }
253
254
255 CommonDictInterface* XdxfPlugin::getNew(const Settings *settings) const {
256     XdxfPlugin *plugin = new XdxfPlugin();
257     if(settings){
258         plugin->setPath(settings->value("path"));
259
260         QStringList list = settings->keys();
261         foreach(QString key, list)
262             plugin->settings()->setValue(key, settings->value(key));
263
264
265         plugin->db_name = plugin->_settings->value("type")
266                + plugin->_settings->value("path");
267         plugin->db = QSqlDatabase::addDatabase("QSQLITE", plugin->db_name);
268
269         if(settings->value("cached").isEmpty() &&
270            settings->value("generateCache") == "true") {
271             plugin->makeCache("");
272         }
273     }
274
275     plugin->getDictionaryInfo();
276     return  plugin;
277 }
278
279 bool XdxfPlugin::isAvailable() const {
280     return true;
281 }
282
283 void XdxfPlugin::setHash(uint _hash) {
284     this->_hash=_hash;
285 }
286
287 uint XdxfPlugin::hash() const {
288    return _hash;
289 }
290
291 Settings* XdxfPlugin::settings() {
292     return _settings;
293 }
294
295 bool XdxfPlugin::isCached() {
296     if(_settings->value("cached") == "true")
297         return true;
298     return false;
299 }
300
301 void XdxfPlugin::setSettings(Settings *settings) {
302
303     QString oldPath = _settings->value("path");
304     if(oldPath != settings->value("path")) {
305         setPath(settings->value("path"));
306     }
307
308     if((_settings->value("cached") == "false" ||
309         _settings->value("cached").isEmpty()) &&
310        settings->value("generateCache") == "true") {
311         makeCache("");
312     }
313     else {
314        _settings->setValue("cached", "false");
315     }
316
317     emit settingsChanged();
318 }
319
320
321 void XdxfPlugin::getDictionaryInfo() {
322     QFile dictionaryFile(path);
323     if(!dictionaryFile.open(QFile::ReadOnly | QFile::Text)) {
324         qDebug()<<"Error: could not open file";
325         return;
326     }
327
328     QXmlStreamReader dictionaryReader(&dictionaryFile);
329     dictionaryReader.readNextStartElement();
330     if(dictionaryReader.name()=="xdxf") {
331       if(dictionaryReader.attributes().hasAttribute("lang_from"))
332         _langFrom = dictionaryReader.attributes().value("lang_from").toString();
333       if(dictionaryReader.attributes().hasAttribute("lang_to"))
334         _langTo = dictionaryReader.attributes().value("lang_to").toString();
335     }
336     dictionaryReader.readNextStartElement();
337     if(dictionaryReader.name()=="full_name")
338         _name=dictionaryReader.readElementText();
339     dictionaryReader.readNextStartElement();
340     if(dictionaryReader.name()=="description")
341         _infoNote=dictionaryReader.readElementText();
342
343     dictionaryFile.close();
344 }
345
346 QString XdxfPlugin::removeAccents(QString string) {
347     string = string.replace(QString::fromUtf8("ł"), "l", Qt::CaseInsensitive);
348     QString normalized = string.normalized(QString::NormalizationForm_D);
349     normalized = normalized;
350     for(int i=0; i<normalized.size(); i++) {
351         if( !normalized[i].isLetterOrNumber() &&
352             !normalized[i].isSpace() &&
353             !normalized[i].isDigit() &&
354             normalized[i] != '*' &&
355             normalized[i] != '%' &&
356             normalized[i] != '_' &&
357             normalized[i] != '?' ) {
358             normalized.remove(i,1);
359         }
360     }
361     return normalized;
362 }
363
364 QIcon* XdxfPlugin::icon() {
365     return &_icon;
366 }
367
368 int XdxfPlugin::countWords() {
369     if(_wordsCount > 0)
370         return _wordsCount;
371
372     QFile dictionaryFile(path);
373     if(!dictionaryFile.open(QFile::ReadOnly | QFile::Text)) {
374         qDebug()<<"Error: could not open file";
375         return -1;
376     }
377
378     dictionaryFile.seek(0);
379
380     long wordsCount = 0;
381
382     QString line;
383     while(!dictionaryFile.atEnd()) {
384         line = dictionaryFile.readLine();
385         if(line.contains("<k>")) {
386             wordsCount++;
387         }
388     }
389     _wordsCount = wordsCount;
390     dictionaryFile.close();
391     return wordsCount;
392 }
393
394
395
396 bool XdxfPlugin::makeCache(QString dir) {
397     cachingDialog->setVisible(true);
398     QCoreApplication::processEvents();
399     stopped = false;
400     QFileInfo dictFileN(_settings->value("path"));
401     QString cachePathN;
402     cachePathN = QDir::homePath() + "/.mdictionary/"
403                  + dictFileN.completeBaseName() + ".cache";
404
405     QFile dictionaryFile(dictFileN.filePath());
406
407
408     if (!dictionaryFile.open(QFile::ReadOnly | QFile::Text)) {
409         return 0;
410     }
411
412     QXmlStreamReader reader(&dictionaryFile);
413
414     db.setDatabaseName(cachePathN);
415     if(!db.open()) {
416         qDebug() << "Database error" << db.lastError().text() << endl;
417         return false;
418     }
419     QCoreApplication::processEvents();
420     QSqlQuery cur(db);
421     cur.exec("PRAGMA synchronous = 0");
422     cur.exec("drop table dict");
423     QCoreApplication::processEvents();
424     cur.exec("create table dict(word text ,translation text)");
425     int counter = 0;
426     cur.exec("BEGIN;");
427
428     QString a;
429     bool match = false;
430     QTime timer;
431     timer.start();
432     countWords();
433
434     int lastProg = -1;
435
436
437     counter=0;
438     while (!reader.atEnd() && !stopped) {
439
440         QCoreApplication::processEvents();
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)