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