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"
30 XdxfPlugin::XdxfPlugin(QObject *parent) : CommonDictInterface(parent),
31 _langFrom(""), _langTo(""),_name(""), _infoNote("") {
32 _settings = new Settings();
33 _dictDialog = new XdxfDictDialog(this, this);
35 connect(_dictDialog, SIGNAL(notify(Notify::NotifyType,QString)),
36 this, SIGNAL(notify(Notify::NotifyType,QString)));
39 _settings->setValue("type","xdxf");
40 _icon = QIcon("/usr/share/mdictionary/xdxf.png");
47 void XdxfPlugin::retranslate() {
48 QString locale = QLocale::system().name();
50 QTranslator *translator = new QTranslator(this);
52 if(!translator->load(":/xdxf/translations/" + locale)) {
53 translator->load(":/xdxf/translations/en_US");
55 QCoreApplication::installTranslator(translator);
59 XdxfPlugin::~XdxfPlugin() {
65 QString XdxfPlugin::langFrom() const {
70 QString XdxfPlugin::langTo() const {
75 QString XdxfPlugin::name() const {
80 QString XdxfPlugin::type() const {
81 return QString("xdxf");
85 QString XdxfPlugin::infoNote() const {
90 QList<Translation*> XdxfPlugin::searchWordList(QString word, int limit) {
91 if( word.indexOf("*")==-1 && word.indexOf("?")==-1 &&
92 word.indexOf("_")==-1 && word.indexOf("%")==-1)
96 return searchWordListCache(word,limit);
97 return searchWordListFile(word, limit);
101 QList<Translation*> XdxfPlugin::searchWordListCache(QString word, int limit) {
103 QSet<Translation*> translations;
104 QString cacheFilePath = _settings->value("cache_path");
106 db.setDatabaseName(cacheFilePath);
107 if(!QFile::exists(cacheFilePath) || !db.open()) {
108 qDebug() << "Database error" << db.lastError().text() << endl;
109 Q_EMIT notify(Notify::Warning, QString(tr("Cache database cannot be "
110 "opened for %1 dictionary. Searching in XDXF file. "
111 "You may want to recache.").arg(name())));
112 _settings->setValue("cached","false");
113 return searchWordListFile(word, limit);
116 word = word.toLower();
117 word = word.replace("*", "%");
118 word = word.replace("?", "_");
122 cur.prepare("select word from dict where word like ? or normalized "
125 cur.prepare("select word from dict where word like ? or normalized "
127 cur.addBindValue(word);
128 cur.addBindValue(word);
130 cur.addBindValue(limit);
134 while(cur.next() && (i<limit || limit==0 ) ) {
138 foreach(tran,translations) {
139 if(tran->key().toLower()==cur.value(0).toString().toLower())
142 if(ok) { /*add key word to list*/
143 translations.insert(new TranslationXdxf(
144 cur.value(0).toString().toLower(),
145 _dictionaryInfo, this));
150 return translations.toList();
154 QList<Translation*> XdxfPlugin::searchWordListFile(QString word, int limit) {
155 QSet<Translation*> translations;
156 QFile dictionaryFile(_settings->value("path"));
157 word = word.toLower();
160 QRegExp regWord(word);
161 regWord.setCaseSensitivity(Qt::CaseInsensitive);
162 regWord.setPatternSyntax(QRegExp::Wildcard);
164 /*check xdxf file exist*/
165 if(!QFile::exists(_settings->value("path"))
166 || !dictionaryFile.open(QFile::ReadOnly | QFile::Text)) {
167 qDebug()<<"Error: could not open file";
168 Q_EMIT notify(Notify::Warning,
169 QString(tr("XDXF file cannot be read for %1").arg(name())));
170 return translations.toList();
173 QXmlStreamReader reader(&dictionaryFile);
177 /*search words list*/
178 while(!reader.atEnd() && !stopped){
179 reader.readNextStartElement();
180 if(reader.name()=="ar") {
181 while(reader.name()!="k" && !reader.atEnd())
182 reader.readNextStartElement();
184 readKey = reader.readElementText();
185 if((regWord.exactMatch(readKey)
186 || regWord.exactMatch(removeAccents(readKey)))
187 && (i<limit || limit==0)) {
190 foreach(tran,translations) {
191 if(tran->key().toLower()==readKey.toLower())
192 ok=false; /*if key is in the dictionary more that one */
194 if(ok) { /*add key word to list*/
195 translations<<(new TranslationXdxf(readKey.toLower(),
196 _dictionaryInfo,this));
199 if(i>=limit && limit!=0)
203 this->thread()->yieldCurrentThread();
206 dictionaryFile.close();
207 return translations.toList();
211 QString XdxfPlugin::search(QString key) {
213 return searchCache(key);
214 return searchFile(key);
218 QString XdxfPlugin::searchCache(QString key) {
220 QString cacheFilePath = _settings->value("cache_path");
221 db.setDatabaseName(cacheFilePath);
224 if(!QFile::exists(cacheFilePath) || !db.open()) {
225 qDebug() << "Database error" << db.lastError().text() << endl;
226 Q_EMIT notify(Notify::Warning, QString(tr("Cache database cannot be "
227 "opened for %1 dictionary. Searching in XDXF file. "
228 "You may want to recache.").arg(name())));
229 _settings->setValue("cached","false");
230 return searchFile(key);
235 cur.prepare("select translation from dict where word like ?");
236 cur.addBindValue(key);
239 result += cur.value(0).toString();
248 QString XdxfPlugin::searchFile(QString key) {
249 QFile dictionaryFile(_settings->value("path"));
250 QString resultString("");
253 /*check xdxf file exist*/
254 if(!QFile::exists(_settings->value("path"))
255 || !dictionaryFile.open(QFile::ReadOnly | QFile::Text)) {
256 Q_EMIT notify(Notify::Warning,
257 QString(tr("XDXF file cannot be read for %1").arg(name())));
258 qDebug()<<"Error: could not open file";
262 QXmlStreamReader reader(&dictionaryFile);
267 /*search translations for word*/
268 while (!reader.atEnd()&& !stopped) {
270 if(reader.tokenType() == QXmlStreamReader::StartElement) {
271 if(reader.name()=="k") {
272 readKey = reader.readElementText();
273 if(readKey.toLower()==key.toLower())
279 while(reader.name()!="ar" && !reader.atEnd()) {
280 if(reader.name()!="" && reader.name()!="k") {
281 if(reader.tokenType()==QXmlStreamReader::EndElement)
283 if(reader.tokenType()==QXmlStreamReader::StartElement)
285 temp+=reader.name().toString();
286 if(reader.name().toString()=="c" &&
287 reader.tokenType()==QXmlStreamReader::StartElement)
288 temp= temp + " c=\"" + reader.attributes().
289 value("c").toString() + "\"";
292 temp+= reader.text().toString().replace("<","<").
296 if(temp.at(0)==QChar('\n'))
298 resultString+="<key>" + readKey +"</key>";
299 resultString+="<t>" + temp + "</t>";
302 this->thread()->yieldCurrentThread();
305 dictionaryFile.close();
310 void XdxfPlugin::stop() {
316 DictDialog* XdxfPlugin::dictDialog() {
321 CommonDictInterface* XdxfPlugin::getNew(const Settings *settings) const {
322 XdxfPlugin *plugin = new XdxfPlugin();
324 connect(plugin, SIGNAL(notify(Notify::NotifyType,QString)),
325 this, SIGNAL(notify(Notify::NotifyType,QString)));
327 ((XdxfDictDialog*)plugin->dictDialog())->setLastDialogParent(_dictDialog->lastDialogParent());
331 if(settings && plugin->setSettings(settings)) {
333 disconnect(plugin, SIGNAL(notify(Notify::NotifyType,QString)),
334 this, SIGNAL(notify(Notify::NotifyType,QString)));
338 disconnect(plugin, SIGNAL(notify(Notify::NotifyType,QString)),
339 this, SIGNAL(notify(Notify::NotifyType,QString)));
346 bool XdxfPlugin::isAvailable() const {
351 Settings* XdxfPlugin::settings() {
356 bool XdxfPlugin::isCached() {
357 if(_settings->value("cached") == "true")
363 bool XdxfPlugin::setSettings(const Settings *settings) {
365 bool isPathChange=false;
366 QString oldPath = _settings->value("path");
367 Settings *oldSettings = new Settings ;
369 if(oldPath != settings->value("path")) {
370 if(oldPath!="" && _settings->value("cache_path")!="")
375 foreach(QString key, _settings->keys())
376 oldSettings->setValue(key, _settings->value(key));
378 foreach(QString key, settings->keys()) {
379 if(key != "generateCache")
380 _settings->setValue(key, settings->value(key));
383 if(!getDictionaryInfo()) {
384 Q_EMIT notify(Notify::Warning,
385 QString(tr("XDXF file is in wrong format")));
386 qDebug()<<"Error: xdxf file is in wrong format";
388 _settings=oldSettings;
395 _settings->setValue("cached","false");
396 if(_settings->value("cached")=="true"
397 && _settings->value("cache_path")!="") {
398 db_name = _settings->value("type")
399 + _settings->value("cache_path");
400 db = QSqlDatabase::addDatabase("QSQLITE",db_name);
404 if((_settings->value("cached") == "false" ||
405 _settings->value("cached").isEmpty()) &&
406 settings->value("generateCache") == "true") {
411 else if (settings->value("generateCache") == "false") {
412 _settings->setValue("cached", "false");
417 Q_EMIT settingsChanged();
422 bool XdxfPlugin::getDictionaryInfo() {
423 QFile dictionaryFile(_settings->value("path"));
424 if(!QFile::exists(_settings->value("path"))
425 || !dictionaryFile.open(QFile::ReadOnly | QFile::Text)) {
426 Q_EMIT notify(Notify::Warning,
427 QString(tr("XDXF dictionary cannot be read from file")));
428 qDebug()<<"Error: could not open file";
433 QXmlStreamReader reader(&dictionaryFile);
434 reader.readNextStartElement();
435 if(reader.name()=="xdxf") {
437 if(reader.attributes().hasAttribute("lang_from"))
438 _langFrom = reader.attributes().value("lang_from").toString();
439 if(reader.attributes().hasAttribute("lang_to"))
440 _langTo = reader.attributes().value("lang_to").toString();
442 reader.readNextStartElement();
443 if(reader.name()=="full_name")
444 _name=reader.readElementText();
446 qDebug()<<"no full_name";
447 reader.readNextStartElement();
448 if(reader.name()=="description")
449 _infoNote=reader.readElementText();
451 qDebug()<<"no description";
453 _dictionaryInfo= _name + " [" + _langFrom + "-"
456 dictionaryFile.close();
463 QIcon* XdxfPlugin::icon() {
468 int XdxfPlugin::countWords() {
471 QFile dictionaryFile(_settings->value("path"));
472 if(!QFile::exists(_settings->value("path"))
473 || !dictionaryFile.open(QFile::ReadOnly | QFile::Text)) {
474 Q_EMIT notify(Notify::Warning,
475 QString(tr("XDXF file cannot be read for %1 dictionary")
477 qDebug()<<"Error: could not open file";
481 dictionaryFile.seek(0);
486 while(!dictionaryFile.atEnd()) {
487 line = dictionaryFile.readLine();
488 if(line.contains("<k>")) {
492 _wordsCount = wordsCount;
493 dictionaryFile.close();
498 bool XdxfPlugin::makeCache(QString) {
500 XdxfCachingDialog d(_dictDialog->lastDialogParent());
502 // qDebug()<<_dictDialog->lastDialogParent();
504 connect(&d, SIGNAL(cancelCaching()),
506 connect(this, SIGNAL(updateCachingProgress(int,int)),
507 &d, SLOT(updateCachingProgress(int,int)));
511 QCoreApplication::processEvents();
512 QFileInfo dictFileN(_settings->value("path"));
516 /*create cache file name*/
519 cachePathN = QDir::homePath() + "/.mdictionary/"
520 + dictFileN.completeBaseName()+"."
521 +QString::number(i) + ".cache";
523 } while(QFile::exists(cachePathN));
525 db_name = _settings->value("type") + cachePathN;
526 db = QSqlDatabase::addDatabase("QSQLITE",db_name);
528 /*checke errors (File open and db open)*/
529 QFile dictionaryFile(dictFileN.filePath());
530 if (!QFile::exists(_settings->value("path"))
531 || !dictionaryFile.open(QFile::ReadOnly | QFile::Text)) {
532 Q_EMIT updateCachingProgress(100, 0);
533 Q_EMIT notify(Notify::Warning,
534 QString(tr("XDXF file cannot be read for %1 dictionary")
538 QXmlStreamReader reader(&dictionaryFile);
539 db.setDatabaseName(cachePathN);
541 qDebug() << "Database error" << db.lastError().text() << endl;
542 Q_EMIT updateCachingProgress(100, 0);
543 Q_EMIT notify(Notify::Warning, QString(tr("Cache database cannot be "
544 "opened for %1 dictionary. Searching in XDXF file. "
545 "You may want to recache.").arg(name())));
550 QCoreApplication::processEvents();
552 cur.exec("PRAGMA synchronous = 0");
553 cur.exec("drop table dict");
554 QCoreApplication::processEvents();
555 cur.exec("create table dict(word text, normalized text ,translation text)");
565 _settings->setValue("strip_accents", "true");
568 /*add all words to db*/
569 while (!reader.atEnd() && !stopped) {
571 QCoreApplication::processEvents();
573 if(reader.tokenType() == QXmlStreamReader::StartElement) {
574 if(reader.name()=="k"){
575 readKey = reader.readElementText();
581 while(reader.name()!="ar" && !reader.atEnd()) {
582 if(reader.name()!="" && reader.name()!="k") {
583 if(reader.tokenType()==QXmlStreamReader::EndElement)
585 if(reader.tokenType()==QXmlStreamReader::StartElement)
587 temp+=reader.name().toString();
588 if(reader.name().toString()=="c"
589 && reader.tokenType()==QXmlStreamReader::StartElement) {
591 + reader.attributes().value("c").toString()
596 temp+= reader.text().toString().replace("<","<").replace(">"
600 if(temp.at(0)==QChar('\n'))
602 temp="<key>" + readKey + "</key>" + "<t>" + temp+ "</t>";
604 cur.prepare("insert into dict values(?,?,?)");
605 cur.addBindValue(readKey);
606 cur.addBindValue(removeAccents(readKey));
607 cur.addBindValue(temp);
610 int prog = counter*100/_wordsCount;
611 if(prog % 2 == 0 && lastProg != prog) {
612 Q_EMIT updateCachingProgress(prog,timer.restart());
618 cur.exec("select count(*) from dict");
620 /*checke errors (wrong number of added words)*/
622 if(!cur.next() || countWords() != cur.value(0).toInt()) {
623 Q_EMIT updateCachingProgress(100, timer.restart());
624 Q_EMIT notify(Notify::Warning,
625 QString(tr("Database caching error, please try again.")));
627 _settings->setValue("cache_path", cachePathN);
630 _settings->setValue("cache_path","");
634 _settings->setValue("cache_path", cachePathN);
635 _settings->setValue("cached", "true");
637 disconnect(&d, SIGNAL(cancelCaching()),
639 disconnect(this, SIGNAL(updateCachingProgress(int,int)),
640 &d, SLOT(updateCachingProgress(int,int)));
645 void XdxfPlugin::clean() {
646 if(QFile::exists(_settings->value("cache_path"))) {
647 QFile(_settings->value("cache_path")).remove();
648 QSqlDatabase::removeDatabase(db_name);
653 Q_EXPORT_PLUGIN2(xdxf, XdxfPlugin)