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, this);
35 cachingDialog = new XdxfCachingDialog(this);
37 connect(cachingDialog, SIGNAL(cancelCaching()),
40 _settings->setValue("type","xdxf");
44 _icon = QIcon(":/icons/xdxf.png");
47 XdxfPlugin::~XdxfPlugin()
49 // QString connection(db.connectionName());
51 // QSqlDatabase::removeDatabase(connection);
56 QString XdxfPlugin::langFrom() const {
60 QString XdxfPlugin::langTo() const {
64 QString XdxfPlugin::name() const {
68 QString XdxfPlugin::type() const {
69 // return _settings->value("type");
73 QString XdxfPlugin::infoNote() const {
77 QList<Translation*> XdxfPlugin::searchWordList(QString word, int limit) {
78 if(word.indexOf("*")==-1 && word.indexOf("?")==-1 && word.indexOf("_")==-1
79 && word.indexOf("%")==-1)
82 return searchWordListCache(word,limit);
83 return searchWordListFile(word, limit);
86 QList<Translation*> XdxfPlugin::searchWordListCache(QString word, int limit) {
88 QSet<Translation*> translations;
89 QString cacheFilePath = _settings->value("cache_path");
90 db.setDatabaseName(cacheFilePath);
92 qDebug() << "Database error" << db.lastError().text() << endl;
93 Q_EMIT notify(Notify::Warning, QString("Cache database cannot be "
94 "opened for %1 dictionary. Searching in xdxf file. "
95 "You may want to recache.").arg(name()));
96 return searchWordListFile(word, limit);
100 word = word.toLower();
101 word = word.replace("*", "%");
102 word = word.replace("?", "_");
103 word = removeAccents(word);
107 cur.prepare("select word from dict where word like ? limit ?");
109 cur.prepare("select word from dict where word like ?");
110 cur.addBindValue(word);
112 cur.addBindValue(limit);
117 foreach(tran,translations) {
118 if(tran->key().toLower()==cur.value(0).toString().toLower())
121 if(ok) /*add key word to list*/
122 translations.insert(new TranslationXdxf(
123 cur.value(0).toString().toLower(),
127 return translations.toList();
130 QList<Translation*> XdxfPlugin::searchWordListFile(QString word, int limit) {
131 QSet<Translation*> translations;
132 QFile dictionaryFile(path);
134 word = word.toLower();
135 word = removeAccents(word);
138 QRegExp regWord(word);
139 regWord.setCaseSensitivity(Qt::CaseInsensitive);
140 regWord.setPatternSyntax(QRegExp::Wildcard);
141 if(!dictionaryFile.open(QFile::ReadOnly | QFile::Text)) {
142 qDebug()<<"Error: could not open file";
143 Q_EMIT notify(Notify::Warning,
144 QString("Xdxf file cannot be read for %1").arg(name()));
145 return translations.toList();
148 QXmlStreamReader reader(&dictionaryFile);
149 /*search words list*/
152 while(!reader.atEnd() && !stopped){
153 reader.readNextStartElement();
154 if(reader.name()=="ar") {
155 while(reader.name()!="k" && !reader.atEnd())
156 reader.readNextStartElement();
158 a = reader.readElementText();
159 if(regWord.exactMatch(removeAccents(a)) && (i<limit || limit==0)) {
162 foreach(tran,translations) {
163 if(tran->key().toLower()==a.toLower())
164 ok=false; /*if key word is in the dictionary more that one */
166 if(ok) /*add key word to list*/
167 translations<<(new TranslationXdxf(a.toLower(),
170 if(i>=limit && limit!=0)
174 this->thread()->yieldCurrentThread();
177 dictionaryFile.close();
178 return translations.toList();
181 QString XdxfPlugin::search(QString key) {
182 // if(_settings->value("cached") == "true")
184 return searchCache(key);
185 return searchFile(key);
188 QString XdxfPlugin::searchCache(QString key) {
190 QString cacheFilePath = _settings->value("cache_path");
191 db.setDatabaseName(cacheFilePath);
195 qDebug() << "Database error" << db.lastError().text() << endl;
196 Q_EMIT notify(Notify::Warning, QString("Cache database cannot be "
197 "opened for %1 dictionary. Searching in xdxf file. "
198 "You may want to recache.").arg(name()));
199 return searchFile(key);
203 cur.prepare("select translation from dict where word like ?");
204 cur.addBindValue(key);
207 result += cur.value(0).toString();
215 QString XdxfPlugin::searchFile(QString key) {
217 QFile dictionaryFile(path);
218 QString resultString("");
219 if(!dictionaryFile.open(QFile::ReadOnly | QFile::Text)) {
220 Q_EMIT notify(Notify::Warning,
221 QString("Xdxf file cannot be read for %1").arg(name()));
222 qDebug()<<"Error: could not open file";
225 QXmlStreamReader reader(&dictionaryFile);
230 while (!reader.atEnd()&& !stopped) {
232 if(reader.tokenType() == QXmlStreamReader::StartElement) {
233 if(reader.name()=="k") {
234 a = reader.readElementText();
235 if(a.toLower()==key.toLower())
241 while(reader.name()!="ar" && !reader.atEnd()) {
242 if(reader.name()!="" && reader.name()!="k") {
243 if(reader.tokenType()==QXmlStreamReader::EndElement)
245 if(reader.tokenType()==QXmlStreamReader::StartElement)
247 temp+=reader.name().toString();
248 if(reader.name().toString()=="c" && reader.tokenType()==QXmlStreamReader::StartElement)
249 temp= temp + tr(" c=\"") + reader.attributes().value(tr("c")).toString() + tr("\"");
252 temp+= reader.text().toString().replace("<","<").replace(">",">");
255 if(temp.at(0)==QChar('\n'))
257 resultString+=tr("<key>") + a +tr("</key>");
258 resultString+=tr("<t>") + temp + tr("</t>");
261 this->thread()->yieldCurrentThread();
264 dictionaryFile.close();
269 void XdxfPlugin::stop() {
273 DictDialog* XdxfPlugin::dictDialog() {
277 void XdxfPlugin::setPath(QString path){
279 _settings->setValue("path",path);
280 //getDictionaryInfo();
283 CommonDictInterface* XdxfPlugin::getNew(const Settings *settings) const {
284 XdxfPlugin *plugin = new XdxfPlugin();
287 plugin->setPath(settings->value("path"));
288 QStringList list = settings->keys();
289 foreach(QString key, list)
290 plugin->settings()->setValue(key, settings->value(key));
293 plugin->db_name = plugin->_settings->value("type")
294 + plugin->_settings->value("path");
295 plugin->db = QSqlDatabase::addDatabase("QSQLITE", plugin->db_name);
297 if(settings->value("cached").isEmpty() &&
298 settings->value("generateCache") == "true") {
299 plugin->makeCache("");
303 plugin->getDictionaryInfo();
307 bool XdxfPlugin::isAvailable() const {
311 void XdxfPlugin::setHash(uint _hash) {
315 uint XdxfPlugin::hash() const {
319 Settings* XdxfPlugin::settings() {
323 bool XdxfPlugin::isCached() {
324 if(_settings->value("cached") == "true")
329 void XdxfPlugin::setSettings(Settings *settings) {
331 QString oldPath = _settings->value("path");
332 if(oldPath != settings->value("path")) {
333 setPath(settings->value("path"));
336 if((_settings->value("cached") == "false" ||
337 _settings->value("cached").isEmpty()) &&
338 settings->value("generateCache") == "true") {
342 _settings->setValue("cached", "false");
346 emit settingsChanged();
349 void XdxfPlugin::getDictionaryInfo() {
350 QFile dictionaryFile(path);
351 if(!dictionaryFile.open(QFile::ReadOnly | QFile::Text)) {
352 Q_EMIT notify(Notify::Warning,
353 QString("Xdxf file cannot be read dictionary"));
354 qDebug()<<"Error: could not open file";
358 QXmlStreamReader reader(&dictionaryFile);
359 reader.readNextStartElement();
360 if(reader.name()=="xdxf") {
361 if(reader.attributes().hasAttribute("lang_from"))
362 _langFrom = reader.attributes().value("lang_from").toString();
363 if(reader.attributes().hasAttribute("lang_to"))
364 _langTo = reader.attributes().value("lang_to").toString();
366 reader.readNextStartElement();
367 if(reader.name()=="full_name")
368 _name=reader.readElementText();
369 reader.readNextStartElement();
370 if(reader.name()=="description")
371 _infoNote=reader.readElementText();
373 QString format = "png";
374 QString initialPath = QDir::currentPath() + tr("/xdxf.") + format;
376 _infoNote="path=\""+initialPath+"\">"+"\n" + _name + " [" + _langFrom + "-" + _langTo + "] "+ "(" + _type + ")";
378 dictionaryFile.close();
381 QString XdxfPlugin::removeAccents(QString string) {
382 string = string.replace(QString::fromUtf8("ł"), "l", Qt::CaseInsensitive);
383 QString normalized = string.normalized(QString::NormalizationForm_D);
384 normalized = normalized;
385 for(int i=0; i<normalized.size(); i++) {
386 if( !normalized[i].isLetterOrNumber() &&
387 !normalized[i].isSpace() &&
388 !normalized[i].isDigit() &&
389 normalized[i] != '*' &&
390 normalized[i] != '%' &&
391 normalized[i] != '_' &&
392 normalized[i] != '?' ) {
393 normalized.remove(i,1);
399 QIcon* XdxfPlugin::icon() {
403 int XdxfPlugin::countWords() {
407 QFile dictionaryFile(path);
408 if(!dictionaryFile.open(QFile::ReadOnly | QFile::Text)) {
409 Q_EMIT notify(Notify::Warning,
410 QString("Xdxf file cannot be read for %1 dictionary")
412 qDebug()<<"Error: could not open file";
416 dictionaryFile.seek(0);
421 while(!dictionaryFile.atEnd()) {
422 line = dictionaryFile.readLine();
423 if(line.contains("<k>")) {
427 _wordsCount = wordsCount;
428 dictionaryFile.close();
432 bool XdxfPlugin::makeCache(QString dir) {
433 cachingDialog->setVisible(true);
434 QCoreApplication::processEvents();
436 QFileInfo dictFileN(_settings->value("path"));
438 cachePathN = QDir::homePath() + "/.mdictionary/"
439 + dictFileN.completeBaseName() + ".cache";
441 QFile dictionaryFile(dictFileN.filePath());
444 if (!dictionaryFile.open(QFile::ReadOnly | QFile::Text)) {
445 Q_EMIT updateCachingProgress(100, 0);
446 Q_EMIT notify(Notify::Warning,
447 QString("Xdxf file cannot be read for %1 dictionary")
452 QXmlStreamReader reader(&dictionaryFile);
454 db.setDatabaseName(cachePathN);
456 qDebug() << "Database error" << db.lastError().text() << endl;
457 Q_EMIT updateCachingProgress(100, 0);
458 Q_EMIT notify(Notify::Warning, QString("Cache database cannot be "
459 "opened for %1 dictionary. Searching in xdxf file. "
460 "You may want to recache.").arg(name()));
463 QCoreApplication::processEvents();
465 cur.exec("PRAGMA synchronous = 0");
466 cur.exec("drop table dict");
467 QCoreApplication::processEvents();
468 cur.exec("create table dict(word text ,translation text)");
482 while (!reader.atEnd() && !stopped) {
484 QCoreApplication::processEvents();
487 if(reader.tokenType() == QXmlStreamReader::StartElement) {
488 if(reader.name()=="k"){
489 a = reader.readElementText();
495 while(reader.name()!="ar" && !reader.atEnd()) {
496 if(reader.name()!="" && reader.name()!="k") {
497 if(reader.tokenType()==QXmlStreamReader::EndElement)
499 if(reader.tokenType()==QXmlStreamReader::StartElement)
501 temp+=reader.name().toString();
502 if(reader.name().toString()=="c" && reader.tokenType()==QXmlStreamReader::StartElement)
503 temp= temp + tr(" c=\"") + reader.attributes().value(tr("c")).toString() + tr("\"");
506 temp+= reader.text().toString().replace("<","<").replace(">",">");;
509 if(temp.at(0)==QChar('\n'))
511 temp=tr("<key>") + a + tr("</key>") + tr("<t>") + temp+ tr("</t>");
513 cur.prepare("insert into dict values(?,?)");
515 cur.addBindValue(temp);
518 int prog = counter*100/_wordsCount;
519 if(prog % 5 == 0 && lastProg != prog) {
520 Q_EMIT updateCachingProgress(prog,
528 cur.exec("select count(*) from dict");
531 cachingDialog->setVisible(false);
533 if(!cur.next() || countWords() != cur.value(0).toInt())
535 Q_EMIT updateCachingProgress(100, timer.restart());
536 Q_EMIT notify(Notify::Warning,
537 QString("Database caching error, please try againg."));
541 _settings->setValue("cache_path", cachePathN);
542 _settings->setValue("cached", "true");
549 Q_EXPORT_PLUGIN2(xdxf, XdxfPlugin)