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"
28 #include <QXmlStreamReader>
30 #include "TranslationXdxf.h"
31 #include "../../../includes/settings.h"
32 #include "../../../includes/Notify.h"
34 XdxfPlugin::XdxfPlugin(QObject *parent) : CommonDictInterface(parent),
35 _langFrom(tr("")), _langTo(tr("")),_name(tr("")),
36 _type(tr("xdxf")), _infoNote(tr("")) {
38 _settings = new Settings();
39 _dictDialog = new XdxfDictDialog(this, this);
40 cachingDialog = new XdxfCachingDialog(this);
42 connect(cachingDialog, SIGNAL(cancelCaching()),
45 _settings->setValue("type","xdxf");
49 _icon = QIcon(":/icons/xdxf.png");
52 XdxfPlugin::~XdxfPlugin()
54 db.removeDatabase(_type+path);
57 QString XdxfPlugin::langFrom() const {
61 QString XdxfPlugin::langTo() const {
65 QString XdxfPlugin::name() const {
69 QString XdxfPlugin::type() const {
70 // return _settings->value("type");
74 QString XdxfPlugin::infoNote() const {
78 QList<Translation*> XdxfPlugin::searchWordList(QString word, int limit) {
79 if(word.indexOf("*")==-1 && word.indexOf("?")==-1 && word.indexOf("_")==-1
80 && word.indexOf("%")==-1)
83 return searchWordListCache(word,limit);
84 return searchWordListFile(word, limit);
87 QList<Translation*> XdxfPlugin::searchWordListCache(QString word, int limit) {
89 QSet<Translation*> translations;
90 QString cacheFilePath = _settings->value("cache_path");
91 db.setDatabaseName(cacheFilePath);
93 qDebug() << "Database error" << db.lastError().text() << endl;
94 Q_EMIT notify(Notify::Warning, QString("Cache database cannot be "
95 "opened for %1 dictionary. Searching in xdxf file. "
96 "You may want to recache.").arg(name()));
97 return searchWordListFile(word, limit);
101 word = word.toLower();
102 word = word.replace("*", "%");
103 word = word.replace("?", "_");
104 word = removeAccents(word);
108 cur.prepare("select word from dict where word like ? limit ?");
110 cur.prepare("select word from dict where word like ?");
111 cur.addBindValue(word);
113 cur.addBindValue(limit);
118 foreach(tran,translations) {
119 if(tran->key().toLower()==cur.value(0).toString().toLower())
122 if(ok) /*add key word to list*/
123 translations.insert(new TranslationXdxf(
124 cur.value(0).toString().toLower(),
128 return translations.toList();
131 QList<Translation*> XdxfPlugin::searchWordListFile(QString word, int limit) {
132 QSet<Translation*> translations;
133 QFile dictionaryFile(path);
135 word = word.toLower();
136 word = removeAccents(word);
139 QRegExp regWord(word);
140 regWord.setCaseSensitivity(Qt::CaseInsensitive);
141 regWord.setPatternSyntax(QRegExp::Wildcard);
142 if(!dictionaryFile.open(QFile::ReadOnly | QFile::Text)) {
143 qDebug()<<"Error: could not open file";
144 Q_EMIT notify(Notify::Warning,
145 QString("Xdxf file cannot be read for %1").arg(name()));
146 return translations.toList();
149 QXmlStreamReader reader(&dictionaryFile);
150 /*search words list*/
153 while(!reader.atEnd() && !stopped){
154 reader.readNextStartElement();
155 if(reader.name()=="ar") {
156 while(reader.name()!="k" && !reader.atEnd())
157 reader.readNextStartElement();
159 a = reader.readElementText();
160 if(regWord.exactMatch(removeAccents(a)) && (i<limit || limit==0)) {
163 foreach(tran,translations) {
164 if(tran->key().toLower()==a.toLower())
165 ok=false; /*if key word is in the dictionary more that one */
167 if(ok) /*add key word to list*/
168 translations<<(new TranslationXdxf(a.toLower(),
171 if(i>=limit && limit!=0)
175 this->thread()->yieldCurrentThread();
178 dictionaryFile.close();
179 return translations.toList();
182 QString XdxfPlugin::search(QString key) {
183 // if(_settings->value("cached") == "true")
185 return searchCache(key);
186 return searchFile(key);
189 QString XdxfPlugin::searchCache(QString key) {
191 QString cacheFilePath = _settings->value("cache_path");
192 db.setDatabaseName(cacheFilePath);
196 qDebug() << "Database error" << db.lastError().text() << endl;
197 Q_EMIT notify(Notify::Warning, QString("Cache database cannot be "
198 "opened for %1 dictionary. Searching in xdxf file. "
199 "You may want to recache.").arg(name()));
200 return searchFile(key);
204 cur.prepare("select translation from dict where word like ?");
205 cur.addBindValue(key);
208 result += cur.value(0).toString();
214 QString XdxfPlugin::searchFile(QString key) {
216 QFile dictionaryFile(path);
217 QString resultString("");
218 if(!dictionaryFile.open(QFile::ReadOnly | QFile::Text)) {
219 Q_EMIT notify(Notify::Warning,
220 QString("Xdxf file cannot be read for %1").arg(name()));
221 qDebug()<<"Error: could not open file";
224 QXmlStreamReader reader(&dictionaryFile);
232 while (!reader.atEnd()&& !stopped) {
234 if(reader.tokenType() == QXmlStreamReader::StartElement) {
235 if(reader.name()=="k") {
236 a = reader.readElementText();
237 if(a.toLower()==key.toLower())
243 while(reader.name()!="ar" && !reader.atEnd()) {
244 if(reader.name()!="" && reader.name()!="k") {
245 if(reader.tokenType()==QXmlStreamReader::EndElement)
247 if(reader.tokenType()==QXmlStreamReader::StartElement)
249 temp+=reader.name().toString();
250 if(reader.name().toString()=="c" && reader.tokenType()==QXmlStreamReader::StartElement)
251 temp= temp + tr(" c=\"") + reader.attributes().value(tr("c")).toString() + tr("\"");
254 temp+= reader.text().toString().replace("<","<").replace(">",">");
257 if(temp.at(0)==QChar('\n'))
259 resultString+=tr("<key>") + a +tr("</key>");
260 resultString+=tr("<t>") + temp + tr("</t>");
263 this->thread()->yieldCurrentThread();
266 dictionaryFile.close();
271 void XdxfPlugin::stop() {
275 DictDialog* XdxfPlugin::dictDialog() {
279 void XdxfPlugin::setPath(QString path){
281 _settings->setValue("path",path);
282 //getDictionaryInfo();
285 CommonDictInterface* XdxfPlugin::getNew(const Settings *settings) const {
286 XdxfPlugin *plugin = new XdxfPlugin();
289 plugin->setPath(settings->value("path"));
290 QStringList list = settings->keys();
291 foreach(QString key, list)
292 plugin->settings()->setValue(key, settings->value(key));
295 plugin->db_name = plugin->_settings->value("type")
296 + plugin->_settings->value("path");
297 // if(!plugin->db.connectionName().isEmpty() || settings->value("generateCache")=="true")
298 plugin->db = QSqlDatabase::addDatabase("QSQLITE", plugin->db_name);
300 if(settings->value("cached").isEmpty() &&
301 settings->value("generateCache") == "true") {
302 plugin->makeCache("");
306 plugin->getDictionaryInfo();
310 bool XdxfPlugin::isAvailable() const {
314 void XdxfPlugin::setHash(uint _hash) {
318 uint XdxfPlugin::hash() const {
322 Settings* XdxfPlugin::settings() {
326 bool XdxfPlugin::isCached() {
327 if(_settings->value("cached") == "true")
332 void XdxfPlugin::setSettings(Settings *settings) {
334 QString oldPath = _settings->value("path");
335 if(oldPath != settings->value("path")) {
336 setPath(settings->value("path"));
339 if((_settings->value("cached") == "false" ||
340 _settings->value("cached").isEmpty()) &&
341 settings->value("generateCache") == "true") {
345 _settings->setValue("cached", "false");
349 emit settingsChanged();
352 void XdxfPlugin::getDictionaryInfo() {
353 QFile dictionaryFile(path);
354 if(!dictionaryFile.open(QFile::ReadOnly | QFile::Text)) {
355 Q_EMIT notify(Notify::Warning,
356 QString("Xdxf file cannot be read dictionary"));
357 qDebug()<<"Error: could not open file";
361 QXmlStreamReader reader(&dictionaryFile);
362 reader.readNextStartElement();
363 if(reader.name()=="xdxf") {
364 if(reader.attributes().hasAttribute("lang_from"))
365 _langFrom = reader.attributes().value("lang_from").toString();
366 if(reader.attributes().hasAttribute("lang_to"))
367 _langTo = reader.attributes().value("lang_to").toString();
369 reader.readNextStartElement();
370 if(reader.name()=="full_name")
371 _name=reader.readElementText();
372 reader.readNextStartElement();
373 if(reader.name()=="description")
374 _infoNote=reader.readElementText();
376 QString format = "png";
377 QString initialPath = QDir::currentPath() + tr("/xdxf.") + format;
379 _infoNote="<info path=\""+initialPath+"\">"+"\n" + _name + " [" + _langFrom + "-" + _langTo + "] "+ "(" + _type + ")" + "</info>";
383 dictionaryFile.close();
386 QString XdxfPlugin::removeAccents(QString string) {
387 string = string.replace(QString::fromUtf8("ł"), "l", Qt::CaseInsensitive);
388 QString normalized = string.normalized(QString::NormalizationForm_D);
389 normalized = normalized;
390 for(int i=0; i<normalized.size(); i++) {
391 if( !normalized[i].isLetterOrNumber() &&
392 !normalized[i].isSpace() &&
393 !normalized[i].isDigit() &&
394 normalized[i] != '*' &&
395 normalized[i] != '%' &&
396 normalized[i] != '_' &&
397 normalized[i] != '?' ) {
398 normalized.remove(i,1);
404 QIcon* XdxfPlugin::icon() {
408 int XdxfPlugin::countWords() {
412 QFile dictionaryFile(path);
413 if(!dictionaryFile.open(QFile::ReadOnly | QFile::Text)) {
414 Q_EMIT notify(Notify::Warning,
415 QString("Xdxf file cannot be read for %1 dictionary")
417 qDebug()<<"Error: could not open file";
421 dictionaryFile.seek(0);
426 while(!dictionaryFile.atEnd()) {
427 line = dictionaryFile.readLine();
428 if(line.contains("<k>")) {
432 _wordsCount = wordsCount;
433 dictionaryFile.close();
437 bool XdxfPlugin::makeCache(QString dir) {
438 cachingDialog->setVisible(true);
439 QCoreApplication::processEvents();
441 QFileInfo dictFileN(_settings->value("path"));
443 cachePathN = QDir::homePath() + "/.mdictionary/"
444 + dictFileN.completeBaseName() + ".cache";
446 QFile dictionaryFile(dictFileN.filePath());
449 if (!dictionaryFile.open(QFile::ReadOnly | QFile::Text)) {
450 Q_EMIT updateCachingProgress(100, 0);
451 Q_EMIT notify(Notify::Warning,
452 QString("Xdxf file cannot be read for %1 dictionary")
457 QXmlStreamReader reader(&dictionaryFile);
459 db.setDatabaseName(cachePathN);
461 qDebug() << "Database error" << db.lastError().text() << endl;
462 Q_EMIT updateCachingProgress(100, 0);
463 Q_EMIT notify(Notify::Warning, QString("Cache database cannot be "
464 "opened for %1 dictionary. Searching in xdxf file. "
465 "You may want to recache.").arg(name()));
468 QCoreApplication::processEvents();
470 cur.exec("PRAGMA synchronous = 0");
471 cur.exec("drop table dict");
472 QCoreApplication::processEvents();
473 cur.exec("create table dict(word text ,translation text)");
487 while (!reader.atEnd() && !stopped) {
489 QCoreApplication::processEvents();
492 if(reader.tokenType() == QXmlStreamReader::StartElement) {
493 if(reader.name()=="k"){
494 a = reader.readElementText();
500 while(reader.name()!="ar" && !reader.atEnd()) {
501 if(reader.name()!="" && reader.name()!="k") {
502 if(reader.tokenType()==QXmlStreamReader::EndElement)
504 if(reader.tokenType()==QXmlStreamReader::StartElement)
506 temp+=reader.name().toString();
507 if(reader.name().toString()=="c" && reader.tokenType()==QXmlStreamReader::StartElement)
508 temp= temp + tr(" c=\"") + reader.attributes().value(tr("c")).toString() + tr("\"");
511 temp+= reader.text().toString().replace("<","<").replace(">",">");;
514 if(temp.at(0)==QChar('\n'))
516 temp=tr("<key>") + a + tr("</key>") + tr("<t>") + temp+ tr("</t>");
518 cur.prepare("insert into dict values(?,?)");
520 cur.addBindValue(temp);
523 int prog = counter*100/_wordsCount;
524 if(prog % 5 == 0 && lastProg != prog) {
525 Q_EMIT updateCachingProgress(prog,
533 cur.exec("select count(*) from dict");
536 cachingDialog->setVisible(false);
538 if(!cur.next() || countWords() != cur.value(0).toInt())
540 Q_EMIT updateCachingProgress(100, timer.restart());
541 Q_EMIT notify(Notify::Warning,
542 QString("Database caching error, please try againg."));
546 _settings->setValue("cache_path", cachePathN);
547 _settings->setValue("cached", "true");
553 Q_EXPORT_PLUGIN2(xdxf, XdxfPlugin)