Merge branch 'master' into google
[mdictionary] / trunk / src / plugins / xdxf / src / xdxfplugin.cpp
index f9a758d..d94ea20 100644 (file)
 #include "../../../includes/Notify.h"
 
 XdxfPlugin::XdxfPlugin(QObject *parent) : CommonDictInterface(parent),
-                    _langFrom(tr("")), _langTo(tr("")),_name(tr("")),
-                    _type(tr("xdxf")), _infoNote(tr("")) {
-    _wordsCount = -1;
+                    _langFrom(""), _langTo(""),_name(""), _infoNote("") {
     _settings = new Settings();
     _dictDialog = new XdxfDictDialog(this);
     cachingDialog = new XdxfCachingDialog(this);
 
+    _settings->setValue("type","xdxf");
+    _icon = QIcon(":/icons/xdxf.png");
+    _wordsCount = -1;
+    stopped = false;
 
     connect(cachingDialog, SIGNAL(cancelCaching()),
             this, SLOT(stop()));
     connect(this, SIGNAL(updateCachingProgress(int,int)),
             cachingDialog, SLOT(updateCachingProgress(int,int)));
-
-    _settings->setValue("type","xdxf");
-
-    stopped = false;
-
-    _icon = QIcon(":/icons/xdxf.png");
     initAccents();
 }
 
@@ -55,29 +51,35 @@ XdxfPlugin::~XdxfPlugin() {
     delete cachingDialog;
 }
 
+
 QString XdxfPlugin::langFrom() const {   
     return _langFrom;
 }
 
+
 QString XdxfPlugin::langTo() const {
     return  _langTo;
 }
 
+
 QString XdxfPlugin::name() const {
     return  _name;
 }
 
+
 QString XdxfPlugin::type() const {
-    return _type;
+    return QString("xdxf");
 }
 
+
 QString XdxfPlugin::infoNote() const {
     return  _infoNote;
 }
 
+
 QList<Translation*> XdxfPlugin::searchWordList(QString word, int limit) {
-    if(word.indexOf("*")==-1 && word.indexOf("?")==-1 && word.indexOf("_")==-1
-       && word.indexOf("%")==-1)
+    if( word.indexOf("*")==-1 && word.indexOf("?")==-1 &&
+        word.indexOf("_")==-1 && word.indexOf("%")==-1)
         word+="*";
 
     if(isCached())
@@ -85,20 +87,22 @@ QList<Translation*> XdxfPlugin::searchWordList(QString word, int limit) {
     return searchWordListFile(word, limit);
 }
 
+
 QList<Translation*> XdxfPlugin::searchWordListCache(QString word, int limit) {
     int i=0;
     QSet<Translation*> translations;
-
     QString cacheFilePath = _settings->value("cache_path");
+
+//  QSqlDatabase::removeDatabase(cacheFilePath);
     db.setDatabaseName(cacheFilePath);
-    if(!db.open()) {
+    if(!QFile::exists(cacheFilePath) || !db.open()) {
         qDebug() << "Database error" << db.lastError().text() << endl;
         Q_EMIT notify(Notify::Warning, QString(tr("Cache database cannot be "
                 "opened for %1 dictionary. Searching in XDXF file. "
                 "You may want to recache.").arg(name())));
+        _settings->setValue("cached","false");
         return searchWordListFile(word, limit);
     }
-
     stopped = false;
     word = word.toLower();
     word = word.replace("*", "%");
@@ -106,14 +110,17 @@ QList<Translation*> XdxfPlugin::searchWordListCache(QString word, int limit) {
 
     QSqlQuery cur(db);
     if(limit !=0)
-        cur.prepare("select word from dict where word like ? or normalized like ? limit ?");
+        cur.prepare("select word from dict where word like ? or normalized "
+                    "like ? limit ?");
     else
-        cur.prepare("select word from dict where word like ? or normalized like ?");
+        cur.prepare("select word from dict where word like ? or normalized "
+                    "like ?");
     cur.addBindValue(word);
     cur.addBindValue(word);
     if(limit !=0)
         cur.addBindValue(limit);
     cur.exec();
+
     bool in = false;
     while(cur.next() && (i<limit || limit==0 ) ) {
         in = true;
@@ -134,19 +141,20 @@ QList<Translation*> XdxfPlugin::searchWordListCache(QString word, int limit) {
     return translations.toList();
 }
 
+
 QList<Translation*> XdxfPlugin::searchWordListFile(QString word, int limit) {
-    QTime time;
     QSet<Translation*> translations;
-    QFile dictionaryFile(path);
-
+    QFile dictionaryFile(_settings->value("path"));
     word = word.toLower();
-    //word = removeAccents(word);
-
     stopped = false;
+
     QRegExp regWord(word);
     regWord.setCaseSensitivity(Qt::CaseInsensitive);
     regWord.setPatternSyntax(QRegExp::Wildcard);
-    if(!dictionaryFile.open(QFile::ReadOnly | QFile::Text)) {
+
+    /*check xdxf file exist*/
+    if(!QFile::exists(_settings->value("path"))
+                || !dictionaryFile.open(QFile::ReadOnly | QFile::Text)) {
         qDebug()<<"Error: could not open file";
         Q_EMIT notify(Notify::Warning,
                 QString(tr("XDXF file cannot be read for %1").arg(name())));
@@ -154,27 +162,29 @@ QList<Translation*> XdxfPlugin::searchWordListFile(QString word, int limit) {
     }
 
     QXmlStreamReader reader(&dictionaryFile);
-    /*search words list*/
-    QString a;
+    QString readKey;
     int i=0;
+
+    /*search words list*/
     while(!reader.atEnd() && !stopped){
         reader.readNextStartElement();
         if(reader.name()=="ar") {
             while(reader.name()!="k" && !reader.atEnd())
                 reader.readNextStartElement();
             if(!reader.atEnd())
-                a = reader.readElementText();
-            if((regWord.exactMatch(a) || regWord.exactMatch(removeAccents(a))) &&
-                    (i<limit || limit==0)) {
+                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()==a.toLower())
-                        ok=false;  /*if key word is in the dictionary more that one */
+                    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(a.toLower(),
-                                _infoNote,this));
+                    translations<<(new TranslationXdxf(readKey.toLower(),
+                                    _infoNote,this));
                     i++;
                 }
                 if(i>=limit && limit!=0)
@@ -188,24 +198,26 @@ QList<Translation*> XdxfPlugin::searchWordListFile(QString word, int limit) {
     return translations.toList();
 }
 
+
 QString XdxfPlugin::search(QString key) {
-//    if(_settings->value("cached") == "true")
     if(isCached())
         return searchCache(key);
     return searchFile(key);
 }
 
+
 QString XdxfPlugin::searchCache(QString key) {
     QString result("");
     QString cacheFilePath = _settings->value("cache_path");
     db.setDatabaseName(cacheFilePath);
     key = key.toLower();
 
-    if(!db.open()) {
+    if(!QFile::exists(cacheFilePath) || !db.open()) {
         qDebug() << "Database error" << db.lastError().text() << endl;
         Q_EMIT notify(Notify::Warning, QString(tr("Cache database cannot be "
                 "opened for %1 dictionary. Searching in XDXF file. "
                 "You may want to recache.").arg(name())));
+        _settings->setValue("cached","false");
         return searchFile(key);
     }
 
@@ -223,27 +235,33 @@ QString XdxfPlugin::searchCache(QString key) {
 
 }
 
+
 QString XdxfPlugin::searchFile(QString key) {
-    key = key.toLower();
-    QFile dictionaryFile(path);
+    QFile dictionaryFile(_settings->value("path"));
     QString resultString("");
-    if(!dictionaryFile.open(QFile::ReadOnly | QFile::Text)) {
+    key = key.toLower();
+
+    /*check xdxf file exist*/
+    if(!QFile::exists(_settings->value("path"))
+                || !dictionaryFile.open(QFile::ReadOnly | QFile::Text)) {
         Q_EMIT notify(Notify::Warning,
                 QString(tr("XDXF file cannot be read for %1").arg(name())));
         qDebug()<<"Error: could not open file";
         return "";
     }
-    QXmlStreamReader reader(&dictionaryFile);
-    QString a;
 
+    QXmlStreamReader reader(&dictionaryFile);
+    QString readKey;
     bool match =false;
     stopped = false;
+
+    /*search translations for word*/
     while (!reader.atEnd()&& !stopped) {
         reader.readNext();
         if(reader.tokenType() == QXmlStreamReader::StartElement) {
             if(reader.name()=="k") {
-                a = reader.readElementText();
-                if(a.toLower()==key.toLower())
+                readKey = reader.readElementText();
+                if(readKey.toLower()==key.toLower())
                     match = true;
             }
         }
@@ -268,7 +286,7 @@ QString XdxfPlugin::searchFile(QString key) {
             }
             if(temp.at(0)==QChar('\n'))
                 temp.remove(0,1);
-            resultString+="<key>" + a +"</key>";
+            resultString+="<key>" + readKey +"</key>";
             resultString+="<t>" + temp + "</t>";
             match=false;
         }
@@ -276,73 +294,49 @@ QString XdxfPlugin::searchFile(QString key) {
     }
     stopped=false;
     dictionaryFile.close();
-
     return resultString;
 }
 
+
 void XdxfPlugin::stop() {
     stopped=true;
 }
 
+
 DictDialog* XdxfPlugin::dictDialog() {
      return _dictDialog;
 }
 
-void XdxfPlugin::setPath(QString path){
-    if(this->path!=path && this->path!="" && _settings->value("cache_path")!="")
-        clean();
-    this->path=path;
-    _settings->setValue("path",path);
-    //getDictionaryInfo();
-}
 
 CommonDictInterface* XdxfPlugin::getNew(const Settings *settings) const {
     XdxfPlugin *plugin = new XdxfPlugin();
     if(settings){
-        plugin->setPath(settings->value("path"));
-        QStringList list = settings->keys();
-
-        plugin->db_name = plugin->_settings->value("type")
-                         + plugin->_settings->value("path");
-        plugin->db = QSqlDatabase::addDatabase("QSQLITE", plugin->db_name);
-
-        if(settings->value("cached").isEmpty() &&
-           settings->value("generateCache") == "true") {
-            plugin->makeCache("");
-        }
-        foreach(QString key, list)
-           if(key != "generateCache")
-                plugin->settings()->setValue(key, settings->value(key));
-        delete settings;
+        plugin->setSettings(settings);
     }
-    plugin->getDictionaryInfo();
     return  plugin;
 }
 
+
 bool XdxfPlugin::isAvailable() const {
     return true;
 }
 
 
-
 void XdxfPlugin::setHash(uint _hash) {
     this->_hash=_hash;
 }
 
 
-
 uint XdxfPlugin::hash() const {
    return _hash;
 }
 
 
-
 Settings* XdxfPlugin::settings() {
     return _settings;
 }
 
 
-
 bool XdxfPlugin::isCached() {
     if(_settings->value("cached") == "true")
         return true;
@@ -350,39 +344,53 @@ bool XdxfPlugin::isCached() {
 }
 
 
+void XdxfPlugin::setSettings(const Settings *settings) {
+    if(settings) {
 
-void XdxfPlugin::setSettings(Settings *settings) {
-    if(settings)
-    {
+        bool isPathChange=false;
         QString oldPath = _settings->value("path");
         if(oldPath != settings->value("path")) {
-            setPath(settings->value("path"));
+            if(oldPath!="" && _settings->value("cache_path")!="")
+                clean();
+            isPathChange=true;
         }
 
-       foreach(QString key, settings->keys())
+        foreach(QString key, settings->keys()) {
            if(key != "generateCache")
                _settings->setValue(key, settings->value(key));
+        }
+
+        if(isPathChange) {
+            _wordsCount=0;
+            if(oldPath!="") {
+                _settings->setValue("cached","false");
+                QSqlDatabase::removeDatabase(db_name);
+            }
+            db_name = _settings->value("type") + _settings->value("path");
+            db = QSqlDatabase::addDatabase("QSQLITE",db_name);
+        }
 
         if((_settings->value("cached") == "false" ||
-                _settings->value("cached").isEmpty()) &&
-                settings->value("generateCache") == "true") {
+            _settings->value("cached").isEmpty()) &&
+            settings->value("generateCache") == "true") {
+            clean();
             makeCache("");
         }
-        else if (settings->value("generateCache") != "true") {
-           _settings->setValue("cached", "false");
+
+        else if (settings->value("generateCache") == "false") {
+            _settings->setValue("cached", "false");
         }
 
         getDictionaryInfo();
-        delete settings;
     }
     Q_EMIT settingsChanged();
 }
 
 
-
 void XdxfPlugin::getDictionaryInfo() {
-    QFile dictionaryFile(path);
-    if(!dictionaryFile.open(QFile::ReadOnly | QFile::Text)) {
+    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";
@@ -407,22 +415,23 @@ void XdxfPlugin::getDictionaryInfo() {
     QString format = "png";
     QString initialPath = QDir::currentPath() + "/xdxf." + format;
 
-    _infoNote="path=\""+initialPath+"\"> \n" + _name + " [" + _langFrom + "-" + _langTo + "] (" + _type + ")";
+    _infoNote="path=\""+initialPath+"\"> \n" + _name + " [" + _langFrom + "-"
+                + _langTo + "] ( xdxf )";
     dictionaryFile.close();
 }
 
 
-
 QIcon* XdxfPlugin::icon() {
     return &_icon;
 }
 
+
 int XdxfPlugin::countWords() {
-    if(_wordsCount > 0)
+    if(_wordsCount>0)
         return _wordsCount;
-
-    QFile dictionaryFile(path);
-    if(!dictionaryFile.open(QFile::ReadOnly | QFile::Text)) {
+    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 file cannot be read for %1 dictionary")
                 .arg(name())));
@@ -446,18 +455,27 @@ int XdxfPlugin::countWords() {
     return wordsCount;
 }
 
+
 bool XdxfPlugin::makeCache(QString) {
     cachingDialog->setVisible(true);
     QCoreApplication::processEvents();
-    stopped = false;
     QFileInfo dictFileN(_settings->value("path"));
     QString cachePathN;
-    cachePathN = QDir::homePath() + "/.mdictionary/"
-                 + dictFileN.completeBaseName() + ".cache";
+    stopped = false;
 
+    /*create cache file name*/
+    int i=0;
+    do {
+        cachePathN = QDir::homePath() + "/.mdictionary/"
+                                      + dictFileN.completeBaseName()+"."
+                                      +QString::number(i) + ".cache";
+        i++;
+    } while(QFile::exists(cachePathN));
+
+    /*checke errors (File open and db open)*/
     QFile dictionaryFile(dictFileN.filePath());
-
-    if (!dictionaryFile.open(QFile::ReadOnly | QFile::Text)) {
+    if (!QFile::exists(_settings->value("path"))
+                || !dictionaryFile.open(QFile::ReadOnly | QFile::Text)) {
         Q_EMIT updateCachingProgress(100, 0);
         Q_EMIT notify(Notify::Warning,
                 QString(tr("XDXF file cannot be read for %1 dictionary")
@@ -465,8 +483,6 @@ bool XdxfPlugin::makeCache(QString) {
         return 0;
     }
     QXmlStreamReader reader(&dictionaryFile);
-
-
     db.setDatabaseName(cachePathN);
     if(!db.open()) {
         qDebug() << "Database error" << db.lastError().text() << endl;
@@ -476,6 +492,8 @@ bool XdxfPlugin::makeCache(QString) {
                 "You may want to recache.").arg(name())));
         return false;
     }
+
+    /*inicial sqlQuery*/
     QCoreApplication::processEvents();
     QSqlQuery cur(db);
     cur.exec("PRAGMA synchronous = 0");
@@ -485,27 +503,22 @@ bool XdxfPlugin::makeCache(QString) {
     int counter = 0;
     cur.exec("BEGIN;");
 
-    QString a;
+    QString readKey;
     bool match = false;
     QTime timer;
     timer.start();
     countWords();
-
     int lastProg = -1;
-
-    QString stripAcc = settings()->value("strip_accents");
     settings()->setValue("strip_accents", "true");
-
-
     counter=0;
-    while (!reader.atEnd() && !stopped) {
 
+    /*add all words to db*/
+    while (!reader.atEnd() && !stopped) {
         QCoreApplication::processEvents();
         reader.readNext();
-
         if(reader.tokenType() == QXmlStreamReader::StartElement) {
             if(reader.name()=="k"){
-                a = reader.readElementText();
+                readKey = reader.readElementText();
                 match = true;
             }
         }
@@ -518,60 +531,61 @@ bool XdxfPlugin::makeCache(QString) {
                     if(reader.tokenType()==QXmlStreamReader::StartElement)
                         temp+="<";
                     temp+=reader.name().toString();
-                    if(reader.name().toString()=="c" && reader.tokenType()==QXmlStreamReader::StartElement)
-                       temp= temp + " c=\"" + reader.attributes().value("c").toString() + "\"";
+                    if(reader.name().toString()=="c"
+                        && reader.tokenType()==QXmlStreamReader::StartElement) {
+                        temp= temp + " c=\""
+                                   + reader.attributes().value("c").toString()
+                                   + "\"";
+                    }
                     temp+=">";
                 }
-                temp+= reader.text().toString().replace("<","&lt;").replace(">","&gt;");;
+                temp+= reader.text().toString().replace("<","&lt;").replace(">"
+                              ,"&gt;");
                 reader.readNext();
             }
             if(temp.at(0)==QChar('\n'))
                 temp.remove(0,1);
-            temp="<key>" + a + "</key>" + "<t>" + temp+ "</t>";
+            temp="<key>" + readKey + "</key>" + "<t>" + temp+ "</t>";
             match=false;
             cur.prepare("insert into dict values(?,?,?)");
-            cur.addBindValue(a);
-            cur.addBindValue(removeAccents(a));
+            cur.addBindValue(readKey);
+            cur.addBindValue(removeAccents(readKey));
             cur.addBindValue(temp);
             cur.exec();
             counter++;
             int prog = counter*100/_wordsCount;
             if(prog % 5 == 0 && lastProg != prog) {
-                Q_EMIT updateCachingProgress(prog,
-                                             timer.restart());
+                Q_EMIT updateCachingProgress(prog,timer.restart());
                 lastProg = prog;
             }
         }
     }
-
     cur.exec("END;");
     cur.exec("select count(*) from dict");
-//    settings()->setValue("strip_accents", stripAcc);
-
-    countWords();
     cachingDialog->setVisible(false);
 
-    if(!cur.next() || countWords() != cur.value(0).toInt())
-    {
+    /*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.")));
         db.close();
         return false;
     }
+
     _settings->setValue("cache_path", cachePathN);
     _settings->setValue("cached", "true");
 
-
     db.close();
     return true;
 }
 
 
-
 void XdxfPlugin::clean() {
-    if(settings()->value("cached") == "true")
-        QFile(settings()->value("cache_path")).remove();
+    if(QFile::exists(_settings->value("cache_path")))
+        QFile(_settings->value("cache_path")).remove();
 }
 
+
 Q_EXPORT_PLUGIN2(xdxf, XdxfPlugin)