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"
30 #include "XdxfDictDownloader.h"
32 XdxfDictDownloader XdxfPlugin::dictDownloader;
34 bool XdxfPlugin::dictDownloaderInitialized = false;
37 XdxfPlugin::XdxfPlugin(QObject *parent) : CommonDictInterface(parent),
38 _langFrom(""), _langTo(""),_name(""), _infoNote("") {
40 //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>");
41 //dictDownloader.download(0);
44 _settings = new Settings();
45 _dictDialog = new XdxfDictDialog(this, this);
47 connect(_dictDialog, SIGNAL(notify(Notify::NotifyType,QString)),
48 this, SIGNAL(notify(Notify::NotifyType,QString)));
51 if(!dictDownloaderInitialized) {
52 connect(&dictDownloader, SIGNAL(notify(Notify::NotifyType,QString)),
53 this, SIGNAL(notify(Notify::NotifyType,QString)));
54 dictDownloaderInitialized = true;
58 _settings->setValue("type","xdxf");
59 _icon = QIcon("/usr/share/mdictionary/xdxf.png");
66 void XdxfPlugin::retranslate() {
67 QString locale = QLocale::system().name();
69 QTranslator *translator = new QTranslator(this);
71 if(!translator->load(":/xdxf/translations/" + locale)) {
72 translator->load(":/xdxf/translations/en_US");
74 QCoreApplication::installTranslator(translator);
78 XdxfPlugin::~XdxfPlugin() {
84 QString XdxfPlugin::langFrom() const {
89 QString XdxfPlugin::langTo() const {
94 QString XdxfPlugin::name() const {
99 QString XdxfPlugin::type() const {
100 return QString("xdxf");
104 QString XdxfPlugin::infoNote() const {
109 QList<Translation*> XdxfPlugin::searchWordList(QString word, int limit) {
110 if( word.indexOf("*")==-1 && word.indexOf("?")==-1 &&
111 word.indexOf("_")==-1 && word.indexOf("%")==-1)
115 return searchWordListCache(word,limit);
116 return searchWordListFile(word, limit);
120 QList<Translation*> XdxfPlugin::searchWordListCache(QString word, int limit) {
121 QSet<Translation*> translations;
122 QString cacheFilePath = _settings->value("cache_path");
124 db.setDatabaseName(cacheFilePath);
125 if(!QFile::exists(cacheFilePath) || !db.open()) {
126 qDebug() << "Database error" << db.lastError().text() << endl;
127 Q_EMIT notify(Notify::Warning, QString(tr("Cache database cannot be "
128 "opened for %1 dictionary. Searching in XDXF file. "
129 "You may want to recache.").arg(name())));
130 _settings->setValue("cached","false");
131 return searchWordListFile(word, limit);
134 word = word.toLower();
135 word = word.replace("*", "%");
136 word = word.replace("?", "_");
140 cur.prepare("select word from dict where word like ? or normalized "
143 cur.prepare("select word from dict where word like ? or normalized "
145 cur.addBindValue(word);
146 cur.addBindValue(word);
148 cur.addBindValue(limit);
151 while(cur.next() && (translations.size()<limit || limit==0)) {
152 translations.insert(new TranslationXdxf(
153 cur.value(0).toString(),
154 _dictionaryInfo, this));
157 return translations.toList();
161 QList<Translation*> XdxfPlugin::searchWordListFile(QString word, int limit) {
162 QSet<Translation*> translations;
163 QFile dictionaryFile(_settings->value("path"));
164 word = word.toLower();
167 QRegExp regWord(word);
168 regWord.setCaseSensitivity(Qt::CaseInsensitive);
169 regWord.setPatternSyntax(QRegExp::Wildcard);
171 /*check xdxf file exist*/
172 if(!QFile::exists(_settings->value("path"))
173 || !dictionaryFile.open(QFile::ReadOnly | QFile::Text)) {
174 qDebug()<<"Error: could not open file";
175 Q_EMIT notify(Notify::Warning,
176 QString(tr("XDXF file cannot be read for %1").arg(name())));
177 return translations.toList();
180 QXmlStreamReader reader(&dictionaryFile);
184 /*search words list*/
185 while(!reader.atEnd() && !stopped){
186 reader.readNextStartElement();
187 if(reader.name()=="ar") {
188 while(reader.name()!="k" && !reader.atEnd())
189 reader.readNextStartElement();
191 readKey = reader.readElementText();
192 if((regWord.exactMatch(readKey)
193 || regWord.exactMatch(removeAccents(readKey)))
194 && (i<limit || limit==0) && !reader.atEnd()) {
195 // qDebug()<<readKey;
196 translations<<(new TranslationXdxf(readKey.toLower(),
197 _dictionaryInfo,this));
198 if(translations.size()==limit && limit!=0)
202 this->thread()->yieldCurrentThread();
205 dictionaryFile.close();
206 return translations.toList();
210 QString XdxfPlugin::search(QString key) {
212 return searchCache(key);
213 return searchFile(key);
217 QString XdxfPlugin::searchCache(QString key) {
219 QString cacheFilePath = _settings->value("cache_path");
220 db.setDatabaseName(cacheFilePath);
223 if(!QFile::exists(cacheFilePath) || !db.open()) {
224 qDebug() << "Database error" << db.lastError().text() << endl;
225 Q_EMIT notify(Notify::Warning, QString(tr("Cache database cannot be "
226 "opened for %1 dictionary. Searching in XDXF file. "
227 "You may want to recache.").arg(name())));
228 _settings->setValue("cached","false");
229 return searchFile(key);
234 cur.prepare("select translation from dict where word like ?");
235 cur.addBindValue(key);
238 result += cur.value(0).toString();
247 QString XdxfPlugin::searchFile(QString key) {
248 QFile dictionaryFile(_settings->value("path"));
249 QString resultString("");
252 /*check xdxf file exist*/
253 if(!QFile::exists(_settings->value("path"))
254 || !dictionaryFile.open(QFile::ReadOnly | QFile::Text)) {
255 Q_EMIT notify(Notify::Warning,
256 QString(tr("XDXF file cannot be read for %1").arg(name())));
257 qDebug()<<"Error: could not open file";
261 QXmlStreamReader reader(&dictionaryFile);
266 /*search translations for word*/
267 while (!reader.atEnd()&& !stopped) {
269 if(reader.tokenType() == QXmlStreamReader::StartElement) {
270 if(reader.name()=="k") {
271 readKey = reader.readElementText();
272 if(readKey.toLower()==key.toLower())
278 while(reader.name()!="ar" && !reader.atEnd()) {
279 if(reader.name()!="" && reader.name()!="k") {
280 if(reader.tokenType()==QXmlStreamReader::EndElement)
282 if(reader.tokenType()==QXmlStreamReader::StartElement)
284 temp+=reader.name().toString();
285 if(reader.name().toString()=="c" &&
286 reader.tokenType()==QXmlStreamReader::StartElement)
287 temp= temp + " c=\"" + reader.attributes().
288 value("c").toString() + "\"";
291 temp+= reader.text().toString().replace("<","<").
295 if(temp.at(0)==QChar('\n'))
297 resultString+="<key>" + readKey +"</key>";
298 resultString+="<t>" + temp + "</t>";
301 this->thread()->yieldCurrentThread();
304 dictionaryFile.close();
309 void XdxfPlugin::stop() {
315 DictDialog* XdxfPlugin::dictDialog() {
320 CommonDictInterface* XdxfPlugin::getNew(const Settings *settings) const {
321 XdxfPlugin *plugin = new XdxfPlugin();
323 connect(plugin, SIGNAL(notify(Notify::NotifyType,QString)),
324 this, SIGNAL(notify(Notify::NotifyType,QString)));
326 ((XdxfDictDialog*)plugin->dictDialog())->setLastDialogParent(_dictDialog->lastDialogParent());
330 if(settings && plugin->setSettings(settings)) {
332 disconnect(plugin, SIGNAL(notify(Notify::NotifyType,QString)),
333 this, SIGNAL(notify(Notify::NotifyType,QString)));
337 disconnect(plugin, SIGNAL(notify(Notify::NotifyType,QString)),
338 this, SIGNAL(notify(Notify::NotifyType,QString)));
345 bool XdxfPlugin::isAvailable() const {
350 Settings* XdxfPlugin::settings() {
355 bool XdxfPlugin::isCached() {
356 if(_settings->value("cached") == "true")
362 bool XdxfPlugin::setSettings(const Settings *settings) {
364 bool isPathChange=false;
365 QString oldPath = _settings->value("path");
366 Settings *oldSettings = new Settings ;
368 if(oldPath != settings->value("path")) {
369 if(oldPath!="" && _settings->value("cache_path")!="")
374 foreach(QString key, _settings->keys())
375 oldSettings->setValue(key, _settings->value(key));
377 foreach(QString key, settings->keys()) {
378 if(key != "generateCache")
379 _settings->setValue(key, settings->value(key));
382 if(!getDictionaryInfo()) {
383 Q_EMIT notify(Notify::Warning,
384 QString(tr("XDXF file is in wrong format")));
385 qDebug()<<"Error: xdxf file is in wrong format";
387 _settings=oldSettings;
394 _settings->setValue("cached","false");
395 if(_settings->value("cached")=="true"
396 && _settings->value("cache_path")!="") {
397 db_name = _settings->value("type")
398 + _settings->value("cache_path");
399 db = QSqlDatabase::addDatabase("QSQLITE",db_name);
403 if((_settings->value("cached") == "false" ||
404 _settings->value("cached").isEmpty()) &&
405 settings->value("generateCache") == "true") {
410 else if (settings->value("generateCache") == "false") {
411 _settings->setValue("cached", "false");
416 Q_EMIT settingsChanged();
421 bool XdxfPlugin::getDictionaryInfo() {
422 QFile dictionaryFile(_settings->value("path"));
423 if(!QFile::exists(_settings->value("path"))
424 || !dictionaryFile.open(QFile::ReadOnly | QFile::Text)) {
425 Q_EMIT notify(Notify::Warning,
426 QString(tr("XDXF dictionary cannot be read from file")));
427 qDebug()<<"Error: could not open file";
432 QXmlStreamReader reader(&dictionaryFile);
433 reader.readNextStartElement();
434 if(reader.name()=="xdxf") {
436 if(reader.attributes().hasAttribute("lang_from"))
437 _langFrom = reader.attributes().value("lang_from").toString();
438 if(reader.attributes().hasAttribute("lang_to"))
439 _langTo = reader.attributes().value("lang_to").toString();
441 reader.readNextStartElement();
442 if(reader.name()=="full_name")
443 _name=reader.readElementText();
445 qDebug()<<"no full_name";
446 reader.readNextStartElement();
447 if(reader.name()=="description")
448 _infoNote=reader.readElementText();
450 qDebug()<<"no description";
452 _dictionaryInfo= _name + " [" + _langFrom + "-"
455 dictionaryFile.close();
462 QIcon* XdxfPlugin::icon() {
467 int XdxfPlugin::countWords() {
470 QFile dictionaryFile(_settings->value("path"));
471 if(!QFile::exists(_settings->value("path"))
472 || !dictionaryFile.open(QFile::ReadOnly | QFile::Text)) {
473 Q_EMIT notify(Notify::Warning,
474 QString(tr("XDXF file cannot be read for %1 dictionary")
476 qDebug()<<"Error: could not open file";
480 dictionaryFile.seek(0);
485 while(!dictionaryFile.atEnd()) {
486 line = dictionaryFile.readLine();
487 if(line.contains("<k>")) {
491 _wordsCount = wordsCount;
492 dictionaryFile.close();
497 bool XdxfPlugin::makeCache(QString) {
499 XdxfCachingDialog d(_dictDialog->lastDialogParent());
501 // qDebug()<<_dictDialog->lastDialogParent();
503 connect(&d, SIGNAL(cancelCaching()),
505 connect(this, SIGNAL(updateCachingProgress(int,int)),
506 &d, SLOT(updateCachingProgress(int,int)));
510 QCoreApplication::processEvents();
511 QFileInfo dictFileN(_settings->value("path"));
515 /*create cache file name*/
518 cachePathN = QDir::homePath() + "/.mdictionary/"
519 + dictFileN.completeBaseName()+"."
520 +QString::number(i) + ".cache";
522 } while(QFile::exists(cachePathN));
524 db_name = _settings->value("type") + cachePathN;
525 db = QSqlDatabase::addDatabase("QSQLITE",db_name);
527 /*checke errors (File open and db open)*/
528 QFile dictionaryFile(dictFileN.filePath());
529 if (!QFile::exists(_settings->value("path"))
530 || !dictionaryFile.open(QFile::ReadOnly | QFile::Text)) {
531 Q_EMIT updateCachingProgress(100, 0);
532 Q_EMIT notify(Notify::Warning,
533 QString(tr("XDXF file cannot be read for %1 dictionary")
537 QXmlStreamReader reader(&dictionaryFile);
538 db.setDatabaseName(cachePathN);
540 qDebug() << "Database error" << db.lastError().text() << endl;
541 Q_EMIT updateCachingProgress(100, 0);
542 Q_EMIT notify(Notify::Warning, QString(tr("Cache database cannot be "
543 "opened for %1 dictionary. Searching in XDXF file. "
544 "You may want to recache.").arg(name())));
549 QCoreApplication::processEvents();
551 cur.exec("PRAGMA synchronous = 0");
552 cur.exec("drop table dict");
553 QCoreApplication::processEvents();
554 cur.exec("create table dict(word text, normalized text ,translation text)");
564 _settings->setValue("strip_accents", "true");
567 /*add all words to db*/
568 while (!reader.atEnd() && !stopped) {
570 QCoreApplication::processEvents();
572 if(reader.tokenType() == QXmlStreamReader::StartElement) {
573 if(reader.name()=="k"){
574 readKey = reader.readElementText();
580 while(reader.name()!="ar" && !reader.atEnd()) {
581 if(reader.name()!="" && reader.name()!="k") {
582 if(reader.tokenType()==QXmlStreamReader::EndElement)
584 if(reader.tokenType()==QXmlStreamReader::StartElement)
586 temp+=reader.name().toString();
587 if(reader.name().toString()=="c"
588 && reader.tokenType()==QXmlStreamReader::StartElement) {
590 + reader.attributes().value("c").toString()
595 temp+= reader.text().toString().replace("<","<").replace(">"
599 if(temp.at(0)==QChar('\n'))
601 temp="<key>" + readKey + "</key>" + "<t>" + temp+ "</t>";
603 cur.prepare("insert into dict values(?,?,?)");
604 cur.addBindValue(readKey.toLower());
605 cur.addBindValue(removeAccents(readKey).toLower());
606 cur.addBindValue(temp);
609 int prog = counter*100/_wordsCount;
610 if(prog % 2 == 0 && lastProg != prog) {
611 Q_EMIT updateCachingProgress(prog,timer.restart());
617 cur.exec("select count(*) from dict");
619 /*checke errors (wrong number of added words)*/
621 if(!cur.next() || countWords() != cur.value(0).toInt()) {
622 Q_EMIT updateCachingProgress(100, timer.restart());
623 Q_EMIT notify(Notify::Warning,
624 QString(tr("Database caching error, please try again.")));
626 _settings->setValue("cache_path", cachePathN);
629 _settings->setValue("cache_path","");
633 _settings->setValue("cache_path", cachePathN);
634 _settings->setValue("cached", "true");
636 disconnect(&d, SIGNAL(cancelCaching()),
638 disconnect(this, SIGNAL(updateCachingProgress(int,int)),
639 &d, SLOT(updateCachingProgress(int,int)));
644 void XdxfPlugin::clean() {
645 if(QFile::exists(_settings->value("cache_path"))) {
646 QFile(_settings->value("cache_path")).remove();
647 QSqlDatabase::removeDatabase(db_name);
652 Q_EXPORT_PLUGIN2(xdxf, XdxfPlugin)