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