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
25 #include "xdxfplugin.h"
27 #include "../../../includes/Notify.h"
29 XdxfPlugin::XdxfPlugin(QObject *parent) : CommonDictInterface(parent),
30 _langFrom(tr("")), _langTo(tr("")),_name(tr("")),
31 _type(tr("xdxf")), _infoNote(tr("")) {
33 _settings = new Settings();
34 _dictDialog = new XdxfDictDialog(this);
35 cachingDialog = new XdxfCachingDialog();
37 connect(cachingDialog, SIGNAL(cancelCaching()),
40 connect(this, SIGNAL(updateCachingProgress(int,int)),
41 cachingDialog, SLOT(updateCachingProgress(int,int)));
43 _settings->setValue("type","xdxf");
47 _icon = QIcon(":/icons/xdxf.png");
50 XdxfPlugin::~XdxfPlugin()
52 // QString connection(db.connectionName());
54 // QSqlDatabase::removeDatabase(connection);
59 QString XdxfPlugin::langFrom() const {
63 QString XdxfPlugin::langTo() const {
67 QString XdxfPlugin::name() const {
71 QString XdxfPlugin::type() const {
72 // return _settings->value("type");
76 QString XdxfPlugin::infoNote() const {
80 QList<Translation*> XdxfPlugin::searchWordList(QString word, int limit) {
81 if(word.indexOf("*")==-1 && word.indexOf("?")==-1 && word.indexOf("_")==-1
82 && word.indexOf("%")==-1)
85 return searchWordListCache(word,limit);
86 return searchWordListFile(word, limit);
89 QList<Translation*> XdxfPlugin::searchWordListCache(QString word, int limit) {
91 QSet<Translation*> translations;
92 QString cacheFilePath = _settings->value("cache_path");
93 db.setDatabaseName(cacheFilePath);
95 qDebug() << "Database error" << db.lastError().text() << endl;
96 Q_EMIT notify(Notify::Warning, QString("Cache database cannot be "
97 "opened for %1 dictionary. Searching in xdxf file. "
98 "You may want to recache.").arg(name()));
99 return searchWordListFile(word, limit);
103 word = word.toLower();
104 word = word.replace("*", "%");
105 word = word.replace("?", "_");
109 cur.prepare("select word from dict where word like ? limit ?");
111 cur.prepare("select word from dict where word like ?");
112 cur.addBindValue(word);
114 cur.addBindValue(limit);
121 foreach(tran,translations) {
122 if(tran->key().toLower()==cur.value(0).toString().toLower())
125 if(ok) /*add key word to list*/
126 translations.insert(new TranslationXdxf(
127 cur.value(0).toString().toLower(),
134 cur.prepare("select word from dict where normalized like ? limit ?");
136 cur.prepare("select word from dict where normalized like ?");
137 cur.addBindValue(word);
139 cur.addBindValue(limit);
144 foreach(tran,translations) {
145 if(tran->key().toLower()==cur.value(0).toString().toLower())
148 if(ok) /*add key word to list*/
149 translations.insert(new TranslationXdxf(
150 cur.value(0).toString().toLower(),
155 return translations.toList();
158 QList<Translation*> XdxfPlugin::searchWordListFile(QString word, int limit) {
161 QSet<Translation*> translations;
162 QFile dictionaryFile(path);
164 word = word.toLower();
165 //word = removeAccents(word);
168 QRegExp regWord(word);
169 regWord.setCaseSensitivity(Qt::CaseInsensitive);
170 regWord.setPatternSyntax(QRegExp::Wildcard);
171 if(!dictionaryFile.open(QFile::ReadOnly | QFile::Text)) {
172 qDebug()<<"Error: could not open file";
173 Q_EMIT notify(Notify::Warning,
174 QString("Xdxf file cannot be read for %1").arg(name()));
175 return translations.toList();
178 QXmlStreamReader reader(&dictionaryFile);
179 /*search words list*/
181 QRegExp regexp(removeAccents(a), Qt::CaseInsensitive, QRegExp::Wildcard);
182 regexp.setMinimal(true);
185 while(!reader.atEnd() && !stopped){
186 reader.readNextStartElement();
187 if(reader.name()=="ar") {
188 while(reader.name()!="k" && !reader.atEnd())
189 reader.readNextStartElement();
191 a = reader.readElementText();
192 regexp.setPattern(a);
193 if((regWord.exactMatch(a) || regexp.exactMatch(
194 word.left(word.size()-1))) &&
195 (i<limit || limit==0)) {
198 foreach(tran,translations) {
199 if(tran->key().toLower()==a.toLower())
200 ok=false; /*if key word is in the dictionary more that one */
202 if(ok) /*add key word to list*/
203 translations<<(new TranslationXdxf(a.toLower(),
206 if(i>=limit && limit!=0)
210 this->thread()->yieldCurrentThread();
213 dictionaryFile.close();
214 qDebug() << time.elapsed();
215 return translations.toList();
218 QString XdxfPlugin::search(QString key) {
219 // if(_settings->value("cached") == "true")
221 return searchCache(key);
222 return searchFile(key);
225 QString XdxfPlugin::searchCache(QString key) {
227 QString cacheFilePath = _settings->value("cache_path");
228 db.setDatabaseName(cacheFilePath);
232 qDebug() << "Database error" << db.lastError().text() << endl;
233 Q_EMIT notify(Notify::Warning, QString("Cache database cannot be "
234 "opened for %1 dictionary. Searching in xdxf file. "
235 "You may want to recache.").arg(name()));
236 return searchFile(key);
240 cur.prepare("select translation from dict where word like ?");
241 cur.addBindValue(key);
244 result += cur.value(0).toString();
252 QString XdxfPlugin::searchFile(QString key) {
254 QFile dictionaryFile(path);
255 QString resultString("");
256 if(!dictionaryFile.open(QFile::ReadOnly | QFile::Text)) {
257 Q_EMIT notify(Notify::Warning,
258 QString("Xdxf file cannot be read for %1").arg(name()));
259 qDebug()<<"Error: could not open file";
262 QXmlStreamReader reader(&dictionaryFile);
267 while (!reader.atEnd()&& !stopped) {
269 if(reader.tokenType() == QXmlStreamReader::StartElement) {
270 if(reader.name()=="k") {
271 a = reader.readElementText();
272 if(a.toLower()==key.toLower())
278 while(reader.name()!="ar" && !reader.atEnd()) {
279 if(reader.name()!="" && reader.name()!="k") {
280 if(reader.tokenType()==QXmlStreamReader::EndElement)
282 if(reader.tokenType()==QXmlStreamReader::StartElement)
284 temp+=reader.name().toString();
285 if(reader.name().toString()=="c" && reader.tokenType()==QXmlStreamReader::StartElement)
286 temp= temp + tr(" c=\"") + reader.attributes().value(tr("c")).toString() + tr("\"");
289 temp+= reader.text().toString().replace("<","<").replace(">",">");
292 if(temp.at(0)==QChar('\n'))
294 resultString+=tr("<key>") + a +tr("</key>");
295 resultString+=tr("<t>") + temp + tr("</t>");
298 this->thread()->yieldCurrentThread();
301 dictionaryFile.close();
306 void XdxfPlugin::stop() {
310 DictDialog* XdxfPlugin::dictDialog() {
314 void XdxfPlugin::setPath(QString path){
316 _settings->setValue("path",path);
317 //getDictionaryInfo();
320 CommonDictInterface* XdxfPlugin::getNew(const Settings *settings) const {
321 XdxfPlugin *plugin = new XdxfPlugin();
324 plugin->setPath(settings->value("path"));
325 QStringList list = settings->keys();
326 foreach(QString key, list)
327 plugin->settings()->setValue(key, settings->value(key));
330 plugin->db_name = plugin->_settings->value("type")
331 + plugin->_settings->value("path");
332 plugin->db = QSqlDatabase::addDatabase("QSQLITE", plugin->db_name);
334 if(settings->value("cached").isEmpty() &&
335 settings->value("generateCache") == "true") {
336 plugin->makeCache("");
340 plugin->getDictionaryInfo();
344 bool XdxfPlugin::isAvailable() const {
348 void XdxfPlugin::setHash(uint _hash) {
352 uint XdxfPlugin::hash() const {
356 Settings* XdxfPlugin::settings() {
360 bool XdxfPlugin::isCached() {
361 if(_settings->value("cached") == "true")
366 void XdxfPlugin::setSettings(Settings *settings) {
368 QString oldPath = _settings->value("path");
369 if(oldPath != settings->value("path")) {
370 setPath(settings->value("path"));
373 if((_settings->value("cached") == "false" ||
374 _settings->value("cached").isEmpty()) &&
375 settings->value("generateCache") == "true") {
379 _settings->setValue("cached", "false");
383 emit settingsChanged();
386 void XdxfPlugin::getDictionaryInfo() {
387 QFile dictionaryFile(path);
388 if(!dictionaryFile.open(QFile::ReadOnly | QFile::Text)) {
389 Q_EMIT notify(Notify::Warning,
390 QString("Xdxf file cannot be read dictionary"));
391 qDebug()<<"Error: could not open file";
395 QXmlStreamReader reader(&dictionaryFile);
396 reader.readNextStartElement();
397 if(reader.name()=="xdxf") {
398 if(reader.attributes().hasAttribute("lang_from"))
399 _langFrom = reader.attributes().value("lang_from").toString();
400 if(reader.attributes().hasAttribute("lang_to"))
401 _langTo = reader.attributes().value("lang_to").toString();
403 reader.readNextStartElement();
404 if(reader.name()=="full_name")
405 _name=reader.readElementText();
406 reader.readNextStartElement();
407 if(reader.name()=="description")
408 _infoNote=reader.readElementText();
410 QString format = "png";
411 QString initialPath = QDir::currentPath() + tr("/xdxf.") + format;
413 _infoNote="path=\""+initialPath+"\">"+"\n" + _name + " [" + _langFrom + "-" + _langTo + "] "+ "(" + _type + ")";
415 dictionaryFile.close();
418 QString XdxfPlugin::removeAccents(QString string, QChar wildcard) {
419 QString normalized = string.toLower();
420 for(int i=0; i<normalized.size(); i++) {
421 if(normalized[i].isLetterOrNumber() && ((normalized.at(1) < QChar('a'))
422 || (normalized.at(i) > QChar('z'))))
423 normalized[i] = wildcard;
428 QIcon* XdxfPlugin::icon() {
432 int XdxfPlugin::countWords() {
436 QFile dictionaryFile(path);
437 if(!dictionaryFile.open(QFile::ReadOnly | QFile::Text)) {
438 Q_EMIT notify(Notify::Warning,
439 QString("Xdxf file cannot be read for %1 dictionary")
441 qDebug()<<"Error: could not open file";
445 dictionaryFile.seek(0);
450 while(!dictionaryFile.atEnd()) {
451 line = dictionaryFile.readLine();
452 if(line.contains("<k>")) {
456 _wordsCount = wordsCount;
457 dictionaryFile.close();
461 bool XdxfPlugin::makeCache(QString dir) {
462 cachingDialog->setVisible(true);
463 QCoreApplication::processEvents();
465 QFileInfo dictFileN(_settings->value("path"));
467 cachePathN = QDir::homePath() + "/.mdictionary/"
468 + dictFileN.completeBaseName() + ".cache";
470 QFile dictionaryFile(dictFileN.filePath());
473 if (!dictionaryFile.open(QFile::ReadOnly | QFile::Text)) {
474 Q_EMIT updateCachingProgress(100, 0);
475 Q_EMIT notify(Notify::Warning,
476 QString("Xdxf file cannot be read for %1 dictionary")
480 QXmlStreamReader reader(&dictionaryFile);
482 db.setDatabaseName(cachePathN);
484 qDebug() << "Database error" << db.lastError().text() << endl;
485 Q_EMIT updateCachingProgress(100, 0);
486 Q_EMIT notify(Notify::Warning, QString("Cache database cannot be "
487 "opened for %1 dictionary. Searching in xdxf file. "
488 "You may want to recache.").arg(name()));
491 QCoreApplication::processEvents();
493 cur.exec("PRAGMA synchronous = 0");
494 cur.exec("drop table dict");
495 QCoreApplication::processEvents();
496 cur.exec("create table dict(word text, normalized text ,translation text)");
510 while (!reader.atEnd() && !stopped) {
512 QCoreApplication::processEvents();
515 if(reader.tokenType() == QXmlStreamReader::StartElement) {
516 if(reader.name()=="k"){
517 a = reader.readElementText();
523 while(reader.name()!="ar" && !reader.atEnd()) {
524 if(reader.name()!="" && reader.name()!="k") {
525 if(reader.tokenType()==QXmlStreamReader::EndElement)
527 if(reader.tokenType()==QXmlStreamReader::StartElement)
529 temp+=reader.name().toString();
530 if(reader.name().toString()=="c" && reader.tokenType()==QXmlStreamReader::StartElement)
531 temp= temp + tr(" c=\"") + reader.attributes().value(tr("c")).toString() + tr("\"");
534 temp+= reader.text().toString().replace("<","<").replace(">",">");;
537 if(temp.at(0)==QChar('\n'))
539 temp=tr("<key>") + a + tr("</key>") + tr("<t>") + temp+ tr("</t>");
541 cur.prepare("insert into dict values(?,?,?)");
543 cur.addBindValue(removeAccents(a,'_'));
544 cur.addBindValue(temp);
547 int prog = counter*100/_wordsCount;
548 if(prog % 5 == 0 && lastProg != prog) {
550 Q_EMIT updateCachingProgress(prog,
558 cur.exec("select count(*) from dict");
561 cachingDialog->setVisible(false);
563 if(!cur.next() || countWords() != cur.value(0).toInt())
565 Q_EMIT updateCachingProgress(100, timer.restart());
566 Q_EMIT notify(Notify::Warning,
567 QString("Database caching error, please try againg."));
571 _settings->setValue("cache_path", cachePathN);
572 _settings->setValue("cached", "true");
579 Q_EXPORT_PLUGIN2(xdxf, XdxfPlugin)