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"
31 XdxfPlugin::XdxfPlugin(QObject *parent) : CommonDictInterface(parent),
32 _langFrom(""), _langTo(""),_name(""), _infoNote("") {
34 //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>");
37 _settings = new Settings();
38 _dictDialog = new XdxfDictDialog(this, this);
40 connect(_dictDialog, SIGNAL(notify(Notify::NotifyType,QString)),
41 this, SIGNAL(notify(Notify::NotifyType,QString)));
44 _settings->setValue("type","xdxf");
45 _icon = QIcon("/usr/share/mdictionary/xdxf.png");
52 void XdxfPlugin::retranslate() {
53 QString locale = QLocale::system().name();
55 QTranslator *translator = new QTranslator(this);
57 if(!translator->load(":/xdxf/translations/" + locale)) {
58 translator->load(":/xdxf/translations/en_US");
60 QCoreApplication::installTranslator(translator);
64 XdxfPlugin::~XdxfPlugin() {
70 QString XdxfPlugin::langFrom() const {
75 QString XdxfPlugin::langTo() const {
80 QString XdxfPlugin::name() const {
85 QString XdxfPlugin::type() const {
86 return QString("xdxf");
90 QString XdxfPlugin::infoNote() const {
95 QList<Translation*> XdxfPlugin::searchWordList(QString word, int limit) {
96 if( word.indexOf("*")==-1 && word.indexOf("?")==-1 &&
97 word.indexOf("_")==-1 && word.indexOf("%")==-1)
101 return searchWordListCache(word,limit);
102 return searchWordListFile(word, limit);
106 QList<Translation*> XdxfPlugin::searchWordListCache(QString word, int limit) {
107 QSet<Translation*> translations;
108 QString cacheFilePath = _settings->value("cache_path");
110 db.setDatabaseName(cacheFilePath);
111 if(!QFile::exists(cacheFilePath) || !db.open()) {
112 qDebug() << "Database error" << db.lastError().text() << endl;
113 Q_EMIT notify(Notify::Warning, QString(tr("Cache database cannot be "
114 "opened for %1 dictionary. Searching in XDXF file. "
115 "You may want to recache.").arg(name())));
116 _settings->setValue("cached","false");
117 return searchWordListFile(word, limit);
120 word = word.toLower();
121 word = word.replace("*", "%");
122 word = word.replace("?", "_");
126 cur.prepare("select word from dict where word like ? or normalized "
129 cur.prepare("select word from dict where word like ? or normalized "
131 cur.addBindValue(word);
132 cur.addBindValue(word);
134 cur.addBindValue(limit);
137 while(cur.next() && (translations.size()<limit || limit==0)) {
138 translations.insert(new TranslationXdxf(
139 cur.value(0).toString(),
140 _dictionaryInfo, this));
143 return translations.toList();
147 QList<Translation*> XdxfPlugin::searchWordListFile(QString word, int limit) {
148 QSet<Translation*> translations;
149 QFile dictionaryFile(_settings->value("path"));
150 word = word.toLower();
153 QRegExp regWord(word);
154 regWord.setCaseSensitivity(Qt::CaseInsensitive);
155 regWord.setPatternSyntax(QRegExp::Wildcard);
157 /*check xdxf file exist*/
158 if(!QFile::exists(_settings->value("path"))
159 || !dictionaryFile.open(QFile::ReadOnly | QFile::Text)) {
160 qDebug()<<"Error: could not open file";
161 Q_EMIT notify(Notify::Warning,
162 QString(tr("XDXF file cannot be read for %1").arg(name())));
163 return translations.toList();
166 QXmlStreamReader reader(&dictionaryFile);
170 /*search words list*/
171 while(!reader.atEnd() && !stopped){
172 reader.readNextStartElement();
173 if(reader.name()=="ar") {
174 while(reader.name()!="k" && !reader.atEnd())
175 reader.readNextStartElement();
177 readKey = reader.readElementText();
178 if((regWord.exactMatch(readKey)
179 || regWord.exactMatch(removeAccents(readKey)))
180 && (i<limit || limit==0) && !reader.atEnd()) {
181 // qDebug()<<readKey;
182 translations<<(new TranslationXdxf(readKey.toLower(),
183 _dictionaryInfo,this));
184 if(translations.size()==limit && limit!=0)
188 this->thread()->yieldCurrentThread();
191 dictionaryFile.close();
192 return translations.toList();
196 QString XdxfPlugin::search(QString key) {
198 return searchCache(key);
199 return searchFile(key);
203 QString XdxfPlugin::searchCache(QString key) {
205 QString cacheFilePath = _settings->value("cache_path");
206 db.setDatabaseName(cacheFilePath);
209 if(!QFile::exists(cacheFilePath) || !db.open()) {
210 qDebug() << "Database error" << db.lastError().text() << endl;
211 Q_EMIT notify(Notify::Warning, QString(tr("Cache database cannot be "
212 "opened for %1 dictionary. Searching in XDXF file. "
213 "You may want to recache.").arg(name())));
214 _settings->setValue("cached","false");
215 return searchFile(key);
220 cur.prepare("select translation from dict where word like ?");
221 cur.addBindValue(key);
224 result += cur.value(0).toString();
233 QString XdxfPlugin::searchFile(QString key) {
234 QFile dictionaryFile(_settings->value("path"));
235 QString resultString("");
238 /*check xdxf file exist*/
239 if(!QFile::exists(_settings->value("path"))
240 || !dictionaryFile.open(QFile::ReadOnly | QFile::Text)) {
241 Q_EMIT notify(Notify::Warning,
242 QString(tr("XDXF file cannot be read for %1").arg(name())));
243 qDebug()<<"Error: could not open file";
247 QXmlStreamReader reader(&dictionaryFile);
252 /*search translations for word*/
253 while (!reader.atEnd()&& !stopped) {
255 if(reader.tokenType() == QXmlStreamReader::StartElement) {
256 if(reader.name()=="k") {
257 readKey = reader.readElementText();
258 if(readKey.toLower()==key.toLower())
264 while(reader.name()!="ar" && !reader.atEnd()) {
265 if(reader.name()!="" && reader.name()!="k") {
266 if(reader.tokenType()==QXmlStreamReader::EndElement)
268 if(reader.tokenType()==QXmlStreamReader::StartElement)
270 temp+=reader.name().toString();
271 if(reader.name().toString()=="c" &&
272 reader.tokenType()==QXmlStreamReader::StartElement)
273 temp= temp + " c=\"" + reader.attributes().
274 value("c").toString() + "\"";
277 temp+= reader.text().toString().replace("<","<").
281 if(temp.at(0)==QChar('\n'))
283 resultString+="<key>" + readKey +"</key>";
284 resultString+="<t>" + temp + "</t>";
287 this->thread()->yieldCurrentThread();
290 dictionaryFile.close();
295 void XdxfPlugin::stop() {
301 DictDialog* XdxfPlugin::dictDialog() {
306 CommonDictInterface* XdxfPlugin::getNew(const Settings *settings) const {
307 XdxfPlugin *plugin = new XdxfPlugin();
309 connect(plugin, SIGNAL(notify(Notify::NotifyType,QString)),
310 this, SIGNAL(notify(Notify::NotifyType,QString)));
312 ((XdxfDictDialog*)plugin->dictDialog())->setLastDialogParent(_dictDialog->lastDialogParent());
316 if(settings && plugin->setSettings(settings)) {
318 disconnect(plugin, SIGNAL(notify(Notify::NotifyType,QString)),
319 this, SIGNAL(notify(Notify::NotifyType,QString)));
323 disconnect(plugin, SIGNAL(notify(Notify::NotifyType,QString)),
324 this, SIGNAL(notify(Notify::NotifyType,QString)));
331 bool XdxfPlugin::isAvailable() const {
336 Settings* XdxfPlugin::settings() {
341 bool XdxfPlugin::isCached() {
342 if(_settings->value("cached") == "true")
348 bool XdxfPlugin::setSettings(const Settings *settings) {
350 bool isPathChange=false;
351 QString oldPath = _settings->value("path");
352 Settings *oldSettings = new Settings ;
354 if(oldPath != settings->value("path")) {
355 if(oldPath!="" && _settings->value("cache_path")!="")
360 foreach(QString key, _settings->keys())
361 oldSettings->setValue(key, _settings->value(key));
363 foreach(QString key, settings->keys()) {
364 if(key != "generateCache")
365 _settings->setValue(key, settings->value(key));
368 if(!getDictionaryInfo()) {
369 Q_EMIT notify(Notify::Warning,
370 QString(tr("XDXF file is in wrong format")));
371 qDebug()<<"Error: xdxf file is in wrong format";
373 _settings=oldSettings;
380 _settings->setValue("cached","false");
381 if(_settings->value("cached")=="true"
382 && _settings->value("cache_path")!="") {
383 db_name = _settings->value("type")
384 + _settings->value("cache_path");
385 db = QSqlDatabase::addDatabase("QSQLITE",db_name);
389 if((_settings->value("cached") == "false" ||
390 _settings->value("cached").isEmpty()) &&
391 settings->value("generateCache") == "true") {
396 else if (settings->value("generateCache") == "false") {
397 _settings->setValue("cached", "false");
402 Q_EMIT settingsChanged();
407 bool XdxfPlugin::getDictionaryInfo() {
408 QFile dictionaryFile(_settings->value("path"));
409 if(!QFile::exists(_settings->value("path"))
410 || !dictionaryFile.open(QFile::ReadOnly | QFile::Text)) {
411 Q_EMIT notify(Notify::Warning,
412 QString(tr("XDXF dictionary cannot be read from file")));
413 qDebug()<<"Error: could not open file";
418 QXmlStreamReader reader(&dictionaryFile);
419 reader.readNextStartElement();
420 if(reader.name()=="xdxf") {
422 if(reader.attributes().hasAttribute("lang_from"))
423 _langFrom = reader.attributes().value("lang_from").toString();
424 if(reader.attributes().hasAttribute("lang_to"))
425 _langTo = reader.attributes().value("lang_to").toString();
427 reader.readNextStartElement();
428 if(reader.name()=="full_name")
429 _name=reader.readElementText();
431 qDebug()<<"no full_name";
432 reader.readNextStartElement();
433 if(reader.name()=="description")
434 _infoNote=reader.readElementText();
436 qDebug()<<"no description";
438 _dictionaryInfo= _name + " [" + _langFrom + "-"
441 dictionaryFile.close();
448 QIcon* XdxfPlugin::icon() {
453 int XdxfPlugin::countWords() {
456 QFile dictionaryFile(_settings->value("path"));
457 if(!QFile::exists(_settings->value("path"))
458 || !dictionaryFile.open(QFile::ReadOnly | QFile::Text)) {
459 Q_EMIT notify(Notify::Warning,
460 QString(tr("XDXF file cannot be read for %1 dictionary")
462 qDebug()<<"Error: could not open file";
466 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) {
485 XdxfCachingDialog d(_dictDialog->lastDialogParent());
487 // qDebug()<<_dictDialog->lastDialogParent();
489 connect(&d, SIGNAL(cancelCaching()),
491 connect(this, SIGNAL(updateCachingProgress(int,int)),
492 &d, SLOT(updateCachingProgress(int,int)));
496 QCoreApplication::processEvents();
497 QFileInfo dictFileN(_settings->value("path"));
501 /*create cache file name*/
504 cachePathN = QDir::homePath() + "/.mdictionary/"
505 + dictFileN.completeBaseName()+"."
506 +QString::number(i) + ".cache";
508 } while(QFile::exists(cachePathN));
510 db_name = _settings->value("type") + cachePathN;
511 db = QSqlDatabase::addDatabase("QSQLITE",db_name);
513 /*checke errors (File open and db open)*/
514 QFile dictionaryFile(dictFileN.filePath());
515 if (!QFile::exists(_settings->value("path"))
516 || !dictionaryFile.open(QFile::ReadOnly | QFile::Text)) {
517 Q_EMIT updateCachingProgress(100, 0);
518 Q_EMIT notify(Notify::Warning,
519 QString(tr("XDXF file cannot be read for %1 dictionary")
523 QXmlStreamReader reader(&dictionaryFile);
524 db.setDatabaseName(cachePathN);
526 qDebug() << "Database error" << db.lastError().text() << endl;
527 Q_EMIT updateCachingProgress(100, 0);
528 Q_EMIT notify(Notify::Warning, QString(tr("Cache database cannot be "
529 "opened for %1 dictionary. Searching in XDXF file. "
530 "You may want to recache.").arg(name())));
535 QCoreApplication::processEvents();
537 cur.exec("PRAGMA synchronous = 0");
538 cur.exec("drop table dict");
539 QCoreApplication::processEvents();
540 cur.exec("create table dict(word text, normalized text ,translation text)");
550 _settings->setValue("strip_accents", "true");
553 /*add all words to db*/
554 while (!reader.atEnd() && !stopped) {
556 QCoreApplication::processEvents();
558 if(reader.tokenType() == QXmlStreamReader::StartElement) {
559 if(reader.name()=="k"){
560 readKey = reader.readElementText();
566 while(reader.name()!="ar" && !reader.atEnd()) {
567 if(reader.name()!="" && reader.name()!="k") {
568 if(reader.tokenType()==QXmlStreamReader::EndElement)
570 if(reader.tokenType()==QXmlStreamReader::StartElement)
572 temp+=reader.name().toString();
573 if(reader.name().toString()=="c"
574 && reader.tokenType()==QXmlStreamReader::StartElement) {
576 + reader.attributes().value("c").toString()
581 temp+= reader.text().toString().replace("<","<").replace(">"
585 if(temp.at(0)==QChar('\n'))
587 temp="<key>" + readKey + "</key>" + "<t>" + temp+ "</t>";
589 cur.prepare("insert into dict values(?,?,?)");
590 cur.addBindValue(readKey.toLower());
591 cur.addBindValue(removeAccents(readKey).toLower());
592 cur.addBindValue(temp);
595 int prog = counter*100/_wordsCount;
596 if(prog % 2 == 0 && lastProg != prog) {
597 Q_EMIT updateCachingProgress(prog,timer.restart());
603 cur.exec("select count(*) from dict");
605 /*checke errors (wrong number of added words)*/
607 if(!cur.next() || countWords() != cur.value(0).toInt()) {
608 Q_EMIT updateCachingProgress(100, timer.restart());
609 Q_EMIT notify(Notify::Warning,
610 QString(tr("Database caching error, please try again.")));
612 _settings->setValue("cache_path", cachePathN);
615 _settings->setValue("cache_path","");
619 _settings->setValue("cache_path", cachePathN);
620 _settings->setValue("cached", "true");
622 disconnect(&d, SIGNAL(cancelCaching()),
624 disconnect(this, SIGNAL(updateCachingProgress(int,int)),
625 &d, SLOT(updateCachingProgress(int,int)));
630 void XdxfPlugin::clean() {
631 if(QFile::exists(_settings->value("cache_path"))) {
632 QFile(_settings->value("cache_path")).remove();
633 QSqlDatabase::removeDatabase(db_name);
638 Q_EXPORT_PLUGIN2(xdxf, XdxfPlugin)