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 *******************************************************************************/
22 /*! \file xdxfplugin.cpp
23 \author Jakub Jaszczynski <j.j.jaszczynski@gmail.com>
26 #include "xdxfplugin.h"
28 #include "../../include/Notify.h"
29 #include "DownloadDict.h"
32 XdxfDictDownloader XdxfPlugin::dictDownloader;
34 XdxfPlugin::XdxfPlugin(QObject *parent) : CommonDictInterface(parent),
35 _langFrom(""), _langTo(""),_name(""), _infoNote("") {
37 //DownloadDict a("<tr><td><img src=\"buf/comn_sdict05_bulg_comp/icon16.png\" alt=\"icon\" /></td><td align=\"center\">English-Bulgarian computer dictionary</td><td align=\"center\"><a href=\"http://downloads.sourceforge.net/xdxf/comn_sdict05_bulg_comp.tar.bz2\" target=\"_blank\">comn_sdict05_bulg_comp.tar.bz2</a></td><td align=\"right\">13,889</td><td align=\"right\">55,094</td><td align=\"right\">523</td><td align=\"center\">English</td><td align=\"center\">Bulgarian</td><td align=\"center\"><a href=\"http://xdxf.revdanica.com/\">Common XDXF</a></td><td align=\"center\">2006-04-23 23:34:40</td></tr>");
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)));
47 _settings->setValue("type","xdxf");
48 _icon = QIcon("/usr/share/mdictionary/xdxf.png");
55 void XdxfPlugin::retranslate() {
56 QString locale = QLocale::system().name();
58 QTranslator *translator = new QTranslator(this);
60 if(!translator->load(":/xdxf/translations/" + locale)) {
61 translator->load(":/xdxf/translations/en_US");
63 QCoreApplication::installTranslator(translator);
67 XdxfPlugin::~XdxfPlugin() {
73 QString XdxfPlugin::langFrom() const {
78 QString XdxfPlugin::langTo() const {
83 QString XdxfPlugin::name() const {
88 QString XdxfPlugin::type() const {
89 return QString("xdxf");
93 QString XdxfPlugin::infoNote() const {
98 QList<Translation*> XdxfPlugin::searchWordList(QString word, int limit) {
99 if( word.indexOf("*")==-1 && word.indexOf("?")==-1 &&
100 word.indexOf("_")==-1 && word.indexOf("%")==-1)
104 return searchWordListCache(word,limit);
105 return searchWordListFile(word, limit);
109 QList<Translation*> XdxfPlugin::searchWordListCache(QString word, int limit) {
110 QSet<Translation*> translations;
111 QString cacheFilePath = _settings->value("cache_path");
113 db.setDatabaseName(cacheFilePath);
114 if(!QFile::exists(cacheFilePath) || !db.open()) {
115 qDebug() << "Database error" << db.lastError().text() << endl;
116 Q_EMIT notify(Notify::Warning, QString(tr("Cache database cannot be "
117 "opened for %1 dictionary. Searching in XDXF file. "
118 "You may want to recache.").arg(name())));
119 _settings->setValue("cached","false");
120 return searchWordListFile(word, limit);
123 word = word.toLower();
124 word = word.replace("*", "%");
125 word = word.replace("?", "_");
129 cur.prepare("select word from dict where word like ? or normalized "
132 cur.prepare("select word from dict where word like ? or normalized "
134 cur.addBindValue(word);
135 cur.addBindValue(word);
137 cur.addBindValue(limit);
140 while(cur.next() && (translations.size()<limit || limit==0)) {
141 translations.insert(new TranslationXdxf(
142 cur.value(0).toString(),
143 _dictionaryInfo, this));
146 return translations.toList();
150 QList<Translation*> XdxfPlugin::searchWordListFile(QString word, int limit) {
151 QSet<Translation*> translations;
152 QFile dictionaryFile(_settings->value("path"));
153 word = word.toLower();
156 QRegExp regWord(word);
157 regWord.setCaseSensitivity(Qt::CaseInsensitive);
158 regWord.setPatternSyntax(QRegExp::Wildcard);
160 /*check xdxf file exist*/
161 if(!QFile::exists(_settings->value("path"))
162 || !dictionaryFile.open(QFile::ReadOnly | QFile::Text)) {
163 qDebug()<<"Error: could not open file";
164 Q_EMIT notify(Notify::Warning,
165 QString(tr("XDXF file cannot be read for %1").arg(name())));
166 return translations.toList();
169 QXmlStreamReader reader(&dictionaryFile);
173 /*search words list*/
174 while(!reader.atEnd() && !stopped){
175 reader.readNextStartElement();
176 if(reader.name()=="ar") {
177 while(reader.name()!="k" && !reader.atEnd())
178 reader.readNextStartElement();
180 readKey = reader.readElementText();
181 if((regWord.exactMatch(readKey)
182 || regWord.exactMatch(removeAccents(readKey)))
183 && (i<limit || limit==0) && !reader.atEnd()) {
184 // qDebug()<<readKey;
185 translations<<(new TranslationXdxf(readKey.toLower(),
186 _dictionaryInfo,this));
187 if(translations.size()==limit && limit!=0)
191 this->thread()->yieldCurrentThread();
194 dictionaryFile.close();
195 return translations.toList();
199 QString XdxfPlugin::search(QString key) {
201 return searchCache(key);
202 return searchFile(key);
206 QString XdxfPlugin::searchCache(QString key) {
208 QString cacheFilePath = _settings->value("cache_path");
209 db.setDatabaseName(cacheFilePath);
212 if(!QFile::exists(cacheFilePath) || !db.open()) {
213 qDebug() << "Database error" << db.lastError().text() << endl;
214 Q_EMIT notify(Notify::Warning, QString(tr("Cache database cannot be "
215 "opened for %1 dictionary. Searching in XDXF file. "
216 "You may want to recache.").arg(name())));
217 _settings->setValue("cached","false");
218 return searchFile(key);
223 cur.prepare("select translation from dict where word like ?");
224 cur.addBindValue(key);
227 result += cur.value(0).toString();
236 QString XdxfPlugin::searchFile(QString key) {
237 QFile dictionaryFile(_settings->value("path"));
238 QString resultString("");
241 /*check xdxf file exist*/
242 if(!QFile::exists(_settings->value("path"))
243 || !dictionaryFile.open(QFile::ReadOnly | QFile::Text)) {
244 Q_EMIT notify(Notify::Warning,
245 QString(tr("XDXF file cannot be read for %1").arg(name())));
246 qDebug()<<"Error: could not open file";
250 QXmlStreamReader reader(&dictionaryFile);
255 /*search translations for word*/
256 while (!reader.atEnd()&& !stopped) {
258 if(reader.tokenType() == QXmlStreamReader::StartElement) {
259 if(reader.name()=="k") {
260 readKey = reader.readElementText();
261 if(readKey.toLower()==key.toLower())
267 while(reader.name()!="ar" && !reader.atEnd()) {
268 if(reader.name()!="" && reader.name()!="k") {
269 if(reader.tokenType()==QXmlStreamReader::EndElement)
271 if(reader.tokenType()==QXmlStreamReader::StartElement)
273 temp+=reader.name().toString();
274 if(reader.name().toString()=="c" &&
275 reader.tokenType()==QXmlStreamReader::StartElement)
276 temp= temp + " c=\"" + reader.attributes().
277 value("c").toString() + "\"";
280 temp+= reader.text().toString().replace("<","<").
284 if(temp.at(0)==QChar('\n'))
286 resultString+="<key>" + readKey +"</key>";
287 resultString+="<t>" + temp + "</t>";
290 this->thread()->yieldCurrentThread();
293 dictionaryFile.close();
298 void XdxfPlugin::stop() {
304 DictDialog* XdxfPlugin::dictDialog() {
309 CommonDictInterface* XdxfPlugin::getNew(const Settings *settings) const {
310 XdxfPlugin *plugin = new XdxfPlugin();
312 connect(plugin, SIGNAL(notify(Notify::NotifyType,QString)),
313 this, SIGNAL(notify(Notify::NotifyType,QString)));
315 ((XdxfDictDialog*)plugin->dictDialog())->setLastDialogParent(_dictDialog->lastDialogParent());
319 if(settings && plugin->setSettings(settings)) {
321 disconnect(plugin, SIGNAL(notify(Notify::NotifyType,QString)),
322 this, SIGNAL(notify(Notify::NotifyType,QString)));
326 disconnect(plugin, SIGNAL(notify(Notify::NotifyType,QString)),
327 this, SIGNAL(notify(Notify::NotifyType,QString)));
334 bool XdxfPlugin::isAvailable() const {
339 Settings* XdxfPlugin::settings() {
344 bool XdxfPlugin::isCached() {
345 if(_settings->value("cached") == "true")
351 bool XdxfPlugin::setSettings(const Settings *settings) {
353 bool isPathChange=false;
354 QString oldPath = _settings->value("path");
355 Settings *oldSettings = new Settings ;
357 if(oldPath != settings->value("path")) {
358 if(oldPath!="" && _settings->value("cache_path")!="")
363 foreach(QString key, _settings->keys())
364 oldSettings->setValue(key, _settings->value(key));
366 foreach(QString key, settings->keys()) {
367 if(key != "generateCache")
368 _settings->setValue(key, settings->value(key));
371 if(!getDictionaryInfo()) {
372 Q_EMIT notify(Notify::Warning,
373 QString(tr("XDXF file is in wrong format")));
374 qDebug()<<"Error: xdxf file is in wrong format";
376 _settings=oldSettings;
383 _settings->setValue("cached","false");
384 if(_settings->value("cached")=="true"
385 && _settings->value("cache_path")!="") {
386 db_name = _settings->value("type")
387 + _settings->value("cache_path");
388 db = QSqlDatabase::addDatabase("QSQLITE",db_name);
392 if((_settings->value("cached") == "false" ||
393 _settings->value("cached").isEmpty()) &&
394 settings->value("generateCache") == "true") {
399 else if (settings->value("generateCache") == "false") {
400 _settings->setValue("cached", "false");
405 Q_EMIT settingsChanged();
410 bool XdxfPlugin::getDictionaryInfo() {
411 QFile dictionaryFile(_settings->value("path"));
412 if(!QFile::exists(_settings->value("path"))
413 || !dictionaryFile.open(QFile::ReadOnly | QFile::Text)) {
414 Q_EMIT notify(Notify::Warning,
415 QString(tr("XDXF dictionary cannot be read from file")));
416 qDebug()<<"Error: could not open file";
421 QXmlStreamReader reader(&dictionaryFile);
422 reader.readNextStartElement();
423 if(reader.name()=="xdxf") {
425 if(reader.attributes().hasAttribute("lang_from"))
426 _langFrom = reader.attributes().value("lang_from").toString();
427 if(reader.attributes().hasAttribute("lang_to"))
428 _langTo = reader.attributes().value("lang_to").toString();
430 reader.readNextStartElement();
431 if(reader.name()=="full_name")
432 _name=reader.readElementText();
434 qDebug()<<"no full_name";
435 reader.readNextStartElement();
436 if(reader.name()=="description")
437 _infoNote=reader.readElementText();
439 qDebug()<<"no description";
441 _dictionaryInfo= _name + " [" + _langFrom + "-"
444 dictionaryFile.close();
451 QIcon* XdxfPlugin::icon() {
456 int XdxfPlugin::countWords() {
459 QFile dictionaryFile(_settings->value("path"));
460 if(!QFile::exists(_settings->value("path"))
461 || !dictionaryFile.open(QFile::ReadOnly | QFile::Text)) {
462 Q_EMIT notify(Notify::Warning,
463 QString(tr("XDXF file cannot be read for %1 dictionary")
465 qDebug()<<"Error: could not open file";
469 dictionaryFile.seek(0);
474 while(!dictionaryFile.atEnd()) {
475 line = dictionaryFile.readLine();
476 if(line.contains("<k>")) {
480 _wordsCount = wordsCount;
481 dictionaryFile.close();
486 bool XdxfPlugin::makeCache(QString) {
488 XdxfCachingDialog d(_dictDialog->lastDialogParent());
490 // qDebug()<<_dictDialog->lastDialogParent();
492 connect(&d, SIGNAL(cancelCaching()),
494 connect(this, SIGNAL(updateCachingProgress(int,int)),
495 &d, SLOT(updateCachingProgress(int,int)));
499 QCoreApplication::processEvents();
500 QFileInfo dictFileN(_settings->value("path"));
504 /*create cache file name*/
507 cachePathN = QDir::homePath() + "/.mdictionary/"
508 + dictFileN.completeBaseName()+"."
509 +QString::number(i) + ".cache";
511 } while(QFile::exists(cachePathN));
513 db_name = _settings->value("type") + cachePathN;
514 db = QSqlDatabase::addDatabase("QSQLITE",db_name);
516 /*checke errors (File open and db open)*/
517 QFile dictionaryFile(dictFileN.filePath());
518 if (!QFile::exists(_settings->value("path"))
519 || !dictionaryFile.open(QFile::ReadOnly | QFile::Text)) {
520 Q_EMIT updateCachingProgress(100, 0);
521 Q_EMIT notify(Notify::Warning,
522 QString(tr("XDXF file cannot be read for %1 dictionary")
526 QXmlStreamReader reader(&dictionaryFile);
527 db.setDatabaseName(cachePathN);
529 qDebug() << "Database error" << db.lastError().text() << endl;
530 Q_EMIT updateCachingProgress(100, 0);
531 Q_EMIT notify(Notify::Warning, QString(tr("Cache database cannot be "
532 "opened for %1 dictionary. Searching in XDXF file. "
533 "You may want to recache.").arg(name())));
538 QCoreApplication::processEvents();
540 cur.exec("PRAGMA synchronous = 0");
541 cur.exec("drop table dict");
542 QCoreApplication::processEvents();
543 cur.exec("create table dict(word text, normalized text ,translation text)");
553 _settings->setValue("strip_accents", "true");
556 /*add all words to db*/
557 while (!reader.atEnd() && !stopped) {
559 QCoreApplication::processEvents();
561 if(reader.tokenType() == QXmlStreamReader::StartElement) {
562 if(reader.name()=="k"){
563 readKey = reader.readElementText();
569 while(reader.name()!="ar" && !reader.atEnd()) {
570 if(reader.name()!="" && reader.name()!="k") {
571 if(reader.tokenType()==QXmlStreamReader::EndElement)
573 if(reader.tokenType()==QXmlStreamReader::StartElement)
575 temp+=reader.name().toString();
576 if(reader.name().toString()=="c"
577 && reader.tokenType()==QXmlStreamReader::StartElement) {
579 + reader.attributes().value("c").toString()
584 temp+= reader.text().toString().replace("<","<").replace(">"
588 if(temp.at(0)==QChar('\n'))
590 temp="<key>" + readKey + "</key>" + "<t>" + temp+ "</t>";
592 cur.prepare("insert into dict values(?,?,?)");
593 cur.addBindValue(readKey.toLower());
594 cur.addBindValue(removeAccents(readKey).toLower());
595 cur.addBindValue(temp);
598 int prog = counter*100/_wordsCount;
599 if(prog % 2 == 0 && lastProg != prog) {
600 Q_EMIT updateCachingProgress(prog,timer.restart());
606 cur.exec("select count(*) from dict");
608 /*checke errors (wrong number of added words)*/
610 if(!cur.next() || countWords() != cur.value(0).toInt()) {
611 Q_EMIT updateCachingProgress(100, timer.restart());
612 Q_EMIT notify(Notify::Warning,
613 QString(tr("Database caching error, please try again.")));
615 _settings->setValue("cache_path", cachePathN);
618 _settings->setValue("cache_path","");
622 _settings->setValue("cache_path", cachePathN);
623 _settings->setValue("cached", "true");
625 disconnect(&d, SIGNAL(cancelCaching()),
627 disconnect(this, SIGNAL(updateCachingProgress(int,int)),
628 &d, SLOT(updateCachingProgress(int,int)));
633 void XdxfPlugin::clean() {
634 if(QFile::exists(_settings->value("cache_path"))) {
635 QFile(_settings->value("cache_path")).remove();
636 QSqlDatabase::removeDatabase(db_name);
641 Q_EXPORT_PLUGIN2(xdxf, XdxfPlugin)