fix bug (duplication of dictionarys in xdxf downloader)
[mdictionary] / src / plugins / xdxf / xdxfplugin.cpp
index 9a29f8a..e0ca9de 100644 (file)
     Copyright 2010 Comarch S.A.
 
 *******************************************************************************/
-
-/*! \file xdxfplugin.cpp
-\author Jakub Jaszczynski <j.j.jaszczynski@gmail.com>
+/*!
+    \file xdxfplugin.cpp
+    \author Jakub Jaszczynski <j.j.jaszczynski@gmail.com>
 */
 
 #include "xdxfplugin.h"
 #include <QDebug>
-#include "../../common/Notify.h"
+#include "../../include/Notify.h"
+#include "DownloadDict.h"
+#include "XdxfDictDownloader.h"
+
+XdxfDictDownloader XdxfPlugin::dictDownloader;
+
+
+bool XdxfPlugin::dictDownloaderInitialized = false;
+
 
 XdxfPlugin::XdxfPlugin(QObject *parent) : CommonDictInterface(parent),
                     _langFrom(""), _langTo(""),_name(""), _infoNote("") {
     _settings = new Settings();
-    _dictDialog = new XdxfDictDialog(this);
-    cachingDialog = new XdxfCachingDialog(this);
+    _dictDialog = new XdxfDictDialog(this, this);
+
+    connect(_dictDialog, SIGNAL(notify(Notify::NotifyType,QString)),
+            this, SIGNAL(notify(Notify::NotifyType,QString)));
+
+    if(!dictDownloaderInitialized) {
+        connect(&dictDownloader, SIGNAL(notify(Notify::NotifyType,QString)),
+                this, SIGNAL(notify(Notify::NotifyType,QString)));
+        dictDownloaderInitialized = true;
+    }
 
     _settings->setValue("type","xdxf");
-    _icon = QIcon(":/icons/xdxf.png");
+    _icon = QIcon("/usr/share/mdictionary/xdxf.png");
     _wordsCount = -1;
     stopped = false;
 
-    connect(cachingDialog, SIGNAL(cancelCaching()),
-            this, SLOT(stop()));
-    connect(this, SIGNAL(updateCachingProgress(int,int)),
-            cachingDialog, SLOT(updateCachingProgress(int,int)));
     initAccents();
 }
 
 
+void XdxfPlugin::retranslate() {
+    QString locale = QLocale::system().name();
+    QTranslator *translator = new QTranslator(this);
+
+    if(!translator->load(":/xdxf/translations/" + locale)) {
+        translator->load(":/xdxf/translations/en_US");
+    }
+    QCoreApplication::installTranslator(translator);
+}
+
+
 XdxfPlugin::~XdxfPlugin() {
     delete _settings;
-    delete cachingDialog;
     delete _dictDialog;
 }
 
@@ -74,7 +96,7 @@ QString XdxfPlugin::type() const {
 
 
 QString XdxfPlugin::infoNote() const {
-    return  _infoNote;
+    return _infoNote;
 }
 
 
@@ -90,7 +112,6 @@ QList<Translation*> XdxfPlugin::searchWordList(QString word, int limit) {
 
 
 QList<Translation*> XdxfPlugin::searchWordListCache(QString word, int limit) {
-    int i=0;
     QSet<Translation*> translations;
     QString cacheFilePath = _settings->value("cache_path");
 
@@ -103,6 +124,7 @@ QList<Translation*> XdxfPlugin::searchWordListCache(QString word, int limit) {
         _settings->setValue("cached","false");
         return searchWordListFile(word, limit);
     }
+
     stopped = false;
     word = word.toLower();
     word = word.replace("*", "%");
@@ -121,21 +143,10 @@ QList<Translation*> XdxfPlugin::searchWordListCache(QString word, int limit) {
         cur.addBindValue(limit);
     cur.exec();
 
-    bool in = false;
-    while(cur.next() && (i<limit || limit==0 ) ) {
-        in = true;
-        bool ok=true;
-        Translation *tran;
-        foreach(tran,translations) {
-            if(tran->key().toLower()==cur.value(0).toString().toLower())
-                    ok=false;
-        }
-        if(ok) {  /*add key word to list*/
-            translations.insert(new TranslationXdxf(
-                    cur.value(0).toString().toLower(),
-                    _infoNote, this));
-            i++;
-        }
+    while(cur.next() && (translations.size()<limit || limit==0)) {
+       translations.insert(new TranslationXdxf(
+            cur.value(0).toString(),
+            _dictionaryInfo, this));
     }
     db.close();
     return translations.toList();
@@ -175,19 +186,10 @@ QList<Translation*> XdxfPlugin::searchWordListFile(QString word, int limit) {
                 readKey = reader.readElementText();
             if((regWord.exactMatch(readKey)
                     || regWord.exactMatch(removeAccents(readKey)))
-                    && (i<limit || limit==0)) {
-                bool ok=true;
-                Translation *tran;
-                foreach(tran,translations) {
-                    if(tran->key().toLower()==readKey.toLower())
-                        ok=false; /*if key is in the dictionary more that one */
-                }
-                if(ok) {  /*add key word to list*/
-                    translations<<(new TranslationXdxf(readKey.toLower(),
-                                    _infoNote,this));
-                    i++;
-                }
-                if(i>=limit && limit!=0)
+                    && (i<limit || limit==0) && !reader.atEnd())  {
+                translations<<(new TranslationXdxf(readKey.toLower(),
+                               _dictionaryInfo,this));
+                if(translations.size()==limit && limit!=0)
                     break;
             }
         }
@@ -228,11 +230,9 @@ QString XdxfPlugin::searchCache(QString key) {
     cur.exec();
     while(cur.next())
         result += cur.value(0).toString();
-
     db.close();
 
     return result;
-
 }
 
 
@@ -309,41 +309,33 @@ DictDialog* XdxfPlugin::dictDialog() {
 
 
 CommonDictInterface* XdxfPlugin::getNew(const Settings *settings) const {
-
-    qDebug()<<"tu";
     XdxfPlugin *plugin = new XdxfPlugin();
-    qDebug()<<"tu2";
-    if(settings){
-            qDebug()<<"tu3";
-        plugin->setSettings(settings);
-    }
-    return  plugin;
-}
 
+    connect(plugin, SIGNAL(notify(Notify::NotifyType,QString)),
+            this, SIGNAL(notify(Notify::NotifyType,QString)));
 
-bool XdxfPlugin::isAvailable() const {
-    return true;
-}
-
+    ((XdxfDictDialog*)plugin->dictDialog())->setLastDialogParent(_dictDialog->lastDialogParent());
 
-void XdxfPlugin::setHash(uint _hash) {
-    this->_hash=_hash;
+    if(settings && plugin->setSettings(settings)) {
+        disconnect(plugin, SIGNAL(notify(Notify::NotifyType,QString)),
+                this, SIGNAL(notify(Notify::NotifyType,QString)));
+        return plugin;
+    }
+    else {
+        disconnect(plugin, SIGNAL(notify(Notify::NotifyType,QString)),
+                this, SIGNAL(notify(Notify::NotifyType,QString)));
+        delete plugin;
+        return 0;
+    }
 }
 
 
-uint XdxfPlugin::hash() const {
-   return _hash;
+bool XdxfPlugin::isAvailable() const {
+    return true;
 }
 
 
 Settings* XdxfPlugin::settings() {
-/*
-    Settings *returnSettings=new Settings;
-    QStringList list = _settings->keys();
-    foreach(QString key, list)
-            returnSettings->setValue(key,_settings->value(key));
-    return returnSettings;
-*/
     return _settings;
 }
 
@@ -355,21 +347,32 @@ bool XdxfPlugin::isCached() {
 }
 
 
-void XdxfPlugin::setSettings(const Settings *settings) {
-    qDebug()<<"tu4";
+bool XdxfPlugin::setSettings(const Settings *settings) {
     if(settings) {
-        qDebug()<<"tu5";
         bool isPathChange=false;
         QString oldPath = _settings->value("path");
+        Settings *oldSettings =  new Settings ;
+
         if(oldPath != settings->value("path")) {
             if(oldPath!="" && _settings->value("cache_path")!="")
                 clean();
             isPathChange=true;
         }
 
-        foreach(QString key, settings->keys()) {
+        foreach(QString key, _settings->keys())
+            oldSettings->setValue(key, _settings->value(key));
+
+        foreach(QString key, settings->keys())
            if(key != "generateCache")
                _settings->setValue(key, settings->value(key));
+
+        if(!getDictionaryInfo()) {
+            Q_EMIT notify(Notify::Warning,
+                QString(tr("XDXF file is in wrong format")));
+            qDebug()<<"Error: xdxf file is in wrong format";
+            delete _settings;
+            _settings=oldSettings;
+            return false;
         }
 
         if(isPathChange) {
@@ -394,44 +397,52 @@ void XdxfPlugin::setSettings(const Settings *settings) {
         else if (settings->value("generateCache") == "false") {
             _settings->setValue("cached", "false");
         }
-
-        getDictionaryInfo();
     }
+    else
+        return false;
     Q_EMIT settingsChanged();
+    return true;
 }
 
 
-void XdxfPlugin::getDictionaryInfo() {
+bool XdxfPlugin::getDictionaryInfo() {
     QFile dictionaryFile(_settings->value("path"));
     if(!QFile::exists(_settings->value("path"))
                 || !dictionaryFile.open(QFile::ReadOnly | QFile::Text)) {
        Q_EMIT notify(Notify::Warning,
                QString(tr("XDXF dictionary cannot be read from file")));
         qDebug()<<"Error: could not open file";
-        return;
+        return false;
     }
 
+    bool okFormat=false;
     QXmlStreamReader reader(&dictionaryFile);
     reader.readNextStartElement();
     if(reader.name()=="xdxf") {
-      if(reader.attributes().hasAttribute("lang_from"))
-        _langFrom = reader.attributes().value("lang_from").toString();
-      if(reader.attributes().hasAttribute("lang_to"))
-        _langTo = reader.attributes().value("lang_to").toString();
+        okFormat=true;
+        if(reader.attributes().hasAttribute("lang_from"))
+            _langFrom = reader.attributes().value("lang_from").toString();
+        if(reader.attributes().hasAttribute("lang_to"))
+            _langTo = reader.attributes().value("lang_to").toString();
     }
     reader.readNextStartElement();
     if(reader.name()=="full_name")
         _name=reader.readElementText();
+    else
+        qDebug()<<"no full_name";
     reader.readNextStartElement();
     if(reader.name()=="description")
         _infoNote=reader.readElementText();
+    else
+        qDebug()<<"no description";
 
-    QString format = "png";
-    QString initialPath = QDir::currentPath() + "/xdxf." + format;
+    _dictionaryInfo= _name + " [" + _langFrom + "-"
+                + _langTo + "]";
 
-    _infoNote="path=\""+initialPath+"\"> \n" + _name + " [" + _langFrom + "-"
-                + _langTo + "] ( xdxf )";
     dictionaryFile.close();
+    if(okFormat)
+        return true;
+    return false;
 }
 
 
@@ -454,7 +465,6 @@ int XdxfPlugin::countWords() {
     }
 
     dictionaryFile.seek(0);
-
     long wordsCount = 0;
 
     QString line;
@@ -471,7 +481,14 @@ int XdxfPlugin::countWords() {
 
 
 bool XdxfPlugin::makeCache(QString) {
-    cachingDialog->setVisible(true);
+    XdxfCachingDialog d(_dictDialog->lastDialogParent());
+
+    connect(&d, SIGNAL(cancelCaching()),
+            this, SLOT(stop()));
+    connect(this, SIGNAL(updateCachingProgress(int,int)),
+            &d, SLOT(updateCachingProgress(int,int)));
+
+    d.show();
     QCoreApplication::processEvents();
     QFileInfo dictFileN(_settings->value("path"));
     QString cachePathN;
@@ -489,9 +506,6 @@ bool XdxfPlugin::makeCache(QString) {
     db_name = _settings->value("type") + cachePathN;
     db = QSqlDatabase::addDatabase("QSQLITE",db_name);
 
-    qDebug()<<QSqlDatabase::connectionNames().size();
-    foreach(QString name,QSqlDatabase::connectionNames())
-        qDebug()<<name;
     /*checke errors (File open and db open)*/
     QFile dictionaryFile(dictFileN.filePath());
     if (!QFile::exists(_settings->value("path"))
@@ -568,13 +582,13 @@ bool XdxfPlugin::makeCache(QString) {
             temp="<key>" + readKey + "</key>" + "<t>" + temp+ "</t>";
             match=false;
             cur.prepare("insert into dict values(?,?,?)");
-            cur.addBindValue(readKey);
-            cur.addBindValue(removeAccents(readKey));
+            cur.addBindValue(readKey.toLower());
+            cur.addBindValue(removeAccents(readKey).toLower());
             cur.addBindValue(temp);
             cur.exec();
             counter++;
             int prog = counter*100/_wordsCount;
-            if(prog % 5 == 0 && lastProg != prog) {
+            if(prog % 2 == 0 && lastProg != prog) {
                 Q_EMIT updateCachingProgress(prog,timer.restart());
                 lastProg = prog;
             }
@@ -582,21 +596,28 @@ bool XdxfPlugin::makeCache(QString) {
     }
     cur.exec("END;");
     cur.exec("select count(*) from dict");
-    cachingDialog->setVisible(false);
 
     /*checke errors (wrong number of added words)*/
     countWords();
     if(!cur.next() || countWords() != cur.value(0).toInt()) {
         Q_EMIT updateCachingProgress(100, timer.restart());
         Q_EMIT notify(Notify::Warning,
-                QString(tr("Database caching error, please try againg.")));
+                QString(tr("Database caching error, please try again.")));
         db.close();
+        _settings->setValue("cache_path", cachePathN);
+        if(stopped)
+            clean();
+        _settings->setValue("cache_path","");
         return false;
     }
 
     _settings->setValue("cache_path", cachePathN);
     _settings->setValue("cached", "true");
 
+    disconnect(&d, SIGNAL(cancelCaching()),
+            this, SLOT(stop()));
+    disconnect(this, SIGNAL(updateCachingProgress(int,int)),
+            &d, SLOT(updateCachingProgress(int,int)));
     db.close();
     return true;
 }