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("xdxf"), _infoNote(tr("")) {
34 _settings = new Settings();
35 _dictDialog = new XdxfDictDialog(this);
36 cachingDialog = new XdxfCachingDialog();
38 connect(cachingDialog, SIGNAL(cancelCaching()),
41 connect(this, SIGNAL(updateCachingProgress(int,int)),
42 cachingDialog, SLOT(updateCachingProgress(int,int)));
44 _settings->setValue("type","xdxf");
48 _icon = QIcon(":/icons/xdxf.png");
54 XdxfPlugin::~XdxfPlugin() {
59 QString XdxfPlugin::langFrom() const {
63 QString XdxfPlugin::langTo() const {
67 QString XdxfPlugin::name() const {
71 QString XdxfPlugin::type() const {
75 QString XdxfPlugin::infoNote() const {
79 QList<Translation*> XdxfPlugin::searchWordList(QString word, int limit) {
80 if(word.indexOf("*")==-1 && word.indexOf("?")==-1 && word.indexOf("_")==-1
81 && word.indexOf("%")==-1)
84 return searchWordListCache(word,limit);
85 return searchWordListFile(word, limit);
88 QList<Translation*> XdxfPlugin::searchWordListCache(QString word, int limit) {
90 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 ? or normalized like ? limit ?");
111 cur.prepare("select word from dict where word like ? or normalized like ?");
112 cur.addBindValue(word);
113 cur.addBindValue(word);
115 cur.addBindValue(limit);
118 while(cur.next() && (i<limit || limit==0 ) ) {
122 foreach(tran,translations) {
123 if(tran->key().toLower()==cur.value(0).toString().toLower())
126 if(ok) { /*add key word to list*/
127 translations.insert(new TranslationXdxf(
128 cur.value(0).toString().toLower(),
134 return translations.toList();
137 QList<Translation*> XdxfPlugin::searchWordListFile(QString word, int limit) {
140 QSet<Translation*> translations;
141 QFile dictionaryFile(path);
143 word = word.toLower();
144 //word = removeAccents(word);
147 QRegExp regWord(word);
148 regWord.setCaseSensitivity(Qt::CaseInsensitive);
149 regWord.setPatternSyntax(QRegExp::Wildcard);
150 if(!dictionaryFile.open(QFile::ReadOnly | QFile::Text)) {
151 qDebug()<<"Error: could not open file";
152 Q_EMIT notify(Notify::Warning,
153 QString("Xdxf file cannot be read for %1").arg(name()));
154 return translations.toList();
157 QXmlStreamReader reader(&dictionaryFile);
158 /*search words list*/
162 while(!reader.atEnd() && !stopped){
163 reader.readNextStartElement();
164 if(reader.name()=="ar") {
165 while(reader.name()!="k" && !reader.atEnd())
166 reader.readNextStartElement();
168 a = reader.readElementText();
169 if((regWord.exactMatch(a) || regWord.exactMatch(removeAccents(a))) &&
170 (i<limit || limit==0)) {
173 foreach(tran,translations) {
174 if(tran->key().toLower()==a.toLower())
175 ok=false; /*if key word is in the dictionary more that one */
177 if(ok) { /*add key word to list*/
178 translations<<(new TranslationXdxf(a.toLower(),
182 if(i>=limit && limit!=0)
186 this->thread()->yieldCurrentThread();
189 dictionaryFile.close();
190 qDebug() << time.elapsed();
191 return translations.toList();
194 QString XdxfPlugin::search(QString key) {
195 // if(_settings->value("cached") == "true")
197 return searchCache(key);
198 return searchFile(key);
201 QString XdxfPlugin::searchCache(QString key) {
203 QString cacheFilePath = _settings->value("cache_path");
204 db.setDatabaseName(cacheFilePath);
208 qDebug() << "Database error" << db.lastError().text() << endl;
209 Q_EMIT notify(Notify::Warning, QString("Cache database cannot be "
210 "opened for %1 dictionary. Searching in xdxf file. "
211 "You may want to recache.").arg(name()));
212 return searchFile(key);
216 cur.prepare("select translation from dict where word like ?");
217 cur.addBindValue(key);
220 result += cur.value(0).toString();
228 QString XdxfPlugin::searchFile(QString key) {
230 QFile dictionaryFile(path);
231 QString resultString("");
232 if(!dictionaryFile.open(QFile::ReadOnly | QFile::Text)) {
233 Q_EMIT notify(Notify::Warning,
234 QString("Xdxf file cannot be read for %1").arg(name()));
235 qDebug()<<"Error: could not open file";
238 QXmlStreamReader reader(&dictionaryFile);
243 while (!reader.atEnd()&& !stopped) {
245 if(reader.tokenType() == QXmlStreamReader::StartElement) {
246 if(reader.name()=="k") {
247 a = reader.readElementText();
248 if(a.toLower()==key.toLower())
254 while(reader.name()!="ar" && !reader.atEnd()) {
255 if(reader.name()!="" && reader.name()!="k") {
256 if(reader.tokenType()==QXmlStreamReader::EndElement)
258 if(reader.tokenType()==QXmlStreamReader::StartElement)
260 temp+=reader.name().toString();
261 if(reader.name().toString()=="c" &&
262 reader.tokenType()==QXmlStreamReader::StartElement)
263 temp= temp + tr(" c=\"") + reader.attributes().
264 value(tr("c")).toString() + tr("\"");
267 temp+= reader.text().toString().replace("<","<").
271 if(temp.at(0)==QChar('\n'))
273 resultString+=tr("<key>") + a +tr("</key>");
274 resultString+=tr("<t>") + temp + tr("</t>");
277 this->thread()->yieldCurrentThread();
280 dictionaryFile.close();
285 void XdxfPlugin::stop() {
289 DictDialog* XdxfPlugin::dictDialog() {
293 void XdxfPlugin::setPath(QString path){
295 _settings->setValue("path",path);
296 //getDictionaryInfo();
299 CommonDictInterface* XdxfPlugin::getNew(const Settings *settings) const {
300 XdxfPlugin *plugin = new XdxfPlugin();
302 plugin->setPath(settings->value("path"));
303 QStringList list = settings->keys();
305 plugin->db_name = plugin->_settings->value("type")
306 + plugin->_settings->value("path");
307 plugin->db = QSqlDatabase::addDatabase("QSQLITE", plugin->db_name);
309 if(settings->value("cached").isEmpty() &&
310 settings->value("generateCache") == "true") {
311 plugin->makeCache("");
313 foreach(QString key, list)
314 if(key != "generateCache")
315 plugin->settings()->setValue(key, settings->value(key));
318 plugin->getDictionaryInfo();
322 bool XdxfPlugin::isAvailable() const {
328 void XdxfPlugin::setHash(uint _hash) {
334 uint XdxfPlugin::hash() const {
340 Settings* XdxfPlugin::settings() {
346 bool XdxfPlugin::isCached() {
347 if(_settings->value("cached") == "true")
354 void XdxfPlugin::setSettings(Settings *settings) {
356 QString oldPath = _settings->value("path");
357 if(oldPath != settings->value("path")) {
358 setPath(settings->value("path"));
361 foreach(QString key, settings->keys())
362 if(key != "generateCache")
363 _settings->setValue(key, settings->value(key));
365 if((_settings->value("cached") == "false" ||
366 _settings->value("cached").isEmpty()) &&
367 settings->value("generateCache") == "true") {
370 else if (settings->value("generateCache") != "true") {
371 _settings->setValue("cached", "false");
377 Q_EMIT settingsChanged();
382 void XdxfPlugin::getDictionaryInfo() {
383 QFile dictionaryFile(path);
384 if(!dictionaryFile.open(QFile::ReadOnly | QFile::Text)) {
385 Q_EMIT notify(Notify::Warning,
386 QString("Xdxf file cannot be read dictionary"));
387 qDebug()<<"Error: could not open file";
391 QXmlStreamReader reader(&dictionaryFile);
392 reader.readNextStartElement();
393 if(reader.name()=="xdxf") {
394 if(reader.attributes().hasAttribute("lang_from"))
395 _langFrom = reader.attributes().value("lang_from").toString();
396 if(reader.attributes().hasAttribute("lang_to"))
397 _langTo = reader.attributes().value("lang_to").toString();
399 reader.readNextStartElement();
400 if(reader.name()=="full_name")
401 _name=reader.readElementText();
402 reader.readNextStartElement();
403 if(reader.name()=="description")
404 _infoNote=reader.readElementText();
406 QString format = "png";
407 QString initialPath = QDir::currentPath() + tr("/xdxf.") + format;
409 _infoNote="path=\""+initialPath+"\"> \n" + _name + " [" + _langFrom + "-" + _langTo + "] (" + _type + ")";
410 dictionaryFile.close();
415 QIcon* XdxfPlugin::icon() {
419 int XdxfPlugin::countWords() {
423 QFile dictionaryFile(path);
424 if(!dictionaryFile.open(QFile::ReadOnly | QFile::Text)) {
425 Q_EMIT notify(Notify::Warning,
426 QString("Xdxf file cannot be read for %1 dictionary")
428 qDebug()<<"Error: could not open file";
432 dictionaryFile.seek(0);
437 while(!dictionaryFile.atEnd()) {
438 line = dictionaryFile.readLine();
439 if(line.contains("<k>")) {
443 _wordsCount = wordsCount;
444 dictionaryFile.close();
448 bool XdxfPlugin::makeCache(QString dir) {
449 cachingDialog->setVisible(true);
450 QCoreApplication::processEvents();
452 QFileInfo dictFileN(_settings->value("path"));
454 cachePathN = QDir::homePath() + "/.mdictionary/"
455 + dictFileN.completeBaseName() + ".cache";
457 QFile dictionaryFile(dictFileN.filePath());
460 if (!dictionaryFile.open(QFile::ReadOnly | QFile::Text)) {
461 Q_EMIT updateCachingProgress(100, 0);
462 Q_EMIT notify(Notify::Warning,
463 QString("Xdxf file cannot be read for %1 dictionary")
467 QXmlStreamReader reader(&dictionaryFile);
470 db.setDatabaseName(cachePathN);
472 qDebug() << "Database error" << db.lastError().text() << endl;
473 Q_EMIT updateCachingProgress(100, 0);
474 Q_EMIT notify(Notify::Warning, QString("Cache database cannot be "
475 "opened for %1 dictionary. Searching in xdxf file. "
476 "You may want to recache.").arg(name()));
479 QCoreApplication::processEvents();
481 cur.exec("PRAGMA synchronous = 0");
482 cur.exec("drop table dict");
483 QCoreApplication::processEvents();
484 cur.exec("create table dict(word text, normalized text ,translation text)");
496 QString stripAcc = settings()->value("strip_accents");
497 settings()->setValue("strip_accents", "true");
501 while (!reader.atEnd() && !stopped) {
503 QCoreApplication::processEvents();
506 if(reader.tokenType() == QXmlStreamReader::StartElement) {
507 if(reader.name()=="k"){
508 a = reader.readElementText();
514 while(reader.name()!="ar" && !reader.atEnd()) {
515 if(reader.name()!="" && reader.name()!="k") {
516 if(reader.tokenType()==QXmlStreamReader::EndElement)
518 if(reader.tokenType()==QXmlStreamReader::StartElement)
520 temp+=reader.name().toString();
521 if(reader.name().toString()=="c" && reader.tokenType()==QXmlStreamReader::StartElement)
522 temp= temp + tr(" c=\"") + reader.attributes().value(tr("c")).toString() + tr("\"");
525 temp+= reader.text().toString().replace("<","<").replace(">",">");;
528 if(temp.at(0)==QChar('\n'))
530 temp=tr("<key>") + a + tr("</key>") + tr("<t>") + temp+ tr("</t>");
532 cur.prepare("insert into dict values(?,?,?)");
534 cur.addBindValue(removeAccents(a));
535 cur.addBindValue(temp);
538 int prog = counter*100/_wordsCount;
539 if(prog % 5 == 0 && lastProg != prog) {
540 Q_EMIT updateCachingProgress(prog,
548 cur.exec("select count(*) from dict");
549 settings()->setValue("strip_accents", stripAcc);
552 cachingDialog->setVisible(false);
554 if(!cur.next() || countWords() != cur.value(0).toInt())
556 Q_EMIT updateCachingProgress(100, timer.restart());
557 Q_EMIT notify(Notify::Warning,
558 QString("Database caching error, please try againg."));
562 _settings->setValue("cache_path", cachePathN);
563 _settings->setValue("cached", "true");
572 void XdxfPlugin::clean() {
573 if(settings()->value("cached") == "true")
574 QFile(settings()->value("cache_path")).remove();
577 Q_EXPORT_PLUGIN2(xdxf, XdxfPlugin)