Fixed caching time and place
[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     _settings->setValue("type","xdxf");
37
38     stopped = false;
39
40     _icon = QIcon(":/icons/xdxf.png");
41 }
42
43 QString XdxfPlugin::langFrom() const {   
44     return _langFrom;
45 }
46
47 QString XdxfPlugin::langTo() const {
48     return  _langTo;
49 }
50
51 QString XdxfPlugin::name() const {
52     return  _name;
53 }
54
55 QString XdxfPlugin::type() const {
56 //    return _settings->value("type");
57     return _type;
58 }
59
60 QString XdxfPlugin::infoNote() const {
61     return  _infoNote;
62 }
63
64 QList<Translation*> XdxfPlugin::searchWordList(QString word, int limit) {
65     if(_settings->value("cached") == "true")
66         return searchWordListCache(word,limit);
67     return searchWordListFile(word, limit);
68 }
69
70 QList<Translation*> XdxfPlugin::searchWordListCache(QString word, int limit) {
71
72     qDebug() << "search cache";
73     QSet<Translation*> translations;
74     QString cacheFilePath = _settings->value("cache_path");
75         db.setDatabaseName(cacheFilePath);
76         if(!db.open()) {
77             qDebug() << "Database error" << db.lastError().text() << endl;
78             return searchWordListFile(word, limit);
79         }
80
81         stopped = false;
82         if(word.indexOf("*")==-1)
83             word+="%";
84         qDebug() << word;
85         word = word.replace("*", "%");
86         qDebug() << word;
87         word = removeAccents(word);
88         qDebug() << word;
89
90         QSqlQuery cur(db);
91         cur.prepare("select word from dict where word like ? limit ?");
92         cur.addBindValue(word);
93         cur.addBindValue(limit);
94         cur.exec();
95         while(cur.next())
96             translations.insert(new TranslationXdxf(cur.value(0).toString(),
97                                                     _infoNote, this));
98         return translations.toList();
99 }
100
101
102
103 QList<Translation*> XdxfPlugin::searchWordListFile(QString word, int limit) {
104     qDebug() << "search file";
105     QSet<Translation*> translations;
106     QFile dictionaryFile(path);
107
108     word = removeAccents(word);
109
110     stopped = false;
111     if(word.indexOf("*")==-1)
112         word+="*";
113     QRegExp regWord(word);
114     regWord.setCaseSensitivity(Qt::CaseInsensitive);
115     regWord.setPatternSyntax(QRegExp::Wildcard);
116     if(!dictionaryFile.open(QFile::ReadOnly | QFile::Text)) {
117         qDebug()<<"Error: could not open file";
118         return translations.toList();
119     }
120
121     QXmlStreamReader dictionaryReader(&dictionaryFile);
122     /*search words list*/
123     QString a;
124     int i=0;
125     while(!dictionaryReader.atEnd() && !stopped){
126         dictionaryReader.readNextStartElement();
127         if(dictionaryReader.name()=="ar"){
128             while(dictionaryReader.name()!="k" && !dictionaryReader.atEnd())
129                 dictionaryReader.readNextStartElement();
130             if(!dictionaryReader.atEnd())
131                 a = dictionaryReader.readElementText();
132             if(regWord.exactMatch(removeAccents(a)) && (i<limit || limit==0)) {
133                 bool ok=true;
134                 Translation *tran;
135                 foreach(tran,translations)
136                 {
137                     if(tran->key()==a)
138                         ok=false;  /*if key word is in the dictionary more that one */
139                 }
140                 if(ok)  /*add key word to list*/
141                     translations<<(new TranslationXdxf(a,_infoNote,this));
142                 i++;
143                 if(i>=limit && limit!=0)
144                     break;
145             }
146         }
147         this->thread()->yieldCurrentThread();
148     }
149     stopped=false;
150     dictionaryFile.close();
151     return translations.toList();
152 }
153
154 QString XdxfPlugin::search(QString key) {
155     if(_settings->value("cached") == "true")
156         return searchCache(key);
157     return searchFile(key);
158 }
159
160
161
162 QString XdxfPlugin::searchCache(QString key) {
163     qDebug() << "search cache";
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         QStringList list = settings->keys();
251         foreach(QString key, list)
252             plugin->settings()->setValue(key, settings->value(key));
253
254         plugin->db_name = plugin->_settings->value("type")
255                + plugin->_settings->value("path");
256         plugin->db = QSqlDatabase::addDatabase("QSQLITE", plugin->db_name);
257     }
258     return  plugin;
259 }
260
261 bool XdxfPlugin::isAvailable() const {
262     return true;
263 }
264
265 void XdxfPlugin::setHash(uint _hash)
266 {
267     this->_hash=_hash;
268 }
269
270 uint XdxfPlugin::hash() const
271 {
272    return _hash;
273 }
274
275 Settings* XdxfPlugin::settings() {
276     return _settings;
277 }
278
279 bool XdxfPlugin::isCached()
280 {
281     return false;
282 }
283
284 void XdxfPlugin::setSettings(Settings *settings) {
285     _settings = settings;
286     setPath(_settings->value("path"));
287     emit settingsChanged();
288 }
289
290
291 void XdxfPlugin::getDictionaryInfo() {
292     QFile dictionaryFile(path);
293     if(!dictionaryFile.open(QFile::ReadOnly | QFile::Text)) {
294         qDebug()<<"Error: could not open file";
295         return;
296     }
297
298     QXmlStreamReader dictionaryReader(&dictionaryFile);
299     dictionaryReader.readNextStartElement();
300     if(dictionaryReader.name()=="xdxf") {
301       if(dictionaryReader.attributes().hasAttribute("lang_from"))
302         _langFrom = dictionaryReader.attributes().value("lang_from").toString();
303       if(dictionaryReader.attributes().hasAttribute("lang_to"))
304         _langTo = dictionaryReader.attributes().value("lang_to").toString();
305     }
306     dictionaryReader.readNextStartElement();
307     if(dictionaryReader.name()=="full_name")
308         _name=dictionaryReader.readElementText();
309     dictionaryReader.readNextStartElement();
310     if(dictionaryReader.name()=="description")
311         _infoNote=dictionaryReader.readElementText();
312
313     dictionaryFile.close();
314 }
315
316 QString XdxfPlugin::removeAccents(QString string) {
317
318     string = string.replace(QString::fromUtf8("ł"), "l", Qt::CaseInsensitive);
319     QString normalized = string.normalized(QString::NormalizationForm_D);
320     normalized = normalized;
321     for(int i=0; i<normalized.size(); i++) {
322         if( !normalized[i].isLetterOrNumber() &&
323             !normalized[i].isSpace() &&
324             !normalized[i].isDigit() &&
325             normalized[i] != '*' &&
326             normalized[i] != '%') {
327             normalized.remove(i,1);
328         }
329     }
330     return normalized;
331 }
332
333 QIcon* XdxfPlugin::icon() {
334     return &_icon;
335 }
336
337 int XdxfPlugin::countWords() {
338     if(_wordsCount > 0)
339         return _wordsCount;
340
341     QFile dictionaryFile(path);
342     if(!dictionaryFile.open(QFile::ReadOnly | QFile::Text)) {
343         qDebug()<<"Error: could not open file";
344         return -1;
345     }
346
347     dictionaryFile.seek(0);
348
349     long wordsCount = 0;
350
351     QString line;
352     while(!dictionaryFile.atEnd()) {
353         line = dictionaryFile.readLine();
354         if(line.contains("<k>")) {
355             wordsCount++;
356         }
357     }
358     _wordsCount = wordsCount;
359     dictionaryFile.close();
360     return wordsCount;
361 }
362
363
364
365 bool XdxfPlugin::makeCache(QString dir) {
366     QFileInfo dictFileN(_settings->value("path"));
367     QString cachePathN;
368     cachePathN = QDir::homePath() + "/.mdictionary/"
369                  + dictFileN.completeBaseName() + ".cache";
370
371     QFile dictionaryFile(dictFileN.filePath());
372
373
374     qDebug() << dictFileN.path();
375     if (!dictionaryFile.open(QFile::ReadOnly | QFile::Text)) {
376         return 0;
377     }
378     qDebug() << "OLE";
379
380     QXmlStreamReader reader(&dictionaryFile);
381
382
383     db.setDatabaseName(cachePathN);
384     if(!db.open()) {
385         qDebug() << "Database error" << endl;
386         return false;
387     }
388     QSqlQuery cur(db);
389     cur.exec("PRAGMA synchronous = 0");
390     cur.exec("drop table dict");
391     cur.exec("create table dict(word text ,translation text)");
392     int counter = 0;
393     cur.exec("BEGIN;");
394
395     QString a;
396     bool match = false;
397     QTime timer;
398     timer.start();
399     countWords();
400
401
402     counter=0;
403     while (!reader.atEnd()) {
404
405         reader.readNext();
406
407         if(reader.tokenType() == QXmlStreamReader::StartElement) {
408             if(reader.name()=="k"){
409                 a = reader.readElementText();
410                 match = true;
411             }
412         }
413         else if(reader.tokenType() == QXmlStreamReader::Characters) {
414              if(match) {
415                 QString temp(reader.text().toString());
416                 temp.replace("\n","");
417                 if(temp == ""){
418                     while(reader.name()!="ar"&&
419                                 !reader.atEnd()){
420                         reader.readNext();
421                         temp+=reader.text().toString();
422                     }
423                 }
424                 match = false;
425                 cur.prepare("insert into dict values(?,?)");
426                 cur.addBindValue(a);
427                 cur.addBindValue(temp);
428                 cur.exec();
429                 counter++;
430                 int prog = counter*100/_wordsCount;
431                 if(prog % 5 == 0)
432                     Q_EMIT update(prog);
433             }
434
435         }
436     }
437
438     qDebug()<<counter;
439     cur.exec("END;");
440     cur.exec("select count(*) from dict");
441     if(!cur.next() || countWords() != cur.value(0).toInt())
442         return false;
443     _settings->setValue("cache_path", cachePathN);
444     _settings->setValue("cached", "true");
445     return true;
446 }
447
448
449 Q_EXPORT_PLUGIN2(xdxf, XdxfPlugin)