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 "../../common/Notify.h"
30 XdxfPlugin::XdxfPlugin(QObject *parent) : CommonDictInterface(parent),
31 _langFrom(""), _langTo(""),_name(""), _infoNote("") {
32 _settings = new Settings();
33 _dictDialog = new XdxfDictDialog(this);
34 cachingDialog = new XdxfCachingDialog(this);
36 _settings->setValue("type","xdxf");
37 _icon = QIcon(":/icons/xdxf.png");
41 connect(cachingDialog, SIGNAL(cancelCaching()),
43 connect(this, SIGNAL(updateCachingProgress(int,int)),
44 cachingDialog, SLOT(updateCachingProgress(int,int)));
48 void XdxfPlugin::retranslate() {
49 QString locale = QLocale::system().name();
51 QTranslator *translator = new QTranslator(this);
54 translator->load(":/translations/dict_xdxf_pl");
56 translator->load(":/translations/dict_xdxf_en");
58 QCoreApplication::installTranslator(translator);
62 XdxfPlugin::~XdxfPlugin() {
69 QString XdxfPlugin::langFrom() const {
74 QString XdxfPlugin::langTo() const {
79 QString XdxfPlugin::name() const {
84 QString XdxfPlugin::type() const {
85 return QString("xdxf");
89 QString XdxfPlugin::infoNote() const {
94 QList<Translation*> XdxfPlugin::searchWordList(QString word, int limit) {
95 if( word.indexOf("*")==-1 && word.indexOf("?")==-1 &&
96 word.indexOf("_")==-1 && word.indexOf("%")==-1)
100 return searchWordListCache(word,limit);
101 return searchWordListFile(word, limit);
105 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);
138 while(cur.next() && (i<limit || limit==0 ) ) {
142 foreach(tran,translations) {
143 if(tran->key().toLower()==cur.value(0).toString().toLower())
146 if(ok) { /*add key word to list*/
147 translations.insert(new TranslationXdxf(
148 cur.value(0).toString().toLower(),
154 return translations.toList();
158 QList<Translation*> XdxfPlugin::searchWordListFile(QString word, int limit) {
159 QSet<Translation*> translations;
160 QFile dictionaryFile(_settings->value("path"));
161 word = word.toLower();
164 QRegExp regWord(word);
165 regWord.setCaseSensitivity(Qt::CaseInsensitive);
166 regWord.setPatternSyntax(QRegExp::Wildcard);
168 /*check xdxf file exist*/
169 if(!QFile::exists(_settings->value("path"))
170 || !dictionaryFile.open(QFile::ReadOnly | QFile::Text)) {
171 qDebug()<<"Error: could not open file";
172 Q_EMIT notify(Notify::Warning,
173 QString(tr("XDXF file cannot be read for %1").arg(name())));
174 return translations.toList();
177 QXmlStreamReader reader(&dictionaryFile);
181 /*search words list*/
182 while(!reader.atEnd() && !stopped){
183 reader.readNextStartElement();
184 if(reader.name()=="ar") {
185 while(reader.name()!="k" && !reader.atEnd())
186 reader.readNextStartElement();
188 readKey = reader.readElementText();
189 if((regWord.exactMatch(readKey)
190 || regWord.exactMatch(removeAccents(readKey)))
191 && (i<limit || limit==0)) {
194 foreach(tran,translations) {
195 if(tran->key().toLower()==readKey.toLower())
196 ok=false; /*if key is in the dictionary more that one */
198 if(ok) { /*add key word to list*/
199 translations<<(new TranslationXdxf(readKey.toLower(),
203 if(i>=limit && limit!=0)
207 this->thread()->yieldCurrentThread();
210 dictionaryFile.close();
211 return translations.toList();
215 QString XdxfPlugin::search(QString key) {
217 return searchCache(key);
218 return searchFile(key);
222 QString XdxfPlugin::searchCache(QString key) {
224 QString cacheFilePath = _settings->value("cache_path");
225 db.setDatabaseName(cacheFilePath);
228 if(!QFile::exists(cacheFilePath) || !db.open()) {
229 qDebug() << "Database error" << db.lastError().text() << endl;
230 Q_EMIT notify(Notify::Warning, QString(tr("Cache database cannot be "
231 "opened for %1 dictionary. Searching in XDXF file. "
232 "You may want to recache.").arg(name())));
233 _settings->setValue("cached","false");
234 return searchFile(key);
239 cur.prepare("select translation from dict where word like ?");
240 cur.addBindValue(key);
243 result += cur.value(0).toString();
252 QString XdxfPlugin::searchFile(QString key) {
253 QFile dictionaryFile(_settings->value("path"));
254 QString resultString("");
257 /*check xdxf file exist*/
258 if(!QFile::exists(_settings->value("path"))
259 || !dictionaryFile.open(QFile::ReadOnly | QFile::Text)) {
260 Q_EMIT notify(Notify::Warning,
261 QString(tr("XDXF file cannot be read for %1").arg(name())));
262 qDebug()<<"Error: could not open file";
266 QXmlStreamReader reader(&dictionaryFile);
271 /*search translations for word*/
272 while (!reader.atEnd()&& !stopped) {
274 if(reader.tokenType() == QXmlStreamReader::StartElement) {
275 if(reader.name()=="k") {
276 readKey = reader.readElementText();
277 if(readKey.toLower()==key.toLower())
283 while(reader.name()!="ar" && !reader.atEnd()) {
284 if(reader.name()!="" && reader.name()!="k") {
285 if(reader.tokenType()==QXmlStreamReader::EndElement)
287 if(reader.tokenType()==QXmlStreamReader::StartElement)
289 temp+=reader.name().toString();
290 if(reader.name().toString()=="c" &&
291 reader.tokenType()==QXmlStreamReader::StartElement)
292 temp= temp + " c=\"" + reader.attributes().
293 value("c").toString() + "\"";
296 temp+= reader.text().toString().replace("<","<").
300 if(temp.at(0)==QChar('\n'))
302 resultString+="<key>" + readKey +"</key>";
303 resultString+="<t>" + temp + "</t>";
306 this->thread()->yieldCurrentThread();
309 dictionaryFile.close();
314 void XdxfPlugin::stop() {
319 DictDialog* XdxfPlugin::dictDialog() {
324 CommonDictInterface* XdxfPlugin::getNew(const Settings *settings) const {
325 XdxfPlugin *plugin = new XdxfPlugin();
326 if(settings && plugin->setSettings(settings))
330 return new XdxfPlugin();
335 bool XdxfPlugin::isAvailable() const {
340 void XdxfPlugin::setHash(uint _hash) {
345 uint XdxfPlugin::hash() const {
350 Settings* XdxfPlugin::settings() {
352 Settings *returnSettings=new Settings;
353 QStringList list = _settings->keys();
354 foreach(QString key, list)
355 returnSettings->setValue(key,_settings->value(key));
356 return returnSettings;
362 bool XdxfPlugin::isCached() {
363 if(_settings->value("cached") == "true")
369 bool XdxfPlugin::setSettings(const Settings *settings) {
371 bool isPathChange=false;
372 QString oldPath = _settings->value("path");
373 if(oldPath != settings->value("path")) {
374 if(oldPath!="" && _settings->value("cache_path")!="")
379 foreach(QString key, settings->keys()) {
380 if(key != "generateCache")
381 _settings->setValue(key, settings->value(key));
384 if(!getDictionaryInfo()) {
385 Q_EMIT notify(Notify::Warning,
386 QString(tr("XDXF file is in wrong format")));
387 qDebug()<<"Error: xdxf file is in wrong format";
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();
444 reader.readNextStartElement();
445 if(reader.name()=="description")
446 _infoNote=reader.readElementText();
448 QString format = "png";
449 QString initialPath = QDir::currentPath() + "/xdxf." + format;
451 _infoNote="path=\""+initialPath+"\"> \n" + _name + " [" + _langFrom + "-"
452 + _langTo + "] ( xdxf )";
453 dictionaryFile.close();
460 QIcon* XdxfPlugin::icon() {
465 int XdxfPlugin::countWords() {
468 QFile dictionaryFile(_settings->value("path"));
469 if(!QFile::exists(_settings->value("path"))
470 || !dictionaryFile.open(QFile::ReadOnly | QFile::Text)) {
471 Q_EMIT notify(Notify::Warning,
472 QString(tr("XDXF file cannot be read for %1 dictionary")
474 qDebug()<<"Error: could not open file";
478 dictionaryFile.seek(0);
483 while(!dictionaryFile.atEnd()) {
484 line = dictionaryFile.readLine();
485 if(line.contains("<k>")) {
489 _wordsCount = wordsCount;
490 dictionaryFile.close();
495 bool XdxfPlugin::makeCache(QString) {
496 cachingDialog->setVisible(true);
497 QCoreApplication::processEvents();
498 QFileInfo dictFileN(_settings->value("path"));
502 /*create cache file name*/
505 cachePathN = QDir::homePath() + "/.mdictionary/"
506 + dictFileN.completeBaseName()+"."
507 +QString::number(i) + ".cache";
509 } while(QFile::exists(cachePathN));
511 db_name = _settings->value("type") + cachePathN;
512 db = QSqlDatabase::addDatabase("QSQLITE",db_name);
514 qDebug()<<QSqlDatabase::connectionNames().size();
515 foreach(QString name,QSqlDatabase::connectionNames())
517 /*checke errors (File open and db open)*/
518 QFile dictionaryFile(dictFileN.filePath());
519 if (!QFile::exists(_settings->value("path"))
520 || !dictionaryFile.open(QFile::ReadOnly | QFile::Text)) {
521 Q_EMIT updateCachingProgress(100, 0);
522 Q_EMIT notify(Notify::Warning,
523 QString(tr("XDXF file cannot be read for %1 dictionary")
527 QXmlStreamReader reader(&dictionaryFile);
528 db.setDatabaseName(cachePathN);
530 qDebug() << "Database error" << db.lastError().text() << endl;
531 Q_EMIT updateCachingProgress(100, 0);
532 Q_EMIT notify(Notify::Warning, QString(tr("Cache database cannot be "
533 "opened for %1 dictionary. Searching in XDXF file. "
534 "You may want to recache.").arg(name())));
539 QCoreApplication::processEvents();
541 cur.exec("PRAGMA synchronous = 0");
542 cur.exec("drop table dict");
543 QCoreApplication::processEvents();
544 cur.exec("create table dict(word text, normalized text ,translation text)");
554 _settings->setValue("strip_accents", "true");
557 /*add all words to db*/
558 while (!reader.atEnd() && !stopped) {
559 QCoreApplication::processEvents();
561 if(reader.tokenType() == QXmlStreamReader::StartElement) {
562 if(reader.name()=="k"){
563 readKey = reader.readElementText();
569 while(reader.name()!="ar" && !reader.atEnd()) {
570 if(reader.name()!="" && reader.name()!="k") {
571 if(reader.tokenType()==QXmlStreamReader::EndElement)
573 if(reader.tokenType()==QXmlStreamReader::StartElement)
575 temp+=reader.name().toString();
576 if(reader.name().toString()=="c"
577 && reader.tokenType()==QXmlStreamReader::StartElement) {
579 + reader.attributes().value("c").toString()
584 temp+= reader.text().toString().replace("<","<").replace(">"
588 if(temp.at(0)==QChar('\n'))
590 temp="<key>" + readKey + "</key>" + "<t>" + temp+ "</t>";
592 cur.prepare("insert into dict values(?,?,?)");
593 cur.addBindValue(readKey);
594 cur.addBindValue(removeAccents(readKey));
595 cur.addBindValue(temp);
598 int prog = counter*100/_wordsCount;
599 if(prog % 5 == 0 && lastProg != prog) {
600 Q_EMIT updateCachingProgress(prog,timer.restart());
606 cur.exec("select count(*) from dict");
607 cachingDialog->setVisible(false);
609 /*checke errors (wrong number of added words)*/
611 if(!cur.next() || countWords() != cur.value(0).toInt()) {
612 Q_EMIT updateCachingProgress(100, timer.restart());
613 Q_EMIT notify(Notify::Warning,
614 QString(tr("Database caching error, please try again.")));
619 _settings->setValue("cache_path", cachePathN);
620 _settings->setValue("cached", "true");
627 void XdxfPlugin::clean() {
628 if(QFile::exists(_settings->value("cache_path"))) {
629 QFile(_settings->value("cache_path")).remove();
630 QSqlDatabase::removeDatabase(db_name);
635 Q_EXPORT_PLUGIN2(xdxf, XdxfPlugin)