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"
31 XdxfDictDownloader XdxfPlugin::dictDownloader;
33 XdxfPlugin::XdxfPlugin(QObject *parent) : CommonDictInterface(parent),
34 _langFrom(""), _langTo(""),_name(""), _infoNote("") {
35 _settings = new Settings();
36 _dictDialog = new XdxfDictDialog(this, this);
38 connect(_dictDialog, SIGNAL(notify(Notify::NotifyType,QString)),
39 this, SIGNAL(notify(Notify::NotifyType,QString)));
42 _settings->setValue("type","xdxf");
43 _icon = QIcon("/usr/share/mdictionary/xdxf.png");
50 void XdxfPlugin::retranslate() {
51 QString locale = QLocale::system().name();
53 QTranslator *translator = new QTranslator(this);
55 if(!translator->load(":/xdxf/translations/" + locale)) {
56 translator->load(":/xdxf/translations/en_US");
58 QCoreApplication::installTranslator(translator);
62 XdxfPlugin::~XdxfPlugin() {
68 QString XdxfPlugin::langFrom() const {
73 QString XdxfPlugin::langTo() const {
78 QString XdxfPlugin::name() const {
83 QString XdxfPlugin::type() const {
84 return QString("xdxf");
88 QString XdxfPlugin::infoNote() const {
93 QList<Translation*> XdxfPlugin::searchWordList(QString word, int limit) {
94 if( word.indexOf("*")==-1 && word.indexOf("?")==-1 &&
95 word.indexOf("_")==-1 && word.indexOf("%")==-1)
99 return searchWordListCache(word,limit);
100 return searchWordListFile(word, limit);
104 QList<Translation*> XdxfPlugin::searchWordListCache(QString word, int limit) {
105 QSet<Translation*> translations;
106 QString cacheFilePath = _settings->value("cache_path");
108 db.setDatabaseName(cacheFilePath);
109 if(!QFile::exists(cacheFilePath) || !db.open()) {
110 qDebug() << "Database error" << db.lastError().text() << endl;
111 Q_EMIT notify(Notify::Warning, QString(tr("Cache database cannot be "
112 "opened for %1 dictionary. Searching in XDXF file. "
113 "You may want to recache.").arg(name())));
114 _settings->setValue("cached","false");
115 return searchWordListFile(word, limit);
118 word = word.toLower();
119 word = word.replace("*", "%");
120 word = word.replace("?", "_");
124 cur.prepare("select word from dict where word like ? or normalized "
127 cur.prepare("select word from dict where word like ? or normalized "
129 cur.addBindValue(word);
130 cur.addBindValue(word);
132 cur.addBindValue(limit);
135 while(cur.next() && (translations.size()<limit || limit==0)) {
136 translations.insert(new TranslationXdxf(
137 cur.value(0).toString(),
138 _dictionaryInfo, this));
141 return translations.toList();
145 QList<Translation*> XdxfPlugin::searchWordListFile(QString word, int limit) {
146 QSet<Translation*> translations;
147 QFile dictionaryFile(_settings->value("path"));
148 word = word.toLower();
151 QRegExp regWord(word);
152 regWord.setCaseSensitivity(Qt::CaseInsensitive);
153 regWord.setPatternSyntax(QRegExp::Wildcard);
155 /*check xdxf file exist*/
156 if(!QFile::exists(_settings->value("path"))
157 || !dictionaryFile.open(QFile::ReadOnly | QFile::Text)) {
158 qDebug()<<"Error: could not open file";
159 Q_EMIT notify(Notify::Warning,
160 QString(tr("XDXF file cannot be read for %1").arg(name())));
161 return translations.toList();
164 QXmlStreamReader reader(&dictionaryFile);
168 /*search words list*/
169 while(!reader.atEnd() && !stopped){
170 reader.readNextStartElement();
171 if(reader.name()=="ar") {
172 while(reader.name()!="k" && !reader.atEnd())
173 reader.readNextStartElement();
175 readKey = reader.readElementText();
176 if((regWord.exactMatch(readKey)
177 || regWord.exactMatch(removeAccents(readKey)))
178 && (i<limit || limit==0) && !reader.atEnd()) {
179 // qDebug()<<readKey;
180 translations<<(new TranslationXdxf(readKey.toLower(),
181 _dictionaryInfo,this));
182 if(translations.size()==limit && limit!=0)
186 this->thread()->yieldCurrentThread();
189 dictionaryFile.close();
190 return translations.toList();
194 QString XdxfPlugin::search(QString key) {
196 return searchCache(key);
197 return searchFile(key);
201 QString XdxfPlugin::searchCache(QString key) {
203 QString cacheFilePath = _settings->value("cache_path");
204 db.setDatabaseName(cacheFilePath);
207 if(!QFile::exists(cacheFilePath) || !db.open()) {
208 qDebug() << "Database error" << db.lastError().text() << endl;
209 Q_EMIT notify(Notify::Warning, QString(tr("Cache database cannot be "
210 "opened for %1 dictionary. Searching in XDXF file. "
211 "You may want to recache.").arg(name())));
212 _settings->setValue("cached","false");
213 return searchFile(key);
218 cur.prepare("select translation from dict where word like ?");
219 cur.addBindValue(key);
222 result += cur.value(0).toString();
231 QString XdxfPlugin::searchFile(QString key) {
232 QFile dictionaryFile(_settings->value("path"));
233 QString resultString("");
236 /*check xdxf file exist*/
237 if(!QFile::exists(_settings->value("path"))
238 || !dictionaryFile.open(QFile::ReadOnly | QFile::Text)) {
239 Q_EMIT notify(Notify::Warning,
240 QString(tr("XDXF file cannot be read for %1").arg(name())));
241 qDebug()<<"Error: could not open file";
245 QXmlStreamReader reader(&dictionaryFile);
250 /*search translations for word*/
251 while (!reader.atEnd()&& !stopped) {
253 if(reader.tokenType() == QXmlStreamReader::StartElement) {
254 if(reader.name()=="k") {
255 readKey = reader.readElementText();
256 if(readKey.toLower()==key.toLower())
262 while(reader.name()!="ar" && !reader.atEnd()) {
263 if(reader.name()!="" && reader.name()!="k") {
264 if(reader.tokenType()==QXmlStreamReader::EndElement)
266 if(reader.tokenType()==QXmlStreamReader::StartElement)
268 temp+=reader.name().toString();
269 if(reader.name().toString()=="c" &&
270 reader.tokenType()==QXmlStreamReader::StartElement)
271 temp= temp + " c=\"" + reader.attributes().
272 value("c").toString() + "\"";
275 temp+= reader.text().toString().replace("<","<").
279 if(temp.at(0)==QChar('\n'))
281 resultString+="<key>" + readKey +"</key>";
282 resultString+="<t>" + temp + "</t>";
285 this->thread()->yieldCurrentThread();
288 dictionaryFile.close();
293 void XdxfPlugin::stop() {
299 DictDialog* XdxfPlugin::dictDialog() {
304 CommonDictInterface* XdxfPlugin::getNew(const Settings *settings) const {
305 XdxfPlugin *plugin = new XdxfPlugin();
307 connect(plugin, SIGNAL(notify(Notify::NotifyType,QString)),
308 this, SIGNAL(notify(Notify::NotifyType,QString)));
310 ((XdxfDictDialog*)plugin->dictDialog())->setLastDialogParent(_dictDialog->lastDialogParent());
314 if(settings && plugin->setSettings(settings)) {
316 disconnect(plugin, SIGNAL(notify(Notify::NotifyType,QString)),
317 this, SIGNAL(notify(Notify::NotifyType,QString)));
321 disconnect(plugin, SIGNAL(notify(Notify::NotifyType,QString)),
322 this, SIGNAL(notify(Notify::NotifyType,QString)));
329 bool XdxfPlugin::isAvailable() const {
334 Settings* XdxfPlugin::settings() {
339 bool XdxfPlugin::isCached() {
340 if(_settings->value("cached") == "true")
346 bool XdxfPlugin::setSettings(const Settings *settings) {
348 bool isPathChange=false;
349 QString oldPath = _settings->value("path");
350 Settings *oldSettings = new Settings ;
352 if(oldPath != settings->value("path")) {
353 if(oldPath!="" && _settings->value("cache_path")!="")
358 foreach(QString key, _settings->keys())
359 oldSettings->setValue(key, _settings->value(key));
361 foreach(QString key, settings->keys()) {
362 if(key != "generateCache")
363 _settings->setValue(key, settings->value(key));
366 if(!getDictionaryInfo()) {
367 Q_EMIT notify(Notify::Warning,
368 QString(tr("XDXF file is in wrong format")));
369 qDebug()<<"Error: xdxf file is in wrong format";
371 _settings=oldSettings;
378 _settings->setValue("cached","false");
379 if(_settings->value("cached")=="true"
380 && _settings->value("cache_path")!="") {
381 db_name = _settings->value("type")
382 + _settings->value("cache_path");
383 db = QSqlDatabase::addDatabase("QSQLITE",db_name);
387 if((_settings->value("cached") == "false" ||
388 _settings->value("cached").isEmpty()) &&
389 settings->value("generateCache") == "true") {
394 else if (settings->value("generateCache") == "false") {
395 _settings->setValue("cached", "false");
400 Q_EMIT settingsChanged();
405 bool XdxfPlugin::getDictionaryInfo() {
406 QFile dictionaryFile(_settings->value("path"));
407 if(!QFile::exists(_settings->value("path"))
408 || !dictionaryFile.open(QFile::ReadOnly | QFile::Text)) {
409 Q_EMIT notify(Notify::Warning,
410 QString(tr("XDXF dictionary cannot be read from file")));
411 qDebug()<<"Error: could not open file";
416 QXmlStreamReader reader(&dictionaryFile);
417 reader.readNextStartElement();
418 if(reader.name()=="xdxf") {
420 if(reader.attributes().hasAttribute("lang_from"))
421 _langFrom = reader.attributes().value("lang_from").toString();
422 if(reader.attributes().hasAttribute("lang_to"))
423 _langTo = reader.attributes().value("lang_to").toString();
425 reader.readNextStartElement();
426 if(reader.name()=="full_name")
427 _name=reader.readElementText();
429 qDebug()<<"no full_name";
430 reader.readNextStartElement();
431 if(reader.name()=="description")
432 _infoNote=reader.readElementText();
434 qDebug()<<"no description";
436 _dictionaryInfo= _name + " [" + _langFrom + "-"
439 dictionaryFile.close();
446 QIcon* XdxfPlugin::icon() {
451 int XdxfPlugin::countWords() {
454 QFile dictionaryFile(_settings->value("path"));
455 if(!QFile::exists(_settings->value("path"))
456 || !dictionaryFile.open(QFile::ReadOnly | QFile::Text)) {
457 Q_EMIT notify(Notify::Warning,
458 QString(tr("XDXF file cannot be read for %1 dictionary")
460 qDebug()<<"Error: could not open file";
464 dictionaryFile.seek(0);
469 while(!dictionaryFile.atEnd()) {
470 line = dictionaryFile.readLine();
471 if(line.contains("<k>")) {
475 _wordsCount = wordsCount;
476 dictionaryFile.close();
481 bool XdxfPlugin::makeCache(QString) {
483 XdxfCachingDialog d(_dictDialog->lastDialogParent());
485 // qDebug()<<_dictDialog->lastDialogParent();
487 connect(&d, SIGNAL(cancelCaching()),
489 connect(this, SIGNAL(updateCachingProgress(int,int)),
490 &d, SLOT(updateCachingProgress(int,int)));
494 QCoreApplication::processEvents();
495 QFileInfo dictFileN(_settings->value("path"));
499 /*create cache file name*/
502 cachePathN = QDir::homePath() + "/.mdictionary/"
503 + dictFileN.completeBaseName()+"."
504 +QString::number(i) + ".cache";
506 } while(QFile::exists(cachePathN));
508 db_name = _settings->value("type") + cachePathN;
509 db = QSqlDatabase::addDatabase("QSQLITE",db_name);
511 /*checke errors (File open and db open)*/
512 QFile dictionaryFile(dictFileN.filePath());
513 if (!QFile::exists(_settings->value("path"))
514 || !dictionaryFile.open(QFile::ReadOnly | QFile::Text)) {
515 Q_EMIT updateCachingProgress(100, 0);
516 Q_EMIT notify(Notify::Warning,
517 QString(tr("XDXF file cannot be read for %1 dictionary")
521 QXmlStreamReader reader(&dictionaryFile);
522 db.setDatabaseName(cachePathN);
524 qDebug() << "Database error" << db.lastError().text() << endl;
525 Q_EMIT updateCachingProgress(100, 0);
526 Q_EMIT notify(Notify::Warning, QString(tr("Cache database cannot be "
527 "opened for %1 dictionary. Searching in XDXF file. "
528 "You may want to recache.").arg(name())));
533 QCoreApplication::processEvents();
535 cur.exec("PRAGMA synchronous = 0");
536 cur.exec("drop table dict");
537 QCoreApplication::processEvents();
538 cur.exec("create table dict(word text, normalized text ,translation text)");
548 _settings->setValue("strip_accents", "true");
551 /*add all words to db*/
552 while (!reader.atEnd() && !stopped) {
554 QCoreApplication::processEvents();
556 if(reader.tokenType() == QXmlStreamReader::StartElement) {
557 if(reader.name()=="k"){
558 readKey = reader.readElementText();
564 while(reader.name()!="ar" && !reader.atEnd()) {
565 if(reader.name()!="" && reader.name()!="k") {
566 if(reader.tokenType()==QXmlStreamReader::EndElement)
568 if(reader.tokenType()==QXmlStreamReader::StartElement)
570 temp+=reader.name().toString();
571 if(reader.name().toString()=="c"
572 && reader.tokenType()==QXmlStreamReader::StartElement) {
574 + reader.attributes().value("c").toString()
579 temp+= reader.text().toString().replace("<","<").replace(">"
583 if(temp.at(0)==QChar('\n'))
585 temp="<key>" + readKey + "</key>" + "<t>" + temp+ "</t>";
587 cur.prepare("insert into dict values(?,?,?)");
588 cur.addBindValue(readKey.toLower());
589 cur.addBindValue(removeAccents(readKey).toLower());
590 cur.addBindValue(temp);
593 int prog = counter*100/_wordsCount;
594 if(prog % 2 == 0 && lastProg != prog) {
595 Q_EMIT updateCachingProgress(prog,timer.restart());
601 cur.exec("select count(*) from dict");
603 /*checke errors (wrong number of added words)*/
605 if(!cur.next() || countWords() != cur.value(0).toInt()) {
606 Q_EMIT updateCachingProgress(100, timer.restart());
607 Q_EMIT notify(Notify::Warning,
608 QString(tr("Database caching error, please try again.")));
610 _settings->setValue("cache_path", cachePathN);
613 _settings->setValue("cache_path","");
617 _settings->setValue("cache_path", cachePathN);
618 _settings->setValue("cached", "true");
620 disconnect(&d, SIGNAL(cancelCaching()),
622 disconnect(this, SIGNAL(updateCachingProgress(int,int)),
623 &d, SLOT(updateCachingProgress(int,int)));
628 void XdxfPlugin::clean() {
629 if(QFile::exists(_settings->value("cache_path"))) {
630 QFile(_settings->value("cache_path")).remove();
631 QSqlDatabase::removeDatabase(db_name);
636 Q_EXPORT_PLUGIN2(xdxf, XdxfPlugin)