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
23 \author Jakub Jaszczynski <j.j.jaszczynski@gmail.com>
26 #include "xdxfplugin.h"
28 #include "../../../includes/Notify.h"
30 XdxfPlugin::XdxfPlugin(QObject *parent) : CommonDictInterface(parent),
31 _langFrom(tr("")), _langTo(tr("")),_name(tr("")),
32 _type(tr("xdxf")), _infoNote(tr("")) {
34 _settings = new Settings();
35 _dictDialog = new XdxfDictDialog(this, this);
36 cachingDialog = new XdxfCachingDialog(this);
38 connect(cachingDialog, SIGNAL(cancelCaching()),
41 _settings->setValue("type","xdxf");
45 _icon = QIcon(":/icons/xdxf.png");
48 XdxfPlugin::~XdxfPlugin()
50 // QString connection(db.connectionName());
52 // QSqlDatabase::removeDatabase(connection);
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();
216 QString XdxfPlugin::searchFile(QString key) {
218 QFile dictionaryFile(path);
219 QString resultString("");
220 if(!dictionaryFile.open(QFile::ReadOnly | QFile::Text)) {
221 Q_EMIT notify(Notify::Warning,
222 QString("Xdxf file cannot be read for %1").arg(name()));
223 qDebug()<<"Error: could not open file";
226 QXmlStreamReader reader(&dictionaryFile);
231 while (!reader.atEnd()&& !stopped) {
233 if(reader.tokenType() == QXmlStreamReader::StartElement) {
234 if(reader.name()=="k") {
235 a = reader.readElementText();
236 if(a.toLower()==key.toLower())
242 while(reader.name()!="ar" && !reader.atEnd()) {
243 if(reader.name()!="" && reader.name()!="k") {
244 if(reader.tokenType()==QXmlStreamReader::EndElement)
246 if(reader.tokenType()==QXmlStreamReader::StartElement)
248 temp+=reader.name().toString();
249 if(reader.name().toString()=="c" && reader.tokenType()==QXmlStreamReader::StartElement)
250 temp= temp + tr(" c=\"") + reader.attributes().value(tr("c")).toString() + tr("\"");
253 temp+= reader.text().toString().replace("<","<").replace(">",">");
256 if(temp.at(0)==QChar('\n'))
258 resultString+=tr("<key>") + a +tr("</key>");
259 resultString+=tr("<t>") + temp + tr("</t>");
262 this->thread()->yieldCurrentThread();
265 dictionaryFile.close();
270 void XdxfPlugin::stop() {
274 DictDialog* XdxfPlugin::dictDialog() {
278 void XdxfPlugin::setPath(QString path){
280 _settings->setValue("path",path);
281 //getDictionaryInfo();
284 CommonDictInterface* XdxfPlugin::getNew(const Settings *settings) const {
285 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));
292 plugin->db_name = plugin->_settings->value("type")
293 + plugin->_settings->value("path");
294 plugin->db = QSqlDatabase::addDatabase("QSQLITE", plugin->db_name);
296 if(settings->value("cached").isEmpty() &&
297 settings->value("generateCache") == "true") {
298 plugin->makeCache("");
302 plugin->getDictionaryInfo();
306 bool XdxfPlugin::isAvailable() const {
310 void XdxfPlugin::setHash(uint _hash) {
314 uint XdxfPlugin::hash() const {
318 Settings* XdxfPlugin::settings() {
322 bool XdxfPlugin::isCached() {
323 if(_settings->value("cached") == "true")
328 void XdxfPlugin::setSettings(Settings *settings) {
330 QString oldPath = _settings->value("path");
331 if(oldPath != settings->value("path")) {
332 setPath(settings->value("path"));
335 if((_settings->value("cached") == "false" ||
336 _settings->value("cached").isEmpty()) &&
337 settings->value("generateCache") == "true") {
341 _settings->setValue("cached", "false");
345 Q_EMIT settingsChanged();
348 void XdxfPlugin::getDictionaryInfo() {
349 QFile dictionaryFile(path);
350 if(!dictionaryFile.open(QFile::ReadOnly | QFile::Text)) {
351 Q_EMIT notify(Notify::Warning,
352 QString("Xdxf file cannot be read dictionary"));
353 qDebug()<<"Error: could not open file";
357 QXmlStreamReader reader(&dictionaryFile);
358 reader.readNextStartElement();
359 if(reader.name()=="xdxf") {
360 if(reader.attributes().hasAttribute("lang_from"))
361 _langFrom = reader.attributes().value("lang_from").toString();
362 if(reader.attributes().hasAttribute("lang_to"))
363 _langTo = reader.attributes().value("lang_to").toString();
365 reader.readNextStartElement();
366 if(reader.name()=="full_name")
367 _name=reader.readElementText();
368 reader.readNextStartElement();
369 if(reader.name()=="description")
370 _infoNote=reader.readElementText();
372 QString format = "png";
373 QString initialPath = QDir::currentPath() + tr("/xdxf.") + format;
375 _infoNote="path=\""+initialPath+"\"> \n" + _name + " [" + _langFrom + "-" + _langTo + "] (" + _type + ")";
377 dictionaryFile.close();
380 QString XdxfPlugin::removeAccents(QString string) {
381 string = string.replace(QString::fromUtf8("ł"), "l", Qt::CaseInsensitive);
382 QString normalized = string.normalized(QString::NormalizationForm_D);
383 normalized = normalized;
384 for(int i=0; i<normalized.size(); i++) {
385 if( !normalized[i].isLetterOrNumber() &&
386 !normalized[i].isSpace() &&
387 !normalized[i].isDigit() &&
388 normalized[i] != '*' &&
389 normalized[i] != '%' &&
390 normalized[i] != '_' &&
391 normalized[i] != '?' ) {
392 normalized.remove(i,1);
398 QIcon* XdxfPlugin::icon() {
402 int XdxfPlugin::countWords() {
406 QFile dictionaryFile(path);
407 if(!dictionaryFile.open(QFile::ReadOnly | QFile::Text)) {
408 Q_EMIT notify(Notify::Warning,
409 QString("Xdxf file cannot be read for %1 dictionary")
411 qDebug()<<"Error: could not open file";
415 dictionaryFile.seek(0);
420 while(!dictionaryFile.atEnd()) {
421 line = dictionaryFile.readLine();
422 if(line.contains("<k>")) {
426 _wordsCount = wordsCount;
427 dictionaryFile.close();
431 bool XdxfPlugin::makeCache(QString dir) {
432 cachingDialog->setVisible(true);
433 QCoreApplication::processEvents();
435 QFileInfo dictFileN(_settings->value("path"));
437 cachePathN = QDir::homePath() + "/.mdictionary/"
438 + dictFileN.completeBaseName() + ".cache";
440 QFile dictionaryFile(dictFileN.filePath());
443 if (!dictionaryFile.open(QFile::ReadOnly | QFile::Text)) {
444 Q_EMIT updateCachingProgress(100, 0);
445 Q_EMIT notify(Notify::Warning,
446 QString("Xdxf file cannot be read for %1 dictionary")
451 QXmlStreamReader reader(&dictionaryFile);
453 db.setDatabaseName(cachePathN);
455 qDebug() << "Database error" << db.lastError().text() << endl;
456 Q_EMIT updateCachingProgress(100, 0);
457 Q_EMIT notify(Notify::Warning, QString("Cache database cannot be "
458 "opened for %1 dictionary. Searching in xdxf file. "
459 "You may want to recache.").arg(name()));
462 QCoreApplication::processEvents();
464 cur.exec("PRAGMA synchronous = 0");
465 cur.exec("drop table dict");
466 QCoreApplication::processEvents();
467 cur.exec("create table dict(word text ,translation text)");
481 while (!reader.atEnd() && !stopped) {
483 QCoreApplication::processEvents();
486 if(reader.tokenType() == QXmlStreamReader::StartElement) {
487 if(reader.name()=="k"){
488 a = reader.readElementText();
494 while(reader.name()!="ar" && !reader.atEnd()) {
495 if(reader.name()!="" && reader.name()!="k") {
496 if(reader.tokenType()==QXmlStreamReader::EndElement)
498 if(reader.tokenType()==QXmlStreamReader::StartElement)
500 temp+=reader.name().toString();
501 if(reader.name().toString()=="c" && reader.tokenType()==QXmlStreamReader::StartElement)
502 temp= temp + tr(" c=\"") + reader.attributes().value(tr("c")).toString() + tr("\"");
505 temp+= reader.text().toString().replace("<","<").replace(">",">");;
508 if(temp.at(0)==QChar('\n'))
510 temp=tr("<key>") + a + tr("</key>") + tr("<t>") + temp+ tr("</t>");
512 cur.prepare("insert into dict values(?,?)");
514 cur.addBindValue(temp);
517 int prog = counter*100/_wordsCount;
518 if(prog % 5 == 0 && lastProg != prog) {
519 Q_EMIT updateCachingProgress(prog,
527 cur.exec("select count(*) from dict");
530 cachingDialog->setVisible(false);
532 if(!cur.next() || countWords() != cur.value(0).toInt())
534 Q_EMIT updateCachingProgress(100, timer.restart());
535 Q_EMIT notify(Notify::Warning,
536 QString("Database caching error, please try againg."));
540 _settings->setValue("cache_path", cachePathN);
541 _settings->setValue("cached", "true");
548 Q_EXPORT_PLUGIN2(xdxf, XdxfPlugin)