1 /*******************************************************************************
3 This file is part of mDictionary.
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.
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.
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/>.
18 Copyright 2010 Comarch S.A.
20 *******************************************************************************/
23 \author Jakub Jaszczynski <j.j.jaszczynski@gmail.com>
26 #include "xdxfplugin.h"
28 #include "../../include/Notify.h"
29 #include "DownloadDict.h"
30 #include "XdxfDictDownloader.h"
32 XdxfDictDownloader XdxfPlugin::dictDownloader;
35 bool XdxfPlugin::dictDownloaderInitialized = false;
38 XdxfPlugin::XdxfPlugin(QObject *parent) : CommonDictInterface(parent),
39 _langFrom(""), _langTo(""),_name(""), _infoNote("") {
40 _settings = new Settings();
41 _dictDialog = new XdxfDictDialog(this, this);
43 connect(_dictDialog, SIGNAL(notify(Notify::NotifyType,QString)),
44 this, SIGNAL(notify(Notify::NotifyType,QString)));
46 if(!dictDownloaderInitialized) {
47 connect(&dictDownloader, SIGNAL(notify(Notify::NotifyType,QString)),
48 this, SIGNAL(notify(Notify::NotifyType,QString)));
49 dictDownloaderInitialized = true;
52 _settings->setValue("type","xdxf");
53 _icon = QIcon("/usr/share/mdictionary/xdxf.png");
61 void XdxfPlugin::retranslate() {
62 QString locale = QLocale::system().name();
63 QTranslator *translator = new QTranslator(this);
65 if(!translator->load(":/xdxf/translations/" + locale)) {
66 translator->load(":/xdxf/translations/en_US");
68 QCoreApplication::installTranslator(translator);
72 XdxfPlugin::~XdxfPlugin() {
78 QString XdxfPlugin::langFrom() const {
83 QString XdxfPlugin::langTo() const {
88 QString XdxfPlugin::name() const {
93 QString XdxfPlugin::type() const {
94 return QString("xdxf");
98 QString XdxfPlugin::infoNote() const {
103 QList<Translation*> XdxfPlugin::searchWordList(QString word, int limit) {
104 if( word.indexOf("*")==-1 && word.indexOf("?")==-1 &&
105 word.indexOf("_")==-1 && word.indexOf("%")==-1)
109 return searchWordListCache(word,limit);
110 return searchWordListFile(word, limit);
114 QList<Translation*> XdxfPlugin::searchWordListCache(QString word, int limit) {
115 QSet<Translation*> translations;
116 QString cacheFilePath = _settings->value("cache_path");
118 db.setDatabaseName(cacheFilePath);
119 if(!QFile::exists(cacheFilePath) || !db.open()) {
120 qDebug() << "Database error" << db.lastError().text() << endl;
121 Q_EMIT notify(Notify::Warning, QString(tr("Cache database cannot be "
122 "opened for %1 dictionary. Searching in XDXF file. "
123 "You may want to recache.").arg(name())));
124 _settings->setValue("cached","false");
125 return searchWordListFile(word, limit);
129 word = word.toLower();
130 word = word.replace("*", "%");
131 word = word.replace("?", "_");
135 cur.prepare("select word from dict where word like ? or normalized "
138 cur.prepare("select word from dict where word like ? or normalized "
140 cur.addBindValue(word);
141 cur.addBindValue(word);
143 cur.addBindValue(limit);
146 while(cur.next() && (translations.size()<limit || limit==0)) {
147 translations.insert(new TranslationXdxf(
148 cur.value(0).toString(),
149 _dictionaryInfo, this));
152 return translations.toList();
156 QList<Translation*> XdxfPlugin::searchWordListFile(QString word, int limit) {
157 QSet<Translation*> translations;
158 QFile dictionaryFile(_settings->value("path"));
159 word = word.toLower();
162 QRegExp regWord(word);
163 regWord.setCaseSensitivity(Qt::CaseInsensitive);
164 regWord.setPatternSyntax(QRegExp::Wildcard);
166 /*check xdxf file exist*/
167 if(!QFile::exists(_settings->value("path"))
168 || !dictionaryFile.open(QFile::ReadOnly | QFile::Text)) {
169 qDebug()<<"Error: could not open file";
170 Q_EMIT notify(Notify::Warning,
171 QString(tr("XDXF file cannot be read for %1").arg(name())));
172 return translations.toList();
175 QXmlStreamReader reader(&dictionaryFile);
179 /*search words list*/
180 while(!reader.atEnd() && !stopped){
181 reader.readNextStartElement();
182 if(reader.name()=="ar") {
183 while(reader.name()!="k" && !reader.atEnd())
184 reader.readNextStartElement();
186 readKey = reader.readElementText();
187 if((regWord.exactMatch(readKey)
188 || regWord.exactMatch(removeAccents(readKey)))
189 && (i<limit || limit==0) && !reader.atEnd()) {
190 translations<<(new TranslationXdxf(readKey.toLower(),
191 _dictionaryInfo,this));
192 if(translations.size()==limit && limit!=0)
196 this->thread()->yieldCurrentThread();
199 dictionaryFile.close();
200 return translations.toList();
204 QString XdxfPlugin::search(QString key) {
206 return searchCache(key);
207 return searchFile(key);
211 QString XdxfPlugin::searchCache(QString key) {
213 QString cacheFilePath = _settings->value("cache_path");
214 db.setDatabaseName(cacheFilePath);
217 if(!QFile::exists(cacheFilePath) || !db.open()) {
218 qDebug() << "Database error" << db.lastError().text() << endl;
219 Q_EMIT notify(Notify::Warning, QString(tr("Cache database cannot be "
220 "opened for %1 dictionary. Searching in XDXF file. "
221 "You may want to recache.").arg(name())));
222 _settings->setValue("cached","false");
223 return searchFile(key);
228 cur.prepare("select translation from dict where word like ?");
229 cur.addBindValue(key);
232 result += cur.value(0).toString();
239 QString XdxfPlugin::searchFile(QString key) {
240 QFile dictionaryFile(_settings->value("path"));
241 QString resultString("");
244 /*check xdxf file exist*/
245 if(!QFile::exists(_settings->value("path"))
246 || !dictionaryFile.open(QFile::ReadOnly | QFile::Text)) {
247 Q_EMIT notify(Notify::Warning,
248 QString(tr("XDXF file cannot be read for %1").arg(name())));
249 qDebug()<<"Error: could not open file";
253 QXmlStreamReader reader(&dictionaryFile);
258 /*search translations for word*/
259 while (!reader.atEnd()&& !stopped) {
261 if(reader.tokenType() == QXmlStreamReader::StartElement) {
262 if(reader.name()=="k") {
263 readKey = reader.readElementText();
264 if(readKey.toLower()==key.toLower())
270 while(reader.name()!="ar" && !reader.atEnd()) {
271 if(reader.name()!="" && reader.name()!="k") {
272 if(reader.tokenType()==QXmlStreamReader::EndElement)
274 if(reader.tokenType()==QXmlStreamReader::StartElement)
276 temp+=reader.name().toString();
277 if(reader.name().toString()=="c" &&
278 reader.tokenType()==QXmlStreamReader::StartElement)
279 temp= temp + " c=\"" + reader.attributes().
280 value("c").toString() + "\"";
283 temp+= reader.text().toString().replace("<","<").
287 if(temp.at(0)==QChar('\n'))
289 resultString+="<key>" + readKey +"</key>";
290 resultString+="<t>" + temp + "</t>";
293 this->thread()->yieldCurrentThread();
296 dictionaryFile.close();
301 void XdxfPlugin::stop() {
306 DictDialog* XdxfPlugin::dictDialog() {
311 CommonDictInterface* XdxfPlugin::getNew(const Settings *settings) const {
312 XdxfPlugin *plugin = new XdxfPlugin();
314 connect(plugin, SIGNAL(notify(Notify::NotifyType,QString)),
315 this, SIGNAL(notify(Notify::NotifyType,QString)));
317 ((XdxfDictDialog*)plugin->dictDialog())->setLastDialogParent(_dictDialog->lastDialogParent());
319 if(settings && plugin->setSettings(settings)) {
320 disconnect(plugin, SIGNAL(notify(Notify::NotifyType,QString)),
321 this, SIGNAL(notify(Notify::NotifyType,QString)));
325 disconnect(plugin, SIGNAL(notify(Notify::NotifyType,QString)),
326 this, SIGNAL(notify(Notify::NotifyType,QString)));
333 bool XdxfPlugin::isAvailable() const {
338 Settings* XdxfPlugin::settings() {
343 bool XdxfPlugin::isCached() {
344 if(_settings->value("cached") == "true")
350 bool XdxfPlugin::setSettings(const Settings *settings) {
352 bool isPathChange=false;
353 QString oldPath = _settings->value("path");
354 Settings *oldSettings = new Settings ;
356 if(oldPath != settings->value("path")) {
357 if(oldPath!="" && _settings->value("cache_path")!="")
362 foreach(QString key, _settings->keys())
363 oldSettings->setValue(key, _settings->value(key));
365 foreach(QString key, settings->keys())
366 if(key != "generateCache")
367 _settings->setValue(key, settings->value(key));
369 if(!getDictionaryInfo()) {
370 Q_EMIT notify(Notify::Warning,
371 QString(tr("XDXF file is in wrong format")));
372 qDebug()<<"Error: xdxf file is in wrong format";
374 _settings=oldSettings;
381 _settings->setValue("cached","false");
382 if(_settings->value("cached")=="true"
383 && _settings->value("cache_path")!="") {
384 db_name = _settings->value("type")
385 + _settings->value("cache_path");
386 db = QSqlDatabase::addDatabase("QSQLITE",db_name);
390 if((_settings->value("cached") == "false" ||
391 _settings->value("cached").isEmpty()) &&
392 settings->value("generateCache") == "true") {
397 else if (settings->value("generateCache") == "false") {
398 _settings->setValue("cached", "false");
403 Q_EMIT settingsChanged();
408 bool XdxfPlugin::getDictionaryInfo() {
409 QFile dictionaryFile(_settings->value("path"));
410 if(!QFile::exists(_settings->value("path"))
411 || !dictionaryFile.open(QFile::ReadOnly | QFile::Text)) {
412 Q_EMIT notify(Notify::Warning,
413 QString(tr("XDXF dictionary cannot be read from file")));
414 qDebug()<<"Error: could not open file";
419 QXmlStreamReader reader(&dictionaryFile);
420 reader.readNextStartElement();
421 if(reader.name()=="xdxf") {
423 if(reader.attributes().hasAttribute("lang_from"))
424 _langFrom = reader.attributes().value("lang_from").toString();
425 if(reader.attributes().hasAttribute("lang_to"))
426 _langTo = reader.attributes().value("lang_to").toString();
428 reader.readNextStartElement();
429 if(reader.name()=="full_name")
430 _name=reader.readElementText();
432 qDebug()<<"no full_name";
433 reader.readNextStartElement();
434 if(reader.name()=="description")
435 _infoNote=reader.readElementText();
437 qDebug()<<"no description";
439 _dictionaryInfo= _name + " [" + _langFrom + "-"
442 dictionaryFile.close();
449 QIcon* XdxfPlugin::icon() {
454 int XdxfPlugin::countWords() {
457 QFile dictionaryFile(_settings->value("path"));
458 if(!QFile::exists(_settings->value("path"))
459 || !dictionaryFile.open(QFile::ReadOnly | QFile::Text)) {
460 Q_EMIT notify(Notify::Warning,
461 QString(tr("XDXF file cannot be read for %1 dictionary")
463 qDebug()<<"Error: could not open file";
467 dictionaryFile.seek(0);
471 while(!dictionaryFile.atEnd()) {
472 line = dictionaryFile.readLine();
473 if(line.contains("<k>")) {
477 _wordsCount = wordsCount;
478 dictionaryFile.close();
483 bool XdxfPlugin::makeCache(QString) {
484 XdxfCachingDialog d(_dictDialog->lastDialogParent());
486 connect(&d, SIGNAL(cancelCaching()),
488 connect(this, SIGNAL(updateCachingProgress(int,int)),
489 &d, SLOT(updateCachingProgress(int,int)));
492 QCoreApplication::processEvents();
493 QFileInfo dictFileN(_settings->value("path"));
497 /*create cache file name*/
500 cachePathN = QDir::homePath() + "/.mdictionary/"
501 + dictFileN.completeBaseName()+"."
502 +QString::number(i) + ".cache";
504 } while(QFile::exists(cachePathN));
506 db_name = _settings->value("type") + cachePathN;
507 db = QSqlDatabase::addDatabase("QSQLITE",db_name);
509 /*checke errors (File open and db open)*/
510 QFile dictionaryFile(dictFileN.filePath());
511 if (!QFile::exists(_settings->value("path"))
512 || !dictionaryFile.open(QFile::ReadOnly | QFile::Text)) {
513 Q_EMIT updateCachingProgress(100, 0);
514 Q_EMIT notify(Notify::Warning,
515 QString(tr("XDXF file cannot be read for %1 dictionary")
519 QXmlStreamReader reader(&dictionaryFile);
520 db.setDatabaseName(cachePathN);
522 qDebug() << "Database error" << db.lastError().text() << endl;
523 Q_EMIT updateCachingProgress(100, 0);
524 Q_EMIT notify(Notify::Warning, QString(tr("Cache database cannot be "
525 "opened for %1 dictionary. Searching in XDXF file. "
526 "You may want to recache.").arg(name())));
531 QCoreApplication::processEvents();
533 cur.exec("PRAGMA synchronous = 0");
534 cur.exec("drop table dict");
535 QCoreApplication::processEvents();
536 cur.exec("create table dict(word text, normalized text ,translation text)");
546 _settings->setValue("strip_accents", "true");
549 /*add all words to db*/
550 while (!reader.atEnd() && !stopped) {
551 QCoreApplication::processEvents();
553 if(reader.tokenType() == QXmlStreamReader::StartElement) {
554 if(reader.name()=="k"){
555 readKey = reader.readElementText();
561 while(reader.name()!="ar" && !reader.atEnd()) {
562 if(reader.name()!="" && reader.name()!="k") {
563 if(reader.tokenType()==QXmlStreamReader::EndElement)
565 if(reader.tokenType()==QXmlStreamReader::StartElement)
567 temp+=reader.name().toString();
568 if(reader.name().toString()=="c"
569 && reader.tokenType()==QXmlStreamReader::StartElement) {
571 + reader.attributes().value("c").toString()
576 temp+= reader.text().toString().replace("<","<").replace(">"
580 if(temp.at(0)==QChar('\n'))
582 temp="<key>" + readKey + "</key>" + "<t>" + temp+ "</t>";
584 cur.prepare("insert into dict values(?,?,?)");
585 cur.addBindValue(readKey.toLower());
586 cur.addBindValue(removeAccents(readKey).toLower());
587 cur.addBindValue(temp);
590 int prog = counter*100/_wordsCount;
591 if(prog % 2 == 0 && lastProg != prog) {
592 Q_EMIT updateCachingProgress(prog,timer.restart());
598 cur.exec("select count(*) from dict");
600 /*checke errors (wrong number of added words)*/
602 if(!cur.next() || countWords() != cur.value(0).toInt()) {
603 Q_EMIT updateCachingProgress(100, timer.restart());
604 Q_EMIT notify(Notify::Warning,
605 QString(tr("Database caching error, please try again.")));
607 _settings->setValue("cache_path", cachePathN);
610 _settings->setValue("cache_path","");
614 _settings->setValue("cache_path", cachePathN);
615 _settings->setValue("cached", "true");
617 disconnect(&d, SIGNAL(cancelCaching()),
619 disconnect(this, SIGNAL(updateCachingProgress(int,int)),
620 &d, SLOT(updateCachingProgress(int,int)));
626 void XdxfPlugin::clean() {
627 if(QFile::exists(_settings->value("cache_path"))) {
628 QFile(_settings->value("cache_path")).remove();
629 QSqlDatabase::removeDatabase(db_name);
634 Q_EXPORT_PLUGIN2(xdxf, XdxfPlugin)