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