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);
128 word = word.toLower();
129 word = word.replace("*", "%");
130 word = word.replace("?", "_");
134 cur.prepare("select word from dict where word like ? or normalized "
137 cur.prepare("select word from dict where word like ? or normalized "
139 cur.addBindValue(word);
140 cur.addBindValue(word);
142 cur.addBindValue(limit);
145 while(cur.next() && (translations.size()<limit || limit==0)) {
146 translations.insert(new TranslationXdxf(
147 cur.value(0).toString(),
148 _dictionaryInfo, this));
151 return translations.toList();
155 QList<Translation*> XdxfPlugin::searchWordListFile(QString word, int limit) {
156 QSet<Translation*> translations;
157 QFile dictionaryFile(_settings->value("path"));
158 word = word.toLower();
161 QRegExp regWord(word);
162 regWord.setCaseSensitivity(Qt::CaseInsensitive);
163 regWord.setPatternSyntax(QRegExp::Wildcard);
165 /*check xdxf file exist*/
166 if(!QFile::exists(_settings->value("path"))
167 || !dictionaryFile.open(QFile::ReadOnly | QFile::Text)) {
168 qDebug()<<"Error: could not open file";
169 Q_EMIT notify(Notify::Warning,
170 QString(tr("XDXF file cannot be read for %1").arg(name())));
171 return translations.toList();
174 QXmlStreamReader reader(&dictionaryFile);
178 /*search words list*/
179 while(!reader.atEnd() && !stopped){
180 reader.readNextStartElement();
181 if(reader.name()=="ar") {
182 while(reader.name()!="k" && !reader.atEnd())
183 reader.readNextStartElement();
185 readKey = reader.readElementText();
186 if((regWord.exactMatch(readKey)
187 || regWord.exactMatch(removeAccents(readKey)))
188 && (i<limit || limit==0) && !reader.atEnd()) {
189 translations<<(new TranslationXdxf(readKey.toLower(),
190 _dictionaryInfo,this));
191 if(translations.size()==limit && limit!=0)
195 this->thread()->yieldCurrentThread();
198 dictionaryFile.close();
199 return translations.toList();
203 QString XdxfPlugin::search(QString key) {
205 return searchCache(key);
206 return searchFile(key);
210 QString XdxfPlugin::searchCache(QString key) {
212 QString cacheFilePath = _settings->value("cache_path");
213 db.setDatabaseName(cacheFilePath);
216 if(!QFile::exists(cacheFilePath) || !db.open()) {
217 qDebug() << "Database error" << db.lastError().text() << endl;
218 Q_EMIT notify(Notify::Warning, QString(tr("Cache database cannot be "
219 "opened for %1 dictionary. Searching in XDXF file. "
220 "You may want to recache.").arg(name())));
221 _settings->setValue("cached","false");
222 return searchFile(key);
227 cur.prepare("select translation from dict where word like ?");
228 cur.addBindValue(key);
231 result += cur.value(0).toString();
238 QString XdxfPlugin::searchFile(QString key) {
239 QFile dictionaryFile(_settings->value("path"));
240 QString resultString("");
243 /*check xdxf file exist*/
244 if(!QFile::exists(_settings->value("path"))
245 || !dictionaryFile.open(QFile::ReadOnly | QFile::Text)) {
246 Q_EMIT notify(Notify::Warning,
247 QString(tr("XDXF file cannot be read for %1").arg(name())));
248 qDebug()<<"Error: could not open file";
252 QXmlStreamReader reader(&dictionaryFile);
257 /*search translations for word*/
258 while (!reader.atEnd()&& !stopped) {
260 if(reader.tokenType() == QXmlStreamReader::StartElement) {
261 if(reader.name()=="k") {
262 readKey = reader.readElementText();
263 if(readKey.toLower()==key.toLower())
269 while(reader.name()!="ar" && !reader.atEnd()) {
270 if(reader.name()!="" && reader.name()!="k") {
271 if(reader.tokenType()==QXmlStreamReader::EndElement)
273 if(reader.tokenType()==QXmlStreamReader::StartElement)
275 temp+=reader.name().toString();
276 if(reader.name().toString()=="c" &&
277 reader.tokenType()==QXmlStreamReader::StartElement)
278 temp= temp + " c=\"" + reader.attributes().
279 value("c").toString() + "\"";
282 temp+= reader.text().toString().replace("<","<").
286 if(temp.at(0)==QChar('\n'))
288 resultString+="<key>" + readKey +"</key>";
289 resultString+="<t>" + temp + "</t>";
292 this->thread()->yieldCurrentThread();
295 dictionaryFile.close();
300 void XdxfPlugin::stop() {
305 DictDialog* XdxfPlugin::dictDialog() {
310 CommonDictInterface* XdxfPlugin::getNew(const Settings *settings) const {
311 XdxfPlugin *plugin = new XdxfPlugin();
313 connect(plugin, SIGNAL(notify(Notify::NotifyType,QString)),
314 this, SIGNAL(notify(Notify::NotifyType,QString)));
316 ((XdxfDictDialog*)plugin->dictDialog())->setLastDialogParent(_dictDialog->lastDialogParent());
318 if(settings && plugin->setSettings(settings)) {
319 disconnect(plugin, SIGNAL(notify(Notify::NotifyType,QString)),
320 this, SIGNAL(notify(Notify::NotifyType,QString)));
324 disconnect(plugin, SIGNAL(notify(Notify::NotifyType,QString)),
325 this, SIGNAL(notify(Notify::NotifyType,QString)));
332 bool XdxfPlugin::isAvailable() const {
337 Settings* XdxfPlugin::settings() {
342 bool XdxfPlugin::isCached() {
343 if(_settings->value("cached") == "true")
349 bool XdxfPlugin::setSettings(const Settings *settings) {
351 bool isPathChange=false;
352 QString oldPath = _settings->value("path");
353 Settings *oldSettings = new Settings ;
355 if(oldPath != settings->value("path")) {
356 if(oldPath!="" && _settings->value("cache_path")!="")
361 foreach(QString key, _settings->keys())
362 oldSettings->setValue(key, _settings->value(key));
364 foreach(QString key, settings->keys())
365 if(key != "generateCache")
366 _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);
470 while(!dictionaryFile.atEnd()) {
471 line = dictionaryFile.readLine();
472 if(line.contains("<k>")) {
476 _wordsCount = wordsCount;
477 dictionaryFile.close();
482 bool XdxfPlugin::makeCache(QString) {
483 XdxfCachingDialog d(_dictDialog->lastDialogParent());
485 connect(&d, SIGNAL(cancelCaching()),
487 connect(this, SIGNAL(updateCachingProgress(int,int)),
488 &d, SLOT(updateCachingProgress(int,int)));
491 QCoreApplication::processEvents();
492 QFileInfo dictFileN(_settings->value("path"));
496 /*create cache file name*/
499 cachePathN = QDir::homePath() + "/.mdictionary/"
500 + dictFileN.completeBaseName()+"."
501 +QString::number(i) + ".cache";
503 } while(QFile::exists(cachePathN));
505 db_name = _settings->value("type") + cachePathN;
506 db = QSqlDatabase::addDatabase("QSQLITE",db_name);
508 /*checke errors (File open and db open)*/
509 QFile dictionaryFile(dictFileN.filePath());
510 if (!QFile::exists(_settings->value("path"))
511 || !dictionaryFile.open(QFile::ReadOnly | QFile::Text)) {
512 Q_EMIT updateCachingProgress(100, 0);
513 Q_EMIT notify(Notify::Warning,
514 QString(tr("XDXF file cannot be read for %1 dictionary")
518 QXmlStreamReader reader(&dictionaryFile);
519 db.setDatabaseName(cachePathN);
521 qDebug() << "Database error" << db.lastError().text() << endl;
522 Q_EMIT updateCachingProgress(100, 0);
523 Q_EMIT notify(Notify::Warning, QString(tr("Cache database cannot be "
524 "opened for %1 dictionary. Searching in XDXF file. "
525 "You may want to recache.").arg(name())));
530 QCoreApplication::processEvents();
532 cur.exec("PRAGMA synchronous = 0");
533 cur.exec("drop table dict");
534 QCoreApplication::processEvents();
535 cur.exec("create table dict(word text, normalized text ,translation text)");
545 _settings->setValue("strip_accents", "true");
548 /*add all words to db*/
549 while (!reader.atEnd() && !stopped) {
550 QCoreApplication::processEvents();
552 if(reader.tokenType() == QXmlStreamReader::StartElement) {
553 if(reader.name()=="k"){
554 readKey = reader.readElementText();
560 while(reader.name()!="ar" && !reader.atEnd()) {
561 if(reader.name()!="" && reader.name()!="k") {
562 if(reader.tokenType()==QXmlStreamReader::EndElement)
564 if(reader.tokenType()==QXmlStreamReader::StartElement)
566 temp+=reader.name().toString();
567 if(reader.name().toString()=="c"
568 && reader.tokenType()==QXmlStreamReader::StartElement) {
570 + reader.attributes().value("c").toString()
575 temp+= reader.text().toString().replace("<","<").replace(">"
579 if(temp.at(0)==QChar('\n'))
581 temp="<key>" + readKey + "</key>" + "<t>" + temp+ "</t>";
583 cur.prepare("insert into dict values(?,?,?)");
584 cur.addBindValue(readKey.toLower());
585 cur.addBindValue(removeAccents(readKey).toLower());
586 cur.addBindValue(temp);
589 int prog = counter*100/_wordsCount;
590 if(prog % 2 == 0 && lastProg != prog) {
591 Q_EMIT updateCachingProgress(prog,timer.restart());
597 cur.exec("select count(*) from dict");
599 /*checke errors (wrong number of added words)*/
601 if(!cur.next() || countWords() != cur.value(0).toInt()) {
602 Q_EMIT updateCachingProgress(100, timer.restart());
603 Q_EMIT notify(Notify::Warning,
604 QString(tr("Database caching error, please try again.")));
606 _settings->setValue("cache_path", cachePathN);
609 _settings->setValue("cache_path","");
613 _settings->setValue("cache_path", cachePathN);
614 _settings->setValue("cached", "true");
616 disconnect(&d, SIGNAL(cancelCaching()),
618 disconnect(this, SIGNAL(updateCachingProgress(int,int)),
619 &d, SLOT(updateCachingProgress(int,int)));
625 void XdxfPlugin::clean() {
626 if(QFile::exists(_settings->value("cache_path"))) {
627 QFile(_settings->value("cache_path")).remove();
628 QSqlDatabase::removeDatabase(db_name);
633 Q_EXPORT_PLUGIN2(xdxf, XdxfPlugin)