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