diff options
author | Dmitrijs Ledkovs <xnox@debian.org> | 2012-04-14 18:11:50 +0100 |
---|---|---|
committer | Roberto C. Sanchez <roberto@connexer.com> | 2014-10-21 22:48:45 -0400 |
commit | 1da8254d16a30cc96f545d198975e9f3a4d847be (patch) | |
tree | 6d94b7a0d34cb80e14287ae50994f1c46d39a154 /src | |
parent | bc6baa3433b5781439754ff2a2a4d475986ec393 (diff) | |
parent | 00bc0a3de99e088902379dcb2905fb1546c7eca2 (diff) |
Imported Debian patch 2.9.1-1
Diffstat (limited to 'src')
211 files changed, 4062 insertions, 4348 deletions
diff --git a/src/backend/bookshelfmodel/btbookshelfmodel.cpp b/src/backend/bookshelfmodel/btbookshelfmodel.cpp index c6aab1b..322b22a 100644 --- a/src/backend/bookshelfmodel/btbookshelfmodel.cpp +++ b/src/backend/bookshelfmodel/btbookshelfmodel.cpp @@ -54,6 +54,10 @@ QVariant BtBookshelfModel::data(CSwordModuleInfo *module, int role) const { return (qulonglong) module->indexSize(); case ModuleDescriptionRole: return module->config(CSwordModuleInfo::Description); + case Qt::ToolTipRole: + return QString("<b>%1:</b><br/>%2") + .arg(module->name()) + .arg(module->config(CSwordModuleInfo::Description)); default: return QVariant(); } diff --git a/src/backend/bookshelfmodel/btbookshelftreemodel.cpp b/src/backend/bookshelfmodel/btbookshelftreemodel.cpp index 6444a81..3d6008f 100644 --- a/src/backend/bookshelfmodel/btbookshelftreemodel.cpp +++ b/src/backend/bookshelfmodel/btbookshelftreemodel.cpp @@ -27,8 +27,11 @@ using namespace BookshelfModel; bool BtBookshelfTreeModel::Grouping::loadFrom(const QString &configKey) { Q_ASSERT(!configKey.isNull()); QVariant v = CBTConfig::getConfig()->value(configKey); + if (!v.canConvert<Grouping>()) + return false; + (*this) = v.value<Grouping>(); - return v.canConvert<Grouping>(); + return true; } void BtBookshelfTreeModel::Grouping::saveTo(const QString &configKey) const { diff --git a/src/backend/bookshelfmodel/btbookshelftreemodel.h b/src/backend/bookshelfmodel/btbookshelftreemodel.h index 2a28dd8..085095d 100644 --- a/src/backend/bookshelfmodel/btbookshelftreemodel.h +++ b/src/backend/bookshelfmodel/btbookshelftreemodel.h @@ -59,13 +59,17 @@ class BtBookshelfTreeModel: public QAbstractItemModel { \warning Be careful using this constructor! */ explicit inline Grouping(bool empty = false) { - if (empty) return; + if (empty) + return; push_back(GROUP_CATEGORY); push_back(GROUP_LANGUAGE); } explicit inline Grouping(Group group) { push_back(group); } explicit inline Grouping(const QString &configKey) { - loadFrom(configKey); + if (loadFrom(configKey)) + return; + push_back(GROUP_CATEGORY); + push_back(GROUP_LANGUAGE); } inline Grouping(const Grouping ©) : QList<Group>(copy) {} diff --git a/src/backend/btinstallbackend.cpp b/src/backend/btinstallbackend.cpp index 67f8945..c1136bf 100644 --- a/src/backend/btinstallbackend.cpp +++ b/src/backend/btinstallbackend.cpp @@ -30,7 +30,6 @@ namespace BtInstallBackend { /** Adds the source described by Source to the backend. */ bool addSource(sword::InstallSource& source) { - qDebug() << "backend::addSource"; SWConfig config(configFilename().toLatin1()); if (!strcmp(source.type, "FTP")) { //make sure the path doesn't have a trailing slash, sword doesn't like it @@ -49,7 +48,6 @@ bool addSource(sword::InstallSource& source) { /** Returns the Source struct. */ sword::InstallSource source(const QString &name) { - qDebug() << "backend::source"; BtInstallMgr mgr; InstallSourceMap::iterator source = mgr.sources.find(name.toLatin1().data()); if (source != mgr.sources.end()) { @@ -84,7 +82,6 @@ sword::InstallSource source(const QString &name) { /** Deletes the source. */ bool deleteSource(const QString &name) { - qDebug() << "backend::deleteSource"; sword::InstallSource is = source(name ); SWConfig config(configFilename().toLatin1()); @@ -108,7 +105,7 @@ bool deleteSource(const QString &name) { ++it; } if (notFound) { - qDebug() << "source was not found, try without uid"; + qDebug() << "source was not found, trying without uid"; //try again without uid QString sce(sourceConfigEntry.c_str()); QStringList l = sce.split('|'); @@ -116,7 +113,6 @@ bool deleteSource(const QString &name) { sce = l.join("|").append("|"); it = range.first; while (it != range.second) { - qDebug() << it->second; if (it->second == sce) { config["Sources"].erase(it); break; @@ -148,7 +144,6 @@ QString configFilename() { } QStringList targetList() { - qDebug() << "backend::targetList"; QStringList names = CSwordBackend::instance()->swordDirList(); return names; } @@ -156,7 +151,6 @@ QStringList targetList() { bool setTargetList( const QStringList& targets ) { namespace DU = util::directory; - qDebug() << "backend::setTargetList"; //saves a new Sword config using the provided target list //QString filename = KGlobal::dirs()->saveLocation("data", "bibletime/") + "sword.conf"; //default is to assume the real location isn't writable //QString filename = util::DirectoryUtil::getUserBaseDir().canonicalPath().append("/.sword/sword.conf"); @@ -174,10 +168,7 @@ bool setTargetList( const QStringList& targets ) { f.close(); i.refresh(); } - if ( i.exists() && i.isWritable() ) { //we can write to the file ourself - qDebug() << "The Sword config file is writable"; - } - else { + if (!i.exists() || !i.isWritable()) { // There is no way to save to the file qWarning() << "The Sword config file is not writable!"; util::showWarning(0, QObject::tr("Can't write file"), QObject::tr("The Sword config file can't be written!")); @@ -213,14 +204,13 @@ bool setTargetList( const QStringList& targets ) { setDataPath = true; } } - qDebug() << "save the sword conf..."; + qDebug() << "Saving Sword configuration ..."; conf.Save(); CSwordBackend::instance()->reloadModules(CSwordBackend::PathChanged); return true; } QStringList sourceNameList() { - qDebug() << "backend::sourceList"; BtInstallMgr mgr; Q_ASSERT(mgr.installConf); @@ -251,7 +241,6 @@ QStringList sourceNameList() { void initPassiveFtpMode() { - qDebug() << "backend::initPassiveFtpMode"; SWConfig config(configFilename().toLatin1()); config["General"]["PassiveFTP"] = "true"; config.Save(); @@ -259,13 +248,13 @@ void initPassiveFtpMode() { QString swordConfigFilename() { namespace DU = util::directory; - qDebug() << "backend::swordConfigFilename"; + qDebug() << "Sword config:" #ifdef Q_WS_WIN - qDebug() << DU::getUserHomeDir().absolutePath().append("/Sword/sword.conf"); + << DU::getUserHomeDir().absolutePath().append("/Sword/sword.conf"); return DU::getUserHomeDir().absolutePath().append("/Sword/sword.conf"); // return DU::getApplicationDir().absolutePath().append("/sword.conf"); #else - qDebug() << DU::getUserHomeDir().absolutePath().append("/.sword/sword.conf"); + << DU::getUserHomeDir().absolutePath().append("/.sword/sword.conf"); return DU::getUserHomeDir().absolutePath().append("/.sword/sword.conf"); #endif } @@ -281,7 +270,6 @@ QDir swordDir() { } CSwordBackend* backend( const sword::InstallSource& is) { - qDebug() << "backend::backend"; CSwordBackend* ret = 0; /// \anchor BackendNotSingleton if (isRemote(is)) { diff --git a/src/backend/btmoduletreeitem.cpp b/src/backend/btmoduletreeitem.cpp index c57d094..4c16231 100644 --- a/src/backend/btmoduletreeitem.cpp +++ b/src/backend/btmoduletreeitem.cpp @@ -9,7 +9,6 @@ #include "backend/btmoduletreeitem.h" -#include <QDebug> #include <QList> #include <QString> #include "backend/drivers/cswordmoduleinfo.h" @@ -24,7 +23,8 @@ BTModuleTreeItem::BTModuleTreeItem(QList<BTModuleTreeItem::Filter*>& filters, BT m_firstChild(0), m_next(0), m_type(BTModuleTreeItem::Root), - m_category(CSwordModuleInfo::UnknownCategory) { + m_category(CSwordModuleInfo::UnknownCategory), + m_grouping (grouping) { if (modules) { m_originalModuleList = *modules; } @@ -32,7 +32,7 @@ BTModuleTreeItem::BTModuleTreeItem(QList<BTModuleTreeItem::Filter*>& filters, BT m_originalModuleList = CSwordBackend::instance()->moduleList(); } //populate the tree with groups/modules - create_tree(filters, grouping); + create_tree(filters); } /** @@ -64,12 +64,10 @@ BTModuleTreeItem::~BTModuleTreeItem() { } QList<BTModuleTreeItem*> BTModuleTreeItem::children() const { - //qDebug() << "BTModuleTreeItem::children"; QList<BTModuleTreeItem*> childList; if (m_firstChild) { BTModuleTreeItem* child = m_firstChild; while (child) { - //qDebug() << "child:" << child->text(); childList.append(child); child = child->m_next; } @@ -120,26 +118,26 @@ QString BTModuleTreeItem::iconName() const { return QString::null; } - -void BTModuleTreeItem::create_tree(QList<BTModuleTreeItem::Filter*>& filters, BTModuleTreeItem::Grouping grouping) { - qDebug() << "BTModuleTreeItem::create_tree"; - static bool map_initialized = false; - static QMap<CSwordModuleInfo::Category, QString> CategoryNamesMap; - if (!map_initialized) { - CategoryNamesMap.insert(CSwordModuleInfo::Commentaries, QObject::tr("Commentaries")); - CategoryNamesMap.insert(CSwordModuleInfo::Cult, QObject::tr("Cults/Unorthodox")); - CategoryNamesMap.insert(CSwordModuleInfo::Images, QObject::tr("Maps and Images")); - CategoryNamesMap.insert(CSwordModuleInfo::DailyDevotional, QObject::tr("Daily Devotionals")); - CategoryNamesMap.insert(CSwordModuleInfo::Lexicons, QObject::tr("Lexicons and Dictionaries")); - CategoryNamesMap.insert(CSwordModuleInfo::Bibles, QObject::tr("Bibles")); - CategoryNamesMap.insert(CSwordModuleInfo::Glossary, QObject::tr("Glossaries")); - CategoryNamesMap.insert(CSwordModuleInfo::Books, QObject::tr("Books")); - - map_initialized = true; +bool BTModuleTreeItem::m_map_initialized = false; +QMap<CSwordModuleInfo::Category, QString> BTModuleTreeItem::m_CategoryNamesMap; + +void BTModuleTreeItem::create_tree(QList<BTModuleTreeItem::Filter*>& filters) { + if (!m_map_initialized) { + m_CategoryNamesMap.insert(CSwordModuleInfo::Commentaries, QObject::tr("Commentaries")); + m_CategoryNamesMap.insert(CSwordModuleInfo::Cult, QObject::tr("Cults/Unorthodox")); + m_CategoryNamesMap.insert(CSwordModuleInfo::Images, QObject::tr("Maps and Images")); + m_CategoryNamesMap.insert(CSwordModuleInfo::DailyDevotional, QObject::tr("Daily Devotionals")); + m_CategoryNamesMap.insert(CSwordModuleInfo::Lexicons, QObject::tr("Lexicons and Dictionaries")); + m_CategoryNamesMap.insert(CSwordModuleInfo::Bibles, QObject::tr("Bibles")); + m_CategoryNamesMap.insert(CSwordModuleInfo::Glossary, QObject::tr("Glossaries")); + m_CategoryNamesMap.insert(CSwordModuleInfo::Books, QObject::tr("Books")); + + m_map_initialized = true; } + add_items(filters); +} - //QList<CSwordModuleInfo*> originalInfoList = CSwordBackend::instance()()->moduleList(); - +void BTModuleTreeItem::add_items(QList<BTModuleTreeItem::Filter*>& filters) { foreach (CSwordModuleInfo* info, m_originalModuleList) { bool included; included = true; @@ -150,39 +148,37 @@ void BTModuleTreeItem::create_tree(QList<BTModuleTreeItem::Filter*>& filters, BT } } if (included) { - //qDebug() << "a module will be included: " << info->name(); - BTModuleTreeItem* parentGroupForModule = this; BTModuleTreeItem* parentGroupForLanguage = this; BTModuleTreeItem* parentGroupForCategory = this; //the order of if(grouping...) clauses is important - if (grouping == BTModuleTreeItem::LangMod || grouping == BTModuleTreeItem::LangCatMod) { + if (m_grouping == BTModuleTreeItem::LangMod || m_grouping == BTModuleTreeItem::LangCatMod) { BTModuleTreeItem* langItem = create_parent_item(parentGroupForLanguage, info->language()->translatedName(), BTModuleTreeItem::Language); - if (grouping == BTModuleTreeItem::LangMod) + if (m_grouping == BTModuleTreeItem::LangMod) parentGroupForModule = langItem; else parentGroupForCategory = langItem; } - if (grouping == BTModuleTreeItem::CatMod || grouping == BTModuleTreeItem::CatLangMod) { - BTModuleTreeItem* catItem = create_parent_item(parentGroupForCategory, CategoryNamesMap.value(info->category()), BTModuleTreeItem::Category, info->category()); + if (m_grouping == BTModuleTreeItem::CatMod || m_grouping == BTModuleTreeItem::CatLangMod) { + BTModuleTreeItem* catItem = create_parent_item(parentGroupForCategory, m_CategoryNamesMap.value(info->category()), BTModuleTreeItem::Category, info->category()); - if (grouping == BTModuleTreeItem::CatMod) + if (m_grouping == BTModuleTreeItem::CatMod) parentGroupForModule = catItem; else parentGroupForLanguage = catItem; } - if (grouping == BTModuleTreeItem::CatLangMod) { + if (m_grouping == BTModuleTreeItem::CatLangMod) { // category is there already, create language and make it the parent for the module parentGroupForModule = create_parent_item(parentGroupForLanguage, info->language()->translatedName(), BTModuleTreeItem::Language); } - if (grouping == BTModuleTreeItem::LangCatMod) { + if (m_grouping == BTModuleTreeItem::LangCatMod) { //language is there already, create category and make it the parent for the module - parentGroupForModule = create_parent_item(parentGroupForCategory, CategoryNamesMap.value(info->category()), BTModuleTreeItem::Category, info->category()); + parentGroupForModule = create_parent_item(parentGroupForCategory, m_CategoryNamesMap.value(info->category()), BTModuleTreeItem::Category, info->category()); } // the parent group for module has been set above, now just add the module to it @@ -214,8 +210,6 @@ BTModuleTreeItem* BTModuleTreeItem::create_parent_item( } void BTModuleTreeItem::sort_children(BTModuleTreeItem* parent) { - //qDebug() << "BTModuleTreeItem::sort_children"; - // sort each child recursively depth-first foreach(BTModuleTreeItem* item, parent->children()) { sort_children(item); @@ -259,3 +253,15 @@ bool BTModuleTreeItem::localeAwareLessThan(BTModuleTreeItem* first, BTModuleTree } return (QString::localeAwareCompare(first->text(), second->text()) < 0 ); } + +QDataStream &operator<<(QDataStream &out, const BTModuleTreeItem::Grouping &grouping) { + out << (qint8) grouping; + return out; +} + +QDataStream &operator>>(QDataStream &in, BTModuleTreeItem::Grouping &grouping) { + qint8 i; + in >> i; + grouping = (BTModuleTreeItem::Grouping) i; + return in; +} diff --git a/src/backend/btmoduletreeitem.h b/src/backend/btmoduletreeitem.h index 6ee6868..008bfb2 100644 --- a/src/backend/btmoduletreeitem.h +++ b/src/backend/btmoduletreeitem.h @@ -10,6 +10,7 @@ #ifndef BTMODULETREEITEM_H #define BTMODULETREEITEM_H +#include <QMap> #include <QString> #include "backend/drivers/cswordmoduleinfo.h" @@ -70,7 +71,6 @@ class BTModuleTreeItem { */ struct Filter { virtual bool filter(CSwordModuleInfo*) = 0; - inline virtual ~Filter() {}; }; /** @@ -81,7 +81,6 @@ class BTModuleTreeItem { inline bool filter(CSwordModuleInfo* mi) { return !mi->isHidden(); } - inline virtual ~HiddenOff() {}; }; /** @@ -94,7 +93,13 @@ class BTModuleTreeItem { * CatLangMod: first category, second language, third module. Mod: don't use * Category or Language at all, Module is toplevel and tree is flat. */ - enum Grouping {CatLangMod, CatMod, LangCatMod, LangMod, Mod}; + enum Grouping { + CatLangMod = 0, + CatMod = 1, + LangCatMod = 2, + LangMod = 3, + Mod = 4 + }; /** @@ -110,6 +115,9 @@ class BTModuleTreeItem { /** When the root item is deleted the whole tree is deleted. */ ~BTModuleTreeItem(); + /** Adds filtered items to the tree */ + void add_items(QList<BTModuleTreeItem::Filter*>& filters); + /** * Returns the item type. */ @@ -154,12 +162,16 @@ class BTModuleTreeItem { BTModuleTreeItem(); /** Creates the tree under this root item (called only from root ctor). */ - void create_tree(QList<BTModuleTreeItem::Filter*>& filters, BTModuleTreeItem::Grouping grouping); + void create_tree(QList<BTModuleTreeItem::Filter*>& filters); /** Sorts recursively the children of of the given item. */ void sort_children(BTModuleTreeItem* parent); /** Helper function for creating a group item while creating the tree. */ BTModuleTreeItem* create_parent_item(BTModuleTreeItem* parent, const QString& text, BTModuleTreeItem::Type type, CSwordModuleInfo::Category category = CSwordModuleInfo::UnknownCategory); + static bool m_map_initialized; + static QMap<CSwordModuleInfo::Category, QString> m_CategoryNamesMap; + + CSwordModuleInfo* m_moduleInfo; QString m_text; BTModuleTreeItem* m_firstChild; @@ -167,6 +179,11 @@ class BTModuleTreeItem { Type m_type; CSwordModuleInfo::Category m_category; QList<CSwordModuleInfo*> m_originalModuleList; + Grouping m_grouping; }; +QDataStream &operator<<(QDataStream &out, const BTModuleTreeItem::Grouping &grouping); +QDataStream &operator>>(QDataStream &in, BTModuleTreeItem::Grouping &grouping); +Q_DECLARE_METATYPE(BTModuleTreeItem::Grouping) + #endif diff --git a/src/backend/config/cbtconfig.cpp b/src/backend/config/cbtconfig.cpp index 883f41f..d82fc7d 100644 --- a/src/backend/config/cbtconfig.cpp +++ b/src/backend/config/cbtconfig.cpp @@ -44,7 +44,6 @@ QString getKey(const strings ID) { case bookshelfCurrentItem: return "bookshelfCurrentItem"; } - Q_ASSERT(false); return QString::null; } @@ -67,7 +66,6 @@ QString getKey(const modules ID) { case standardGreekMorphLexicon: return "standardGreekMorphLexicon"; } - Q_ASSERT(false); return QString::null; } @@ -78,8 +76,8 @@ QString getKey(const bools ID) { case readOldBookmarks: return "readOldBookmarks"; - case toolbar: - return "toolbar"; + case showMainWindowToolbar: + return "showMainWindowToolbar"; case mainIndex: return "mainIndex"; case infoDisplay: @@ -129,9 +127,10 @@ QString getKey(const bools ID) { return "showToolbarsInEachWindow"; case showTipAtStartup: return "showTipAtStartup"; + default: + Q_ASSERT(false); + return QString::null; } - Q_ASSERT(false); - return QString::null; } QString getKey(const ints ID) { @@ -198,9 +197,10 @@ QString getKey(const ints ID) { return "configDialogWidth"; case tipNumber: return "tipNumber"; + default: + Q_ASSERT(false); + return QString::null; } - Q_ASSERT(false); - return QString::null; } QString getKey(const intLists ID) { @@ -214,7 +214,6 @@ QString getKey(const intLists ID) { case searchResultSplitterSizes: return "searchResultSplitterSizes"; } - Q_ASSERT(false); return QString::null; } @@ -230,18 +229,15 @@ QString getKey(const stringLists ID) { return "bookshelfOpenGroups"; case hiddenModules: return "hiddenModules"; + default: + Q_ASSERT(false); + return QString::null; } - Q_ASSERT(false); - return QString::null; } QString getKey(const stringMaps ID) { - switch (ID) { - case searchScopes: - return "SearchScopes"; - }; - Q_ASSERT(false); - return QString::null; + Q_ASSERT(ID == searchScopes); + return "SearchScopes"; } QString getKey(const CLanguageMgr::Language * const language) { @@ -251,19 +247,36 @@ QString getKey(const CLanguageMgr::Language * const language) { } // anonymous namespace -QString IntListToString(const QList<int> intList) { +QString IntListToString(const QList<int> &intList) { QStringList intStrings; - foreach(int i, intList) { + Q_FOREACH (int i, intList) { intStrings << QString::number(i); } return intStrings.join(","); } -QList<int> StringToIntList(const QString &intListString) { +QList<int> StringToIntList(const QString &intListString, + bool *ok, + QString::SplitBehavior splitBehavior) +{ QList<int> intList; - if (!intListString.isEmpty() && intListString.contains(',')) { - foreach(QString intString, intListString.split(',')) { - intList << intString.trimmed().toInt(); + if (ok != 0) { + *ok = true; + + if (!intListString.isEmpty()) { + Q_FOREACH (const QString &intString, intListString.split(',', splitBehavior)) { + int i = intString.trimmed().toInt(ok); + if (!(*ok)) + break; + + intList << i; + } + } + } else { + if (!intListString.isEmpty()) { + Q_FOREACH (const QString &intString, intListString.split(',', splitBehavior)) { + intList << intString.trimmed().toInt(); + } } } return intList; @@ -276,15 +289,14 @@ QString getDefault(const strings ID) { case language: return QLocale::system().name(); case displayStyle: - return CDisplayTemplateMgr::defaultTemplate(); + return CDisplayTemplateMgr::defaultTemplateName(); case bookshelfCurrentItem: + default: return QString::null; } - return QString::null; } QString getDefault(const modules ID) { - // CSwordBackend *b = CSwordBackend::instance()(); switch (ID) { case standardBible: return "KJV"; @@ -303,171 +315,103 @@ QString getDefault(const modules ID) { return "StrongsHebrew"; case standardGreekMorphLexicon: return "StrongsGreek"; + default: + return QString::null; } - - return QString::null; } bool getDefault(const bools ID) { switch (ID) { case firstSearchDialog: - return true; - case readOldBookmarks: - return false; - - case toolbar: - return true; + case showMainWindowToolbar: case mainIndex: - return true; case infoDisplay: - return true; - case autoTileVertical: - return true; - case autoTileHorizontal: - return false; - case autoTile: - return false; - case autoTabbed: - return false; - case autoCascade: - return false; - - case lineBreaks: - return false; case verseNumbers: - return true; - case logo: - return true; case autoDeleteOrphanedIndices: - return true; - case crashedLastTime: - return false; - case crashedTwoTimes: - return false; - case bookshelfShowHidden: - return false; - case allowNetworkConnection: - return false; - case showTextWindowHeaders: - return true; case showTextWindowNavigator: - return true; case showTextWindowModuleSelectorButtons: - return true; case showTextWindowToolButtons: - return true; case showFormatToolbarButtons: - return true; case showToolbarsInEachWindow: - return true; case showTipAtStartup: return true; + case readOldBookmarks: + case autoTileHorizontal: + case autoTile: + case autoTabbed: + case autoCascade: + case lineBreaks: + case crashedLastTime: + case crashedTwoTimes: + case bookshelfShowHidden: + case allowNetworkConnection: + default: + return false; } - return false; } int getDefault(const ints ID) { switch (ID) { + case bookshelfGrouping: + return BTModuleTreeItem::CatLangMod; + case searchType: + return Search::BtSearchOptionsArea::AndType; + case searchDialogHeight: + case magDelay: + return 400; + case searchDialogWidth: + case searchDialogX: + case searchDialogY: + return 200; case footnotes: - return int(true); case strongNumbers: - return int(true); case headings: - return int(true); case morphTags: - return int(true); case lemmas: - return int(true); case hebrewPoints: - return int(true); case hebrewCantillation: - return int(true); case greekAccents: - return int(true); - case textualVariants: - return int(false); case scriptureReferences: - return int(true); case morphSegmentation: - return int(true); - case bookshelfContentsX: - return 0; - case bookshelfContentsY: - return 0; - case magDelay: - return 400; - case bookshelfGrouping: - return BTModuleTreeItem::CatLangMod; - case searchDialogWidth: - return 200; - case searchDialogHeight: - return 400; - case searchDialogX: - return 200; - case searchDialogY: - return 200; - case searchType: - return Search::BtSearchOptionsArea::AndType; - case mainindexActiveTab: - return 0; - case installPathIndex: - return 0; case bookshelfPosX: - return 1; case bookshelfPosY: - return 1; case bookshelfHeight: - return 1; case bookshelfWidth: - return 1; case configDialogPosX: - return 1; case configDialogPosY: - return 1; case configDialogHeight: - return 1; case configDialogWidth: return 1; + case textualVariants: + case bookshelfContentsX: + case bookshelfContentsY: + case mainindexActiveTab: + case installPathIndex: case tipNumber: + default: return 0; } - return 0; } QList<int> getDefault(const intLists /*ID*/) { - QList<int> result; - /*switch ( ID ) { - case leftPaneSplitterSizes: break; - case mainSplitterSizes: break; - case searchMainSplitterSizes: break; - case searchResultSplitterSizes: break;*/ - return result; + return QList<int>(); } QStringList getDefault(const stringLists ID) { - switch (ID) { - case searchTexts: { - QStringList list; - list.append(QString::null); - return list; - } - case searchCompletionTexts: - return QStringList(); - case bookshelfOpenGroups: - return QStringList(); - case hiddenModules: - return QStringList(); - case searchModulesHistory: - return QStringList(); + if (ID == searchTexts) { + QStringList list; + list.append(QString::null); + return list; + } else { + return QStringList(); } - return QStringList(); } StringMap getDefault(const stringMaps ID) { - if (ID != searchScopes) return StringMap(); + Q_ASSERT(ID == searchScopes); StringMap map; map.insert(QObject::tr("Old testament"), QString("Gen - Mal")); @@ -487,7 +431,7 @@ StringMap getDefault(const stringMaps ID) { sword::ListKey list(vk.ParseVerseList(it.value().toLocal8Bit(), "Genesis 1:1", true)); QString data; for (int i(0); i < list.Count(); i++) { - data.append(QString::fromUtf8(list.GetElement(i)->getRangeText())); + data.append(QString::fromUtf8(list.getElement(i)->getRangeText())); data.append("; "); } map[it.key()] = data; @@ -498,186 +442,170 @@ StringMap getDefault(const stringMaps ID) { QFont &getDefault(const CLanguageMgr::Language * const) { // Language specific lookup of the font name - if (m_defaultFont) return *m_defaultFont; + if (m_defaultFont) + return *m_defaultFont; /// \todo make the font name and size a configuration option - // int fontSize = QWebSettings::globalSettings()->fontSize(QWebSettings::DefaultFontSize); - int fontSize(12); - QString fontName(QWebSettings::globalSettings()->fontFamily(QWebSettings::StandardFont)); - m_defaultFont = new QFont(fontName, fontSize); /// \todo there may be a mem leak here! + m_defaultFont = new QFont(); + m_defaultFont->setPointSize(12); return *m_defaultFont; } QString get(const strings ID) { - getConfig()->beginGroup("strings"); - QString result(getConfig()->value(getKey(ID), getDefault(ID)).toString()); - getConfig()->endGroup(); - return result; + QVariant v = getConfig()->value("strings/" + getKey(ID)); + if (v.isValid()) + return v.toString(); + + return getDefault(ID); } CSwordModuleInfo *get(const modules ID) { - getConfig()->beginGroup("modules"); - CSwordModuleInfo *result(CSwordBackend::instance()->findModuleByName( - getConfig()->value(getKey(ID), getDefault(ID)).toString() - )); - getConfig()->endGroup(); - return result; + QVariant v = getConfig()->value("modules/" + getKey(ID)); + CSwordBackend *b = CSwordBackend::instance(); + if (v.isValid()) + return b->findModuleByName(v.toString()); + + return b->findModuleByName(getDefault(ID)); } bool get(const bools ID) { - getConfig()->beginGroup("bools"); - bool result(getConfig()->value(getKey(ID), getDefault(ID)).toBool()); - getConfig()->endGroup(); - return result; + QVariant v = getConfig()->value("bools/" + getKey(ID)); + if (v.isValid()) + return v.toBool(); + + return getDefault(ID); } int get(const ints ID) { - getConfig()->beginGroup("ints"); - int result(getConfig()->value(getKey(ID), getDefault(ID)).toInt()); - getConfig()->endGroup(); - return result; + QVariant v = getConfig()->value("ints/" + getKey(ID)); + if (v.isValid()) + return v.toInt(); + + return getDefault(ID); } QList<int> get(const intLists ID) { - getConfig()->beginGroup("intlists"); - QList<int> result(StringToIntList( - getConfig()->value(getKey(ID), IntListToString(getDefault(ID))) - .toString() - )); - getConfig()->endGroup(); - return result; + QVariant v = getConfig()->value("intlists/" + getKey(ID)); + if (v.isValid()) { + bool ok; + QList<int> r = StringToIntList(v.toString(), &ok); + if (ok) + return r; + } + return getDefault(ID); } QStringList get(const stringLists ID) { - getConfig()->beginGroup("stringlists"); - QStringList result( - getConfig()->value(getKey(ID), getDefault(ID)).toStringList() - ); - getConfig()->endGroup(); - return result; + QVariant v = getConfig()->value("stringlists/" + getKey(ID)); + if (v.isValid()) + return v.toStringList(); + + return getDefault(ID); } StringMap get(const stringMaps ID) { + Q_ASSERT(ID == searchScopes); + + QSettings *s = getConfig(); + s->beginGroup(getKey(ID)); + const QStringList keys = s->childKeys(); + + if (keys.isEmpty()) { + s->endGroup(); + return getDefault(ID); + } + + /** + Make sure we return the scopes in the chosen language. saved + keys are in english. + */ StringMap map; + sword::VerseKey vk; + Q_FOREACH (const QString &key, keys) { + if (key.isEmpty()) + continue; - getConfig()->beginGroup(getKey(ID)); - QStringList keys(getConfig()->childKeys()); - - if (!keys.isEmpty()) { - switch (ID) { - case searchScopes: { - /** - Make sure we return the scopes in the chosen language. saved - keys are in english. - */ - sword::VerseKey vk; - foreach (QString key, keys) { - Q_ASSERT(!key.isEmpty()); - QByteArray b(getConfig()->value(key).toString().toUtf8()); - sword::ListKey list(vk.ParseVerseList(b, "Genesis 1:1", true)); - QString data; - for (int i(0); i < list.Count(); i++) { - data.append(QString::fromUtf8(list.GetElement(i)->getRangeText())); - data.append("; "); - } - map[key] = data; // Set the new data - } - } - default: - break; + QByteArray b = s->value(key).toString().toUtf8(); + sword::ListKey list(vk.ParseVerseList(b, "Genesis 1:1", true)); + QString data; + for (int i = 0; i < list.Count(); i++) { + data.append(QString::fromUtf8(list.getElement(i)->getRangeText())); + data.append("; "); } + map[key] = data; // Set the new data } - else { - map = getDefault(ID); - } - getConfig()->endGroup(); + s->endGroup(); return map; } FontSettingsPair get(const CLanguageMgr::Language * const language) { // Check the cache first: - FontCacheMap::const_iterator it(m_fontCache.find(language)); - if (it != m_fontCache.end()) return *it; - - FontSettingsPair settings; - - getConfig()->beginGroup("font standard settings"); - settings.first = getConfig()->value(getKey(language), false).toBool(); - getConfig()->endGroup(); - - getConfig()->beginGroup("fonts"); - QFont font; - if (settings.first) { - font.fromString(getConfig()->value(getKey(language), getDefault(language)).toString()); - } - else { - font = getDefault(language); + FontCacheMap::const_iterator it = m_fontCache.find(language); + if (it != m_fontCache.end()) + return *it; + + QSettings *s = getConfig(); + FontSettingsPair fontSettings; + fontSettings.first = s->value("font standard settings/" + getKey(language), false).toBool(); + + if (fontSettings.first) { + QVariant v = s->value("fonts/" + getKey(language)); + if (v.isValid()) { + fontSettings.second.fromString(v.toString()); + } else { + fontSettings.second = getDefault(language); + } + } else { + fontSettings.second = getDefault(language); } - settings.second = font; - getConfig()->endGroup(); // Cache the value: - m_fontCache.insert(language, settings); + m_fontCache.insert(language, fontSettings); - return settings; + return fontSettings; } void set(const strings ID, const QString &value) { -// KConfigGroup cg = getConfig()->group("strings"); -// cg.writeEntry(getKey(ID), value); - getConfig()->beginGroup("strings"); - getConfig()->setValue(getKey(ID), value); - getConfig()->endGroup(); + getConfig()->setValue("strings/" + getKey(ID), value); } void set(const modules ID, CSwordModuleInfo * const value) { -// KConfigGroup cg = getConfig()->group("modules"); -// cg.writeEntry(getKey(ID), value ? value->name() : QString::null); - getConfig()->beginGroup("modules"); - getConfig()->setValue(getKey(ID), value ? value->name() : QString::null); - getConfig()->endGroup(); + getConfig()->setValue("modules/" + getKey(ID), value ? value->name() : QString::null); } -void set(const modules ID, const QString& value) { +void set(const modules ID, const QString &value) { CSwordModuleInfo *module(CSwordBackend::instance()->findModuleByName(value)); if (module) { set(ID, module); } } -void set(const bools ID, const bool value) { - getConfig()->beginGroup("bools"); - getConfig()->setValue(getKey(ID), value); - getConfig()->endGroup(); +void set(const bools ID, const bool value) { + getConfig()->setValue("bools/" + getKey(ID), value); } void set(const ints ID, const int value) { - getConfig()->beginGroup("ints"); - getConfig()->setValue(getKey(ID), value); - getConfig()->endGroup(); + getConfig()->setValue("ints/" + getKey(ID), value); } -void set(const intLists ID, const QList<int> value) { - getConfig()->beginGroup("intlists"); - getConfig()->setValue(getKey(ID), IntListToString(value)); - getConfig()->endGroup(); +void set(const intLists ID, const QList<int> &value) { + getConfig()->setValue("intlists/" + getKey(ID), IntListToString(value)); } -void set(const stringLists ID, const QStringList value) { - getConfig()->beginGroup("stringlists"); - getConfig()->setValue(getKey(ID), value); - getConfig()->endGroup(); +void set(const stringLists ID, const QStringList &value) { + getConfig()->setValue("stringlists/" + getKey(ID), value); } -void set(const stringMaps ID, const StringMap value) { +void set(const stringMaps ID, const StringMap &value) { typedef StringMap::ConstIterator SMCI; using namespace sword; - getConfig()->beginGroup(getKey(ID)); + QSettings *s = getConfig(); + s->beginGroup(getKey(ID)); // Clear all entries of this group to make sure old stuff gets removed: - getConfig()->remove(""); + s->remove(""); switch (ID) { case searchScopes: { @@ -690,35 +618,34 @@ void set(const stringMaps ID, const StringMap value) { QString data; ListKey list(vk.ParseVerseList(it.value().toUtf8(), "Genesis 1:1", true)); for (int i(0); i < list.Count(); i++) { - VerseKey *range(dynamic_cast<VerseKey*>(list.GetElement(i))); + VerseKey *range(dynamic_cast<VerseKey*>(list.getElement(i))); if (range) { range->setLocale("en"); data.append(QString::fromUtf8( range->getRangeText() )); data.append(";"); } } - getConfig()->setValue(it.key(), data); + s->setValue(it.key(), data); } break; } default: { for (SMCI it(value.begin()); it != value.end(); it++) { - getConfig()->setValue(it.key(), it.value()); + s->setValue(it.key(), it.value()); } break; } } - getConfig()->endGroup(); + s->endGroup(); } void set(const CLanguageMgr::Language * const language, - const FontSettingsPair& value) { - getConfig()->beginGroup("fonts"); - getConfig()->setValue(getKey(language), value.second.toString()); - getConfig()->endGroup(); - getConfig()->beginGroup("font standard settings"); - getConfig()->setValue(getKey(language), value.first); - getConfig()->endGroup(); + const FontSettingsPair& value) +{ + QSettings *s = getConfig(); + QString lang = getKey(language); + s->setValue("fonts/" + lang, value.second.toString()); + s->setValue("font standard settings/" + lang, value.first); // Remove language from the cache: m_fontCache.remove(language); @@ -751,9 +678,9 @@ FilterOptions getFilterOptionDefaults() { } void setupAccelSettings(const keys type, - BtActionCollection * const actionCollection) { - qDebug() << "CBTConfig::setupAccelSettings begin"; - QString groupName; + BtActionCollection * const actionCollection) +{ + const char *groupName =""; switch (type) { case allWindows: groupName = "Displaywindow shortcuts"; @@ -780,18 +707,15 @@ void setupAccelSettings(const keys type, groupName = "Application shortcuts"; break; } - qDebug() << groupName; - Q_ASSERT(getConfig()); actionCollection->setConfigGroup(groupName); actionCollection->readSettings(); - qDebug() << "CBTConfig::setupAccelSettings end"; } void saveAccelSettings(const keys type, - BtActionCollection * const actionCollection) { - qDebug() << "CBTConfig::saveAccelSettings begin"; - QString groupName; + BtActionCollection * const actionCollection) +{ + const char *groupName =""; switch (type) { case allWindows: groupName = "Displaywindow shortcuts"; @@ -821,22 +745,22 @@ void saveAccelSettings(const keys type, actionCollection->setConfigGroup(groupName); actionCollection->writeSettings(); - qDebug() << "CBTConfig::saveAccelSettings end"; } QString getModuleEncryptionKey(const QString &module) { Q_ASSERT(!module.isEmpty()); - getConfig()->beginGroup("Module keys"); - QString result(getConfig()->value(module, QVariant(QString::null)).toString()); - getConfig()->endGroup(); - return result; + static const QString nullString; + + QVariant v = getConfig()->value("Module keys/" + module); + if (v.isValid()) + return v.toString(); + + return nullString; } void setModuleEncryptionKey(const QString &module, const QString &key) { - getConfig()->beginGroup("Module keys"); - getConfig()->setValue(module, key); - getConfig()->endGroup(); + getConfig()->setValue("Module keys/" + module, key); } QSettings *getConfig() { diff --git a/src/backend/config/cbtconfig.h b/src/backend/config/cbtconfig.h index ef618a2..f3fa042 100644 --- a/src/backend/config/cbtconfig.h +++ b/src/backend/config/cbtconfig.h @@ -49,7 +49,7 @@ enum bools { firstSearchDialog, readOldBookmarks, - toolbar, + showMainWindowToolbar, mainIndex, infoDisplay, @@ -144,8 +144,10 @@ enum stringMaps { searchScopes }; -QString IntListToString(const QList<int> intList); -QList<int> StringToIntList(const QString &intListString); +QString IntListToString(const QList<int> &intList); +QList<int> StringToIntList(const QString &intListString, + bool *ok = 0, + QString::SplitBehavior splitBehavior = QString::KeepEmptyParts); QString getDefault(const strings); QString getDefault(const modules); @@ -167,12 +169,12 @@ FontSettingsPair get(const CLanguageMgr::Language * const); void set(const strings, const QString &value); void set(const modules, CSwordModuleInfo * const module); -void set(const modules, const QString& moduleName); +void set(const modules, const QString &moduleName); void set(const bools, const bool value); void set(const ints, const int value); -void set(const intLists, const QList<int> value); -void set(const stringLists, const QStringList value); -void set(const stringMaps, const StringMap value); +void set(const intLists, const QList<int> &value); +void set(const stringLists, const QStringList &value); +void set(const stringMaps, const StringMap &value); void set(const CLanguageMgr::Language * const language, const FontSettingsPair &fontSettings); diff --git a/src/backend/cswordmodulesearch.h b/src/backend/cswordmodulesearch.h index bc0d37c..aa864b0 100644 --- a/src/backend/cswordmodulesearch.h +++ b/src/backend/cswordmodulesearch.h @@ -66,7 +66,7 @@ class CSwordModuleSearch: public QObject { Resets the search scope. */ inline void resetSearchScope() { - m_searchScope.ClearList(); + m_searchScope.clear(); } /** diff --git a/src/backend/drivers/cswordbiblemoduleinfo.cpp b/src/backend/drivers/cswordbiblemoduleinfo.cpp index a81430f..e87fea2 100644 --- a/src/backend/drivers/cswordbiblemoduleinfo.cpp +++ b/src/backend/drivers/cswordbiblemoduleinfo.cpp @@ -12,7 +12,6 @@ #include <QSharedPointer> #include <QFile> #include "backend/managers/cswordbackend.h" -#include "backend/keys/cswordversekey.h" // Sword includes: #include <versekey.h> @@ -21,53 +20,46 @@ CSwordBibleModuleInfo::CSwordBibleModuleInfo(sword::SWModule *module, CSwordBackend * const usedBackend, ModuleType type) - : CSwordModuleInfo(module, usedBackend, type), - m_lowerBound(0), - m_upperBound(0), - m_bookList(0), - m_cachedLocale("unknown") + : CSwordModuleInfo(module, usedBackend, type) + , m_boundsInitialized(false) + , m_lowerBound(0) + , m_upperBound(0) + , m_bookList(0) { - initBounds(); + // Intentionally empty } -CSwordBibleModuleInfo::CSwordBibleModuleInfo(const CSwordBibleModuleInfo ©) : - CSwordModuleInfo(copy), - m_lowerBound(0), - m_upperBound(0), - m_bookList(0), - m_cachedLocale(copy.m_cachedLocale), - m_hasOT(copy.m_hasOT), - m_hasNT(copy.m_hasNT) -{ - if (copy.m_bookList) { - m_bookList = new QStringList(); - *m_bookList = *copy.m_bookList; - } - initBounds(); -} +void CSwordBibleModuleInfo::initBounds() const { + /// \todo The fields calculated by this method could be cached to disk. -void CSwordBibleModuleInfo::initBounds() { - const bool oldStatus = module()->getSkipConsecutiveLinks(); - module()->setSkipConsecutiveLinks(true); + Q_ASSERT(!m_boundsInitialized); - module()->setPosition(sword::TOP); // position to first entry - sword::VerseKey key(module()->KeyText()); - m_hasOT = (key.Testament() == 1); + sword::SWModule *m = module(); + const bool oldStatus = m->getSkipConsecutiveLinks(); + m->setSkipConsecutiveLinks(true); - module()->setPosition(sword::BOTTOM); - key = module()->KeyText(); - m_hasNT = (key.Testament() == 2); + m->setPosition(sword::TOP); // position to first entry + sword::VerseKey key(module()->getKeyText()); + m_hasOT = (key.getTestament() == 1); - module()->setSkipConsecutiveLinks(oldStatus); + m->setPosition(sword::BOTTOM); + key = module()->getKeyText(); + m_hasNT = (key.getTestament() == 2); + + m->setSkipConsecutiveLinks(oldStatus); m_lowerBound.setKey(m_hasOT ? "Genesis 1:1" : "Matthew 1:1"); m_upperBound.setKey(!m_hasNT ? "Malachi 4:6" : "Revelation of John 22:21"); + + m_boundsInitialized = true; } /** Returns the books available in this module */ QStringList *CSwordBibleModuleInfo::books() const { - if (m_cachedLocale != backend()->booknameLanguage()) { //if the locale has changed + if (m_cachedLocale != backend()->booknameLanguage()) { + // Reset the booklist because the locale has changed + m_cachedLocale = backend()->booknameLanguage(); delete m_bookList; m_bookList = 0; } @@ -75,37 +67,29 @@ QStringList *CSwordBibleModuleInfo::books() const { if (!m_bookList) { m_bookList = new QStringList(); + // Initialize m_hasOT and m_hasNT + if (!m_boundsInitialized) + initBounds(); + int min = 1; // 1 = OT int max = 2; // 2 = NT - //find out if we have ot and nt, only ot or only nt + if (!m_hasOT) + min++; // min == 2 - if (m_hasOT && m_hasNT) { //both - min = 1; - max = 2; - } - else if (m_hasOT && !m_hasNT) { //only OT - min = 1; - max = 1; - } - else if (!m_hasOT && m_hasNT) { //only NT - min = 2; - max = 2; - } - else if (!m_hasOT && !m_hasNT) { //somethings wrong here! - no OT and no NT - qWarning("CSwordBibleModuleInfo (%s) no OT and not NT! Check your config!", module()->Name()); - min = 1; - max = 0; - } + if (!m_hasNT) + max--; // max == 1 - QSharedPointer<sword::VerseKey> key((sword::VerseKey *)module()->CreateKey()); - key->setPosition(sword::TOP); + if (min > max) { + qWarning("CSwordBibleModuleInfo (%s) no OT and not NT! Check your config!", module()->Name()); + } else { + QSharedPointer<sword::VerseKey> key((sword::VerseKey *)module()->CreateKey()); + key->setPosition(sword::TOP); - for (key->setTestament(min); !key->Error() && key->getTestament() <= max; key->Book(key->Book() + 1)) { - m_bookList->append( QString::fromUtf8(key->getBookName()) ); + for (key->setTestament(min); !key->Error() && key->getTestament() <= max; key->setBook(key->getBook() + 1)) { + m_bookList->append( QString::fromUtf8(key->getBookName()) ); + } } - - m_cachedLocale = backend()->booknameLanguage(); } return m_bookList; @@ -118,9 +102,9 @@ unsigned int CSwordBibleModuleInfo::chapterCount(const unsigned int book) const key->setPosition(sword::TOP); // works for old and new versions - key->Book(book); + key->setBook(book); key->setPosition(sword::MAXCHAPTER); - result = key->Chapter(); + result = key->getChapter(); return result; } @@ -140,10 +124,10 @@ unsigned int CSwordBibleModuleInfo::verseCount(const unsigned int book, key->setPosition(sword::TOP); // works for old and new versions - key->Book(book); - key->Chapter(chapter); + key->setBook(book); + key->setChapter(chapter); key->setPosition(sword::MAXVERSE); - result = key->Verse(); + result = key->getVerse(); return result; } @@ -162,7 +146,7 @@ unsigned int CSwordBibleModuleInfo::bookNumber(const QString &book) const { key->setBookName(book.toUtf8().constData()); - bookNumber = ((key->getTestament() > 1) ? key->BMAX[0] : 0) + key->Book(); + bookNumber = ((key->getTestament() > 1) ? key->BMAX[0] : 0) + key->getBook(); return bookNumber; } diff --git a/src/backend/drivers/cswordbiblemoduleinfo.h b/src/backend/drivers/cswordbiblemoduleinfo.h index 40ec8cb..49606e3 100644 --- a/src/backend/drivers/cswordbiblemoduleinfo.h +++ b/src/backend/drivers/cswordbiblemoduleinfo.h @@ -24,21 +24,9 @@ class CSwordBibleModuleInfo: public CSwordModuleInfo { Q_OBJECT - public: /* Types: */ - enum Testament { - OldTestament = 1, - NewTestament = 2 - }; - public: /* Methods: */ CSwordBibleModuleInfo(sword::SWModule *module, CSwordBackend * const, ModuleType type = Bible); - CSwordBibleModuleInfo(const CSwordBibleModuleInfo ©); - - /* Reimplementation of CSwordModuleInfo::clone(). */ - virtual inline CSwordModuleInfo *clone() const { - return new CSwordBibleModuleInfo(*this); - } inline ~CSwordBibleModuleInfo() { delete m_bookList; @@ -82,16 +70,29 @@ class CSwordBibleModuleInfo: public CSwordModuleInfo { unsigned int bookNumber(const QString &book) const; /** - \returns whether this module has the text of desired type of testament + \returns whether this module has the Old Testament texts. */ - bool hasTestament(CSwordBibleModuleInfo::Testament type) const { - return type == OldTestament ? m_hasOT : m_hasNT; + inline bool hasOldTestament() const { + if (!m_boundsInitialized) + initBounds(); + return m_hasOT; + } + + /** + \returns whether this module has the New Testament texts. + */ + inline bool hasNewTestament() const { + if (!m_boundsInitialized) + initBounds(); + return m_hasNT; } /** \returns the key which represents the lower bound of this module. */ inline const CSwordVerseKey &lowerBound() const { + if (!m_boundsInitialized) + initBounds(); return m_lowerBound; } @@ -99,20 +100,25 @@ class CSwordBibleModuleInfo: public CSwordModuleInfo { \returns the key which represents the upper bound of this module. */ inline const CSwordVerseKey &upperBound() const { + if (!m_boundsInitialized) + initBounds(); return m_upperBound; } private: /* Methods: */ - void initBounds(); - private: - CSwordVerseKey m_lowerBound; - CSwordVerseKey m_upperBound; + void initBounds() const; + + private: /* Fields: */ + + mutable bool m_boundsInitialized; + mutable CSwordVerseKey m_lowerBound; + mutable CSwordVerseKey m_upperBound; + mutable bool m_hasOT; + mutable bool m_hasNT; mutable QStringList *m_bookList; //This booklist is cached mutable QString m_cachedLocale; - bool m_hasOT; - bool m_hasNT; }; #endif diff --git a/src/backend/drivers/cswordbookmoduleinfo.h b/src/backend/drivers/cswordbookmoduleinfo.h index 12a3d01..c6b0494 100644 --- a/src/backend/drivers/cswordbookmoduleinfo.h +++ b/src/backend/drivers/cswordbookmoduleinfo.h @@ -33,11 +33,6 @@ class CSwordBookModuleInfo: public CSwordModuleInfo { inline CSwordBookModuleInfo(const CSwordBookModuleInfo ©) : CSwordModuleInfo(copy), m_depth(copy.m_depth) {} - /* Reimplementation of CSwordModuleInfo::clone(). */ - virtual inline CSwordModuleInfo *clone() const { - return new CSwordBookModuleInfo(*this); - } - /** \returns the maximal depth of sections and subsections. */ diff --git a/src/backend/drivers/cswordcommentarymoduleinfo.h b/src/backend/drivers/cswordcommentarymoduleinfo.h index 60640a2..3c42d99 100644 --- a/src/backend/drivers/cswordcommentarymoduleinfo.h +++ b/src/backend/drivers/cswordcommentarymoduleinfo.h @@ -27,11 +27,6 @@ class CSwordCommentaryModuleInfo: public CSwordBibleModuleInfo { : CSwordBibleModuleInfo(module, usedBackend, CSwordModuleInfo::Commentary) {} - /* Reimplementation of CSwordModuleInfo::clone(). */ - virtual inline CSwordModuleInfo* clone() const { - return new CSwordCommentaryModuleInfo(*this); - } - /* Reimplementation of CSwordModuleInfo::isWritable(). */ virtual bool isWritable() const; }; diff --git a/src/backend/drivers/cswordlexiconmoduleinfo.cpp b/src/backend/drivers/cswordlexiconmoduleinfo.cpp index d6515be..4e53361 100644 --- a/src/backend/drivers/cswordlexiconmoduleinfo.cpp +++ b/src/backend/drivers/cswordlexiconmoduleinfo.cpp @@ -86,12 +86,12 @@ const QStringList &CSwordLexiconModuleInfo::entries() const { do { if ( isUnicode() ) { - m_entries.append(QString::fromUtf8(module()->KeyText())); + m_entries.append(QString::fromUtf8(module()->getKeyText())); } else { //for latin1 modules use fromLatin1 because of speed QTextCodec* codec = QTextCodec::codecForName("Windows-1252"); - m_entries.append(codec->toUnicode(module()->KeyText())); + m_entries.append(codec->toUnicode(module()->getKeyText())); } module()->increment(); diff --git a/src/backend/drivers/cswordlexiconmoduleinfo.h b/src/backend/drivers/cswordlexiconmoduleinfo.h index d75e106..1789b9b 100644 --- a/src/backend/drivers/cswordlexiconmoduleinfo.h +++ b/src/backend/drivers/cswordlexiconmoduleinfo.h @@ -29,11 +29,6 @@ class CSwordLexiconModuleInfo: public CSwordModuleInfo { inline CSwordLexiconModuleInfo(const CSwordLexiconModuleInfo ©) : CSwordModuleInfo(copy), m_entries(copy.m_entries) {} - /* Reimplementation of CSwordModuleInfo::clone(). */ - virtual inline CSwordModuleInfo *clone() const { - return new CSwordLexiconModuleInfo(*this); - } - /** This method returns the entries of the modules represented by this object. If this function is called for the first time the list is load diff --git a/src/backend/drivers/cswordmoduleinfo.cpp b/src/backend/drivers/cswordmoduleinfo.cpp index b1e646f..a7ceca9 100644 --- a/src/backend/drivers/cswordmoduleinfo.cpp +++ b/src/backend/drivers/cswordmoduleinfo.cpp @@ -11,8 +11,6 @@ #include <QSharedPointer> #include <CLucene.h> -#include <CLucene/util/Misc.h> -#include <CLucene/util/Reader.h> #include <QByteArray> #include <QCoreApplication> #include <QDebug> @@ -43,7 +41,7 @@ #include <versekey.h> -#ifdef BT_DEBUG +#if 0 namespace { /** HELPER Method to dump all current EntryAttributes of a module. */ @@ -223,7 +221,7 @@ bool CSwordModuleInfo::hasIndex() const { return lucene::index::IndexReader::indexExists(getModuleStandardIndexLocation().toAscii().constData()); } -void CSwordModuleInfo::buildIndex() { +bool CSwordModuleInfo::buildIndex() { m_cancelIndexing = false; @@ -260,7 +258,6 @@ void CSwordModuleInfo::buildIndex() { QSharedPointer<lucene::index::IndexWriter> writer( new lucene::index::IndexWriter(index.toAscii().constData(), &an, true) ); //always create a new index writer->setMaxFieldLength(BT_MAX_LUCENE_FIELD_LENGTH); writer->setUseCompoundFile(true); //merge segments into a single file - writer->setMinMergeDocs(1000); m_module->setPosition(sword::TOP); unsigned long verseLowIndex = m_module->Index(); @@ -406,12 +403,22 @@ void CSwordModuleInfo::buildIndex() { emit hasIndexChanged(true); } } + catch (CLuceneError &e) { + qWarning() << "CLucene exception occurred while indexing:" << e.what(); + util::showWarning(0, QCoreApplication::tr("Indexing aborted"), QCoreApplication::tr("An internal error occurred while building the index: %1").arg(e.what())); + deleteIndex(); + m_cancelIndexing = false; + return false; + } catch (...) { qWarning("CLucene exception occurred while indexing"); util::showWarning(0, QCoreApplication::tr("Indexing aborted"), QCoreApplication::tr("An internal error occurred while building the index.")); deleteIndex(); m_cancelIndexing = false; + return false; } + + return true; } void CSwordModuleInfo::deleteIndex() { @@ -442,10 +449,10 @@ int CSwordModuleInfo::searchIndexed(const QString &searchedText, QList<sword::VerseKey*> list; if (s) { - m_module->SetKey(*s); + m_module->setKey(*s); } - results.ClearList(); + results.clear(); try { // do not use any stop words @@ -455,7 +462,11 @@ int CSwordModuleInfo::searchIndexed(const QString &searchedText, lucene_utf8towcs(wcharBuffer, searchedText.toUtf8().constData(), BT_MAX_LUCENE_FIELD_LENGTH); QSharedPointer<lucene::search::Query> q( lucene::queryParser::QueryParser::parse((const TCHAR*)wcharBuffer, (const TCHAR*)_T("content"), &analyzer) ); +#ifdef CLUCENE2 + QSharedPointer<lucene::search::Hits> h( searcher.search(q.data(), lucene::search::Sort::INDEXORDER()) ); +#else QSharedPointer<lucene::search::Hits> h( searcher.search(q.data(), lucene::search::Sort::INDEXORDER) ); +#endif /// \warning This is a workaround for Sword constness const bool useScope = (const_cast<sword::ListKey&>(scope).Count() > 0); @@ -465,7 +476,11 @@ int CSwordModuleInfo::searchIndexed(const QString &searchedText, QSharedPointer<sword::SWKey> swKey( module()->CreateKey() ); - for (int i = 0; i < h->length(); ++i) { +#ifdef CLUCENE2 + for (unsigned int i = 0; i < h->length(); ++i) { +#else + for (int i = 0; i < h->length(); ++i) { +#endif doc = &h->doc(i); lucene_wcstoutf8(utfBuffer, (const wchar_t*)doc->get((const TCHAR*)_T("key")), BT_MAX_LUCENE_FIELD_LENGTH); @@ -691,14 +706,14 @@ CSwordModuleInfo::TextDirection CSwordModuleInfo::textDirection() const { } void CSwordModuleInfo::write(CSwordKey *key, const QString &newText) { - module()->KeyText(key->key().toUtf8().constData()); + module()->setKey(key->key().toUtf8().constData()); //don't store a pointer to the const char* value somewhere because QCString doesn't keep the value of it module()->setEntry(isUnicode() ? newText.toUtf8().constData() : newText.toLocal8Bit().constData()); } bool CSwordModuleInfo::deleteEntry(CSwordKey * const key) { - module()->KeyText(isUnicode() ? key->key().toUtf8().constData() : key->key().toLocal8Bit().constData()); + module()->setKey(isUnicode() ? key->key().toUtf8().constData() : key->key().toLocal8Bit().constData()); if (module()) { module()->deleteEntry(); @@ -751,7 +766,7 @@ void CSwordModuleInfo::initCachedLanguage() { } Rendering::CEntryDisplay * CSwordModuleInfo::getDisplay() const { - return dynamic_cast < Rendering::CEntryDisplay * >(m_module->Disp()); + return dynamic_cast<Rendering::CEntryDisplay *>(m_module->getDisplay()); } QString CSwordModuleInfo::aboutText() const { diff --git a/src/backend/drivers/cswordmoduleinfo.h b/src/backend/drivers/cswordmoduleinfo.h index d7397de..3c59f9d 100644 --- a/src/backend/drivers/cswordmoduleinfo.h +++ b/src/backend/drivers/cswordmoduleinfo.h @@ -23,6 +23,11 @@ #include <swsearchable.h> #include <swversion.h> +#ifdef CLUCENE2 +// CLucene no longer lists the following functions in its headers +extern size_t lucene_utf8towcs(wchar_t *, const char *, size_t maxslen); +extern size_t lucene_wcstoutf8 (char *, const wchar_t *, size_t maxslen); +#endif class CSwordBackend; class CSwordKey; @@ -138,7 +143,7 @@ class CSwordModuleInfo: public QObject { Cult = 0x80, /**< Cult / sect / questionable module. */ AllCategories = 0xff }; - Q_DECLARE_FLAGS(Categories, Category); + Q_DECLARE_FLAGS(Categories, Category) /** * Returns the base directory for search indices @@ -168,11 +173,6 @@ class CSwordModuleInfo: public QObject { CSwordModuleInfo(const CSwordModuleInfo ©); - virtual CSwordModuleInfo *clone() const = 0; - - virtual inline ~CSwordModuleInfo() {} - - /** * Returns the module object so all objects can access the original Sword module. */ @@ -243,8 +243,9 @@ wrong, or if the config file was write protected return false. /** Builds a search index for this module + \returns Whether indexing this module was successful. */ - void buildIndex(); + bool buildIndex(); /** \returns index size @@ -396,7 +397,6 @@ wrong, or if the config file was write protected return false. } protected: - friend class CSwordBackend; inline CSwordBackend* backend() const { return m_backend; diff --git a/src/backend/filters/osismorphsegmentation.cpp b/src/backend/filters/osismorphsegmentation.cpp index 421b63e..981ce89 100644 --- a/src/backend/filters/osismorphsegmentation.cpp +++ b/src/backend/filters/osismorphsegmentation.cpp @@ -24,8 +24,6 @@ Filters::OSISMorphSegmentation::OSISMorphSegmentation() : sword::SWOptionFilter( setOptionValue("Off"); } -Filters::OSISMorphSegmentation::~OSISMorphSegmentation() {} - char Filters::OSISMorphSegmentation::processText(sword::SWBuf &text, const sword::SWKey * /*key*/, const sword::SWModule * /*module*/) { sword::SWBuf token; bool intoken = false; diff --git a/src/backend/filters/osismorphsegmentation.h b/src/backend/filters/osismorphsegmentation.h index 4843488..8d5a4ab 100644 --- a/src/backend/filters/osismorphsegmentation.h +++ b/src/backend/filters/osismorphsegmentation.h @@ -28,7 +28,6 @@ class OSISMorphSegmentation : public sword::SWOptionFilter { public: OSISMorphSegmentation(); - virtual ~OSISMorphSegmentation(); virtual char processText(sword::SWBuf &text, const sword::SWKey *key = 0, const sword::SWModule *module = 0); }; diff --git a/src/backend/filters/plaintohtml.cpp b/src/backend/filters/plaintohtml.cpp index bc19440..70df723 100644 --- a/src/backend/filters/plaintohtml.cpp +++ b/src/backend/filters/plaintohtml.cpp @@ -9,61 +9,90 @@ #include "backend/filters/plaintohtml.h" +#include <QDebug> -Filters::PlainToHtml::PlainToHtml() : sword::SWFilter() { -} +// Sword includes: +#include <swbuf.h> -/** No descriptions */ -char Filters::PlainToHtml::processText(sword::SWBuf& text, const sword::SWKey* /*key*/, const sword::SWModule* /*module*/) { - int count = 0; +char Filters::PlainToHtml::processText(sword::SWBuf &text, + const sword::SWKey * /*key*/, + const sword::SWModule * /*module*/) +{ sword::SWBuf orig = text; - const char *from = orig.c_str(); - for (text = ""; *from; from++) { - if ((*from == '\n') && (from[1] == '\n')) { // two newlinea are a paragraph - text += "<P>"; - from++; - continue; - } - //This is a special case: Newlines in the plaintext editor are stored as <br />, not as \n - //we need to let them through - else if ((*from == '<') && (from[1] == 'b') && (from[2] == 'r') && (from[3] == ' ') && (from[4] == '/') && (from[5] == '>')) { - text += "<br />"; - from += 5; - continue; - } - else if ((*from == '\n')) { // only one new line - text += "<br/>"; - continue; - } - else if (*from == '<') { - text += "<"; - continue; - } - else if (*from == '>') { + const char * from = orig.c_str(); + bool inFootNote = false; + + for (text = "<p>"; *from; from++) { + switch (*from) { + + case '\n': + if (text.size() > 3) { // ignore leading newlines + if (from[1] == '\n') { // two or more newlines denote a new paragraph + text += "</p><p>"; + do { + from++; + } while (from[1] == '\n'); + } else { // only one new line + text += "<br/>"; + } + } + break; + + case '<': + // This is a special case: Newlines in the plaintext editor are stored as <br />, not as \n + // we need to let them through + /// \todo is this quirk necessary? + if ((from[1] == 'b') + && (from[2] == 'r') + && (from[3] == ' ') + && (from[4] == '/') + && (from[5] == '>')) + { + text += "<br/>"; + from += 5; + } else { + text += "<"; + } + break; + + case '>': text += ">"; - continue; - } - else if (*from == '&') { + break; + + case '&': text += "&"; - continue; - } - else if (*from == '{') { //footnote start - text += "<font color=\"#800000\"><small> ("; /// \bug Possible color conflict - continue; - } - else if (*from == '}') { //footnote end - text += ") </small></font>"; - continue; - } - else if ((*from == ' ') && (count > 5000)) { - text += "<wbr/>"; - count = 0; - continue; + break; + + case '{': // footnote start + if (inFootNote) { + text += *from; + } else { + text += "<span class=\"footnote\">"; + inFootNote = true; + } + break; + + case '}': // footnote end + if (inFootNote) { + text += "</span>"; + inFootNote = false; + } + // fall through: + + default: + text += *from; + break; + } + } - text += *from; - count++; + // Handle missing footnode end: + if (inFootNote) { + qWarning() << "PlainToHtml filter detected missing footnote end."; + text += "</span>"; } + + text += "</p>"; return 0; } diff --git a/src/backend/filters/plaintohtml.h b/src/backend/filters/plaintohtml.h index 1093e2c..b327ecc 100644 --- a/src/backend/filters/plaintohtml.h +++ b/src/backend/filters/plaintohtml.h @@ -11,9 +11,9 @@ #define FILTERS_PLAINTOHTML_H // Sword includes: -#include <swbuf.h> #include <swfilter.h> + namespace sword { class SWKey; class SWModule; @@ -25,14 +25,14 @@ namespace Filters { \brief Plain text to HTML conversion filter. */ class PlainToHtml: public sword::SWFilter { - public: /* Methods: */ - PlainToHtml(); protected: /* Methods: */ + /** Reimplemented from sword::SWFilter. */ virtual char processText(sword::SWBuf &buf, const sword::SWKey *key, const sword::SWModule *module = 0); + }; } // namespace Filters diff --git a/src/backend/filters/thmltohtml.cpp b/src/backend/filters/thmltohtml.cpp index 703b362..12f42bf 100644 --- a/src/backend/filters/thmltohtml.cpp +++ b/src/backend/filters/thmltohtml.cpp @@ -62,7 +62,7 @@ char ThmlToHtml::processText(sword::SWBuf &buf, const sword::SWKey *key, int pos = tag.indexIn(t, 0); if (pos == -1) { //no strong or morph code found in this text - return 1; //WARNING: Return alread here + return 1; //WARNING: Return already here } while (pos != -1) { diff --git a/src/backend/keys/cswordkey.cpp b/src/backend/keys/cswordkey.cpp index 9c5b25b..a685b27 100644 --- a/src/backend/keys/cswordkey.cpp +++ b/src/backend/keys/cswordkey.cpp @@ -153,8 +153,15 @@ QString CSwordKey::strippedText() { return QString::fromUtf8( m_module->module()->StripText() ); } +void CSwordKey::emitBeforeChanged() { + if (m_signal.isNull()) + return; + m_signal->emitBeforeChanged(); +} + void CSwordKey::emitChanged() { - if (m_signal.isNull()) return; + if (m_signal.isNull()) + return; m_signal->emitChanged(); } diff --git a/src/backend/keys/cswordkey.h b/src/backend/keys/cswordkey.h index 48e511c..9b043b7 100644 --- a/src/backend/keys/cswordkey.h +++ b/src/backend/keys/cswordkey.h @@ -81,14 +81,14 @@ class CSwordKey { /** Returns the raw, unchanged text. Returns the text without any filter modifications, * just in the way it comes out of the module. */ - virtual QString rawText(); + QString rawText(); /** Returns the rendered text. Returns the text of the current key after passing it through the * modules filters. */ - virtual QString renderedText( const CSwordKey::TextRenderType mode = CSwordKey::Normal ); + QString renderedText( const CSwordKey::TextRenderType mode = CSwordKey::Normal ); /** Stripped down text. Returns the text after removing all markup tags from it. */ - virtual QString strippedText(); + QString strippedText(); const BtSignal *signaler(); @@ -100,13 +100,21 @@ class CSwordKey { */ static CSwordKey* createInstance(const CSwordModuleInfo *module); + /** + * This is called before a key change to emit a signal + * */ + void emitBeforeChanged(); + /** + * This is called after a key change to emit a signal + * */ + void emitChanged(); + protected: /** * Returns the encoded key appropriate for use directly with Sword. */ virtual const char * rawKey() const = 0; static inline const QTextCodec *cp1252Codec() { return m_cp1252Codec; }; - void emitChanged(); private: /** diff --git a/src/backend/keys/cswordldkey.cpp b/src/backend/keys/cswordldkey.cpp index ecde8b7..822da8c 100644 --- a/src/backend/keys/cswordldkey.cpp +++ b/src/backend/keys/cswordldkey.cpp @@ -86,7 +86,7 @@ bool CSwordLDKey::setKey(const char *newKey) { if (newKey) { SWKey::operator = (newKey); //set the key - m_module->module()->SetKey(this); + m_module->module()->setKey(this); m_module->snap(); } @@ -95,29 +95,29 @@ bool CSwordLDKey::setKey(const char *newKey) { /** Uses the parameter to returns the next entry afer this key. */ CSwordLDKey* CSwordLDKey::NextEntry() { - m_module->module()->SetKey(this); //use this key as base for the next one! + m_module->module()->setKey(this); // use this key as base for the next one! // m_module->module()->getKey()->setText( (const char*)key().utf8() ); m_module->module()->setSkipConsecutiveLinks(true); ( *( m_module->module() ) )++; m_module->module()->setSkipConsecutiveLinks(false); - setKey(m_module->module()->KeyText()); - SWKey::operator = (m_module->module()->KeyText()); + setKey(m_module->module()->getKeyText()); + setText(m_module->module()->getKeyText()); return this; } /** Uses the parameter to returns the next entry afer this key. */ CSwordLDKey* CSwordLDKey::PreviousEntry() { - m_module->module()->SetKey(this); //use this key as base for the next one! + m_module->module()->setKey(this); // use this key as base for the next one! // m_module->module()->getKey()->setText( (const char*)key().utf8() ); m_module->module()->setSkipConsecutiveLinks(true); ( *( m_module->module() ) )--; m_module->module()->setSkipConsecutiveLinks(false); - SWKey::operator = (m_module->module()->KeyText()); + setText(m_module->module()->getKeyText()); return this; } diff --git a/src/backend/keys/cswordversekey.cpp b/src/backend/keys/cswordversekey.cpp index 5ea1455..de4fd0e 100644 --- a/src/backend/keys/cswordversekey.cpp +++ b/src/backend/keys/cswordversekey.cpp @@ -81,8 +81,8 @@ QString CSwordVerseKey::book( const QString& newBook ) { const CSBMI *bible = dynamic_cast<const CSBMI*>(module()); if (bible != 0) { - const bool hasOT = bible->hasTestament(CSBMI::OldTestament); - const bool hasNT = bible->hasTestament(CSBMI::NewTestament); + const bool hasOT = bible->hasOldTestament(); + const bool hasNT = bible->hasNewTestament(); if (hasOT && hasNT) { min = 0; @@ -106,7 +106,7 @@ QString CSwordVerseKey::book( const QString& newBook ) { setBookName(newBook.toUtf8().constData()); } - if ( (Testament() >= min + 1) && (Testament() <= max + 1) && (Book() <= BMAX[min]) ) { + if ((getTestament() >= min + 1) && (getTestament() <= max + 1) && (getBook() <= BMAX[min])) { return QString::fromUtf8( getBookName() ); } @@ -135,12 +135,15 @@ bool CSwordVerseKey::setKey(const char *newKey) { /// \todo Is this check necessary? // Check if empty string: if (*newKey != '\0') { + QString newKeyStr = newKey; + emitBeforeChanged(); positionFrom(newKey); } else { const CSwordModuleInfo *m = module(); if (m->type() == CSwordModuleInfo::Bible) { Q_ASSERT(dynamic_cast<const CSBMI*>(m) != 0); const CSBMI *bible = static_cast<const CSBMI*>(m); + emitBeforeChanged(); positionFrom(bible->lowerBound().key().toUtf8().constData()); } } @@ -160,24 +163,24 @@ bool CSwordVerseKey::next( const JumpType type ) { switch (type) { case UseBook: { - const int currentTestament = Testament(); - const int currentBook = Book(); + const int currentTestament = getTestament(); + const int currentBook = getBook(); if ((currentTestament == 2) && (currentBook >= BMAX[currentTestament-1])) { //Revelation, i.e. end of navigation return false; } else if ((currentTestament == 1) && (currentBook >= BMAX[currentTestament-1])) { //Malachi, switch to the NT - Testament(currentTestament + 1); - Book(1); + setTestament(currentTestament + 1); + setBook(1); } else { - Book(Book() + 1); + setBook(getBook() + 1); } break; } case UseChapter: { - Chapter(Chapter() + 1); + setChapter(getChapter() + 1); break; } @@ -198,7 +201,7 @@ bool CSwordVerseKey::next( const JumpType type ) { m_module->module()->setSkipConsecutiveLinks(oldStatus); if (!m_module->module()->Error()) { - setKey(QString::fromUtf8(m_module->module()->KeyText())); + setKey(QString::fromUtf8(m_module->module()->getKeyText())); } else { // Verse(Verse()+1); @@ -210,7 +213,7 @@ bool CSwordVerseKey::next( const JumpType type ) { } else { - Verse(Verse() + 1); + setVerse(getVerse() + 1); } break; @@ -223,11 +226,13 @@ bool CSwordVerseKey::next( const JumpType type ) { const CSBMI *bible = dynamic_cast<const CSBMI*>(module()); if (bible != 0) { if (_compare(bible->lowerBound()) < 0 ) { + emitBeforeChanged(); setKey(bible->lowerBound()); ret = false; } if (_compare(bible->upperBound()) > 0 ) { + emitBeforeChanged(); setKey(bible->upperBound()); ret = false; } @@ -251,22 +256,22 @@ bool CSwordVerseKey::previous( const JumpType type ) { switch (type) { case UseBook: { - if ( (Book() == 1) && (Testament() == 1) ) { //Genesis + if ((getBook() == 1) && (getTestament() == 1)) { //Genesis return false; } - else if ( (Book() == 1) && (Testament() == 2) ) { //Matthew - Testament(1); - Book(BMAX[0]); + else if ((getBook() == 1) && (getTestament() == 2)) { //Matthew + setTestament(1); + setBook(BMAX[0]); } else { - Book( Book() - 1 ); + setBook(getBook() - 1); } break; } case UseChapter: { - Chapter(Chapter() - 1); + setChapter(getChapter() - 1); break; } @@ -285,7 +290,7 @@ bool CSwordVerseKey::previous( const JumpType type ) { m_module->module()->setSkipConsecutiveLinks(oldStatus); if (!m_module->module()->Error()) { - setKey(QString::fromUtf8(m_module->module()->KeyText()));//don't use fromUtf8 + setKey(QString::fromUtf8(m_module->module()->getKeyText())); // don't use fromUtf8 } else { ret = false; @@ -294,7 +299,7 @@ bool CSwordVerseKey::previous( const JumpType type ) { } } else { - Verse(Verse() - 1); + setVerse(getVerse() - 1); } break; @@ -307,11 +312,13 @@ bool CSwordVerseKey::previous( const JumpType type ) { const CSBMI *bible = dynamic_cast<const CSBMI*>(module()); if (bible != 0) { if (_compare(bible->lowerBound()) < 0 ) { + emitBeforeChanged(); setKey(bible->lowerBound()); ret = false; } if (_compare(bible->upperBound()) > 0 ) { + emitBeforeChanged(); setKey(bible->upperBound()); ret = false; } diff --git a/src/backend/managers/cdisplaytemplatemgr.cpp b/src/backend/managers/cdisplaytemplatemgr.cpp index b3def8c..b433dd7 100644 --- a/src/backend/managers/cdisplaytemplatemgr.cpp +++ b/src/backend/managers/cdisplaytemplatemgr.cpp @@ -29,37 +29,45 @@ CDisplayTemplateMgr::CDisplayTemplateMgr(QString &errorMessage) { namespace DU = util::directory; QStringList filter("*.tmpl"); + QStringList cssfilter("*.css"); // Preload global display templates from disk: QDir td = DU::getDisplayTemplatesDir(); - Q_FOREACH(QString file, td.entryList(filter, QDir::Files | QDir::Readable)) + Q_FOREACH(const QString &file, td.entryList(filter, QDir::Files | QDir::Readable)) loadTemplate(td.canonicalPath() + "/" + file); + + // Load app stylesheets + Q_FOREACH(const QString &file, td.entryList(cssfilter, QDir::Files | QDir::Readable)) + loadCSSTemplate(td.canonicalPath() + "/" + file); /* Preload user display templates from disk, overriding any global templates with the same file name: */ QDir utd = DU::getUserDisplayTemplatesDir(); - Q_FOREACH(QString file, utd.entryList(filter, QDir::Files | QDir::Readable)) + Q_FOREACH(const QString &file, utd.entryList(filter, QDir::Files | QDir::Readable)) loadTemplate(utd.canonicalPath() + "/" + file); - if (m_templateMap.contains(defaultTemplate())) { + if (m_cssMap.contains(defaultTemplateName())) { errorMessage = QString::null; } else { errorMessage = QObject::tr("Default template \"%1\" not found!") - .arg(defaultTemplate()); + .arg(defaultTemplateName()); } } -const QString CDisplayTemplateMgr::fillTemplate( const QString& name, const QString& content, Settings& settings ) { - qDebug() << "CDisplayTemplateMgr::fillTemplate"; - - const QString templateName = m_templateMap.contains(name) ? name : defaultTemplate(); +QString CDisplayTemplateMgr::fillTemplate(const QString &name, + const QString &content, + const Settings &settings) +{ + const QString templateName = m_cssMap.contains(name) ? name : defaultTemplateName(); QString displayTypeString; + QString moduleName; if (!settings.pageCSS_ID.isEmpty()) { displayTypeString = settings.pageCSS_ID; + moduleName = ""; } else { if (settings.modules.count()) { @@ -79,9 +87,11 @@ const QString CDisplayTemplateMgr::fillTemplate( const QString& name, const QStr displayTypeString = "singleentry"; break; }; + moduleName = settings.modules.first()->name(); } else { //use bible as default type if no modules are set displayTypeString = "bible"; + moduleName = ""; }; } @@ -93,13 +103,11 @@ const QString CDisplayTemplateMgr::fillTemplate( const QString& name, const QStr qDebug() << "There were more than 1 module, create headers"; QString header; - QList<const CSwordModuleInfo*>::iterator end_it = settings.modules.end(); - - for (QList<const CSwordModuleInfo*>::iterator it(settings.modules.begin()); it != end_it; ++it) { + Q_FOREACH(const CSwordModuleInfo *mi, settings.modules) { header.append("<th style=\"width:") .append(QString::number(int( 100.0 / (float)moduleCount ))) .append("%;\">") - .append((*it)->name()) + .append(mi->name()) .append("</th>"); } @@ -113,12 +121,8 @@ const QString CDisplayTemplateMgr::fillTemplate( const QString& name, const QStr QString langCSS; CLanguageMgr::LangMap langMap = CLanguageMgr::instance()->availableLanguages(); - qDebug() << "langMap length:" << langMap.count(); - qDebug() << "loop through langMap"; foreach(const CLanguageMgr::Language* lang, langMap) { //const CLanguageMgr::Language* lang = *it; - //qDebug() << "foreach, lang: "; - //qDebug() << lang; //if (lang->isValid() && CBTConfig::get(lang).first) { if (!lang->abbrev().isEmpty() && CBTConfig::get(lang).first) { @@ -154,19 +158,34 @@ const QString CDisplayTemplateMgr::fillTemplate( const QString& name, const QStr .arg(standardFont.italic() ? "italic" : "normal") ); } + + // Template stylesheet + // qWarning("Outputing unformated text"); - const QString t = QString(m_templateMap[ templateName ]) //don't change the map's content directly, use a copy + const QString t = QString(m_templateMap[ "Basic.tmpl" ]) //don't change the map's content directly, use a copy .replace("#TITLE#", settings.title) .replace("#LANG_ABBREV#", settings.langAbbrev.isEmpty() ? QString("en") : settings.langAbbrev) .replace("#DISPLAYTYPE#", displayTypeString) .replace("#LANG_CSS#", langCSS) .replace("#PAGE_DIRECTION#", settings.pageDirection) - .replace("#CONTENT#", newContent); + .replace("#CONTENT#", newContent) + .replace("#THEME_STYLE#", m_cssMap[ templateName ]) + .replace("#MODTYPE#", displayTypeString) + .replace("#MODNAME#", moduleName) + .replace("#MODULE_STYLESHEET#", QString("")); // Let's fix this! return t; } +QString CDisplayTemplateMgr::activeTemplateName() { + const QString tn = CBTConfig::get(CBTConfig::displayStyle); + if (tn.isEmpty()) + return defaultTemplateName(); + + return tn; +} + void CDisplayTemplateMgr::loadTemplate(const QString &filename) { QFile f(filename); if (f.open(QIODevice::ReadOnly)) { @@ -177,3 +196,8 @@ void CDisplayTemplateMgr::loadTemplate(const QString &filename) { } } } + +void CDisplayTemplateMgr::loadCSSTemplate(const QString &filename) { + QFile f(filename); + m_cssMap[QFileInfo(f).fileName()] = QString("file://") + filename; +} diff --git a/src/backend/managers/cdisplaytemplatemgr.h b/src/backend/managers/cdisplaytemplatemgr.h index 9b96e8b..a7b49e5 100644 --- a/src/backend/managers/cdisplaytemplatemgr.h +++ b/src/backend/managers/cdisplaytemplatemgr.h @@ -22,12 +22,15 @@ class CSwordModuleInfo; \note This is a singleton. */ class CDisplayTemplateMgr { + public: /* Types: */ + /** Settings which are used to fill the content into the template. */ struct Settings { - Settings() : pageDirection("ltr") {} + + inline Settings() : pageDirection("ltr") {} /** The list of modules */ QList<const CSwordModuleInfo*> modules; @@ -43,6 +46,7 @@ class CDisplayTemplateMgr { /** The CSS ID which is used in the content part of the page */ QString pageCSS_ID; + }; public: /* Methods: */ @@ -57,7 +61,7 @@ class CDisplayTemplateMgr { \returns the list of available templates. */ inline const QStringList availableTemplates() const { - return m_templateMap.keys(); + return m_cssMap.keys(); } /** @@ -72,12 +76,18 @@ class CDisplayTemplateMgr { \returns The full HTML template HTML code including the CSS data. */ - const QString fillTemplate( const QString& name, const QString& content, Settings& settings); + QString fillTemplate(const QString &name, const QString &content, + const Settings &settings); /** \returns the name of the default template. */ - inline static const char *defaultTemplate() { return "Blue.tmpl"; } + static inline const char * defaultTemplateName() { return "Blue.css"; } + + /** + \returns the name of the active template. + */ + static QString activeTemplateName(); /** \returns The singleton instance of the instance of this class. @@ -85,15 +95,20 @@ class CDisplayTemplateMgr { static inline CDisplayTemplateMgr *instance() { Q_ASSERT(m_instance != 0); return m_instance; - }; + } private: /* Methods: */ + /** Preloads a single template from disk: */ void loadTemplate(const QString &filename); + void loadCSSTemplate(const QString &filename); private: /* Fields: */ + QMap<QString, QString> m_templateMap; + QMap<QString, QString> m_cssMap; static CDisplayTemplateMgr *m_instance; + }; #endif diff --git a/src/backend/managers/cswordbackend.cpp b/src/backend/managers/cswordbackend.cpp index b5c109f..b5f4bff 100644 --- a/src/backend/managers/cswordbackend.cpp +++ b/src/backend/managers/cswordbackend.cpp @@ -75,23 +75,21 @@ void CSwordBackend::filterInit() { cleanupFilters.push_back(thmlplain); } -QList<CSwordModuleInfo*> CSwordBackend::takeModulesFromList(QStringList names) { - int numberOfRemoved = 0; +QList<CSwordModuleInfo*> CSwordBackend::takeModulesFromList(const QStringList &names) { QList<CSwordModuleInfo*> list; - foreach(QString name, names) { + Q_FOREACH (const QString &name, names) { CSwordModuleInfo* mInfo = findModuleByName(name); if (mInfo) { m_dataModel.removeModule(mInfo); - ++numberOfRemoved; list.append(mInfo); } } - if (numberOfRemoved > 0) + if (!list.isEmpty()) emit sigSwordSetupChanged(RemovedModules); return list; } -QList<CSwordModuleInfo*> CSwordBackend::getPointerList(const QStringList &names) { +QList<CSwordModuleInfo*> CSwordBackend::getPointerList(const QStringList &names) const { QList<CSwordModuleInfo*> list; Q_FOREACH (const QString &name, names) { CSwordModuleInfo *mInfo = findModuleByName(name); @@ -103,7 +101,7 @@ QList<CSwordModuleInfo*> CSwordBackend::getPointerList(const QStringList &names) } QList<const CSwordModuleInfo*> CSwordBackend::getConstPointerList( - const QStringList &names) + const QStringList &names) const { QList<const CSwordModuleInfo*> list; Q_FOREACH (const QString &name, names) { @@ -133,19 +131,19 @@ CSwordBackend::LoadError CSwordBackend::initModules(SetupChangedReason reason) { if (!strcmp(curMod->Type(), "Biblical Texts")) { newModule = new CSwordBibleModuleInfo(curMod, this); - newModule->module()->Disp(&m_chapterDisplay); + newModule->module()->setDisplay(&m_chapterDisplay); } else if (!strcmp(curMod->Type(), "Commentaries")) { newModule = new CSwordCommentaryModuleInfo(curMod, this); - newModule->module()->Disp(&m_entryDisplay); + newModule->module()->setDisplay(&m_entryDisplay); } else if (!strcmp(curMod->Type(), "Lexicons / Dictionaries")) { newModule = new CSwordLexiconModuleInfo(curMod, this); - newModule->module()->Disp(&m_entryDisplay); + newModule->module()->setDisplay(&m_entryDisplay); } else if (!strcmp(curMod->Type(), "Generic Books")) { newModule = new CSwordBookModuleInfo(curMod, this); - newModule->module()->Disp(&m_bookDisplay); + newModule->module()->setDisplay(&m_bookDisplay); } if (newModule) { @@ -279,7 +277,7 @@ void CSwordBackend::setFilterOptions(const FilterOptions &options) { } /** This function searches for a module with the specified description */ -CSwordModuleInfo* CSwordBackend::findModuleByDescription(const QString& description) { +CSwordModuleInfo* CSwordBackend::findModuleByDescription(const QString &description) const { Q_FOREACH (CSwordModuleInfo *mod, m_dataModel.moduleList()) { if (mod->config(CSwordModuleInfo::Description) == description) return mod; } @@ -287,16 +285,16 @@ CSwordModuleInfo* CSwordBackend::findModuleByDescription(const QString& descript } /** This function searches for a module with the specified name */ -CSwordModuleInfo* CSwordBackend::findModuleByName(const QString& name) { +CSwordModuleInfo* CSwordBackend::findModuleByName(const QString &name) const { Q_FOREACH (CSwordModuleInfo *mod, m_dataModel.moduleList()) { if (mod->name() == name) return mod; } return 0; } -CSwordModuleInfo* CSwordBackend::findSwordModuleByPointer(const sword::SWModule* const swmodule) { +CSwordModuleInfo* CSwordBackend::findSwordModuleByPointer(const sword::SWModule * const swmodule) const { Q_FOREACH (CSwordModuleInfo *mod, m_dataModel.moduleList()) { - if (mod->module() == swmodule ) return mod; + if (mod->module() == swmodule) return mod; } return 0; } diff --git a/src/backend/managers/cswordbackend.h b/src/backend/managers/cswordbackend.h index 68be102..764d6d5 100644 --- a/src/backend/managers/cswordbackend.h +++ b/src/backend/managers/cswordbackend.h @@ -65,7 +65,7 @@ class CSwordBackend : public QObject, public sword::SWMgr { NoModules = 1 }; /** - * The constructor of the Sword backend. This is actually used nowhere. + * The constructor of the Sword backend. Used by BtInstallBackend only. * Notice that using augmentHome=false can mess up the system because it is true elsewhere. * @param path The path which is used to load modules * @param augmentHome True if the $HOME/.sword/ modules should be augmented with the other modules @@ -132,20 +132,20 @@ class CSwordBackend : public QObject, public sword::SWMgr { * @param description The description of the desired module * @return pointer to the desired module; null if no module has the specified description */ - CSwordModuleInfo* findModuleByDescription(const QString& description); + CSwordModuleInfo* findModuleByDescription(const QString &description) const; /** * This function searches for a module with the specified name * @param name The name of the desired module * @return Pointer to the desired module; null if no module has the specified name */ - CSwordModuleInfo* findModuleByName(const QString& name); + CSwordModuleInfo* findModuleByName(const QString &name) const; /** * This function searches for a module with the specified sword module as module() object! * @param swmodule to a Sword module * @return pointer to the desired module; null if no module has the specified name */ - CSwordModuleInfo* findSwordModuleByPointer(const sword::SWModule* const swmodule); + CSwordModuleInfo* findSwordModuleByPointer(const sword::SWModule * const swmodule) const; /** * @return Our global config object which contains the configs of all modules merged together. @@ -177,19 +177,19 @@ class CSwordBackend : public QObject, public sword::SWMgr { * Takes off the given modules from the list and returns them. * User must take care of the deletion of the returned CSwordModuleInfo pointers. */ - QList<CSwordModuleInfo*> takeModulesFromList(QStringList names); + QList<CSwordModuleInfo*> takeModulesFromList(const QStringList &names); /** \returns a list of pointers to modules, created from a list of module names. */ - QList<CSwordModuleInfo*> getPointerList(const QStringList &names); + QList<CSwordModuleInfo*> getPointerList(const QStringList &names) const; /** \returns a list of pointers to const modules, created from a list of module names. */ - QList<const CSwordModuleInfo*> getConstPointerList(const QStringList &names); + QList<const CSwordModuleInfo*> getConstPointerList(const QStringList &names) const; /** Sword prefix list. * @return A list of all known Sword prefix dirs diff --git a/src/backend/managers/referencemanager.cpp b/src/backend/managers/referencemanager.cpp index de41af2..0a17645 100644 --- a/src/backend/managers/referencemanager.cpp +++ b/src/backend/managers/referencemanager.cpp @@ -250,51 +250,35 @@ const QString ReferenceManager::preferredModule( const ReferenceManager::Type ty switch (type) { case ReferenceManager::Bible: - - module = CBTConfig::get - ( CBTConfig::standardBible ); - + module = CBTConfig::get(CBTConfig::standardBible); break; case ReferenceManager::Commentary: - module = CBTConfig::get - ( CBTConfig::standardCommentary ); - + module = CBTConfig::get(CBTConfig::standardCommentary); break; case ReferenceManager::Lexicon: - module = CBTConfig::get - ( CBTConfig::standardLexicon ); - + module = CBTConfig::get(CBTConfig::standardLexicon); break; case ReferenceManager::StrongsHebrew: - module = CBTConfig::get - ( CBTConfig::standardHebrewStrongsLexicon ); - + module = CBTConfig::get(CBTConfig::standardHebrewStrongsLexicon); break; case ReferenceManager::StrongsGreek: - module = CBTConfig::get - ( CBTConfig::standardGreekStrongsLexicon ); - + module = CBTConfig::get(CBTConfig::standardGreekStrongsLexicon); break; case ReferenceManager::MorphHebrew: - module = CBTConfig::get - ( CBTConfig::standardHebrewMorphLexicon ); - + module = CBTConfig::get(CBTConfig::standardHebrewMorphLexicon); break; case ReferenceManager::MorphGreek: - module = CBTConfig::get - ( CBTConfig::standardGreekMorphLexicon ); - + module = CBTConfig::get(CBTConfig::standardGreekMorphLexicon); break; default: module = 0; - break; } diff --git a/src/backend/rendering/cbookdisplay.cpp b/src/backend/rendering/cbookdisplay.cpp index 259e904..6589e99 100644 --- a/src/backend/rendering/cbookdisplay.cpp +++ b/src/backend/rendering/cbookdisplay.cpp @@ -53,8 +53,6 @@ const QString Rendering::CBookDisplay::text( const QString renderedText = render.renderKeyTree(tree); key->setOffset( offset ); - - qDeleteAll(tree); // Dispose of the heap allocated objects pointed to in tree. return renderedText; }; @@ -84,7 +82,6 @@ const QString Rendering::CBookDisplay::text( const QString renderedText = render.renderKeyTree(tree); key->setOffset( offset ); - qDeleteAll(tree); // Dispose of the heap allocated objects pointed to in tree. return renderedText; }; @@ -101,7 +98,6 @@ const QString Rendering::CBookDisplay::text( const QString renderedText = render.renderKeyTree(tree); key->setOffset( offset ); - qDeleteAll(tree); // Dispose of the heap allocated objects pointed to in tree. return renderedText; }; }; @@ -119,8 +115,6 @@ const QString Rendering::CBookDisplay::text( const QString renderedText = render.renderKeyTree(tree); key->setOffset( offset ); //restore key - - qDeleteAll(tree); // Dispose of the heap allocated objects pointed to in tree. return renderedText; } diff --git a/src/backend/rendering/cbookdisplay.h b/src/backend/rendering/cbookdisplay.h index be5ec9b..4bd5c22 100644 --- a/src/backend/rendering/cbookdisplay.h +++ b/src/backend/rendering/cbookdisplay.h @@ -26,21 +26,22 @@ namespace Rendering { Sword. */ class CBookDisplay: public CEntryDisplay { + public: /* Methods: */ - virtual inline ~CBookDisplay() {} - /** Reimplemented from CEntryDisplay. */ virtual const QString text(const QList<const CSwordModuleInfo*> &modules, const QString &key, const DisplayOptions &displayOptions, const FilterOptions &filterOptions); protected: /* Methods: */ + void setupRenderTree(CSwordTreeKey *swordTree, CTextRendering::KeyTree *renderTree, const QString &highlightKey); -}; -} // namespace Rendering +}; /* class CBookDisplay */ + +} /* namespace Rendering */ #endif diff --git a/src/backend/rendering/cchapterdisplay.cpp b/src/backend/rendering/cchapterdisplay.cpp index 31b56b8..eea2a72 100644 --- a/src/backend/rendering/cchapterdisplay.cpp +++ b/src/backend/rendering/cchapterdisplay.cpp @@ -51,14 +51,17 @@ const QString Rendering::CChapterDisplay::text( k1.Headings(1); k1.setKey(keyName); - if (k1.Chapter() == 1) k1.Chapter(0); //Chapter 1, start with 0:0, otherwise X:0 + if (k1.getChapter() == 1) + k1.setChapter(0); // Chapter 1, start with 0:0, otherwise X:0 - k1.Verse(0); + k1.setVerse(0); startKey = k1.key(); - if (k1.Chapter() == 0) k1.Chapter(1); - k1.Verse(bible->verseCount(k1.book(), k1.Chapter())); + if (k1.getChapter() == 0) + k1.setChapter(1); + + k1.setVerse(bible->verseCount(k1.book(), k1.getChapter())); endKey = k1.key(); } diff --git a/src/backend/rendering/cchapterdisplay.h b/src/backend/rendering/cchapterdisplay.h index a13ebc3..c245c57 100644 --- a/src/backend/rendering/cchapterdisplay.h +++ b/src/backend/rendering/cchapterdisplay.h @@ -22,18 +22,16 @@ namespace Rendering { once. */ class CChapterDisplay: public CEntryDisplay { + public: /* Methods: */ - virtual inline ~CChapterDisplay() {} - /** - Reimplemented from CEntryDisplay. - */ virtual const QString text(const QList<const CSwordModuleInfo*> &modules, const QString &key, const DisplayOptions &displayOptions, const FilterOptions &filterOptions); -}; -} // namespace Rendering +}; /* class CChapterDisplay */ + +} /* namespace Rendering */ #endif diff --git a/src/backend/rendering/cdisplayrendering.cpp b/src/backend/rendering/cdisplayrendering.cpp index c79cfdf..175cf4e 100644 --- a/src/backend/rendering/cdisplayrendering.cpp +++ b/src/backend/rendering/cdisplayrendering.cpp @@ -11,7 +11,6 @@ #include <QString> #include <QRegExp> -#include <QDebug> #include "backend/keys/cswordkey.h" #include "backend/keys/cswordversekey.h" #include "backend/managers/cdisplaytemplatemgr.h" @@ -22,14 +21,13 @@ namespace Rendering { CDisplayRendering::CDisplayRendering(const DisplayOptions &displayOptions, const FilterOptions &filterOptions) - : CHTMLExportRendering(CHTMLExportRendering::Settings(true), - displayOptions, filterOptions) + : CHTMLExportRendering(true, displayOptions, filterOptions) { // Intentionally empty } -const QString CDisplayRendering::entryLink(const KeyTreeItem &item, - const CSwordModuleInfo *module) +QString CDisplayRendering::entryLink(const KeyTreeItem &item, + const CSwordModuleInfo * module) { QString linkText; @@ -41,7 +39,7 @@ const QString CDisplayRendering::entryLink(const KeyTreeItem &item, vk.setKey(item.key()); } - if (isBible && (vk.Verse() == 0)) { + if (isBible && (vk.getVerse() == 0)) { return QString::null; //Warning: return already here } @@ -72,7 +70,7 @@ const QString CDisplayRendering::entryLink(const KeyTreeItem &item, case KeyTreeItem::Settings::SimpleKey: { if (isBible) { - linkText = QString::number(vk.Verse()); + linkText = QString::number(vk.getVerse()); break; } @@ -101,18 +99,14 @@ const QString CDisplayRendering::entryLink(const KeyTreeItem &item, return QString::null; } -const QString CDisplayRendering::keyToHTMLAnchor(const QString& key) { - QString ret = key; +QString CDisplayRendering::keyToHTMLAnchor(const QString& key) { // Be careful not to remove non-ASCII characters, this causes problems // with many languages. - ret = ret.trimmed().remove(QRegExp("\\s")).replace(QString(":"), QString("_")); - - return ret; + return key.trimmed().remove(QRegExp("\\s")).replace(QString(":"), QString("_")); } -const QString CDisplayRendering::finishText( const QString& oldText, KeyTree& tree ) { - QList<const CSwordModuleInfo*> modules = collectModules(&tree); - qDebug() << "CDisplayRendering::finishText"; +QString CDisplayRendering::finishText(const QString &text, const KeyTree &tree) { + QList<const CSwordModuleInfo*> modules = collectModules(tree); //marking words is very slow, we have to find a better solution @@ -160,6 +154,6 @@ const QString CDisplayRendering::finishText( const QString& oldText, KeyTree& tr else settings.pageDirection = QString::null; - return tMgr->fillTemplate(CBTConfig::get(CBTConfig::displayStyle), oldText, settings); + return tMgr->fillTemplate(CDisplayTemplateMgr::activeTemplateName(), text, settings); } } diff --git a/src/backend/rendering/cdisplayrendering.h b/src/backend/rendering/cdisplayrendering.h index 8b222ac..362fc2a 100644 --- a/src/backend/rendering/cdisplayrendering.h +++ b/src/backend/rendering/cdisplayrendering.h @@ -21,21 +21,24 @@ namespace Rendering { */ class CDisplayRendering : public CHTMLExportRendering { - public: - static const QString keyToHTMLAnchor(const QString& key); + + public: /* Methods: */ + + static QString keyToHTMLAnchor(const QString &key); CDisplayRendering( const DisplayOptions &displayOptions = CBTConfig::getDisplayOptionDefaults(), - const FilterOptions &filterOptions = CBTConfig::getFilterOptionDefaults() - ); + const FilterOptions &filterOptions = CBTConfig::getFilterOptionDefaults()); + + protected: /* Methods: */ + + virtual QString entryLink(const KeyTreeItem &item, + const CSwordModuleInfo * module); - protected: - virtual const QString entryLink(const KeyTreeItem &item, - const CSwordModuleInfo *module); + virtual QString finishText(const QString &text, const KeyTree &tree); - virtual const QString finishText( const QString&, KeyTree& tree ); -}; +}; /* class CDisplayRendering */ -} +} /* namespace Rendering */ #endif diff --git a/src/backend/rendering/centrydisplay.cpp b/src/backend/rendering/centrydisplay.cpp index d1b2a34..7415eda 100644 --- a/src/backend/rendering/centrydisplay.cpp +++ b/src/backend/rendering/centrydisplay.cpp @@ -49,23 +49,21 @@ const QString CEntryDisplay::text( // don't print the key CTextRendering::KeyTreeItem::Settings preverse_settings(false, CTextRendering::KeyTreeItem::Settings::NoKey); - if (k1.Verse() == 1) { //X:1, prepend X:0 - if (k1.Chapter() == 1) { //1:1, also prepend 0:0 before that - k1.Chapter(0); - k1.Verse(0); + if (k1.getVerse() == 1) { // X:1, prepend X:0 + if (k1.getChapter() == 1) { // 1:1, also prepend 0:0 before that + k1.setChapter(0); + k1.setVerse(0); if ( k1.rawText().length() > 0 ) { tree.append( new Rendering::CTextRendering::KeyTreeItem(k1.key(), modules, preverse_settings) ); } - k1.Chapter(1); + k1.setChapter(1); } - k1.Verse(0); + k1.setVerse(0); if ( k1.rawText().length() > 0 ) { tree.append( new Rendering::CTextRendering::KeyTreeItem(k1.key(), modules, preverse_settings) ); } } } tree.append( new Rendering::CTextRendering::KeyTreeItem(keyName, modules, normal_settings) ); - QString result(render.renderKeyTree(tree)); - qDeleteAll(tree); - return result; + return render.renderKeyTree(tree); } diff --git a/src/backend/rendering/centrydisplay.h b/src/backend/rendering/centrydisplay.h index 08a55c4..50b6447 100644 --- a/src/backend/rendering/centrydisplay.h +++ b/src/backend/rendering/centrydisplay.h @@ -23,7 +23,9 @@ struct FilterOptions; namespace Rendering { class CEntryDisplay: public sword::SWDisplay { - public: + + public: /* Methods: */ + /** \returns the rendered text using the modules in the list and using the key parameter. @@ -32,9 +34,9 @@ class CEntryDisplay: public sword::SWDisplay { const QString &key, const DisplayOptions &displayOptions, const FilterOptions &filterOptions); -}; +}; /* class CEntryDisplay */ -} +} /* namespace Rendering */ #endif diff --git a/src/backend/rendering/chtmlexportrendering.cpp b/src/backend/rendering/chtmlexportrendering.cpp index 3d82602..66897b5 100644 --- a/src/backend/rendering/chtmlexportrendering.cpp +++ b/src/backend/rendering/chtmlexportrendering.cpp @@ -10,7 +10,6 @@ #include "backend/rendering/chtmlexportrendering.h" #include <QSharedPointer> -#include <QDebug> #include "backend/drivers/cswordmoduleinfo.h" #include "backend/keys/cswordkey.h" @@ -19,7 +18,9 @@ #include "backend/managers/clanguagemgr.h" -#ifdef BT_DEBUG +#if 0 +#include <QDebug> + namespace { /** Helper function to dump a verse with all its enty attributes. */ @@ -45,26 +46,28 @@ void dumpEntryAttributes(sword::SWModule *module) { namespace Rendering { CHTMLExportRendering::CHTMLExportRendering( - const CHTMLExportRendering::Settings &settings, + bool addText, const DisplayOptions &displayOptions, const FilterOptions &filterOptions) - : m_displayOptions(displayOptions), - m_filterOptions(filterOptions), - m_settings(settings) + : m_displayOptions(displayOptions) + , m_filterOptions(filterOptions) + , m_addText(addText) { // Intentionally empty } -const QString CHTMLExportRendering::renderEntry( const KeyTreeItem& i, CSwordKey* k) { +QString CHTMLExportRendering::renderEntry(const KeyTreeItem& i, CSwordKey* k) { if (i.hasAlternativeContent()) { - QString ret = QString(i.settings().highlight ? "<div class=\"currententry\">" : "<div class=\"entry\">"); + QString ret = i.settings().highlight + ? "<div class=\"currententry\">" + : "<div class=\"entry\">"; ret.append(i.getAlternativeContent()); // Q_ASSERT(i.hasChildItems()); if (!i.childList()->isEmpty()) { - KeyTree * const tree = i.childList(); + const KeyTree & tree = *i.childList(); const QList<const CSwordModuleInfo*> modules = collectModules(tree); @@ -72,8 +75,8 @@ const QString CHTMLExportRendering::renderEntry( const KeyTreeItem& i, CSwordKey ret.insert( 5, QString("dir=\"%1\" ").arg((modules.first()->textDirection() == CSwordModuleInfo::LeftToRight) ? "ltr" : "rtl" )); } - foreach ( KeyTreeItem* c, (*tree) ) { - ret.append( renderEntry( *c ) ); + Q_FOREACH (const KeyTreeItem * const item, tree) { + ret.append(renderEntry(*item)); } } @@ -83,8 +86,8 @@ const QString CHTMLExportRendering::renderEntry( const KeyTreeItem& i, CSwordKey const QList<const CSwordModuleInfo*> &modules(i.modules()); - if (modules.count() == 0) { - return QString(""); //no module present for rendering + if (modules.isEmpty()) { + return ""; //no module present for rendering } QSharedPointer<CSwordKey> scoped_key( !k ? CSwordKey::createInstance(modules.first()) : 0 ); @@ -93,7 +96,9 @@ const QString CHTMLExportRendering::renderEntry( const KeyTreeItem& i, CSwordKey CSwordVerseKey* myVK = dynamic_cast<CSwordVerseKey*>(key); - if ( myVK ) myVK->Headings(1); + if (myVK) { + myVK->Headings(1); + } QString renderedText( (modules.count() > 1) ? "\n\t\t<tr>\n" : "\n" ); // Only insert the table stuff if we are displaying parallel. @@ -142,7 +147,7 @@ const QString CHTMLExportRendering::renderEntry( const KeyTreeItem& i, CSwordKey (*mod_Itr)->module()->getEntryAttributes()["Heading"]["Preverse"].end(); for (; it != end; ++it) { - QString unfiltered = it->second.c_str(); + QString unfiltered = QString::fromUtf8(it->second.c_str()); /// \todo This is only a preliminary workaround to strip the tags: QRegExp filter("<title>(.*)</title>"); @@ -169,12 +174,12 @@ const QString CHTMLExportRendering::renderEntry( const KeyTreeItem& i, CSwordKey entry.append( i.settings().highlight ? "class=\"currententry\" " : "class=\"entry\" " ); } - entry.append(langAttr).append(isRTL ? " dir=\"rtl\"" : " dir=\"ltr\"").append(">"); + entry.append(langAttr).append(isRTL ? " dir=\"rtl\">" : " dir=\"ltr\">"); //keys should normally be left-to-right, but this doesn't apply in all cases entry.append("<span class=\"entryname\" dir=\"ltr\">").append(entryLink(i, *mod_Itr)).append("</span>"); - if (m_settings.addText) { + if (m_addText) { //entry.append( QString::fromLatin1("<span %1>%2</span>").arg(langAttr).arg(key_renderedText) ); entry.append( key_renderedText ); } @@ -182,7 +187,7 @@ const QString CHTMLExportRendering::renderEntry( const KeyTreeItem& i, CSwordKey if (!i.childList()->isEmpty()) { KeyTree* tree(i.childList()); - foreach (KeyTreeItem* c, (*tree)) { + Q_FOREACH (const KeyTreeItem * const c, *tree) { entry.append( renderEntry(*c) ); } } @@ -218,28 +223,31 @@ void CHTMLExportRendering::initRendering() { CSwordBackend::instance()->setFilterOptions( m_filterOptions ); } -const QString CHTMLExportRendering::finishText( const QString& text, KeyTree& tree ) { - const QList<const CSwordModuleInfo*> modules = collectModules(&tree); - - const CLanguageMgr::Language* const lang = modules.first()->language(); - - CDisplayTemplateMgr *tMgr = CDisplayTemplateMgr::instance(); - CDisplayTemplateMgr::Settings settings; - settings.modules = modules; - settings.langAbbrev = ((modules.count() == 1) && lang->isValid()) ? lang->abbrev() : "unknown"; - if (modules.count() == 1) - settings.pageDirection = ((modules.first()->textDirection() == CSwordModuleInfo::LeftToRight) ? "ltr" : "rtl"); - else +QString CHTMLExportRendering::finishText(const QString &text, const KeyTree &tree) { + typedef CDisplayTemplateMgr CDTM; + + CDTM::Settings settings; + settings.modules = collectModules(tree); + if (settings.modules.count() == 1) { + const CSwordModuleInfo * const firstModule = settings.modules.first(); + const CLanguageMgr::Language * const lang = firstModule->language(); + settings.langAbbrev = lang->isValid() ? lang->abbrev() : "unknown"; + if (firstModule->textDirection() == CSwordModuleInfo::RightToLeft) { + settings.pageDirection = "rtl"; + } + } else { + settings.langAbbrev = "unknown"; settings.pageDirection = QString::null; + } - return tMgr->fillTemplate(QObject::tr("Export"), text, settings); + return CDTM::instance()->fillTemplate(QObject::tr("Export"), text, settings); } /*! \fn CHTMLExportRendering::entryLink( KeyTreeItem& item ) */ -const QString CHTMLExportRendering::entryLink(const KeyTreeItem& item, - const CSwordModuleInfo *module) +QString CHTMLExportRendering::entryLink(const KeyTreeItem &item, + const CSwordModuleInfo * module) { Q_UNUSED(module); diff --git a/src/backend/rendering/chtmlexportrendering.h b/src/backend/rendering/chtmlexportrendering.h index 97e632d..db90707 100644 --- a/src/backend/rendering/chtmlexportrendering.h +++ b/src/backend/rendering/chtmlexportrendering.h @@ -25,37 +25,31 @@ namespace Rendering { * @short HTML rendering for export. * @author The BibleTime team */ +class CHTMLExportRendering: public CTextRendering { -class CHTMLExportRendering : public CTextRendering { - - public: - struct Settings { - Settings(const bool text = true) { - addText = text; - }; - - bool addText; - }; + public: /* Methods: */ CHTMLExportRendering( - const Settings &settings, + bool addText, const DisplayOptions &displayOptions = CBTConfig::getDisplayOptionDefaults(), - const FilterOptions &filterOptions = CBTConfig::getFilterOptionDefaults() - ); - virtual inline ~CHTMLExportRendering() {}; - - protected: - virtual const QString renderEntry( const KeyTreeItem&, CSwordKey* = 0 ); - virtual const QString finishText( const QString&, KeyTree& tree ); - virtual const QString entryLink(const KeyTreeItem &item, - const CSwordModuleInfo *module); + const FilterOptions &filterOptions = CBTConfig::getFilterOptionDefaults()); + + protected: /* Methods: */ + + virtual QString renderEntry(const KeyTreeItem &item, CSwordKey * key = 0); + virtual QString finishText(const QString &text, const KeyTree &tree); + virtual QString entryLink(const KeyTreeItem &item, + const CSwordModuleInfo *module); virtual void initRendering(); + protected: /* Fields: */ + DisplayOptions m_displayOptions; FilterOptions m_filterOptions; - Settings m_settings; -}; + bool m_addText; + +}; /* class CHTMLExportRendering */ -} +} /* namespace Rendering */ #endif diff --git a/src/backend/rendering/cplaintextexportrendering.cpp b/src/backend/rendering/cplaintextexportrendering.cpp index cad5eb9..4bff025 100644 --- a/src/backend/rendering/cplaintextexportrendering.cpp +++ b/src/backend/rendering/cplaintextexportrendering.cpp @@ -16,33 +16,29 @@ namespace Rendering { CPlainTextExportRendering::CPlainTextExportRendering( - const CPlainTextExportRendering::Settings &settings, + bool addText, const DisplayOptions &displayOptions, const FilterOptions &filterOptions) - : CHTMLExportRendering(settings, displayOptions, filterOptions) + : CHTMLExportRendering(addText, displayOptions, filterOptions) { // Intentionally empty } -const QString CPlainTextExportRendering::renderEntry(const KeyTreeItem &i, - CSwordKey *k) +QString CPlainTextExportRendering::renderEntry(const KeyTreeItem &i, + CSwordKey * k) { Q_UNUSED(k); - if (!m_settings.addText) { + if (!m_addText) return QString(i.key()).append("\n"); - } - QList<const CSwordModuleInfo*> modules = i.modules(); - QSharedPointer<CSwordKey> key( CSwordKey::createInstance(modules.first()) ); + const QList<const CSwordModuleInfo*> modules = i.modules(); + CSwordKey * key = CSwordKey::createInstance(modules.first()); QString renderedText = QString(i.key()).append(":\n"); QString entry; - // for (CSwordModuleInfo* m = modules.first(); m; m = modules.next()) { - QList<const CSwordModuleInfo*>::iterator end_it = modules.end(); - - for (QList<const CSwordModuleInfo*>::iterator it(modules.begin()); it != end_it; ++it) { - key->setModule(*it); + Q_FOREACH(const CSwordModuleInfo * module, modules) { + key->setModule(module); key->setKey(i.key()); /// \todo Check this code @@ -50,11 +46,13 @@ const QString CPlainTextExportRendering::renderEntry(const KeyTreeItem &i, renderedText.append( entry ); } + delete key; return renderedText; } -const QString CPlainTextExportRendering::finishText( const QString& oldText, KeyTree& ) { - return oldText; +QString CPlainTextExportRendering::finishText(const QString &text, const KeyTree &tree) { + Q_UNUSED(tree); + return text; } } diff --git a/src/backend/rendering/cplaintextexportrendering.h b/src/backend/rendering/cplaintextexportrendering.h index d14192e..9360474 100644 --- a/src/backend/rendering/cplaintextexportrendering.h +++ b/src/backend/rendering/cplaintextexportrendering.h @@ -20,22 +20,22 @@ namespace Rendering { * @short Text rendering as plain text. * @author The BibleTime team */ +class CPlainTextExportRendering: public CHTMLExportRendering { -class CPlainTextExportRendering : public CHTMLExportRendering { + public: /* Methods: */ - public: CPlainTextExportRendering( - const Settings &settings, + bool addText, const DisplayOptions &displayOptions = CBTConfig::getDisplayOptionDefaults(), - const FilterOptions &filterOptions = CBTConfig::getFilterOptionDefaults() - ); - virtual inline ~CPlainTextExportRendering() {}; + const FilterOptions &filterOptions = CBTConfig::getFilterOptionDefaults()); - protected: - virtual const QString renderEntry( const KeyTreeItem&, CSwordKey* = 0 ); - virtual const QString finishText( const QString&, KeyTree& tree ); -}; + protected: /* Methods: */ -} + virtual QString renderEntry(const KeyTreeItem &item, CSwordKey * key = 0); + virtual QString finishText(const QString &text, const KeyTree &tree); + +}; /* class CPlainTextExportRendering */ + +} /* namespace Rendering */ #endif diff --git a/src/backend/rendering/ctextrendering.cpp b/src/backend/rendering/ctextrendering.cpp index 586d11e..72e4e12 100644 --- a/src/backend/rendering/ctextrendering.cpp +++ b/src/backend/rendering/ctextrendering.cpp @@ -74,8 +74,10 @@ CTextRendering::KeyTreeItem::KeyTreeItem(const KeyTreeItem& i) m_key( i.m_key ), m_childList(), m_stopKey( i.m_stopKey ), - m_alternativeContent( i.m_alternativeContent ) { - foreach(KeyTreeItem* item, (*i.childList())) { + m_alternativeContent( i.m_alternativeContent ) +{ + const KeyTree &tree = *i.childList(); + Q_FOREACH (const KeyTreeItem * const item, tree) { m_childList.append(new KeyTreeItem((*item))); //deep copy } @@ -134,19 +136,19 @@ CTextRendering::KeyTreeItem::KeyTreeItem(const QString &startKey, else { sword::VerseKey vk(startKey.toUtf8().constData(), stopKey.toUtf8().constData()); - if (vk.LowerBound().Book() != vk.UpperBound().Book()) { + if (vk.LowerBound().getBook() != vk.UpperBound().getBook()) { m_alternativeContent = QString::fromUtf8(vk.getRangeText()); } - else if (vk.LowerBound().Chapter() != vk.UpperBound().Chapter()) { + else if (vk.LowerBound().getChapter() != vk.UpperBound().getChapter()) { m_alternativeContent = QString("%1 - %2:%3") .arg(QString::fromUtf8(vk.LowerBound().getText())) - .arg(vk.UpperBound().Chapter()) - .arg(vk.UpperBound().Verse()); + .arg(vk.UpperBound().getChapter()) + .arg(vk.UpperBound().getVerse()); } else { //only verses differ (same book, same chapter) m_alternativeContent = QString("%1 - %2") .arg(QString::fromUtf8(vk.LowerBound().getText())) - .arg(vk.UpperBound().Verse()); + .arg(vk.UpperBound().getVerse()); } } @@ -154,29 +156,24 @@ CTextRendering::KeyTreeItem::KeyTreeItem(const QString &startKey, m_alternativeContent.prepend("<div class=\"rangeheading\" dir=\"ltr\">").append("</div>"); //insert the right tags } -const QString& CTextRendering::KeyTreeItem::getAlternativeContent() const { - return m_alternativeContent; -} - -const QList<const CSwordModuleInfo*> CTextRendering::collectModules(KeyTree* const tree) const { +QList<const CSwordModuleInfo*> CTextRendering::collectModules(const KeyTree &tree) const { //collect all modules which are available and used by child items QList<const CSwordModuleInfo*> modules; - foreach (KeyTreeItem* c, (*tree)) { - Q_ASSERT(c); - foreach (const CSwordModuleInfo* mod, c->modules()) { - if (!modules.contains(mod)) { + Q_FOREACH (const KeyTreeItem * const c, tree) { + Q_ASSERT(c != 0); + Q_FOREACH (const CSwordModuleInfo * const mod, c->modules()) { + if (!modules.contains(mod)) modules.append(mod); - } } } return modules; } -const QString CTextRendering::renderKeyTree( KeyTree& tree ) { +const QString CTextRendering::renderKeyTree(const KeyTree &tree) { initRendering(); - QList<const CSwordModuleInfo*> modules = collectModules(&tree); + const QList<const CSwordModuleInfo*> modules = collectModules(tree); QString t; //optimization for entries with the same key @@ -185,13 +182,13 @@ const QString CTextRendering::renderKeyTree( KeyTree& tree ) { ); if (modules.count() == 1) { //this optimizes the rendering, only one key created for all items - foreach (KeyTreeItem* c, tree) { + Q_FOREACH (const KeyTreeItem * const c, tree) { key->setKey(c->key()); t.append( renderEntry( *c, key.data()) ); } } else { - foreach (KeyTreeItem* c, tree) { + Q_FOREACH (const KeyTreeItem * const c, tree) { t.append( renderEntry( *c ) ); } } @@ -245,18 +242,16 @@ const QString CTextRendering::renderKeyRange( it should be displayed as one entry with the caption 1-5. */ - if (vk_start->Chapter() == 0) { //range was 0:0-1:x, render 0:0 first and jump to 1:0 - vk_start->Verse(0); + if (vk_start->getChapter() == 0) { // range was 0:0-1:x, render 0:0 first and jump to 1:0 + vk_start->setVerse(0); tree.append( new KeyTreeItem(vk_start->key(), modules, settings) ); - vk_start->Chapter(1); - vk_start->Verse(0); + vk_start->setChapter(1); + vk_start->setVerse(0); } tree.append( new KeyTreeItem(vk_start->key(), modules, settings) ); ok = vk_start->next(CSwordVerseKey::UseVerse); } - const QString renderedText = renderKeyTree(tree); - qDeleteAll(tree); - return renderedText; + return renderKeyTree(tree); } return QString::null; @@ -270,7 +265,5 @@ const QString CTextRendering::renderSingleKey( KeyTree tree; tree.append( new KeyTreeItem(key, modules, settings) ); - const QString renderedText = renderKeyTree(tree); - qDeleteAll(tree); - return renderedText; + return renderKeyTree(tree); } diff --git a/src/backend/rendering/ctextrendering.h b/src/backend/rendering/ctextrendering.h index c6b187a..161deef 100644 --- a/src/backend/rendering/ctextrendering.h +++ b/src/backend/rendering/ctextrendering.h @@ -11,12 +11,15 @@ #define CTEXTRENDERING_H #include <QList> +#include <QSharedPointer> #include <QString> class CSwordKey; class CSwordModuleInfo; +namespace Rendering { + /** * CTextRendering is BibleTime's place where the actual rendering takes place. * It provides several methods to convert an abstract tree of items @@ -26,20 +29,28 @@ class CSwordModuleInfo; * @short Text rendering based on trees * @author The BibleTime team */ - -namespace Rendering { - class CTextRendering { - public: + public: /* Types: */ class KeyTreeItem; - typedef QList<KeyTreeItem*> KeyTree; - class KeyTreeItem { + class KeyTreeSharedPointer: public QSharedPointer<KeyTreeItem> { public: + inline KeyTreeSharedPointer(KeyTreeItem * i) + : QSharedPointer<KeyTreeItem>(i) {} + + inline operator const KeyTreeItem * () const { return data(); } + }; + + typedef QList<KeyTreeSharedPointer> KeyTree; + + class KeyTreeItem { + + public: /* Types: */ struct Settings { + enum KeyRenderingFace { NoKey, //< means no key shown at all SimpleKey, //< means only versenumber or only lexicon entry name @@ -47,11 +58,18 @@ class CTextRendering { CompleteLong //< means "Genesis 1:1" }; - Settings(const bool highlight = false, KeyRenderingFace keyRendering = SimpleKey) : highlight(highlight), keyRenderingFace(keyRendering) {} + Settings(const bool highlight = false, + KeyRenderingFace keyRendering = SimpleKey) + : highlight(highlight) + , keyRenderingFace(keyRendering) + {} bool highlight; KeyRenderingFace keyRenderingFace; - }; + + }; /* struct Settings */ + + public: /* Methods: */ KeyTreeItem(const QString &key, const CSwordModuleInfo *module, @@ -70,37 +88,40 @@ class CTextRendering { KeyTreeItem(const KeyTreeItem &i); - virtual inline ~KeyTreeItem() { - qDeleteAll(m_childList); + inline const QString &getAlternativeContent() const { + return m_alternativeContent; } - const QString& getAlternativeContent() const; inline void setAlternativeContent(const QString& newContent) { m_alternativeContent = newContent; - }; + } inline bool hasAlternativeContent() const { return !m_alternativeContent.isNull(); - }; + } inline const QList<const CSwordModuleInfo*>& modules() const { return m_moduleList; - }; + } inline const QString& key() const { return m_key; - }; + } inline const Settings& settings() const { return m_settings; - }; + } - inline KeyTree* childList() const; -// inline const bool hasChildItems() const; + inline KeyTree* childList() const { + return &m_childList; + } + + protected: /* Methods: */ - protected: KeyTreeItem(); + private: /* Fields: */ + Settings m_settings; QList<const CSwordModuleInfo*> m_moduleList; QString m_key; @@ -108,11 +129,12 @@ class CTextRendering { QString m_stopKey; QString m_alternativeContent; - }; - virtual ~CTextRendering() {} + }; /* class KeyTreeItem */ + + public: /* Methods: */ - const QString renderKeyTree( KeyTree& ); + const QString renderKeyTree(const KeyTree &tree); const QString renderKeyRange( const QString &start, @@ -126,21 +148,15 @@ class CTextRendering { const QList<const CSwordModuleInfo*> &modules, const KeyTreeItem::Settings &settings = KeyTreeItem::Settings()); - protected: - const QList<const CSwordModuleInfo*> collectModules(KeyTree* const tree) const; - virtual const QString renderEntry( const KeyTreeItem&, CSwordKey* = 0 ) = 0; - virtual const QString finishText( const QString&, KeyTree& tree ) = 0; + protected: /* Methods: */ + + QList<const CSwordModuleInfo*> collectModules(const KeyTree &tree) const; + virtual QString renderEntry(const KeyTreeItem &item, CSwordKey * key = 0) = 0; + virtual QString finishText(const QString &text, const KeyTree &tree) = 0; virtual void initRendering() = 0; -}; -inline CTextRendering::KeyTree* CTextRendering::KeyTreeItem::childList() const { - return &m_childList; -} -// -//inline const bool CTextRendering::KeyTreeItem::hasChildItems() const { -// return !m_childList.isEmpty(); -//} +}; /* class CTextRendering */ -} +} /* namespace Rendering */ #endif diff --git a/src/bibletime.cpp b/src/bibletime.cpp index d4fa90d..4864c9a 100644 --- a/src/bibletime.cpp +++ b/src/bibletime.cpp @@ -9,17 +9,16 @@ #include "bibletime.h" +#include <cstdlib> #include <QAction> #include <QApplication> #include <QCloseEvent> -#include <QDate> #include <QDebug> #include <QInputDialog> #include <QMdiSubWindow> #include <QMessageBox> #include <QSplashScreen> #include <QSplitter> -#include <ctime> #include "backend/config/cbtconfig.h" #include "backend/drivers/cswordbiblemoduleinfo.h" #include "backend/drivers/cswordbookmoduleinfo.h" @@ -46,58 +45,57 @@ using namespace Profile; BibleTime *BibleTime::m_instance = 0; BibleTime::BibleTime(QWidget *parent, Qt::WindowFlags flags) - : QMainWindow(parent, flags), m_WindowWasMaximizedBeforeFullScreen(false) + : QMainWindow(parent, flags) { namespace DU = util::directory; Q_ASSERT(m_instance == 0); m_instance = this; - QSplashScreen splash; - bool showSplash = CBTConfig::get(CBTConfig::logo); + QSplashScreen *splash = 0; QString splashHtml; - if (showSplash) { + if (CBTConfig::get(CBTConfig::logo)) { splashHtml = "<div style='background:transparent;color:white;font-weight:bold'>%1" "</div>"; - const QDate date(QDate::currentDate()); - const int day = date.day(); - const int month = date.month(); - QString splashImage(DU::getPicsDir().canonicalPath().append("/")); - - if ((month >= 12 && day >= 24) || (month <= 1 && day < 6)) { - splashImage.append("startuplogo_christmas.png"); - } else { - splashImage.append("startuplogo.png"); - } + static const char * const splashes[3] = { + "startuplogo.png", + "startuplogo_christmas.png", + "startuplogo_easter.jpg" + }; + QString splashImage = DU::getPicsDir().canonicalPath().append("/") + .append(splashes[rand() % 3]); QPixmap pm; if (!pm.load(splashImage)) { qWarning("Can't load startuplogo! Check your installation."); } - splash.setPixmap(pm); - splash.show(); - - splash.showMessage(splashHtml.arg(tr("Initializing the SWORD engine...")), - Qt::AlignCenter); + splash = new QSplashScreen(this, pm); + splash->setAttribute(Qt::WA_DeleteOnClose); + splash->finish(this); + splash->showMessage(splashHtml.arg(tr("Initializing the SWORD engine...")), + Qt::AlignCenter); + splash->show(); + qApp->processEvents(); } initBackends(); - if (showSplash) { - splash.showMessage(splashHtml.arg(tr("Creating BibleTime's user interface...")), - Qt::AlignCenter); + if (splash != 0) { + splash->showMessage(splashHtml.arg(tr("Creating BibleTime's user interface...")), + Qt::AlignCenter); + qApp->processEvents(); } initView(); - if (showSplash) { - splash.showMessage(splashHtml.arg(tr("Initializing menu- and toolbars...")), - Qt::AlignCenter); + if (splash != 0) { + splash->showMessage(splashHtml.arg(tr("Initializing menu- and toolbars...")), + Qt::AlignCenter); + qApp->processEvents(); } initActions(); initMenubar(); initToolbars(); initConnections(); - readSettings(); setWindowTitle("BibleTime " BT_VERSION); setWindowIcon(DU::getIcon(CResMgr::mainWindow::icon)); @@ -110,73 +108,12 @@ BibleTime::~BibleTime() { #ifdef BT_DEBUG deleteDebugWindow(); #endif - saveSettings(); -} - -/** Saves the properties of BibleTime to the application wide configfile */ -void BibleTime::saveSettings() { - /// \todo how to write settings? - //accel()->writeSettings(CBTConfig::getConfig()); - - CBTConfig::set(CBTConfig::toolbar, m_viewToolbarAction->isChecked()); - - // set the default to false - /* CBTConfig::set(CBTConfig::autoTileVertical, false); - CBTConfig::set(CBTConfig::autoTileHorizontal, false); - CBTConfig::set(CBTConfig::autoCascade, false); - */ - CBTConfig::set(CBTConfig::autoTileVertical, m_windowAutoTileVerticalAction->isChecked()); - CBTConfig::set(CBTConfig::autoTileHorizontal, m_windowAutoTileHorizontalAction->isChecked()); - CBTConfig::set(CBTConfig::autoTile, m_windowAutoTileAction->isChecked()); - CBTConfig::set(CBTConfig::autoTabbed, m_windowAutoTabbedAction->isChecked()); - CBTConfig::set(CBTConfig::autoCascade, m_windowAutoCascadeAction->isChecked()); - CProfile* p = m_profileMgr.startupProfile(); if (p) { saveProfile(p); } } -/** Reads the settings from the configfile and sets the right properties. */ -void BibleTime::readSettings() { - qDebug() << "******************BibleTime::readSettings******************************"; - // accel()->readSettings(CBTConfig::getConfig()); - CBTConfig::setupAccelSettings(CBTConfig::application, m_actionCollection); - - m_viewToolbarAction->setChecked( CBTConfig::get(CBTConfig::toolbar) ); - slotToggleMainToolbar(); - - if ( CBTConfig::get(CBTConfig::autoTileVertical) ) { - m_windowAutoTileVerticalAction->setChecked( true ); - m_windowManualModeAction->setChecked(false); - slotAutoTileVertical(); - } - else if ( CBTConfig::get(CBTConfig::autoTileHorizontal) ) { - m_windowAutoTileHorizontalAction->setChecked( true ); - m_windowManualModeAction->setChecked(false); - slotAutoTileHorizontal(); - } - else if ( CBTConfig::get(CBTConfig::autoTile) ) { - m_windowAutoTileAction->setChecked(true); - m_windowManualModeAction->setChecked(false); - slotAutoTile(); - } - else if ( CBTConfig::get(CBTConfig::autoTabbed) ) { - m_windowAutoTabbedAction->setChecked(true); - m_windowManualModeAction->setChecked(false); - slotAutoTabbed(); - } - else if ( CBTConfig::get(CBTConfig::autoCascade) ) { - m_windowAutoCascadeAction->setChecked(true); - m_windowManualModeAction->setChecked(false); - slotAutoCascade(); - } - else { - m_windowManualModeAction->setChecked(true); - slotManualArrangementMode(); - } -} - /** Creates a new presenter in the MDI area according to the type of the module. */ CDisplayWindow* BibleTime::createReadDisplayWindow(QList<CSwordModuleInfo*> modules, const QString& key) { qApp->setOverrideCursor( QCursor(Qt::WaitCursor) ); @@ -217,7 +154,7 @@ CDisplayWindow* BibleTime::createWriteDisplayWindow(CSwordModuleInfo* module, co if ( displayWindow ) { displayWindow->init(); m_mdi->addSubWindow(displayWindow); - if (m_mdi->subWindowList().count() == 0) + if (m_mdi->subWindowList().isEmpty()) displayWindow->showMaximized(); else displayWindow->show(); @@ -295,8 +232,8 @@ void BibleTime::moduleAbout(CSwordModuleInfo *module) { } /** Refreshes all presenters.*/ -void BibleTime::refreshDisplayWindows() { - foreach (QMdiSubWindow* subWindow, m_mdi->subWindowList()) { +void BibleTime::refreshDisplayWindows() const { + Q_FOREACH (const QMdiSubWindow * const subWindow, m_mdi->subWindowList()) { if (CDisplayWindow* window = dynamic_cast<CDisplayWindow*>(subWindow->widget())) { window->reload(CSwordBackend::OtherChange); } @@ -314,8 +251,8 @@ void BibleTime::closeEvent(QCloseEvent *event) { window returns false, the querying is stopped and the close event is ignored. If all subwindows return true, the close event is accepted. */ - Q_FOREACH(QMdiSubWindow *subWindow, m_mdi->subWindowList()) { - if (CDisplayWindow* window = dynamic_cast<CDisplayWindow*>(subWindow->widget())) { + Q_FOREACH (QMdiSubWindow * const subWindow, m_mdi->subWindowList()) { + if (CDisplayWindow * const window = dynamic_cast<CDisplayWindow*>(subWindow->widget())) { if (!window->queryClose()) { event->ignore(); return; @@ -325,20 +262,16 @@ void BibleTime::closeEvent(QCloseEvent *event) { event->accept(); } -/** Restores the workspace if the flag for this is set in the config. */ -void BibleTime::restoreWorkspace() { - if (CProfile* p = m_profileMgr.startupProfile()) { - loadProfile(p); - } -} - void BibleTime::processCommandline(bool ignoreSession, const QString &bibleKey) { if (CBTConfig::get(CBTConfig::crashedTwoTimes)) { return; } + // Restore workspace if not not ignoring session data: if (!ignoreSession) { - restoreWorkspace(); + CProfile * p = m_profileMgr.startupProfile(); + if (p) + loadProfile(p); } if (CBTConfig::get(CBTConfig::crashedLastTime)) { @@ -350,9 +283,6 @@ void BibleTime::processCommandline(bool ignoreSession, const QString &bibleKey) if (bibleKey == "random") { CSwordVerseKey vk(0); const int maxIndex = 31100; - time_t seconds; - seconds = time (NULL); - srand(seconds); int newIndex = rand() % maxIndex; vk.setPosition(sword::TOP); vk.Index(newIndex); diff --git a/src/bibletime.h b/src/bibletime.h index f35be23..22faac2 100644 --- a/src/bibletime.h +++ b/src/bibletime.h @@ -15,7 +15,6 @@ #include <QList> #include "frontend/displaywindow/cdisplaywindow.h" #include "frontend/displaywindow/cwritewindow.h" -#include "frontend/profile/cprofile.h" #include "frontend/profile/cprofilemgr.h" #include <QSignalMapper> #ifdef BT_DEBUG @@ -137,18 +136,6 @@ class BibleTime : public QMainWindow { static inline BibleTime *instance() { return m_instance; } /** - * Reads the settings from the configfile and sets the right properties. - */ - void readSettings(); - /** - * Saves the settings of this class - */ - void saveSettings(); - /** - * Restores the workspace if the flaf for this is set in the config. - */ - void restoreWorkspace(); - /** * Apply the settings given by the profile p */ void applyProfileSettings( Profile::CProfile* p ); @@ -296,7 +283,7 @@ class BibleTime : public QMainWindow { /** * Refreshes all presenter supporting at least in of the features given as parameter. */ - void refreshDisplayWindows(); + void refreshDisplayWindows() const; /** * Refresh main window accelerators */ @@ -441,9 +428,6 @@ class BibleTime : public QMainWindow { private: static BibleTime *m_instance; - // True if window was maximized before last toggle to full screen. - bool m_WindowWasMaximizedBeforeFullScreen; - // Docking widgets and their respective content widgets: BtBookshelfDockWidget* m_bookshelfDock; QDockWidget* m_bookmarksDock; @@ -464,11 +448,11 @@ class BibleTime : public QMainWindow { // View menu: QMenu *m_viewMenu; - QAction* m_viewToolbarAction; QAction *m_showBookshelfAction; QAction *m_showBookmarksAction; QAction *m_showMagAction; QMenu *m_toolBarsMenu; + QAction* m_showMainWindowToolbarAction; QAction *m_showTextAreaHeadersAction; QAction *m_showTextWindowNavigationAction; QAction *m_showTextWindowModuleChooserAction; diff --git a/src/bibletime_dbus.cpp b/src/bibletime_dbus.cpp index e3013db..9b983c1 100644 --- a/src/bibletime_dbus.cpp +++ b/src/bibletime_dbus.cpp @@ -9,10 +9,8 @@ #include "bibletime.h" -#include <QDebug> #include <QList> #include <QMdiSubWindow> -#include "backend/config/cbtconfig.h" #include "backend/keys/cswordversekey.h" #include "frontend/cmdiarea.h" @@ -23,59 +21,19 @@ //helper function void BibleTime::syncAllModulesByType(const CSwordModuleInfo::ModuleType type, const QString& key) { - qDebug() << "Syncing modules by type to key" << key.toLatin1(); - foreach (QMdiSubWindow* w, m_mdi->usableWindowList()) { - CDisplayWindow* d = dynamic_cast<CDisplayWindow*>(w->widget()); - if (d && d->modules().count() && d->modules().first()->type() == type) { + Q_FOREACH (const QMdiSubWindow * const w, m_mdi->usableWindowList()) { + CDisplayWindow * const d = dynamic_cast<CDisplayWindow*>(w->widget()); + if (d != 0 && !d->modules().isEmpty() && d->modules().first()->type() == type) { d->lookupKey(key); } } } void BibleTime::closeAllModuleWindows() { - qDebug() << "DBUS: close all windows now..."; m_mdi->closeAllSubWindows(); } -void BibleTime::syncAllBibles(const QString& key) { - qDebug() << "DBUS: syncing all bibles ..."; - syncAllModulesByType(CSwordModuleInfo::Bible, key); -} - -void BibleTime::syncAllCommentaries(const QString& key) { - qDebug() << "DBUS: syncing all commentaries ..."; - syncAllModulesByType(CSwordModuleInfo::Commentary, key); -} - -void BibleTime::syncAllLexicons(const QString& key) { - qDebug() << "DBUS: syncing all lexicons ..."; - syncAllModulesByType(CSwordModuleInfo::Lexicon, key); -} - -void BibleTime::syncAllVerseBasedModules(const QString& key) { - qDebug() << "DBUS: syncing all verse based modules ..."; - syncAllModulesByType(CSwordModuleInfo::Bible, key); - syncAllModulesByType(CSwordModuleInfo::Commentary, key); -} - -void BibleTime::openWindow(const QString& moduleName, const QString& key) { - qDebug() << "DBUS: open window for module" << moduleName.toLatin1() << "and key" << key.toLatin1(); - CSwordModuleInfo* module = CSwordBackend::instance()->findModuleByName(moduleName); - if (module) { - createReadDisplayWindow(module, key); - } -} - -void BibleTime::openDefaultBible(const QString& key) { - qDebug() << "DBUS: open default bible ..."; - CSwordModuleInfo* mod = CBTConfig::get(CBTConfig::standardBible); - if (mod) { - openWindow(mod->name(), key); - } -} - QStringList BibleTime::searchInModule(const QString& moduleName, const QString& searchText) { - qDebug() << "DBUS: searchInModule" << moduleName.toLatin1(); QStringList ret; CSwordModuleInfo* mod = CSwordBackend::instance()->findModuleByName(moduleName); @@ -102,33 +60,23 @@ QStringList BibleTime::searchInModule(const QString& moduleName, const QString& } } } - return ret; - } QStringList BibleTime::searchInOpenModules(const QString& searchText) { - qDebug() << "DBUS: search in open modules ..."; QStringList ret; - foreach (QMdiSubWindow* subWindow, m_mdi->subWindowList()) { - if (CDisplayWindow* w = dynamic_cast<CDisplayWindow*>(subWindow->widget())) { - QList<const CSwordModuleInfo*> windowModules = w->modules(); - QList<const CSwordModuleInfo*>::iterator end_it = windowModules.end(); - for (QList<const CSwordModuleInfo*>::iterator it(windowModules.begin()); it != end_it; ++it) { - ret += searchInModule((*it)->name(), searchText); + Q_FOREACH (const QMdiSubWindow * const subWindow, m_mdi->subWindowList()) { + const CDisplayWindow * const w = dynamic_cast<CDisplayWindow*>(subWindow->widget()); + if (w != 0) { + Q_FOREACH (const CSwordModuleInfo * const mi, w->modules()) { + ret += searchInModule(mi->name(), searchText); } } } return ret; } -QStringList BibleTime::searchInDefaultBible(const QString& searchText) { - CSwordModuleInfo* bible = CBTConfig::get(CBTConfig::standardBible); - return searchInModule(bible->name(), searchText); -} - QString BibleTime::getCurrentReference() { - qDebug() << "BibleTime::getCurrentReference"; QString ret = QString::null; QMdiSubWindow* activeSubWindow = m_mdi->activeSubWindow(); @@ -174,8 +122,8 @@ QString BibleTime::getCurrentReference() { QStringList BibleTime::getModulesOfType(const QString& type) { QStringList ret; + CSwordModuleInfo::ModuleType modType; - CSwordModuleInfo::ModuleType modType = CSwordModuleInfo::Unknown; if (type == "BIBLES") { modType = CSwordModuleInfo::Bible; } @@ -184,16 +132,17 @@ QStringList BibleTime::getModulesOfType(const QString& type) { } else if (type == "LEXICONS") { modType = CSwordModuleInfo::Lexicon; - } else if (type == "BOOKS") { modType = CSwordModuleInfo::GenericBook; } + else { + modType = CSwordModuleInfo::Unknown; + } - QList<CSwordModuleInfo*> modList = CSwordBackend::instance()->moduleList(); - for (QList<CSwordModuleInfo*>::iterator it( modList.begin() ); it != modList.end(); ++it) { - if ((*it)->type() == modType) { - ret.append( (*it)->name() ); + Q_FOREACH(const CSwordModuleInfo * const mi, CSwordBackend::instance()->moduleList()) { + if (mi->type() == modType) { + ret.append(mi->name()); } } diff --git a/src/bibletime_dbus_adaptor.cpp b/src/bibletime_dbus_adaptor.cpp index bf6ba79..6912ff1 100644 --- a/src/bibletime_dbus_adaptor.cpp +++ b/src/bibletime_dbus_adaptor.cpp @@ -11,56 +11,78 @@ #include "bibletime_dbus_adaptor.h" - -BibleTimeDBusAdaptor::BibleTimeDBusAdaptor(BibleTime *bibletime_ptr) : - QDBusAbstractAdaptor(bibletime_ptr), - m_bibletime(bibletime_ptr) { +#include <QDebug> +#include "backend/config/cbtconfig.h" + +BibleTimeDBusAdaptor::BibleTimeDBusAdaptor(BibleTime *pBibleTime) + : QDBusAbstractAdaptor(pBibleTime) + , m_bibletime(pBibleTime) +{ + // Intentionally empty } -void BibleTimeDBusAdaptor::syncAllBibles(const QString& key) { - m_bibletime->syncAllBibles(key); +void BibleTimeDBusAdaptor::syncAllBibles(const QString &key) { + qDebug() << "DBUS: syncing all bibles ..."; + m_bibletime->syncAllModulesByType(CSwordModuleInfo::Bible, key); } -void BibleTimeDBusAdaptor::syncAllCommentaries(const QString& key) { - m_bibletime->syncAllCommentaries(key); +void BibleTimeDBusAdaptor::syncAllCommentaries(const QString &key) { + qDebug() << "DBUS: syncing all commentaries ..."; + m_bibletime->syncAllModulesByType(CSwordModuleInfo::Commentary, key); } -void BibleTimeDBusAdaptor::syncAllLexicons(const QString& key) { - m_bibletime->syncAllLexicons(key); +void BibleTimeDBusAdaptor::syncAllLexicons(const QString &key) { + qDebug() << "DBUS: syncing all lexicons ..."; + m_bibletime->syncAllModulesByType(CSwordModuleInfo::Lexicon, key); } -void BibleTimeDBusAdaptor::syncAllVerseBasedModules(const QString& key) { - m_bibletime->syncAllVerseBasedModules(key); +void BibleTimeDBusAdaptor::syncAllVerseBasedModules(const QString &key) { + qDebug() << "DBUS: syncing all verse based modules ..."; + m_bibletime->syncAllModulesByType(CSwordModuleInfo::Bible, key); + m_bibletime->syncAllModulesByType(CSwordModuleInfo::Commentary, key); } -void BibleTimeDBusAdaptor::openWindow(const QString& moduleName, const QString& key) { - m_bibletime->openWindow(moduleName, key); +void BibleTimeDBusAdaptor::openWindow(const QString &moduleName, const QString &key) { + qDebug() << "DBUS: open window for module" << moduleName.toLatin1() << "and key" << key.toLatin1() << " ..."; + CSwordModuleInfo *module = CSwordBackend::instance()->findModuleByName(moduleName); + if (module) + m_bibletime->createReadDisplayWindow(module, key); } -void BibleTimeDBusAdaptor::openDefaultBible(const QString& key) { - m_bibletime->openDefaultBible(key); +void BibleTimeDBusAdaptor::openDefaultBible(const QString &key) { + qDebug() << "DBUS: open default bible ..."; + CSwordModuleInfo *module = CBTConfig::get(CBTConfig::standardBible); + if (module) + m_bibletime->createReadDisplayWindow(module, key); } void BibleTimeDBusAdaptor::closeAllModuleWindows() { + qDebug() << "DBUS: close all windows now ..."; m_bibletime->closeAllModuleWindows(); } QString BibleTimeDBusAdaptor::getCurrentReference() { + qDebug() << "DBUS: getCurrentReference ..."; return m_bibletime->getCurrentReference(); } -QStringList BibleTimeDBusAdaptor::searchInModule(const QString& moduleName, const QString& searchText) { +QStringList BibleTimeDBusAdaptor::searchInModule(const QString &moduleName, const QString &searchText) { + qDebug() << "DBUS: searchInModule" << moduleName.toLatin1() << " ..."; return m_bibletime->searchInModule(moduleName, searchText); } -QStringList BibleTimeDBusAdaptor::searchInOpenModules(const QString& searchText) { +QStringList BibleTimeDBusAdaptor::searchInOpenModules(const QString &searchText) { + qDebug() << "DBUS: search in open modules ..."; return m_bibletime->searchInOpenModules(searchText); } -QStringList BibleTimeDBusAdaptor::searchInDefaultBible(const QString& searchText) { - return m_bibletime->searchInDefaultBible(searchText); +QStringList BibleTimeDBusAdaptor::searchInDefaultBible(const QString &searchText) { + qDebug() << "DBUS: search in default bible ..."; + CSwordModuleInfo *bible = CBTConfig::get(CBTConfig::standardBible); + return m_bibletime->searchInModule(bible->name(), searchText); } -QStringList BibleTimeDBusAdaptor::getModulesOfType(const QString& type) { +QStringList BibleTimeDBusAdaptor::getModulesOfType(const QString &type) { + qDebug() << "DBUS: get modules of type ..."; return m_bibletime->getModulesOfType(type); } diff --git a/src/bibletime_dbus_adaptor.h b/src/bibletime_dbus_adaptor.h index 0f9f301..65c5c7b 100644 --- a/src/bibletime_dbus_adaptor.h +++ b/src/bibletime_dbus_adaptor.h @@ -21,87 +21,116 @@ #include <QStringList> -class BibleTimeDBusAdaptor : QDBusAbstractAdaptor { - Q_OBJECT - Q_CLASSINFO("D-Bus Interface", "info.bibletime.BibleTime") - - private: - BibleTime* m_bibletime; - - public: - BibleTimeDBusAdaptor(BibleTime *bibletime_ptr); - - public slots: - /** Sync all open Bible windows to the key. - * @param key The key which is set to all Bible windows. - */ - void syncAllBibles(const QString& key); - /** Sync all open commentary windows to the key. - * @param key The key which is set to all Commentary windows. - */ - void syncAllCommentaries(const QString& key); - /** Sync all open lexicon windows to the key. - * @param key The key which is set to all Lexicon windows. - */ - void syncAllLexicons(const QString& key); - /** Sync all open verse based (i.e. Bibles and commentaries) windows to the key. - * @param key The key which is set to all Bible and Commentary windows. - */ - void syncAllVerseBasedModules(const QString& key); - - /** Open a new read window for the module moduleName using the given key - * @param moduleName The name of the module which is opened in a new module window. - * @param key The key to set to the newly opened window. - */ - void openWindow(const QString& moduleName, const QString& key); - /** Open a new read window for the default Bible module using the given key - * @param key The key to set to the newly opened window. - */ - void openDefaultBible(const QString& key); - /** Close all open windows. - */ - void closeAllModuleWindows(); - /** Returns the reference used in the current window. - * The format of the returned reference is - * [Module] [Type] OSIS_Reference, - * wtih type one of BIBLE/COMMENTARY/BOOK/LEXICON/UNSUPPORTED - * If the type is BIBLE or COMMENTARY the reference is an OSIS ref - * in the other cases it's the key name, for books /Chapter/Subsection - * for Lexicons just the plain key, e.g. "ADAM". - * e.g. - * [KJV] [BIBLE] Gen.1.1 - * [MHC] [COMMENTARY] Gen.1.1 - * [ISBE] [LEXICON] REDEMPTION - * @return The reference displayed in the currently active module window. Empty if none is active. - */ - QString getCurrentReference(); - /** Search the searchText in the specified module. - * @param moduleName The module to search in - * @param searchText Search for this in the modules - * @return The search result. It's in the format [modulename] osis_ref_of_the_found_key. For example "[KJV] Gen.1.1". - */ - QStringList searchInModule(const QString& moduleName, const QString& searchText) ; - /** Search in all open modules and return the search result. - * The result is in the same format as searchInModule - * @param searchText Search for this in the modules - * @return The search result for a searchin all opened module windows - * @see searchInModule For the search result format. - */ - QStringList searchInOpenModules(const QString& searchText); - /** Search in the default Bible module and return the search result. - * The result is in the same format as searchInModule - * @param searchText Search for this in the modules - * @return The search result for a search in the default Bible - * @see searchInModule - */ - QStringList searchInDefaultBible(const QString& searchText); - /** Return a list of modules of the given type. - * @param type One of BIBLES, COMMENTARIES, LEXICONS, BOOKS - * @return The list of modules of the given type, may be empty - */ - QStringList getModulesOfType(const QString& type); -}; +class BibleTimeDBusAdaptor: QDBusAbstractAdaptor { -#endif + Q_OBJECT + Q_CLASSINFO("D-Bus Interface", "info.bibletime.BibleTime") + +public: /* Methods: */ + + BibleTimeDBusAdaptor(BibleTime *pBibleTime); + +public slots: + + /** + Sync all open Bible windows to the key. + \param[in] key The key which is set to all Bible windows. + */ + void syncAllBibles(const QString &key); + + /** + Sync all open commentary windows to the key. + \param[in] key The key which is set to all Commentary windows. + */ + void syncAllCommentaries(const QString &key); + + /** + Sync all open lexicon windows to the key. + \param[in] key The key which is set to all Lexicon windows. + */ + void syncAllLexicons(const QString &key); + + /** + Sync all open verse based (i.e. Bibles and commentaries) windows to the key. + \param key The key which is set to all Bible and Commentary windows. + */ + void syncAllVerseBasedModules(const QString &key); + + /** + Open a new read window for the module moduleName using the given key + \param[in] moduleName The name of the module which is opened in a new module window. + \param[in] key The key to set to the newly opened window. + */ + void openWindow(const QString &moduleName, const QString &key); + + /** + Open a new read window for the default Bible module using the given key + \param[in] key The key to set to the newly opened window. + */ + void openDefaultBible(const QString &key); + + /** + Close all open windows. + */ + void closeAllModuleWindows(); + + /** + Returns the reference used in the current window. + The format of the returned reference is + [Module] [Type] OSIS_Reference, + with type one of BIBLE/COMMENTARY/BOOK/LEXICON/UNSUPPORTED + If the type is BIBLE or COMMENTARY the reference is an OSIS ref + in the other cases it's the key name, for books /Chapter/Subsection + for Lexicons just the plain key, e.g. "ADAM". + e.g. + [KJV] [BIBLE] Gen.1.1 + [MHC] [COMMENTARY] Gen.1.1 + [ISBE] [LEXICON] REDEMPTION + \returns The reference displayed in the currently active module window. + Empty if none is active. + */ + QString getCurrentReference(); + + /** + Search the searchText in the specified module. + \param[in] moduleName The module to search in + \param[in] searchText Search for this in the modules + \returns The search result. It's in the format [modulename] + osis_ref_of_the_found_key. For example "[KJV] Gen.1.1". + */ + QStringList searchInModule(const QString &moduleName, const QString &searchText) ; + + /** + Search in all open modules and return the search result. + The result is in the same format as searchInModule + \param[in] searchText Search for this in the modules + \returns The search result for a searchin all opened module windows + \see searchInModule For the search result format. + */ + QStringList searchInOpenModules(const QString &searchText); + + /** + Search in the default Bible module and return the search result. + The result is in the same format as searchInModule + \param[in] searchText Search for this in the modules + \returns The search result for a search in the default Bible + \see searchInModule + */ + QStringList searchInDefaultBible(const QString &searchText); + + /** + Return a list of modules of the given type. + \param[in] type One of BIBLES, COMMENTARIES, LEXICONS, BOOKS + \returns The list of modules of the given type, may be empty + */ + QStringList getModulesOfType(const QString &type); + +private: /* Fields: */ + + BibleTime *m_bibletime; + +}; /* class BibleTimeDBusAdaptor */ + +#endif /* #ifdef NO_DBUS */ -#endif //NO_DBUS +#endif /* #ifdef BIBLETIME_DBUS_ADAPTOR_H */ diff --git a/src/bibletime_init.cpp b/src/bibletime_init.cpp index 4ac6350..df8fdea 100644 --- a/src/bibletime_init.cpp +++ b/src/bibletime_init.cpp @@ -32,8 +32,6 @@ #include "frontend/displaywindow/btactioncollection.h" #include "frontend/displaywindow/btmodulechooserbar.h" #include "frontend/bookmarks/cbookmarkindex.h" -#include "frontend/profile/cprofile.h" -#include "frontend/profile/cprofilemgr.h" #include "util/cresmgr.h" #include "util/directory.h" @@ -77,6 +75,9 @@ void BibleTime::initView() { m_magDock->setWidget(m_infoDisplay); addDockWidget(Qt::LeftDockWidgetArea, m_magDock); + connect(m_bookshelfDock, SIGNAL(moduleHovered(CSwordModuleInfo*)), + m_infoDisplay, SLOT(setInfo(CSwordModuleInfo*))); + m_mdi->setMinimumSize(100, 100); m_mdi->setFocusPolicy(Qt::ClickFocus); } @@ -353,61 +354,77 @@ void BibleTime::initActions() { this, SLOT(createReadDisplayWindow(CSwordModuleInfo*))); m_quitAction = m_actionCollection->action("quit"); + Q_ASSERT(m_quitAction != 0); connect(m_quitAction, SIGNAL(triggered()), this, SLOT(quit())); // View menu actions: m_windowFullscreenAction = m_actionCollection->action("toggleFullscreen"); + Q_ASSERT(m_windowFullscreenAction != 0); m_windowFullscreenAction->setCheckable(true); connect(m_windowFullscreenAction, SIGNAL(triggered()), this, SLOT(toggleFullscreen())); - m_viewToolbarAction = m_actionCollection->action("showToolbar"); - m_viewToolbarAction->setCheckable(true); - m_viewToolbarAction->setChecked(true); - connect(m_viewToolbarAction, SIGNAL(triggered()), - this, SLOT(slotToggleMainToolbar())); - // Special case these actions, overwrite those already in collection + namespace DU = util::directory; m_showBookshelfAction = m_bookshelfDock->toggleViewAction(); + m_showBookshelfAction->setIcon(DU::getIcon(CResMgr::mainMenu::view::showBookshelf::icon)); + m_showBookshelfAction->setToolTip(tr("Toggle visibility of the bookshelf window")); m_actionCollection->addAction("showBookshelf", m_showBookshelfAction); m_showBookmarksAction = m_bookmarksDock->toggleViewAction(); + m_showBookmarksAction->setIcon(DU::getIcon(CResMgr::mainMenu::view::showBookmarks::icon)); + m_showBookmarksAction->setToolTip(tr("Toggle visibility of the bookmarks window")); m_actionCollection->addAction("showBookmarks", m_showBookmarksAction); m_showMagAction = m_magDock->toggleViewAction(); + m_showMagAction->setIcon(DU::getIcon(CResMgr::mainMenu::view::showMag::icon)); + m_showMagAction->setToolTip(tr("Toggle visibility of the mag window")); m_actionCollection->addAction("showMag", m_showMagAction); m_showTextAreaHeadersAction = m_actionCollection->action("showParallelTextHeaders"); + Q_ASSERT(m_showTextAreaHeadersAction != 0); m_showTextAreaHeadersAction->setCheckable(true); m_showTextAreaHeadersAction->setChecked(CBTConfig::get(CBTConfig::showTextWindowHeaders)); connect(m_showTextAreaHeadersAction, SIGNAL(toggled(bool)), this, SLOT(slotToggleTextWindowHeader())); + m_showMainWindowToolbarAction = m_actionCollection->action("showToolbar"); + Q_ASSERT(m_showMainWindowToolbarAction != 0); + m_showMainWindowToolbarAction->setCheckable(true); + m_showMainWindowToolbarAction->setChecked(CBTConfig::get(CBTConfig::showMainWindowToolbar)); + connect( m_showMainWindowToolbarAction, SIGNAL(triggered()), + this, SLOT(slotToggleMainToolbar())); + m_showTextWindowNavigationAction = m_actionCollection->action("showNavigation"); + Q_ASSERT(m_showTextWindowNavigationAction != 0); m_showTextWindowNavigationAction->setCheckable(true); m_showTextWindowNavigationAction->setChecked(CBTConfig::get(CBTConfig::showTextWindowNavigator)); connect(m_showTextWindowNavigationAction, SIGNAL(toggled(bool)), this, SLOT(slotToggleNavigatorToolbar())); m_showTextWindowModuleChooserAction = m_actionCollection->action("showWorks"); + Q_ASSERT(m_showTextWindowModuleChooserAction != 0); m_showTextWindowModuleChooserAction->setCheckable(true); m_showTextWindowModuleChooserAction->setChecked(CBTConfig::get(CBTConfig::showTextWindowModuleSelectorButtons)); connect(m_showTextWindowModuleChooserAction, SIGNAL(toggled(bool)), this, SLOT(slotToggleWorksToolbar())); m_showTextWindowToolButtonsAction = m_actionCollection->action("showTools"); + Q_ASSERT(m_showTextWindowToolButtonsAction != 0); m_showTextWindowToolButtonsAction->setCheckable(true); m_showTextWindowToolButtonsAction->setChecked(CBTConfig::get(CBTConfig::showTextWindowToolButtons)); connect(m_showTextWindowToolButtonsAction, SIGNAL(toggled(bool)), this, SLOT(slotToggleToolsToolbar())); m_showFormatToolbarAction = m_actionCollection->action("showFormat"); + Q_ASSERT(m_showFormatToolbarAction != 0); m_showFormatToolbarAction->setCheckable(true); m_showFormatToolbarAction->setChecked(CBTConfig::get(CBTConfig::showFormatToolbarButtons)); bool ok = connect(m_showFormatToolbarAction, SIGNAL(toggled(bool)), this, SLOT(slotToggleFormatToolbar())); m_toolbarsInEachWindow = m_actionCollection->action("showToolbarsInTextWindows"); + Q_ASSERT(m_toolbarsInEachWindow != 0); m_toolbarsInEachWindow->setCheckable(true); m_toolbarsInEachWindow->setChecked(CBTConfig::get(CBTConfig::showToolbarsInEachWindow)); ok = connect(m_toolbarsInEachWindow, SIGNAL(toggled(bool)), @@ -416,95 +433,154 @@ void BibleTime::initActions() { // Search menu actions: m_searchOpenWorksAction = m_actionCollection->action("searchOpenWorks"); + Q_ASSERT(m_searchOpenWorksAction != 0); connect(m_searchOpenWorksAction, SIGNAL(triggered()), this, SLOT(slotSearchModules())); m_searchStandardBibleAction = m_actionCollection->action("searchStdBible"); + Q_ASSERT(m_searchStandardBibleAction != 0); connect(m_searchStandardBibleAction, SIGNAL(triggered()), this, SLOT(slotSearchDefaultBible())); // Window menu actions: m_windowCloseAction = m_actionCollection->action("closeWindow"); + Q_ASSERT(m_windowCloseAction != 0); connect(m_windowCloseAction, SIGNAL(triggered()), m_mdi, SLOT(closeActiveSubWindow())); m_windowCloseAllAction = m_actionCollection->action("closeAllWindows"); + Q_ASSERT(m_windowCloseAllAction != 0); connect(m_windowCloseAllAction, SIGNAL(triggered()), m_mdi, SLOT(closeAllSubWindows())); m_windowCascadeAction = m_actionCollection->action("cascade"); + Q_ASSERT(m_windowCascadeAction != 0); connect(m_windowCascadeAction, SIGNAL(triggered()), this, SLOT(slotCascade())); m_windowTileAction = m_actionCollection->action("tile"); + Q_ASSERT(m_windowTileAction != 0); connect(m_windowTileAction, SIGNAL(triggered()), this, SLOT(slotTile())); m_windowTileVerticalAction = m_actionCollection->action("tileVertically"); + Q_ASSERT(m_windowTileVerticalAction != 0); connect(m_windowTileVerticalAction, SIGNAL(triggered()), this, SLOT(slotTileVertical())); m_windowTileHorizontalAction = m_actionCollection->action("tileHorizontally"); + Q_ASSERT(m_windowTileHorizontalAction != 0); connect(m_windowTileHorizontalAction, SIGNAL(triggered()), this, SLOT(slotTileHorizontal())); m_windowManualModeAction = m_actionCollection->action("manualArrangement"); + Q_ASSERT(m_windowManualModeAction != 0); m_windowManualModeAction->setCheckable(true); + m_windowManualModeAction->setChecked(true); connect(m_windowManualModeAction, SIGNAL(triggered()), this, SLOT(slotManualArrangementMode())); m_windowAutoTabbedAction = m_actionCollection->action("autoTabbed"); + Q_ASSERT(m_windowAutoTabbedAction != 0); m_windowAutoTabbedAction->setCheckable(true); + if(CBTConfig::get(CBTConfig::autoTabbed) == true) { + m_windowManualModeAction->setChecked(false); + m_windowAutoTabbedAction->setChecked(true); + } connect(m_windowAutoTabbedAction, SIGNAL(triggered()), this, SLOT(slotAutoTabbed())); //: Vertical tiling means that windows are vertical, placed side by side m_windowAutoTileVerticalAction = m_actionCollection->action("autoVertical"); + Q_ASSERT(m_windowAutoTileVerticalAction != 0); m_windowAutoTileVerticalAction->setCheckable(true); + if(CBTConfig::get(CBTConfig::autoTileVertical) == true) { + m_windowManualModeAction->setChecked(false); + m_windowAutoTileVerticalAction->setChecked(true); + } connect(m_windowAutoTileVerticalAction, SIGNAL(triggered()), this, SLOT(slotAutoTileVertical())); //: Horizontal tiling means that windows are horizontal, placed on top of each other m_windowAutoTileHorizontalAction = m_actionCollection->action("autoHorizontal"); + Q_ASSERT(m_windowAutoTileHorizontalAction != 0); m_windowAutoTileHorizontalAction->setCheckable(true); + if(CBTConfig::get(CBTConfig::autoTileHorizontal) == true) { + m_windowManualModeAction->setChecked(false); + m_windowAutoTileHorizontalAction->setChecked(true); + } connect(m_windowAutoTileHorizontalAction, SIGNAL(triggered()), this, SLOT(slotAutoTileHorizontal())); m_windowAutoTileAction = m_actionCollection->action("autoTile"); + Q_ASSERT(m_windowAutoTileAction != 0); m_windowAutoTileAction->setCheckable(true); + if(CBTConfig::get(CBTConfig::autoTile) == true) { + m_windowManualModeAction->setChecked(false); + m_windowAutoTileAction->setChecked(true); + } connect(m_windowAutoTileAction, SIGNAL(triggered()), this, SLOT(slotAutoTile())); m_windowAutoCascadeAction = m_actionCollection->action("autoCascade"); + Q_ASSERT(m_windowAutoCascadeAction != 0); m_windowAutoCascadeAction->setCheckable(true); + if(CBTConfig::get(CBTConfig::autoCascade) == true) { + m_windowManualModeAction->setChecked(false); + m_windowAutoCascadeAction->setChecked(true); + } connect(m_windowAutoCascadeAction, SIGNAL(triggered()), this, SLOT(slotAutoCascade())); + /* + * All actions related to arrangement modes have to be initialized before calling a slot on them, + * thus we call them afterwards now. + */ + if(m_windowAutoTabbedAction->isChecked() == true) + slotAutoTabbed(); + else if(m_windowAutoTileVerticalAction->isChecked() == true) + slotAutoTileVertical(); + else if(m_windowAutoTileHorizontalAction->isChecked() == true) + slotAutoTileHorizontal(); + else if(m_windowAutoTileAction->isChecked() == true) + slotAutoTile(); + else if(m_windowAutoCascadeAction->isChecked() == true) + slotAutoCascade(); + else + slotManualArrangementMode(); + m_windowSaveToNewProfileAction = m_actionCollection->action("saveNewSession"); + Q_ASSERT(m_windowSaveToNewProfileAction != 0); connect(m_windowSaveToNewProfileAction, SIGNAL(triggered()), this, SLOT(saveToNewProfile())); m_setPreferencesAction = m_actionCollection->action("setPreferences"); + Q_ASSERT(m_setPreferencesAction != 0); connect(m_setPreferencesAction, SIGNAL(triggered()), this, SLOT(slotSettingsOptions())); m_bookshelfManagerAction = m_actionCollection->action("bookshelfManager"); + Q_ASSERT(m_bookshelfManagerAction != 0); connect(m_bookshelfManagerAction, SIGNAL(triggered()), this, SLOT(slotSwordSetupDialog())); m_openHandbookAction = m_actionCollection->action("openHandbook"); + Q_ASSERT(m_openHandbookAction != 0); connect(m_openHandbookAction, SIGNAL(triggered()), this, SLOT(openOnlineHelp_Handbook())); m_bibleStudyHowtoAction = m_actionCollection->action("bibleStudyHowto"); + Q_ASSERT(m_bibleStudyHowtoAction != 0); connect(m_bibleStudyHowtoAction, SIGNAL(triggered()), this, SLOT(openOnlineHelp_Howto())); m_aboutBibleTimeAction = m_actionCollection->action("aboutBibleTime"); + Q_ASSERT(m_aboutBibleTimeAction != 0); connect(m_aboutBibleTimeAction, SIGNAL(triggered()), this, SLOT(slotOpenAboutDialog()) ); m_tipOfTheDayAction = m_actionCollection->action("tipOfTheDay"); + Q_ASSERT(m_tipOfTheDayAction != 0); connect(m_tipOfTheDayAction, SIGNAL(triggered()), this, SLOT(slotOpenTipDialog()) ); @@ -535,7 +611,7 @@ void BibleTime::initMenubar() { m_viewMenu->addAction(m_showTextAreaHeadersAction); m_viewMenu->addSeparator(); m_toolBarsMenu = new QMenu(this); - m_toolBarsMenu->addAction(m_viewToolbarAction); + m_toolBarsMenu->addAction( m_showMainWindowToolbarAction); m_toolBarsMenu->addAction(m_showTextWindowNavigationAction); m_toolBarsMenu->addAction(m_showTextWindowModuleChooserAction); m_toolBarsMenu->addAction(m_showTextWindowToolButtonsAction); @@ -618,11 +694,17 @@ void BibleTime::initToolbars() { openWorkButton->setPopupMode(QToolButton::InstantPopup); m_mainToolBar->addWidget(openWorkButton); - m_mainToolBar->addSeparator(); m_mainToolBar->addAction(m_windowFullscreenAction); - m_mainToolBar->addSeparator(); + QAction *a = m_actionCollection->action("showBookshelf"); + Q_ASSERT(a != 0); + m_mainToolBar->addAction(a); + a = m_actionCollection->action("showBookmarks"); + Q_ASSERT(a != 0); + m_mainToolBar->addAction(a); + a = m_actionCollection->action("showMag"); + Q_ASSERT(a != 0); + m_mainToolBar->addAction(a); m_mainToolBar->addAction(m_searchOpenWorksAction); - m_mainToolBar->addSeparator(); m_mainToolBar->addAction(m_openHandbookAction); } @@ -662,16 +744,36 @@ void BibleTime::retranslateUi() { * The second is used during the use of the configuration shortcut editor */ void BibleTime::retranslateUiActions(BtActionCollection* ac) { - ac->action("showToolbarsInTextWindows")->setText(tr("Show toolbars in text windows")); - ac->action("showToolbar")->setText(tr("Show main toolbar")); - ac->action("showNavigation")->setText(tr("Show navigation bar")); - ac->action("showWorks")->setText(tr("Show works toolbar")); - ac->action("showTools")->setText(tr("Show tools toolbar")); - ac->action("showFormat")->setText(tr("Show formatting toolbar")); - ac->action("showBookshelf")->setText(tr("Show bookshelf")); - ac->action("showBookmarks")->setText(tr("Show bookmarks")); - ac->action("showMag")->setText(tr("Show mag")); - ac->action("showParallelTextHeaders")->setText(tr("Show parallel text headers")); + QAction *a = ac->action("showToolbarsInTextWindows"); + Q_ASSERT(a != 0); + a->setText(tr("Show toolbars in text windows")); + a = ac->action("showToolbar"); + Q_ASSERT(a != 0); + a->setText(tr("Show main toolbar")); + a = ac->action("showNavigation"); + Q_ASSERT(a != 0); + a->setText(tr("Show navigation bar")); + a = ac->action("showWorks"); + Q_ASSERT(a != 0); + a->setText(tr("Show works toolbar")); + a = ac->action("showTools"); + Q_ASSERT(a != 0); + a->setText(tr("Show tools toolbar")); + a = ac->action("showFormat"); + Q_ASSERT(a != 0); + a->setText(tr("Show formatting toolbar")); + a = ac->action("showBookshelf"); + Q_ASSERT(a != 0); + a->setText(tr("Show bookshelf")); + a = ac->action("showBookmarks"); + Q_ASSERT(a != 0); + a->setText(tr("Show bookmarks")); + a = ac->action("showMag"); + Q_ASSERT(a != 0); + a->setText(tr("Show mag")); + a = ac->action("showParallelTextHeaders"); + Q_ASSERT(a != 0); + a->setText(tr("Show parallel text headers")); } /** Initializes the SIGNAL / SLOT connections */ @@ -740,8 +842,6 @@ void BibleTime::initSwordConfigFile() { /** Initializes the backend */ void BibleTime::initBackends() { - qDebug() << "BibleTime::initBackends"; - initSwordConfigFile(); sword::StringMgr::setSystemStringMgr( new BTStringMgr() ); @@ -807,7 +907,6 @@ void BibleTime::initBackends() { } void BibleTime::applyProfileSettings( CProfile* p ) { - qDebug() << "BibleTime::applyProfileSettings"; Q_ASSERT(p); if (!p) return; diff --git a/src/bibletime_slots.cpp b/src/bibletime_slots.cpp index 9fdab62..05729bf 100644 --- a/src/bibletime_slots.cpp +++ b/src/bibletime_slots.cpp @@ -12,6 +12,7 @@ #include <QAction> #include <QApplication> #include <QClipboard> +#include <QDebug> #include <QDesktopServices> #include <QInputDialog> #include <QList> @@ -29,9 +30,6 @@ #include "frontend/bookshelfmanager/btmodulemanagerdialog.h" #include "frontend/displaywindow/btmodulechooserbar.h" #include "frontend/displaywindow/cdisplaywindow.h" -#include "frontend/profile/cprofilemgr.h" -#include "frontend/profile/cprofile.h" -#include "frontend/profile/cprofilewindow.h" #include "frontend/searchdialog/csearchdialog.h" #include "frontend/settingsdialogs/cconfigurationdialog.h" #include "frontend/tips/bttipdialog.h" @@ -89,7 +87,7 @@ void BibleTime::slotSwordSetupDialog() { dlg->activateWindow(); } -/** Is called just before the window menu is ahown. */ +/** Is called just before the window menu is shown. */ void BibleTime::slotWindowMenuAboutToShow() { Q_ASSERT(m_windowMenu); @@ -118,13 +116,13 @@ void BibleTime::slotWindowMenuAboutToShow() { } } -/** Is called just before the open windows menu is ahown. */ +/** Is called just before the open windows menu is shown. */ void BibleTime::slotOpenWindowsMenuAboutToShow() { Q_ASSERT(m_openWindowsMenu); QList<QMdiSubWindow*> windows = m_mdi->usableWindowList(); m_openWindowsMenu->clear(); - foreach (QMdiSubWindow *window, windows) { + Q_FOREACH (QMdiSubWindow * const window, windows) { QAction *openWindowAction = m_openWindowsMenu->addAction(window->windowTitle()); openWindowAction->setCheckable(true); openWindowAction->setChecked(window == m_mdi->activeSubWindow()); @@ -166,6 +164,11 @@ void BibleTime::slotUpdateWindowArrangementActions( QAction* clickedAction ) { m_windowAutoTabbedAction->setChecked(false); m_mdi->enableWindowMinMaxFlags(true); m_mdi->setMDIArrangementMode( CMDIArea::ArrangementModeManual ); + CBTConfig::set(CBTConfig::autoTileVertical, false); + CBTConfig::set(CBTConfig::autoTileHorizontal, false); + CBTConfig::set(CBTConfig::autoTile, false); + CBTConfig::set(CBTConfig::autoTabbed, false); + CBTConfig::set(CBTConfig::autoCascade, false); } else if (clickedAction == m_windowAutoTileVerticalAction) { m_windowManualModeAction->setChecked(false); @@ -175,6 +178,7 @@ void BibleTime::slotUpdateWindowArrangementActions( QAction* clickedAction ) { m_windowAutoTabbedAction->setChecked(false); m_mdi->enableWindowMinMaxFlags(false); m_mdi->setMDIArrangementMode( CMDIArea::ArrangementModeTileVertical ); + CBTConfig::set(CBTConfig::autoTileVertical, true); } else if (clickedAction == m_windowAutoTileHorizontalAction) { m_windowManualModeAction->setChecked(false); @@ -184,6 +188,7 @@ void BibleTime::slotUpdateWindowArrangementActions( QAction* clickedAction ) { m_windowAutoTabbedAction->setChecked(false); m_mdi->enableWindowMinMaxFlags(false); m_mdi->setMDIArrangementMode( CMDIArea::ArrangementModeTileHorizontal ); + CBTConfig::set(CBTConfig::autoTileHorizontal, true); } else if (clickedAction == m_windowAutoTileAction) { m_windowManualModeAction->setChecked(false); @@ -193,6 +198,7 @@ void BibleTime::slotUpdateWindowArrangementActions( QAction* clickedAction ) { m_windowAutoCascadeAction->setChecked(false); m_mdi->enableWindowMinMaxFlags(false); m_mdi->setMDIArrangementMode( CMDIArea::ArrangementModeTile ); + CBTConfig::set(CBTConfig::autoTile, true); } else if (clickedAction == m_windowAutoTabbedAction) { m_windowManualModeAction->setChecked(false); @@ -202,6 +208,7 @@ void BibleTime::slotUpdateWindowArrangementActions( QAction* clickedAction ) { m_windowAutoCascadeAction->setChecked(false); m_mdi->enableWindowMinMaxFlags(false); m_mdi->setMDIArrangementMode( CMDIArea::ArrangementModeTabbed ); + CBTConfig::set(CBTConfig::autoTabbed, true); } else if (clickedAction == m_windowAutoCascadeAction) { m_windowManualModeAction->setChecked(false); @@ -211,6 +218,7 @@ void BibleTime::slotUpdateWindowArrangementActions( QAction* clickedAction ) { m_windowAutoTabbedAction->setChecked(false); m_mdi->enableWindowMinMaxFlags(false); m_mdi->setMDIArrangementMode( CMDIArea::ArrangementModeCascade ); + CBTConfig::set(CBTConfig::autoCascade, true); } else if (clickedAction == m_windowTileAction) { m_mdi->setMDIArrangementMode( CMDIArea::ArrangementModeManual ); @@ -278,7 +286,9 @@ void BibleTime::slotAutoCascade() { /** Shows/hides the toolbar */ void BibleTime::slotToggleMainToolbar() { Q_ASSERT(m_mainToolBar); - if (m_viewToolbarAction->isChecked()) { + bool currentState = CBTConfig::get(CBTConfig::showMainWindowToolbar); + CBTConfig::set(CBTConfig::showMainWindowToolbar, !currentState); + if ( m_showMainWindowToolbarAction->isChecked()) { m_mainToolBar->show(); } else { @@ -379,8 +389,9 @@ void BibleTime::slotSearchModules() { //get the modules of the open windows QList<const CSwordModuleInfo*> modules; - foreach(QMdiSubWindow* subWindow, m_mdi->subWindowList()) { - if (CDisplayWindow* w = dynamic_cast<CDisplayWindow*>(subWindow->widget())) { + Q_FOREACH (const QMdiSubWindow * const subWindow, m_mdi->subWindowList()) { + const CDisplayWindow * const w = dynamic_cast<CDisplayWindow*>(subWindow->widget()); + if (w != 0) { modules << w->modules(); } } @@ -423,9 +434,9 @@ void BibleTime::slotOpenTipDialog() { void BibleTime::saveProfile(QAction* action) { m_mdi->setUpdatesEnabled(false); - const QString profileName = action->text().remove("&"); - CProfile* p = m_profileMgr.profile( profileName ); + CProfile * p = (CProfile *) action->property("CProfilePointer").value<void *>(); Q_ASSERT(p); + Q_ASSERT(p == m_profileMgr.profile(action->text().remove("&"))); if ( p ) { saveProfile(p); } @@ -441,13 +452,13 @@ void BibleTime::saveProfile(CProfile* profile) { storeProfileSettings(profile); QList<CProfileWindow*> profileWindows; - foreach (QMdiSubWindow* w, m_mdi->subWindowList(QMdiArea::StackingOrder)) { - CDisplayWindow* displayWindow = dynamic_cast<CDisplayWindow*>(w->widget()); - if (!displayWindow) { + Q_FOREACH (const QMdiSubWindow * const w, m_mdi->subWindowList(QMdiArea::StackingOrder)) { + CDisplayWindow * const displayWindow = dynamic_cast<CDisplayWindow*>(w->widget()); + if (displayWindow == 0) { continue; } - CProfileWindow* profileWindow = new CProfileWindow(); + CProfileWindow * const profileWindow = new CProfileWindow(); displayWindow->storeProfileSettings(profileWindow); profileWindows.append(profileWindow); } @@ -460,9 +471,9 @@ void BibleTime::saveProfile(CProfile* profile) { } void BibleTime::loadProfile(QAction* action) { - const QString profileName = action->text().remove("&"); - CProfile* p = m_profileMgr.profile( profileName ); + CProfile * p = (CProfile *) action->property("CProfilePointer").value<void *>(); Q_ASSERT(p); + Q_ASSERT(p == m_profileMgr.profile(action->text().remove("&"))); if ( p ) { m_mdi->closeAllSubWindows(); loadProfile(p); @@ -483,31 +494,31 @@ void BibleTime::loadProfile(CProfile* p) { QWidget* focusWindow = 0; // for (CProfileWindow* w = windows.last(); w; w = windows.prev()) { //from the last one to make sure the order is right in the mdi area - foreach (CProfileWindow* w, windows) { - const QString key = w->key(); - QStringList usedModules = w->modules(); + Q_FOREACH (CProfileWindow * w, windows) { + const QString &key = w->key; QList<CSwordModuleInfo*> modules; - for ( QStringList::Iterator it = usedModules.begin(); it != usedModules.end(); ++it ) { - if (CSwordModuleInfo* m = CSwordBackend::instance()->findModuleByName(*it)) { + Q_FOREACH (const QString &moduleName, w->modules) { + CSwordModuleInfo * const m = CSwordBackend::instance()->findModuleByName(moduleName); + if (m != 0) { modules.append(m); } } - if (!modules.count()) { //are the modules still installed? If not continue wih next session window + if (modules.isEmpty()) { //are the modules still installed? If not continue wih next session window continue; } //is w->isWriteWindow is false we create a write window, otherwise a read window CDisplayWindow* displayWindow = 0; - if (w->writeWindowType() > 0) { //create a write window - displayWindow = createWriteDisplayWindow(modules.first(), key, CWriteWindow::WriteWindowType(w->writeWindowType()) ); + if (w->writeWindowType > 0) { //create a write window + displayWindow = createWriteDisplayWindow(modules.first(), key, CWriteWindow::WriteWindowType(w->writeWindowType) ); } else { //create a read window displayWindow = createReadDisplayWindow(modules, key); } if (displayWindow) { //if a window was created initialize it. - if (w->hasFocus()) { + if (w->hasFocus) { focusWindow = displayWindow; } @@ -525,28 +536,16 @@ void BibleTime::loadProfile(CProfile* p) { void BibleTime::deleteProfile(QAction* action) { //HACK: work around the inserted & char by KPopupMenu - const QString profileName = action->text().remove("&"); - CProfile* p = m_profileMgr.profile( profileName ); + CProfile * p = (CProfile *) action->property("CProfilePointer").value<void *>(); Q_ASSERT(p); - if ( p ) m_profileMgr.remove(p); + Q_ASSERT(p == m_profileMgr.profile(action->text().remove("&"))); + if (p) + m_profileMgr.remove(p); refreshProfileMenus(); } void BibleTime::toggleFullscreen() { - if (m_windowFullscreenAction->isChecked()) { - // set full screen mode - m_WindowWasMaximizedBeforeFullScreen = isMaximized(); - showFullScreen(); - } - else { - // restore previous non-full screen mode - if (m_WindowWasMaximizedBeforeFullScreen) { - showMaximized(); - } - else { - showNormal(); - } - } + setWindowState(windowState() ^ Qt::WindowFullScreen); m_mdi->triggerWindowUpdate(); } @@ -570,17 +569,22 @@ void BibleTime::refreshProfileMenus() { //refresh the load, save and delete profile menus m_profileMgr.refresh(); - QList<CProfile*> profiles = m_profileMgr.profiles(); + const QList<CProfile*> profiles = m_profileMgr.profiles(); - const bool enableActions = bool(profiles.count() != 0); + const bool enableActions = !profiles.isEmpty(); m_windowSaveProfileMenu->setEnabled(enableActions); m_windowLoadProfileMenu->setEnabled(enableActions); m_windowDeleteProfileMenu->setEnabled(enableActions); - foreach (CProfile* p, profiles) { - m_windowSaveProfileMenu->addAction(p->name()); - m_windowLoadProfileMenu->addAction(p->name()); - m_windowDeleteProfileMenu->addAction(p->name()); + Q_FOREACH (const CProfile * const p, profiles) { + const QString &profileName = p->name(); + QAction * a; + a = m_windowSaveProfileMenu->addAction(profileName); + a->setProperty("CProfilePointer", QVariant::fromValue((void *) p)); + a = m_windowLoadProfileMenu->addAction(profileName); + a->setProperty("CProfilePointer", QVariant::fromValue((void *) p)); + a = m_windowDeleteProfileMenu->addAction(profileName); + a->setProperty("CProfilePointer", QVariant::fromValue((void *) p)); } } diff --git a/src/bibletimeapp.cpp b/src/bibletimeapp.cpp index 8521f2a..f73d501 100644 --- a/src/bibletimeapp.cpp +++ b/src/bibletimeapp.cpp @@ -17,7 +17,8 @@ BibleTimeApp::~BibleTimeApp() { // Prevent writing to the log file before the directory cache is init: - if (!m_init) return; + if (!m_init) + return; //we can set this safely now because we close now (hopyfully without crash) CBTConfig::set(CBTConfig::crashedLastTime, false); @@ -31,7 +32,8 @@ BibleTimeApp::~BibleTimeApp() { bool BibleTimeApp::initDisplayTemplateManager() { QString errorMessage; new CDisplayTemplateMgr(errorMessage); - if (errorMessage.isNull()) return true; + if (errorMessage.isNull()) + return true; QMessageBox::critical(0, tr("Fatal error!"), errorMessage); return false; } diff --git a/src/btglobal.cpp b/src/btglobal.cpp new file mode 100644 index 0000000..53c274c --- /dev/null +++ b/src/btglobal.cpp @@ -0,0 +1,16 @@ +#include "btglobal.h" + +#include <QDataStream> + + +QDataStream &operator<<(QDataStream &out, const alignmentMode &mode) { + out << (qint8) mode; + return out; +} + +QDataStream &operator>>(QDataStream &in, alignmentMode &mode) { + qint8 i; + in >> i; + mode = (alignmentMode) i; + return in; +} diff --git a/src/btglobal.h b/src/btglobal.h index 9fa97fe..1b584e8 100644 --- a/src/btglobal.h +++ b/src/btglobal.h @@ -10,6 +10,12 @@ #ifndef BTGLOBAL_H #define BTGLOBAL_H +#include <QMetaType> + + +class QDataStream; + + /** Filter options to control the text display of modules. Uses int and not bool because not all options have just two toggle values. @@ -50,4 +56,20 @@ struct DisplayOptions { }; Q_DECLARE_METATYPE(DisplayOptions) +/*! + * Enumeration indicating the alignment mode + * used for child windows. + */ +enum alignmentMode { /* Values provided for serialization */ + autoTileVertical = 0, + autoTileHorizontal = 1, + autoTile = 2, + autoTabbed = 3, + autoCascade = 4, + manual = 5 +}; +QDataStream &operator<<(QDataStream &out, const alignmentMode &mode); +QDataStream &operator>>(QDataStream &in, alignmentMode &mode); +Q_DECLARE_METATYPE(alignmentMode) + #endif // BTGLOBAL_H diff --git a/src/display-templates/Basic.tmpl b/src/display-templates/Basic.tmpl new file mode 100644 index 0000000..c707b50 --- /dev/null +++ b/src/display-templates/Basic.tmpl @@ -0,0 +1,26 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> +<html xmlns="http://www.w3.org/1999/xhtml"> +<head> + <title>#TITLE#</title> + <meta name="GENERATOR" content="BibleTime - www.bibletime.info" /> + <meta name="AUTHOR" content="BibleTime - www.bibletime.info" /> + <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> + <!-- Link to the application default stylesheet --> + <link rel="stylesheet" type="text/css" href="#THEME_STYLE#" /> + <!-- Link to module stylesheet, if applicable --> + #MODULE_STYLESHEET# + + <style type="text/css"> + /* <![CDATA[ */ +#LANG_CSS# + + + /* ]]> */ + </style> +</head> + +<body id="#DISPLAYTYPE#" class="#MODTYPE# #MODTYPE#_#MODNAME#"> + <div id="content" lang="#LANG_ABBREV#" xml:lang="#LANG_ABBREV#" dir="#PAGE_DIRECTION#">#CONTENT#</div> +</body> +</html> diff --git a/src/display-templates/Blue.tmpl b/src/display-templates/Blue.css index 66b7567..229289c 100644 --- a/src/display-templates/Blue.tmpl +++ b/src/display-templates/Blue.css @@ -1,16 +1,6 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> -<html xmlns="http://www.w3.org/1999/xhtml"> -<head> - <title>#TITLE#</title> - <meta name="GENERATOR" content="BibleTime - www.bibletime.info" /> - <meta name="AUTHOR" content="BibleTime - www.bibletime.info" /> - <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> - - <style type="text/css"> - /* <![CDATA[ */ -#LANG_CSS# - +/** + * Theme by BibleTime - www.bibletime.info * + */ body { background-color: white; color: black; @@ -278,7 +268,7 @@ td.entry + td.entry { padding:0; } -#infodisplay .footnoteinfo h3, #infodisplay .strongsinfo h3, #infodisplay .morphinfo h3, #infodisplay .translationinfo h3, #infodisplay .crossrefinfo h3 { +#infodisplay .footnoteinfo h3, #infodisplay .strongsinfo h3, #infodisplay .morphinfo h3, #infodisplay .translationinfo h3, #infodisplay .crossrefinfo h3, #infodisplay .moduleinfo h3 { padding:4px 4px 2px 0; color:darkGray; font-weight:bold; @@ -328,12 +318,3 @@ td.entry + td.entry { border-bottom:1px solid black; color:black; } - - /* ]]> */ - </style> -</head> - -<body id="#DISPLAYTYPE#"> - <div id="content" lang="#LANG_ABBREV#" xml:lang="#LANG_ABBREV#" dir="#PAGE_DIRECTION#">#CONTENT#</div> -</body> -</html>
\ No newline at end of file diff --git a/src/display-templates/Christmastide.tmpl b/src/display-templates/Christmastide.css index 6c4c9ea..e12385b 100644 --- a/src/display-templates/Christmastide.tmpl +++ b/src/display-templates/Christmastide.css @@ -1,14 +1,6 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> -<html xmlns="http://www.w3.org/1999/xhtml"> -<head> - <title>Christmastide</title> - <meta name="GENERATOR" content="BibleTime " VERSION "0.1" /> - <meta name="AUTHOR" content="BibleTime " VERSION "tabthorpe@FreeBSD.org" /> - <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> - - <style type="text/css"> -/* <![CDATA[ */ +/** + * Theme by tabthorpe@FreeBSD.org * + */ body { background-color: #FDF5E6; /* OldeLaceWhite */ color: #006400; /* # DarkGreen */ @@ -139,13 +131,3 @@ div.currententry { .italic { font-style: italic; } - -#LANG_CSS# -/* ]]> */ - </style> -</head> - -<body> - <div id="content" lang="#LANG_ABBREV#" xml:lang="#LANG_ABBREV#" dir="#PAGE_DIRECTION#">#CONTENT#</div> -</body> -</html> diff --git a/src/display-templates/Crazy.tmpl b/src/display-templates/Crazy.css index b21527a..94e9646 100644 --- a/src/display-templates/Crazy.tmpl +++ b/src/display-templates/Crazy.css @@ -1,15 +1,6 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> -<html xmlns="http://www.w3.org/1999/xhtml"> -<head> - <!--TODO: This needs a better title than "Crazy"--> - <title>#TITLE#</title> - <meta name="GENERATOR" content="BibleTime - www.bibletime.info" /> - <meta name="AUTHOR" content="BibleTime - www.bibletime.info" /> - <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> - - <style type="text/css"> -/* <![CDATA[ */ +/** + * Theme by BibleTime - www.bibletime.info * + */ body { background-color: white; color: black; @@ -278,7 +269,8 @@ so something like .alternative:before { content:"'"attr(alternative); } is possi #infodisplay .strongsinfo h3, #infodisplay .morphinfo h3, #infodisplay .translationinfo h3, -#infodisplay .crossrefinfo h3 { +#infodisplay .crossrefinfo h3, +#infodisplay .moduleinfo h3 { font-size:12pt; font-weight:bold; text-transform:uppercase; @@ -306,16 +298,3 @@ so something like .alternative:before { content:"'"attr(alternative); } is possi #printer .rangeheading {} *[dir=rtl] { text-align:right !important; } - -/* Here's the marker for the language specific fotn information. BibleTime replaces this by the CSS for the fonts */ -#LANG_CSS# - -/* ]]> */ - </style> -</head> - -<!-- The display type may be bible, book, printer --> -<body id="#DISPLAYTYPE#"> - <div id="content" lang="#LANG_ABBREV#" xml:lang="#LANG_ABBREV#" dir="#PAGE_DIRECTION#">#CONTENT#</div> -</body> -</html>
\ No newline at end of file diff --git a/src/display-templates/Green.tmpl b/src/display-templates/Green.css index 033bcb2..cd9e68b 100644 --- a/src/display-templates/Green.tmpl +++ b/src/display-templates/Green.css @@ -1,15 +1,6 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> -<html xmlns="http://www.w3.org/1999/xhtml"> -<head> - <title>#TITLE#</title> - <meta name="GENERATOR" content="BibleTime - www.bibletime.info" /> - <meta name="AUTHOR" content="BibleTime - www.bibletime.info" /> - <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> - - <style type="text/css"> - /* <![CDATA[ */ - +/** + * Theme by BibleTime - www.bibletime.info * + */ body { background-color: white; color: black; @@ -265,7 +256,7 @@ td.entry + td.entry { padding:0; } -#infodisplay .footnoteinfo h3, #infodisplay .strongsinfo h3, #infodisplay .morphinfo h3, #infodisplay .translationinfo h3, #infodisplay .crossrefinfo h3 { +#infodisplay .footnoteinfo h3, #infodisplay .strongsinfo h3, #infodisplay .morphinfo h3, #infodisplay .translationinfo h3, #infodisplay .crossrefinfo h3, #infodisplay .moduleinfo h3 { padding:4px 4px 2px 0; color:darkGray; font-weight:bold; @@ -307,14 +298,3 @@ td.entry + td.entry { border-bottom:1px solid black; color:black; } - -#LANG_CSS# - - /* ]]> */ - </style> -</head> - -<body id="#DISPLAYTYPE#"> - <div id="content" lang="#LANG_ABBREV#" xml:lang="#LANG_ABBREV#" dir="#PAGE_DIRECTION#">#CONTENT#</div> -</body> -</html>
\ No newline at end of file diff --git a/src/display-templates/HighContrast.tmpl b/src/display-templates/HighContrast.css index 1e1366d..3652b74 100644 --- a/src/display-templates/HighContrast.tmpl +++ b/src/display-templates/HighContrast.css @@ -1,15 +1,6 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> -<html xmlns="http://www.w3.org/1999/xhtml"> -<head> - <title>#TITLE#</title> - <meta name="GENERATOR" content="BibleTime - www.bibletime.info" /> - <meta name="AUTHOR" content="BibleTime - www.bibletime.info" /> - <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> - - <style type="text/css"> - /* <![CDATA[ */ - +/** + * Theme by BibleTime - www.bibletime.info + */ * { /* To work around a KDE 3.2 bug / problem */ /* background-color:white; #this seems to break*/ @@ -279,7 +270,7 @@ td.entry + td.entry { padding:0; } -#infodisplay .footnoteinfo h3, #infodisplay .strongsinfo h3, #infodisplay .morphinfo h3, #infodisplay .translationinfo h3, #infodisplay .crossrefinfo h3 { +#infodisplay .footnoteinfo h3, #infodisplay .strongsinfo h3, #infodisplay .morphinfo h3, #infodisplay .translationinfo h3, #infodisplay .crossrefinfo h3, #infodisplay .moduleinfo h3 { padding: 2px 0 0 0; color: black; font-weight: bold; @@ -319,14 +310,3 @@ td.entry + td.entry { border-bottom: 1px solid black; color: black; } - -#LANG_CSS# - - /* ]]> */ - </style> -</head> - -<body id="#DISPLAYTYPE#"> - <div id="content" lang="#LANG_ABBREV#" xml:lang="#LANG_ABBREV#">#CONTENT#</div> -</body> -</html> diff --git a/src/display-templates/Simple.tmpl b/src/display-templates/Simple.css index e6ac8ad..ed2e976 100644 --- a/src/display-templates/Simple.tmpl +++ b/src/display-templates/Simple.css @@ -1,14 +1,6 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> -<html xmlns="http://www.w3.org/1999/xhtml"> -<head> - <title>#TITLE#</title> - <meta name="GENERATOR" content="BibleTime " VERSION "" /> - <meta name="AUTHOR" content="BibleTime " VERSION "" /> - <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> - - <style type="text/css"> -/* <![CDATA[ */ +/** + * Theme by BibleTime + */ body { background-color: white; color: black; @@ -124,12 +116,3 @@ div.currententry { .italic { font-style: italic; } -#LANG_CSS# -/* ]]> */ - </style> -</head> - -<body> - <div id="content" lang="#LANG_ABBREV#" xml:lang="#LANG_ABBREV#" dir="#PAGE_DIRECTION#">#CONTENT#</div> -</body> -</html>
\ No newline at end of file diff --git a/src/display-templates/basic_template.txt b/src/display-templates/basic_template.txt index 16ed394..dc98ab6 100644 --- a/src/display-templates/basic_template.txt +++ b/src/display-templates/basic_template.txt @@ -1,18 +1,3 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> -<html xmlns="http://www.w3.org/1999/xhtml"> -<head> - <title>#TITLE#</title> - <meta name="GENERATOR" content="BibleTime - www.bibletime.info" /> - <meta name="AUTHOR" content="BibleTime - www.bibletime.info" /> - <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> - - <style type="text/css"> -/* <![CDATA[ */ -* { - background-color:inherit; /* To work around a KDE 3.2 bug / problem */ -} - /* content wraps all of the displayed elements */ #content { } /* The table contains the Bible verses, each verse on an own row, each Bible module in an own column */ @@ -24,12 +9,12 @@ a { } a:hover { } -/* An entry is the generic element used for all content items. +/* An entry is the generic element used for all content items. In Bibles an entry contains a verse, in commentaries the comment to a verse range, in lexicons an simple item and in book the text of an item with other .entry elements as childs. - + If just one module is chosen, all entries are put together in one sourrounding table column. In this case the elements div and span may have the class "entry". If it's a div each entry should be on it's own line. span.entry should not add a linebreak. - + If more than one module (Bibles) was chosen, the entry class applies to "td" elements, one column for a verse */ .entry { } @@ -93,8 +78,8 @@ td.entry + td.entry { } .crossreference a { } .crossreference a:hover { } -/* Alternative reading as defined in the OSIS specs. The information about the alternative text is displayed in the info display. It's -often a good idea to format this the same as footnotes +/* Alternative reading as defined in the OSIS specs. The information about the alternative text is displayed in the info display. It's +often a good idea to format this the same as footnotes The text which is the alternative of the displayed text is available in the attribute "alternative" so something like .alternative:before { content:"'"attr(alternative); } is possible */ @@ -190,16 +175,4 @@ so something like .alternative:before { content:"'"attr(alternative); } is possi #infodisplay .entryname { } #infodisplay .rangeheading {} -#printer .rangeheading {} - -/* Here's the marker for the language specific fotn information. BibleTime replaces this by the CSS for the fonts */ -#LANG_CSS# - -/* ]]> */ - </style> -</head> - -<!-- The display type may be bible, book, printer --> -<body id="#DISPLAYTYPE#"> - <div id="content" lang="#LANG_ABBREV#" xml:lang="#LANG_ABBREV#">#CONTENT#</div></body> -</html>
\ No newline at end of file +#printer .rangeheading {}
\ No newline at end of file diff --git a/src/frontend/bookmarks/btbookmarkfolder.cpp b/src/frontend/bookmarks/btbookmarkfolder.cpp index 1cc2583..af027a9 100644 --- a/src/frontend/bookmarks/btbookmarkfolder.cpp +++ b/src/frontend/bookmarks/btbookmarkfolder.cpp @@ -9,7 +9,6 @@ #include "frontend/bookmarks/btbookmarkfolder.h" -#include <QDebug> #include <QFileDialog> #include "frontend/bookmarks/btbookmarkitembase.h" #include "frontend/bookmarks/btbookmarkitem.h" @@ -39,7 +38,6 @@ void BtBookmarkFolder::exportBookmarks() { QString fileName = QFileDialog::getSaveFileName(0, QObject::tr("Export Bookmarks"), "", filter); if (!fileName.isEmpty()) { - qDebug() << "exportBookmarks()"; BtBookmarkLoader loader; loader.saveTreeFromRootItem(this, fileName, false ); //false: don't overwrite without asking }; @@ -50,17 +48,12 @@ void BtBookmarkFolder::importBookmarks() { QString filter = QObject::tr("BibleTime bookmark files") + QString(" (*.btb);;") + QObject::tr("All files") + QString(" (*.*)"); QString fileName = QFileDialog::getOpenFileName(0, QObject::tr("Import bookmarks"), "", filter); if (!fileName.isEmpty()) { - qDebug() << "import bookmarks"; BtBookmarkLoader loader; QList<QTreeWidgetItem*> itemList = loader.loadTree(fileName); this->insertChildren(0, itemList); }; } -QString BtBookmarkFolder::toolTip() const { - return QString::null; -} - void BtBookmarkFolder::newSubFolder() { if (dynamic_cast<BtBookmarkFolder*>(this)) { BtBookmarkFolder* f = new BtBookmarkFolder(QObject::tr("New folder"), this); @@ -86,8 +79,6 @@ void BtBookmarkFolder::rename() { void BtBookmarkFolder::update() { namespace DU = util::directory; - qDebug() << "BtBookmarkFolder::update()"; - BtBookmarkItemBase::update(); if (isExpanded() && childCount()) setIcon(0, DU::getIcon(CResMgr::mainIndex::openedFolder::icon)); else @@ -95,14 +86,10 @@ void BtBookmarkFolder::update() { } bool BtBookmarkFolder::hasDescendant(QTreeWidgetItem* item) const { - qDebug() << "BtBookmarkFolder::hasDescendant, this:" << this << "possible descendant:" << item; - if (this == item) { - qDebug() << "it's this, return true"; return true; } if (getChildList().indexOf(item) > -1) { - qDebug() << "direct child, return true"; return true; } foreach(QTreeWidgetItem* childItem, getChildList()) { @@ -113,16 +100,13 @@ bool BtBookmarkFolder::hasDescendant(QTreeWidgetItem* item) const { } if (subresult == true) { - qDebug() << "descendand child, return true"; return true; } } - qDebug() << "no child, return false"; return false; } BtBookmarkFolder* BtBookmarkFolder::deepCopy() { - qDebug() << "BtBookmarkFolder::deepCopy"; BtBookmarkFolder* newFolder = new BtBookmarkFolder(this->text(0)); foreach(QTreeWidgetItem* subitem, getChildList()) { if (BtBookmarkItem* bmItem = dynamic_cast<BtBookmarkItem*>(subitem)) { diff --git a/src/frontend/bookmarks/btbookmarkfolder.h b/src/frontend/bookmarks/btbookmarkfolder.h index 90021f8..20388df 100644 --- a/src/frontend/bookmarks/btbookmarkfolder.h +++ b/src/frontend/bookmarks/btbookmarkfolder.h @@ -17,9 +17,8 @@ class BtBookmarkFolder : public BtBookmarkItemBase { public: - friend class BtBookmarkLoader; + BtBookmarkFolder(const QString &name, QTreeWidgetItem *parent = 0); - ~BtBookmarkFolder() {} /** See the base class. */ virtual bool enableAction(const MenuAction action); @@ -44,7 +43,6 @@ class BtBookmarkFolder : public BtBookmarkItemBase { void rename(); void update(); - QString toolTip() const; }; #endif diff --git a/src/frontend/bookmarks/btbookmarkitem.cpp b/src/frontend/bookmarks/btbookmarkitem.cpp index fff3d2c..639d33e 100644 --- a/src/frontend/bookmarks/btbookmarkitem.cpp +++ b/src/frontend/bookmarks/btbookmarkitem.cpp @@ -10,7 +10,6 @@ #include "frontend/bookmarks/btbookmarkitem.h" #include <QSharedPointer> -#include <QDebug> #include "backend/config/cbtconfig.h" #include "backend/drivers/cswordmoduleinfo.h" #include "backend/keys/cswordversekey.h" @@ -137,7 +136,6 @@ void BtBookmarkItem::rename() { void BtBookmarkItem::update() { namespace DU = util::directory; - qDebug() << "BtBookmarkItem::update"; setIcon(0, DU::getIcon(CResMgr::mainIndex::bookmark::icon)); if (m_title.isEmpty()) { diff --git a/src/frontend/bookmarks/btbookmarkitem.h b/src/frontend/bookmarks/btbookmarkitem.h index 3166e61..89fd412 100644 --- a/src/frontend/bookmarks/btbookmarkitem.h +++ b/src/frontend/bookmarks/btbookmarkitem.h @@ -31,8 +31,6 @@ class BtBookmarkItem : public BtBookmarkItemBase { /** Creates a copy. */ BtBookmarkItem(const BtBookmarkItem& other); - ~BtBookmarkItem() {} - /** Returns the used module, 0 if there is no such module. */ CSwordModuleInfo *module() const; @@ -49,18 +47,19 @@ class BtBookmarkItem : public BtBookmarkItemBase { return m_title; } - /** Returns a tooltip for this bookmark. */ - virtual QString toolTip() const; - /** Returns whether the action is supported by this item. */ virtual bool enableAction(MenuAction action); /** Changes this bookmark. */ virtual void rename(); - void update(); + virtual void update(); private: + + /** Returns a tooltip for this bookmark. */ + QString toolTip() const; + /** Returns the english key.*/ inline const QString &englishKey() const { return m_key; diff --git a/src/frontend/bookmarks/btbookmarkitembase.cpp b/src/frontend/bookmarks/btbookmarkitembase.cpp deleted file mode 100644 index 1a80f7d..0000000 --- a/src/frontend/bookmarks/btbookmarkitembase.cpp +++ /dev/null @@ -1,21 +0,0 @@ -/********* -* -* This file is part of BibleTime's source code, http://www.bibletime.info/. -* -* Copyright 1999-2011 by the BibleTime developers. -* The BibleTime source code is licensed under the GNU General Public License version 2.0. -* -**********/ - -#include "frontend/bookmarks/btbookmarkitembase.h" - - -BtBookmarkItemBase::BtBookmarkItemBase() { - // Intentionally empty -} - -BtBookmarkItemBase::BtBookmarkItemBase(QTreeWidgetItem *parent) - : QTreeWidgetItem(parent) -{ - // Intentionally empty -} diff --git a/src/frontend/bookmarks/btbookmarkitembase.h b/src/frontend/bookmarks/btbookmarkitembase.h index 8452473..2ae1430 100644 --- a/src/frontend/bookmarks/btbookmarkitembase.h +++ b/src/frontend/bookmarks/btbookmarkitembase.h @@ -12,15 +12,11 @@ #include <QTreeWidgetItem> -#include <QDropEvent> -#include <QMimeData> -#include <QString> +class BtBookmarkItemBase: public QTreeWidgetItem { -class CBookmarkIndex; + public: /* Types: */ -class BtBookmarkItemBase : public QTreeWidgetItem { - public: enum MenuAction { NewFolder = 0, ChangeFolder, @@ -38,23 +34,19 @@ class BtBookmarkItemBase : public QTreeWidgetItem { ActionEnd = DeleteEntries }; - /** Where to drop/create item(s): above, below or inside an item.*/ - enum Location {Above, Below, Inside}; + public: /* Methods: */ - BtBookmarkItemBase(); - BtBookmarkItemBase(QTreeWidgetItem* parent); - virtual ~BtBookmarkItemBase() {} - - virtual QString toolTip() const = 0; + inline BtBookmarkItemBase(QTreeWidgetItem *parent = 0) + : QTreeWidgetItem(parent) {} /** Returns true if the given action should be enabled in the popup menu. */ - virtual bool enableAction( MenuAction action ) = 0; + virtual bool enableAction(MenuAction action) = 0; /** Rename the item. */ virtual void rename() = 0; /** Update the item (icon etc.) after creating or changing it. */ - virtual void update() {} + virtual void update() = 0; }; diff --git a/src/frontend/bookmarks/btbookmarkloader.cpp b/src/frontend/bookmarks/btbookmarkloader.cpp index ed1dd29..c9133a4 100644 --- a/src/frontend/bookmarks/btbookmarkloader.cpp +++ b/src/frontend/bookmarks/btbookmarkloader.cpp @@ -9,7 +9,6 @@ #include "frontend/bookmarks/btbookmarkloader.h" -#include <QDebug> #include <QDomElement> #include <QDomNode> #include <QDomDocument> @@ -27,7 +26,6 @@ #define CURRENT_SYNTAX_VERSION 1 QList<QTreeWidgetItem*> BtBookmarkLoader::loadTree(QString fileName) { - qDebug() << "BtBookmarkLoader::loadTree"; QList<QTreeWidgetItem*> itemList; QDomDocument doc; @@ -44,7 +42,6 @@ QList<QTreeWidgetItem*> BtBookmarkLoader::loadTree(QString fileName) { QDomElement child = document.firstChild().toElement(); while ( !child.isNull() && child.parentNode() == document) { - qDebug() << "BtBookmarkLoader::loadTree while start"; QTreeWidgetItem* i = handleXmlElement(child, 0); itemList.append(i); if (!child.nextSibling().isNull()) { @@ -60,17 +57,14 @@ QList<QTreeWidgetItem*> BtBookmarkLoader::loadTree(QString fileName) { } QTreeWidgetItem* BtBookmarkLoader::handleXmlElement(QDomElement& element, QTreeWidgetItem* parent) { - qDebug() << "BtBookmarkLoader::handleXmlElement"; QTreeWidgetItem* newItem = 0; if (element.tagName() == "Folder") { - qDebug() << "BtBookmarkLoader::handleXmlElement: found folder"; BtBookmarkFolder* newFolder = new BtBookmarkFolder(QString::null, parent); if (element.hasAttribute("caption")) { newFolder->setText(0, element.attribute("caption")); } QDomNodeList childList = element.childNodes(); for (unsigned int i = 0; i < childList.length(); i++) { - qDebug() << "BtBookmarkLoader::handleXmlElement: go through child list of folder"; QDomElement newElement = childList.at(i).toElement(); QTreeWidgetItem* newChildItem = handleXmlElement(newElement, newFolder); newFolder->addChild(newChildItem); @@ -79,7 +73,6 @@ QTreeWidgetItem* BtBookmarkLoader::handleXmlElement(QDomElement& element, QTreeW newItem = newFolder; } else if (element.tagName() == "Bookmark") { - qDebug() << "BtBookmarkLoader::handleXmlElement: found bookmark"; BtBookmarkItem* newBookmarkItem = new BtBookmarkItem(parent); if (element.hasAttribute("modulename")) { //we use the name in all cases, even if the module isn't installed anymore @@ -97,7 +90,6 @@ QTreeWidgetItem* BtBookmarkLoader::handleXmlElement(QDomElement& element, QTreeW newBookmarkItem->update(); newItem = newBookmarkItem; } - qDebug() << "BtBookmarkLoader::handleXmlElement: return new item"; return newItem; } diff --git a/src/frontend/bookmarks/cbookmarkindex.cpp b/src/frontend/bookmarks/cbookmarkindex.cpp index b6adbfa..15f272c 100644 --- a/src/frontend/bookmarks/cbookmarkindex.cpp +++ b/src/frontend/bookmarks/cbookmarkindex.cpp @@ -66,8 +66,6 @@ CBookmarkIndex::~CBookmarkIndex() { /** Initializes the view. */ void CBookmarkIndex::initView() { - //qDebug() << "CBookmarkIndex::initView"; - setHeaderHidden(true); setFocusPolicy(Qt::WheelFocus); @@ -121,7 +119,6 @@ void CBookmarkIndex::initView() { m_popup->addAction(m_actions.deleteEntries); m_bookmarksModified = false; - //qDebug() << "CBookmarkIndex::initView end"; } /** Convenience function for creating a new QAction. @@ -142,7 +139,6 @@ QAction* CBookmarkIndex::newQAction(const QString& text, const QString& pix, con /** Initialize the SIGNAL<->SLOT connections */ void CBookmarkIndex::initConnections() { - //qDebug() << "CBookmarkIndex::initConnections"; bool ok; ok = connect(this, SIGNAL(itemActivated(QTreeWidgetItem*, int)), this, SLOT(slotExecuted(QTreeWidgetItem*))); Q_ASSERT(ok); @@ -168,15 +164,12 @@ void CBookmarkIndex::initConnections() { * Hack to get single click and selection working. See slotExecuted. */ void CBookmarkIndex::mouseReleaseEvent(QMouseEvent* event) { - //qDebug() << "CBookmarkIndex::mouseReleaseEvent"; m_mouseReleaseEventModifiers = event->modifiers(); QTreeWidget::mouseReleaseEvent(event); } /** Called when an item is clicked with mouse or activated with keyboard. */ void CBookmarkIndex::slotExecuted( QTreeWidgetItem* i ) { - qDebug() << "CBookmarkIndex::slotExecuted"; - //HACK: checking the modifier keys from the last mouseReleaseEvent //depends on executing order: mouseReleaseEvent first, then itemClicked signal int modifiers = m_mouseReleaseEventModifiers; @@ -224,7 +217,6 @@ QMimeData* CBookmarkIndex::dragObject() { } void CBookmarkIndex::dragEnterEvent( QDragEnterEvent* event ) { - //qDebug() << "CBookmarkIndex::dragEnterEvent"; setState(QAbstractItemView::DraggingState); QTreeWidget::dragEnterEvent(event); if (event->source() == this || event->mimeData()->hasFormat("BibleTime/Bookmark")) { @@ -234,8 +226,6 @@ void CBookmarkIndex::dragEnterEvent( QDragEnterEvent* event ) { void CBookmarkIndex::dragMoveEvent( QDragMoveEvent* event ) { - //qDebug() << "CBookmarkIndex::dragMoveEvent"; - // do this first, otherwise the event may be ignored QTreeWidget::dragMoveEvent(event); @@ -249,7 +239,6 @@ void CBookmarkIndex::dragMoveEvent( QDragMoveEvent* event ) { } void CBookmarkIndex::dragLeaveEvent( QDragLeaveEvent* ) { - qDebug() << "CBookmarkIndex::dragLeaveEvent"; setState(QAbstractItemView::NoState); // not dragging anymore viewport()->update(); // clear the arrow } @@ -337,7 +326,6 @@ void CBookmarkIndex::paintEvent(QPaintEvent* event) { void CBookmarkIndex::dropEvent( QDropEvent* event ) { - qDebug() << "CBookmarkIndex::dropEvent"; //setState(QAbstractItemView::NoState); // Try to prevent annoying timed autocollapsing. Remember to disconnect before return. @@ -348,14 +336,11 @@ void CBookmarkIndex::dropEvent( QDropEvent* event ) { // Find the place where the drag is dropped if (item) { - qDebug() << "there was item"; - QRect rect = visualItemRect(item); bool isFolder = dynamic_cast<BtBookmarkFolder*>(item); bool isBookmark = dynamic_cast<BtBookmarkItem*>(item); if (isFolder) { // item is a folder - qDebug() << "item was folder"; if (event->pos().y() > rect.bottom() - (2* rect.height() / 3) ) { parentItem = item; } @@ -364,13 +349,11 @@ void CBookmarkIndex::dropEvent( QDropEvent* event ) { if (!parentItem) { parentItem = invisibleRootItem(); } - qDebug() << "item:" << item << "parent:" << parentItem; indexUnderParent = parentItem->indexOfChild(item); // before the current folder } } else { if (isBookmark) { // item is a bookmark - qDebug() << "item was bookmark"; parentItem = item->parent(); if (!parentItem) { parentItem = invisibleRootItem(); @@ -391,14 +374,12 @@ void CBookmarkIndex::dropEvent( QDropEvent* event ) { } else { // no item under event point: drop to the end - qDebug() << "there was no item"; parentItem = invisibleRootItem(); indexUnderParent = parentItem->childCount() - 1; } if ( event->source() == this ) { - qDebug() << "dropping internal drag"; event->accept(); bool bookmarksOnly = true; @@ -424,7 +405,6 @@ void CBookmarkIndex::dropEvent( QDropEvent* event ) { QAction* move = dropPopupMenu->addAction(tr("Move")); QAction* dropAction = dropPopupMenu->exec(QCursor::pos()); if (dropAction == copy) { - qDebug() << "copy"; parentItem->insertChildren(indexUnderParent, newItems); // Need this here because the "move" case goes through // "deleteEntries" which has a save call. @@ -432,7 +412,6 @@ void CBookmarkIndex::dropEvent( QDropEvent* event ) { } else { if (dropAction == move) { - qDebug() << "move"; parentItem->insertChildren(indexUnderParent, newItems); deleteEntries(false); } @@ -444,7 +423,6 @@ void CBookmarkIndex::dropEvent( QDropEvent* event ) { } } else { - qDebug() << "the source was outside this"; createBookmarkFromDrop(event, parentItem, indexUnderParent); } QObject::disconnect(this, SIGNAL(itemCollapsed(QTreeWidgetItem*)), this, SLOT(expandAutoCollapsedItem(QTreeWidgetItem*))); @@ -453,7 +431,6 @@ void CBookmarkIndex::dropEvent( QDropEvent* event ) { void CBookmarkIndex::createBookmarkFromDrop(QDropEvent* event, QTreeWidgetItem* parentItem, int indexInParent) { - //qDebug() << "CBookmarkIndex::createBookmarkFromDrop"; //take the bookmark data from the mime source const BTMimeData* mdata = dynamic_cast<const BTMimeData*>(event->mimeData()); if (mdata) { @@ -462,13 +439,12 @@ void CBookmarkIndex::createBookmarkFromDrop(QDropEvent* event, QTreeWidgetItem* QString keyText = mdata->bookmark().key(); QString description = mdata->bookmark().description(); CSwordModuleInfo *minfo = CSwordBackend::instance()->findModuleByName(moduleName); - QString title; // TODO + QString title; /// \todo QTreeWidgetItem* newItem = new BtBookmarkItem(minfo, keyText, description, title); // connect(newItem, SIGNAL(bookmarkModified()), this, SLOT(needToSaveBookmarks()) ); parentItem->insertChild(indexInParent, newItem); - qDebug() << "Saving in...CBookmarkIndex::createBookmarkFromDrop"; needToSaveBookmarks(); } } @@ -476,7 +452,6 @@ void CBookmarkIndex::createBookmarkFromDrop(QDropEvent* event, QTreeWidgetItem* /** Load the tree from file */ void CBookmarkIndex::initTree() { - qDebug() << "CBookmarkIndex::initTree"; BtBookmarkLoader loader; addTopLevelItems(loader.loadTree()); @@ -487,7 +462,6 @@ void CBookmarkIndex::initTree() { } void CBookmarkIndex::slotItemEntered(QTreeWidgetItem* item, int) { - qDebug() << "CBookmarkIndex::slotItemEntered"; if (item == m_extraItem) { m_extraItem->setText(0, tr("Drag references from text views to this view")); } @@ -528,7 +502,6 @@ QAction* CBookmarkIndex::action( BtBookmarkItemBase::MenuAction type ) const { /** Shows the context menu at the given position. */ void CBookmarkIndex::contextMenu(const QPoint& p) { - //qDebug() << "CBookmarkIndex::contextMenu"; //setup menu entries depending on current selection QTreeWidgetItem* i = itemAt(p); QList<QTreeWidgetItem *> items = selectedItems(); @@ -536,7 +509,7 @@ void CBookmarkIndex::contextMenu(const QPoint& p) { if (i && !items.contains(i) && i != m_extraItem) items.append(i); - if (items.count() == 0) { + if (items.isEmpty()) { //special handling for no selection BtBookmarkItemBase::MenuAction actionType; for (int index = BtBookmarkItemBase::ActionBegin; index <= BtBookmarkItemBase::ActionEnd; ++index) { @@ -593,12 +566,10 @@ void CBookmarkIndex::contextMenu(const QPoint& p) { } //finally, open the popup m_popup->exec(mapToGlobal(p)); - //qDebug() << "CBookmarkIndex::contextMenu end"; } /** Adds a new subfolder to the current item. */ void CBookmarkIndex::createNewFolder() { - //qDebug() << "CBookmarkIndex::createNewFolder"; QList<QTreeWidgetItem*> selected = selectedItems(); if (selected.count() > 0) { BtBookmarkFolder* i = dynamic_cast<BtBookmarkFolder*>(currentItem()); @@ -705,7 +676,7 @@ void CBookmarkIndex::printBookmarks() { } } - if (items.count() == 0) { + if (items.isEmpty()) { qWarning("Tried to print empty bookmark list."); return; } @@ -755,7 +726,6 @@ a BibleTime mimedata object. It can be dragged and dropped to a text view or som The internal drag is handled differently, it doesn't use the mimedata (see dropEvent()). */ void CBookmarkIndex::startDrag(Qt::DropActions) { - qDebug() << "CBookmarkIndex::startDrag"; QMimeData* mData = dragObject(); // create the data which can be used in other widgets QDrag* drag = new QDrag(this); @@ -800,19 +770,15 @@ bool CBookmarkIndex::isMultiAction( const BtBookmarkItemBase::MenuAction type ) /* Saves the bookmarks to the default bookmarks file. */ void CBookmarkIndex::saveBookmarks() { - - qDebug() << "CBookmarkIndex::saveBookmarks()"; BtBookmarkLoader loader; loader.saveTreeFromRootItem(invisibleRootItem()); } void CBookmarkIndex::mouseMoveEvent(QMouseEvent* event) { - //qDebug() << "CBookmarkIndex::mouseMoveEvent"; // Restart the mag timer if we have moved to another item and shift was not pressed. QTreeWidgetItem* itemUnderPointer = itemAt(event->pos()); if (itemUnderPointer && (itemUnderPointer != m_previousEventItem) ) { - //qDebug() << "CBookmarkIndex::mouseMoveEvent, moved onto another item"; if ( !(event->modifiers() & Qt::ShiftModifier)) { m_magTimer.start(); // see the ctor for the timer properties } @@ -828,8 +794,6 @@ void CBookmarkIndex::mouseMoveEvent(QMouseEvent* event) { } void CBookmarkIndex::magTimeout() { - //qDebug() << "CBookmarkIndex::magTimeout"; - QTreeWidgetItem* itemUnderPointer = 0; if (underMouse()) { itemUnderPointer = itemAt(mapFromGlobal(QCursor::pos())); @@ -838,7 +802,6 @@ void CBookmarkIndex::magTimeout() { if (itemUnderPointer && (m_previousEventItem == itemUnderPointer)) { BtBookmarkItem* bitem = dynamic_cast<BtBookmarkItem*>(itemUnderPointer); if (bitem) { - //qDebug() << "CBookmarkIndex::timerEvent: update the infodisplay"; // Update the mag if (bitem->module()) { (BibleTime::instance()->infoDisplay())->setInfo( @@ -866,42 +829,34 @@ and the list is incomplete. */ QList<QTreeWidgetItem*> CBookmarkIndex::addItemsToDropTree( QTreeWidgetItem* target, bool& bookmarksOnly, bool& targetIncluded, bool& moreThanOneFolder) { - qDebug() << "CBookmarkIndex::addItemsToDropTree"; QList<QTreeWidgetItem*> selectedList = selectedItems(); QList<QTreeWidgetItem*> newList; foreach(QTreeWidgetItem* item, selectedList) { - qDebug() << "go through all items:" << item; if ( BtBookmarkFolder* folder = dynamic_cast<BtBookmarkFolder*>(item)) { bookmarksOnly = false; if (selectedList.count() > 1) { // only one item allowed if a folder is selected - qDebug() << "one folder and something else is selected"; moreThanOneFolder = true; break; } if (folder->hasDescendant(target)) { // dropping to self or descendand not allowed - qDebug() << "addItemsToDropTree: target is included"; targetIncluded = true; break; } } else { - qDebug() << "append new QTreeWidget item (should be BtBookmarkItem?)"; newList.append(new BtBookmarkItem( *(dynamic_cast<BtBookmarkItem*>(item)) )); } } if (!bookmarksOnly && selectedList.count() == 1) { - qDebug() << "exactly one folder"; BtBookmarkFolder* folder = dynamic_cast<BtBookmarkFolder*>(selectedList.value(0)); BtBookmarkFolder* copy = folder->deepCopy(); newList.append(copy); } if (!bookmarksOnly && selectedList.count() > 1) { // wrong amount of items - qDebug() << "one folder and something else is selected 2"; moreThanOneFolder = true; } - qDebug() << "return the new list" << newList; return newList; } @@ -910,7 +865,6 @@ QList<QTreeWidgetItem*> CBookmarkIndex::addItemsToDropTree( /// modifications are made, the bookmarks are saved. The timer is reset when a /// new modification is made. The timer bookmarkSaveTimer is set to be oneshot. void CBookmarkIndex::needToSaveBookmarks() { - qDebug() << "Got signal to save bookmarks!"; m_bookmarksModified = true; bookmarkSaveTimer.start(1500); // Only save after 1.5s. } @@ -919,7 +873,6 @@ void CBookmarkIndex::needToSaveBookmarks(QTreeWidgetItem* treeItem) { // but actually a folder or bookmark. BtBookmarkItemBase* bookmark = dynamic_cast<BtBookmarkItemBase*>(treeItem); if (bookmark) { - qDebug() << "Got signal to save bookmarks!"; m_bookmarksModified = true; bookmarkSaveTimer.start(1500); // Only save after 1.5s. } @@ -928,7 +881,6 @@ void CBookmarkIndex::needToSaveBookmarks(QTreeWidgetItem* treeItem) { /// Considers saving bookmarks only if they have been modified. This procedure /// should be called by the qtimer bookmarkTimer. void CBookmarkIndex::considerSavingBookmarks() { - qDebug() << "Considering to save bookmarks!"; if (m_bookmarksModified) { saveBookmarks(); m_bookmarksModified = false; diff --git a/src/frontend/bookshelfmanager/btconfigdialog.cpp b/src/frontend/bookshelfmanager/btconfigdialog.cpp index 3d02388..3b82560 100644 --- a/src/frontend/bookshelfmanager/btconfigdialog.cpp +++ b/src/frontend/bookshelfmanager/btconfigdialog.cpp @@ -17,16 +17,17 @@ #include <QLabel> #include <QListWidget> #include <QListView> -#include <QListWidgetItem> #include <QStackedWidget> #include <QVBoxLayout> -BtConfigDialog::BtConfigDialog(QWidget* parent) - : QDialog(parent), - m_maxItemWidth(0), - m_previousPageIndex(-2) { - setWindowFlags(Qt::Window); +BtConfigDialog::BtConfigDialog(QWidget* parent, Qt::WindowFlags flags) + : QDialog(parent, flags) + , m_buttonBoxRuler(0) + , m_buttonBox(0) + , m_maxItemWidth(0) + , m_previousPageIndex(-2) +{ m_contentsList = new QListWidget(this); m_contentsList->setViewMode(QListView::IconMode); m_contentsList->setMovement(QListView::Static); @@ -34,35 +35,27 @@ BtConfigDialog::BtConfigDialog(QWidget* parent) m_pageWidget = new QStackedWidget(this); m_pageWidget->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding); - QHBoxLayout *mainLayout = new QHBoxLayout; - setLayout(mainLayout); - mainLayout->addWidget(m_contentsList); m_pageLayout = new QVBoxLayout; - mainLayout->addLayout(m_pageLayout); - m_pageLayout->addWidget(m_pageWidget); - connect(m_contentsList, - SIGNAL(currentRowChanged(int)), - this, SLOT(slotChangePage(int)) - ); + QHBoxLayout *mainLayout = new QHBoxLayout(this); + mainLayout->addWidget(m_contentsList); + mainLayout->addLayout(m_pageLayout); + connect(m_contentsList, SIGNAL(currentRowChanged(int)), + this, SLOT(slotChangePage(int))); } -BtConfigDialog::~BtConfigDialog() {} - -void BtConfigDialog::addPage(BtConfigPage* pageWidget) { - // this is a friend - pageWidget->m_parentDialog = this; +void BtConfigDialog::addPage(Page* pageWidget) { m_pageWidget->addWidget(pageWidget); - QListWidgetItem* item = new QListWidgetItem(m_contentsList); item->setIcon(pageWidget->icon()); - item->setText(pageWidget->header()); + item->setText(pageWidget->headerText()); item->setTextAlignment(Qt::AlignHCenter); item->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled); + pageWidget->setListWidgetItem(item); //set the list width - it may bee too wide (if there were no pages) or too narrow if (m_maxItemWidth < m_contentsList->visualItemRect(item).width()) { @@ -74,23 +67,29 @@ void BtConfigDialog::addPage(BtConfigPage* pageWidget) { m_contentsList->item(i)->setSizeHint(QSize(m_maxItemWidth, m_contentsList->visualItemRect(m_contentsList->item(i)).height()) ); } - slotChangePage(m_contentsList->row(item)); + setCurrentPage(m_contentsList->row(item)); } -void BtConfigDialog::addButtonBox(QDialogButtonBox* box) { +void BtConfigDialog::setButtonBox(QDialogButtonBox *box) { + Q_ASSERT(box != 0); + Q_ASSERT(m_buttonBox == 0); + Q_ASSERT(m_buttonBoxRuler == 0); + + m_buttonBox = box; + // First add a horizontal ruler: - QFrame *line = new QFrame(); - line->setGeometry(QRect(1, 1, 1, 3)); - line->setFrameShape(QFrame::HLine); - line->setFrameShadow(QFrame::Sunken); - line->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); - m_pageLayout->addWidget(line); + m_buttonBoxRuler = new QFrame(this); + m_buttonBoxRuler->setGeometry(QRect(1, 1, 1, 3)); + m_buttonBoxRuler->setFrameShape(QFrame::HLine); + m_buttonBoxRuler->setFrameShadow(QFrame::Sunken); + m_buttonBoxRuler->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); + m_pageLayout->addWidget(m_buttonBoxRuler); // Add button box: m_pageLayout->addWidget(box); } -void BtConfigDialog::slotChangePage(int newIndex) { +void BtConfigDialog::setCurrentPage(int newIndex) { if (m_previousPageIndex != newIndex) { m_previousPageIndex = newIndex; m_contentsList->setCurrentRow(newIndex); @@ -98,15 +97,13 @@ void BtConfigDialog::slotChangePage(int newIndex) { } } - - -BtConfigPage::BtConfigPage(QWidget *parent) - : QWidget(parent) - , m_parentDialog(0) -{ - setLayout(new QVBoxLayout); -} - -BtConfigPage::~BtConfigPage() { - // Intentionally empty +void BtConfigDialog::slotChangePage(int newIndex) { + /* + This check is in place here because this slot is indirectly called by the + setCurrentPage method. + */ + if (m_previousPageIndex != newIndex) { + m_previousPageIndex = newIndex; + m_pageWidget->setCurrentIndex(newIndex); + } } diff --git a/src/frontend/bookshelfmanager/btconfigdialog.h b/src/frontend/bookshelfmanager/btconfigdialog.h index dce22ab..e90c3ed 100644 --- a/src/frontend/bookshelfmanager/btconfigdialog.h +++ b/src/frontend/bookshelfmanager/btconfigdialog.h @@ -12,15 +12,13 @@ #include <QDialog> -#include <QDebug> -#include <QWidget> +#include <QIcon> +#include <QListWidgetItem> class BtConfigPage; class QDialogButtonBox; -class QLabel; -class QListWidget; -class QListWidgetItem; +class QFrame; class QStackedWidget; class QVBoxLayout; @@ -33,60 +31,78 @@ class QVBoxLayout; * an auto-destroying window. */ class BtConfigDialog : public QDialog { + Q_OBJECT - public: - BtConfigDialog(QWidget *parent = 0); - virtual ~BtConfigDialog(); + + public: /* Types: */ + + /** Base class for configuration dialog pages. */ + class Page : public QWidget { + + friend class BtConfigDialog; + + public: /* Methods: */ + + inline Page(BtConfigDialog *parent) + : QWidget(parent), m_listWidgetItem(0) {} + inline Page(const QIcon &icon, BtConfigDialog *parent) + : QWidget(parent), m_icon(icon), m_listWidgetItem(0) {} + + inline const QIcon &icon() const { return m_icon; } + inline void setIcon(const QIcon &icon) { + m_icon = icon; + if (m_listWidgetItem != 0) + m_listWidgetItem->setIcon(icon); + } + + inline const QString &headerText() const { return m_headerText; } + inline void setHeaderText(const QString &headerText) { + m_headerText = headerText; + if (m_listWidgetItem != 0) + m_listWidgetItem->setText(headerText); + } + + private: /* Methods: */ + + void setListWidgetItem(QListWidgetItem *item) { + m_listWidgetItem = item; + } + + private: /* Fields: */ + + QIcon m_icon; + QString m_headerText; + QListWidgetItem *m_listWidgetItem; + + }; + + public: /* Methods: */ + + BtConfigDialog(QWidget *parent = 0, Qt::WindowFlags flags = 0); /** Adds a BtConfigPage to the paged widget stack. The new page will be the current page.*/ - void addPage(BtConfigPage* pageWidget); + void addPage(Page *pageWidget); + /** Adds a button box to the lower edge of the dialog. */ - void addButtonBox(QDialogButtonBox* buttonBox); + void setButtonBox(QDialogButtonBox* buttonBox); - public slots: /** Changes the current page using the given index number. */ + void setCurrentPage(int newIndex); + + private slots: + void slotChangePage(int newIndex); - private: + private: /* Fields: */ + QListWidget* m_contentsList; QStackedWidget* m_pageWidget; QVBoxLayout* m_pageLayout; + QFrame *m_buttonBoxRuler; + QDialogButtonBox *m_buttonBox; int m_maxItemWidth; int m_previousPageIndex; -}; - - -/** -* Base class for configuration dialog pages. -*/ -class BtConfigPage : public QWidget { - Q_OBJECT - friend class BtConfigDialog; - - public: - /** - Constructs a configuration dialog base, with QVBoxLayout as layout() and a header - label as the first widget in this layout. - \param[in] parent The parent widget. - */ - BtConfigPage(QWidget *parent = 0); - virtual ~BtConfigPage(); - - /** Implement these to return the correct values. - * For example: header(){return tr("General");} - */ - virtual const QIcon &icon() const = 0; - virtual QString header() const = 0; - - inline BtConfigDialog *parentDialog() const { - return m_parentDialog; - } - - private: - BtConfigDialog *m_parentDialog; }; - #endif - diff --git a/src/frontend/bookshelfmanager/btinstallmgr.cpp b/src/frontend/bookshelfmanager/btinstallmgr.cpp index 756fcae..652ff04 100644 --- a/src/frontend/bookshelfmanager/btinstallmgr.cpp +++ b/src/frontend/bookshelfmanager/btinstallmgr.cpp @@ -11,7 +11,6 @@ #include "backend/managers/cswordbackend.h" #include "backend/btinstallbackend.h" -#include <QDebug> #include <QList> #include <QObject> #include <QString> @@ -28,7 +27,6 @@ BtInstallMgr::BtInstallMgr() : InstallMgr(BtInstallBackend::configPath().toLatin1(), this), m_totalBytes(1), m_completedBytes(0), m_firstCallOfPreStatus(true) { //use this class also as status reporter - qDebug() << "BtInstallMgr::BtInstallMgr"; this->setFTPPassive(true); } @@ -44,7 +42,6 @@ bool BtInstallMgr::isUserDisclaimerConfirmed() const { } void BtInstallMgr::statusUpdate(double dltotal, double dlnow) { - //qDebug() << "BtInstallMgr::statusUpdate"; if (dlnow > dltotal) dlnow = dltotal; @@ -65,7 +62,6 @@ void BtInstallMgr::statusUpdate(double dltotal, double dlnow) { filePercent = 0; } //qApp->processEvents(); - //qDebug() << "status: total"<<totalPercent<<"file"<<filePercent; emit percentCompleted(totalPercent, filePercent); } @@ -75,7 +71,6 @@ void BtInstallMgr::preStatus(long totalBytes, long completedBytes, const char* m m_firstCallOfPreStatus = false; emit downloadStarted(); } - qDebug() << "BtInstallMgr::preStatus:" << (int)totalBytes << "/" << (int)completedBytes << QString(message); m_completedBytes = completedBytes; m_totalBytes = (totalBytes > 0) ? totalBytes : 1; //avoid division by zero } diff --git a/src/frontend/bookshelfmanager/btmodulemanagerdialog.cpp b/src/frontend/bookshelfmanager/btmodulemanagerdialog.cpp index f0547b8..42febaa 100644 --- a/src/frontend/bookshelfmanager/btmodulemanagerdialog.cpp +++ b/src/frontend/bookshelfmanager/btmodulemanagerdialog.cpp @@ -18,34 +18,39 @@ static BtModuleManagerDialog *m_staticModuleManagerDialog = 0; -BtModuleManagerDialog* BtModuleManagerDialog::getInstance(QWidget* parent) { - if (!m_staticModuleManagerDialog) { - m_staticModuleManagerDialog = new BtModuleManagerDialog(parent); - }; +BtModuleManagerDialog* BtModuleManagerDialog::getInstance(QWidget *parent, + Qt::WindowFlags flags) +{ + if (m_staticModuleManagerDialog) { + m_staticModuleManagerDialog->setParent(parent, flags); + } else { + m_staticModuleManagerDialog = new BtModuleManagerDialog(parent, flags); + } Q_ASSERT(m_staticModuleManagerDialog); return m_staticModuleManagerDialog; } -BtModuleManagerDialog::BtModuleManagerDialog(QWidget* parent) - : BtConfigDialog(parent) { +BtModuleManagerDialog::BtModuleManagerDialog(QWidget *parent, + Qt::WindowFlags flags) + : BtConfigDialog(parent, + flags | Qt::CustomizeWindowHint | Qt::WindowTitleHint + | Qt::WindowCloseButtonHint | Qt::WindowMaximizeButtonHint) +{ setAttribute(Qt::WA_DeleteOnClose); - setWindowTitle(tr("Bookshelf Manager")); - // Install page - BtInstallPage* installPage = new BtInstallPage(); - addPage(installPage); + addPage(new BtInstallPage()); + addPage(new BtRemovePage()); + addPage(new BtIndexPage()); - //Uninstall page - BtRemovePage* removePage = new BtRemovePage(); - addPage(removePage); + retranslateUi(); - //Index page - BtIndexPage* indexPage = new BtIndexPage(); - addPage(indexPage); + loadDialogSettings(); + setCurrentPage(0); - slotChangePage(0); +} - loadDialogSettings(); +void BtModuleManagerDialog::retranslateUi() { + setWindowTitle(tr("Bookshelf Manager")); } BtModuleManagerDialog::~BtModuleManagerDialog() { @@ -53,17 +58,12 @@ BtModuleManagerDialog::~BtModuleManagerDialog() { m_staticModuleManagerDialog = 0; } -// The QWidget close() sends close event, so does closing by the window X button. -void BtModuleManagerDialog::closeEvent(QCloseEvent*) { - qDebug() << "BtModuleManagerDialog::closeEvent"; -} - void BtModuleManagerDialog::loadDialogSettings() { resize(CBTConfig::get(CBTConfig::bookshelfWidth), CBTConfig::get(CBTConfig::bookshelfHeight)); move(CBTConfig::get(CBTConfig::bookshelfPosX), CBTConfig::get(CBTConfig::bookshelfPosY)); } -void BtModuleManagerDialog::saveDialogSettings() { +void BtModuleManagerDialog::saveDialogSettings() const { CBTConfig::set(CBTConfig::bookshelfWidth, size().width()); CBTConfig::set(CBTConfig::bookshelfHeight, size().height()); CBTConfig::set(CBTConfig::bookshelfPosX, x()); diff --git a/src/frontend/bookshelfmanager/btmodulemanagerdialog.h b/src/frontend/bookshelfmanager/btmodulemanagerdialog.h index 0392cc2..01ef594 100644 --- a/src/frontend/bookshelfmanager/btmodulemanagerdialog.h +++ b/src/frontend/bookshelfmanager/btmodulemanagerdialog.h @@ -13,38 +13,31 @@ #include "frontend/bookshelfmanager/btconfigdialog.h" -class QWidget; - /** * The Bookshelf Manager dialog. Includes pages for Install, Remove, Indexes. */ -class BtModuleManagerDialog : public BtConfigDialog { +class BtModuleManagerDialog: public BtConfigDialog { + Q_OBJECT public: - static BtModuleManagerDialog* getInstance(QWidget* parent); + static BtModuleManagerDialog *getInstance(QWidget *parent = 0, + Qt::WindowFlags flags = 0); ~BtModuleManagerDialog(); + private: - //void slotClose(); - protected: - /** Reimplementation from QWidget. */ - virtual void closeEvent(QCloseEvent* event); + BtModuleManagerDialog(QWidget *parent = 0, Qt::WindowFlags flags = 0); - /** Adds the pages and the button box. */ - BtModuleManagerDialog(QWidget* parent); + void retranslateUi(); - private: - // Load the settings from the resource file + /** Loads the settings from the resource file. */ void loadDialogSettings(); - // Save the settings to the resource file - void saveDialogSettings(); - + /** Saves the settings to the resource file. */ + void saveDialogSettings() const; -//signals: -// void swordSetupChanged(); }; diff --git a/src/frontend/bookshelfmanager/cswordsetupinstallsourcesdialog.cpp b/src/frontend/bookshelfmanager/cswordsetupinstallsourcesdialog.cpp index 14aecb9..f40d8c3 100644 --- a/src/frontend/bookshelfmanager/cswordsetupinstallsourcesdialog.cpp +++ b/src/frontend/bookshelfmanager/cswordsetupinstallsourcesdialog.cpp @@ -24,7 +24,6 @@ #include <QDialogButtonBox> #include <QProgressDialog> #include <QApplication> -#include <QDebug> #include "backend/btinstallbackend.h" #include "util/dialogutil.h" @@ -157,7 +156,6 @@ void CSwordSetupInstallSourcesDialog::slotGetListClicked() { if (answer == QMessageBox::No) { return; } - qDebug() << "Ok, create installmgr"; BtInstallMgr iMgr; m_progressDialog = new QProgressDialog("", tr("Cancel"), 0 , 100, this); @@ -174,11 +172,9 @@ void CSwordSetupInstallSourcesDialog::slotGetListClicked() { m_progressDialog->setLabelText(tr("Connecting...")); m_progressDialog->setValue(0); qApp->processEvents(); - qWarning() << "Start downloading the list of sources"; int ret = iMgr.refreshRemoteSourceConfiguration(); if ( !ret ) { //make sure the sources were updated sucessfully - qDebug() << "download succeeded"; m_progressDialog->setValue(100); //make sure the dialog closes m_remoteListAdded = true; accept(); diff --git a/src/frontend/bookshelfmanager/indexpage/btindexpage.cpp b/src/frontend/bookshelfmanager/indexpage/btindexpage.cpp index 026aad5..960f5c8 100644 --- a/src/frontend/bookshelfmanager/indexpage/btindexpage.cpp +++ b/src/frontend/bookshelfmanager/indexpage/btindexpage.cpp @@ -19,24 +19,22 @@ #include "backend/config/cbtconfig.h" #include "backend/drivers/cswordmoduleinfo.h" #include "backend/managers/cswordbackend.h" +#include "frontend/bookshelfmanager/btmodulemanagerdialog.h" #include "frontend/btmoduleindexdialog.h" #include "util/directory.h" #include "util/cresmgr.h" #include "util/tool.h" -BtIndexPage::BtIndexPage(QWidget *parent) - : BtConfigPage(parent) +BtIndexPage::BtIndexPage(BtModuleManagerDialog *parent) + : BtConfigDialog::Page(util::directory::getIcon(CResMgr::bookshelfmgr::indexpage::icon), parent) { namespace DU = util::directory; - Q_ASSERT(qobject_cast<QVBoxLayout*>(layout()) != 0); - QVBoxLayout *vboxLayout = static_cast<QVBoxLayout*>(layout()); + QVBoxLayout *vboxLayout = new QVBoxLayout(this); QHBoxLayout *hboxLayout; m_autoDeleteOrphanedIndicesBox = new QCheckBox(this); - m_autoDeleteOrphanedIndicesBox->setToolTip(tr("If selected, those indexes which have no corresponding work will be deleted when BibleTime starts")); - m_autoDeleteOrphanedIndicesBox->setText(tr("Automatically delete orphaned indexes when BibleTime starts")); vboxLayout->addWidget(m_autoDeleteOrphanedIndicesBox); m_moduleList = new QTreeWidget(this); @@ -48,19 +46,15 @@ BtIndexPage::BtIndexPage(QWidget *parent) hboxLayout->addItem(spacerItem); m_deleteButton = new QPushButton(this); - m_deleteButton->setToolTip(tr("Delete the selected indexes")); - m_deleteButton->setText(tr("Delete")); hboxLayout->addWidget(m_deleteButton); m_createButton = new QPushButton(this); - m_createButton->setToolTip(tr("Create new indexes for the selected works")); - m_createButton->setText(tr("Create...")); hboxLayout->addWidget(m_createButton); vboxLayout->addLayout(hboxLayout); // configure the list view - m_moduleList->setHeaderLabels( (QStringList(tr("Work")) << tr("Index size")) ); + m_moduleList->setHeaderLabels( (QStringList(tr("Work")) << tr("Index size")) ); /// \todo Move to retranslateUi() m_moduleList->setRootIsDecorated(true); m_moduleList->setColumnWidth(0, util::tool::mWidth(m_moduleList, 20) ); //m_moduleList->setTextAlignment(1, Qt::AlignRight); see doc... @@ -73,26 +67,20 @@ BtIndexPage::BtIndexPage(QWidget *parent) m_deleteButton->setIcon(DU::getIcon(CResMgr::bookshelfmgr::indexpage::delete_icon)); // connect our signals/slots - connect(m_createButton, SIGNAL(clicked()), this, SLOT(createIndices())); - connect(m_deleteButton, SIGNAL(clicked()), this, SLOT(deleteIndices())); - connect(CSwordBackend::instance(), SIGNAL(sigSwordSetupChanged(CSwordBackend::SetupChangedReason)), SLOT(slotSwordSetupChanged())); - - populateModuleList(); + connect(m_createButton, SIGNAL(clicked()), + this, SLOT(createIndices())); + connect(m_deleteButton, SIGNAL(clicked()), + this, SLOT(deleteIndices())); + connect(CSwordBackend::instance(), SIGNAL(sigSwordSetupChanged(CSwordBackend::SetupChangedReason)), + this, SLOT(slotSwordSetupChanged())); + + retranslateUi(); // also calls populateModuleList(); } BtIndexPage::~BtIndexPage() { CBTConfig::set( CBTConfig::autoDeleteOrphanedIndices, m_autoDeleteOrphanedIndicesBox->isChecked() ); } -const QIcon &BtIndexPage::icon() const { - return util::directory::getIcon(CResMgr::bookshelfmgr::indexpage::icon); -} - -QString BtIndexPage::header() const { - return tr("Search Indexes"); -} - - /** Populates the module list with installed modules and orphaned indices */ void BtIndexPage::populateModuleList() { typedef QList<CSwordModuleInfo*>::const_iterator MLCI; @@ -110,8 +98,6 @@ void BtIndexPage::populateModuleList() { m_modsWithoutIndices->setFlags(Qt::ItemIsUserCheckable | Qt::ItemIsEnabled | Qt::ItemIsTristate); m_modsWithoutIndices->setExpanded(true); - - const QList<CSwordModuleInfo*> &modules(CSwordBackend::instance()->moduleList()); for (MLCI it(modules.begin()); it != modules.end(); ++it) { QTreeWidgetItem* item = 0; @@ -119,20 +105,35 @@ void BtIndexPage::populateModuleList() { if ((*it)->hasIndex()) { item = new QTreeWidgetItem(m_modsWithIndices); item->setText(0, (*it)->name()); - item->setText(1, QString("%1 ").arg((*it)->indexSize() / 1024) + tr("KiB")); + item->setText(1, tr("%1 KiB").arg((*it)->indexSize() / 1024)); item->setFlags(Qt::ItemIsUserCheckable | Qt::ItemIsEnabled); item->setCheckState(0, Qt::Unchecked); } else { item = new QTreeWidgetItem(m_modsWithoutIndices); item->setText(0, (*it)->name()); - item->setText(1, QString("0 ") + tr("KiB")); + item->setText(1, tr("0 KiB")); item->setFlags(Qt::ItemIsUserCheckable | Qt::ItemIsEnabled); item->setCheckState(0, Qt::Checked); } } } +void BtIndexPage::retranslateUi() { + setHeaderText(tr("Search Indexes")); + + m_autoDeleteOrphanedIndicesBox->setToolTip(tr("If selected, those indexes which have no corresponding work will be deleted when BibleTime starts")); + m_autoDeleteOrphanedIndicesBox->setText(tr("Automatically delete orphaned indexes when BibleTime starts")); + + m_deleteButton->setToolTip(tr("Delete the selected indexes")); + m_deleteButton->setText(tr("Delete")); + + m_createButton->setToolTip(tr("Create new indexes for the selected works")); + m_createButton->setText(tr("Create...")); + + populateModuleList(); +} + /** Creates indices for selected modules if no index currently exists */ void BtIndexPage::createIndices() { bool indicesCreated = false; diff --git a/src/frontend/bookshelfmanager/indexpage/btindexpage.h b/src/frontend/bookshelfmanager/indexpage/btindexpage.h index 89a7e35..303c6ab 100644 --- a/src/frontend/bookshelfmanager/indexpage/btindexpage.h +++ b/src/frontend/bookshelfmanager/indexpage/btindexpage.h @@ -13,27 +13,26 @@ #include "frontend/bookshelfmanager/btconfigdialog.h" +class BtModuleManagerDialog; class QCheckBox; class QTreeWidget; class QTreeWidgetItem; +/** \todo add void retranslateUi(); */ + /** * This class encapsulates the "Manage search indices" page of the Bookshelf * Manager. It allows for creation and deletion of search indicies for each * installed module. It also allows for deletion of orphaned indices. */ -class BtIndexPage : public BtConfigPage { +class BtIndexPage: public BtConfigDialog::Page { + Q_OBJECT public: - BtIndexPage(QWidget *parent = 0); - ~BtIndexPage(); - - /** Reimplemented from BtConfigPage. */ - virtual QString header() const; - /** Reimplemented from BtConfigPage. */ - virtual const QIcon &icon() const; + BtIndexPage(BtModuleManagerDialog *parent = 0); + ~BtIndexPage(); public slots: void slotSwordSetupChanged(); @@ -45,7 +44,7 @@ class BtIndexPage : public BtConfigPage { */ void populateModuleList(); - + void retranslateUi(); public slots: /** @@ -66,6 +65,7 @@ class BtIndexPage : public BtConfigPage { QTreeWidgetItem* m_modsWithIndices; QTreeWidgetItem* m_modsWithoutIndices; + }; diff --git a/src/frontend/bookshelfmanager/installpage/btinstallpage.cpp b/src/frontend/bookshelfmanager/installpage/btinstallpage.cpp index d3bac59..9c7955a 100644 --- a/src/frontend/bookshelfmanager/installpage/btinstallpage.cpp +++ b/src/frontend/bookshelfmanager/installpage/btinstallpage.cpp @@ -46,8 +46,8 @@ const QString selectedModuleKey("GUI/BookshelfManager/InstallPage/selectedModule // *********** Config dialog page: Install/Update ********** // ********************************************************* -BtInstallPage::BtInstallPage(QWidget *parent) - : BtConfigPage(parent) +BtInstallPage::BtInstallPage(BtModuleManagerDialog *parent) + : BtConfigDialog::Page(util::directory::getIcon(CResMgr::bookshelfmgr::installpage::icon), parent) , m_groupingOrder(groupingOrderKey) , m_modulesSelected(0) , m_modulesSelectedSources(0) @@ -58,10 +58,11 @@ BtInstallPage::BtInstallPage(QWidget *parent) // Initialize widgets: initView(); initConnections(); + + retranslateUi(); } void BtInstallPage::setInstallEnabled(bool b) { - qDebug() << "void BtInstallPage::setInstallEnabled(bool b) start"; m_installButton->setEnabled(b); } @@ -73,36 +74,31 @@ void BtInstallPage::initView() { namespace DU = util::directory; // Warning label: - - m_warningLabel = util::tool::explanationLabel(this, tr("WARNING!!!"), - tr("If you live in a persecuted country and don't want to risk " - "detection don't use remote sources.")); + m_warningLabel = new QLabel(this); // Source chooser: - m_sourceGroupBox = new QGroupBox(tr("Select installation &source:"), this); + m_sourceGroupBox = new QGroupBox(this); m_sourceGroupBox->setFlat(true); m_sourceComboBox = new QComboBox(this); m_sourceComboBox->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Minimum); initSourcesCombo(); - m_sourceAddButton = new QPushButton(tr("&Add...")); - m_sourceAddButton ->setToolTip(tr("Add new source")); + m_sourceAddButton = new QPushButton(this); m_sourceAddButton ->setIcon(DU::getIcon(CResMgr::bookshelfmgr::installpage::add_icon)); - m_sourceDeleteButton = new QPushButton(tr("&Delete...")); - m_sourceDeleteButton->setToolTip(tr("Delete this source")); + m_sourceDeleteButton = new QPushButton(this); m_sourceDeleteButton->setIcon(DU::getIcon(CResMgr::bookshelfmgr::installpage::delete_icon)); QHBoxLayout *sourceChooserLayout = new QHBoxLayout(); - sourceChooserLayout->setContentsMargins(0, 0, 0, 0); + sourceChooserLayout->setContentsMargins(0, 8, 0, 0); sourceChooserLayout->addWidget(m_sourceComboBox, 1); sourceChooserLayout->addWidget(m_sourceAddButton); sourceChooserLayout->addWidget(m_sourceDeleteButton); m_sourceGroupBox->setLayout(sourceChooserLayout); // Works chooser: - m_worksGroupBox = new QGroupBox(tr("Select &works to install:"), this); + m_worksGroupBox = new QGroupBox(this); m_worksGroupBox->setFlat(true); m_worksLayout = new QStackedLayout(); m_worksGroupBox->setLayout(m_worksLayout); @@ -113,35 +109,31 @@ void BtInstallPage::initView() { m_installGroupBox->setFlat(true); retranslateInstallGroupBox(); - m_pathLabel = new QLabel(tr("Install &folder:")); + m_pathLabel = new QLabel(this); m_pathCombo = new QComboBox(this); m_pathCombo->setMinimumContentsLength(20); m_pathCombo->setSizeAdjustPolicy(QComboBox::AdjustToMinimumContentsLengthWithIcon); m_pathCombo->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Minimum); - m_pathCombo->setToolTip(tr("The folder where the new works will be installed")); m_pathCombo->view()->setTextElideMode(Qt::ElideMiddle); m_pathLabel->setBuddy(m_pathCombo); initPathCombo(); m_configurePathButton = new QToolButton(this); - m_configurePathButton->setToolTip(tr("Configure folders where works are installed and found")); m_configurePathButton->setIcon(DU::getIcon(CResMgr::bookshelfmgr::installpage::path_icon)); - m_installButton = new QPushButton(tr("&Install..."), this); - m_installButton->setToolTip(tr("Install or update selected works")); + m_installButton = new QPushButton(this); m_installButton->setIcon(DU::getIcon(CResMgr::bookshelfmgr::installpage::install_icon)); m_installButton->setEnabled(false); QHBoxLayout *pathLayout = new QHBoxLayout(); - pathLayout->setContentsMargins(0, 0, 0, 0); + pathLayout->setContentsMargins(0, 8, 0, 0); pathLayout->addWidget(m_pathLabel); pathLayout->addWidget(m_pathCombo); pathLayout->addWidget(m_configurePathButton); pathLayout->addWidget(m_installButton); m_installGroupBox->setLayout(pathLayout); - Q_ASSERT(qobject_cast<QVBoxLayout*>(layout()) != 0); - QVBoxLayout *mainLayout = static_cast<QVBoxLayout*>(layout()); + QVBoxLayout *mainLayout = new QVBoxLayout(this); mainLayout->addWidget(m_warningLabel); mainLayout->addWidget(m_sourceGroupBox); mainLayout->addWidget(m_worksGroupBox, 1); @@ -232,11 +224,10 @@ void BtInstallPage::initSourcesCombo() { } void BtInstallPage::activateSource(const sword::InstallSource &src) { - qDebug() << "Selected source" << src.caption; qApp->setOverrideCursor(Qt::WaitCursor); BtInstallPageWorksWidget *w = m_sourceMap.value(QString(src.caption), 0); if (w == 0) { - if (parentDialog() != 0) parentDialog()->setEnabled(false); + window()->setEnabled(false); qApp->processEvents(); w = new BtInstallPageWorksWidget(src, m_groupingOrder, this); m_sourceMap.insert(QString(src.caption), w); @@ -245,7 +236,7 @@ void BtInstallPage::activateSource(const sword::InstallSource &src) { this, SLOT(slotGroupingOrderChanged(const BtBookshelfTreeModel::Grouping&))); connect(w->treeModel(), SIGNAL(moduleChecked(CSwordModuleInfo*,bool)), this, SLOT(slotSelectedModulesChanged())); - if (parentDialog() != 0) parentDialog()->setEnabled(true); + window()->setEnabled(true); } else { disconnect(w->treeView()->header(), SIGNAL(geometriesChanged()), this, SLOT(slotHeaderChanged())); @@ -268,6 +259,30 @@ void BtInstallPage::retranslateInstallGroupBox() { } } +void BtInstallPage::retranslateUi() { + setHeaderText(tr("Install/Update")); + + util::tool::initExplanationLabel(m_warningLabel, tr("WARNING!!!"), + tr("If you live in a persecuted country and don't want to risk " + "detection don't use remote sources.")); + + m_sourceGroupBox->setTitle(tr("Select installation &source:")); + m_sourceAddButton->setText(tr("&Add...")); + m_sourceAddButton ->setToolTip(tr("Add new source")); + m_sourceDeleteButton->setText(tr("&Delete...")); + m_sourceDeleteButton->setToolTip(tr("Delete this source")); + + m_worksGroupBox->setTitle(tr("Select &works to install:")); + + m_pathLabel->setText(tr("Install &folder:")); + m_pathCombo->setToolTip(tr("The folder where the new works will be installed")); + m_configurePathButton->setToolTip(tr("Configure folders where works are installed and found")); + m_installButton->setText(tr("&Install...")); + m_installButton->setToolTip(tr("Install or update selected works")); + + retranslateInstallGroupBox(); +} + void BtInstallPage::slotGroupingOrderChanged(const BtBookshelfTreeModel::Grouping &g) { m_groupingOrder = g; m_groupingOrder.saveTo(groupingOrderKey); @@ -282,8 +297,6 @@ void BtInstallPage::slotHeaderChanged() { } void BtInstallPage::slotInstall() { - qDebug() << "BtInstallPage::slotInstall"; - // check that the destination path is writable, do nothing if not and user doesn't want to continue QDir dir = selectedInstallPath(); bool canWrite = true; @@ -319,23 +332,20 @@ void BtInstallPage::slotInstall() { cm.insert(m); } - if (cm.empty()) return; + if (cm.empty()) + return; /// \todo first remove all modules which will be updated from the module list // but what modules? all with the same real name? (there may be _n modules...) - BtModuleManagerDialog *parentDlg = dynamic_cast<BtModuleManagerDialog*>(parentDialog()); - - BtInstallProgressDialog *dlg = new BtInstallProgressDialog(cm, selectedInstallPath(), parentDlg); - - if (!parentDlg) qDebug() << "error, wrong parent!"; + // progressDialog is WA_DeleteOnClose + BtInstallProgressDialog *progressDialog = new BtInstallProgressDialog(cm, selectedInstallPath(), this); m_installButton->setEnabled(false); // the progress dialog is now modal, it can be made modeless later. - dlg->exec(); + progressDialog->exec(); - qDebug() << "BtSourceWidget::slotInstallAccepted end"; } delete dlg; } @@ -358,7 +368,10 @@ void BtInstallPage::slotSourceAdd() { QSharedPointer<SSISD> dlg(new SSISD()); if (dlg->exec() == QDialog::Accepted) { - if (!dlg->wasRemoteListAdded()) { + if (dlg->wasRemoteListAdded()) { + initSourcesCombo(); + } + else { sword::InstallSource newSource = dlg->getSource(); if ( !((QString)newSource.type.c_str()).isEmpty() ) { // we have a valid source to add BtInstallBackend::addSource(newSource); @@ -415,16 +428,6 @@ void BtInstallPage::slotSelectedModulesChanged() { retranslateInstallGroupBox(); } -// implement the BtConfigPage methods - -const QIcon &BtInstallPage::icon() const { - return util::directory::getIcon(CResMgr::bookshelfmgr::installpage::icon); -} - -QString BtInstallPage::header() const { - return tr("Install/Update"); -} - void BtInstallPage::slotSwordSetupChanged() { QString moduleName = m_sourceComboBox->currentText(); diff --git a/src/frontend/bookshelfmanager/installpage/btinstallpage.h b/src/frontend/bookshelfmanager/installpage/btinstallpage.h index 88d1f92..0cb6724 100644 --- a/src/frontend/bookshelfmanager/installpage/btinstallpage.h +++ b/src/frontend/bookshelfmanager/installpage/btinstallpage.h @@ -20,8 +20,10 @@ class InstallSource; } class BtInstallPageWorksWidget; +class BtModuleManagerDialog; class QComboBox; class QGroupBox; +class QLabel; class QPushButton; class QStackedLayout; class QToolButton; @@ -29,17 +31,13 @@ class QToolButton; /** * The Install page includes module path chooser, source/module handler and install button. */ -class BtInstallPage: public BtConfigPage { +class BtInstallPage: public BtConfigDialog::Page { + Q_OBJECT public: - BtInstallPage(QWidget *parent = 0); - - /** Reimplemented from BtConfigPage. */ - virtual const QIcon &icon() const; - /** Reimplemented from BtConfigPage. */ - virtual QString header() const; + BtInstallPage(BtModuleManagerDialog *parent = 0); void setInstallEnabled(bool b); @@ -48,6 +46,10 @@ class BtInstallPage: public BtConfigPage { public slots: void slotSwordSetupChanged(); + protected: + + void retranslateUi(); + private: void initView(); void initConnections(); diff --git a/src/frontend/bookshelfmanager/installpage/btinstallpageworkswidget.cpp b/src/frontend/bookshelfmanager/installpage/btinstallpageworkswidget.cpp index 6b9fb53..0bb8829 100644 --- a/src/frontend/bookshelfmanager/installpage/btinstallpageworkswidget.cpp +++ b/src/frontend/bookshelfmanager/installpage/btinstallpageworkswidget.cpp @@ -57,8 +57,6 @@ BtInstallPageWorksWidget::BtInstallPageWorksWidget( { namespace DU = util::directory; - qDebug() << "Creating new BtInstallPageWorksWidget for source" << source.caption; - setTreeModel(new BtInstallPageModel(g, this)); treeView()->setHeaderHidden(false); @@ -79,8 +77,6 @@ BtInstallPageWorksWidget::BtInstallPageWorksWidget( } BtInstallPageWorksWidget::~BtInstallPageWorksWidget() { - qDebug() << "Deleting BtInstallPageWorksWidget for source" << m_source.caption; - delete m_backend; } diff --git a/src/frontend/bookshelfmanager/installpage/btinstallpathdialog.cpp b/src/frontend/bookshelfmanager/installpage/btinstallpathdialog.cpp index a272d89..b4deb51 100644 --- a/src/frontend/bookshelfmanager/installpage/btinstallpathdialog.cpp +++ b/src/frontend/bookshelfmanager/installpage/btinstallpathdialog.cpp @@ -120,7 +120,6 @@ BtInstallPathDialog::~BtInstallPathDialog() { } void BtInstallPathDialog::updateTopLevelItems() { - qDebug() << "BtInstallPathDialog::updateTopLevelItems"; if (m_writableItem->childCount()) { m_writableItem->setHidden(false); m_swordPathListBox->expandItem(m_writableItem); @@ -209,18 +208,14 @@ void BtInstallPathDialog::slotAddClicked() { } void BtInstallPathDialog::slotRemoveClicked() { - qDebug() << "BtInstallPathDialog::slotRemoveClicked"; QTreeWidgetItem* i = m_swordPathListBox->selectedItems().value(0); - qDebug() << i; if (i && i->parent() != m_swordPathListBox->invisibleRootItem()) { - qDebug() << "delete" << i; delete i; } updateTopLevelItems(); } void BtInstallPathDialog::writeSwordConfig() { - qDebug() << "BtInstallPathDialog::writeSwordConfig"; QStringList targets; QTreeWidgetItemIterator it(m_swordPathListBox, QTreeWidgetItemIterator::NoChildren | QTreeWidgetItemIterator::Enabled | QTreeWidgetItemIterator::NotHidden); while (*it) { diff --git a/src/frontend/bookshelfmanager/installpage/btinstallprogressdialog.cpp b/src/frontend/bookshelfmanager/installpage/btinstallprogressdialog.cpp index 465ec03..288be4e 100644 --- a/src/frontend/bookshelfmanager/installpage/btinstallprogressdialog.cpp +++ b/src/frontend/bookshelfmanager/installpage/btinstallprogressdialog.cpp @@ -91,13 +91,11 @@ void BtInstallProgressDialog::startThreads() { //foreach (QString mName, m_threadsByModule.keys()) { //} //QList<CSwordModuleInfo*> CSwordBackend::instance()()->takeModulesFromList(m_threadsByModule.keys()); - qDebug() << "start threads..."; //loop through the multimap of the waiting threads, start at most 3 threads for each source QMultiMap<QString, BtInstallThread*>::iterator threadIterator = m_waitingThreads.end(); // concurrency is disabled for now // while (threadIterator != m_waitingThreads.end()) { // QString sourceName = threadIterator.key(); -// qDebug() << sourceName; // if (m_runningThreads.values(sourceName).count() < 3) { // BtInstallThread* t = threadIterator.value(); // m_runningThreads.insert(sourceName, t); @@ -117,13 +115,8 @@ void BtInstallProgressDialog::startThreads() { threadIterator = m_waitingThreads.erase(threadIterator); t->start(); } - - qDebug() << "BtInstallProgressDialog::startThreads end"; } -BtInstallProgressDialog::~BtInstallProgressDialog() {} - - void BtInstallProgressDialog::slotOneItemCompleted(QString module, QString source, int status) { QString message; //status comes from the sword installer. @@ -156,9 +149,7 @@ void BtInstallProgressDialog::oneItemStoppedOrCompleted(QString module, QString //concurrency is disabled for now // //start a waiting thread if there are any // QList<BtInstallThread*> threadsForSource = m_waitingThreads.values(source); -// qDebug() << threadsForSource; // if (!threadsForSource.isEmpty()) { -// qDebug() << "Threads are waiting for turn"; // BtInstallThread* thread = threadsForSource.at(0); // m_waitingThreads.remove(source, thread); // m_runningThreads.insert(source, thread); @@ -167,7 +158,7 @@ void BtInstallProgressDialog::oneItemStoppedOrCompleted(QString module, QString //non-concurrent QMultiMap<QString, BtInstallThread*>::iterator threadIterator = m_waitingThreads.end(); - if (m_runningThreads.size() == 0 && threadIterator != m_waitingThreads.begin()) { + if (m_runningThreads.isEmpty() && threadIterator != m_waitingThreads.begin()) { threadIterator--; // the last item QString sourceName = threadIterator.key(); BtInstallThread* t = threadIterator.value(); @@ -199,8 +190,6 @@ void BtInstallProgressDialog::slotStopInstall() { } void BtInstallProgressDialog::slotStatusUpdated(QString module, int status) { - //qDebug() << "BtInstallProgressDialog::slotStatusUpdated"; - //qDebug() << "module:" << module << "status:" << status; // find the progress bar for this module and update the value QWidget* itemWidget = m_statusWidget->itemWidget(getItem(module) , 1); QProgressBar* bar = dynamic_cast<QProgressBar*>(itemWidget); @@ -212,7 +201,6 @@ void BtInstallProgressDialog::slotInstallStarted(QString module, QString) { } void BtInstallProgressDialog::slotDownloadStarted(QString module) { - qDebug() << "BtInstallProgressDialog::slotDownloadStarted" << module; getItem(module)->setText(1, QString::null); //m_statusWidget->itemWidget(getItem(module), 1)->setVisible(true); @@ -223,13 +211,10 @@ void BtInstallProgressDialog::slotDownloadStarted(QString module) { } QTreeWidgetItem* BtInstallProgressDialog::getItem(QString moduleName) { - //qDebug() << "BtInstallProgressDialog::getItem" << moduleName; return m_statusWidget->findItems(moduleName, Qt::MatchExactly).at(0); } void BtInstallProgressDialog::closeEvent(QCloseEvent* event) { - qDebug() << "BtInstallProgressDialog::closeEvent"; - if (event->spontaneous()) { event->ignore(); return; @@ -239,5 +224,5 @@ void BtInstallProgressDialog::closeEvent(QCloseEvent* event) { } bool BtInstallProgressDialog::threadsDone() { - return (m_waitingThreads.count() == 0 && m_runningThreads.count() == 0); + return (m_waitingThreads.isEmpty() && m_runningThreads.isEmpty()); } diff --git a/src/frontend/bookshelfmanager/installpage/btinstallprogressdialog.h b/src/frontend/bookshelfmanager/installpage/btinstallprogressdialog.h index 8b990ad..a72b280 100644 --- a/src/frontend/bookshelfmanager/installpage/btinstallprogressdialog.h +++ b/src/frontend/bookshelfmanager/installpage/btinstallprogressdialog.h @@ -28,8 +28,6 @@ class BtInstallProgressDialog : public QDialog { const QString &destination, QWidget *parent = 0, Qt::WindowFlags flags = 0); - ~BtInstallProgressDialog(); - public slots: void slotOneItemCompleted(QString module, QString source, int status); void slotOneItemStopped(QString module, QString source); diff --git a/src/frontend/bookshelfmanager/installpage/btinstallthread.cpp b/src/frontend/bookshelfmanager/installpage/btinstallthread.cpp index 2d04a51..3b25f02 100644 --- a/src/frontend/bookshelfmanager/installpage/btinstallthread.cpp +++ b/src/frontend/bookshelfmanager/installpage/btinstallthread.cpp @@ -75,7 +75,6 @@ void BtInstallThread::run() { sword::SWMgr lMgr( m_destination.toLatin1() ); if (BtInstallBackend::isRemote(*m_installSource)) { - qDebug() << "calling install"; int status = m_iMgr->installModule(&lMgr, 0, m_module.toLatin1(), m_installSource.data()); if (status != 0) { qWarning() << "Error with install: " << status << "module:" << m_module; @@ -109,7 +108,6 @@ void BtInstallThread::slotStopInstall() { qDebug() << "*********************************\nBtInstallThread::slotStopInstall, installing" << m_module << "was cancelled\n**************************************"; m_iMgr->terminate(); //this->terminate(); // It's dangerous to forcibly stop, but we will clean up the files - qDebug() << "BtInstallThread::slotStopInstall 2"; //qApp->processEvents(); // wait to terminate for some secs. We rather let the execution go on and cleaning up to fail than the app to freeze int notRun = this->wait(25000); @@ -120,11 +118,9 @@ void BtInstallThread::slotStopInstall() { delete m_iMgr; // this makes sure the ftp library will be cleaned up in the destroyer m_iMgr = 0; } - qDebug() << "BtInstallThread::slotStopInstall 3"; // cleanup: remove the module, remove the temp files // if installation has already started if (m_installSource.data() != 0) { - qDebug() << "BtInstallThread::slotStopInstall 4"; // remove the installed module, just to be sure because mgr may // have been terminated when copying files removeModule(); @@ -136,17 +132,14 @@ void BtInstallThread::slotStopInstall() { } void BtInstallThread::slotManagerStatusUpdated(int totalProgress, int /*fileProgress*/) { - //qDebug() << "BtInstallThread::slotManagerStatusUpdated"; emit statusUpdated(m_module, totalProgress); } void BtInstallThread::slotDownloadStarted() { - qDebug() << "BtInstallThread::slotDownloadStarted"; emit downloadStarted(m_module); } void BtInstallThread::removeModule() { - qDebug() << "BtInstallThread::removeModule start"; CSwordModuleInfo* m; m = CSwordBackend::instance()->findModuleByName(m_module); if (!m) { @@ -177,8 +170,6 @@ void BtInstallThread::removeModule() { } void BtInstallThread::removeTempFiles() { - qDebug() << "BtInstallThread::removeTempFiles start"; - // (take the remote conf file for this module, take DataPath, // take the absolute path of the InstallMgr) diff --git a/src/frontend/bookshelfmanager/installpage/btrefreshprogressdialog.cpp b/src/frontend/bookshelfmanager/installpage/btrefreshprogressdialog.cpp index 3666888..949c82e 100644 --- a/src/frontend/bookshelfmanager/installpage/btrefreshprogressdialog.cpp +++ b/src/frontend/bookshelfmanager/installpage/btrefreshprogressdialog.cpp @@ -1,7 +1,6 @@ #include "frontend/bookshelfmanager/installpage/btrefreshprogressdialog.h" #include <QApplication> -#include <QDebug> #include "backend/btinstallbackend.h" #include "util/dialogutil.h" @@ -12,8 +11,6 @@ BtRefreshProgressDialog::BtRefreshProgressDialog(sword::InstallSource &source, : QProgressDialog(parent, flags) , m_source(source) { - qDebug() << "Creating BtRefreshProgressDialog for source" << source.caption; - Q_ASSERT(BtInstallBackend::isRemote(source)); setWindowTitle(tr("Refreshing source %1").arg(QString(source.caption))); setCancelButtonText(tr("&Cancel")); @@ -31,21 +28,15 @@ BtRefreshProgressDialog::BtRefreshProgressDialog(sword::InstallSource &source, } void BtRefreshProgressDialog::slotPercentCompleted(int, int current) { - qDebug() << "BtRefreshProgressDialog progress:" << current; - setValue(current); qApp->processEvents(); } void BtRefreshProgressDialog::slotCanceled() { - qDebug() << "BtRefreshProgressDialog cancel clicked."; - m_installMgr.terminate(); } bool BtRefreshProgressDialog::runAndDelete() { - qDebug() << "BtRefreshProgressDialog runAndDelete()"; - show(); qApp->processEvents(); bool r = (m_installMgr.refreshRemoteSource(&m_source) == 0); diff --git a/src/frontend/bookshelfmanager/removepage/btremovepage.cpp b/src/frontend/bookshelfmanager/removepage/btremovepage.cpp index a19ab89..6c664a8 100644 --- a/src/frontend/bookshelfmanager/removepage/btremovepage.cpp +++ b/src/frontend/bookshelfmanager/removepage/btremovepage.cpp @@ -13,6 +13,7 @@ #include "frontend/bookshelfmanager/removepage/btremovepage.h" #include <QAction> +#include <QDebug> #include <QGroupBox> #include <QHBoxLayout> #include <QHeaderView> @@ -22,6 +23,7 @@ #include <QVBoxLayout> #include "backend/bookshelfmodel/btbookshelffiltermodel.h" #include "backend/managers/cswordbackend.h" +#include "frontend/bookshelfmanager/btmodulemanagerdialog.h" #include "frontend/btbookshelfview.h" #include "frontend/btbookshelfwidget.h" #include "util/cresmgr.h" @@ -37,12 +39,12 @@ namespace { const QString groupingOrderKey("GUI/BookshelfManager/RemovePage/grouping"); } -BtRemovePage::BtRemovePage(QWidget *parent) - : BtConfigPage(parent) +BtRemovePage::BtRemovePage(BtModuleManagerDialog *parent) + : BtConfigDialog::Page(util::directory::getIcon(CResMgr::bookshelfmgr::removepage::icon), parent) { namespace DU = util::directory; - m_worksGroupBox = new QGroupBox(tr("Select &works to uninstall:"), this); + m_worksGroupBox = new QGroupBox(this); m_worksGroupBox->setFlat(true); QVBoxLayout *wLayout = new QVBoxLayout; wLayout->setContentsMargins(0, 0, 0, 0); @@ -65,20 +67,17 @@ BtRemovePage::BtRemovePage(QWidget *parent) m_uninstallGroupBox = new QGroupBox(this); m_uninstallGroupBox->setFlat(true); - retranslateUninstallGroupBox(); QHBoxLayout *uLayout = new QHBoxLayout; uLayout->setContentsMargins(0, 0, 0, 0); m_uninstallGroupBox->setLayout(uLayout); uLayout->addStretch(1); - m_removeButton = new QPushButton(tr("&Remove..."), this); - m_removeButton->setToolTip(tr("Remove the selected works")); + m_removeButton = new QPushButton(this); m_removeButton->setIcon(DU::getIcon(CResMgr::bookshelfmgr::removepage::remove_icon)); m_removeButton->setEnabled(false); uLayout->addWidget(m_removeButton, 0, Qt::AlignRight); - Q_ASSERT(qobject_cast<QVBoxLayout*>(layout()) != 0); - QVBoxLayout *mainLayout = static_cast<QVBoxLayout*>(layout()); + QVBoxLayout *mainLayout = new QVBoxLayout(this); mainLayout->addWidget(m_worksGroupBox, 1); mainLayout->addWidget(m_uninstallGroupBox); @@ -88,14 +87,19 @@ BtRemovePage::BtRemovePage(QWidget *parent) this, SLOT(slotResetRemoveButton())); connect(m_bookshelfWidget->treeModel(), SIGNAL(rowsRemoved(const QModelIndex&,int,int)), this, SLOT(slotResetRemoveButton())); -} -const QIcon &BtRemovePage::icon() const { - return util::directory::getIcon(CResMgr::bookshelfmgr::removepage::icon); + retranslateUi(); } -QString BtRemovePage::header() const { - return tr("Remove"); +void BtRemovePage::retranslateUi() { + setHeaderText(tr("Remove")); + + m_worksGroupBox->setTitle(tr("Select &works to uninstall:")); + + m_removeButton->setText(tr("&Remove...")); + m_removeButton->setToolTip(tr("Remove the selected works")); + + retranslateUninstallGroupBox(); } void BtRemovePage::retranslateUninstallGroupBox() { @@ -118,6 +122,7 @@ void BtRemovePage::slotRemoveModules() { if (m_bookshelfWidget->treeModel()->checkedModules().empty()) return; QStringList moduleNames; + QStringList prettyModuleNames; const int textHeight = fontMetrics().height(); /// \bug <nobr> is not working, Qt bug const QString moduleString("<nobr><img src=\"%1\" width=\"%2\" height=\"%3\"/> %4</nobr>"); @@ -127,15 +132,16 @@ void BtRemovePage::slotRemoveModules() { { const QIcon icon = CSwordModuleInfo::moduleIcon(m); const QSize iconSize = icon.actualSize(QSize(textHeight, textHeight)); - moduleNames.append(moduleString - .arg(iconDir + CSwordModuleInfo::moduleIconFilename(m)) - .arg(iconSize.width()) - .arg(iconSize.height()) - .arg(m->name())); + prettyModuleNames.append(moduleString + .arg(iconDir + CSwordModuleInfo::moduleIconFilename(m)) + .arg(iconSize.width()) + .arg(iconSize.height()) + .arg(m->name())); + moduleNames.append(m->name()); } const QString message = tr("You selected the following work(s): ") .append("<br/><br/> ") - .append(moduleNames.join(", ")) + .append(prettyModuleNames.join(", ")) .append("<br/><br/>") .append(tr("Do you really want to remove them from your system?")); @@ -143,6 +149,7 @@ void BtRemovePage::slotRemoveModules() { // Update the module list before really removing. Remember deleting the pointers later. QList<CSwordModuleInfo*> toBeDeleted = CSwordBackend::instance()->takeModulesFromList(moduleNames); + Q_ASSERT(toBeDeleted.size() == moduleNames.size()); sword::InstallMgr installMgr; QMap<QString, sword::SWMgr*> mgrDict; //maps config paths to SWMgr objects diff --git a/src/frontend/bookshelfmanager/removepage/btremovepage.h b/src/frontend/bookshelfmanager/removepage/btremovepage.h index 11017d0..02ff88e 100644 --- a/src/frontend/bookshelfmanager/removepage/btremovepage.h +++ b/src/frontend/bookshelfmanager/removepage/btremovepage.h @@ -22,35 +22,40 @@ class BtBookshelfWidget; +class BtModuleManagerDialog; class QGroupBox; class QPushButton; -class BtRemovePage: public BtConfigPage { +class BtRemovePage: public BtConfigDialog::Page { + Q_OBJECT - public: - BtRemovePage(QWidget *parent = 0); + public: /* Methods: */ + + BtRemovePage(BtModuleManagerDialog *parent = 0); + + public: /* Methods: */ - /** Reimplemented from BtConfigPage. */ - virtual QString header() const; + void retranslateUi(); - /** Reimplemented from BtConfigPage. */ - virtual const QIcon &icon() const; + private: /* Methods: */ - private: void retranslateUninstallGroupBox(); private slots: + void slotRemoveModules(); void slotResetRemoveButton(); void slotGroupingOrderChanged(const BtBookshelfTreeModel::Grouping &g); - private: + private: /* Fields: */ + QGroupBox *m_worksGroupBox; BtBookshelfWidget *m_bookshelfWidget; QGroupBox *m_uninstallGroupBox; QPushButton *m_removeButton; + }; #endif diff --git a/src/frontend/btaboutdialog.cpp b/src/frontend/btaboutdialog.cpp index 5b62cf3..60253dd 100644 --- a/src/frontend/btaboutdialog.cpp +++ b/src/frontend/btaboutdialog.cpp @@ -12,6 +12,7 @@ #include <QApplication> #include <QDesktopServices> #include <QDialogButtonBox> +#include <QFontMetrics> #include <QLabel> #include <QTabWidget> #include <QTextStream> @@ -50,16 +51,21 @@ BtAboutDialog::BtAboutDialog(QWidget *parent, Qt::WindowFlags wflags) : QDialog(parent, wflags) { setAttribute(Qt::WA_DeleteOnClose); - resize(550, 340); + resize(640, 380); QVBoxLayout *mainLayout = new QVBoxLayout; QWidget *top = new QWidget(this); QHBoxLayout *topLayout = new QHBoxLayout; - QLabel *iconLabel = new QLabel(this); - iconLabel->setPixmap(QIcon(util::directory::getIconDir().path() + "/bibletime.svg").pixmap(48)); - topLayout->addWidget(iconLabel); - topLayout->addWidget(new QLabel("<h1>BibleTime " BT_VERSION "</h1>"), 1); + m_iconLabel = new QLabel(this); + m_iconLabel->setPixmap(QIcon(util::directory::getIconDir().path() + "/bibletime.svg").pixmap(48)); + topLayout->addWidget(m_iconLabel); + m_versionLabel = new QLabel(this); + QFont font = m_versionLabel->font(); + font.setPointSize(font.pointSize()+6); + font.setBold(true); + m_versionLabel->setFont(font); + topLayout->addWidget(m_versionLabel); top->setLayout(topLayout); mainLayout->addWidget(top, 0, Qt::AlignCenter); @@ -86,6 +92,15 @@ BtAboutDialog::~BtAboutDialog() { // Intentionally empty } +void BtAboutDialog::resizeEvent(QResizeEvent* event) { + QString version = "BibleTime " BT_VERSION; + QFontMetrics fm(m_versionLabel->font()); + int w = width() - m_iconLabel->width() - 80; + QString shortVersion = fm.elidedText(version, Qt::ElideMiddle, w); + m_versionLabel->setText(shortVersion); +} + + void BtAboutDialog::initTab(QWebView *&tab) { tab = new QWebView(this); m_tabWidget->addTab(tab, ""); @@ -126,6 +141,7 @@ void BtAboutDialog::retranslateContributorsTab() { const QString developer(tr("developer")); const QString designer(tr("designer")); + const QString artist(tr("artist")); /**************************************************************************************** *** NB!!! Credits are sorted alphabetically by last name! *** @@ -143,18 +159,19 @@ void BtAboutDialog::retranslateContributorsTab() { MAKE_CONTR(content, "Lee Carpenter", developer) MAKE_CONTR(content, "Jeremy Erickson", tr("packager")) MAKE_CONTR(content, "Troy A. Griffitts", tr("creator of The Sword Project")) - MAKE_CONTR2(content, "Martin Gruner", tr("project manager"), developer) + MAKE_CONTR(content, "Martin Gruner", developer) MAKE_CONTR(content, "Thomas Hagedorn", tr("domain sponsor")) MAKE_CONTR(content, "Bob Harman", tr("howto")) MAKE_CONTR(content, "Gary Holmlund", developer) MAKE_CONTR(content, "Nikolay Igotti", developer) + MAKE_CONTR(content, "Laurent Valentin Jospin", artist) MAKE_CONTR(content, "Eeli Kaikkonnen", developer) MAKE_CONTR(content, "Chris Kujawa", developer) MAKE_CONTR(content, "Mark Lybarger", developer) MAKE_CONTR(content, "Luke Mauldin", developer) MAKE_CONTR(content, "James Ots", designer) - MAKE_CONTR(content, "Andrus Raag", tr("artist")) - MAKE_CONTR(content, "Jaak Ristioja", developer) + MAKE_CONTR(content, "Andrus Raag", artist) + MAKE_CONTR2(content, "Jaak Ristioja", tr("project manager"), developer) MAKE_CONTR(content, "Fred Saalbach", tr("documentation")) MAKE_CONTR(content, "Gary Sims", developer) MAKE_CONTR2(content, "Wolfgang Stradner", tr("tester"), tr("usability expert")) @@ -162,6 +179,7 @@ void BtAboutDialog::retranslateContributorsTab() { MAKE_CONTR(content, "Thorsten Uhlmann", developer) MAKE_CONTR(content, "David White", developer) MAKE_CONTR(content, "Mark Zealey", developer) + MAKE_CONTR(content, "Patrick Sebastian Zimmermann", developer) "</ul><p><b>"; @@ -172,8 +190,10 @@ void BtAboutDialog::retranslateContributorsTab() { content += "</b></p><ul>" "<li>Horatiu Alexe</li>" "<li>Roy Alvear Aguirre</li>" + "<li>Andrew Alfy</li>" "<li>Luis Barron</li>" "<li>Jan Bělohoubek</li>" + "<li>Mário Castanheira</li>" "<li>Chun-shek Chan</li>" "<li>Nouhoun Y. Diarra</li>" "<li>Rafael Fagundes</li>" diff --git a/src/frontend/btaboutdialog.h b/src/frontend/btaboutdialog.h index 34c7bcf..2ad6607 100644 --- a/src/frontend/btaboutdialog.h +++ b/src/frontend/btaboutdialog.h @@ -16,6 +16,7 @@ class QDialogButtonBox; class QTabWidget; class QUrl; class QWebView; +class QLabel; class BtAboutDialog: public QDialog { Q_OBJECT @@ -23,6 +24,9 @@ class BtAboutDialog: public QDialog { BtAboutDialog(QWidget *parent = 0, Qt::WindowFlags wflags = Qt::Dialog); ~BtAboutDialog(); + protected: + virtual void resizeEvent(QResizeEvent* event); + private: void initTab(QWebView *&tab); @@ -38,12 +42,14 @@ class BtAboutDialog: public QDialog { private: QTabWidget *m_tabWidget; - QWebView *m_bibletimeTab; - QWebView *m_contributorsTab; - QWebView *m_swordTab; - QWebView *m_qtTab; - QWebView *m_licenceTab; + QWebView *m_bibletimeTab; + QWebView *m_contributorsTab; + QWebView *m_swordTab; + QWebView *m_qtTab; + QWebView *m_licenceTab; QDialogButtonBox *m_buttonBox; + QLabel *m_iconLabel; + QLabel *m_versionLabel; }; #endif diff --git a/src/frontend/btaboutmoduledialog.cpp b/src/frontend/btaboutmoduledialog.cpp index e4847a6..ab15fb9 100644 --- a/src/frontend/btaboutmoduledialog.cpp +++ b/src/frontend/btaboutmoduledialog.cpp @@ -17,9 +17,11 @@ #include "util/dialogutil.h" -BTAboutModuleDialog::BTAboutModuleDialog(CSwordModuleInfo *moduleInfo, QWidget *parent, +BTAboutModuleDialog::BTAboutModuleDialog(const CSwordModuleInfo *moduleInfo, + QWidget *parent, Qt::WindowFlags flags) - : QDialog(parent, flags), m_moduleInfo(moduleInfo) + : QDialog(parent, flags) + , m_moduleInfo(moduleInfo) { resize(650, 400); QVBoxLayout* vboxLayout = new QVBoxLayout(this); diff --git a/src/frontend/btaboutmoduledialog.h b/src/frontend/btaboutmoduledialog.h index eb4b15c..fda51ea 100644 --- a/src/frontend/btaboutmoduledialog.h +++ b/src/frontend/btaboutmoduledialog.h @@ -19,22 +19,27 @@ class QTextEdit; /** Dialog to show the information about a module. - - @author The BibleTime team <info@bibletime.info> */ class BTAboutModuleDialog: public QDialog { + Q_OBJECT - public: - BTAboutModuleDialog(CSwordModuleInfo *moduleInfo, QWidget *parent = 0, + + public: /* Methods: */ + + BTAboutModuleDialog(const CSwordModuleInfo *moduleInfo, + QWidget *parent = 0, Qt::WindowFlags flags = 0); - protected: + protected: /* Methods: */ + void retranslateUi(); - private: - CSwordModuleInfo *m_moduleInfo; + private: /* Fields: */ + + const CSwordModuleInfo *m_moduleInfo; QTextEdit *m_textEdit; QDialogButtonBox *m_buttons; -}; + +}; /* class BTAboutModuleDialog */ #endif diff --git a/src/frontend/btbookshelfdockwidget.cpp b/src/frontend/btbookshelfdockwidget.cpp index 9159210..2d85930 100644 --- a/src/frontend/btbookshelfdockwidget.cpp +++ b/src/frontend/btbookshelfdockwidget.cpp @@ -18,10 +18,8 @@ #include <QMenu> #include <QMessageBox> #include <QPushButton> -#include <QSettings> #include <QStackedWidget> #include <QVBoxLayout> -#include "backend/config/cbtconfig.h" #include "backend/managers/cswordbackend.h" #include "bibletime.h" #include "frontend/btbookshelfview.h" @@ -59,6 +57,7 @@ BtBookshelfDockWidget::BtBookshelfDockWidget(QWidget *parent, Qt::WindowFlags f) m_bookshelfWidget->setTreeModel(m_treeModel); m_bookshelfWidget->setSourceModel(bookshelfModel); m_bookshelfWidget->setItemContextMenu(m_itemContextMenu); + m_bookshelfWidget->treeView()->setMouseTracking(true); // required for moduleHovered /// \bug The correct grouping action is not selected on startup. // Setup welcome widgets: @@ -84,6 +83,8 @@ BtBookshelfDockWidget::BtBookshelfDockWidget(QWidget *parent, Qt::WindowFlags f) // Connect signals: connect(m_bookshelfWidget->treeView(), SIGNAL(moduleActivated(CSwordModuleInfo*)), this, SLOT(slotModuleActivated(CSwordModuleInfo*))); + connect(m_bookshelfWidget->treeView(), SIGNAL(moduleHovered(CSwordModuleInfo*)), + this, SIGNAL(moduleHovered(CSwordModuleInfo*))); connect(m_treeModel, SIGNAL(moduleChecked(CSwordModuleInfo*, bool)), this, SLOT(slotModuleChecked(CSwordModuleInfo*, bool))); connect(m_treeModel, SIGNAL(groupingOrderChanged(BtBookshelfTreeModel::Grouping)), diff --git a/src/frontend/btbookshelfdockwidget.h b/src/frontend/btbookshelfdockwidget.h index 58a014b..87508f4 100644 --- a/src/frontend/btbookshelfdockwidget.h +++ b/src/frontend/btbookshelfdockwidget.h @@ -38,6 +38,7 @@ class BtBookshelfDockWidget: public QDockWidget { } signals: + void moduleHovered(CSwordModuleInfo *module); void moduleOpenTriggered(CSwordModuleInfo *module); void moduleSearchTriggered(CSwordModuleInfo *module); void moduleEditPlainTriggered(CSwordModuleInfo *module); diff --git a/src/frontend/btbookshelfview.cpp b/src/frontend/btbookshelfview.cpp index 2dfa745..cb0dcd9 100644 --- a/src/frontend/btbookshelfview.cpp +++ b/src/frontend/btbookshelfview.cpp @@ -33,6 +33,8 @@ BtBookshelfView::BtBookshelfView(QWidget *parent) connect(this, SIGNAL(activated(QModelIndex)), this, SLOT(slotItemActivated(QModelIndex))); + connect(this, SIGNAL(entered(QModelIndex)), + this, SLOT(slotItemHovered(QModelIndex))); } BtBookshelfView::~BtBookshelfView() { @@ -106,3 +108,7 @@ void BtBookshelfView::slotItemActivated(const QModelIndex &index) { emit moduleActivated(i); } } + +void BtBookshelfView::slotItemHovered(const QModelIndex &index) { + emit moduleHovered(getModule(index)); +} diff --git a/src/frontend/btbookshelfview.h b/src/frontend/btbookshelfview.h index 916559a..940c084 100644 --- a/src/frontend/btbookshelfview.h +++ b/src/frontend/btbookshelfview.h @@ -31,6 +31,7 @@ class BtBookshelfView: public QTreeView { void moduleContextMenuActivated(CSwordModuleInfo *item, QPoint pos); void moduleActivated(CSwordModuleInfo *item); + void moduleHovered(CSwordModuleInfo *item); protected: void keyPressEvent(QKeyEvent *event); @@ -38,6 +39,7 @@ class BtBookshelfView: public QTreeView { protected slots: void slotItemActivated(const QModelIndex &index); + void slotItemHovered(const QModelIndex &index); }; #endif // BTBOOKSHELFVIEW_H diff --git a/src/frontend/btbookshelfwidget.cpp b/src/frontend/btbookshelfwidget.cpp index d4f162e..c4b0d54 100644 --- a/src/frontend/btbookshelfwidget.cpp +++ b/src/frontend/btbookshelfwidget.cpp @@ -126,7 +126,7 @@ void BtBookshelfWidget::initMenus() { void BtBookshelfWidget::initWidgets() { QVBoxLayout *layout(new QVBoxLayout); - layout->setContentsMargins(0, 0, 0, 0); + layout->setContentsMargins(0, 8, 0, 0); m_toolBar = new QHBoxLayout; // Add a small margin between the edge of the window and the label (looks better) m_toolBar->setContentsMargins(3, 0, 0, 0); diff --git a/src/frontend/btmoduleindexdialog.cpp b/src/frontend/btmoduleindexdialog.cpp index 0fa879e..2dac498 100644 --- a/src/frontend/btmoduleindexdialog.cpp +++ b/src/frontend/btmoduleindexdialog.cpp @@ -65,7 +65,9 @@ bool BtModuleIndexDialog::indexAllModules2( // Single module indexing blocks until finished: setLabelText(tr("Creating index for work: %1").arg(m->name())); - m->buildIndex(); + + if (!m->buildIndex()) success = false; + m_currentModuleIndex++; disconnect(this, SIGNAL(canceled()), @@ -75,10 +77,9 @@ bool BtModuleIndexDialog::indexAllModules2( disconnect(m, SIGNAL(indexingProgress(int)), this, SLOT(slotModuleProgress(int))); - if (wasCanceled()) { - success = false; - break; - } + if (wasCanceled()) success = false; + + if (!success) break; } if (!success) { diff --git a/src/frontend/cdragdrop.cpp b/src/frontend/cdragdrop.cpp deleted file mode 100644 index 657c83e..0000000 --- a/src/frontend/cdragdrop.cpp +++ /dev/null @@ -1,52 +0,0 @@ -/********* -* -* This file is part of BibleTime's source code, http://www.bibletime.info/. -* -* Copyright 1999-2011 by the BibleTime developers. -* The BibleTime source code is licensed under the GNU General Public License version 2.0. -* -**********/ - -#include "frontend/cdragdrop.h" - -#include <QByteArray> -#include <QList> -#include <QMimeData> -#include <QString> - -BTMimeData::BTMimeData() {} - -BTMimeData::~BTMimeData() {} - -/** Creates a new BTMimeData. -* Creates a new bookmark item and appends it to the list. -*/ -BTMimeData::BTMimeData(QString module, QString key, QString description) { - appendBookmark(module, key, description); -} - -/** Creates a new BTMimeData, setting the text MIME type (see QMimeData::setText()). */ -BTMimeData::BTMimeData(QString text) { - setText(text); -} - -/** Appends a new bookmark item into the list.*/ -void BTMimeData::appendBookmark(QString module, QString key, QString description) { - BookmarkItem bm = BookmarkItem(module, key, description); - m_bookmarkList.append(bm); - setData("BibleTime/Bookmark", QByteArray()); -} - - - -/** Returns the first bookmark item in the list. */ -const BookmarkItem& BTMimeData::bookmark() const { - return m_bookmarkList.first(); -} - -BookmarkItem::BookmarkItem(const QString &module, const QString &key, - const QString &description) - : m_moduleName(module), m_key(key), m_description(description) -{ - // Intentionally empty -} diff --git a/src/frontend/cdragdrop.h b/src/frontend/cdragdrop.h index 37b2052..8fa270f 100644 --- a/src/frontend/cdragdrop.h +++ b/src/frontend/cdragdrop.h @@ -11,8 +11,6 @@ #define CDRAGDROP_H #include <QMimeData> -#include <QString> -#include <QStringList> /** @@ -21,30 +19,39 @@ BTMimeData object. */ class BookmarkItem { + friend class BTMimeData; - public: - /** Returns the key */ + + public: /* Methods: */ + + /** \returns the key */ inline const QString &key() const { return m_key; } - /** Returns the module name */ + + /** \returns the module name */ inline const QString &module() const { return m_moduleName; } - /** Returns the bookmark description */ + + /** \returns the bookmark description */ inline const QString &description() const { return m_description; } - protected: + protected: /* Methods: */ + /** Creates a new bookmark item. */ BookmarkItem(const QString &module, const QString &key, - const QString &description); + const QString &description) + : m_moduleName(module), m_key(key), m_description(description) {} + + protected: /* Fields: */ - protected: QString m_moduleName; /**< The module which is used by this item. */ QString m_key; /**< The key of a bookmark. */ QString m_description; /**< The description of a bookmark. */ + }; @@ -56,42 +63,64 @@ class BookmarkItem { * includes also a list of bookmark items. * For further documentation see http://doc.trolltech.com/4.3/dnd.html */ -class BTMimeData : public QMimeData { +class BTMimeData: public QMimeData { + Q_OBJECT - public: + + public: /* Types: */ /** Type for bookmark item list. Usage: BTMimeData::ItemList. */ typedef QList<BookmarkItem> ItemList; - /** Creates a new empty BTMimeData. */ - BTMimeData(); + public: /* Methods: */ - virtual ~BTMimeData(); + /** Creates a new empty BTMimeData. */ + inline BTMimeData() {} /** Creates a new BTMimeData. * Creates a new bookmark item and appends it to the list. * MIME type "BibleTime/Bookmark" is added. * Bookmarks can not be reached by data() method, use bookmark() or bookmarks() instead. */ - BTMimeData(QString module, QString key, QString description); + inline BTMimeData(const QString &module, + const QString &key, + const QString &description) + { + appendBookmark(module, key, description); + } + /** Creates a new BTMimeData, setting the text MIME type (see QMimeData::setText()). */ - BTMimeData(QString text); + inline BTMimeData(const QString &text) { + setText(text); + } /** Appends a new bookmark item into the list. * Creates the item using the arguments. * MIME type "BibleTime/Bookmark" is added. */ - virtual void appendBookmark(QString module, QString key, QString description); - /** Returns the bookmarks list. */ - virtual const ItemList& bookmarks() const { + inline void appendBookmark(const QString &module, + const QString &key, + const QString &description) + { + m_bookmarkList.append(BookmarkItem(module, key, description)); + setData("BibleTime/Bookmark", QByteArray()); + } + + /** \returns the bookmarks list. */ + const ItemList &bookmarks() const { return m_bookmarkList; - } ; - /** Returns the first bookmark item in the list. */ - virtual const BookmarkItem& bookmark() const; + } + + /** \returns the first bookmark item in the list. */ + const BookmarkItem &bookmark() const { + return m_bookmarkList.first(); + } + + private: /* Fields: */ - private: ItemList m_bookmarkList; + }; #endif diff --git a/src/frontend/cexportmanager.cpp b/src/frontend/cexportmanager.cpp index eaa0894..640eae7 100644 --- a/src/frontend/cexportmanager.cpp +++ b/src/frontend/cexportmanager.cpp @@ -9,7 +9,6 @@ #include "frontend/cexportmanager.h" -#include <QSharedPointer> #include <QApplication> #include <QClipboard> #include <QFileDialog> @@ -35,18 +34,25 @@ using namespace Rendering; using namespace Printing; -CExportManager::CExportManager(const QString &caption, - const bool showProgress, +CExportManager::CExportManager(const bool showProgress, const QString &progressLabel, const FilterOptions &filterOptions, const DisplayOptions &displayOptions) { - m_caption = !caption.isEmpty() ? caption : QString::fromLatin1("BibleTime"); - m_progressLabel = progressLabel; m_filterOptions = filterOptions; m_displayOptions = displayOptions; - m_showProgress = showProgress; - m_progressDialog = 0; + + if (showProgress) { + m_progressDialog = new QProgressDialog(0, Qt::Dialog); + m_progressDialog->setWindowTitle("BibleTime"); + m_progressDialog->setLabelText(progressLabel); + } else { + m_progressDialog = 0; + } +} + +CExportManager::~CExportManager() { + delete m_progressDialog; } bool CExportManager::saveKey(CSwordKey* key, const Format format, const bool addText) { @@ -61,24 +67,9 @@ bool CExportManager::saveKey(CSwordKey* key, const Format format, const bool add return false; } - FilterOptions filterOptions = m_filterOptions; - filterOptions.footnotes = false; - filterOptions.strongNumbers = false; - filterOptions.morphTags = false; - filterOptions.lemmas = false; - filterOptions.scriptureReferences = false; - filterOptions.textualVariants = false; - - CHTMLExportRendering::Settings settings(addText); - QSharedPointer<CTextRendering> render ( - (format == HTML) - ? new CHTMLExportRendering(settings, m_displayOptions, filterOptions) - : new CPlainTextExportRendering(settings, m_displayOptions, filterOptions) - ); + CTextRendering * render = newRenderer(format, addText); QString text; - QString startKey; - QString stopKey; QList<const CSwordModuleInfo*> modules; modules.append(key->module()); @@ -90,13 +81,13 @@ bool CExportManager::saveKey(CSwordKey* key, const Format format, const bool add else { //no range supported text = render->renderSingleKey(key->key(), modules); } + delete render; - if (!progressWasCancelled()) { - util::tool::savePlainFile(filename, text, false, (format == HTML) ? QTextCodec::codecForName("UTF-8") : QTextCodec::codecForLocale() ); - closeProgressDialog(); - return true; - } - return false; + util::tool::savePlainFile(filename, text, false, + (format == HTML) + ? QTextCodec::codecForName("UTF-8") + : QTextCodec::codecForLocale()); + return true; } bool CExportManager::saveKeyList(const sword::ListKey &l, @@ -114,22 +105,7 @@ bool CExportManager::saveKeyList(const sword::ListKey &l, return false; } - FilterOptions filterOptions = m_filterOptions; - filterOptions.footnotes = false; - filterOptions.strongNumbers = false; - filterOptions.morphTags = false; - filterOptions.lemmas = false; - filterOptions.scriptureReferences = false; - filterOptions.textualVariants = false; - - CHTMLExportRendering::Settings settings(addText); - QSharedPointer<CTextRendering> render ( - (format == HTML) - ? new CHTMLExportRendering(settings, m_displayOptions, filterOptions) - : new CPlainTextExportRendering(settings, m_displayOptions, filterOptions) - ); - - CTextRendering::KeyTree tree; + CTextRendering::KeyTree tree; /// \todo Verify that items in tree are properly freed. setProgressRange(list.Count()); CTextRendering::KeyTreeItem::Settings itemSettings; @@ -143,7 +119,9 @@ bool CExportManager::saveKeyList(const sword::ListKey &l, list.increment(); } + CTextRendering * render = newRenderer(format, addText); const QString text = render->renderKeyTree(tree); + delete render; if (!progressWasCancelled()) { util::tool::savePlainFile(filename, text, false, (format == HTML) ? QTextCodec::codecForName("UTF-8") : QTextCodec::codecForLocale() ); @@ -165,22 +143,7 @@ bool CExportManager::saveKeyList(const QList<CSwordKey*> &list, return false; } - FilterOptions filterOptions = m_filterOptions; - filterOptions.footnotes = false; - filterOptions.strongNumbers = false; - filterOptions.morphTags = false; - filterOptions.lemmas = false; - filterOptions.scriptureReferences = false; - filterOptions.textualVariants = false; - - CHTMLExportRendering::Settings settings(addText); - QSharedPointer<CTextRendering> render ( - (format == HTML) - ? new CHTMLExportRendering(settings, m_displayOptions, filterOptions) - : new CPlainTextExportRendering(settings, m_displayOptions, filterOptions) - ); - - CTextRendering::KeyTree tree; + CTextRendering::KeyTree tree; /// \todo Verify that items in tree are properly freed. setProgressRange(list.count()); CTextRendering::KeyTreeItem::Settings itemSettings; @@ -193,7 +156,9 @@ bool CExportManager::saveKeyList(const QList<CSwordKey*> &list, incProgress(); }; + CTextRendering * render = newRenderer(format, addText); const QString text = render->renderKeyTree(tree); + delete render; if (!progressWasCancelled()) { util::tool::savePlainFile(filename, text, false, (format == HTML) ? QTextCodec::codecForName("UTF-8") : QTextCodec::codecForLocale() ); @@ -204,36 +169,15 @@ bool CExportManager::saveKeyList(const QList<CSwordKey*> &list, } bool CExportManager::copyKey(CSwordKey* key, const Format format, const bool addText) { - if (!key) { - return false; - } - if (!key->module()) { + if (!key || !key->module()) return false; - } - - FilterOptions filterOptions = m_filterOptions; - filterOptions.footnotes = false; - filterOptions.strongNumbers = false; - filterOptions.morphTags = false; - filterOptions.lemmas = false; - filterOptions.scriptureReferences = false; - filterOptions.textualVariants = false; - - CHTMLExportRendering::Settings settings(addText); - QSharedPointer<CTextRendering> render ( - (format == HTML) - ? new CHTMLExportRendering(settings, m_displayOptions, filterOptions) - : new CPlainTextExportRendering(settings, m_displayOptions, filterOptions) - ); QString text; - QString startKey; - QString stopKey; - QList<const CSwordModuleInfo*> modules; modules.append(key->module()); - CSwordVerseKey *vk = dynamic_cast<CSwordVerseKey*>(key); + CTextRendering * render = newRenderer(format, addText); + CSwordVerseKey * vk = dynamic_cast<CSwordVerseKey*>(key); if (vk && vk->isBoundSet()) { text = render->renderKeyRange( QString::fromUtf8(vk->LowerBound()), @@ -245,6 +189,8 @@ bool CExportManager::copyKey(CSwordKey* key, const Format format, const bool add text = render->renderSingleKey(key->key(), modules); } + delete render; + QApplication::clipboard()->setText(text); return true; } @@ -258,22 +204,7 @@ bool CExportManager::copyKeyList(const sword::ListKey &l, if (!list.Count()) return false; - FilterOptions filterOptions = m_filterOptions; - filterOptions.footnotes = false; - filterOptions.strongNumbers = false; - filterOptions.morphTags = false; - filterOptions.lemmas = false; - filterOptions.scriptureReferences = false; - filterOptions.textualVariants = false; - - CHTMLExportRendering::Settings settings(addText); - QSharedPointer<CTextRendering> render ( - (format == HTML) - ? new CHTMLExportRendering(settings, m_displayOptions, filterOptions) - : new CPlainTextExportRendering(settings, m_displayOptions, filterOptions) - ); - - CTextRendering::KeyTree tree; + CTextRendering::KeyTree tree; /// \todo Verify that items in tree are properly freed. CTextRendering::KeyTreeItem::Settings itemSettings; itemSettings.highlight = false; @@ -284,7 +215,9 @@ bool CExportManager::copyKeyList(const sword::ListKey &l, list.increment(); } + CTextRendering * render = newRenderer(format, addText); const QString text = render->renderKeyTree(tree); + delete render; QApplication::clipboard()->setText(text); return true; } @@ -297,22 +230,8 @@ bool CExportManager::copyKeyList(const QList<CSwordKey*> &list, if (!list.count()) return false; - FilterOptions filterOptions = m_filterOptions; - filterOptions.footnotes = false; - filterOptions.strongNumbers = false; - filterOptions.morphTags = false; - filterOptions.lemmas = false; - filterOptions.scriptureReferences = false; - filterOptions.textualVariants = false; - - CHTMLExportRendering::Settings settings(addText); - QSharedPointer<CTextRendering> render ( - (format == HTML) - ? new CHTMLExportRendering(settings, m_displayOptions, filterOptions) - : new CPlainTextExportRendering(settings, m_displayOptions, filterOptions) - ); - CTextRendering::KeyTree tree; + CTextRendering::KeyTree tree; /// \todo Verify that items in tree are properly freed. CTextRendering::KeyTreeItem::Settings itemSettings; itemSettings.highlight = false; @@ -324,7 +243,10 @@ bool CExportManager::copyKeyList(const QList<CSwordKey*> &list, incProgress(); }; + CTextRendering * render = newRenderer(format, addText); const QString text = render->renderKeyTree(tree); + delete render; + QApplication::clipboard()->setText(text); if (!progressWasCancelled()) { closeProgressDialog(); @@ -340,37 +262,36 @@ bool CExportManager::printKeyList(const sword::ListKey &l, /// \warning This is a workaround for Sword constness sword::ListKey list = l; CPrinter::KeyTreeItem::Settings settings; - CPrinter::KeyTree tree; + CPrinter::KeyTree tree; /// \todo Verify that items in tree are properly freed. - QString startKey, stopKey; setProgressRange(list.Count()); - - list.setPosition(sword::TOP); - while (!list.Error() && !progressWasCancelled()) { - if (dynamic_cast<const sword::VerseKey&>(l) != 0) { - const sword::VerseKey &vk = static_cast<const sword::VerseKey&>(l); - startKey = QString::fromUtf8((const char*) vk.LowerBound()); - stopKey = QString::fromUtf8((const char*) vk.UpperBound()); + for (int i=0; i< list.Count(); i++) { + const sword::SWKey* swKey = list.getElement(i); + const sword::VerseKey* vKey = dynamic_cast<const sword::VerseKey*>(swKey); + if (vKey != 0) { + QString startKey = vKey->getText(); tree.append(new CTextRendering::KeyTreeItem(startKey, - stopKey, - module, - settings)); + startKey, + module, + settings)); } else { - startKey = QString::fromUtf8((const char*) * list); - tree.append(new CTextRendering::KeyTreeItem(startKey, - module, - settings)); + QString key = swKey->getText(); + tree.append(new CTextRendering::KeyTreeItem(key, + key, + module, + settings)); } - - list.increment(); incProgress(); + if (progressWasCancelled()) + break; } - QSharedPointer<CPrinter> printer(new CPrinter(0, displayOptions, filterOptions)); if (!progressWasCancelled()) { + CPrinter * printer = new CPrinter(0, displayOptions, filterOptions); printer->printKeyTree(tree); + delete printer; closeProgressDialog(); return true; } @@ -390,7 +311,7 @@ bool CExportManager::printKey(const CSwordModuleInfo *module, ? CPrinter::KeyTreeItem::Settings::SimpleKey : CPrinter::KeyTreeItem::Settings::NoKey; - CPrinter::KeyTree tree; + CPrinter::KeyTree tree; /// \todo Verify that items in tree are properly freed. if (startKey != stopKey) { tree.append( new CPrinter::KeyTreeItem(startKey, stopKey, module, settings) ); } @@ -398,8 +319,9 @@ bool CExportManager::printKey(const CSwordModuleInfo *module, tree.append( new CPrinter::KeyTreeItem(startKey, module, settings) ); } - QSharedPointer<CPrinter> printer(new CPrinter(0, displayOptions, filterOptions)); + CPrinter * printer = new CPrinter(0, displayOptions, filterOptions); printer->printKeyTree(tree); + delete printer; return true; } @@ -413,11 +335,12 @@ bool CExportManager::printKey(const CSwordKey *key, ? CPrinter::KeyTreeItem::Settings::SimpleKey : CPrinter::KeyTreeItem::Settings::NoKey; - CPrinter::KeyTree tree; + CPrinter::KeyTree tree; /// \todo Verify that items in tree are properly freed. tree.append( new CPrinter::KeyTreeItem(key->key(), key->module(), settings) ); - QSharedPointer<CPrinter> printer(new CPrinter(0, displayOptions, filterOptions)); + CPrinter * printer = new CPrinter(0, displayOptions, filterOptions); printer->printKeyTree(tree); + delete printer; return true; } @@ -434,7 +357,7 @@ bool CExportManager::printByHyperlink(const QString &hyperlink, moduleName = ReferenceManager::preferredModule(type); } - CPrinter::KeyTree tree; + CPrinter::KeyTree tree; /// \todo Verify that items in tree are properly freed. CPrinter::KeyTreeItem::Settings settings; settings.keyRenderingFace = displayOptions.verseNumbers @@ -450,15 +373,15 @@ bool CExportManager::printByHyperlink(const QString &hyperlink, sword::ListKey verses = sword::VerseKey().ParseVerseList((const char*)keyName.toUtf8(), "Genesis 1:1", true); for (int i = 0; i < verses.Count(); ++i) { - sword::VerseKey* element = dynamic_cast<sword::VerseKey*>(verses.GetElement(i)); + sword::VerseKey* element = dynamic_cast<sword::VerseKey*>(verses.getElement(i)); if (element) { const QString startKey = QString::fromUtf8(element->LowerBound().getText()); const QString stopKey = QString::fromUtf8(element->UpperBound().getText()); tree.append( new CPrinter::KeyTreeItem(startKey, stopKey, module, settings) ); } - else if (verses.GetElement(i)) { - const QString key = QString::fromUtf8(verses.GetElement(i)->getText()); + else if (verses.getElement(i)) { + const QString key = QString::fromUtf8(verses.getElement(i)->getText()); tree.append( new CPrinter::KeyTreeItem(key, module, settings) ); } @@ -469,8 +392,9 @@ bool CExportManager::printByHyperlink(const QString &hyperlink, } } - QSharedPointer<CPrinter> printer(new CPrinter(0, displayOptions, filterOptions)); + CPrinter * printer = new CPrinter(0, displayOptions, filterOptions); printer->printKeyTree(tree); + delete printer; return true; } @@ -485,7 +409,7 @@ bool CExportManager::printKeyList(const QStringList &list, ? CPrinter::KeyTreeItem::Settings::SimpleKey : CPrinter::KeyTreeItem::Settings::NoKey; - CPrinter::KeyTree tree; + CPrinter::KeyTree tree; /// \todo Verify that items in tree are properly freed. setProgressRange(list.count()); const QStringList::const_iterator end = list.constEnd(); @@ -494,10 +418,11 @@ bool CExportManager::printKeyList(const QStringList &list, incProgress(); } - QSharedPointer<CPrinter> printer(new CPrinter(0, displayOptions, filterOptions)); if (!progressWasCancelled()) { + CPrinter * printer = new CPrinter(0, displayOptions, filterOptions); printer->printKeyTree(tree); + delete printer; closeProgressDialog(); return true; } @@ -522,55 +447,53 @@ const QString CExportManager::getSaveFileName(const Format format) { return QFileDialog::getSaveFileName(0, QObject::tr("Save file"), "", filterString(format), 0); } -/** No descriptions */ -void CExportManager::setProgressRange( const int items ) { - if (QProgressDialog* dlg = progressDialog()) { - dlg->setMaximum(items); - dlg->setValue(0); - dlg->setMinimumDuration(0); - dlg->show(); - // dlg->repaint(); - qApp->processEvents(); //do not lock the GUI! - } -} - -/** Creates the progress dialog with the correct settings. */ -QProgressDialog* CExportManager::progressDialog() { - if (!m_showProgress) { - return 0; - } - - if (!m_progressDialog) { - m_progressDialog = new QProgressDialog(0, Qt::Dialog ); - m_progressDialog->setLabelText(m_progressLabel); +CTextRendering * CExportManager::newRenderer(const Format format, bool addText) { + FilterOptions filterOptions = m_filterOptions; + filterOptions.footnotes = false; + filterOptions.strongNumbers = false; + filterOptions.morphTags = false; + filterOptions.lemmas = false; + filterOptions.scriptureReferences = false; + filterOptions.textualVariants = false; - m_progressDialog->setWindowTitle("BibleTime"); + if (format == HTML) { + return new CHTMLExportRendering(addText, m_displayOptions, filterOptions); + } else { + Q_ASSERT(format == Text); + return new CPlainTextExportRendering(addText, m_displayOptions, filterOptions); } +} - return m_progressDialog; +void CExportManager::setProgressRange( const int items ) { + if (!m_progressDialog) + return; + + m_progressDialog->setMaximum(items); + m_progressDialog->setValue(0); + m_progressDialog->setMinimumDuration(0); + m_progressDialog->show(); + // m_progressDialog->repaint(); + qApp->processEvents(); //do not lock the GUI! } /** Increments the progress by one item. */ void CExportManager::incProgress() { - if (QProgressDialog* dlg = progressDialog()) { - dlg->setValue( dlg->value() + 1 ); - } + if (m_progressDialog) + m_progressDialog->setValue(m_progressDialog->value() + 1); } -/** No descriptions */ bool CExportManager::progressWasCancelled() { - if (QProgressDialog* dlg = progressDialog()) { - return dlg->wasCanceled(); - } + if (m_progressDialog) + return m_progressDialog->wasCanceled(); - return true; + return false; } /** Closes the progress dialog immediatly. */ void CExportManager::closeProgressDialog() { - if (QProgressDialog* dlg = progressDialog()) { - dlg->close(); - dlg->reset(); + if (m_progressDialog) { + m_progressDialog->close(); + m_progressDialog->reset(); } qApp->processEvents(); //do not lock the GUI! diff --git a/src/frontend/cexportmanager.h b/src/frontend/cexportmanager.h index d2a185d..0d882e0 100644 --- a/src/frontend/cexportmanager.h +++ b/src/frontend/cexportmanager.h @@ -19,6 +19,9 @@ class CSwordKey; class CSwordModuleInfo; class ListKey; class QProgressDialog; +namespace Rendering { +class CTextRendering; +} /** Contains the functions to export text to disk, clipboard or printer. * @author The BibleTime team @@ -32,11 +35,11 @@ class CExportManager { Text }; - CExportManager(const QString &caption, - const bool showProgress = true, + CExportManager(const bool showProgress = true, const QString &progressLabel = QString::null, const FilterOptions &filterOptions = CBTConfig::getFilterOptionDefaults(), const DisplayOptions &displayOptions = CBTConfig::getDisplayOptionDefaults()); + ~CExportManager(); bool saveKey(CSwordKey* key, const Format format, const bool addText); @@ -97,32 +100,34 @@ class CExportManager { */ const QString getSaveFileName(const Format format); - private: - QString m_caption; ///< \todo Useless field - QString m_progressLabel; - bool m_showProgress; - FilterOptions m_filterOptions; - DisplayOptions m_displayOptions; + private: /* Methods: */ - QProgressDialog* m_progressDialog; + Rendering::CTextRendering * newRenderer(const Format format, + bool addText); /** - * Creates the progress dialog with the correct settings. - */ - QProgressDialog* progressDialog(); - /** * Returns the CSS string used in HTML pages. */ void setProgressRange( const int item ); + /** * Increments the progress by one item. */ inline void incProgress(); + bool progressWasCancelled(); + /** * Closes the progress dialog immediately. */ void closeProgressDialog(); + + private: + + FilterOptions m_filterOptions; + DisplayOptions m_displayOptions; + + QProgressDialog* m_progressDialog; }; #endif diff --git a/src/frontend/cinfodisplay.cpp b/src/frontend/cinfodisplay.cpp index 19323fc..8165b8b 100644 --- a/src/frontend/cinfodisplay.cpp +++ b/src/frontend/cinfodisplay.cpp @@ -56,7 +56,7 @@ CInfoDisplay::CInfoDisplay(QWidget *parent) : QWidget(parent) { copyAction->setShortcut( QKeySequence(Qt::CTRL + Qt::Key_C) ); QObject::connect(copyAction, SIGNAL(triggered()), m_htmlPart->connectionsProxy(), SLOT(copySelection()) ); - QMenu* menu = new QMenu(); + QMenu* menu = new QMenu(this); menu->addAction(selectAllAction); menu->addAction(copyAction); m_htmlPart->installPopup(menu); @@ -69,25 +69,36 @@ CInfoDisplay::CInfoDisplay(QWidget *parent) : QWidget(parent) { layout->addWidget(m_htmlPart->view()); + unsetInfo(); +} + +void CInfoDisplay::unsetInfo() { + setInfo(tr("<small>This is the Mag viewer area. Hover the mouse over links " + "or other items which include some data and the contents appear " + "in the Mag after a short delay. Move the mouse into Mag " + "rapidly or lock the view by pressing and holding Shift while " + "moving the mouse.</small>")); +} + +void CInfoDisplay::setInfo(const QString &data, const QString &lang) { CDisplayTemplateMgr *mgr = CDisplayTemplateMgr::instance(); + Q_ASSERT(mgr != 0); + CDisplayTemplateMgr::Settings settings; settings.pageCSS_ID = "infodisplay"; - QString divText("<div class=\"infodisplay\">%1</div>"); - QString initialMagText(tr("<small>This is the Mag viewer area. Hover the " - "mouse over links or other items which include " - "some data and the contents appear in the Mag " - "after a short delay. Move the mouse into Mag " - "rapidly or lock the view by pressing and " - "holding Shift while moving the mouse.</small>")); - QString content(mgr->fillTemplate(CBTConfig::get(CBTConfig::displayStyle), - divText.arg(initialMagText), - settings) - ); - m_htmlPart->setText(content); -} + QString div = "<div class=\"infodisplay\""; + if (!lang.isEmpty()) { + div.append(" lang=\""); + div.append(lang); + div.append("\""); + } + div.append(">"); -CInfoDisplay::~CInfoDisplay() { + QString content(mgr->fillTemplate(CDisplayTemplateMgr::activeTemplateName(), + div + data + "</div>", + settings)); + m_htmlPart->setText(content); } void CInfoDisplay::lookupInfo(const QString &mod_name, const QString &key_text) { @@ -100,23 +111,7 @@ void CInfoDisplay::lookupInfo(const QString &mod_name, const QString &key_text) QSharedPointer<CSwordKey> key( CSwordKey::createInstance(m) ); key->setKey(key_text); - CDisplayTemplateMgr *mgr = CDisplayTemplateMgr::instance(); - CDisplayTemplateMgr::Settings settings; - settings.pageCSS_ID = "infodisplay"; - - // lookup text and wrap in a "div" with language set to module language - QString lang = m->language()->abbrev(); - QString renderedText = key->renderedText(); - QString divText = "<div class=\"infodisplay\" lang=\""; - divText.append(lang); - divText.append("\">"); - divText.append(renderedText); - divText.append("</div>"); - - QString content = mgr->fillTemplate(CBTConfig::get - (CBTConfig::displayStyle), divText, settings); - - m_htmlPart->setText(content); + setInfo(key->renderedText(), m->language()->abbrev()); } void CInfoDisplay::setInfo(const InfoType type, const QString& data) { @@ -133,7 +128,7 @@ void CInfoDisplay::setInfo(const ListInfoData& list) { return; } - if (list.count() == 0) { + if (list.isEmpty()) { m_htmlPart->setText("<html></html>"); return; } @@ -172,16 +167,18 @@ void CInfoDisplay::setInfo(const ListInfoData& list) { }; } - CDisplayTemplateMgr *mgr = CDisplayTemplateMgr::instance(); - CDisplayTemplateMgr::Settings settings; - settings.pageCSS_ID = "infodisplay"; - // settings.langAbbrev = ""; - QString content = mgr->fillTemplate(CBTConfig::get - (CBTConfig::displayStyle), text, settings); - - // qWarning("setting text:\n%s", content.latin1()); + setInfo(text); +} - m_htmlPart->setText(content); +void CInfoDisplay::setInfo(CSwordModuleInfo *module) { + if (module) { + setInfo(tr("<div class=\"moduleinfo\"><h3>%1</h3><p>%2</p><p>Version: %3</p></div>") + .arg(module->name()) + .arg(module->config(CSwordModuleInfo::Description)) + .arg(module->config(CSwordModuleInfo::ModuleVersion))); + } else { + unsetInfo(); + } } void CInfoDisplay::selectAll() { @@ -301,8 +298,7 @@ const QString CInfoDisplay::decodeCrossReference( const QString& data ) { lang = module->language()->abbrev(); } - QString RenderedText = renderer.renderKeyTree(tree); - qDeleteAll(tree); + const QString RenderedText = renderer.renderKeyTree(tree); return QString("<div class=\"crossrefinfo\" lang=\"%1\"><h3>%2</h3><div class=\"para\" dir=\"%3\">%4</div></div>") .arg(lang) @@ -506,14 +502,6 @@ const QString CInfoDisplay::getWordTranslation( const QString& data ) { return ret; } -void CInfoDisplay::clearInfo() { - CDisplayTemplateMgr *tmgr = CDisplayTemplateMgr::instance(); - CDisplayTemplateMgr::Settings settings; - settings.pageCSS_ID = "infodisplay"; - - m_htmlPart->setText( tmgr->fillTemplate(CBTConfig::get(CBTConfig::displayStyle), QString::null, settings) ); -} - QSize CInfoDisplay::sizeHint() const { return QSize(100, 150); } diff --git a/src/frontend/cinfodisplay.h b/src/frontend/cinfodisplay.h index 17c36a5..7bc15e7 100644 --- a/src/frontend/cinfodisplay.h +++ b/src/frontend/cinfodisplay.h @@ -41,13 +41,16 @@ class CInfoDisplay : public QWidget { typedef QList<InfoData> ListInfoData; CInfoDisplay(QWidget *parent = 0); - virtual ~CInfoDisplay(); + void unsetInfo(); + void setInfo(const QString &data, const QString &lang = QString()); void setInfo(const InfoType, const QString& data); void setInfo(const ListInfoData&); - void clearInfo(); QSize sizeHint() const; + public slots: + void setInfo(CSwordModuleInfo *module); + protected: const QString decodeAbbreviation( const QString& data ); const QString decodeCrossReference( const QString& data ); diff --git a/src/frontend/cmdiarea.cpp b/src/frontend/cmdiarea.cpp index cfdb6ee..b2896da 100644 --- a/src/frontend/cmdiarea.cpp +++ b/src/frontend/cmdiarea.cpp @@ -13,14 +13,22 @@ #include <QEvent> #include <QMdiSubWindow> +#include <QMenu> +#include <QtGlobal> +#include <QTabBar> #include <QTimer> #include <QToolBar> #include <QWindowStateChangeEvent> -#include <QMenu> + +#define MOVESIZE 30 CMDIArea::CMDIArea(BibleTime *parent) - : QMdiArea(parent), m_mdiArrangementMode(ArrangementModeManual), m_activeWindow(0), m_bibleTime(parent) { + : QMdiArea(parent) + , m_mdiArrangementMode(ArrangementModeManual) + , m_activeWindow(0) + , m_bibleTime(parent) +{ Q_ASSERT(parent != 0); #if QT_VERSION >= 0x040500 @@ -42,16 +50,11 @@ CMDIArea::CMDIArea(BibleTime *parent) this, SLOT(slotSubWindowActivated(QMdiSubWindow*))); } -static const int moveSize = 30; - void CMDIArea::fixSystemMenu(QMdiSubWindow* subWindow) { // Change Qt QMdiSubWindow Close action to have no shortcuts // This makes our closeWindow actions with Ctrl-W work correctly - QList<QAction*> actions = subWindow->systemMenu()->actions(); - for (int i=0; i<actions.count(); i++) { - QAction* action = actions.at(i); - QString text = action->text(); - if (text.contains("Close")) { + Q_FOREACH(QAction * const action, subWindow->systemMenu()->actions()) { + if (action->text().contains("Close")) { action->setShortcuts(QList<QKeySequence>()); break; } @@ -77,10 +80,10 @@ QMdiSubWindow* CMDIArea::addSubWindow(QWidget * widget, Qt::WindowFlags windowFl // Make new window the same size as the active window and move it slightly. subWindow->resize(activeSubWindow()->size()); QRect subWinGeom = activeSubWindow()->geometry(); - subWinGeom.translate(moveSize, moveSize); + subWinGeom.translate(MOVESIZE, MOVESIZE); // If it goes off screen, move it almost to the top left if ( ! frameRect().contains(subWinGeom)) { - subWinGeom.moveTo(moveSize, moveSize); + subWinGeom.moveTo(MOVESIZE, MOVESIZE); } subWindow->setGeometry(subWinGeom); } @@ -117,21 +120,41 @@ void CMDIArea::setMDIArrangementMode( const MDIArrangementMode newArrangementMod triggerWindowUpdate(); break; } + Q_FOREACH (QTabBar* tab, findChildren<QTabBar *>()) { + QObject* parent = tab->parent(); + if (parent == this) { + tab->setTabsClosable(true); + disconnect(tab, SIGNAL(tabCloseRequested(int)), this, SLOT(closeTab(int))); + connect(tab, SIGNAL(tabCloseRequested(int)), this, SLOT(closeTab(int))); + } + } +} + +void CMDIArea::closeTab(int i) { + QMdiSubWindow *sub = subWindowList()[i]; + QWidget *win = sub->widget(); + win->close(); + setActiveSubWindow(sub); + closeActiveSubWindow(); } void CMDIArea::myTileVertical() { - if (!updatesEnabled() || !usableWindowList().count() ) { + if (!updatesEnabled()) { + return; + } + QList<QMdiSubWindow*> windows = usableWindowList(); + if (windows.isEmpty()) { return; } setViewMode(QMdiArea::SubWindowView); - QList<QMdiSubWindow*> windows = usableWindowList(); setUpdatesEnabled(false); - QMdiSubWindow* active = activeSubWindow(); + + QMdiSubWindow * const active = activeSubWindow(); const int widthForEach = width() / windows.count(); unsigned int x = 0; - foreach (QMdiSubWindow *window, windows) { + Q_FOREACH (QMdiSubWindow * const window, windows) { window->showNormal(); const int preferredWidth = window->minimumWidth() + window->baseSize().width(); @@ -141,24 +164,30 @@ void CMDIArea::myTileVertical() { x += actWidth; } - if (active) active->setFocus(); + if (active != 0) { + active->setFocus(); + } + setUpdatesEnabled(true); -emitWindowCaptionChanged(); + emitWindowCaptionChanged(); } void CMDIArea::myTileHorizontal() { - if (!updatesEnabled() || !usableWindowList().count() ) { + if (!updatesEnabled()) { + return; + } + QList<QMdiSubWindow*> windows = usableWindowList(); + if (windows.isEmpty()) { return; } setViewMode(QMdiArea::SubWindowView); - QList<QMdiSubWindow*> windows = usableWindowList(); setUpdatesEnabled(false); - QMdiSubWindow* active = activeSubWindow(); + QMdiSubWindow * const active = activeSubWindow(); const int heightForEach = height() / windows.count(); unsigned int y = 0; - foreach (QMdiSubWindow *window, windows) { + Q_FOREACH (QMdiSubWindow * const window, windows) { window->showNormal(); const int preferredHeight = window->minimumHeight() + window->baseSize().height(); @@ -167,14 +196,18 @@ void CMDIArea::myTileHorizontal() { window->setGeometry( 0, y, width(), actHeight ); y += actHeight; } - if (active) active->setFocus(); + + if (active != 0) { + active->setFocus(); + } + setUpdatesEnabled(true); emitWindowCaptionChanged(); } // Tile the windows, tiling implemented by Qt void CMDIArea::myTile() { - if (!updatesEnabled() || !usableWindowList().count() ) { + if (!updatesEnabled() || usableWindowList().isEmpty()) { return; } setViewMode(QMdiArea::SubWindowView); @@ -183,29 +216,31 @@ void CMDIArea::myTile() { } void CMDIArea::myCascade() { - if (!updatesEnabled() || !usableWindowList().count() ) { + if (!updatesEnabled()) { return; } - setViewMode(QMdiArea::SubWindowView); - QList<QMdiSubWindow*> windows = usableWindowList(); + if (windows.isEmpty()) { + return; + } + setViewMode(QMdiArea::SubWindowView); if (windows.count() == 1) { - windows.at(0)->showMaximized(); + windows.first()->showMaximized(); } else { setUpdatesEnabled(false); - QMdiSubWindow* active = activeSubWindow(); + QMdiSubWindow * const active = activeSubWindow(); - const unsigned int offsetX = 40; - const unsigned int offsetY = 40; + static const unsigned offsetX = 40; + static const unsigned offsetY = 40; const unsigned int windowWidth = width() - (windows.count() - 1) * offsetX; const unsigned int windowHeight = height() - (windows.count() - 1) * offsetY; unsigned int x = 0; unsigned int y = 0; - foreach (QMdiSubWindow* window, windows) { + Q_FOREACH (QMdiSubWindow * const window, windows) { if (window == active) { //leave out the active window which should be the top window continue; } @@ -222,6 +257,7 @@ void CMDIArea::myCascade() { setUpdatesEnabled(true); } + emitWindowCaptionChanged(); } @@ -234,30 +270,29 @@ void CMDIArea::emitWindowCaptionChanged() { } } -QList<QMdiSubWindow*> CMDIArea::usableWindowList() { +QList<QMdiSubWindow*> CMDIArea::usableWindowList() const { //Take care: when new windows are added, they will not appear //in subWindowList() when their ChildAdded-Event is triggered QList<QMdiSubWindow*> ret; - foreach(QMdiSubWindow* w, subWindowList()) { - if (w->isHidden()) { //not usable for us - continue; + Q_FOREACH (QMdiSubWindow * const w, subWindowList()) { + if (!w->isHidden()) { + ret.append(w); } - ret.append( w ); } return ret; } void CMDIArea::slotSubWindowActivated(QMdiSubWindow* client) { - if (subWindowList().count() == 0) + if (subWindowList().isEmpty()) m_bibleTime->clearMdiToolBars(); - if (!client) { + if (client == 0) { return; } emit sigSetToplevelCaption( client->windowTitle().trimmed() ); // Notify child window it is active - CDisplayWindow* activeWindow = qobject_cast<CDisplayWindow*>(client->widget()); + CDisplayWindow * const activeWindow = qobject_cast<CDisplayWindow*>(client->widget()); if (activeWindow != 0 && activeWindow != m_activeWindow) { m_activeWindow = activeWindow; activeWindow->windowActivated(); @@ -282,7 +317,7 @@ void CMDIArea::resizeEvent(QResizeEvent* e) { //handle events of the client windows to update layout if necessary bool CMDIArea::eventFilter(QObject *o, QEvent *e) { - QMdiSubWindow *w(qobject_cast<QMdiSubWindow*>(o)); + const QMdiSubWindow * const w = qobject_cast<QMdiSubWindow*>(o); // Let the event be handled by other filters: if (w == 0) @@ -350,15 +385,13 @@ void CMDIArea::triggerWindowUpdate() { void CMDIArea::enableWindowMinMaxFlags(bool enable) { - foreach(QMdiSubWindow* subWindow, subWindowList()) { + Q_FOREACH (QMdiSubWindow * const subWindow, subWindowList()) { Qt::WindowFlags flags = subWindow->windowFlags(); if (enable) { - flags |= Qt::WindowMinimizeButtonHint; - flags |= Qt::WindowMaximizeButtonHint; + flags |= (Qt::WindowMinimizeButtonHint | Qt::WindowMaximizeButtonHint); } else { - flags &= ~Qt::WindowMinimizeButtonHint; - flags &= ~Qt::WindowMaximizeButtonHint; + flags &= ~(Qt::WindowMinimizeButtonHint | Qt::WindowMaximizeButtonHint); } subWindow->setWindowFlags(flags); } diff --git a/src/frontend/cmdiarea.h b/src/frontend/cmdiarea.h index 9a62370..4b9d70e 100644 --- a/src/frontend/cmdiarea.h +++ b/src/frontend/cmdiarea.h @@ -14,6 +14,7 @@ #include <QList> + class BibleTime; class CSwordModuleInfo; class CDisplayWindow; @@ -22,10 +23,12 @@ class CDisplayWindow; A custom MDI area widget. */ class CMDIArea: public QMdiArea { + Q_OBJECT Q_PROPERTY(MDIArrangementMode m_mdiArrangementMode READ getMDIArrangementMode WRITE setMDIArrangementMode) - public: + public: /* Types: */ + /** Possible MDI subwindow arrangement modes. */ @@ -38,6 +41,8 @@ class CMDIArea: public QMdiArea { ArrangementModeTabbed = 6 }; + public: /* Methods: */ + /** \param[in] parent BibleTime main window used for parent widget. */ @@ -67,9 +72,9 @@ class CMDIArea: public QMdiArea { void triggerWindowUpdate(); /** - Returns a lists of all subwindows which are not minimized or hidden. + \returns a lists of all subwindows which are not minimized or hidden. */ - QList<QMdiSubWindow*> usableWindowList(); + QList<QMdiSubWindow*> usableWindowList() const; /** Show or hide the sub-window min/max buttons. @@ -77,6 +82,7 @@ class CMDIArea: public QMdiArea { void enableWindowMinMaxFlags(bool enable); public slots: + /** Uses Qt's tileSubWindows function. \note This not set an automatic arrangement mode, it just arranges the @@ -113,12 +119,14 @@ class CMDIArea: public QMdiArea { void myTileHorizontal(); signals: + /** * Emits a signal to set the caption of the toplevel widget. */ void sigSetToplevelCaption(const QString&); - protected: + protected: /* Methods: */ + /** Reimplementation of QWidget::resizeEvent() to handle our automatic tiling properly. @@ -132,20 +140,30 @@ class CMDIArea: public QMdiArea { bool eventFilter(QObject *o, QEvent *e); void emitWindowCaptionChanged(); + void fixSystemMenu(QMdiSubWindow* subWindow); protected slots: + /** Called whan a subwindow was activated. */ void slotSubWindowActivated(QMdiSubWindow *client); - protected: + /** + Called whan a tabbed subwindow is closed from the tab + */ + void closeTab(int i); + + protected: /* Fields: */ + MDIArrangementMode m_mdiArrangementMode; - private: + private: /* Fields: */ + CDisplayWindow* m_activeWindow; BibleTime* m_bibleTime; -}; + +}; /* class CMDIArea */ #endif diff --git a/src/frontend/cprinter.cpp b/src/frontend/cprinter.cpp index 99d1daf..3645472 100644 --- a/src/frontend/cprinter.cpp +++ b/src/frontend/cprinter.cpp @@ -52,8 +52,8 @@ void CPrinter::printKeyTree( KeyTree& tree ) { } } -const QString CPrinter::entryLink(const KeyTreeItem &item, - const CSwordModuleInfo *module) +QString CPrinter::entryLink(const KeyTreeItem &item, + const CSwordModuleInfo * module) { Q_ASSERT(module); if (module->type() == CSwordModuleInfo::Bible) { @@ -71,13 +71,15 @@ const QString CPrinter::entryLink(const KeyTreeItem &item, case KeyTreeItem::Settings::SimpleKey: //fall through default: - return QString::number(vk.Verse()); + return QString::number(vk.getVerse()); } } return item.key(); } -const QString CPrinter::renderEntry( const KeyTreeItem& i, CSwordKey* ) { +QString CPrinter::renderEntry(const KeyTreeItem &i, CSwordKey * key) { + Q_UNUSED(key); + const CPrinter::KeyTreeItem* printItem = dynamic_cast<const CPrinter::KeyTreeItem*>(&i); Q_ASSERT(printItem); @@ -87,7 +89,7 @@ const QString CPrinter::renderEntry( const KeyTreeItem& i, CSwordKey* ) { if (!i.childList()->isEmpty()) { KeyTree const * tree = i.childList(); - foreach ( KeyTreeItem* c, (*tree)) { + Q_FOREACH (const KeyTreeItem * const c, *tree) { ret.append( CDisplayRendering::renderEntry( *c ) ); } } @@ -98,8 +100,8 @@ const QString CPrinter::renderEntry( const KeyTreeItem& i, CSwordKey* ) { return CDisplayRendering::renderEntry(i); } -const QString CPrinter::finishText(const QString& text, KeyTree& tree) { - QList<const CSwordModuleInfo*> modules = collectModules(&tree); +QString CPrinter::finishText(const QString &text, const KeyTree &tree) { + QList<const CSwordModuleInfo*> modules = collectModules(tree); Q_ASSERT(modules.count() > 0); const CLanguageMgr::Language* const lang = modules.first()->language(); @@ -120,7 +122,7 @@ const QString CPrinter::finishText(const QString& text, KeyTree& tree) { } CDisplayTemplateMgr *tMgr = CDisplayTemplateMgr::instance(); - return tMgr->fillTemplate(CBTConfig::get(CBTConfig::displayStyle), text, settings); + return tMgr->fillTemplate(CDisplayTemplateMgr::activeTemplateName(), text, settings); } } //end of namespace diff --git a/src/frontend/cprinter.h b/src/frontend/cprinter.h index 2252786..e702565 100644 --- a/src/frontend/cprinter.h +++ b/src/frontend/cprinter.h @@ -13,7 +13,6 @@ #include <QObject> #include "backend/rendering/cdisplayrendering.h" -#include "backend/config/cbtconfig.h" #include "backend/managers/cswordbackend.h" @@ -34,11 +33,11 @@ class CPrinter : public QObject, public Rendering::CDisplayRendering { void printKeyTree( KeyTree& ); protected: - virtual const QString entryLink(const KeyTreeItem &item, - const CSwordModuleInfo *module); + virtual QString entryLink(const KeyTreeItem &item, + const CSwordModuleInfo * module); - virtual const QString renderEntry( const KeyTreeItem&, CSwordKey* = 0 ); - virtual const QString finishText(const QString& arg1, KeyTree& tree); + virtual QString renderEntry(const KeyTreeItem &item, CSwordKey * key = 0); + virtual QString finishText(const QString &text, const KeyTree &tree); private: QWebPage* m_htmlPage; diff --git a/src/frontend/crossrefrendering.cpp b/src/frontend/crossrefrendering.cpp index 616766c..ac538da 100644 --- a/src/frontend/crossrefrendering.cpp +++ b/src/frontend/crossrefrendering.cpp @@ -18,18 +18,18 @@ namespace InfoDisplay { CrossRefRendering::CrossRefRendering(const DisplayOptions &displayOptions, const FilterOptions &filterOptions) - : CHTMLExportRendering(Settings(), displayOptions, filterOptions) + : CHTMLExportRendering(true, displayOptions, filterOptions) { // Intentionally empty } -const QString CrossRefRendering::finishText( const QString& text, KeyTree& ) { - // qDebug() << "CrossRefRendering::finishText"; +QString CrossRefRendering::finishText(const QString &text, const KeyTree &tree) { + Q_UNUSED(tree); return text; } -const QString CrossRefRendering::entryLink(const KeyTreeItem &item, - const CSwordModuleInfo *module) +QString CrossRefRendering::entryLink(const KeyTreeItem &item, + const CSwordModuleInfo *module) { QString linkText; @@ -60,7 +60,7 @@ const QString CrossRefRendering::entryLink(const KeyTreeItem &item, } case KeyTreeItem::Settings::SimpleKey: { if (isBible) { - linkText = QString::number(vk.Verse()); + linkText = QString::number(vk.getVerse()); break; } //fall through for non-Bible modules diff --git a/src/frontend/crossrefrendering.h b/src/frontend/crossrefrendering.h index 1e65d06..d6f33a2 100644 --- a/src/frontend/crossrefrendering.h +++ b/src/frontend/crossrefrendering.h @@ -24,10 +24,10 @@ class CrossRefRendering : public Rendering::CHTMLExportRendering { const FilterOptions &filterOptions = CBTConfig::getFilterOptionDefaults() ); - virtual const QString entryLink(const KeyTreeItem &item, - const CSwordModuleInfo *module); + virtual QString entryLink(const KeyTreeItem &item, + const CSwordModuleInfo *module); - virtual const QString finishText( const QString&, KeyTree& tree ); + virtual QString finishText(const QString &text, const KeyTree &tree); }; diff --git a/src/frontend/display/bthtmljsobject.cpp b/src/frontend/display/bthtmljsobject.cpp index 119c2a8..6b11d5b 100644 --- a/src/frontend/display/bthtmljsobject.cpp +++ b/src/frontend/display/bthtmljsobject.cpp @@ -77,7 +77,7 @@ void BtHtmlJsObject::mouseMoveEvent(const QString& attributes, const int& x, con QPoint current(x, y); if ((current - m_dndData.startPos).manhattanLength() > 4 /*qApp->startDragDistance()*/ ) { QDrag* drag = 0; - if (m_dndData.url.size() != 0 ) { + if (!m_dndData.url.isEmpty()) { // create a new bookmark drag! QString moduleName = QString::null; QString keyName = QString::null; diff --git a/src/frontend/display/bthtmljsobject.h b/src/frontend/display/bthtmljsobject.h index c49dc83..109de5a 100644 --- a/src/frontend/display/bthtmljsobject.h +++ b/src/frontend/display/bthtmljsobject.h @@ -22,7 +22,7 @@ class BtHtmlJsObject: public QObject { public: BtHtmlJsObject(BtHtmlReadDisplay* display); - ~BtHtmlJsObject() {} + void moveToAnchor(const QString& anchor); void clearPrevAttribute(); diff --git a/src/frontend/display/bthtmlreaddisplay.cpp b/src/frontend/display/bthtmlreaddisplay.cpp index 2d95c38..d7ee33f 100644 --- a/src/frontend/display/bthtmlreaddisplay.cpp +++ b/src/frontend/display/bthtmlreaddisplay.cpp @@ -12,7 +12,6 @@ #include <QSharedPointer> #include <QMenu> #include <QString> -#include "backend/config/cbtconfig.h" #include "backend/keys/cswordkey.h" #include "backend/managers/referencemanager.h" #include "frontend/cdragdrop.h" @@ -55,7 +54,7 @@ void BtHtmlReadDisplay::initJavascript() { namespace DU = util::directory; // read bthtml.js javascript file once - if (javascript.size() == 0) { + if (javascript.isEmpty()) { QString jsFile = DU::getJavascriptDir().canonicalPath() + "/bthtml.js"; QFile file(jsFile); if (file.open(QFile::ReadOnly)) { @@ -75,6 +74,16 @@ void BtHtmlReadDisplay::initJavascript() { // When the QWebFrame is cleared, this function is called to install the // javascript object (BtHtmlJsObject class) into the Javascript model void BtHtmlReadDisplay::loadJSObject() { + // Starting with Qt 4.7.4 with QtWebKit 2.2 stronger security checking occurs. + // The BtHtmlJsObject that is associated with a given load of a page is rejected + // as causing a cross site security problem when a new page is loaded. Deleting + // the object and creating it new for each page loaded allows the object to access + // javascript variables without this security issue. + if (m_jsObject != 0) + delete m_jsObject; + m_jsObject = new BtHtmlJsObject(this); + m_jsObject->setObjectName("btHtmlJsObject"); + mainFrame()->addToJavaScriptWindowObject(m_jsObject->objectName(), m_jsObject); } @@ -248,7 +257,7 @@ void BtHtmlReadDisplay::slotGoToAnchor(const QString& anchor) { // Save the Lemma (Strongs number) attribute void BtHtmlReadDisplay::setLemma(const QString& lemma) { - m_nodeInfo[ CDisplay::Lemma ] = lemma; + m_nodeInfo = lemma; } // Open the Find text dialog @@ -263,7 +272,7 @@ void BtHtmlReadDisplay::slotLoadFinished(bool) { } // For debugging javascript - set breakpoint in this function to catch javascript error messages -#if DEBUG_JS +#ifdef DEBUG_JS void BtHtmlReadDisplay::javaScriptConsoleMessage (const QString& message, int lineNumber, const QString& sourceID ) { } #endif diff --git a/src/frontend/display/bthtmlreaddisplay.h b/src/frontend/display/bthtmlreaddisplay.h index 21724b9..f1e1f5c 100644 --- a/src/frontend/display/bthtmlreaddisplay.h +++ b/src/frontend/display/bthtmlreaddisplay.h @@ -54,7 +54,7 @@ class BtHtmlReadDisplay : public QWebPage, public CReadDisplay { virtual void selectAll(); virtual void moveToAnchor( const QString& anchor ); virtual void openFindTextDialog(); - virtual QMap<CDisplay::NodeInfoType, QString> getCurrentNodeInfo() { + inline virtual QString getCurrentNodeInfo() const { return m_nodeInfo; } QWidget* view(); @@ -86,7 +86,7 @@ class BtHtmlReadDisplay : public QWebPage, public CReadDisplay { QString currentSource; - QMap<NodeInfoType, QString> m_nodeInfo; + QString m_nodeInfo; int m_magTimerId; // For debugging javascript - setbreakpoint in this function to catch javascript error messages diff --git a/src/frontend/display/cdisplay.cpp b/src/frontend/display/cdisplay.cpp index 78d9038..4def9f5 100644 --- a/src/frontend/display/cdisplay.cpp +++ b/src/frontend/display/cdisplay.cpp @@ -11,7 +11,6 @@ #include <QApplication> #include <QClipboard> -#include <QDebug> #include <QFileDialog> #include <QMenu> #include <QTimer> @@ -38,8 +37,6 @@ void CDisplayConnections::saveAsPlain() { /** Emits the signal. */ void CDisplayConnections::emitReferenceClicked( const QString& module, const QString& key) { - qDebug() << "CDisplayConnections::emitReferenceClicked"; - qDebug() << "Module: " << module << " key: " << key; emit referenceClicked( module, key ); } @@ -94,14 +91,6 @@ void CDisplayConnections::clear() { m_display->setText(QString::null); } -void CDisplayConnections::zoomIn() { - m_display->zoomIn(); -} - -void CDisplayConnections::zoomOut() { - m_display->zoomOut(); -} - void CDisplayConnections::openFindTextDialog() { m_display->openFindTextDialog(); } diff --git a/src/frontend/display/cdisplay.h b/src/frontend/display/cdisplay.h index af49178..a0a0020 100644 --- a/src/frontend/display/cdisplay.h +++ b/src/frontend/display/cdisplay.h @@ -102,17 +102,10 @@ class CDisplay { */ QMenu* installedPopup(); - virtual void zoomIn() {} - virtual void zoomOut() {} virtual void openFindTextDialog() {} - enum NodeInfoType { - Lemma - }; - - - virtual QMap<NodeInfoType, QString> getCurrentNodeInfo() { - return QMap<NodeInfoType, QString>(); + inline virtual QString getCurrentNodeInfo() const { + return QString::null; } protected: @@ -165,9 +158,6 @@ class CDisplayConnections : public QObject { void clear(); - void zoomIn(); - void zoomOut(); - void openFindTextDialog(); signals: diff --git a/src/frontend/display/cplainwritedisplay.cpp b/src/frontend/display/cplainwritedisplay.cpp index bfcbe0b..07cecf3 100644 --- a/src/frontend/display/cplainwritedisplay.cpp +++ b/src/frontend/display/cplainwritedisplay.cpp @@ -14,7 +14,6 @@ #include <QDragMoveEvent> #include <QDropEvent> #include <QMenu> -#include <QDebug> #include "backend/keys/cswordkey.h" #include "frontend/cdragdrop.h" @@ -32,8 +31,6 @@ CPlainWriteDisplay::CPlainWriteDisplay(CWriteWindow* parentWindow, QWidget* pare connectionsProxy(), SLOT(emitTextChanged())); } -CPlainWriteDisplay::~CPlainWriteDisplay() {} - /** Reimplementation. */ void CPlainWriteDisplay::selectAll() { QTextEdit::selectAll(); @@ -53,8 +50,7 @@ bool CPlainWriteDisplay::hasSelection() { return textCursor().hasSelection(); } -QWidget* CPlainWriteDisplay::view() { - qDebug() << "CPlainWriteDisplay::view()"; +QWidget *CPlainWriteDisplay::view() { return this; } @@ -114,11 +110,9 @@ void CPlainWriteDisplay::dragMoveEvent( QDragMoveEvent* e ) { /** Reimplementation to manage drops of our drag and drop objects. */ void CPlainWriteDisplay::dropEvent( QDropEvent* e ) { - //qDebug() << "CPlainWriteDisplay::dropEvent"; const BTMimeData* mimedata = qobject_cast<const BTMimeData*>(e->mimeData()); if ( mimedata && mimedata->hasFormat("BibleTime/Bookmark") ) { - //qDebug() << "format was bookmark"; e->acceptProposedAction(); BTMimeData::ItemList items = mimedata->bookmarks(); @@ -137,7 +131,6 @@ void CPlainWriteDisplay::dropEvent( QDropEvent* e ) { } } else if ( e->mimeData()->hasFormat("text/plain")) { - //qDebug() << "format was plain text"; e->acceptProposedAction(); setTextCursor(cursorForPosition(e->pos())); textCursor().insertText( e->mimeData()->text() ); diff --git a/src/frontend/display/cplainwritedisplay.h b/src/frontend/display/cplainwritedisplay.h index 2c7e1be..575789e 100644 --- a/src/frontend/display/cplainwritedisplay.h +++ b/src/frontend/display/cplainwritedisplay.h @@ -71,10 +71,8 @@ class CPlainWriteDisplay : public QTextEdit, public CWriteDisplay { protected: friend class CDisplay; - friend class CHTMLWriteDisplay; CPlainWriteDisplay(CWriteWindow* parentWindow, QWidget* parent); - virtual ~CPlainWriteDisplay(); /** * Reimplementation from QTextEdit to manage drops of our drag and drop objects. diff --git a/src/frontend/display/creaddisplay.cpp b/src/frontend/display/creaddisplay.cpp index 690ee57..f1b2f65 100644 --- a/src/frontend/display/creaddisplay.cpp +++ b/src/frontend/display/creaddisplay.cpp @@ -27,8 +27,6 @@ CReadDisplay::CReadDisplay(CReadWindow* readWindow) : m_activeAnchor(QString::null), m_useMouseTracking(true) {} -CReadDisplay::~CReadDisplay() {} - /** Returns the current active anchor. */ const QString& CReadDisplay::activeAnchor() { return m_activeAnchor; @@ -56,7 +54,7 @@ void CReadDisplay::print(const CDisplay::TextPart type, const CSwordModuleInfo *module = key->module(); const CDisplayWindow *displayWindow = parentWindow(); - CExportManager mgr(QObject::tr("Print keys"), false, QString::null, displayWindow->filterOptions(), displayWindow->displayOptions()); + CExportManager mgr(false, QString::null, displayWindow->filterOptions(), displayWindow->displayOptions()); switch (type) { case Document: { @@ -64,13 +62,13 @@ void CReadDisplay::print(const CDisplay::TextPart type, CSwordVerseKey* vk = dynamic_cast<CSwordVerseKey*>(key); CSwordVerseKey startKey(*vk); - startKey.Verse(1); + startKey.setVerse(1); CSwordVerseKey stopKey(*vk); const CSBiMI *bible = dynamic_cast<const CSBiMI*>(module); if (bible) { - stopKey.Verse( bible->verseCount( bible->bookNumber(startKey.book()), startKey.Chapter() ) ); + stopKey.setVerse(bible->verseCount(bible->bookNumber(startKey.book()), startKey.getChapter())); } mgr.printKey(module, startKey.key(), stopKey.key(), displayOptions, filterOptions); diff --git a/src/frontend/display/creaddisplay.h b/src/frontend/display/creaddisplay.h index d1e81c4..4b6dbeb 100644 --- a/src/frontend/display/creaddisplay.h +++ b/src/frontend/display/creaddisplay.h @@ -46,15 +46,10 @@ class CReadDisplay : public CDisplay { }; protected: // Protected methods - friend class BtHtmlReadDisplay; - friend class BtHtmlReadDisplayView; + friend class BtHtmlJsObject; - friend class CDisplay; - friend class CHTMLReadDisplay; - friend class CHTMLReadDisplayView; CReadDisplay( CReadWindow* readWindow ); - ~CReadDisplay(); /** * Sets the current anchor to the parameter. diff --git a/src/frontend/display/cwritedisplay.h b/src/frontend/display/cwritedisplay.h index 3591efe..0010749 100644 --- a/src/frontend/display/cwritedisplay.h +++ b/src/frontend/display/cwritedisplay.h @@ -21,8 +21,7 @@ class QToolBar; */ class CWriteDisplay : public CDisplay { protected: - friend class CDisplay; - friend class CPlainWriteDisplay; + CWriteDisplay( CWriteWindow* writeWindow ); ~CWriteDisplay(); diff --git a/src/frontend/displaywindow/btactioncollection.cpp b/src/frontend/displaywindow/btactioncollection.cpp index 9c26143..dd36939 100644 --- a/src/frontend/displaywindow/btactioncollection.cpp +++ b/src/frontend/displaywindow/btactioncollection.cpp @@ -19,117 +19,126 @@ #include "util/directory.h" -class BtActionItem : public QObject { - public: +class BtActionItem: public QObject { + + public: /* Methods: */ + BtActionItem(QAction *action, QObject *parent = 0) : QObject(parent), defaultKeys(action->shortcut()), action(action) { // Intentionally empty } + + public: /* Fields: */ + QKeySequence defaultKeys; QAction* action; -}; - -BtActionCollection::BtActionCollection(QObject* parent) - : QObject(parent) { -} -BtActionCollection::~BtActionCollection() { -} +}; QList<QAction*> BtActionCollection::actions() { QList<QAction*> actionList; - - QMap<QString, BtActionItem*>::const_iterator iter = m_actions.constBegin(); - while (iter != m_actions.constEnd()) { - QAction* action = iter.value()->action; - actionList.append(action); - ++iter; + for (ActionMap::const_iterator iter = m_actions.constBegin(); + iter != m_actions.constEnd(); + iter++) + { + actionList.append(iter.value()->action); } return actionList; } -QAction* BtActionCollection::action(const QString& name) { - if (m_actions.contains(name)) - return m_actions[name]->action; +QAction *BtActionCollection::action(const QString &name) const { + ActionMap::const_iterator it = m_actions.find(name); + if (it != m_actions.constEnd()) + return (*it)->action; + qWarning() << "A QAction for a shortcut named" << name << "was requested but it is not defined."; - return (new QAction(this)); // dummy QAction* + return 0; } QAction* BtActionCollection::addAction(const QString& name, QAction* action) { Q_ASSERT(action != 0); - if (m_actions.contains(name)) { - delete m_actions[name]; - } - BtActionItem* item = new BtActionItem(action, this); - m_actions.insert(name, item); + ActionMap::iterator it = m_actions.find(name); + if (it != m_actions.constEnd()) + delete *it; + + m_actions.insert(name, new BtActionItem(action, this)); return action; } QAction* BtActionCollection::addAction(const QString &name, const QObject *receiver, const char* member) { QAction* action = new QAction(name, this); if (receiver && member) { - bool ok = connect(action, SIGNAL(triggered()), receiver, SLOT(triggered())); + bool ok = connect(action, SIGNAL(triggered()), + receiver, SLOT(triggered())); Q_ASSERT(ok); } return addAction(name, action); } QKeySequence BtActionCollection::getDefaultShortcut(QAction* action) { - QMap<QString, BtActionItem*>::const_iterator iter = m_actions.constBegin(); - while (iter != m_actions.constEnd()) { - if ( iter.value()->action == action) { + for (ActionMap::const_iterator iter = m_actions.constBegin(); + iter != m_actions.constEnd(); + iter++) + { + if (iter.value()->action == action) { return iter.value()->defaultKeys; } - iter++; } return QKeySequence(); } -void BtActionCollection::setConfigGroup(const QString &group) { - m_groupName = group; -} - void BtActionCollection::readSettings() { QSettings* settings = CBTConfig::getConfig(); settings->beginGroup(m_groupName); - QStringList keyList = settings->childKeys(); - for (int i = 0; i < keyList.size(); i++) { - QString key = keyList.at(i); + + Q_FOREACH (const QString &key, settings->childKeys()) { + QAction *a = action(key); + if (a == 0) + continue; + QVariant variant = settings->value(key); + qDebug() << variant << " | " << variant.typeName(); + if (variant.type() != QVariant::List + && variant.type() != QVariant::StringList) + { + continue; + } + QList<QKeySequence> shortcuts; - if ( variant != QVariant()) { - QList<QVariant> varShortcuts = variant.toList(); - for (int i = 0; i < varShortcuts.count(); i++) { - QString keys = varShortcuts.at(i).toString(); - QKeySequence shortcut(keys); + if (variant.type() == QVariant::List) { // For BibleTime before 2.9 + Q_FOREACH (const QVariant &shortcut, variant.toList()) { + shortcuts.append(shortcut.toString()); + } + } else { + Q_ASSERT(variant.type() == QVariant::StringList); + Q_FOREACH (const QString &shortcut, variant.toStringList()) { shortcuts.append(shortcut); } } - action(key)->setShortcuts(shortcuts); + a->setShortcuts(shortcuts); } - settings->endGroup(); -} -static QList<QVariant> keyListToVariantList(const QList<QKeySequence>& keyList) { - QList<QVariant> varList; - for (int i = 0; i < keyList.count(); i++) { - QKeySequence keySeq = keyList.at(i); - varList.append(keySeq.toString()); - } - return varList; + settings->endGroup(); } void BtActionCollection::writeSettings() { QSettings* settings = CBTConfig::getConfig(); settings->beginGroup(m_groupName); - QMap<QString, BtActionItem*>::const_iterator iter = m_actions.constBegin(); - while (iter != m_actions.constEnd()) { - QString actionName = iter.key(); - QList<QKeySequence> keyList = iter.value()->action->shortcuts(); - QList<QVariant> varList = keyListToVariantList(keyList); - settings->setValue(actionName, varList); - iter++; + + for (ActionMap::const_iterator iter = m_actions.constBegin(); + iter != m_actions.constEnd(); + iter++) + { + // Write beautiful string lists (since 2.9): + QStringList varList; + Q_FOREACH (const QKeySequence &shortcut, iter.value()->action->shortcuts()) { + /// \note saving QKeySequences directly doesn't appear to work! + varList.append(shortcut.toString()); + } + settings->setValue(iter.key(), varList); + qDebug() << ">>" << settings->value(iter.key()).typeName(); } + settings->endGroup(); } diff --git a/src/frontend/displaywindow/btactioncollection.h b/src/frontend/displaywindow/btactioncollection.h index 2ce273d..e99522d 100644 --- a/src/frontend/displaywindow/btactioncollection.h +++ b/src/frontend/displaywindow/btactioncollection.h @@ -19,25 +19,42 @@ class BtActionItem; class QAction; class QKeySequence; -class QString; -class BtActionCollection : public QObject { +class BtActionCollection: public QObject { + Q_OBJECT - public: - BtActionCollection(QObject* parent); - ~BtActionCollection(); + + private: /* Types: */ + + typedef QMap<QString, BtActionItem*> ActionMap; + + public: /* Methods: */ + + inline BtActionCollection(QObject *parent = 0) : QObject(parent) {} + QAction* addAction(const QString& name, QAction* action); + QAction* addAction(const QString &name, const QObject *receiver, const char* member = 0); + QList<QAction*> actions(); - QAction* action(const QString& name); - void setConfigGroup(const QString &group); + + QAction *action(const QString &name) const; + + inline void setConfigGroup(const QString &group) { + m_groupName = group; + } + void readSettings(); + void writeSettings(); + QKeySequence getDefaultShortcut(QAction* action); - private: - QMap<QString, BtActionItem*> m_actions; + private: /* Fields: */ + + ActionMap m_actions; QString m_groupName; + }; #endif diff --git a/src/frontend/displaywindow/btdisplaysettingsbutton.cpp b/src/frontend/displaywindow/btdisplaysettingsbutton.cpp index 2fa1d2d..597a965 100644 --- a/src/frontend/displaywindow/btdisplaysettingsbutton.cpp +++ b/src/frontend/displaywindow/btdisplaysettingsbutton.cpp @@ -93,6 +93,9 @@ void BtDisplaySettingsButton::initMenu() { m_scriptureReferencesAction = new QAction(this); m_scriptureReferencesAction->setCheckable(true); + m_footnotesAction = new QAction(this); + m_footnotesAction->setCheckable(true); + m_morphSegmentationAction = new QAction(this); m_morphSegmentationAction->setCheckable(true); } @@ -107,6 +110,7 @@ void BtDisplaySettingsButton::retranslateUi() { m_greekAccentsAction->setText(tr("Show Greek accents")); m_variantAction->setText(tr("Use alternative textual variant")); m_scriptureReferencesAction->setText(tr("Show scripture cross-references")); + m_footnotesAction->setText(tr("Show footnotes")); m_morphSegmentationAction->setText(tr("Show morph segmentation")); retranslateToolTip(); @@ -151,6 +155,9 @@ void BtDisplaySettingsButton::slotOptionToggled(QAction *action) { } else if (action == m_scriptureReferencesAction) { m_filterOptions.scriptureReferences = checked; emit sigFilterOptionsChanged(m_filterOptions); + } else if (action == m_footnotesAction) { + m_filterOptions.footnotes = checked; + emit sigFilterOptionsChanged(m_filterOptions); } else if (action == m_redWordsAction) { m_filterOptions.redLetterWords = checked; emit sigFilterOptionsChanged(m_filterOptions); @@ -209,6 +216,11 @@ void BtDisplaySettingsButton::repopulateMenu() { enable = true; } + if (isOptionAvailable(CSwordModuleInfo::footnotes)) { + addMenuEntry(m_footnotesAction, m_filterOptions.footnotes); + enable = true; + } + if (isOptionAvailable(CSwordModuleInfo::morphSegmentation)) { addMenuEntry(m_morphSegmentationAction, m_filterOptions.morphSegmentation); enable = true; diff --git a/src/frontend/displaywindow/btdisplaysettingsbutton.h b/src/frontend/displaywindow/btdisplaysettingsbutton.h index 489395e..c7c8f09 100644 --- a/src/frontend/displaywindow/btdisplaysettingsbutton.h +++ b/src/frontend/displaywindow/btdisplaysettingsbutton.h @@ -69,6 +69,7 @@ class BtDisplaySettingsButton: public QToolButton { QAction *m_greekAccentsAction; QAction *m_variantAction; QAction *m_scriptureReferencesAction; + QAction *m_footnotesAction; QAction *m_morphSegmentationAction; }; diff --git a/src/frontend/displaywindow/btmodulechooserbar.cpp b/src/frontend/displaywindow/btmodulechooserbar.cpp index 29be862..22b5ca8 100644 --- a/src/frontend/displaywindow/btmodulechooserbar.cpp +++ b/src/frontend/displaywindow/btmodulechooserbar.cpp @@ -10,6 +10,7 @@ #include "frontend/displaywindow/btmodulechooserbar.h" #include "frontend/displaywindow/btmodulechooserbutton.h" #include "creadwindow.h" +#include "util/btmodules.h" #include <QAction> #include <QDebug> @@ -22,8 +23,6 @@ BtModuleChooserBar::BtModuleChooserBar(QWidget *parent) BtWindowModuleChooser(CSwordModuleInfo::Unknown, 0), m_idCounter(0), m_window(0) { - - qDebug() << "BtModuleChooserBar::BtModuleChooserBar"; setAllowedAreas(Qt::TopToolBarArea); setFloatable(false); } @@ -38,12 +37,12 @@ void BtModuleChooserBar::slotBackendModulesChanged() { BtModuleChooserButton* button = m_buttonList.at(i); QString moduleName = (i >= m_modules.count()) ? QString::null : m_modules.at(i); qDebug() << "refresh button's menu:" << moduleName << i; - button->recreateMenu(m_modules, moduleName, i); + int leftLikeModules = leftLikeParallelModules(m_modules); + button->recreateMenu(m_modules, moduleName, i, leftLikeModules); } } void BtModuleChooserBar::adjustButtonCount(bool adjustToZero) { - //qDebug() << "BtModuleChooserBar::ajustButtonCount"; int buttonCountDifference = 0; if (adjustToZero) { buttonCountDifference = m_buttonList.count(); @@ -69,14 +68,12 @@ void BtModuleChooserBar::adjustButtonCount(bool adjustToZero) { } void BtModuleChooserBar::slotWindowModulesChanged() { - //qDebug() << "BtModuleChooserBar::windowModulesChanged"; m_modules = m_window->getModuleList(); adjustButtonCount(); updateButtonMenus(); } BtModuleChooserButton* BtModuleChooserBar::addButton() { - //qDebug() << "BtModuleChooserBar::addButton"; BtModuleChooserButton* b = new BtModuleChooserButton(this, m_moduleType); QAction* a = addWidget(b); m_buttonList.append(b); @@ -94,7 +91,6 @@ BtModuleChooserButton* BtModuleChooserBar::addButton() { /** Sets the modules which are chosen in this module chooser bar. */ void BtModuleChooserBar::setModules( QStringList useModules,CSwordModuleInfo::ModuleType type, CReadWindow* window) { - qDebug() << "BtModuleChooserBar::setModules"; m_modules = useModules; m_window = window; m_moduleType = type; @@ -111,19 +107,16 @@ void BtModuleChooserBar::setModules( QStringList useModules,CSwordModuleInfo::Mo addButton(); // for ADD button } updateButtonMenus(); - qDebug() << "BtModuleChooserBar::setModules end"; connect(m_window, SIGNAL(sigModuleListSet(QStringList)), SLOT(slotBackendModulesChanged())); connect(m_window, SIGNAL(sigModuleListChanged()), SLOT(slotWindowModulesChanged())); } void BtModuleChooserBar::updateButtonMenus() { - //qDebug() << "BtModuleChooserBar::updateMenuItems"; - + int leftLikeModules = leftLikeParallelModules(m_modules); for (int i = 0; i < m_buttonList.count(); i++) { BtModuleChooserButton* button = m_buttonList.at(i); QString moduleName = (i >= m_modules.count()) ? QString::null : m_modules.at(i); - //qDebug() << "refresh button's menu:" << moduleName << i; - button->updateMenu(m_modules, moduleName, i); + button->updateMenu(m_modules, moduleName, i, leftLikeModules); } } diff --git a/src/frontend/displaywindow/btmodulechooserbutton.cpp b/src/frontend/displaywindow/btmodulechooserbutton.cpp index 9c8ad2f..200da78 100644 --- a/src/frontend/displaywindow/btmodulechooserbutton.cpp +++ b/src/frontend/displaywindow/btmodulechooserbutton.cpp @@ -26,19 +26,15 @@ BtModuleChooserButton::BtModuleChooserButton(BtModuleChooserBar *parent, CSwordM : QToolButton(parent), m_moduleType(mtype), m_popup(0) { - //qDebug()<<"BtModuleChooserButton::BtModuleChooserButton"; setPopupMode(QToolButton::InstantPopup); } -BtModuleChooserButton::~BtModuleChooserButton() {} - -void BtModuleChooserButton::recreateMenu(QStringList newModulesToUse, QString thisModule, int newIndex) { +void BtModuleChooserButton::recreateMenu(QStringList newModulesToUse, QString thisModule, int newIndex, int leftLikeModules) { populateMenu(); - updateMenu(newModulesToUse, thisModule, newIndex); + updateMenu(newModulesToUse, thisModule, newIndex, leftLikeModules); } const QString BtModuleChooserButton::iconName() { - qDebug() << "BtModuleChooserButton::iconName, has module:" << m_hasModule; switch (m_moduleType) { case CSwordModuleInfo::Bible: return (m_hasModule) ? CResMgr::modules::bible::icon_unlocked : CResMgr::modules::bible::icon_add; @@ -53,12 +49,13 @@ const QString BtModuleChooserButton::iconName() { } } -void BtModuleChooserButton::updateMenu(QStringList newModulesToUse, QString thisModule, int newIndex) { - //qDebug() << "BtModuleChooserButton::updateMenu" << newModulesToUse << thisModule << newIndex << this; +void BtModuleChooserButton::updateMenu(QStringList newModulesToUse, QString thisModule, int newIndex, int leftLikeModules) { + m_id = newIndex; + // create the menu if it doesn't exist - if (!m_popup) populateMenu(); + if (!m_popup) + populateMenu(); - m_id = newIndex; m_module = thisModule; m_hasModule = thisModule.isEmpty() ? false : true; namespace DU = util::directory; @@ -81,14 +78,27 @@ void BtModuleChooserButton::updateMenu(QStringList newModulesToUse, QString this else { setToolTip( tr("Select an additional work") ); } - m_noneAction->setDisabled((newModulesToUse.count() == 1) ? true : false); - //qDebug()<<"BtModuleChooserButton::modulesChanged end"; + bool disableNone = false; + if (newModulesToUse.count() == 1 || + (newIndex == 0 && leftLikeModules == 1)) + disableNone = true; + m_noneAction->setDisabled(disableNone); + + // Disable non-Bible categories on first button + if (m_moduleType == CSwordModuleInfo::Bible && m_id == 0) { + QList<QAction*> actions = m_popup->actions(); + for (int i=0; i<actions.count(); i++) { + QAction* action = actions.at(i); + QString text = action->text(); + if (text != QObject::tr("Bibles")) { + action->setDisabled(true); + } + } + } } /** Is called after a module was selected in the popup */ void BtModuleChooserButton::moduleChosen( QAction* action ) { - //qDebug() << "BtModuleChooserButton::moduleChosen"; - if (action->text() == tr("NONE")) { // note: this is for m_popup, the toplevel! if (m_hasModule) { qDebug() << "remove module" << m_id; @@ -112,7 +122,6 @@ void BtModuleChooserButton::moduleChosen( QAction* action ) { void BtModuleChooserButton::populateMenu() { - //qDebug()<<"BtModuleChooserButton::populateMenu"; qDeleteAll(m_submenus); m_submenus.clear(); delete m_popup; @@ -131,22 +140,36 @@ void BtModuleChooserButton::populateMenu() { // Filters: add only non-hidden and right type BTModuleTreeItem::HiddenOff hiddenFilter; - TypeFilter typeFilter(m_moduleType); QList<BTModuleTreeItem::Filter*> filters; if (!CBTConfig::get(CBTConfig::bookshelfShowHidden)) { filters.append(&hiddenFilter); } + TypeFilter typeFilter(m_moduleType); filters.append(&typeFilter); - BTModuleTreeItem root(filters, BTModuleTreeItem::LangMod); - // add all items recursively - addItemToMenu(&root, m_popup); + + if (m_moduleType == CSwordModuleInfo::Bible) { + BTModuleTreeItem root(filters, BTModuleTreeItem::CatLangMod); + QList<BTModuleTreeItem::Filter*> filters2; + if (!CBTConfig::get(CBTConfig::bookshelfShowHidden)) { + filters2.append(&hiddenFilter); + } + TypeFilter typeFilter2(CSwordModuleInfo::Commentary); + filters2.append(&typeFilter2); + root.add_items(filters2); + // add all items recursively + addItemToMenu(&root, m_popup); + } + else { + BTModuleTreeItem root(filters, BTModuleTreeItem::LangMod); + addItemToMenu(&root, m_popup); + } } void BtModuleChooserButton::addItemToMenu(BTModuleTreeItem* item, QMenu* menu) { - qDebug() << "BtModuleChooserButton::addItemToMenu"; foreach (BTModuleTreeItem* i, item->children()) { - if (i->type() == BTModuleTreeItem::Language) { + if (i->type() == BTModuleTreeItem::Language || + i->type() == BTModuleTreeItem::Category ) { // argument menu was m_popup, create and add a new lang menu to it QMenu* langMenu = new QMenu(i->text(), this); menu->addMenu(langMenu); diff --git a/src/frontend/displaywindow/btmodulechooserbutton.h b/src/frontend/displaywindow/btmodulechooserbutton.h index 270603b..ba7d89e 100644 --- a/src/frontend/displaywindow/btmodulechooserbutton.h +++ b/src/frontend/displaywindow/btmodulechooserbutton.h @@ -44,8 +44,6 @@ class BtModuleChooserButton : public QToolButton { * A new empty button. updateMenu() is needed to update the icon, menu items etc. */ BtModuleChooserButton(BtModuleChooserBar *parent, CSwordModuleInfo::ModuleType mtype); - /** Does nothing. All resources are freed and children deleted automatically.*/ - ~BtModuleChooserButton(); // /** Returns the module name this button represents. Not needed?*/ //QString module(); @@ -61,10 +59,10 @@ class BtModuleChooserButton : public QToolButton { * If the menu doesn't exist, creates it first and then updates it. * Updates also the icon. */ - void updateMenu(QStringList newModulesToUse, QString thisModule, int newIndex); + void updateMenu(QStringList newModulesToUse, QString thisModule, int newIndex, int leftLikeModules); /** Creates the menu from scratch and updates the items using updateMenu().*/ - void recreateMenu(QStringList newModulesToUse, QString thisModule, int newIndex); + void recreateMenu(QStringList newModulesToUse, QString thisModule, int newIndex, int leftLikeModules); signals: /** User selected a module from menu to replace another module*/ diff --git a/src/frontend/displaywindow/bttextwindowheader.cpp b/src/frontend/displaywindow/bttextwindowheader.cpp index 5bacf2b..71e98f0 100644 --- a/src/frontend/displaywindow/bttextwindowheader.cpp +++ b/src/frontend/displaywindow/bttextwindowheader.cpp @@ -11,6 +11,7 @@ #include "bttextwindowheaderwidget.h" #include "clexiconreadwindow.h" +#include "util/btmodules.h" #include <QStringList> #include <QWidget> @@ -37,8 +38,6 @@ BtTextWindowHeader::BtTextWindowHeader(CSwordModuleInfo::ModuleType modtype, connect(window, SIGNAL(sigModuleListChanged()), SLOT(slotWindowModulesChanged())); } -BtTextWindowHeader::~BtTextWindowHeader() {} - void BtTextWindowHeader::slotBackendModulesChanged() { m_modules = m_window->getModuleList(); @@ -49,7 +48,8 @@ void BtTextWindowHeader::slotBackendModulesChanged() { BtTextWindowHeaderWidget* widgt = m_widgetList.at(i); QString moduleName = m_modules.at(i); qDebug() << "refresh button's menu:" << moduleName << i; - widgt->recreateWidget(m_modules, moduleName, i); + int leftLikeModules = leftLikeParallelModules(m_modules); + widgt->recreateWidget(m_modules, moduleName, i, leftLikeModules); } } @@ -60,7 +60,6 @@ void BtTextWindowHeader::slotWindowModulesChanged() { } void BtTextWindowHeader::adjustWidgetCount(bool adjustToZero) { - //qDebug() << "BtModuleChooserBar::ajustButtonCount"; int widgetCountDifference = 0; if (adjustToZero) { widgetCountDifference = m_widgetList.count(); @@ -105,7 +104,6 @@ BtTextWindowHeaderWidget* BtTextWindowHeader::addWidget() { } void BtTextWindowHeader::setModules( QStringList useModules ) { - qDebug() << "BtModuleChooserBar::setModules"; m_modules = useModules; adjustWidgetCount(true); @@ -114,14 +112,13 @@ void BtTextWindowHeader::setModules( QStringList useModules ) { addWidget(); } updateWidgets(); - //qDebug() << "BtModuleChooserBar::setModules end"; } void BtTextWindowHeader::updateWidgets() { + int leftLikeModules = leftLikeParallelModules(m_modules); for (int i = 0; i < m_widgetList.count(); i++) { BtTextWindowHeaderWidget* w = m_widgetList.at(i); //QString moduleName = m_modules.at(i); - //qDebug() << "refresh button's menu:" << moduleName << i; - w->updateWidget(m_modules, m_modules.at(i), i); + w->updateWidget(m_modules, m_modules.at(i), i, leftLikeModules); } } diff --git a/src/frontend/displaywindow/bttextwindowheader.h b/src/frontend/displaywindow/bttextwindowheader.h index 1ea86b4..6dd4b0a 100644 --- a/src/frontend/displaywindow/bttextwindowheader.h +++ b/src/frontend/displaywindow/bttextwindowheader.h @@ -23,7 +23,6 @@ class BtTextWindowHeader: public QWidget, public BtWindowModuleChooser { Q_OBJECT public: BtTextWindowHeader(CSwordModuleInfo::ModuleType modtype, QStringList modules, CDisplayWindow *window); - virtual ~BtTextWindowHeader(); public slots: /** diff --git a/src/frontend/displaywindow/bttextwindowheaderwidget.cpp b/src/frontend/displaywindow/bttextwindowheaderwidget.cpp index f0829bc..600bf15 100644 --- a/src/frontend/displaywindow/bttextwindowheaderwidget.cpp +++ b/src/frontend/displaywindow/bttextwindowheaderwidget.cpp @@ -9,8 +9,6 @@ #include "frontend/displaywindow/bttextwindowheaderwidget.h" -#include <QDebug> -//#include <QHash> #include <QMenu> #include <QString> #include <QToolButton> @@ -54,16 +52,13 @@ BtTextWindowHeaderWidget::BtTextWindowHeaderWidget(BtTextWindowHeader *parent, C layout->addWidget(m_separator); } -BtTextWindowHeaderWidget::~BtTextWindowHeaderWidget() {} - -void BtTextWindowHeaderWidget::recreateWidget(QStringList newModulesToUse, QString thisModule, int newIndex) { +void BtTextWindowHeaderWidget::recreateWidget(QStringList newModulesToUse, QString thisModule, int newIndex, int lefLikeModules) { populateMenu(); - updateWidget(newModulesToUse, thisModule, newIndex); + updateWidget(newModulesToUse, thisModule, newIndex, lefLikeModules); } // don't remove yet, maybe we'll add icons to buttons... // const QString BtTextWindowHeaderWidget::iconName() { -// qDebug() << "BtTextWindowHeaderWidget::iconName, has module:" << m_hasModule; // switch (m_moduleType) { // case CSwordModuleInfo::Bible: // return (m_hasModule) ? CResMgr::modules::bible::icon_unlocked : CResMgr::modules::bible::icon_add; @@ -78,13 +73,13 @@ void BtTextWindowHeaderWidget::recreateWidget(QStringList newModulesToUse, QStri // } // } -void BtTextWindowHeaderWidget::updateWidget(QStringList newModulesToUse, QString thisModule, int newIndex) { - //qDebug() << "BtTextWindowHeaderWidget::updateMenu" << newModulesToUse << thisModule << newIndex << this; +void BtTextWindowHeaderWidget::updateWidget(QStringList newModulesToUse, QString thisModule, int newIndex, int leftLikeModules) { m_label->setText(thisModule); + m_id = newIndex; // create the menu if it doesn't exist - if (!m_popup) populateMenu(); + if (!m_popup) + populateMenu(); - m_id = newIndex; m_module = thisModule; namespace DU = util::directory; @@ -98,20 +93,37 @@ void BtTextWindowHeaderWidget::updateWidget(QStringList newModulesToUse, QString } } - if (m_id == newModulesToUse.count() - 1) { - // this is the rightmost module, hide the separator - m_separator->hide(); - } - else { - m_separator->show(); + bool disableRemove = false; + if (newModulesToUse.count() == 1 || + (newIndex == 0 && leftLikeModules == 1)) + disableRemove = true; + m_removeAction->setDisabled(disableRemove); + + // Disable non-Bible categories on left replace menu + if (m_moduleType == CSwordModuleInfo::Bible && m_id == 0) { + QList<QAction*> actionsType = m_popup->actions(); + for (int t=0; t<actionsType.count(); t++) { + QAction* actionType = actionsType.at(t); + QString typeText = actionType->text(); + if (typeText != QObject::tr("Replace")) + continue; + QMenu* menuType = actionType->menu(); + if (menuType == 0) + continue; + QList<QAction*> actions = menuType->actions(); + for (int i=0; i<actions.count(); i++) { + QAction* action = actions.at(i); + QString text = action->text(); + if (text != QObject::tr("Bibles")) { + action->setDisabled(true); + } + } + } } - m_removeAction->setDisabled((newModulesToUse.count() == 1) ? true : false); } /** Is called after a module was selected in the popup */ void BtTextWindowHeaderWidget::moduleChosen( QAction* action ) { - //qDebug() << "BtTextWindowHeaderWidget::moduleChosen"; - if (action->property(ActionType).toInt() == RemoveAction) { // note: this is for m_popup, the toplevel! emit sigModuleRemove(m_id); return; @@ -127,7 +139,6 @@ void BtTextWindowHeaderWidget::moduleChosen( QAction* action ) { void BtTextWindowHeaderWidget::populateMenu() { - //qDebug()<<"BtTextWindowHeaderWidget::populateMenu"; delete m_popup; m_popup = new QMenu(m_button); @@ -155,28 +166,41 @@ void BtTextWindowHeaderWidget::populateMenu() { toplevelMenus.append(addItem); foreach(QMenu* menu, toplevelMenus) { - // ******* Add languages and modules ******** - //m_popup->addSeparator(); - + // ******* Add categories, languages and modules ******** // Filters: add only non-hidden, non-locked and correct type BTModuleTreeItem::HiddenOff hiddenFilter; - TypeFilter typeFilter(m_moduleType); QList<BTModuleTreeItem::Filter*> filters; if (!CBTConfig::get(CBTConfig::bookshelfShowHidden)) { filters.append(&hiddenFilter); } + TypeFilter typeFilter(m_moduleType); filters.append(&typeFilter); - BTModuleTreeItem root(filters, BTModuleTreeItem::LangMod); - // add all items recursively - addItemToMenu(&root, menu, (TypeOfAction)menu->property(ActionType).toInt()); + + if (m_moduleType == CSwordModuleInfo::Bible) { + BTModuleTreeItem root(filters, BTModuleTreeItem::CatLangMod); + QList<BTModuleTreeItem::Filter*> filters2; + if (!CBTConfig::get(CBTConfig::bookshelfShowHidden)) { + filters2.append(&hiddenFilter); + } + if (menu == addItem || menu == replaceItem) { + TypeFilter typeFilter2(CSwordModuleInfo::Commentary); + filters2.append(&typeFilter2); + root.add_items(filters2); + } + addItemToMenu(&root, menu, (TypeOfAction)menu->property(ActionType).toInt()); + } + else { + BTModuleTreeItem root(filters, BTModuleTreeItem::LangMod); + addItemToMenu(&root, menu, (TypeOfAction)menu->property(ActionType).toInt()); + } } } void BtTextWindowHeaderWidget::addItemToMenu(BTModuleTreeItem* item, QMenu* menu, TypeOfAction actionType) { - qDebug() << "BtTextWindowHeaderWidget::addItemToMenu"; foreach (BTModuleTreeItem* i, item->children()) { - if (i->type() == BTModuleTreeItem::Language) { + if (i->type() == BTModuleTreeItem::Language || + i->type() == BTModuleTreeItem::Category) { // argument menu was m_popup, create and add a new lang menu to it QMenu* langMenu = new QMenu(i->text(), this); menu->addMenu(langMenu); diff --git a/src/frontend/displaywindow/bttextwindowheaderwidget.h b/src/frontend/displaywindow/bttextwindowheaderwidget.h index d2bbe40..02e0310 100644 --- a/src/frontend/displaywindow/bttextwindowheaderwidget.h +++ b/src/frontend/displaywindow/bttextwindowheaderwidget.h @@ -54,8 +54,6 @@ class BtTextWindowHeaderWidget : public QWidget { * A new empty widget. updateMenu() is needed to update the label, menu items etc. */ BtTextWindowHeaderWidget(BtTextWindowHeader *parent, CSwordModuleInfo::ModuleType mtype); - /** Does nothing. All resources are freed and children deleted automatically.*/ - ~BtTextWindowHeaderWidget(); public: /** @@ -63,10 +61,10 @@ class BtTextWindowHeaderWidget : public QWidget { * the existing menu items but doesn't add or remove them if the menu exists. * If the menu doesn't exist, creates it first and then updates it. */ - void updateWidget(QStringList newModulesToUse, QString thisModule, int newIndex); + void updateWidget(QStringList newModulesToUse, QString thisModule, int newIndex, int leftLikeModules); /** Creates the menu from scratch and updates the items using updateMenu().*/ - void recreateWidget(QStringList newModulesToUse, QString thisModule, int newIndex); + void recreateWidget(QStringList newModulesToUse, QString thisModule, int newIndex, int leftLikeModules); signals: /** User selected a module from menu to replace an existing module.*/ diff --git a/src/frontend/displaywindow/btwindowmodulechooser.h b/src/frontend/displaywindow/btwindowmodulechooser.h index 1cf3fd1..a39e7a1 100644 --- a/src/frontend/displaywindow/btwindowmodulechooser.h +++ b/src/frontend/displaywindow/btwindowmodulechooser.h @@ -39,8 +39,6 @@ class BtWindowModuleChooser { CDisplayWindow *parentWindow) : m_window(parentWindow), m_moduleType (moduleType) {} - virtual ~BtWindowModuleChooser() {} - /** * The backend module list was updated, module list and widgets must be updated. * This expects that the window module list has already been updated, so diff --git a/src/frontend/displaywindow/cbiblereadwindow.cpp b/src/frontend/displaywindow/cbiblereadwindow.cpp index 868dd8d..aa6ae6b 100644 --- a/src/frontend/displaywindow/cbiblereadwindow.cpp +++ b/src/frontend/displaywindow/cbiblereadwindow.cpp @@ -16,8 +16,6 @@ #include <QMenu> #include <QTimer> #include <QWidget> -#include <QDebug> - #include "backend/config/cbtconfig.h" #include "backend/drivers/cswordbiblemoduleinfo.h" #include "backend/keys/cswordversekey.h" @@ -38,7 +36,6 @@ using namespace Profile; CBibleReadWindow::CBibleReadWindow(QList<CSwordModuleInfo*> moduleList, CMDIArea* parent) : CLexiconReadWindow(moduleList, parent) { - qDebug() << "CBibleReadWindow::CBibleReadWindow"; } CBibleReadWindow::~CBibleReadWindow() { @@ -51,7 +48,7 @@ void CBibleReadWindow::applyProfileSettings(CProfileWindow* const settings) { */ CLexiconReadWindow::applyProfileSettings(settings); - int result = settings->windowSettings(); + int result = settings->windowSettings; filterOptions().footnotes = (result & 0x0001) != 0; filterOptions().strongNumbers = (result & 0x0002) != 0; @@ -97,7 +94,7 @@ void CBibleReadWindow::storeProfileSettings( CProfileWindow * const settings) { if (displayOptions().lineBreaks) result |= 0x1000; if (displayOptions().verseNumbers) result |= 0x2000; - settings->setWindowSettings(result); + settings->windowSettings = result; CLexiconReadWindow::storeProfileSettings(settings); } @@ -167,87 +164,114 @@ void CBibleReadWindow::insertKeyboardActions( BtActionCollection* const a ) { } void CBibleReadWindow::initActions() { - qDebug() << "CBibleReadWindow::initActions"; - BtActionCollection* ac = actionCollection(); CLexiconReadWindow::initActions(); //make sure the predefined actions are available CBibleReadWindow::insertKeyboardActions(ac); + QAction * qaction; + //cleanup, not a clean oo-solution - ac->action("nextEntry")->setEnabled(false); - ac->action("previousEntry")->setEnabled(false); + qaction = ac->action("nextEntry"); + Q_ASSERT(qaction != 0); + qaction->setEnabled(false); + qaction = ac->action("previousEntry"); + Q_ASSERT(qaction != 0); + qaction->setEnabled(false); - QAction* qaction; qaction = m_actionCollection->action("nextBook"); + Q_ASSERT(qaction != 0); QObject::connect(qaction, SIGNAL(triggered()), this, SLOT(nextBook()) ); addAction(qaction); qaction = m_actionCollection->action("previousBook"); + Q_ASSERT(qaction != 0); QObject::connect(qaction, SIGNAL(triggered()), this, SLOT(previousBook()) ); addAction(qaction); qaction = m_actionCollection->action("nextChapter"); + Q_ASSERT(qaction != 0); QObject::connect(qaction, SIGNAL(triggered()), this, SLOT(nextChapter()) ); addAction(qaction); qaction = m_actionCollection->action("previousChapter"); + Q_ASSERT(qaction != 0); QObject::connect(qaction, SIGNAL(triggered()), this, SLOT(previousChapter()) ); addAction(qaction); qaction = m_actionCollection->action("nextVerse"); + Q_ASSERT(qaction != 0); QObject::connect(qaction, SIGNAL(triggered()), this, SLOT(nextVerse()) ); addAction(qaction); qaction = m_actionCollection->action("previousVerse"); + Q_ASSERT(qaction != 0); QObject::connect(qaction, SIGNAL(triggered()), this, SLOT(previousVerse()) ); addAction(qaction); m_actions.selectAll = ac->action("selectAll"); - Q_ASSERT(m_actions.selectAll); + Q_ASSERT(m_actions.selectAll != 0); m_actions.findText = ac->action("findText"); - Q_ASSERT(m_actions.findText); + Q_ASSERT(m_actions.findText != 0); m_actions.findStrongs = m_actionCollection->action(CResMgr::displaywindows::general::findStrongs::actionName); + Q_ASSERT(m_actions.findStrongs != 0); m_actions.copy.referenceOnly = m_actionCollection->action("copyReferenceOnly"); + Q_ASSERT(m_actions.copy.referenceOnly != 0); m_actions.copy.referenceTextOnly = m_actionCollection->action("copyTextOfReference"); - QObject::connect(m_actions.copy.referenceTextOnly, SIGNAL(triggered()), displayWidget()->connectionsProxy(), SLOT(copyAnchorTextOnly()) ); + Q_ASSERT(m_actions.copy.referenceTextOnly != 0); + QObject::connect(m_actions.copy.referenceTextOnly, SIGNAL(triggered()), + displayWidget()->connectionsProxy(), SLOT(copyAnchorTextOnly())); addAction(m_actions.copy.referenceTextOnly); m_actions.copy.referenceAndText = m_actionCollection->action("copyReferenceWithText"); - QObject::connect(m_actions.copy.referenceAndText, SIGNAL(triggered()), displayWidget()->connectionsProxy(), SLOT(copyAnchorWithText()) ); + Q_ASSERT(m_actions.copy.referenceAndText != 0); + QObject::connect(m_actions.copy.referenceAndText, SIGNAL(triggered()), + displayWidget()->connectionsProxy(), SLOT(copyAnchorWithText())); addAction(m_actions.copy.referenceAndText); m_actions.copy.chapter = m_actionCollection->action("copyChapter"); - QObject::connect(m_actions.copy.chapter, SIGNAL(triggered()), this, SLOT(copyDisplayedText()) ); + Q_ASSERT(m_actions.copy.chapter != 0); + QObject::connect(m_actions.copy.chapter, SIGNAL(triggered()), + this, SLOT(copyDisplayedText())); addAction(m_actions.copy.chapter); m_actions.copy.selectedText = ac->action("copySelectedText"); - Q_ASSERT(m_actions.copy.selectedText); + Q_ASSERT(m_actions.copy.selectedText != 0); m_actions.save.referenceAndText = m_actionCollection->action("saveReferenceWithText"); - QObject::connect(m_actions.save.referenceAndText, SIGNAL(triggered()), displayWidget()->connectionsProxy(), SLOT(saveAnchorWithText()) ); + Q_ASSERT(m_actions.save.referenceAndText != 0); + QObject::connect(m_actions.save.referenceAndText, SIGNAL(triggered()), + displayWidget()->connectionsProxy(), SLOT(saveAnchorWithText())); addAction(m_actions.copy.chapter); m_actions.save.chapterAsPlain = m_actionCollection->action("saveChapterAsPlainText"); - QObject::connect(m_actions.save.chapterAsPlain, SIGNAL(triggered()), this, SLOT(saveChapterPlain()) ); + Q_ASSERT(m_actions.save.chapterAsPlain != 0); + QObject::connect(m_actions.save.chapterAsPlain, SIGNAL(triggered()), + this, SLOT(saveChapterPlain())); addAction(m_actions.save.referenceAndText); m_actions.save.chapterAsHTML = m_actionCollection->action("saveChapterAsHTML"); - QObject::connect(m_actions.save.chapterAsHTML, SIGNAL(triggered()), this, SLOT(saveChapterHTML()) ); + Q_ASSERT(m_actions.save.chapterAsHTML != 0); + QObject::connect(m_actions.save.chapterAsHTML, SIGNAL(triggered()), + this, SLOT(saveChapterHTML())); addAction(m_actions.save.chapterAsHTML); m_actions.print.reference = m_actionCollection->action("printReferenceWithText"); - QObject::connect(m_actions.print.reference, SIGNAL(triggered()), this, SLOT(printAnchorWithText()) ); + Q_ASSERT(m_actions.print.reference != 0); + QObject::connect(m_actions.print.reference, SIGNAL(triggered()), + this, SLOT(printAnchorWithText())); addAction(m_actions.print.reference); m_actions.print.chapter = m_actionCollection->action("printChapter"); - QObject::connect(m_actions.print.chapter, SIGNAL(triggered()), this, SLOT(printAll()) ); + Q_ASSERT(m_actions.print.chapter != 0); + QObject::connect(m_actions.print.chapter, SIGNAL(triggered()), + this, SLOT(printAll())); addAction(m_actions.print.chapter); CBTConfig::setupAccelSettings(CBTConfig::bibleWindow, ac); @@ -313,7 +337,7 @@ void CBibleReadWindow::setupPopupMenu() { void CBibleReadWindow::updatePopupMenu() { qWarning("CBibleReadWindow::updatePopupMenu()"); - m_actions.findStrongs->setEnabled( displayWidget()->getCurrentNodeInfo()[CDisplay::Lemma] != QString::null ); + m_actions.findStrongs->setEnabled(!displayWidget()->getCurrentNodeInfo().isNull()); m_actions.copy.referenceOnly->setEnabled( ((CReadDisplay*)displayWidget())->hasActiveAnchor() ); m_actions.copy.referenceTextOnly->setEnabled( ((CReadDisplay*)displayWidget())->hasActiveAnchor() ); @@ -378,16 +402,16 @@ CSwordVerseKey* CBibleReadWindow::verseKey() { /** Copies the current chapter into the clipboard. */ void CBibleReadWindow::copyDisplayedText() { CSwordVerseKey dummy(*verseKey()); - dummy.Verse(1); + dummy.setVerse(1); CSwordVerseKey vk(*verseKey()); vk.LowerBound(dummy); const CSwordBibleModuleInfo* bible = dynamic_cast<const CSwordBibleModuleInfo*>(modules().first()); - dummy.Verse(bible->verseCount(dummy.book(), dummy.Chapter())); + dummy.setVerse(bible->verseCount(dummy.book(), dummy.getChapter())); vk.UpperBound(dummy); - CExportManager mgr(tr("Copy chapter to clipboard ..."), false, tr("Copying"), filterOptions(), displayOptions()); + CExportManager mgr(false, tr("Copying"), filterOptions(), displayOptions()); mgr.copyKey(&vk, CExportManager::Text, true); } @@ -398,15 +422,15 @@ void CBibleReadWindow::saveChapterHTML() { const CSwordBibleModuleInfo *bible = static_cast<const CSwordBibleModuleInfo*>(modules().first()); CSwordVerseKey dummy(*verseKey()); - dummy.Verse(1); + dummy.setVerse(1); CSwordVerseKey vk(*verseKey()); vk.LowerBound(dummy); - dummy.Verse(bible->verseCount(dummy.book(), dummy.Chapter())); + dummy.setVerse(bible->verseCount(dummy.book(), dummy.getChapter())); vk.UpperBound(dummy); - CExportManager mgr(tr("Saving chapter ..."), true, tr("Saving"), filterOptions(), displayOptions()); + CExportManager mgr(true, tr("Saving"), filterOptions(), displayOptions()); mgr.saveKey(&vk, CExportManager::HTML, true); } @@ -417,21 +441,21 @@ void CBibleReadWindow::saveChapterPlain() { CSwordVerseKey vk(*verseKey()); CSwordVerseKey dummy(*verseKey()); - dummy.Verse(1); + dummy.setVerse(1); vk.LowerBound(dummy); const CSwordBibleModuleInfo* bible = dynamic_cast<const CSwordBibleModuleInfo*>(modules().first()); - dummy.Verse(bible->verseCount(dummy.book(), dummy.Chapter())); + dummy.setVerse(bible->verseCount(dummy.book(), dummy.getChapter())); vk.UpperBound(dummy); - CExportManager mgr(tr("Saving chapter ..."), true, tr("Saving"), filterOptions(), displayOptions()); + CExportManager mgr(true, tr("Saving"), filterOptions(), displayOptions()); mgr.saveKey(&vk, CExportManager::Text, true); } void CBibleReadWindow::reload(CSwordBackend::SetupChangedReason reason) { CLexiconReadWindow::reload(reason); - if (m_modules.count() == 0) { + if (m_modules.isEmpty()) { close(); return; } diff --git a/src/frontend/displaywindow/cbiblereadwindow.h b/src/frontend/displaywindow/cbiblereadwindow.h index 117c778..198c4fd 100644 --- a/src/frontend/displaywindow/cbiblereadwindow.h +++ b/src/frontend/displaywindow/cbiblereadwindow.h @@ -125,7 +125,7 @@ class CBibleReadWindow : public CLexiconReadWindow { void syncWindows(); private: - friend class CCommentaryReadWindow; + /** * Wrapper around key() to return the right type of key. */ diff --git a/src/frontend/displaywindow/cbookreadwindow.cpp b/src/frontend/displaywindow/cbookreadwindow.cpp index 3aba333..ff2adf2 100644 --- a/src/frontend/displaywindow/cbookreadwindow.cpp +++ b/src/frontend/displaywindow/cbookreadwindow.cpp @@ -39,8 +39,7 @@ CBookReadWindow::~CBookReadWindow() { void CBookReadWindow::applyProfileSettings( CProfileWindow* profileWindow ) { CLexiconReadWindow::applyProfileSettings(profileWindow); - const bool enable = static_cast<bool>( profileWindow->windowSettings() ); - if (enable) { + if (profileWindow->windowSettings) { m_treeAction->activate(QAction::Trigger); } } @@ -49,7 +48,7 @@ void CBookReadWindow::storeProfileSettings( CProfileWindow* profileWindow ) { CLexiconReadWindow::storeProfileSettings(profileWindow); //store information about our show tree structure button - profileWindow->setWindowSettings( static_cast<int>( m_treeAction->isChecked() ) ); + profileWindow->windowSettings = m_treeAction->isChecked(); } void CBookReadWindow::initActions() { @@ -58,13 +57,17 @@ void CBookReadWindow::initActions() { insertKeyboardActions(ac); //cleanup, not a clean oo-solution - Q_ASSERT(ac->action("nextEntry")); - Q_ASSERT(ac->action("previousEntry")); - ac->action("nextEntry")->setEnabled(false); - ac->action("previousEntry")->setEnabled(false); + QAction *a = ac->action("nextEntry"); + Q_ASSERT(a != 0); + a->setEnabled(false); + a = ac->action("previousEntry"); + Q_ASSERT(a != 0); + a->setEnabled(false); m_treeAction = ac->action("toggleTree"); - QObject::connect(m_treeAction, SIGNAL(triggered()), this, SLOT(treeToggled()) ); + Q_ASSERT(m_treeAction != 0); + QObject::connect(m_treeAction, SIGNAL(triggered()), + this, SLOT(treeToggled())); addAction(m_treeAction); CBTConfig::setupAccelSettings(CBTConfig::bookWindow, ac); @@ -132,9 +135,8 @@ void CBookReadWindow::initToolbars() { BtDisplaySettingsButton* button = new BtDisplaySettingsButton(buttonsToolBar()); setDisplaySettingsButton(button); buttonsToolBar()->addWidget(button); // Display settings - QAction* action = qobject_cast<QAction*>(actionCollection()->action( - CResMgr::displaywindows::general::search::actionName )); - if (action) { + QAction *action = actionCollection()->action(CResMgr::displaywindows::general::search::actionName); + if (action != 0) { buttonsToolBar()->addAction(action); // Search } } @@ -158,9 +160,8 @@ void CBookReadWindow::setupMainWindowToolBars() { BtDisplaySettingsButton* button = new BtDisplaySettingsButton(buttonsToolBar()); setDisplaySettingsButton(button); btMainWindow()->toolsToolBar()->addWidget(button); // Display settings - QAction* action = qobject_cast<QAction*>(actionCollection()->action( - CResMgr::displaywindows::general::search::actionName )); - if (action) { + QAction *action = actionCollection()->action(CResMgr::displaywindows::general::search::actionName); + if (action != 0) { btMainWindow()->toolsToolBar()->addAction(action); // Search } } diff --git a/src/frontend/displaywindow/ccommentaryreadwindow.cpp b/src/frontend/displaywindow/ccommentaryreadwindow.cpp index b1a291f..f2c2c3d 100644 --- a/src/frontend/displaywindow/ccommentaryreadwindow.cpp +++ b/src/frontend/displaywindow/ccommentaryreadwindow.cpp @@ -72,36 +72,51 @@ void CCommentaryReadWindow::initActions() { insertKeyboardActions(ac); //cleanup, not a clean oo-solution - ac->action("nextEntry")->setEnabled(false); - ac->action("previousEntry")->setEnabled(false); - - QAction* qaction; + QAction *qaction = ac->action("nextEntry"); + Q_ASSERT(qaction != 0); + qaction->setEnabled(false); + qaction = ac->action("previousEntry"); + Q_ASSERT(qaction != 0); + qaction->setEnabled(false); qaction = ac->action("nextBook"); - QObject::connect(qaction, SIGNAL(triggered()), this, SLOT(nextBook()) ); + Q_ASSERT(qaction != 0); + QObject::connect(qaction, SIGNAL(triggered()), + this, SLOT(nextBook())); addAction(qaction); qaction = ac->action("previousBook"); - QObject::connect(qaction, SIGNAL(triggered()), this, SLOT(previousBook()) ); + Q_ASSERT(qaction != 0); + QObject::connect(qaction, SIGNAL(triggered()), + this, SLOT(previousBook())); addAction(qaction); qaction = ac->action("nextChapter"); - QObject::connect(qaction, SIGNAL(triggered()), this, SLOT(nextChapter()) ); + Q_ASSERT(qaction != 0); + QObject::connect(qaction, SIGNAL(triggered()), + this, SLOT(nextChapter())); addAction(qaction); qaction = ac->action("previousChapter"); - QObject::connect(qaction, SIGNAL(triggered()), this, SLOT(previousChapter()) ); + Q_ASSERT(qaction != 0); + QObject::connect(qaction, SIGNAL(triggered()), + this, SLOT(previousChapter())); addAction(qaction); qaction = ac->action("nextVerse"); - QObject::connect(qaction, SIGNAL(triggered()), this, SLOT(nextVerse()) ); + Q_ASSERT(qaction != 0); + QObject::connect(qaction, SIGNAL(triggered()), + this, SLOT(nextVerse())); addAction(qaction); qaction = ac->action("previousVerse"); - QObject::connect(qaction, SIGNAL(triggered()), this, SLOT(previousVerse()) ); + Q_ASSERT(qaction != 0); + QObject::connect(qaction, SIGNAL(triggered()), + this, SLOT(previousVerse())); addAction(qaction); qaction = ac->action(CResMgr::displaywindows::commentaryWindow::syncWindow::actionName); + Q_ASSERT(qaction != 0); m_syncButton = qaction; addAction(qaction); @@ -110,14 +125,14 @@ void CCommentaryReadWindow::initActions() { void CCommentaryReadWindow::applyProfileSettings( CProfileWindow* profileWindow ) { CLexiconReadWindow::applyProfileSettings(profileWindow); - if (profileWindow->windowSettings()) { + if (profileWindow->windowSettings) { m_syncButton->setChecked(true); } } void CCommentaryReadWindow::storeProfileSettings( CProfileWindow* profileWindow ) { CLexiconReadWindow::storeProfileSettings(profileWindow); - profileWindow->setWindowSettings( m_syncButton->isChecked() ); + profileWindow->windowSettings = m_syncButton->isChecked(); } void CCommentaryReadWindow::initToolbars() { diff --git a/src/frontend/displaywindow/cdisplaywindow.cpp b/src/frontend/displaywindow/cdisplaywindow.cpp index 2b712c7..0b9bc61 100644 --- a/src/frontend/displaywindow/cdisplaywindow.cpp +++ b/src/frontend/displaywindow/cdisplaywindow.cpp @@ -48,7 +48,6 @@ CDisplayWindow::CDisplayWindow(QList<CSwordModuleInfo*> modules, CMDIArea *paren m_popupMenu(0), m_displayWidget(0), m_history(0) { - qDebug() << "CDisplayWindow::CDisplayWindow"; setAttribute(Qt::WA_DeleteOnClose); //we want to destroy this window when it is closed m_actionCollection = new BtActionCollection(this); setModules(modules); @@ -108,25 +107,13 @@ const QString CDisplayWindow::windowCaption() { /** Returns the used modules as a pointer list */ const QList<const CSwordModuleInfo*> CDisplayWindow::modules() const { - //qDebug() << "CDisplayWindow::modules"; - return CSwordBackend::instance()->getConstPointerList(m_modules); } void CDisplayWindow::insertKeyboardActions( BtActionCollection* a ) { namespace DU = util::directory; - qDebug() << "CDisplayWindow::insertKeyboardActions: ac: " << a; - - QAction* actn = new QAction(QIcon(), tr("Zoom in"), a); - actn->setShortcut(QKeySequence::ZoomIn); - a->addAction("zoomIn", actn); - - actn = new QAction(QIcon(), tr("Zoom out"), a); - actn->setShortcut(QKeySequence::ZoomOut); - a->addAction("zoomOut", actn); - - actn = new QAction(QIcon(), tr("Select all"), a); + QAction* actn = new QAction(QIcon(), tr("Select all"), a); actn->setShortcut(QKeySequence::SelectAll); a->addAction("selectAll", actn); @@ -165,57 +152,60 @@ void CDisplayWindow::insertKeyboardActions( BtActionCollection* a ) { } void CDisplayWindow::initActions() { - qDebug() << "CDisplayWindow::initActions"; - BtActionCollection* ac = actionCollection(); CDisplayWindow::insertKeyboardActions(ac); QAction* actn = ac->action(CResMgr::displaywindows::general::search::actionName); - QObject::connect(actn, SIGNAL(triggered()), this, SLOT(slotSearchInModules())); + Q_ASSERT(actn != 0); + QObject::connect(actn, SIGNAL(triggered()), + this, SLOT(slotSearchInModules())); CDisplayConnections* conn = displayWidget()->connectionsProxy(); actn = ac->action("openLocation"); - QObject::connect(actn, SIGNAL(triggered()), this, SLOT(setFocusKeyChooser())); - addAction(actn); - - actn = ac->action("zoomIn"); - QObject::connect(actn, SIGNAL(triggered()), conn, SLOT(zoomIn())); - addAction(actn); - - actn = ac->action("zoomOut"); - QObject::connect(actn, SIGNAL(triggered()), conn, SLOT(zoomOut())); + Q_ASSERT(actn != 0); + QObject::connect(actn, SIGNAL(triggered()), + this, SLOT(setFocusKeyChooser())); addAction(actn); actn = ac->action("selectAll"); - QObject::connect(actn, SIGNAL(triggered()), conn, SLOT(selectAll())); + Q_ASSERT(actn != 0); + QObject::connect(actn, SIGNAL(triggered()), + conn, SLOT(selectAll())); addAction(actn); actn = ac->action("copySelectedText"); - QObject::connect(actn, SIGNAL(triggered()), conn, SLOT(copySelection())); + Q_ASSERT(actn != 0); + QObject::connect(actn, SIGNAL(triggered()), + conn, SLOT(copySelection())); addAction(actn); actn = ac->action("findText"); - QObject::connect(actn, SIGNAL(triggered()), conn, SLOT(openFindTextDialog())); + Q_ASSERT(actn != 0); + QObject::connect(actn, SIGNAL(triggered()), + conn, SLOT(openFindTextDialog())); addAction(actn); - QAction* popupaction = ac->action(CResMgr::displaywindows::general::backInHistory::actionName); - bool ok = QObject::connect(popupaction, SIGNAL(triggered()), keyChooser()->history(), SLOT(back())); + actn = ac->action(CResMgr::displaywindows::general::backInHistory::actionName); + Q_ASSERT(actn != 0); + bool ok = QObject::connect(actn, SIGNAL(triggered()), + keyChooser()->history(), SLOT(back())); Q_ASSERT(ok); - addAction(popupaction); + addAction(actn); - popupaction = ac->action(CResMgr::displaywindows::general::forwardInHistory::actionName); - ok = QObject::connect(popupaction, SIGNAL(triggered()), keyChooser()->history(), SLOT(fw()) ); + actn = ac->action(CResMgr::displaywindows::general::forwardInHistory::actionName); + Q_ASSERT(actn != 0); + ok = QObject::connect(actn, SIGNAL(triggered()), + keyChooser()->history(), SLOT(fw())); Q_ASSERT(ok); - addAction(popupaction); + addAction(actn); CBTConfig::setupAccelSettings(CBTConfig::allWindows, ac); } /** Refresh the settings of this window. */ void CDisplayWindow::reload(CSwordBackend::SetupChangedReason) { - qDebug() << "CDisplayWindow::reload"; //first make sure all used Sword modules are still present QMutableStringListIterator it(m_modules); while (it.hasNext()) { @@ -224,7 +214,7 @@ void CDisplayWindow::reload(CSwordBackend::SetupChangedReason) { } } - if (m_modules.count() == 0) { + if (m_modules.isEmpty()) { close(); return; } @@ -235,12 +225,10 @@ void CDisplayWindow::reload(CSwordBackend::SetupChangedReason) { CBTConfig::setupAccelSettings(CBTConfig::allWindows, actionCollection()); CBTConfig::setupAccelSettings(CBTConfig::readWindow, actionCollection()); - qDebug() << "CDisplayWindow::reload emits sigModuleListSet..."; emit sigModuleListSet(m_modules); } void CDisplayWindow::slotAddModule(int index, QString module) { - qDebug() << "CDisplayWindow::slotAddModule"; m_modules.insert(index, module); lookup(); modulesChanged(); @@ -257,7 +245,6 @@ void CDisplayWindow::slotReplaceModule(int index, QString newModule) { } void CDisplayWindow::slotRemoveModule(int index) { - qDebug() << "CDisplayWindow::slotRemoveModule"; m_modules.removeAt(index); lookup(); modulesChanged(); @@ -320,7 +307,6 @@ void CDisplayWindow::modulesChanged() { /** Sets the module chooser bar. */ void CDisplayWindow::setModuleChooserBar( BtModuleChooserBar* bar ) { - qDebug() << "CDisplayWindow::setModuleChooserBar"; if (m_moduleChooserBar) { m_moduleChooserBar->deleteLater(); } @@ -344,7 +330,6 @@ void CDisplayWindow::setHeaderBar( QToolBar* header ) { /** Sets the modules. */ void CDisplayWindow::setModules( const QList<CSwordModuleInfo*>& newModules ) { - qDebug() << "CDisplayWindow::setModules"; m_modules.clear(); foreach (CSwordModuleInfo* mod, newModules) { @@ -354,7 +339,6 @@ void CDisplayWindow::setModules( const QList<CSwordModuleInfo*>& newModules ) { /** Initialize the window. Call this method from the outside, because calling this in the constructor is not possible! */ bool CDisplayWindow::init() { - qDebug() << "CDisplayWindow::init"; initView(); setMinimumSize( 100, 100 ); @@ -490,7 +474,6 @@ void CDisplayWindow::lookupKey( const QString& keyName ) { */ Q_ASSERT(modules().first()); - qDebug() << "CDisplayWindow::lookupKey: " << keyName; lookupModKey(modules().first()->name(), keyName); } diff --git a/src/frontend/displaywindow/cdisplaywindow.h b/src/frontend/displaywindow/cdisplaywindow.h index c54aab0..4935d8f 100644 --- a/src/frontend/displaywindow/cdisplaywindow.h +++ b/src/frontend/displaywindow/cdisplaywindow.h @@ -225,7 +225,7 @@ class CDisplayWindow : public QMainWindow { void slotShowHeader(bool show); protected: - friend class CMDIArea; + friend class CBibleReadWindow; CDisplayWindow(QList<CSwordModuleInfo*> modules, CMDIArea* parent); diff --git a/src/frontend/displaywindow/cdisplaywindowfactory.cpp b/src/frontend/displaywindow/cdisplaywindowfactory.cpp index 9e1b5f6..e280c6d 100644 --- a/src/frontend/displaywindow/cdisplaywindowfactory.cpp +++ b/src/frontend/displaywindow/cdisplaywindowfactory.cpp @@ -9,8 +9,6 @@ #include "frontend/displaywindow/cdisplaywindowfactory.h" -#include <QDebug> - #include "backend/drivers/cswordmoduleinfo.h" #include "frontend/displaywindow/cbiblereadwindow.h" #include "frontend/displaywindow/cbookreadwindow.h" @@ -24,7 +22,6 @@ CReadWindow* CDisplayWindowFactory::createReadInstance(QList<CSwordModuleInfo*> modules, CMDIArea* parent) { - qDebug() << "CDisplayWindowFactory::createReadInstance"; CReadWindow* win = 0; switch (modules.first()->type()) { case CSwordModuleInfo::Bible: diff --git a/src/frontend/displaywindow/chtmlwritewindow.cpp b/src/frontend/displaywindow/chtmlwritewindow.cpp index df36080..705daf0 100644 --- a/src/frontend/displaywindow/chtmlwritewindow.cpp +++ b/src/frontend/displaywindow/chtmlwritewindow.cpp @@ -29,8 +29,6 @@ using namespace Profile; CHTMLWriteWindow::CHTMLWriteWindow(QList<CSwordModuleInfo*> modules, CMDIArea* parent) : CPlainWriteWindow(modules, parent) {} -CHTMLWriteWindow::~CHTMLWriteWindow() {} - void CHTMLWriteWindow::initView() { CWriteDisplay* writeDisplay = CDisplay::createWriteInstance(this, CDisplay::HTMLDisplay); Q_ASSERT(writeDisplay); @@ -77,13 +75,15 @@ void CHTMLWriteWindow::initToolbars() { void CHTMLWriteWindow::storeProfileSettings( CProfileWindow* profileWindow ) { CWriteWindow::storeProfileSettings(profileWindow); QAction* action = actionCollection()->action(CResMgr::displaywindows::commentaryWindow::syncWindow::actionName); - profileWindow->setWindowSettings( action->isChecked() ); + Q_ASSERT(action != 0); + profileWindow->windowSettings = action->isChecked(); } void CHTMLWriteWindow::applyProfileSettings( CProfileWindow* profileWindow ) { CWriteWindow::applyProfileSettings(profileWindow); - if (profileWindow->windowSettings()) { + if (profileWindow->windowSettings) { QAction* action = actionCollection()->action(CResMgr::displaywindows::commentaryWindow::syncWindow::actionName); + Q_ASSERT(action != 0); action->setChecked(true); } } @@ -91,8 +91,10 @@ void CHTMLWriteWindow::applyProfileSettings( CProfileWindow* profileWindow ) { /** Is called when the current text was changed. */ void CHTMLWriteWindow::textChanged() { QAction* action = actionCollection()->action(CResMgr::displaywindows::writeWindow::saveText::actionName); + Q_ASSERT(action != 0); action->setEnabled( ((CWriteDisplay*)displayWidget())->isModified() ); action = actionCollection()->action(CResMgr::displaywindows::writeWindow::restoreText::actionName); + Q_ASSERT(action != 0); action->setEnabled( ((CWriteDisplay*)displayWidget())->isModified() ); } @@ -105,6 +107,7 @@ void CHTMLWriteWindow::restoreText() { bool CHTMLWriteWindow::syncAllowed() const { QAction* action = actionCollection()->action(CResMgr::displaywindows::commentaryWindow::syncWindow::actionName); + Q_ASSERT(action != 0); return action->isChecked(); } diff --git a/src/frontend/displaywindow/chtmlwritewindow.h b/src/frontend/displaywindow/chtmlwritewindow.h index b669f94..8aec012 100644 --- a/src/frontend/displaywindow/chtmlwritewindow.h +++ b/src/frontend/displaywindow/chtmlwritewindow.h @@ -26,7 +26,6 @@ class CHTMLWriteWindow : public CPlainWriteWindow { Q_OBJECT public: CHTMLWriteWindow(QList<CSwordModuleInfo*> modules, CMDIArea* parent); - virtual ~CHTMLWriteWindow(); /** * Store the settings of this window in the given CProfileWindow object. diff --git a/src/frontend/displaywindow/clexiconreadwindow.cpp b/src/frontend/displaywindow/clexiconreadwindow.cpp index dae85e3..7d76293 100644 --- a/src/frontend/displaywindow/clexiconreadwindow.cpp +++ b/src/frontend/displaywindow/clexiconreadwindow.cpp @@ -38,7 +38,6 @@ CLexiconReadWindow::CLexiconReadWindow(QList<CSwordModuleInfo*> moduleList, CMDIArea* parent) : CReadWindow(moduleList, parent) { - qDebug() << "CLexiconReadWindow::CLexiconReadWindow"; moduleList.first(); setKey( CSwordKey::createInstance(moduleList.first()) ); } @@ -47,7 +46,6 @@ CLexiconReadWindow::~CLexiconReadWindow() { } void CLexiconReadWindow::insertKeyboardActions( BtActionCollection* const a ) { - qDebug() << "CLexiconReadWindow::insertKeyboardActions"; QAction* qaction; qaction = new QAction( tr("Next entry"), a); qaction->setShortcut(CResMgr::displaywindows::lexiconWindow::nextEntry::accel); @@ -81,77 +79,90 @@ void CLexiconReadWindow::insertKeyboardActions( BtActionCollection* const a ) { } void CLexiconReadWindow::initActions() { - qDebug() << "CLexiconReadWindow::initActions"; - BtActionCollection* ac = actionCollection(); CReadWindow::initActions(); CLexiconReadWindow::insertKeyboardActions(ac); - m_actions.backInHistory = dynamic_cast<BtToolBarPopupAction*>( - ac->action(CResMgr::displaywindows::general::backInHistory::actionName) ); + QAction *qaction = ac->action(CResMgr::displaywindows::general::backInHistory::actionName); + Q_ASSERT(qaction != 0); + m_actions.backInHistory = dynamic_cast<BtToolBarPopupAction*>(qaction); Q_ASSERT(m_actions.backInHistory); addAction(m_actions.backInHistory); - m_actions.forwardInHistory = dynamic_cast<BtToolBarPopupAction*>( - ac->action(CResMgr::displaywindows::general::forwardInHistory::actionName) ); + qaction = ac->action(CResMgr::displaywindows::general::forwardInHistory::actionName); + Q_ASSERT(qaction != 0); + m_actions.forwardInHistory = dynamic_cast<BtToolBarPopupAction*>(qaction); Q_ASSERT(m_actions.forwardInHistory); addAction(m_actions.forwardInHistory); - QAction* qaction; - qaction = ac->action("nextEntry"); - QObject::connect(qaction, SIGNAL(triggered()), this, SLOT( nextEntry() ) ); + Q_ASSERT(qaction != 0); + connect(qaction, SIGNAL(triggered()), + this, SLOT(nextEntry())); addAction(qaction); qaction = ac->action("previousEntry"); - QObject::connect(qaction, SIGNAL(triggered()), this, SLOT( previousEntry() ) ); + Q_ASSERT(qaction != 0); + connect(qaction, SIGNAL(triggered()), + this, SLOT(previousEntry())); addAction(qaction); m_actions.selectAll = ac->action("selectAll"); - Q_ASSERT(m_actions.selectAll); + Q_ASSERT(m_actions.selectAll != 0); m_actions.findText = ac->action("findText"); - Q_ASSERT(m_actions.findText); + Q_ASSERT(m_actions.findText != 0); m_actions.findStrongs = ac->action(CResMgr::displaywindows::general::findStrongs::actionName); - QObject::connect(m_actions.findStrongs, SIGNAL(triggered()), this, SLOT(openSearchStrongsDialog()) ); + Q_ASSERT(m_actions.findStrongs != 0); + connect(m_actions.findStrongs, SIGNAL(triggered()), + this, SLOT(openSearchStrongsDialog()) ); addAction(m_actions.findStrongs); m_actions.copy.reference = ac->action("copyReferenceOnly"); - QObject::connect(m_actions.copy.reference, SIGNAL(triggered()), displayWidget()->connectionsProxy(), SLOT(copyAnchorOnly()) ); + Q_ASSERT(m_actions.copy.reference != 0); + connect(m_actions.copy.reference, SIGNAL(triggered()), + displayWidget()->connectionsProxy(), SLOT(copyAnchorOnly())); addAction(m_actions.copy.reference); m_actions.copy.entry = ac->action("copyEntryWithText"); - QObject::connect(m_actions.copy.entry, SIGNAL(triggered()), displayWidget()->connectionsProxy(), SLOT(copyAll()) ); + Q_ASSERT(m_actions.copy.entry != 0); + connect(m_actions.copy.entry, SIGNAL(triggered()), + displayWidget()->connectionsProxy(), SLOT(copyAll())); addAction(m_actions.copy.entry); - Q_ASSERT(ac->action("copySelectedText")); m_actions.copy.selectedText = ac->action("copySelectedText"); + Q_ASSERT(m_actions.copy.selectedText != 0); m_actions.save.entryAsPlain = new QAction(tr("Entry as plain text"), ac ); - QObject::connect(m_actions.save.entryAsPlain, SIGNAL(triggered()), this, SLOT(saveAsPlain()) ); + connect(m_actions.save.entryAsPlain, SIGNAL(triggered()), + this, SLOT(saveAsPlain())); addAction(m_actions.save.entryAsPlain); m_actions.save.entryAsHTML = ac->action("saveHtml"); - QObject::connect(m_actions.save.entryAsHTML, SIGNAL(triggered()), this, SLOT(saveAsHTML())); + Q_ASSERT(m_actions.save.entryAsHTML != 0); + connect(m_actions.save.entryAsHTML, SIGNAL(triggered()), + this, SLOT(saveAsHTML())); addAction(m_actions.save.entryAsHTML); m_actions.print.reference = ac->action("printReferenceOnly"); - QObject::connect(m_actions.print.reference, SIGNAL(triggered()), this, SLOT(printAnchorWithText())); + Q_ASSERT(m_actions.print.reference != 0); + connect(m_actions.print.reference, SIGNAL(triggered()), + this, SLOT(printAnchorWithText())); addAction(m_actions.print.reference); m_actions.print.entry = ac->action("printEntryWithText"); - QObject::connect(m_actions.print.entry, SIGNAL(triggered()), this, SLOT(printAll())); + Q_ASSERT(m_actions.print.entry != 0); + connect(m_actions.print.entry, SIGNAL(triggered()), + this, SLOT(printAll())); addAction(m_actions.print.entry); // init with the user defined settings - qDebug() << "call CBTConfig::setupAccelSettings(CBTConfig::lexiconWindow, ac); and end CLexiconReadWindow::initActions"; CBTConfig::setupAccelSettings(CBTConfig::lexiconWindow, ac); } /** No descriptions */ void CLexiconReadWindow::initConnections() { - qDebug() << "CLexiconReadWindow::initConnections"; Q_ASSERT(keyChooser()); connect(keyChooser(), SIGNAL(keyChanged(CSwordKey*)), this, SLOT(lookupSwordKey(CSwordKey*))); @@ -182,8 +193,6 @@ void CLexiconReadWindow::initConnections() { } void CLexiconReadWindow::initView() { - qDebug() << "CLexiconReadWindow::initView"; - // Create display widget for this window setDisplayWidget( CDisplay::createReadInstance(this) ); setCentralWidget( displayWidget()->view() ); @@ -219,12 +228,10 @@ void CLexiconReadWindow::initToolbars() { mainToolBar()->addAction(m_actions.forwardInHistory); //2nd button //Tools toolbar - QAction* action = qobject_cast<QAction*>(actionCollection()->action( - CResMgr::displaywindows::general::search::actionName)); - Q_ASSERT( action ); - if (action) { - buttonsToolBar()->addAction(action); - } + QAction *action = actionCollection()->action(CResMgr::displaywindows::general::search::actionName); + Q_ASSERT(action != 0); + buttonsToolBar()->addAction(action); + BtDisplaySettingsButton* button = new BtDisplaySettingsButton(buttonsToolBar()); setDisplaySettingsButton(button); buttonsToolBar()->addWidget(button); @@ -249,12 +256,9 @@ void CLexiconReadWindow::setupMainWindowToolBars() { btMainWindow()->worksToolBar()->setModules(getModuleList(), modules().first()->type(), this); // Tools toolbar - QAction* action = actionCollection()->action( - CResMgr::displaywindows::general::search::actionName); - Q_ASSERT( action ); - if (action) { - btMainWindow()->toolsToolBar()->addAction(action); - } + QAction *action = actionCollection()->action(CResMgr::displaywindows::general::search::actionName); + Q_ASSERT(action != 0); + btMainWindow()->toolsToolBar()->addAction(action); BtDisplaySettingsButton* button = new BtDisplaySettingsButton(buttonsToolBar()); setDisplaySettingsButton(button); btMainWindow()->toolsToolBar()->addWidget(button); @@ -305,7 +309,7 @@ void CLexiconReadWindow::setupPopupMenu() { void CLexiconReadWindow::updatePopupMenu() { //enable the action depending on the supported module features - m_actions.findStrongs->setEnabled( displayWidget()->getCurrentNodeInfo()[CDisplay::Lemma] != QString::null ); + m_actions.findStrongs->setEnabled(!displayWidget()->getCurrentNodeInfo().isNull()); m_actions.copy.reference->setEnabled( ((CReadDisplay*)displayWidget())->hasActiveAnchor() ); m_actions.copy.selectedText->setEnabled( displayWidget()->hasSelection() ); @@ -336,43 +340,35 @@ CSwordLDKey* CLexiconReadWindow::ldKey() { /** This function saves the entry as html using the CExportMgr class. */ void CLexiconReadWindow::saveAsHTML() { - CExportManager mgr(tr("Saving entry ..."), true, tr("Saving"), filterOptions(), displayOptions()); + CExportManager mgr(true, tr("Saving"), filterOptions(), displayOptions()); mgr.saveKey(key(), CExportManager::HTML, true); } /** Saving the raw HTML for debugging purposes */ void CLexiconReadWindow::saveRawHTML() { - //qDebug() << "CLexiconReadWindow::saveRawHTML"; QString savefilename = QFileDialog::getSaveFileName(); if (savefilename.isEmpty()) return; - QFile file(savefilename); BtHtmlReadDisplay* disp = dynamic_cast<BtHtmlReadDisplay*>(displayWidget()); if (disp) { + QFile file(savefilename); if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) { - qDebug() << "could not open file"; + qWarning() << "saveRawHTML: could not open file" << savefilename; return; } QString source = disp->getCurrentSource(); file.write(source.toUtf8()); - //qDebug() << "wrote" << bytes << "bytes"; file.close(); file.flush(); } - else { - qDebug() << "No htmlreaddisplay widget!"; - } - } /** This function saves the entry as html using the CExportMgr class. */ void CLexiconReadWindow::saveAsPlain() { - CExportManager mgr(tr("Saving entry ..."), true, tr("Saving"), filterOptions(), displayOptions()); + CExportManager mgr(true, tr("Saving"), filterOptions(), displayOptions()); mgr.saveKey(key(), CExportManager::Text, true); } void CLexiconReadWindow::slotFillBackHistory() { - qDebug() << "CLexiconReadWindow::slotFillBackHistory"; - QMenu* menu = m_actions.backInHistory->popupMenu(); menu->clear(); @@ -384,8 +380,6 @@ void CLexiconReadWindow::slotFillBackHistory() { } void CLexiconReadWindow::slotFillForwardHistory() { - qDebug() << "CLexiconReadWindow::slotFillForwardHistory"; - QMenu* menu = m_actions.forwardInHistory->popupMenu(); menu->clear(); /// \todo take the history list and fill the menu using addAction @@ -397,7 +391,6 @@ void CLexiconReadWindow::slotFillForwardHistory() { void CLexiconReadWindow::slotUpdateHistoryButtons(bool backEnabled, bool fwEnabled) { - qDebug() << "CLexiconReadWindow::slotUpdateHistoryButtons"; Q_ASSERT(m_actions.backInHistory); Q_ASSERT(keyChooser()); diff --git a/src/frontend/displaywindow/cplainwritewindow.cpp b/src/frontend/displaywindow/cplainwritewindow.cpp index ad3b978..f0af601 100644 --- a/src/frontend/displaywindow/cplainwritewindow.cpp +++ b/src/frontend/displaywindow/cplainwritewindow.cpp @@ -33,9 +33,6 @@ CPlainWriteWindow::CPlainWriteWindow(QList<CSwordModuleInfo*> moduleList, CMDIAr setKey( CSwordKey::createInstance(moduleList.first()) ); } - -CPlainWriteWindow::~CPlainWriteWindow() {} - /** Initialize the state of this widget. */ void CPlainWriteWindow::initView() { // qWarning("CPlainWriteWindow::initView()"); @@ -61,12 +58,16 @@ void CPlainWriteWindow::initToolbars() { // Tools toolbar QAction* action = actionCollection()->action(CResMgr::displaywindows::commentaryWindow::syncWindow::actionName); + Q_ASSERT(action != 0); buttonsToolBar()->addAction(action); action = actionCollection()->action(CResMgr::displaywindows::writeWindow::saveText::actionName); + Q_ASSERT(action != 0); buttonsToolBar()->addAction(action); action = actionCollection()->action(CResMgr::displaywindows::writeWindow::deleteEntry::actionName); + Q_ASSERT(action != 0); buttonsToolBar()->addAction(action); action = actionCollection()->action(CResMgr::displaywindows::writeWindow::restoreText::actionName); + Q_ASSERT(action != 0); buttonsToolBar()->addAction(action); } @@ -76,17 +77,19 @@ void CPlainWriteWindow::setupMainWindowToolBars() { btMainWindow()->navToolBar()->addWidget(keyChooser); bool ok = connect(keyChooser, SIGNAL(keyChanged(CSwordKey*)), this, SLOT(lookupSwordKey(CSwordKey*))); Q_ASSERT(ok); - ok = connect(keyChooser, SIGNAL(beforeKeyChange(const QString&)), this, SLOT(beforeKeyChange(const QString&))); - Q_ASSERT(ok); // Tools toolbar QAction* action = actionCollection()->action(CResMgr::displaywindows::commentaryWindow::syncWindow::actionName); + Q_ASSERT(action != 0); btMainWindow()->toolsToolBar()->addAction(action); action = actionCollection()->action(CResMgr::displaywindows::writeWindow::saveText::actionName); + Q_ASSERT(action != 0); btMainWindow()->toolsToolBar()->addAction(action); action = actionCollection()->action(CResMgr::displaywindows::writeWindow::deleteEntry::actionName); + Q_ASSERT(action != 0); btMainWindow()->toolsToolBar()->addAction(action); action = actionCollection()->action(CResMgr::displaywindows::writeWindow::restoreText::actionName); + Q_ASSERT(action != 0); btMainWindow()->toolsToolBar()->addAction(action); } @@ -99,13 +102,15 @@ void CPlainWriteWindow::initConnections() { void CPlainWriteWindow::storeProfileSettings( CProfileWindow* profileWindow ) { CWriteWindow::storeProfileSettings(profileWindow); QAction* action = actionCollection()->action(CResMgr::displaywindows::commentaryWindow::syncWindow::actionName); - profileWindow->setWindowSettings( action->isChecked() ); + Q_ASSERT(action != 0); + profileWindow->windowSettings = action->isChecked(); } void CPlainWriteWindow::applyProfileSettings( CProfileWindow* profileWindow ) { CWriteWindow::applyProfileSettings(profileWindow); - if (profileWindow->windowSettings()) { + if (profileWindow->windowSettings) { QAction* action = actionCollection()->action(CResMgr::displaywindows::commentaryWindow::syncWindow::actionName); + Q_ASSERT(action != 0); action->setChecked(true); } } @@ -122,9 +127,8 @@ void CPlainWriteWindow::saveCurrentText( const QString& /*key*/ ) { const QString& oldKey = this->key()->key(); if ( modules().first()->isWritable() ) { const_cast<CSwordModuleInfo*>(modules().first())->write(this->key(), t); - this->key()->setKey(oldKey); - ((CWriteDisplay*)displayWidget())->setModified(false); + this->key()->setKey(oldKey); textChanged(); } else { @@ -146,8 +150,10 @@ void CPlainWriteWindow::restoreText() { /** Is called when the current text was changed. */ void CPlainWriteWindow::textChanged() { QAction* action = actionCollection()->action(CResMgr::displaywindows::writeWindow::saveText::actionName); + Q_ASSERT(action != 0); action->setEnabled( ((CWriteDisplay*)displayWidget())->isModified() ); action = actionCollection()->action(CResMgr::displaywindows::writeWindow::restoreText::actionName); + Q_ASSERT(action != 0); action->setEnabled( ((CWriteDisplay*)displayWidget())->isModified() ); } @@ -163,6 +169,7 @@ void CPlainWriteWindow::setupPopupMenu() {} bool CPlainWriteWindow::syncAllowed() const { QAction* action = actionCollection()->action(CResMgr::displaywindows::commentaryWindow::syncWindow::actionName); + Q_ASSERT(action != 0); return action->isChecked(); } @@ -170,19 +177,27 @@ void CPlainWriteWindow::initActions() { insertKeyboardActions(actionCollection()); QAction* action = actionCollection()->action(CResMgr::displaywindows::commentaryWindow::syncWindow::actionName); - bool ok = QObject::connect(action, SIGNAL(triggered()), this, SLOT(saveCurrentText())); + Q_ASSERT(action != 0); + bool ok = QObject::connect(action, SIGNAL(triggered()), + this, SLOT(saveCurrentText())); Q_ASSERT(ok); action = actionCollection()->action(CResMgr::displaywindows::writeWindow::saveText::actionName); - ok = QObject::connect(action, SIGNAL(triggered()), this, SLOT(saveCurrentText())); + Q_ASSERT(action != 0); + ok = QObject::connect(action, SIGNAL(triggered()), + this, SLOT(saveCurrentText())); Q_ASSERT(ok); action = actionCollection()->action(CResMgr::displaywindows::writeWindow::deleteEntry::actionName); - ok = QObject::connect(action, SIGNAL(triggered()), this, SLOT(deleteEntry()) ); + Q_ASSERT(action != 0); + ok = QObject::connect(action, SIGNAL(triggered()), + this, SLOT(deleteEntry())); Q_ASSERT(ok); action = actionCollection()->action(CResMgr::displaywindows::writeWindow::restoreText::actionName); - ok = QObject::connect(action, SIGNAL(triggered()), this, SLOT(restoreText()) ); + Q_ASSERT(action != 0); + ok = QObject::connect(action, SIGNAL(triggered()), + this, SLOT(restoreText())); Q_ASSERT(ok); } diff --git a/src/frontend/displaywindow/cplainwritewindow.h b/src/frontend/displaywindow/cplainwritewindow.h index 9d3f29c..732ff8a 100644 --- a/src/frontend/displaywindow/cplainwritewindow.h +++ b/src/frontend/displaywindow/cplainwritewindow.h @@ -29,7 +29,6 @@ class CPlainWriteWindow : public CWriteWindow { Q_OBJECT public: CPlainWriteWindow( QList<CSwordModuleInfo*> modules, CMDIArea* parent); - virtual ~CPlainWriteWindow(); /** * Store the settings of this window in the given CProfileWindow object. diff --git a/src/frontend/displaywindow/creadwindow.cpp b/src/frontend/displaywindow/creadwindow.cpp index 4c18b0b..7f11dca 100644 --- a/src/frontend/displaywindow/creadwindow.cpp +++ b/src/frontend/displaywindow/creadwindow.cpp @@ -9,7 +9,6 @@ #include "frontend/displaywindow/creadwindow.h" -#include <QDebug> #include <QMdiSubWindow> #include <QResizeEvent> #include "backend/keys/cswordkey.h" @@ -29,14 +28,9 @@ using namespace Profile; CReadWindow::CReadWindow(QList<CSwordModuleInfo*> modules, CMDIArea* parent) : CDisplayWindow(modules, parent), m_readDisplayWidget(0) { - qDebug() << "CReadWindow::CReadWindow"; // installEventFilter(this); } -CReadWindow::~CReadWindow() { - // qWarning("destructor of CReadWindow"); -} - /** Sets the display widget of this display window. */ void CReadWindow::setDisplayWidget( CDisplay* newDisplay ) { // Lets be orwellianly paranoid here: @@ -78,7 +72,6 @@ void CReadWindow::setDisplayWidget( CDisplay* newDisplay ) { /** Lookup the given entry. */ void CReadWindow::lookupSwordKey( CSwordKey* newKey ) { - qDebug() << "CReadWindow::lookup newKey" << newKey->key(); Q_ASSERT(newKey); using namespace Rendering; @@ -109,12 +102,9 @@ void CReadWindow::lookupSwordKey( CSwordKey* newKey ) { setWindowTitle(windowCaption()); // moving to anchor happens in slotMoveToAnchor which catches the completed() signal from KHTMLPart - - qDebug() << "CReadWindow::lookup end, key is :" << newKey->key(); } void CReadWindow::slotMoveToAnchor() { - qDebug() << "CReadWindow::slotMoveToAnchor"; ((CReadDisplay*)displayWidget())->moveToAnchor( Rendering::CDisplayRendering::keyToHTMLAnchor(key()->key()) ); } @@ -125,12 +115,12 @@ void CReadWindow::storeProfileSettings(CProfileWindow * const settings) { rect.setY(parentWidget()->y()); rect.setWidth(parentWidget()->width()); rect.setHeight(parentWidget()->height()); - settings->setGeometry(rect); + settings->windowGeometry = rect; // settings->setScrollbarPositions( m_htmlWidget->view()->horizontalScrollBar()->value(), m_htmlWidget->view()->verticalScrollBar()->value() ); - settings->setType(modules().first()->type()); - settings->setMaximized(isMaximized() || parentWidget()->isMaximized()); - settings->setFocus( (this == dynamic_cast<CReadWindow*>(mdi()->activeSubWindow()) ) ); //set property to true if this window is the active one. + settings->type = modules().first()->type(); + settings->maximized = (isMaximized() || parentWidget()->isMaximized()); + settings->hasFocus = (this == dynamic_cast<CReadWindow*>(mdi()->activeSubWindow()) ); //set property to true if this window is the active one. if (key()) { sword::VerseKey* vk = dynamic_cast<sword::VerseKey*>(key()); @@ -139,7 +129,7 @@ void CReadWindow::storeProfileSettings(CProfileWindow * const settings) { oldLang = QString(vk->getLocale()); vk->setLocale("en"); //save english locale names as default! } - settings->setKey( key()->key() ); + settings->key = key()->key(); if (vk) { vk->setLocale(oldLang.toLatin1()); } @@ -149,19 +139,19 @@ void CReadWindow::storeProfileSettings(CProfileWindow * const settings) { Q_FOREACH (const CSwordModuleInfo *module, modules()) { mods.append(module->name()); } - settings->setModules(mods); + settings->modules = mods; } void CReadWindow::applyProfileSettings(CProfileWindow * const settings) { // parentWidget()->setUpdatesEnabled(false); setUpdatesEnabled(false); - if (settings->maximized()) { //maximize this window + if (settings->maximized) { //maximize this window // Use parentWidget() to call showMaximized. Otherwise we'd get lot's of X11 errors parentWidget()->showMaximized(); } else { - const QRect rect = settings->geometry(); + const QRect &rect = settings->windowGeometry; parentWidget()->resize(rect.width(), rect.height()); parentWidget()->move(rect.x(), rect.y()); } @@ -173,8 +163,7 @@ void CReadWindow::insertKeyboardActions( BtActionCollection* const ) {} /** No descriptions */ void CReadWindow::copyDisplayedText() { - CExportManager mgr(QString::null); - mgr.copyKey(key(), CExportManager::Text, true); + CExportManager().copyKey(key(), CExportManager::Text, true); } @@ -188,13 +177,11 @@ void CReadWindow::resizeEvent(QResizeEvent* /*e*/) { } void CReadWindow::openSearchStrongsDialog() { -// qWarning("looking for lemma %s", displayWidget()->getCurrentNodeInfo()[CDisplay::Lemma].latin1() ); - QString searchText = QString::null; - - if (displayWidget()->getCurrentNodeInfo()[CDisplay::Lemma] != QString::null) { - Q_FOREACH(QString strongNumber, displayWidget()->getCurrentNodeInfo()[CDisplay::Lemma].split("|")) { - searchText.append("strong:").append( strongNumber ).append(" "); - } + QString searchText; + Q_FOREACH (const QString &strongNumber, + displayWidget()->getCurrentNodeInfo().split('|', QString::SkipEmptyParts)) + { + searchText.append("strong:").append(strongNumber).append(' '); } Search::CSearchDialog::openDialog( modules(), searchText, 0 ); diff --git a/src/frontend/displaywindow/creadwindow.h b/src/frontend/displaywindow/creadwindow.h index 855baa2..d00d4f0 100644 --- a/src/frontend/displaywindow/creadwindow.h +++ b/src/frontend/displaywindow/creadwindow.h @@ -35,7 +35,7 @@ class CReadWindow : public CDisplayWindow { static void insertKeyboardActions( BtActionCollection* const a ); CReadWindow(QList<CSwordModuleInfo*> modules, CMDIArea* parent); - virtual ~CReadWindow(); + /** * Store the settings of this window in the given CProfileWindow object. */ diff --git a/src/frontend/displaywindow/cwritewindow.cpp b/src/frontend/displaywindow/cwritewindow.cpp index 3369d8a..fbcf8de 100644 --- a/src/frontend/displaywindow/cwritewindow.cpp +++ b/src/frontend/displaywindow/cwritewindow.cpp @@ -16,21 +16,18 @@ #include "frontend/keychooser/ckeychooser.h" #include "frontend/profile/cprofilewindow.h" #include "util/dialogutil.h" - +#include "util/btsignal.h" using namespace Profile; CWriteWindow::CWriteWindow(QList<CSwordModuleInfo*> modules, CMDIArea* parent) : CDisplayWindow(modules, parent), m_writeDisplay(0) {} -CWriteWindow::~CWriteWindow() {} - - void CWriteWindow::insertKeyboardActions( BtActionCollection* const ) {} void CWriteWindow::initConnections() { Q_ASSERT(keyChooser()); - QObject::connect(keyChooser(), SIGNAL(beforeKeyChange(const QString&)), this, SLOT(beforeKeyChange(const QString&))); + QObject::connect(key()->signaler(), SIGNAL(beforeChanged()), this, SLOT(beforeKeyChange())); } void CWriteWindow::initActions() {} @@ -38,18 +35,15 @@ void CWriteWindow::initActions() {} void CWriteWindow::storeProfileSettings(CProfileWindow * const settings) { - settings->setWriteWindowType( writeWindowType() ); - - QRect rect; - rect.setX(parentWidget()->x()); - rect.setY(parentWidget()->y()); - rect.setWidth(parentWidget()->width()); - rect.setHeight(parentWidget()->height()); - settings->setGeometry(rect); + settings->writeWindowType = writeWindowType(); + settings->windowGeometry.setRect(parentWidget()->x(), + parentWidget()->y(), + parentWidget()->width(), + parentWidget()->height()); // settings->setScrollbarPositions( m_htmlWidget->view()->horizontalScrollBar()->value(), m_htmlWidget->view()->verticalScrollBar()->value() ); - settings->setType(modules().first()->type()); - settings->setMaximized(isMaximized() || parentWidget()->isMaximized()); + settings->type = modules().first()->type(); + settings->maximized = isMaximized() || parentWidget()->isMaximized(); if (key()) { sword::VerseKey* vk = dynamic_cast<sword::VerseKey*>(key()); @@ -58,7 +52,7 @@ void CWriteWindow::storeProfileSettings(CProfileWindow * const settings) { oldLang = QString::fromLatin1(vk->getLocale()); vk->setLocale("en"); //save english locale names as default! } - settings->setKey( key()->key() ); + settings->key = key()->key(); if (vk) { vk->setLocale(oldLang.toLatin1()); } @@ -68,17 +62,17 @@ void CWriteWindow::storeProfileSettings(CProfileWindow * const settings) { Q_FOREACH(const CSwordModuleInfo *m, modules()) { mods.append(m->name()); } - settings->setModules(mods); + settings->modules = mods; } void CWriteWindow::applyProfileSettings(CProfileWindow * const settings) { setUpdatesEnabled(false); - if (settings->maximized()) { + if (settings->maximized) { parentWidget()->showMaximized(); } else { - const QRect rect = settings->geometry(); + const QRect &rect = settings->windowGeometry; parentWidget()->resize(rect.width(), rect.height()); parentWidget()->move(rect.x(), rect.y()); //setGeometry( settings->geometry() ); @@ -127,17 +121,25 @@ bool CWriteWindow::queryClose() { return true; } -void CWriteWindow::beforeKeyChange(const QString& key) { +void CWriteWindow::beforeKeyChange() { Q_ASSERT(displayWidget()); Q_ASSERT(keyChooser()); - if (!isReady()) return; + if (!isReady()) + return; + // Get current key string for this window + QString thisWindowsKey; + CSwordKey* oldKey = key(); + if (oldKey == 0) + return; + thisWindowsKey = oldKey->key(); + //If the text changed and we'd do a lookup ask the user if the text should be saved if (modules().first() && ((CWriteDisplay*)displayWidget())->isModified()) { switch (util::showQuestion( this, tr("Save Text?"), tr("Save changed text?"), QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes) ) { case QMessageBox::Yes: { //save the changes - saveCurrentText( key ); + saveCurrentText( thisWindowsKey ); break; } default: {// set modified to false so it won't ask again diff --git a/src/frontend/displaywindow/cwritewindow.h b/src/frontend/displaywindow/cwritewindow.h index 7a5a524..3ff9d06 100644 --- a/src/frontend/displaywindow/cwritewindow.h +++ b/src/frontend/displaywindow/cwritewindow.h @@ -37,7 +37,6 @@ class CWriteWindow : public CDisplayWindow { static void insertKeyboardActions( BtActionCollection* const a ); CWriteWindow(QList<CSwordModuleInfo*> modules, CMDIArea* parent); - virtual ~CWriteWindow(); /** * Store the settings of this window in the given CProfileWindow object. */ @@ -84,7 +83,7 @@ class CWriteWindow : public CDisplayWindow { void saveCurrentText(); /** */ - virtual void beforeKeyChange(const QString&); + virtual void beforeKeyChange(); private: CWriteDisplay* m_writeDisplay; diff --git a/src/frontend/keychooser/bthistory.cpp b/src/frontend/keychooser/bthistory.cpp index 329ce78..93651a5 100644 --- a/src/frontend/keychooser/bthistory.cpp +++ b/src/frontend/keychooser/bthistory.cpp @@ -10,7 +10,6 @@ #include "frontend/keychooser/bthistory.h" #include <QAction> -#include <QDebug> #include <QList> #include "backend/keys/cswordkey.h" @@ -24,7 +23,6 @@ BTHistory::BTHistory(QWidget* parent) } void BTHistory::add(CSwordKey* newKey) { - qDebug() << "BTHistory::add"; Q_ASSERT(newKey); // Add new key Action after current index if we were not using the history functions, // if it's not a duplicate and if it's not empty. @@ -39,7 +37,6 @@ void BTHistory::add(CSwordKey* newKey) { } void BTHistory::move(QAction* historyItem) { - qDebug() << "BTHistory::move"; //Q_ASSERT(historyItem); Q_ASSERT(m_historyList.count()); @@ -56,7 +53,6 @@ void BTHistory::move(QAction* historyItem) { } void BTHistory::back() { - qDebug() << "BTHistory::back"; if ( m_index >= 1) { move(m_historyList.at(m_index - 1)); } @@ -64,7 +60,6 @@ void BTHistory::back() { } void BTHistory::fw() { - qDebug() << "BTHistory::fw"; if (m_index < (m_historyList.size() - 1)) { move(m_historyList.at(m_index + 1)); } @@ -72,28 +67,21 @@ void BTHistory::fw() { } QList<QAction*> BTHistory::getBackList() { - qDebug() << "BTHistory::getBackList"; QList<QAction*> list; for (int i = m_index - 1; i >= 0; --i) { list.append(m_historyList.at(i)); } - qDebug() << "return:" << list; Q_ASSERT(class_invariant()); return list; } QList<QAction*> BTHistory::getFwList() { - qDebug() << "BTHistory::getFwList"; - QList<QAction*> list; - //qDebug() << "historyList.size:" << m_historyList.size(); for (int i = m_index + 1; i < m_historyList.size(); ++i) { - //qDebug() << "i:" << i; list.append(m_historyList.at(i)); } - qDebug() << "return:" << list; Q_ASSERT(class_invariant()); return list; diff --git a/src/frontend/keychooser/bthistory.h b/src/frontend/keychooser/bthistory.h index 2a374b6..a92a25e 100644 --- a/src/frontend/keychooser/bthistory.h +++ b/src/frontend/keychooser/bthistory.h @@ -23,7 +23,6 @@ class BTHistory: public QObject { Q_OBJECT public: BTHistory(QWidget* parent); - ~BTHistory() {} /** * Return a list of Actions behind the current point, the first of the history list will be the diff --git a/src/frontend/keychooser/cbooktreechooser.cpp b/src/frontend/keychooser/cbooktreechooser.cpp index 1b0edd4..a41922e 100644 --- a/src/frontend/keychooser/cbooktreechooser.cpp +++ b/src/frontend/keychooser/cbooktreechooser.cpp @@ -10,7 +10,6 @@ #include "frontend/keychooser/cbooktreechooser.h" #include <QApplication> -#include <QDebug> #include <QHBoxLayout> #include <QTreeWidget> #include <QTreeWidgetItem> @@ -57,7 +56,6 @@ void CBookTreeChooser::setKey(CSwordKey* key) { /** Sets a new key to this keychooser. Inherited from ckeychooser. */ void CBookTreeChooser::setKey(CSwordKey* newKey, const bool emitSignal) { - qDebug() << "CBookTreeChooser::setKey"; if (m_key != newKey ) { m_key = dynamic_cast<CSwordTreeKey*>(newKey); @@ -130,7 +128,6 @@ void CBookTreeChooser::refreshContent() { /** Slot for signal when item is selected by user. */ void CBookTreeChooser::itemActivated( QTreeWidgetItem* item ) { - qDebug() << "CBookTreeChooser::itemActivated"; //Sometimes Qt calls this function with a null pointer. if (item) { m_key->setKey(item->text(1)); diff --git a/src/frontend/keychooser/ckeychooser.cpp b/src/frontend/keychooser/ckeychooser.cpp index 4d58298..b46ee51 100644 --- a/src/frontend/keychooser/ckeychooser.cpp +++ b/src/frontend/keychooser/ckeychooser.cpp @@ -10,7 +10,6 @@ #include "frontend/keychooser/ckeychooser.h" #include <QAction> -#include <QDebug> #include "backend/drivers/cswordbiblemoduleinfo.h" #include "backend/drivers/cswordcommentarymoduleinfo.h" #include "backend/drivers/cswordlexiconmoduleinfo.h" @@ -26,7 +25,6 @@ CKeyChooser::CKeyChooser(const QList<const CSwordModuleInfo*> &, BTHistory* hist CSwordKey *, QWidget *parent) : QWidget(parent), m_history(historyPtr) { - //qDebug() << "CKeyChooser::CKeyChooser"; bool ok = QObject::connect(history(), SIGNAL(historyMoved(QString&)), this, SLOT(setKey(QString&))); Q_ASSERT(ok); } @@ -44,13 +42,13 @@ CKeyChooser* CKeyChooser::createInstance( } CSwordModuleInfo::ModuleType typeOfModules = modules.first()->type(); - +/* #ifdef BT_DEBUG Q_FOREACH (const CSwordModuleInfo *module, modules) { Q_ASSERT(module->type() == typeOfModules); } #endif - +*/ switch (typeOfModules) { case CSwordModuleInfo::Commentary: /* Fall thru - Bibles and commentaries use the same key chooser */ diff --git a/src/frontend/keychooser/ckeychooser.h b/src/frontend/keychooser/ckeychooser.h index 2a52de3..0ab9c5b 100644 --- a/src/frontend/keychooser/ckeychooser.h +++ b/src/frontend/keychooser/ckeychooser.h @@ -83,10 +83,6 @@ class CKeyChooser : public QWidget { * is emitted if the @ref CKey was changed by the user */ void keyChanged(CSwordKey* newKey); - /** - * Is emitted before the key is changed! - */ - void beforeKeyChange(const QString& key); protected: @@ -94,8 +90,6 @@ class CKeyChooser : public QWidget { BTHistory *history, CSwordKey *key = 0, QWidget *parent = 0); - virtual inline ~CKeyChooser() {} - /** Resets the appropriate font to for the modules. */ diff --git a/src/frontend/keychooser/ckeychooserwidget.cpp b/src/frontend/keychooser/ckeychooserwidget.cpp index 1c8cc4d..36fc05b 100644 --- a/src/frontend/keychooser/ckeychooserwidget.cpp +++ b/src/frontend/keychooser/ckeychooserwidget.cpp @@ -10,7 +10,6 @@ #include "frontend/keychooser/ckeychooserwidget.h" #include <QComboBox> -#include <QDebug> #include <QFocusEvent> #include <QHBoxLayout> #include <QLineEdit> @@ -180,7 +179,7 @@ void CKeyChooserWidget::reset(const QStringList *list, int index, bool do_emit) emit changed(m_comboBox->currentIndex()); } - const QSize dummySize = m_comboBox->sizeHint(); //without this function call the combo box won't be properly sized! + m_comboBox->sizeHint(); //without this function call the combo box won't be properly sized! //DON'T REMOVE OR MOVE THE show()! Otherwise QComboBox's sizeHint() function won't work properly! m_comboBox->show(); @@ -193,7 +192,6 @@ void CKeyChooserWidget::reset(const QStringList *list, int index, bool do_emit) /** Initializes this widget. We need this function because we have more than one constructor. */ void CKeyChooserWidget::init() { - qDebug() << "CKeyChooserWidget::init"; oldKey = QString::null; setFocusPolicy(Qt::WheelFocus); @@ -234,7 +232,6 @@ void CKeyChooserWidget::init() { /** Is called when the return key was presed in the combobox. */ void CKeyChooserWidget::slotReturnPressed( /*const QString& text*/) { Q_ASSERT(comboBox()->lineEdit()); - qDebug() << "return pressed"; QString text = comboBox()->lineEdit()->text(); for (int index = 0; index < comboBox()->count(); ++index) { @@ -248,7 +245,6 @@ void CKeyChooserWidget::slotReturnPressed( /*const QString& text*/) { /** Is called when the current item of the combo box was changed. */ void CKeyChooserWidget::slotComboChanged(int index) { - qDebug() << "CKeyChooserWidget::slotComboChanged(int index)"; if (!updatesEnabled()) { return; } diff --git a/src/frontend/keychooser/ckeychooserwidget.h b/src/frontend/keychooser/ckeychooserwidget.h index 384b19a..3121af8 100644 --- a/src/frontend/keychooser/ckeychooserwidget.h +++ b/src/frontend/keychooser/ckeychooserwidget.h @@ -158,7 +158,7 @@ class CKeyChooserWidget : public QWidget { private: - friend class CLexiconKeyChooser; + QStringList m_list; bool m_useNextPrevSignals; bool updatelock; diff --git a/src/frontend/keychooser/clexiconkeychooser.cpp b/src/frontend/keychooser/clexiconkeychooser.cpp index e09efb1..42fb4e8 100644 --- a/src/frontend/keychooser/clexiconkeychooser.cpp +++ b/src/frontend/keychooser/clexiconkeychooser.cpp @@ -11,8 +11,6 @@ #include <algorithm> #include <QHBoxLayout> -#include <QDebug> -#include "backend/config/cbtconfig.h" #include "backend/drivers/cswordlexiconmoduleinfo.h" #include "backend/keys/cswordldkey.h" #include "frontend/keychooser/bthistory.h" @@ -77,8 +75,6 @@ void CLexiconKeyChooser::updateKey(CSwordKey* key) { } void CLexiconKeyChooser::setKey(CSwordKey* key) { - qDebug() << "CLexiconKeyChooser::setKey"; - if (!(m_key = dynamic_cast<CSwordLDKey*>(key))) { return; } diff --git a/src/frontend/keychooser/cscrollbutton.cpp b/src/frontend/keychooser/cscrollbutton.cpp index df1c35d..9a92b5f 100644 --- a/src/frontend/keychooser/cscrollbutton.cpp +++ b/src/frontend/keychooser/cscrollbutton.cpp @@ -19,7 +19,7 @@ CScrollButton::CScrollButton(QWidget *parent) - : QToolButton(parent), m_isLocked(false) { + : QToolButton(parent), m_isLocked(false), m_movement(0.0) { setFocusPolicy(Qt::WheelFocus); setCursor(Qt::SplitVCursor); } @@ -40,10 +40,11 @@ void CScrollButton::mouseReleaseEvent(QMouseEvent *e) { if (!m_isLocked) return; if (e->button() != Qt::LeftButton) return; m_isLocked = false; + m_movement = 0.0; releaseMouse(); emit unlock(); } - +#include <stdio.h> void CScrollButton::mouseMoveEvent(QMouseEvent *e) { if (m_isLocked) { // Recalculate the center of the widget (might change during grab): @@ -53,29 +54,16 @@ void CScrollButton::mouseMoveEvent(QMouseEvent *e) { int vchange = (e->globalY() - center.y()); if (vchange != 0) { - // Calculate the real change we are going to emit: - int avchange(vchange >= 0 ? vchange : -vchange); - if (avchange < 10) { - avchange = (int) pow(avchange, 0.3); - } - else if (avchange < 30) { - avchange = (int) pow(avchange, 0.6); - } - else if (avchange < 40) { - avchange = (int) pow(avchange, 1.2); - } - else { - avchange = (int) pow(avchange, 2.0); - } + // Adapt the change value, so we get a more natural feeling: + if(vchange > 0) + m_movement += pow((float)vchange/10.0, 1.2); + else // (vchange < 0) + m_movement -= pow(-(float)vchange/10.0, 1.2); - // Emit the change request signal only when necessary: - if (avchange != 0) { - if (vchange > 0) { - emit change_requested(avchange); - } - else if (vchange < 0) { - emit change_requested(-avchange); - } + // Emit the change request signal only when the mouse was moved far enough + if (m_movement >= 1.0 || m_movement <= -1.0) { + emit change_requested((int) m_movement); + m_movement = 0.0; } } diff --git a/src/frontend/keychooser/cscrollbutton.h b/src/frontend/keychooser/cscrollbutton.h index 2c298b3..06d272d 100644 --- a/src/frontend/keychooser/cscrollbutton.h +++ b/src/frontend/keychooser/cscrollbutton.h @@ -75,6 +75,14 @@ class CScrollButton: public QToolButton { * change_requested() signal. */ bool m_isLocked; + + /** + * \brief The amount the mouse moved. + * + * This is saved so slow movements of mice can still be tracked and yet not + * emitting a change for every smallest movement of the mouse. + */ + float m_movement; }; #endif diff --git a/src/frontend/keychooser/cscrollerwidgetset.h b/src/frontend/keychooser/cscrollerwidgetset.h index 8645efc..f2ae643 100644 --- a/src/frontend/keychooser/cscrollerwidgetset.h +++ b/src/frontend/keychooser/cscrollerwidgetset.h @@ -37,8 +37,9 @@ class CScrollerWidgetSet : public QWidget { signals: /** - * is emitted to proceed to some other entry relative to the - * current, indicated by the int value + * Is emitted to proceed to some other entry relative to the + * current, indicated by the int value. + * \param count offset to change to */ void change(int count); diff --git a/src/frontend/keychooser/versekeychooser/btbiblekeywidget.cpp b/src/frontend/keychooser/versekeychooser/btbiblekeywidget.cpp index b74752e..5feb371 100644 --- a/src/frontend/keychooser/versekeychooser/btbiblekeywidget.cpp +++ b/src/frontend/keychooser/versekeychooser/btbiblekeywidget.cpp @@ -20,7 +20,6 @@ #include <QString> #include <QStringList> #include <QToolButton> -#include "backend/config/cbtconfig.h" #include "backend/keys/cswordversekey.h" #include "frontend/keychooser/cscrollerwidgetset.h" #include "frontend/keychooser/versekeychooser/btdropdownchooserbutton.h" @@ -240,41 +239,66 @@ void BtBibleKeyWidget::slotUpdateUnlock() { emit changed(m_key); } -void BtBibleKeyWidget::slotStepBook(int n) { +void BtBibleKeyWidget::slotStepBook(int offset) { emit beforeChange(m_key); - n > 0 ? m_key->next( CSwordVerseKey::UseBook ) : m_key->previous( CSwordVerseKey::UseBook ); + + if(offset >= 0) + for(; offset != 0; offset--) + m_key->next( CSwordVerseKey::UseBook ); + else + for(; offset != 0; offset++) + m_key->previous( CSwordVerseKey::UseBook ); + if (!updatelock) emit changed(m_key); } -void BtBibleKeyWidget::slotStepChapter(int n) { +void BtBibleKeyWidget::slotStepChapter(int offset) { emit beforeChange(m_key); - n > 0 ? m_key->next( CSwordVerseKey::UseChapter ) : m_key->previous( CSwordVerseKey::UseChapter ); + + if(offset >= 0) + for(; offset != 0; offset--) + m_key->next( CSwordVerseKey::UseChapter ); + else + for(; offset != 0; offset++) + m_key->previous( CSwordVerseKey::UseChapter ); + if (!updatelock) emit changed(m_key); } -void BtBibleKeyWidget::slotStepVerse(int n) { +void BtBibleKeyWidget::slotStepVerse(int offset) { emit beforeChange(m_key); - n > 0 ? m_key->next( CSwordVerseKey::UseVerse ) : m_key->previous( CSwordVerseKey::UseVerse ); + + if(offset >= 0) + for(; offset != 0; offset--) + m_key->next( CSwordVerseKey::UseVerse ); + else + for(; offset != 0; offset++) + m_key->previous( CSwordVerseKey::UseVerse ); + if (!updatelock) emit changed(m_key); } void BtBibleKeyWidget::slotChangeVerse(int n) { - if (m_key->Verse() != n) { + if (m_key->getVerse() != n) { emit beforeChange(m_key); - m_key->Verse( n ); + m_key->emitBeforeChanged(); + m_key->setVerse(n); + m_key->emitChanged(); setKey( m_key ); } if (!updatelock) emit changed(m_key); } void BtBibleKeyWidget::slotChangeChapter(int n) { - if (m_key->Chapter() != n) { + if (m_key->getChapter() != n) { emit beforeChange(m_key); - m_key->Chapter( n ); + m_key->emitBeforeChanged(); + m_key->setChapter(n); + m_key->emitChanged(); setKey( m_key ); } if (!updatelock) @@ -284,7 +308,9 @@ void BtBibleKeyWidget::slotChangeChapter(int n) { void BtBibleKeyWidget::slotChangeBook(QString bookname) { if (m_key->book() != bookname) { emit beforeChange(m_key); + m_key->emitBeforeChanged(); m_key->book( bookname ); + m_key->emitChanged(); setKey( m_key ); } if (!updatelock) diff --git a/src/frontend/keychooser/versekeychooser/btbiblekeywidget.h b/src/frontend/keychooser/versekeychooser/btbiblekeywidget.h index 29633fd..644bc75 100644 --- a/src/frontend/keychooser/versekeychooser/btbiblekeywidget.h +++ b/src/frontend/keychooser/versekeychooser/btbiblekeywidget.h @@ -55,11 +55,41 @@ class BtBibleKeyWidget : public QWidget { void slotUpdateLock(); void slotUpdateUnlock(); - void slotStepBook(int); - void slotStepChapter(int); - void slotStepVerse(int); + + /** + * \brief Change the book by the given offset. + * \param offset The offset to move to. + */ + void slotStepBook(int offset); + + /** + * \brief Change the chapter by the given offset. + * \param offset The offset to move to. + */ + void slotStepChapter(int offset); + + /** + * \brief Change the verse by the given offset. + * \param offset The offset to move to. + */ + void slotStepVerse(int offset); + + /** + * \brief Jump to the specified book. + * \param bookname name of the book to change to + */ void slotChangeBook(QString bookname); + + /** + * \brief Jump to the specified chapter. + * \param chapter number of the chapter to change to + */ void slotChangeChapter(int chapter); + + /** + * \brief Jump to the specified verse. + * \param bookname number of the verse to change to + */ void slotChangeVerse(int verse); public slots: diff --git a/src/frontend/keychooser/versekeychooser/btdropdownchooserbutton.cpp b/src/frontend/keychooser/versekeychooser/btdropdownchooserbutton.cpp index 512a0f3..8030aaf 100644 --- a/src/frontend/keychooser/versekeychooser/btdropdownchooserbutton.cpp +++ b/src/frontend/keychooser/versekeychooser/btdropdownchooserbutton.cpp @@ -9,7 +9,6 @@ #include "frontend/keychooser/versekeychooser/btdropdownchooserbutton.h" -#include <QDebug> #include <QWheelEvent> #include "frontend/keychooser/versekeychooser/btversekeymenu.h" #include "frontend/keychooser/versekeychooser/btbiblekeywidget.h" @@ -37,7 +36,6 @@ BtDropdownChooserButton::BtDropdownChooserButton(BtBibleKeyWidget* ref) void BtDropdownChooserButton::mousePressEvent(QMouseEvent* e) { - //qDebug() << "BtDropdownChooserButton::mousePressEvent"; //recreate the menu menu()->clear(); this->newList(); @@ -76,7 +74,6 @@ void BtBookDropdownChooserButton::newList() { } void BtBookDropdownChooserButton::slotMenuTriggered(QAction* action) { - qDebug() << "BtBookDropdownChooserButton::slotMenuTriggered" << action->text(); m_ref->slotChangeBook(action->text()); } @@ -112,7 +109,7 @@ BtVerseDropdownChooserButton::BtVerseDropdownChooserButton(BtBibleKeyWidget* ref void BtVerseDropdownChooserButton::newList() { QMenu* m = menu(); - int count = ref()->m_module->verseCount(ref()->m_key->book(), ref()->m_key->Chapter()); + int count = ref()->m_module->verseCount(ref()->m_key->book(), ref()->m_key->getChapter()); for (int i = 1; i <= count; i++) { m->addAction(QString::number(i)); } diff --git a/src/frontend/keychooser/versekeychooser/btdropdownchooserbutton.h b/src/frontend/keychooser/versekeychooser/btdropdownchooserbutton.h index 04b7000..bdd56da 100644 --- a/src/frontend/keychooser/versekeychooser/btdropdownchooserbutton.h +++ b/src/frontend/keychooser/versekeychooser/btdropdownchooserbutton.h @@ -23,7 +23,6 @@ class BtDropdownChooserButton : public QToolButton { public: BtDropdownChooserButton(BtBibleKeyWidget* ref); - virtual ~BtDropdownChooserButton() {} /** The item list is constructed here just before the menu is shown.*/ virtual void mousePressEvent(QMouseEvent* event); /** Recreates the menu list.*/ @@ -47,7 +46,6 @@ class BtBookDropdownChooserButton : public BtDropdownChooserButton { Q_OBJECT public: BtBookDropdownChooserButton(BtBibleKeyWidget* ref); - ~BtBookDropdownChooserButton() {} virtual void newList(); public slots: virtual void slotMenuTriggered(QAction* action); @@ -58,7 +56,6 @@ class BtChapterDropdownChooserButton : public BtDropdownChooserButton { Q_OBJECT public: BtChapterDropdownChooserButton(BtBibleKeyWidget* ref); - ~BtChapterDropdownChooserButton() {} virtual void newList(); public slots: virtual void slotMenuTriggered(QAction* action); @@ -69,7 +66,6 @@ class BtVerseDropdownChooserButton : public BtDropdownChooserButton { Q_OBJECT public: BtVerseDropdownChooserButton(BtBibleKeyWidget* ref); - ~BtVerseDropdownChooserButton() {} virtual void newList(); public slots: virtual void slotMenuTriggered(QAction* action); diff --git a/src/frontend/keychooser/versekeychooser/btversekeymenu.cpp b/src/frontend/keychooser/versekeychooser/btversekeymenu.cpp index 9c6e77f..ac94299 100644 --- a/src/frontend/keychooser/versekeychooser/btversekeymenu.cpp +++ b/src/frontend/keychooser/versekeychooser/btversekeymenu.cpp @@ -9,22 +9,21 @@ #include "frontend/keychooser/versekeychooser/btversekeymenu.h" -#include <QDebug> #include <QMenu> #include <QMouseEvent> #include <QTimerEvent> BtVerseKeyMenu::BtVerseKeyMenu(QWidget* parent) - : QMenu(parent), - m_timerId(0), - m_firstClickLock(true) { - qDebug() << "BtVerseKeyMenu::BtVerseKeyMenu"; - QObject::connect(this, SIGNAL(aboutToShow()), this, SLOT(startFirstClickDelayTimer())); + : QMenu(parent) + , m_timerId(0) + , m_firstClickLock(true) +{ + connect(this, SIGNAL(aboutToShow()), + this, SLOT(startFirstClickDelayTimer())); } void BtVerseKeyMenu::startFirstClickDelayTimer() { - //qDebug() << "BtVerseKeyMenu::startFirstClickDelayTimer"; m_firstClickLock = true; killTimer(m_timerId); m_timerId = startTimer(300); @@ -32,7 +31,6 @@ void BtVerseKeyMenu::startFirstClickDelayTimer() { void BtVerseKeyMenu::timerEvent(QTimerEvent* e) { if (e->timerId() == m_timerId) { - //qDebug() << "BtVerseKeyMenu::timerEvent"; killTimer(m_timerId); m_firstClickLock = false; } @@ -42,8 +40,6 @@ void BtVerseKeyMenu::timerEvent(QTimerEvent* e) { } void BtVerseKeyMenu::mouseReleaseEvent(QMouseEvent* e) { - //qDebug() << "BtVerseKeyMenu::mouseReleaseEvent"; if (m_firstClickLock) return; - //qDebug() << "BtVerseKeyMenu::mouseReleaseEvent 2"; QMenu::mouseReleaseEvent(e); } diff --git a/src/frontend/keychooser/versekeychooser/btversekeymenu.h b/src/frontend/keychooser/versekeychooser/btversekeymenu.h index 7f5b333..343277c 100644 --- a/src/frontend/keychooser/versekeychooser/btversekeymenu.h +++ b/src/frontend/keychooser/versekeychooser/btversekeymenu.h @@ -26,7 +26,6 @@ class BtVerseKeyMenu : public QMenu { Q_OBJECT public: BtVerseKeyMenu(QWidget* parent); - ~BtVerseKeyMenu() {} protected: virtual void mouseReleaseEvent(QMouseEvent* event); /** Frees the mouse button release after the delay has elapsed.*/ diff --git a/src/frontend/keychooser/versekeychooser/cbiblekeychooser.cpp b/src/frontend/keychooser/versekeychooser/cbiblekeychooser.cpp index 6a16d8d..358c9c4 100644 --- a/src/frontend/keychooser/versekeychooser/cbiblekeychooser.cpp +++ b/src/frontend/keychooser/versekeychooser/cbiblekeychooser.cpp @@ -46,7 +46,9 @@ CBibleKeyChooser::CBibleKeyChooser( layout->addWidget(w_ref); bool ok = connect(w_ref, SIGNAL(beforeChange(CSwordVerseKey *)), SLOT(beforeRefChange(CSwordVerseKey *))); - connect(w_ref, SIGNAL(changed(CSwordVerseKey *)), SLOT(refChanged(CSwordVerseKey *))); + Q_ASSERT(ok); + + ok =connect(w_ref, SIGNAL(changed(CSwordVerseKey *)), SLOT(refChanged(CSwordVerseKey *))); Q_ASSERT(ok); setKey(m_key); //set the key without changing it, setKey(key()) would change it @@ -63,7 +65,6 @@ void CBibleKeyChooser::setKey(CSwordKey* key) { Q_ASSERT(dynamic_cast<CSwordVerseKey*>(key)); if (dynamic_cast<CSwordVerseKey*>(key) == 0) return; - emit (beforeKeyChange(m_key->key())); //required to make direct setKey calls work from the outside m_key = dynamic_cast<CSwordVerseKey*>(key); w_ref->setKey(m_key); emit keyChanged(m_key); @@ -76,10 +77,6 @@ void CBibleKeyChooser::beforeRefChange(CSwordVerseKey* key) { if (!updatesEnabled()) return; - - if (m_key) - emit beforeKeyChange(m_key->key()); - } void CBibleKeyChooser::refChanged(CSwordVerseKey* key) { diff --git a/src/frontend/profile/cprofile.cpp b/src/frontend/profile/cprofile.cpp index e36c227..b1eca08 100644 --- a/src/frontend/profile/cprofile.cpp +++ b/src/frontend/profile/cprofile.cpp @@ -122,13 +122,13 @@ QList<CProfileWindow*> CProfile::load() { m_profileWindows.append(p); if (elem.hasAttribute("windowSettings")) { - p->setWindowSettings( elem.attribute("windowSettings").toInt() ); + p->windowSettings = elem.attribute("windowSettings").toInt(); } if (elem.hasAttribute("writeWindowType")) { - p->setWriteWindowType( elem.attribute("writeWindowType").toInt() ); + p->writeWindowType = elem.attribute("writeWindowType").toInt(); } if (elem.hasAttribute("hasFocus")) { - p->setFocus( static_cast<bool>(elem.attribute("hasFocus").toInt()) ); + p->hasFocus = elem.attribute("hasFocus").toInt(); } QRect rect; @@ -148,35 +148,33 @@ QList<CProfileWindow*> CProfile::load() { rect.setHeight(object.attribute("height").toInt()); } if (object.hasAttribute("isMaximized")) { - p->setMaximized( static_cast<bool>(object.attribute("isMaximized").toInt()) ); + p->maximized = object.attribute("isMaximized").toInt(); } } - p->setGeometry(rect); + p->windowGeometry = rect; object = elem.namedItem("MODULES").toElement(); if (!object.isNull()) { if (object.hasAttribute("list")) { const QString sep = object.hasAttribute("separator") ? object.attribute("separator") : "|"; - QStringList modules = object.attribute("list").split(sep); - p->setModules(modules); + p->modules = object.attribute("list").split(sep); } } object = elem.namedItem("KEY").toElement(); if (!object.isNull()) { if (object.hasAttribute("name")) - p->setKey(object.attribute("name")); + p->key = object.attribute("name"); } object = elem.namedItem("SCROLLBARS").toElement(); if (!object.isNull()) { - int horizontal = 0, vertical = 0; - if (object.hasAttribute("horizontal")) - horizontal = object.attribute("horizontal").toInt(); - if (object.hasAttribute("vertical")) - vertical = object.attribute("vertical").toInt(); - - p->setScrollbarPositions(horizontal, vertical); + p->scrollbarPosH = object.hasAttribute("horizontal") + ? object.attribute("horizontal").toInt() + : 0; + p->scrollbarPosV = object.hasAttribute("vertical") + ? object.attribute("vertical").toInt() + : 0; } } elem = elem.nextSibling().toElement(); @@ -185,12 +183,12 @@ QList<CProfileWindow*> CProfile::load() { // Are any windows maximized? bool maximized = false; for (int i = 0; i < m_profileWindows.count(); i++) { - if (m_profileWindows.at(i)->maximized()) + if (m_profileWindows.at(i)->maximized) maximized = true; } // Set all windows the same for maximized for (int i = 0; i < m_profileWindows.count(); i++) { - m_profileWindows.at(i)->setMaximized(maximized); + m_profileWindows.at(i)->maximized = maximized; } return m_profileWindows; @@ -230,7 +228,7 @@ bool CProfile::save(QList<CProfileWindow*> windows) { //for (CProfileWindow* p = windows.first(); p; p = windows.next()) { foreach(CProfileWindow* p, windows) { QDomElement window; - switch (p->type()) { + switch (p->type) { case CSwordModuleInfo::Bible: window = doc.createElement("BIBLE"); break; @@ -248,32 +246,32 @@ bool CProfile::save(QList<CProfileWindow*> windows) { } if (window.isNull()) break; - window.setAttribute("windowSettings", p->windowSettings()); - window.setAttribute("writeWindowType", p->writeWindowType()); - window.setAttribute("hasFocus", p->hasFocus()); + window.setAttribute("windowSettings", p->windowSettings); + window.setAttribute("writeWindowType", p->writeWindowType); + window.setAttribute("hasFocus", p->hasFocus); //save geomtery - const QRect r = p->geometry(); + const QRect & r = p->windowGeometry; QDomElement geometry = doc.createElement("GEOMETRY"); geometry.setAttribute("x", r.x()); geometry.setAttribute("y", r.y()); geometry.setAttribute("width", r.width()); geometry.setAttribute("height", r.height()); - geometry.setAttribute("isMaximized", static_cast<int>(p->maximized())); + geometry.setAttribute("isMaximized", static_cast<int>(p->maximized)); window.appendChild( geometry ); QDomElement modules = doc.createElement("MODULES"); modules.setAttribute("separator", "|"); - modules.setAttribute("list", p->modules().join("|")); + modules.setAttribute("list", p->modules.join("|")); window.appendChild( modules ); QDomElement key = doc.createElement("KEY"); - key.setAttribute("name", p->key()); + key.setAttribute("name", p->key); window.appendChild( key ); QDomElement scrollbars = doc.createElement("SCROLLBARS"); - scrollbars.setAttribute("horizontal", p->scrollbarPositions().horizontal); - scrollbars.setAttribute("vertical", p->scrollbarPositions().vertical); + scrollbars.setAttribute("horizontal", p->scrollbarPosH); + scrollbars.setAttribute("vertical", p->scrollbarPosV); window.appendChild( scrollbars ); content.appendChild( window ); @@ -298,16 +296,6 @@ bool CProfile::save() { return save(m_profileWindows); } -/** Returns the filename used for this profile. */ -const QString& CProfile::filename() { - return m_filename; -} - -/** Returns the name of this profile. */ -const QString& CProfile::name() { - return m_name; -} - /** Initializes the XML for the first time (use to create a new profile) */ void CProfile::init(const QString file) { const QString oldFile = m_filename; diff --git a/src/frontend/profile/cprofile.h b/src/frontend/profile/cprofile.h index 8acffd3..654160e 100644 --- a/src/frontend/profile/cprofile.h +++ b/src/frontend/profile/cprofile.h @@ -43,11 +43,15 @@ class CProfile { /** * Returns the name of this profile. */ - const QString& name(); + inline const QString &name() const { + return m_name; + } /** * Returns the filename used for this profile. */ - const QString& filename(); + inline const QString &filename() const { + return m_filename; + } /** * Initializes the XML for the first time (use to create a new profile) */ diff --git a/src/frontend/profile/cprofilemgr.cpp b/src/frontend/profile/cprofilemgr.cpp index 99e7823..4b8bcc3 100644 --- a/src/frontend/profile/cprofilemgr.cpp +++ b/src/frontend/profile/cprofilemgr.cpp @@ -42,11 +42,6 @@ CProfileMgr::~CProfileMgr() { delete m_startupProfile; } -/** Returns a list of available profiles. */ -const QList<CProfile*>& CProfileMgr::profiles() { - return m_profiles; -} - /** Creates a new profile with the name "name" (first parameter). @return The profile object */ CProfile *CProfileMgr::create(const QString &name) { CProfile* p = new CProfile(QString::null, name); @@ -84,15 +79,11 @@ bool CProfileMgr::remove( const QString& profile) { } /** Returns the profile with the desired name. If there's no such profile 0 is returned. */ -CProfile* CProfileMgr::profile(const QString& name) { - QListIterator<CProfile*> it(m_profiles); - while (it.hasNext()) { - CProfile* p = it.next(); - if (p && p->name() == name) { +CProfile * CProfileMgr::profile(const QString & name) const { + Q_FOREACH (CProfile * const p, m_profiles) { + if (p && p->name() == name) return p; - } } - return 0; } diff --git a/src/frontend/profile/cprofilemgr.h b/src/frontend/profile/cprofilemgr.h index 7f5edcf..00bb321 100644 --- a/src/frontend/profile/cprofilemgr.h +++ b/src/frontend/profile/cprofilemgr.h @@ -32,7 +32,9 @@ class CProfileMgr { /** * @return a list of available profiles */ - const QList<CProfile*>& profiles(); + inline const QList<CProfile*> &profiles() const { + return m_profiles; + } /** * Removes the profile from the list and from the directory containg the profile files. */ @@ -44,7 +46,7 @@ class CProfileMgr { /** * Returns the profile with the desired name. If there's no such profile 0 is returned. */ - CProfile* profile(const QString&); + CProfile * profile(const QString & profileName) const; /** * Returns the startup profile if it exists, otherwise return 0. */ diff --git a/src/frontend/profile/cprofilewindow.cpp b/src/frontend/profile/cprofilewindow.cpp index 4f8fab9..682c99a 100644 --- a/src/frontend/profile/cprofilewindow.cpp +++ b/src/frontend/profile/cprofilewindow.cpp @@ -9,122 +9,22 @@ #include "frontend/profile/cprofilewindow.h" -#include <QRect> -#include <QString> -#include <QStringList> -#include "backend/drivers/cswordmoduleinfo.h" -#include "backend/managers/cswordbackend.h" - namespace Profile { -CProfileWindow::CProfileWindow(CSwordModuleInfo::ModuleType type) - : m_type(type), - m_windowGeometry(), - m_moduleList(), - m_key(QString::null), - m_maximized(false), - m_hasFocus(false), - m_windowSettings(0), - m_writeWindowType(0) { - m_scrollbarPos.horizontal = 0; - m_scrollbarPos.vertical = 0; -} - -CProfileWindow::~CProfileWindow() {} - -/** Returns the size of the window including the x,y coordinates. */ -const QRect& CProfileWindow::geometry() const { - return m_windowGeometry; -} - -/** Sets the size of the window. */ -void CProfileWindow::setGeometry( const QRect& rect ) { - m_windowGeometry = rect; -} - -/** Returns the type of the managed window (bible window, commentary window or lexicon window). */ -CSwordModuleInfo::ModuleType CProfileWindow::type() const { - if (m_type != CSwordModuleInfo::Unknown) - return m_type; - return CSwordModuleInfo::Unknown; -} - -/** Sets the modules. */ -void CProfileWindow::setModules( const QStringList& modules ) { - m_moduleList = modules; //copy module pointers into our own list -} - -/** Returns a list of module names which are chosen in the managed window profile. */ -const QStringList& CProfileWindow::modules() const { - return m_moduleList; -} - -/** Returns the current key set in the modules. */ -const QString& CProfileWindow::key() const { - return m_key; -} - -/** Set the key used in the modules. */ -void CProfileWindow::setKey( const QString& key ) { - m_key = key; -} - -/** Sets the current position of the scrollbars. */ -void CProfileWindow::setScrollbarPositions(const int& horizontal, const int& vertical) { - // m_scrollbarPos = {x,y}; - m_scrollbarPos.horizontal = horizontal; - m_scrollbarPos.vertical = vertical; -} - -/** Returns tghe position of the scrollbars */ -const CProfileWindow::ScrollbarPos& CProfileWindow::scrollbarPositions() const { - return m_scrollbarPos; -} - -/** Sets the type of the used modules. */ -void CProfileWindow::setType(const CSwordModuleInfo::ModuleType& type) { - m_type = type; -} - -/** Returns true if the window is maximized. */ -const bool& CProfileWindow::maximized() const { - return m_maximized; -} - -/** Sets the windows maximized state to true or false. */ -void CProfileWindow::setMaximized( const bool& maximized ) { - m_maximized = maximized; -} - -/** Returns true if the window is maximized. */ -const bool& CProfileWindow::hasFocus() const { - return m_hasFocus; -} - -/** Sets the windows maximized state to true or false. */ -void CProfileWindow::setFocus( const bool& hasFocus ) { - m_hasFocus = hasFocus; -} - -/** Returns an integer with the window specific settings */ -const int& CProfileWindow::windowSettings() const { - return m_windowSettings; -} - -/** Sets the window specific settings. */ -void CProfileWindow::setWindowSettings( const int& settings ) { - m_windowSettings = settings; -} - -/** Tells this profile window to represent a write window. */ -void CProfileWindow::setWriteWindowType( const int& writeWindowType ) { - m_writeWindowType = writeWindowType; -} - -/** Returns whether this profile window represents a write window. */ -const int& CProfileWindow::writeWindowType() const { - return m_writeWindowType; +CProfileWindow::CProfileWindow(CSwordModuleInfo::ModuleType t) + : type(t) + , windowGeometry() + , modules() + , key(QString::null) + , scrollbarPosH(0) + , scrollbarPosV(0) + , maximized(false) + , hasFocus(false) + , windowSettings(0) + , writeWindowType(0) +{ + // Intentionally empty } } //end of namespace Profile diff --git a/src/frontend/profile/cprofilewindow.h b/src/frontend/profile/cprofilewindow.h index f9c144f..78d2b71 100644 --- a/src/frontend/profile/cprofilewindow.h +++ b/src/frontend/profile/cprofilewindow.h @@ -13,7 +13,7 @@ #include <QRect> #include <QString> #include <QStringList> -#include "backend/managers/cswordbackend.h" +#include "backend/drivers/cswordmoduleinfo.h" class CSwordModuleInfo; @@ -23,101 +23,23 @@ namespace Profile { /** Contains the settings for one window saved in the profile. * @author The BibleTime team */ -class CProfileWindow { - public: - struct ScrollbarPos { - int horizontal; //the position of the horizontal scrollbar - int vertical; //the position of the vertical scrollbar - }; +struct CProfileWindow { - CProfileWindow(CSwordModuleInfo::ModuleType type = CSwordModuleInfo::Unknown); - ~CProfileWindow(); - /** - * Sets the modules. - */ - void setModules( const QStringList& modules ); - /** - * Returns the type of the managed window (bible window, commentary window or lexicon window). - */ - CSwordModuleInfo::ModuleType type() const; - /** - * Sets the type of the used modules. - */ - void setType(const CSwordModuleInfo::ModuleType& type); - /** - * Sets the size of the window. - */ - void setGeometry( const QRect& s ); - /** - * Returns the size of the window including the x,y coordinates. - */ - const QRect& geometry() const; - /** - * Returns a list of module names which are chosen in the managed window profile. - */ - const QStringList& modules() const; - /** - * Set the key used in the modules. - */ - void setKey( const QString& ); - /** - * Returns the current key set in the modules. - */ - const QString& key() const; - /** - * Sets the current position of the scrollbars. - */ - void setScrollbarPositions(const int& x, const int& y); - /** - * Sets the windows maximized state to true or false. - */ - void setMaximized( const bool& maximized ); - /** - * Sets the windows hasFocus state to true or false. - */ - void setFocus( const bool& hasFocus ); - /** - * Sets the window specific settings. - */ - void setWindowSettings( const int& settings ); - /** - * Returns an integer with the window specific settings - */ - const int& windowSettings() const; - /** - * Returns true if the window is maximized. - */ - const bool& maximized() const; - /** - * Returns true if the window has the focus in the MDI area. - */ - const bool& hasFocus() const; - /** - * Returns tghe position of the scrollbars - */ - const CProfileWindow::ScrollbarPos& scrollbarPositions() const; - /** - * Returns whether this profile window represents a write window. - */ - const int& writeWindowType() const; - /** - * Tells this profile window to represent a write window. - */ - void setWriteWindowType( const int& writeWindowType ); + CProfileWindow(CSwordModuleInfo::ModuleType type = CSwordModuleInfo::Unknown); + + CSwordModuleInfo::ModuleType type; + QRect windowGeometry; + QStringList modules; + QString key; + int scrollbarPosH; + int scrollbarPosV; + bool maximized; + bool hasFocus; + int windowSettings; + int writeWindowType; - private: - CSwordModuleInfo::ModuleType m_type; - QRect m_windowGeometry; - QStringList m_moduleList; - QString m_key; - ScrollbarPos m_scrollbarPos; - bool m_maximized; - bool m_hasFocus; - int m_windowSettings; - int m_writeWindowType; }; } //end of namespace Profile #endif - diff --git a/src/frontend/searchdialog/analysis/csearchanalysisscene.cpp b/src/frontend/searchdialog/analysis/csearchanalysisscene.cpp index e4165ab..a039e19 100644 --- a/src/frontend/searchdialog/analysis/csearchanalysisscene.cpp +++ b/src/frontend/searchdialog/analysis/csearchanalysisscene.cpp @@ -213,7 +213,7 @@ unsigned int CSearchAnalysisScene::getCount(const QString &book, unsigned int count = 0; const unsigned int resultCount = result.Count(); while (i < resultCount) { - if ( strncmp(book.toUtf8(), (const char*)*result.GetElement(i), length) ) + if (strncmp(book.toUtf8(), (const char *) *result.getElement(i), length)) break; i++; ++count; diff --git a/src/frontend/searchdialog/analysis/csearchanalysisscene.h b/src/frontend/searchdialog/analysis/csearchanalysisscene.h index a3a1832..f8bb966 100644 --- a/src/frontend/searchdialog/analysis/csearchanalysisscene.h +++ b/src/frontend/searchdialog/analysis/csearchanalysisscene.h @@ -36,8 +36,6 @@ class CSearchAnalysisScene : public QGraphicsScene { public: CSearchAnalysisScene(QObject* parent); - virtual ~CSearchAnalysisScene() {} - /** * Starts the analysis of the search result. * This should be called only once because diff --git a/src/frontend/searchdialog/analysis/csearchanalysisview.h b/src/frontend/searchdialog/analysis/csearchanalysisview.h index 8d8c5f3..19d53c1 100644 --- a/src/frontend/searchdialog/analysis/csearchanalysisview.h +++ b/src/frontend/searchdialog/analysis/csearchanalysisview.h @@ -28,8 +28,6 @@ class CSearchAnalysisView : public QGraphicsView { public: CSearchAnalysisView(CSearchAnalysisScene* scene, QWidget* parent); - ~CSearchAnalysisView() {} - /** * Returns the sizeHint for this view * We give back the size of the parent widgetas default. diff --git a/src/frontend/searchdialog/btsearchoptionsarea.cpp b/src/frontend/searchdialog/btsearchoptionsarea.cpp index 9f76b6b..902666b 100644 --- a/src/frontend/searchdialog/btsearchoptionsarea.cpp +++ b/src/frontend/searchdialog/btsearchoptionsarea.cpp @@ -205,8 +205,6 @@ void BtSearchOptionsArea::initConnections() { /** Sets the modules used by the search. */ void BtSearchOptionsArea::setModules(const QList<const CSwordModuleInfo*> &modules) { - qDebug() << "BtSearchOptionsArea::setModules"; - qDebug() << modules; QString t; m_modules.clear(); //remove old modules @@ -246,15 +244,13 @@ void BtSearchOptionsArea::setModules(const QList<const CSwordModuleInfo*> &modul historyList.append(m_modulesCombo->itemText(i)); } CBTConfig::set(CBTConfig::searchModulesHistory, historyList); - emit sigSetSearchButtonStatus(modules.count() != 0); + emit sigSetSearchButtonStatus(!modules.isEmpty()); } // Catch activated signal of module selector combobox void BtSearchOptionsArea::moduleListTextSelected(int index) { - qDebug() << "BtSearchOptionsArea::moduleListTextSelected"; //create the module list QString text = m_modulesCombo->itemText(index); - qDebug() << text; QStringList moduleNamesList = text.split(", "); QList<const CSwordModuleInfo*> moduleList; foreach(QString name, moduleNamesList) { @@ -332,8 +328,9 @@ void BtSearchOptionsArea::aboutToShow() { } void BtSearchOptionsArea::setupRanges() { - CRangeChooserDialog* chooser = new CRangeChooserDialog(this); + CRangeChooserDialog * chooser = new CRangeChooserDialog(this); chooser->exec(); + delete chooser; refreshRanges(); } @@ -376,16 +373,13 @@ void BtSearchOptionsArea::addToHistory(const QString& text) { } void BtSearchOptionsArea::slotSearchTextEditReturnPressed() { - qDebug() << "BtSearchOptionsArea::slotSearchTextEditReturnPressed"; m_searchTextCombo->addToHistory( m_searchTextCombo->currentText() ); emit sigStartSearch(); } bool BtSearchOptionsArea::eventFilter(QObject* obj, QEvent* event) { if (event->type() == QEvent::KeyPress || event->type() == QEvent::KeyRelease) { - //qDebug() << "BtSearchOptionsArea::eventFilter" << obj << event; if (obj == m_searchTextCombo->view() || obj == m_searchTextCombo || obj == m_searchTextCombo->lineEdit()) { - //qDebug() << "BtSearchOptionsArea::eventFilter" << obj << event; obj->event(event); // don't handle this event in parent event->accept(); @@ -397,10 +391,7 @@ bool BtSearchOptionsArea::eventFilter(QObject* obj, QEvent* event) { void BtSearchOptionsArea::slotValidateText(const QString& /*newText*/) { // static const QRegExp re("\\b(AND|OR)\\b"); -// qDebug() << "new text:" << newText; -// qDebug() << "contains:" << (newText.contains(re)); // if (newText.isEmpty() || !newText.contains(re) ) { -// qDebug()<< "no AND/OR"; // if (!m_typeAndButton->isEnabled()) { // m_typeOrButton->setEnabled(true); // m_typeAndButton->setEnabled(true); @@ -409,7 +400,6 @@ void BtSearchOptionsArea::slotValidateText(const QString& /*newText*/) { // } // } // else { -// qDebug() << "AND/OR!"; // if (m_typeAndButton->isEnabled()) { // m_typeOrButton->setChecked(true); // m_typeOrButton->setEnabled(false); @@ -426,4 +416,16 @@ void BtSearchOptionsArea::slotValidateText(const QString& /*newText*/) { //} +} // namespace Search + +QDataStream &operator<<(QDataStream &out, const Search::BtSearchOptionsArea::SearchType &searchType) { + out << (qint8) searchType; + return out; +} + +QDataStream &operator>>(QDataStream &in, Search::BtSearchOptionsArea::SearchType &searchType) { + qint8 i; + in >> i; + searchType = (Search::BtSearchOptionsArea::SearchType) i; + return in; } diff --git a/src/frontend/searchdialog/btsearchoptionsarea.h b/src/frontend/searchdialog/btsearchoptionsarea.h index afc73ca..375b5e7 100644 --- a/src/frontend/searchdialog/btsearchoptionsarea.h +++ b/src/frontend/searchdialog/btsearchoptionsarea.h @@ -33,9 +33,11 @@ class BtSearchOptionsArea : public QWidget { Q_OBJECT public: - enum SearchType {AndType, OrType, FullType}; - - friend class CSearchDialog; + enum SearchType { /* Values provided for serialization */ + AndType = 0, + OrType = 1, + FullType = 2 + }; BtSearchOptionsArea(QWidget *parent = 0); ~BtSearchOptionsArea(); @@ -147,4 +149,8 @@ class BtSearchOptionsArea : public QWidget { } +QDataStream &operator<<(QDataStream &out, const Search::BtSearchOptionsArea::SearchType &searchType); +QDataStream &operator>>(QDataStream &in, Search::BtSearchOptionsArea::SearchType &searchType); +Q_DECLARE_METATYPE(Search::BtSearchOptionsArea::SearchType) + #endif diff --git a/src/frontend/searchdialog/btsearchresultarea.cpp b/src/frontend/searchdialog/btsearchresultarea.cpp index 623de0e..9986e26 100644 --- a/src/frontend/searchdialog/btsearchresultarea.cpp +++ b/src/frontend/searchdialog/btsearchresultarea.cpp @@ -33,10 +33,8 @@ namespace Search { BtSearchResultArea::BtSearchResultArea(QWidget *parent) : QWidget(parent) { - qDebug() << "BtSearchResultArea::BtSearchResultArea"; initView(); initConnections(); - qDebug() << "BtSearchResultArea::BtSearchResultArea end"; } void BtSearchResultArea::initView() { @@ -155,11 +153,11 @@ void BtSearchResultArea::updatePreview(const QString& key) { vk.previous(CSwordVerseKey::UseVerse); //include Headings in display, they are indexed and searched too - if (vk.Verse() == 1) { - if (vk.Chapter() == 1) { - vk.Chapter(0); + if (vk.getVerse() == 1) { + if (vk.getChapter() == 1) { + vk.setChapter(0); } - vk.Verse(0); + vk.setVerse(0); } const QString startKey = vk.key(); @@ -182,11 +180,11 @@ void BtSearchResultArea::updatePreview(const QString& key) { ((sword::VerseKey*)(module->module()->getKey()))->Headings(1); //HACK: enable headings for VerseKeys //include Headings in display, they are indexed and searched too - if (vk.Verse() == 1) { - if (vk.Chapter() == 1) { - vk.Chapter(0); + if (vk.getVerse() == 1) { + if (vk.getChapter() == 1) { + vk.setChapter(0); } - vk.Verse(0); + vk.setVerse(0); } const QString startKey = vk.key(); @@ -525,7 +523,7 @@ void BtSearchResultArea::loadDialogSettings() { /** * Save the settings to the resource file */ -void BtSearchResultArea::saveDialogSettings() { +void BtSearchResultArea::saveDialogSettings() const { CBTConfig::set(CBTConfig::searchMainSplitterSizes, m_mainSplitter->sizes()); CBTConfig::set(CBTConfig::searchResultSplitterSizes, m_resultListSplitter->sizes()); } @@ -568,7 +566,7 @@ StrongsResultList::StrongsResultList(const CSwordModuleInfo *module, progress.setValue(index); qApp->processEvents(QEventLoop::AllEvents, 1); //1 ms only - QString key = QString::fromUtf8(result.GetElement(index)->getText()); + QString key = QString::fromUtf8(result.getElement(index)->getText()); QString text = CDisplayRendering().renderSingleKey(key, modules, settings); for (int sIndex = 0;;) { continueloop: diff --git a/src/frontend/searchdialog/btsearchresultarea.h b/src/frontend/searchdialog/btsearchresultarea.h index f7ef8d8..bd75a02 100644 --- a/src/frontend/searchdialog/btsearchresultarea.h +++ b/src/frontend/searchdialog/btsearchresultarea.h @@ -151,7 +151,7 @@ class BtSearchResultArea : public QWidget { /** * Save the settings to the resource file */ - void saveDialogSettings(); + void saveDialogSettings() const; protected slots: /** diff --git a/src/frontend/searchdialog/cmoduleresultview.cpp b/src/frontend/searchdialog/cmoduleresultview.cpp index f37b4d9..ab4810b 100644 --- a/src/frontend/searchdialog/cmoduleresultview.cpp +++ b/src/frontend/searchdialog/cmoduleresultview.cpp @@ -15,7 +15,6 @@ #include <QMenu> #include <QStringList> #include <QTreeWidget> -#include <QDebug> #include <QtAlgorithms> #include "backend/drivers/cswordmoduleinfo.h" @@ -224,7 +223,6 @@ CSwordModuleInfo* CModuleResultView::activeModule() { /** Reimplementation from QWidget. */ void CModuleResultView::contextMenuEvent( QContextMenuEvent * event ) { - qDebug() << "CModuleResultView::showPopup"; //make sure that all entries have the correct status m_popup->exec(event->globalPos()); } @@ -233,8 +231,7 @@ void CModuleResultView::contextMenuEvent( QContextMenuEvent * event ) { void CModuleResultView::copyResult() { CSwordModuleInfo *m = activeModule(); if (m != 0) { - CExportManager mgr(tr("Copy search result..."), true, - tr("Copying search result")); + CExportManager mgr(true, tr("Copying search result")); mgr.copyKeyList(m_results[m], m, CExportManager::Text, false); }; @@ -244,9 +241,7 @@ void CModuleResultView::copyResult() { void CModuleResultView::copyResultWithText() { CSwordModuleInfo *m = activeModule(); if (m != 0) { - CExportManager mgr(tr("Copy search result..."), true, - tr("Copying search result")); - + CExportManager mgr(true, tr("Copying search result")); mgr.copyKeyList(m_results[m], m, CExportManager::Text, true); }; } @@ -255,9 +250,7 @@ void CModuleResultView::copyResultWithText() { void CModuleResultView::saveResult() { CSwordModuleInfo *m = activeModule(); if (m != 0) { - CExportManager mgr(tr("Save search result..."), true, - tr("Saving search result")); - + CExportManager mgr(true, tr("Saving search result")); mgr.saveKeyList(m_results[m], m, CExportManager::Text, false); }; } @@ -266,9 +259,7 @@ void CModuleResultView::saveResult() { void CModuleResultView::saveResultWithText() { CSwordModuleInfo *m = activeModule(); if (m != 0) { - CExportManager mgr(tr("Save search result..."), true, - tr("Saving search result")); - + CExportManager mgr(true, tr("Saving search result")); mgr.saveKeyList(m_results[m], m, CExportManager::Text, true); }; } @@ -277,9 +268,7 @@ void CModuleResultView::saveResultWithText() { void CModuleResultView::printResult() { CSwordModuleInfo *m = activeModule(); if (m != 0) { - CExportManager mgr(tr("Print search result..."), true, - tr("Printing search result")); - + CExportManager mgr(true, tr("Printing search result")); mgr.printKeyList(m_results[m], m, CBTConfig::getDisplayOptionDefaults(), CBTConfig::getFilterOptionDefaults()); }; diff --git a/src/frontend/searchdialog/crangechooserdialog.cpp b/src/frontend/searchdialog/crangechooserdialog.cpp index 4fc2a3d..6a8c89d 100644 --- a/src/frontend/searchdialog/crangechooserdialog.cpp +++ b/src/frontend/searchdialog/crangechooserdialog.cpp @@ -17,7 +17,6 @@ #include <QListWidget> #include <QListWidgetItem> #include <QPushButton> -#include <QString> #include <QTextEdit> #include <QVBoxLayout> #include "backend/config/cbtconfig.h" @@ -27,285 +26,244 @@ #include "versekey.h" #include "listkey.h" - namespace Search { -/********** RangeItem ******************/ -CRangeChooserDialog::RangeItem::RangeItem(QListWidget* view, QListWidgetItem* /*afterThis*/, const QString caption, const QString range) - : QListWidgetItem(view) { - setCaption(caption); - setRange(range); -} - -CRangeChooserDialog::RangeItem::~RangeItem() {} - -const QString& CRangeChooserDialog::RangeItem::range() const { - // qWarning("range is %s", (const char*)m_range.utf8()); - return m_range; -} - -void CRangeChooserDialog::RangeItem::setRange(QString newRange) { - m_range = newRange; -} - -QString CRangeChooserDialog::RangeItem::caption() const { - return text(); -} - -void CRangeChooserDialog::RangeItem::setCaption(const QString newCaption) { - setText(newCaption); -} - - -/*********** Dialog ***************/ - -CRangeChooserDialog::CRangeChooserDialog( QWidget* parentDialog ) - : QDialog(parentDialog) { - //Set the flag to destroy when closed - otherwise eats memory - setAttribute(Qt::WA_DeleteOnClose); +CRangeChooserDialog::CRangeChooserDialog(QWidget *parentDialog) + : QDialog(parentDialog) +{ initView(); initConnections(); - //add the existing scopes - CBTConfig::StringMap map = CBTConfig::get - (CBTConfig::searchScopes); + retranslateUi(); + + // Add the existing scopes + CBTConfig::StringMap map = CBTConfig::get(CBTConfig::searchScopes); CBTConfig::StringMap::Iterator it; for (it = map.begin(); it != map.end(); ++it) { - new RangeItem(m_rangeList, 0, it.key(), it.value()); - }; - - editRange(0); - if (RangeItem* i = dynamic_cast<RangeItem*>(m_rangeList->currentItem()) - ) { - nameChanged(i->caption()); + new RangeItem(it.key(), it.value(), m_rangeList); } + resetEditControls(); } -/** Initializes the view of this object. */ void CRangeChooserDialog::initView() { - setWindowTitle(tr("Setup Search Scopes")); - - QVBoxLayout* vboxLayout = new QVBoxLayout(this); - - QHBoxLayout* hboxLayout = new QHBoxLayout(); - QVBoxLayout* vboxLayout1 = new QVBoxLayout(); - QLabel* rangeListLabel = new QLabel(tr("S&earch range:"), this); - vboxLayout1->addWidget(rangeListLabel); - m_rangeList = new QListWidget(this); - m_rangeList->setToolTip(tr("Select a scope from the list to edit the search ranges")); - vboxLayout1->addWidget(m_rangeList); - - QHBoxLayout* hboxLayout1 = new QHBoxLayout(); - m_newRangeButton = new QPushButton(tr("&Add new scope"), this); - m_newRangeButton->setToolTip(tr("Add a new search scope. First enter an appropriate name, then edit the search ranges.")); - hboxLayout1->addWidget(m_newRangeButton); - m_deleteRangeButton = new QPushButton(tr("Delete current &scope"), this); - m_deleteRangeButton->setToolTip(tr("Delete the selected search scope")); - hboxLayout1->addWidget(m_deleteRangeButton); + m_rangeListLabel = new QLabel(this); + m_rangeListLabel->setBuddy(m_rangeList); - vboxLayout1->addLayout(hboxLayout1); - hboxLayout->addLayout(vboxLayout1); - - QVBoxLayout* vboxLayout2 = new QVBoxLayout(); - QHBoxLayout* hboxLayout2 = new QHBoxLayout(); - QLabel* nameEditLabel = new QLabel(tr("&Name:"), this); - hboxLayout2->addWidget(nameEditLabel); + m_newRangeButton = new QPushButton(this); + m_deleteRangeButton = new QPushButton(this); m_nameEdit = new QLineEdit(this); - m_nameEdit->setToolTip(tr("Change the name of the selected search scope")); - hboxLayout2->addWidget(m_nameEdit); - vboxLayout2->addLayout(hboxLayout2); - - QLabel* rangeEditLabel = new QLabel(tr("Edi&t current range:"), this); - vboxLayout2->addWidget(rangeEditLabel); + m_nameEditLabel = new QLabel(this); + m_nameEditLabel->setBuddy(m_nameEdit); m_rangeEdit = new QTextEdit(this); - m_rangeEdit->setToolTip(tr("Change the search ranges of the selected search scope item. Have a look at the predefined search scopes to see how search ranges are constructed.")); - - vboxLayout2->addWidget(m_rangeEdit); - - QLabel* resultListLabel = new QLabel(tr("Parsed search range:"), this); - vboxLayout2->addWidget(resultListLabel); + m_rangeEditLabel = new QLabel(this); + m_rangeEditLabel->setBuddy(m_rangeEdit); m_resultList = new QListWidget(this); - m_resultList->setToolTip(tr("The search ranges which will be used for the search, parsed to the canonical form")); - vboxLayout2->addWidget(m_resultList); - - hboxLayout->addLayout(vboxLayout2); - vboxLayout->addLayout(hboxLayout); + m_resultListLabel = new QLabel(this); + m_resultListLabel->setBuddy(m_resultList); - QFrame* line = new QFrame(this); - line->setFrameShape(QFrame::HLine); - line->setFrameShadow(QFrame::Sunken); - vboxLayout->addWidget(line); + QFrame *hSeparatorLine = new QFrame(this); + hSeparatorLine->setFrameShape(QFrame::HLine); + hSeparatorLine->setFrameShadow(QFrame::Sunken); m_buttonBox = new QDialogButtonBox(this); m_buttonBox->setOrientation(Qt::Horizontal); - m_buttonBox->setStandardButtons(QDialogButtonBox::Cancel | QDialogButtonBox::NoButton | QDialogButtonBox::Ok | QDialogButtonBox::RestoreDefaults); + m_buttonBox->setStandardButtons(QDialogButtonBox::Ok + | QDialogButtonBox::Cancel + | QDialogButtonBox::RestoreDefaults); util::prepareDialogBox(m_buttonBox); + + QHBoxLayout *rangeButtonsLayout = new QHBoxLayout(); + rangeButtonsLayout->addWidget(m_newRangeButton); + rangeButtonsLayout->addWidget(m_deleteRangeButton); + + QVBoxLayout* rangeListLayout = new QVBoxLayout; + rangeListLayout->addWidget(m_rangeListLabel); + rangeListLayout->addWidget(m_rangeList); + rangeListLayout->addLayout(rangeButtonsLayout); + + QHBoxLayout* nameEditLayout = new QHBoxLayout(); + nameEditLayout->addWidget(m_nameEditLabel); + nameEditLayout->addWidget(m_nameEdit); + + QVBoxLayout* rangeEditLayout = new QVBoxLayout(); + rangeEditLayout->addLayout(nameEditLayout); + rangeEditLayout->addWidget(m_rangeEditLabel); + rangeEditLayout->addWidget(m_rangeEdit); + rangeEditLayout->addWidget(m_resultListLabel); + rangeEditLayout->addWidget(m_resultList); + + QHBoxLayout *topLayout = new QHBoxLayout; + topLayout->addLayout(rangeListLayout); + topLayout->addLayout(rangeEditLayout); + + QVBoxLayout *vboxLayout = new QVBoxLayout(this); + vboxLayout->addLayout(topLayout); + vboxLayout->addWidget(hSeparatorLine); vboxLayout->addWidget(m_buttonBox); +} - rangeListLabel->setBuddy(m_rangeList); - nameEditLabel->setBuddy(m_nameEdit); - rangeEditLabel->setBuddy(m_rangeEdit); - resultListLabel->setBuddy(m_resultList); +void CRangeChooserDialog::initConnections() { + connect(m_rangeList, SIGNAL(currentItemChanged(QListWidgetItem*, + QListWidgetItem*)), + this, SLOT(selectedRangeChanged(QListWidgetItem*, + QListWidgetItem*))); + connect(m_nameEdit, SIGNAL(textEdited(QString)), + this, SLOT(nameEditTextChanged(QString))); + connect(m_rangeEdit, SIGNAL(textChanged()), + this, SLOT(updateResultList())); + + // Connect buttons: + connect(m_buttonBox, SIGNAL(accepted()), + this, SLOT(accept())); + connect(m_buttonBox, SIGNAL(rejected()), + this, SLOT(reject())); + connect(m_newRangeButton, SIGNAL(clicked()), + this, SLOT(addNewRange())); + connect(m_deleteRangeButton, SIGNAL(clicked()), + this, SLOT(deleteCurrentRange())); + QPushButton * defaultsButton = m_buttonBox->button(QDialogButtonBox::RestoreDefaults); + connect(defaultsButton, SIGNAL(clicked()), + this, SLOT(restoreDefaults())); } +void CRangeChooserDialog::retranslateUi() { + setWindowTitle(tr("Setup Search Scopes")); + m_rangeListLabel->setText(tr("S&earch range:")); + m_rangeList->setToolTip(tr("Select a scope from the list to edit the search" + "ranges")); -void CRangeChooserDialog::initConnections() { - // Signals from text/list widgets - QObject::connect(m_rangeList, SIGNAL(currentItemChanged(QListWidgetItem*, QListWidgetItem*)), - this, SLOT(editRange(QListWidgetItem*))); - - QObject::connect(m_rangeEdit, SIGNAL(textChanged()), - this, SLOT(parseRange())); - QObject::connect(m_rangeEdit, SIGNAL(textChanged()), - this, SLOT(rangeChanged())); - - QObject::connect(m_nameEdit, SIGNAL(textChanged(const QString&)), - this, SLOT(nameChanged(const QString&))); - - // Buttons - QObject::connect(m_buttonBox, SIGNAL(accepted()), this, SLOT(slotOk())); - QObject::connect(m_buttonBox, SIGNAL(rejected()), this, SLOT(close())); - QObject::connect(m_newRangeButton, SIGNAL(clicked()), this, SLOT(addNewRange())); - QObject::connect(m_deleteRangeButton, SIGNAL(clicked()), this, SLOT(deleteCurrentRange())); - //restore defaults! - QPushButton* defaultsButton = m_buttonBox->button(QDialogButtonBox::RestoreDefaults); - QObject::connect(defaultsButton, SIGNAL(clicked()), this, SLOT(slotDefault())); + m_newRangeButton->setText(tr("&Add new scope")); + m_newRangeButton->setToolTip(tr("Add a new search scope. First enter an " + "appropriate name, then edit the search " + "ranges.")); + + m_deleteRangeButton->setText(tr("Delete current &scope")); + m_deleteRangeButton->setToolTip(tr("Delete the selected search scope")); + + m_nameEditLabel->setText(tr("&Name:")); + m_nameEdit->setToolTip(tr("Change the name of the selected search scope")); + + m_rangeEditLabel->setText(tr("Edi&t current range:")); + m_rangeEdit->setToolTip(tr("Change the search ranges of the selected search" + "scope item. Have a look at the predefined " + "search scopes to see how search ranges are " + "constructed.")); + + m_resultListLabel->setText(tr("Parsed search range:")); + m_resultList->setToolTip(tr("The search ranges which will be used for the " + "search, parsed to the canonical form")); +} + +void CRangeChooserDialog::saveCurrentToRange(RangeItem * i) { + if (!m_nameEdit->text().isEmpty()) + i->setCaption(m_nameEdit->text()); + + i->setRange(m_rangeEdit->toPlainText()); } -/** Adds a new range to the list. */ void CRangeChooserDialog::addNewRange() { - //qDebug() << "CRangeChooserDialog::addNewRange"; - //RangeItem* i = new RangeItem(m_rangeList, m_rangeList->lastItem(), tr("New range")); - RangeItem* i = new RangeItem(m_rangeList, 0, tr("New range")); - //use just setCurrentItem... m_rangeList->setSelected(i, true); + static const QString nullStr; + RangeItem * const i = new RangeItem(tr("New range"), nullStr, m_rangeList); m_rangeList->setCurrentItem(i); - editRange(i); + resetEditControls(); +} - m_nameEdit->setFocus(); +void CRangeChooserDialog::selectedRangeChanged(QListWidgetItem * current, + QListWidgetItem * previous) +{ + if (previous) { + Q_ASSERT(dynamic_cast<RangeItem*>(previous) != 0); + saveCurrentToRange(static_cast<RangeItem*>(previous)); + } + + resetEditControls(); } -/** No descriptions */ -void CRangeChooserDialog::editRange(QListWidgetItem* item) { - //qDebug() << "CRangeChooserDialog::editRange"; - RangeItem* const range = dynamic_cast<RangeItem*>(item); +void CRangeChooserDialog::resetEditControls() { + const QListWidgetItem * const item = m_rangeList->currentItem(); + Q_ASSERT(item == 0 || dynamic_cast<const RangeItem *>(item) != 0); + const RangeItem * rangeItem = static_cast<const RangeItem *>(item); - m_nameEdit->setEnabled( range ); //only if an item is selected enable the edit part - m_rangeEdit->setEnabled( range ); - m_resultList->setEnabled( range ); - m_deleteRangeButton->setEnabled( range ); + m_nameEdit->setEnabled(item != 0); + m_rangeEdit->setEnabled(item != 0); + m_resultList->setEnabled(item != 0); + m_deleteRangeButton->setEnabled(item != 0); + m_nameEdit->setText(item != 0 ? rangeItem->caption() : ""); + m_rangeEdit->setText(item != 0 ? rangeItem->range() : ""); - if (range) { - m_nameEdit->setText(range->caption()); - m_rangeEdit->setText(range->range()); - } + if (item != 0) + m_nameEdit->setFocus(); + + nameEditTextChanged(item != 0 ? rangeItem->caption() : ""); } -/** Parses the entered text and prints out the result in the list box below the edit area. */ -void CRangeChooserDialog::parseRange() { - //qDebug() << "CRangeChooserDialog::parseRange"; +void CRangeChooserDialog::updateResultList() { + typedef sword::VerseKey VK; + m_resultList->clear(); /// \todo remove this hack: - //HACK: repair range to work with Sword 1.5.6 - QString range( m_rangeEdit->toPlainText() ); - range.replace(QRegExp("\\s{0,}-\\s{0,}"), "-" ); + //HACK: repair range to work with Sword 1.5.6 + const QString range = m_rangeEdit->toPlainText().replace(QRegExp("\\s{0,}-\\s{0,}"), "-"); - sword::VerseKey key; - sword::ListKey verses = key.ParseVerseList((const char*)range.toUtf8(), "Genesis 1:1", true); + sword::ListKey verses = VK().ParseVerseList(range.toUtf8().constData(), + "Genesis 1:1", true); for (int i = 0; i < verses.Count(); ++i) { - new QListWidgetItem(QString::fromUtf8(verses.GetElement(i)->getRangeText()), m_resultList ); - // qWarning("range=%s, text=%s",verses.GetElement(i)->getRangeText(), verses.GetElement(i)->getText() ); + new QListWidgetItem(QString::fromUtf8(verses.getElement(i)->getRangeText()), + m_resultList); } - } -/** No descriptions */ -void CRangeChooserDialog::rangeChanged() { - //qDebug() << "CRangeChooserDialog::rangeChanged"; - if (RangeItem* i = dynamic_cast<RangeItem*>(m_rangeList->currentItem()) - ) { - QString range( m_rangeEdit->toPlainText() ); - /// \todo remove this hack: - //HACK: repair range to work with Sword 1.5.6 - range.replace(QRegExp("\\s{0,}-\\s{0,}"), "-" ); - i->setRange(range); - }; -} +void CRangeChooserDialog::deleteCurrentRange() { + Q_ASSERT(dynamic_cast<RangeItem*>(m_rangeList->currentItem()) != 0); + QListWidgetItem *i = m_rangeList->currentItem(); + m_rangeList->removeItemWidget(i); + delete i; -/** No descriptions */ -void CRangeChooserDialog::nameChanged(const QString& newCaption) { - //qDebug() << "CRangeChooserDialog::nameChanged"; - m_rangeEdit->setEnabled(!newCaption.isEmpty()); - m_resultList->setEnabled(!newCaption.isEmpty()); - //m_resultList->header()->setEnabled(!newCaption.isEmpty()); - - if (RangeItem* i = dynamic_cast<RangeItem*>(m_rangeList->currentItem()) - ) { - if (!newCaption.isEmpty()) { - //enable some items (see "else" below) - m_newRangeButton->setEnabled(true); - m_buttonBox->button(QDialogButtonBox::Ok)->setEnabled(true); - m_rangeList->setDisabled(false); - i->setCaption(newCaption); - } - else { //invalid name - i->setCaption(tr("<invalid name of search range>")); - //disable some items to prevent saving invalid range - m_newRangeButton->setEnabled(false); - m_buttonBox->button(QDialogButtonBox::Ok)->setEnabled(false); - m_rangeList->setDisabled(true); - }; - }; + resetEditControls(); } -/** Deletes the selected range. */ -void CRangeChooserDialog::deleteCurrentRange() { - //qDebug() << "CRangeChooserDialog::deleteCurrentRange"; - if (RangeItem* i = dynamic_cast<RangeItem*>(m_rangeList->currentItem()) ) { - int row = m_rangeList->row(i); - m_rangeList->takeItem(row); - delete i; +void CRangeChooserDialog::accept() { + // Update the active item: + QListWidgetItem *currentItem = m_rangeList->currentItem(); + if (currentItem != 0) { + Q_ASSERT(dynamic_cast<RangeItem*>(currentItem) != 0); + saveCurrentToRange(static_cast<RangeItem*>(currentItem)); } - editRange(m_rangeList->currentItem()); -} -void CRangeChooserDialog::slotOk() { - m_rangeList->sortItems(); //sorted first because the order will be saved - //save the new map of search scopes + // Save the new sorted map of search scopes: + m_rangeList->sortItems(); CBTConfig::StringMap map; for (int i = 0; i < m_rangeList->count(); i++) { - if ( RangeItem* item = dynamic_cast<RangeItem*>(m_rangeList->item(i)) ) { - map[item->caption()] = item->range(); - }; + Q_ASSERT(dynamic_cast<RangeItem*>(m_rangeList->item(i)) != 0); + const RangeItem * item = static_cast<RangeItem*>(m_rangeList->item(i)); + map[item->caption()] = item->range(); } - CBTConfig::set - (CBTConfig::searchScopes, map); + CBTConfig::set(CBTConfig::searchScopes, map); QDialog::accept(); } -void CRangeChooserDialog::slotDefault() { - //qDebug() << "CRangeChooserDialog::slotDefault"; +void CRangeChooserDialog::restoreDefaults() { + typedef CBTConfig::StringMap::ConstIterator SMCI; + m_rangeList->clear(); - CBTConfig::StringMap map = CBTConfig::getDefault(CBTConfig::searchScopes); - CBTConfig::StringMap::Iterator it; - for (it = map.begin(); it != map.end(); ++it) { - new RangeItem(m_rangeList, 0, it.key(), it.value()); + const CBTConfig::StringMap map = CBTConfig::getDefault(CBTConfig::searchScopes); + for (SMCI it = map.begin(); it != map.end(); ++it) { + new RangeItem(it.key(), it.value(), m_rangeList); }; m_rangeList->setCurrentItem(0); - - editRange(0); - if (RangeItem* i = dynamic_cast<RangeItem*>(m_rangeList->currentItem()) - ) { - nameChanged(i->caption()); - } - + resetEditControls(); } +void CRangeChooserDialog::nameEditTextChanged(const QString &newText) { + const bool e = !newText.isEmpty() || m_rangeList->count() <= 0; + m_buttonBox->button(QDialogButtonBox::Ok)->setEnabled(e); +} } //end of namespace Search diff --git a/src/frontend/searchdialog/crangechooserdialog.h b/src/frontend/searchdialog/crangechooserdialog.h index 8a3a91e..db2ad30 100644 --- a/src/frontend/searchdialog/crangechooserdialog.h +++ b/src/frontend/searchdialog/crangechooserdialog.h @@ -16,6 +16,7 @@ class QDialogButtonBox; +class QLabel; class QLineEdit; class QListWidget; class QPushButton; @@ -23,65 +24,121 @@ class QTextEdit; namespace Search { -class CRangeChooserDialog : public QDialog { +/** \todo Redesign this dialog and rename to have a Bt prefix. */ +class CRangeChooserDialog: public QDialog { + Q_OBJECT + +private: /* Types: */ + + class RangeItem: public QListWidgetItem { + public: - CRangeChooserDialog(QWidget* parentDialog); - ~CRangeChooserDialog() {} - - protected: // Protected methods - class RangeItem : public QListWidgetItem { - public: - RangeItem(QListWidget*, QListWidgetItem* afterThis = 0, const QString caption = QString::null, const QString range = QString::null); - ~RangeItem(); - const QString& range() const; - QString caption() const; - void setRange(QString range); - void setCaption(const QString); - private: - QString m_range; - }; - - /** - * Initializes the connections of this widget. - */ - void initConnections(); - /** - * Initializes the view of this object. - */ - void initView(); - - protected slots: // Protected slots - /** - * Adds a new range to the list. - */ - void addNewRange(); - void editRange(QListWidgetItem*); - /** - * Parses the entered text and prints out the result in the list box below the edit area. - */ - void parseRange(); - void nameChanged(const QString&); - void rangeChanged(); - /** - * Deletes the selected range. - */ - void deleteCurrentRange(); - virtual void slotDefault(); - virtual void slotOk(); - - private: - QListWidget* m_rangeList; - QListWidget* m_resultList; - QLineEdit* m_nameEdit; - QTextEdit* m_rangeEdit; - QPushButton* m_newRangeButton; - QPushButton* m_deleteRangeButton; - QDialogButtonBox* m_buttonBox; -}; - - -} //end of namespace Search + inline RangeItem(const QString &caption, + const QString &range = QString::null, + QListWidget * parent = 0) + : QListWidgetItem(caption, parent) + , m_range(range) {} + + inline const QString caption() const { return text(); } + inline void setCaption(const QString &caption) { setText(caption); } + inline const QString &range() const { return m_range; } + inline void setRange(const QString &range) { m_range = range; } + + private: /* Fields: */ + + QString m_range; + + }; /* class RangeItem */ + +public: /* Methods: */ + + CRangeChooserDialog(QWidget *parentDialog = 0); + + virtual void accept(); + +private: /* Methods: */ + + /** + Initializes widgets. + */ + void initView(); + + /** + Initializes connections. + */ + void initConnections(); + + void retranslateUi(); + + /** + Stores the values from the current edit view to the given RangeItem. + \param[out] i The RangeItem object to store the values to. + */ + void saveCurrentToRange(RangeItem * i); + + /** + Resets the editing controls based on whether a range is selected in the + range list. + */ + void resetEditControls(); + +private slots: + + /** + Adds a new range to the list. + */ + void addNewRange(); + + /** + Handles changes in m_rangeList. + */ + void selectedRangeChanged(QListWidgetItem * current, + QListWidgetItem * previous); + + /** + Parses the entered text and prints out the result in the list box below + the edit area. + */ + void updateResultList(); + + /** + Deletes the selected range. + */ + void deleteCurrentRange(); + + /** + Restores the default ranges. + */ + void restoreDefaults(); + + /** + Called when m_nameEdit changes. + */ + void nameEditTextChanged(const QString &newText); + +private: + + QLabel *m_rangeListLabel; + QListWidget *m_rangeList; + + QLabel *m_nameEditLabel; + QLineEdit *m_nameEdit; + + QLabel *m_rangeEditLabel; + QTextEdit *m_rangeEdit; + + QLabel *m_resultListLabel; + QListWidget *m_resultList; + + QPushButton *m_newRangeButton; + QPushButton *m_deleteRangeButton; + + QDialogButtonBox *m_buttonBox; + +}; /* class CRangeChooserDialog */ + +} /* namespace Search */ #endif diff --git a/src/frontend/searchdialog/csearchdialog.cpp b/src/frontend/searchdialog/csearchdialog.cpp index 5461732..8ce55d4 100644 --- a/src/frontend/searchdialog/csearchdialog.cpp +++ b/src/frontend/searchdialog/csearchdialog.cpp @@ -14,7 +14,6 @@ #include <QLabel> #include <QLineEdit> #include <QPushButton> -#include <QSettings> #include <QSizePolicy> #include <QString> #include <QRegExp> @@ -181,7 +180,6 @@ QString CSearchDialog::prepareSearchText(const QString& orig) { static const QRegExp orWords("\\bor\\b", Qt::CaseInsensitive); QString text(""); if (m_searchOptionsArea->searchType() == BtSearchOptionsArea::AndType) { - qDebug() << "AND type"; text = orig.simplified(); text.remove(syntaxCharacters); qDebug() << "After syntax characters removed:" << text; @@ -289,7 +287,7 @@ void CSearchDialog::loadDialogSettings() { move(CBTConfig::get(CBTConfig::searchDialogX), CBTConfig::get(CBTConfig::searchDialogY)); } -void CSearchDialog::saveDialogSettings() { +void CSearchDialog::saveDialogSettings() const { CBTConfig::set(CBTConfig::searchDialogWidth, size().width()); CBTConfig::set(CBTConfig::searchDialogHeight, size().height()); CBTConfig::set(CBTConfig::searchDialogX, x()); diff --git a/src/frontend/searchdialog/csearchdialog.h b/src/frontend/searchdialog/csearchdialog.h index b8c097f..dd2fcd2 100644 --- a/src/frontend/searchdialog/csearchdialog.h +++ b/src/frontend/searchdialog/csearchdialog.h @@ -38,10 +38,9 @@ class CSearchDialog : public QDialog { static void closeDialog(); protected: + friend class CSearchAnalysisScene; - friend class CSearchResultArea; friend class BtSearchResultArea; - friend class BibleTime; /** * Only interesting for the class members! Useful to get the searched text etc. @@ -109,7 +108,7 @@ class CSearchDialog : public QDialog { /** * Save the settings to the resource file */ - void saveDialogSettings(); + void saveDialogSettings() const; protected slots: /** diff --git a/src/frontend/searchdialog/csearchresultview.cpp b/src/frontend/searchdialog/csearchresultview.cpp index 6f15b62..7966e56 100644 --- a/src/frontend/searchdialog/csearchresultview.cpp +++ b/src/frontend/searchdialog/csearchresultview.cpp @@ -15,7 +15,6 @@ #include <QTreeWidget> #include <QTreeWidgetItem> #include <QWidget> -#include <QDebug> #include "backend/keys/cswordversekey.h" #include "frontend/cdragdrop.h" #include "frontend/cexportmanager.h" @@ -32,8 +31,6 @@ CSearchResultView::CSearchResultView(QWidget* parent) initConnections(); } -CSearchResultView::~CSearchResultView() {} - /** Initializes the view of this widget. */ void CSearchResultView::initView() { namespace DU = util::directory; @@ -112,7 +109,7 @@ void CSearchResultView::setupTree(const CSwordModuleInfo *m, QTreeWidgetItem* item = 0; for (int index = 0; index < count; index++) { item = new QTreeWidgetItem(this, oldItem); - item->setText(0, QString::fromUtf8(result.GetElement(index)->getText())); + item->setText(0, QString::fromUtf8(result.getElement(index)->getText())); oldItem = item; } @@ -161,13 +158,12 @@ void CSearchResultView::executed(QTreeWidgetItem* current, QTreeWidgetItem*) { /// \todo another function? /** Reimplementation to show the popup menu. */ void CSearchResultView::contextMenuEvent(QContextMenuEvent* event) { - qDebug() << "CSearchResultView::showPopup"; m_popup->exec(event->globalPos()); } void CSearchResultView::printItems() { QList<QTreeWidgetItem*> items = selectedItems(); - CExportManager mgr(tr("Print search result..."), true, tr("Printing search result")); + CExportManager mgr(true, tr("Printing search result")); QStringList list; foreach (QTreeWidgetItem* k, items) { @@ -177,7 +173,7 @@ void CSearchResultView::printItems() { } void CSearchResultView::saveItems() { - CExportManager mgr(tr("Save search result..."), true, tr("Saving search result")); + CExportManager mgr(true, tr("Saving search result")); const CSwordModuleInfo *m = module(); CSwordKey* k = 0; @@ -195,7 +191,7 @@ void CSearchResultView::saveItems() { } void CSearchResultView::saveItemsWithText() { - CExportManager mgr(tr("Save search result..."), true, tr("Saving search result")); + CExportManager mgr(true, tr("Saving search result")); const CSwordModuleInfo *m = module(); CSwordKey* k = 0; @@ -213,7 +209,7 @@ void CSearchResultView::saveItemsWithText() { } void CSearchResultView::copyItems() { - CExportManager mgr(tr("Copy search result..."), true, tr("Copying search result")); + CExportManager mgr(true, tr("Copying search result")); const CSwordModuleInfo *m = module(); CSwordKey* k = 0; @@ -231,7 +227,7 @@ void CSearchResultView::copyItems() { } void CSearchResultView::copyItemsWithText() { - CExportManager mgr(tr("Copy search result..."), true, tr("Copying search result")); + CExportManager mgr(true, tr("Copying search result")); const CSwordModuleInfo *m = module(); CSwordKey* k = 0; diff --git a/src/frontend/searchdialog/csearchresultview.h b/src/frontend/searchdialog/csearchresultview.h index b3a09ee..1d37cbd 100644 --- a/src/frontend/searchdialog/csearchresultview.h +++ b/src/frontend/searchdialog/csearchresultview.h @@ -27,7 +27,6 @@ class CSearchResultView : public QTreeWidget { Q_OBJECT public: CSearchResultView(QWidget* parent); - virtual ~CSearchResultView(); /** \returns the module which is currently used. diff --git a/src/frontend/settingsdialogs/btfontchooserwidget.cpp b/src/frontend/settingsdialogs/btfontchooserwidget.cpp new file mode 100644 index 0000000..4d943c4 --- /dev/null +++ b/src/frontend/settingsdialogs/btfontchooserwidget.cpp @@ -0,0 +1,287 @@ +/********* +* +* This file is part of BibleTime's source code, http://www.bibletime.info/. +* +* Copyright 1999-2011 by the BibleTime developers. +* The BibleTime source code is licensed under the GNU General Public License version 2.0. +* +**********/ + +#include "frontend/settingsdialogs/btfontchooserwidget.h" + +#include <QFontDatabase> +#include <QFrame> +#include <QGridLayout> +#include <QLabel> +#include <QListWidget> +#include <QListWidgetItem> +#include <QWebSettings> +#include <QWebView> +#include "frontend/settingsdialogs/clistwidget.h" + + +namespace { + +class BtFontPreviewWebView: public QWebView { + + public: /* Methods: */ + + inline BtFontPreviewWebView(QWidget *parent = 0) + : QWebView(parent) + { + setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Fixed); + } + + virtual inline QSize sizeHint() const { + return QSize(100, 100); + } + +}; + +const QString DEFAULT_FONT_PREVIEW_TEXT = + "1 In the beginning God created the heaven and the earth. " + "2 And the earth was without form, and void; and darkness was on the face of the deep. " + " And the Spirit of God moved on the face of the waters."; + +} // anonymous namespace + +BtFontChooserWidget::BtFontChooserWidget(QWidget* parent) + : QFrame(parent) + , m_htmlText(DEFAULT_FONT_PREVIEW_TEXT) +{ + setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred); + createLayout(); + connectListWidgets(); + loadFonts(); + setFrameStyle(QFrame::Box); + setFrameShadow(QFrame::Raised); + + retranslateUi(); +} + +void BtFontChooserWidget::createLayout() { + m_fontNameLabel = new QLabel(this); + + m_fontListWidget = new CListWidget(); + m_fontListWidget->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::MinimumExpanding); + m_fontListWidget->setMinimumHeight(50); + + m_fontStyleLabel = new QLabel(this); + + m_styleListWidget = new CListWidget(); + m_styleListWidget->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::MinimumExpanding); + m_styleListWidget->setMinimumHeight(50); + m_styleListWidget->setCharWidth(12); + + m_fontSizeLabel = new QLabel(this); + + m_sizeListWidget = new CListWidget(); + m_sizeListWidget->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::MinimumExpanding); + m_sizeListWidget->setMinimumHeight(50); + m_sizeListWidget->setCharWidth(5); + + m_fontPreview = new BtFontPreviewWebView(this); + + QGridLayout *l = new QGridLayout; + l->addWidget(m_fontNameLabel, 0, 0); + l->addWidget(m_fontListWidget, 1, 0); + l->addWidget(m_fontStyleLabel, 0, 1); + l->addWidget(m_styleListWidget, 1, 1); + l->addWidget(m_fontSizeLabel, 0, 2); + l->addWidget(m_sizeListWidget, 1, 2); + l->addWidget(m_fontPreview, 2, 0, 1, 3); + setLayout(l); +} + +void BtFontChooserWidget::retranslateUi() { + m_fontNameLabel->setText(tr("Font name:")); + m_fontStyleLabel->setText(tr("Font style:")); + m_fontSizeLabel->setText(tr("Size:")); +} + +void BtFontChooserWidget::connectListWidgets() { + bool ok = connect( + m_fontListWidget, + SIGNAL(currentItemChanged(QListWidgetItem *, QListWidgetItem *)), + this, + SLOT(fontChanged(QListWidgetItem *, QListWidgetItem *))); + Q_ASSERT(ok); + + ok = connect( + m_styleListWidget, + SIGNAL(currentItemChanged(QListWidgetItem *, QListWidgetItem *)), + this, + SLOT(styleChanged(QListWidgetItem *, QListWidgetItem *))); + Q_ASSERT(ok); + + ok = connect( + m_sizeListWidget, + SIGNAL(currentItemChanged(QListWidgetItem *, QListWidgetItem *)), + this, + SLOT(sizeChanged(QListWidgetItem *, QListWidgetItem *))); + Q_ASSERT(ok); +} + +void BtFontChooserWidget::fontChanged(QListWidgetItem* current, QListWidgetItem* /*previous*/) { + if (current == 0) + return; + + const QString fontFamily = current->text(); + m_font.setFamily(fontFamily); + loadStyles(fontFamily); + outputHtmlText(); + emit fontSelected(m_font); +} + +void BtFontChooserWidget::loadFonts() { + m_fontListWidget->clear(); + QFontDatabase database; + Q_FOREACH (const QString &font, database.families()) { + m_fontListWidget->addItem(font); + } + // This triggers loading the styles for the first font + m_fontListWidget->setCurrentRow(0); +} + +void BtFontChooserWidget::loadStyles(const QString& font) { + m_styleListWidget->clear(); + QFontDatabase database; + Q_FOREACH (const QString &style, database.styles(font)) { + m_styleListWidget->addItem(style); + // This triggers loading the sizes for the first style + restoreListWidgetValue(m_styleListWidget, m_choosenStyle); + } +} + +void BtFontChooserWidget::loadSizes(const QString& font, const QString& style) { + const QString saveText = saveListWidgetValue(m_sizeListWidget); + + // Put new values into listWidget + m_sizeListWidget->clear(); + QFontDatabase database; + Q_FOREACH (int size, database.pointSizes(font, style)) { + m_sizeListWidget->addItem(QString::number(size)); + } + + restoreListWidgetValue(m_sizeListWidget, saveText); +} + +void BtFontChooserWidget::outputHtmlText() { + m_fontPreview->setHtml( + QString( + "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n" + "<html xmlns=\"http://www.w3.org/1999/xhtml\">" + "<head>" + "<style type=\"text/css\">" + "*{background-color:%1;" + "color:%2;" + "font-family:%3;" + "font-size:%4pt;" + "font-weight:%5;" + "font-style:%6}" + "</style>" + "</head>" + "<body>" + "<div style=\"display: inline;\" lang=\"en\">" + "%7" + "</div>" + "</body>" + "</html>" + ) + .arg(palette().base().color().name()) + .arg(palette().text().color().name()) + .arg(m_font.family()) + .arg(QString::number(m_font.pointSize())) + .arg(m_font.bold() ? "bold" : "normal") + .arg(m_font.italic() ? "italic" : "normal") + .arg(m_htmlText) + ); +} + +void BtFontChooserWidget::restoreListWidgetValue(QListWidget* listWidget, const QString& value) { + if (!value.isEmpty()) { + for (int i = 0; i < listWidget->count(); i++) { + if (listWidget->item(i)->text() == value) { + listWidget->setCurrentRow(i); + return; + } + } + } + listWidget->setCurrentRow(0); +} + +QString BtFontChooserWidget::saveListWidgetValue(QListWidget* listWidget) { + int row = listWidget->currentRow(); + if (row >= 0) + return listWidget->item(row)->text(); + + return QString(); +} + +void BtFontChooserWidget::setFont(const QFont& font) { + disconnect(m_fontListWidget, 0, 0, 0); + disconnect(m_styleListWidget, 0, 0, 0); + disconnect(m_sizeListWidget, 0, 0, 0); + + // set the font + m_font = font; + const QString fontFamily = font.family(); + restoreListWidgetValue(m_fontListWidget, fontFamily); + + // set the style + loadStyles(fontFamily); + QFontDatabase database; + const QString styleString = database.styleString(m_font); + m_choosenStyle = styleString; + restoreListWidgetValue(m_styleListWidget, styleString); + + // set the size + loadSizes(fontFamily, styleString); + restoreListWidgetValue(m_sizeListWidget, QString::number(m_font.pointSize()) ); + + outputHtmlText(); + connectListWidgets(); +} + +void BtFontChooserWidget::setFontStyle(const QString& styleString, QFont* font) { + font->setBold(styleString.contains("bold", Qt::CaseInsensitive)); + font->setItalic(styleString.contains("italic", Qt::CaseInsensitive) + || styleString.contains("oblique", Qt::CaseInsensitive)); +} + +void BtFontChooserWidget::setSampleText(const QString& htmlText) { + m_htmlText = htmlText; + outputHtmlText(); +} + +void BtFontChooserWidget::sizeChanged(QListWidgetItem* current, QListWidgetItem* /*previous*/) { + if (current == 0) + return; + + m_font.setPointSize(m_sizeListWidget->currentItem()->text().toInt()); + + outputHtmlText(); + emit fontSelected(m_font); +} + +QSize BtFontChooserWidget::sizeHint() const { + return QSize(170, 100); +} + +void BtFontChooserWidget::styleChanged(QListWidgetItem* current, QListWidgetItem* /*previous*/) { + if (current == 0) + return; + + QString styleString = current->text(); + setFontStyle(styleString, &m_font); + + // Save style if the user choose it + if (m_styleListWidget->hasFocus()) + m_choosenStyle = styleString; + + loadSizes(m_fontListWidget->currentItem()->text(), styleString); + + outputHtmlText(); + emit fontSelected(m_font); +} diff --git a/src/frontend/settingsdialogs/cfontchooser.h b/src/frontend/settingsdialogs/btfontchooserwidget.h index 0ebed51..9eb1f4d 100644 --- a/src/frontend/settingsdialogs/cfontchooser.h +++ b/src/frontend/settingsdialogs/btfontchooserwidget.h @@ -15,27 +15,35 @@ #include <QWidget> +class QLabel; class CListWidget; class QListWidget; class QListWidgetItem; class QString; -class QVBoxLayout; class QWebView; -class CFontChooser : public QFrame { +class BtFontChooserWidget : public QFrame { + Q_OBJECT - public: - CFontChooser(QWidget *parent = 0); - ~CFontChooser(); - void setFont(const QFont& font); - void setSampleText(const QString& text); - QSize sizeHint() const; + public: /* Methods: */ + + BtFontChooserWidget(QWidget *parent = 0); + + void setFont(const QFont &font); + void setSampleText(const QString &text); + + // Inherited from QWidget: + virtual QSize sizeHint() const; + + signals: + + void fontSelected(const QFont&); + + private: /* Methods: */ - private: - void createFontAreaLayout(); void createLayout(); - void createTextAreaLayout(); + void retranslateUi(); void connectListWidgets(); QString formatAsHtml(const QString& text); void loadFonts(); @@ -45,24 +53,29 @@ class CFontChooser : public QFrame { void restoreListWidgetValue(QListWidget* listWidget, const QString& value); QString saveListWidgetValue(QListWidget* listWidget); - QFrame* m_fontWidget; - QWebView* m_webView; - CListWidget* m_fontListWidget; - CListWidget* m_styleListWidget; - CListWidget* m_sizeListWidget; - QString m_htmlText; - QFont m_font; - QVBoxLayout* m_vBoxLayout; - QString m_choosenStyle; private slots: + void fontChanged(QListWidgetItem* current, QListWidgetItem* previous); void setFontStyle(const QString& styleString, QFont* font); void sizeChanged(QListWidgetItem* current, QListWidgetItem* previous); void styleChanged(QListWidgetItem* current, QListWidgetItem* previous); - signals: - void fontSelected(const QFont&); + private: /* Fields: */ + + QLabel *m_fontNameLabel; + CListWidget *m_fontListWidget; + QLabel *m_fontStyleLabel; + CListWidget *m_styleListWidget; + QLabel *m_fontSizeLabel; + CListWidget *m_sizeListWidget; + + QWebView *m_fontPreview; + + QString m_htmlText; + QFont m_font; + QString m_choosenStyle; + }; #endif diff --git a/src/frontend/settingsdialogs/btfontsettings.cpp b/src/frontend/settingsdialogs/btfontsettings.cpp index 7160e54..77a8b0b 100644 --- a/src/frontend/settingsdialogs/btfontsettings.cpp +++ b/src/frontend/settingsdialogs/btfontsettings.cpp @@ -16,7 +16,8 @@ #include <QLabel> #include <QVBoxLayout> #include <QWidget> -#include "frontend/settingsdialogs/cfontchooser.h" +#include "frontend/settingsdialogs/btfontchooserwidget.h" +#include "frontend/settingsdialogs/cconfigurationdialog.h" #include "util/cresmgr.h" #include "util/tool.h" #include "util/directory.h" @@ -26,18 +27,15 @@ #include <swlocale.h> -BtFontSettingsPage::BtFontSettingsPage(QWidget *parent) - : BtConfigPage(parent) +BtFontSettingsPage::BtFontSettingsPage(CConfigurationDialog *parent) + : BtConfigDialog::Page(util::directory::getIcon(CResMgr::settings::fonts::icon), parent) { namespace DU = util::directory; - m_languageLabel = new QLabel(tr("&Language:"), this); - + m_languageLabel = new QLabel(this); m_languageComboBox = new QComboBox(this); - m_languageComboBox->setToolTip(tr("The font selection below will apply to all texts in this language")); m_languageLabel->setBuddy(m_languageComboBox); - - m_languageCheckBox = new QCheckBox(tr("Use custom font"), this); + m_languageCheckBox = new QCheckBox(this); connect(m_languageCheckBox, SIGNAL(toggled(bool)), this, SLOT(useOwnFontClicked(bool)) ); @@ -49,43 +47,47 @@ BtFontSettingsPage::BtFontSettingsPage(QWidget *parent) hLayout->addWidget(m_languageCheckBox); CLanguageMgr::LangMap langMap = CLanguageMgr::instance()->availableLanguages(); - - for (CLanguageMgr::LangMapIterator it = langMap.constBegin() ; it != langMap.constEnd(); ++it ) { - const QString name = - (*it)->translatedName().isEmpty() - ? (*it)->abbrev() - : (*it)->translatedName(); - - m_fontMap.insert(name, CBTConfig::get(*it) ); + typedef CLanguageMgr::Language L; + for (CLanguageMgr::LangMapIterator it = langMap.constBegin(); + it != langMap.constEnd(); + it++) + { + const L * const l = *it; + const QString &(L::*f)() const = + l->translatedName().isEmpty() + ? &L::abbrev + : &L::translatedName; + + m_fontMap.insert((l->*f)(), CBTConfig::get(l)); } - for ( QMap<QString, CBTConfig::FontSettingsPair>::Iterator it = m_fontMap.begin(); it != m_fontMap.end(); ++it ) { - if ( m_fontMap[it.key()].first ) { //show font icon - m_languageComboBox->addItem(DU::getIcon("fonts.svg"), it.key() ); - } - else { //don't show icon for font - m_languageComboBox->addItem(it.key()); + for (FontMap::ConstIterator it = m_fontMap.constBegin(); it != m_fontMap.constEnd(); ++it) { + const QString &k = it.key(); + if (m_fontMap[k].first) { // show font icon + m_languageComboBox->addItem(DU::getIcon("fonts.svg"), k); + } else { // don't show icon for font + m_languageComboBox->addItem(k); } } /// \todo remember the last selected font and jump there. - m_fontChooser = new CFontChooser(this); - - /// \todo Eeli's wishlist: why not show something relevant here, like a Bible verse in chosen (not tr()'ed!) language? - QString sampleText; - sampleText.append("1 In the beginning God created the heaven and the earth. "); - sampleText.append("2 And the earth was without form, and void; and darkness was on the face of the deep."); - sampleText.append(" And the Spirit of God moved on the face of the waters."); - - m_fontChooser->setSampleText(sampleText); - - connect(m_fontChooser, SIGNAL(fontSelected(const QFont&)), SLOT(newDisplayWindowFontSelected(const QFont&))); - connect(m_languageComboBox, SIGNAL(activated(const QString&)), SLOT(newDisplayWindowFontAreaSelected(const QString&))); - - m_fontChooser->setFont( m_fontMap[m_languageComboBox->currentText()].second ); - useOwnFontClicked( m_fontMap[m_languageComboBox->currentText()].first ); - m_languageCheckBox->setChecked( m_fontMap[m_languageComboBox->currentText()].first ); + m_fontChooser = new BtFontChooserWidget(this); + /** + \todo Eeli's wishlist: why not show something relevant here, like a Bible + verse in chosen (not tr()'ed!) language? + */ + // m_fontChooser->setSampleText("SOMETHING"); + + connect(m_fontChooser, SIGNAL(fontSelected(const QFont&)), + this, SLOT(newDisplayWindowFontSelected(const QFont&))); + connect(m_languageComboBox, SIGNAL(activated(const QString&)), + this, SLOT(newDisplayWindowFontAreaSelected(const QString&))); + + const CBTConfig::FontSettingsPair &v = m_fontMap.value(m_languageComboBox->currentText()); + m_fontChooser->setFont(v.second); + useOwnFontClicked(v.first); + m_languageCheckBox->setChecked(v.first); m_fontChooser->setMinimumSize(m_fontChooser->sizeHint()); QVBoxLayout *fLayout = new QVBoxLayout; @@ -93,24 +95,28 @@ BtFontSettingsPage::BtFontSettingsPage(QWidget *parent) fLayout->addLayout(hLayout); fLayout->addWidget(m_fontChooser); - m_fontsGroupBox = new QGroupBox(tr("Optionally specify a custom font for each language:"), this); + m_fontsGroupBox = new QGroupBox(this); m_fontsGroupBox->setFlat(true); m_fontsGroupBox->setLayout(fLayout); - Q_ASSERT(qobject_cast<QVBoxLayout*>(layout()) != 0); - static_cast<QVBoxLayout*>(layout())->addWidget(m_fontsGroupBox); -} - + QVBoxLayout *mainLayout = new QVBoxLayout(this); + mainLayout->addWidget(m_fontsGroupBox); -BtFontSettingsPage::~BtFontSettingsPage() { + retranslateUi(); } -void BtFontSettingsPage::save() { - for (QMap<QString, CBTConfig::FontSettingsPair>::Iterator it = m_fontMap.begin(); it != m_fontMap.end(); ++it ) { - const CLanguageMgr::Language * const lang = CLanguageMgr::instance()->languageForTranslatedName(it.key()); - if (!lang->isValid()) { //we possibly use a language, for which we have only the abbrev +void BtFontSettingsPage::save() const { + for (FontMap::ConstIterator it = m_fontMap.constBegin(); + it != m_fontMap.constEnd(); + it++) + { + const QString &k = it.key(); + const CLanguageMgr::Language * const lang = CLanguageMgr::instance()->languageForTranslatedName(k); + if (!lang->isValid()) { + // We possibly use a language, for which we have only the abbrevation if (!lang->abbrev().isEmpty()) { - CLanguageMgr::Language l(it.key(), it.key(), it.key()); //create a temp language + // Create a temp language: + CLanguageMgr::Language l(k, k, k); CBTConfig::set(&l, it.value()); } } @@ -120,45 +126,32 @@ void BtFontSettingsPage::save() { } } -/** */ void BtFontSettingsPage::newDisplayWindowFontSelected(const QFont &newFont) { - //belongs to the languages/fonts page - CBTConfig::FontSettingsPair oldSettings = m_fontMap[ m_languageComboBox->currentText() ]; - m_fontMap.insert( m_languageComboBox->currentText(), CBTConfig::FontSettingsPair(oldSettings.first, newFont) ); + const QString languageName = m_languageComboBox->currentText(); + m_fontMap.insert(languageName, + CBTConfig::FontSettingsPair(m_fontMap[languageName].first, newFont)); } -/** Called when the combobox contents is changed */ -void BtFontSettingsPage::newDisplayWindowFontAreaSelected(const QString& usage) { - //belongs to fonts/languages - useOwnFontClicked( m_fontMap[usage].first ); - m_languageCheckBox->setChecked( m_fontMap[usage].first ); - - m_fontChooser->setFont( m_fontMap[usage].second ); +void BtFontSettingsPage::newDisplayWindowFontAreaSelected(const QString &usage) { + const CBTConfig::FontSettingsPair &p = m_fontMap[usage]; + useOwnFontClicked(p.first); + m_languageCheckBox->setChecked(p.first); + m_fontChooser->setFont(p.second); } - -/** This slot is called when the "Use own font for language" bo was clicked. */ void BtFontSettingsPage::useOwnFontClicked(bool isOn) { namespace DU = util::directory; - //belongs to fonts/languages - m_fontChooser->setEnabled(isOn); - m_fontMap[ m_languageComboBox->currentText() ].first = isOn; - - if (isOn) { //show font icon - m_languageComboBox->setItemIcon(m_languageComboBox->currentIndex(), DU::getIcon("fonts.svg")); - } - else { //don't show - m_languageComboBox->setItemText(m_languageComboBox->currentIndex(), m_languageComboBox->currentText() ); /// \todo should this change icon to empty? - } + m_fontMap[m_languageComboBox->currentText()].first = isOn; + m_languageComboBox->setItemIcon(m_languageComboBox->currentIndex(), + isOn ? DU::getIcon("fonts.svg") : QIcon()); } - -const QIcon &BtFontSettingsPage::icon() const { - return util::directory::getIcon(CResMgr::settings::fonts::icon); -} - -QString BtFontSettingsPage::header() const { - return tr("Fonts"); +void BtFontSettingsPage::retranslateUi() { + setHeaderText(tr("Fonts")); + m_languageLabel->setText(tr("&Language:")); + m_languageComboBox->setToolTip(tr("The font selection below will apply to all texts in this language")); + m_languageCheckBox->setText(tr("Use custom font")); + m_fontsGroupBox->setTitle(tr("Optionally specify a custom font for each language:")); } diff --git a/src/frontend/settingsdialogs/btfontsettings.h b/src/frontend/settingsdialogs/btfontsettings.h index 9df4bc5..659cd75 100644 --- a/src/frontend/settingsdialogs/btfontsettings.h +++ b/src/frontend/settingsdialogs/btfontsettings.h @@ -17,26 +17,26 @@ #include "backend/config/cbtconfig.h" -class CFontChooser; +class BtFontChooserWidget; +class CConfigurationDialog; class QCheckBox; class QComboBox; class QGroupBox; +class QLabel; + +class BtFontSettingsPage: public BtConfigDialog::Page { -/** - @author The BibleTime team <info@bibletime.info> -*/ -class BtFontSettingsPage : public BtConfigPage { Q_OBJECT - public: - BtFontSettingsPage(QWidget *parent = 0); - ~BtFontSettingsPage(); - void save(); - /** Reimplemented from BtConfigPage. */ - virtual const QIcon &icon() const; + private: /* Types: */ + + typedef QMap<QString, CBTConfig::FontSettingsPair> FontMap; + + public: /* Methods: */ + + BtFontSettingsPage(CConfigurationDialog *parent = 0); - /** Reimplemented from BtConfigPage. */ - virtual QString header() const; + void save() const; protected slots: @@ -49,14 +49,20 @@ class BtFontSettingsPage : public BtConfigPage { // Called when the combobox contents is changed void newDisplayWindowFontAreaSelected(const QString&); - private: + private: /* Methods: */ + + void retranslateUi(); + + private: /* Fields: */ + QGroupBox *m_fontsGroupBox; QLabel *m_languageLabel; QComboBox *m_languageComboBox; QCheckBox *m_languageCheckBox; - CFontChooser* m_fontChooser; + BtFontChooserWidget* m_fontChooser; + + FontMap m_fontMap; - QMap<QString, CBTConfig::FontSettingsPair> m_fontMap; }; #endif diff --git a/src/frontend/settingsdialogs/btlanguagesettings.cpp b/src/frontend/settingsdialogs/btlanguagesettings.cpp index dc31d0b..fdbe653 100644 --- a/src/frontend/settingsdialogs/btlanguagesettings.cpp +++ b/src/frontend/settingsdialogs/btlanguagesettings.cpp @@ -10,11 +10,12 @@ #include "frontend/settingsdialogs/btlanguagesettings.h" #include <QComboBox> -#include <QHBoxLayout> +#include <QFormLayout> #include <QLabel> #include <QVBoxLayout> #include <QWidget> - +#include "backend/config/cbtconfig.h" +#include "frontend/settingsdialogs/cconfigurationdialog.h" #include "util/cresmgr.h" #include "util/tool.h" #include "util/directory.h" @@ -24,122 +25,112 @@ #include <swlocale.h> -BtLanguageSettingsPage::BtLanguageSettingsPage(QWidget *parent) - : BtConfigPage(parent) -{ - namespace DU = util::directory; +typedef std::list<sword::SWBuf>::const_iterator SBLCI; - Q_ASSERT(qobject_cast<QVBoxLayout*>(layout()) != 0); - QVBoxLayout *mainLayout = static_cast<QVBoxLayout*>(layout()); - //Sword locales +BtLanguageSettingsPage::BtLanguageSettingsPage(CConfigurationDialog *parent) + : BtConfigDialog::Page(util::directory::getIcon(CResMgr::settings::languages::icon), parent) +{ m_swordLocaleCombo = new QComboBox(this); - QLabel* label = new QLabel( tr("Language for names of Bible books:"), this); - label->setBuddy(m_swordLocaleCombo); - m_swordLocaleCombo->setToolTip(tr("The languages which can be used for the biblical booknames")); - - - QHBoxLayout* hBoxLayout = new QHBoxLayout(); - hBoxLayout->addWidget(label); - hBoxLayout->addWidget(m_swordLocaleCombo); - hBoxLayout->addStretch(); - mainLayout->addLayout(hBoxLayout); - - mainLayout->addSpacerItem(new QSpacerItem(1,1, QSizePolicy::Fixed, QSizePolicy::Expanding)); - - QStringList languageNames; - languageNames.append(CLanguageMgr::instance()->languageForAbbrev("en_US")->translatedName()); + m_languageNamesLabel = new QLabel(this); + m_languageNamesLabel->setBuddy(m_swordLocaleCombo); - std::list<sword::SWBuf> locales = sword::LocaleMgr::getSystemLocaleMgr()->getAvailableLocales(); - for (std::list<sword::SWBuf>::const_iterator it = locales.begin(); it != locales.end(); it++) { - // qWarning("working on %s", (*it).c_str()); - const CLanguageMgr::Language * const l = - CLanguageMgr::instance()->languageForAbbrev( sword::LocaleMgr::getSystemLocaleMgr()->getLocale((*it).c_str())->getName() ); + QFormLayout * formLayout = new QFormLayout(this); + formLayout->addRow(m_languageNamesLabel, m_swordLocaleCombo); - if (l->isValid()) { - languageNames.append( l->translatedName() ); - } - else { - languageNames.append( - sword::LocaleMgr::getSystemLocaleMgr()->getLocale((*it).c_str())->getDescription() - ); - } - } //for + retranslateUi(); - languageNames.sort(); - m_swordLocaleCombo->addItems( languageNames ); + initSwordLocaleCombo(); +} - const CLanguageMgr::Language * const l = - CLanguageMgr::instance()->languageForAbbrev( CBTConfig::get(CBTConfig::language) ); +void BtLanguageSettingsPage::save() { + CBTConfig::set(CBTConfig::language, m_swordLocaleCombo->itemData(m_swordLocaleCombo->currentIndex()).toString()); +} - QString currentLanguageName; - if ( l->isValid() && languageNames.contains(l->translatedName()) ) { //tranlated language name is in the box - currentLanguageName = l->translatedName(); - } - else { //a language like "German Abbrevs" might be the language to set - sword::SWLocale* locale = - sword::LocaleMgr::getSystemLocaleMgr()->getLocale( CBTConfig::get(CBTConfig::language).toLocal8Bit() ); - if (locale) { - currentLanguageName = QString::fromLatin1(locale->getDescription()); +void BtLanguageSettingsPage::resetLanguage() { + QVector<QString> atv = bookNameAbbreviationsTryVector(); + + QString best = "en_US"; + Q_ASSERT(atv.contains(best)); + int i = atv.indexOf(best); + if (i > 0) { + atv.resize(i); + const std::list<sword::SWBuf> locales = sword::LocaleMgr::getSystemLocaleMgr()->getAvailableLocales(); + for (SBLCI it = locales.begin(); it != locales.end(); ++it) { + const char * abbr = sword::LocaleMgr::getSystemLocaleMgr()->getLocale((*it).c_str())->getName(); + i = atv.indexOf(abbr); + if (i >= 0) { + best = abbr; + if (i == 0) + break; + atv.resize(i); + } } } + CBTConfig::set(CBTConfig::language, best); +} - if (currentLanguageName.isEmpty()) { // set english as default if nothing was chosen - Q_ASSERT(CLanguageMgr::instance()->languageForAbbrev("en_US")); - currentLanguageName = CLanguageMgr::instance()->languageForAbbrev("en_US")->translatedName(); +QVector<QString> BtLanguageSettingsPage::bookNameAbbreviationsTryVector() { + QVector<QString> atv; + atv.reserve(4); + { + QString settingsLanguage = CBTConfig::get(CBTConfig::language); + if (!settingsLanguage.isEmpty()) + atv.append(settingsLanguage); } - - //now set the item with the right name as current item - for (int i = 0; i < m_swordLocaleCombo->count(); ++i) { - if (currentLanguageName == m_swordLocaleCombo->itemText(i)) { - m_swordLocaleCombo->setCurrentIndex(i); - break; //item found, finish the loop + { + const QString localeLanguageAndCountry = QLocale::system().name(); + if (!localeLanguageAndCountry.isEmpty()) { + atv.append(localeLanguageAndCountry); + int i = localeLanguageAndCountry.indexOf('_'); + if (i > 0) + atv.append(localeLanguageAndCountry.left(i)); } } - -} - - -BtLanguageSettingsPage::~BtLanguageSettingsPage() { + Q_ASSERT(CLanguageMgr::instance()->languageForAbbrev("en_US")); + atv.append("en_US"); + return atv; } -void BtLanguageSettingsPage::save() { +void BtLanguageSettingsPage::initSwordLocaleCombo() { + typedef QMap<QString, QString>::const_iterator SSMCI; - QString languageAbbrev; + QMap<QString, QString> languageNames; + Q_ASSERT(CLanguageMgr::instance()->languageForAbbrev("en_US")); + languageNames.insert(CLanguageMgr::instance()->languageForAbbrev("en_US")->translatedName(), "en_US"); - const QString currentLanguageName = m_swordLocaleCombo->currentText(); - const CLanguageMgr::Language * const l = CLanguageMgr::instance()->languageForTranslatedName( currentLanguageName ); + const std::list<sword::SWBuf> locales = sword::LocaleMgr::getSystemLocaleMgr()->getAvailableLocales(); + for (SBLCI it = locales.begin(); it != locales.end(); ++it) { + const char * abbreviation = sword::LocaleMgr::getSystemLocaleMgr()->getLocale((*it).c_str())->getName(); + const CLanguageMgr::Language * const l = CLanguageMgr::instance()->languageForAbbrev(abbreviation); - if (l && l->isValid()) { - languageAbbrev = l->abbrev(); + if (l->isValid()) { + languageNames.insert(l->translatedName(), abbreviation); + } else { + languageNames.insert( + sword::LocaleMgr::getSystemLocaleMgr()->getLocale((*it).c_str())->getDescription(), + abbreviation); + } } - else { //it can be the lang abbrev like de_abbrev or the Sword description - std::list <sword::SWBuf> locales = sword::LocaleMgr::getSystemLocaleMgr()->getAvailableLocales(); - - for (std::list <sword::SWBuf>::iterator it = locales.begin(); it != locales.end(); it++) { - sword::SWLocale* locale = sword::LocaleMgr::getSystemLocaleMgr()->getLocale((*it).c_str()); - Q_ASSERT(locale); - if ( locale && (QString::fromLatin1(locale->getDescription()) == currentLanguageName) ) { - languageAbbrev = QString::fromLatin1(locale->getName()); //we found the abbrevation for the current language - break; + int index = 0; + QVector<QString> atv = bookNameAbbreviationsTryVector(); + for (SSMCI it = languageNames.constBegin(); it != languageNames.constEnd(); ++it) { + if (!atv.isEmpty()) { + int i = atv.indexOf(it.value()); + if (i >= 0) { + atv.resize(i); + index = m_swordLocaleCombo->count(); } } - - if (languageAbbrev.isEmpty()) { - languageAbbrev = currentLanguageName; //probably a non-standard locale name like de_abbrev - } - } - - if (!languageAbbrev.isEmpty()) { - CBTConfig::set(CBTConfig::language, languageAbbrev); + m_swordLocaleCombo->addItem(it.key(), it.value()); } + m_swordLocaleCombo->setCurrentIndex(index); } -const QIcon &BtLanguageSettingsPage::icon() const { - return util::directory::getIcon(CResMgr::settings::languages::icon); -} +void BtLanguageSettingsPage::retranslateUi() { + setHeaderText(tr("Languages")); -QString BtLanguageSettingsPage::header() const { - return tr("Languages"); + m_languageNamesLabel->setText(tr("Language for names of Bible books:")); + m_swordLocaleCombo->setToolTip(tr("The languages which can be used for the biblical booknames")); } diff --git a/src/frontend/settingsdialogs/btlanguagesettings.h b/src/frontend/settingsdialogs/btlanguagesettings.h index 911e466..7c3b0c9 100644 --- a/src/frontend/settingsdialogs/btlanguagesettings.h +++ b/src/frontend/settingsdialogs/btlanguagesettings.h @@ -14,47 +14,35 @@ #include <QMap> #include <QWidget> -#include "backend/config/cbtconfig.h" -//class CFontChooser; -//class QCheckBox; +class CConfigurationDialog; class QComboBox; +class QLabel; + +class BtLanguageSettingsPage: public BtConfigDialog::Page { -/** - @author The BibleTime team <info@bibletime.info> -*/ -class BtLanguageSettingsPage : public BtConfigPage { Q_OBJECT - public: - BtLanguageSettingsPage(QWidget *parent = 0); - ~BtLanguageSettingsPage(); - void save(); - /** Reimplemented from BtConfigPage. */ - virtual const QIcon &icon() const; + public: /* Methods: */ - /** Reimplemented from BtConfigPage. */ - virtual QString header() const; + BtLanguageSettingsPage(CConfigurationDialog *parent = 0); + + void save(); - protected slots: + static void resetLanguage(); - // This slot is called when the "Use own font for language" button was clicked. - //void useOwnFontClicked(bool); + private: /* Methods: */ - // Called when a new font in the fonts page was selected. - //void newDisplayWindowFontSelected(const QFont &); + static QVector<QString> bookNameAbbreviationsTryVector(); + void initSwordLocaleCombo(); + void retranslateUi(); - // Called when the combobox contents is changed - //void newDisplayWindowFontAreaSelected(const QString&); + private: /* Fields: */ - private: + QLabel *m_languageNamesLabel; QComboBox* m_swordLocaleCombo; - //QComboBox* m_usageCombo; - //QCheckBox* m_useOwnFontCheck; - //CFontChooser* m_fontChooser; - //QMap<QString, CBTConfig::FontSettingsPair> m_fontMap; }; #endif diff --git a/src/frontend/settingsdialogs/cacceleratorsettings.cpp b/src/frontend/settingsdialogs/cacceleratorsettings.cpp index 15394fb..177ea2f 100644 --- a/src/frontend/settingsdialogs/cacceleratorsettings.cpp +++ b/src/frontend/settingsdialogs/cacceleratorsettings.cpp @@ -25,21 +25,21 @@ #include "frontend/displaywindow/ccommentaryreadwindow.h" #include "frontend/displaywindow/clexiconreadwindow.h" #include "frontend/displaywindow/creadwindow.h" +#include "frontend/settingsdialogs/cconfigurationdialog.h" #include "util/cresmgr.h" #include "util/directory.h" -CAcceleratorSettingsPage::CAcceleratorSettingsPage(QWidget *parent) - : BtConfigPage(parent) +CAcceleratorSettingsPage::CAcceleratorSettingsPage(CConfigurationDialog *parent) + : BtConfigDialog::Page(util::directory::getIcon(CResMgr::settings::keys::icon), parent) { - Q_ASSERT(qobject_cast<QVBoxLayout*>(layout()) != 0); - QVBoxLayout *mainLayout = static_cast<QVBoxLayout*>(layout()); + QVBoxLayout *mainLayout = new QVBoxLayout(this); QHBoxLayout* layoutForWindowTypeChooser = new QHBoxLayout(); mainLayout->addLayout(layoutForWindowTypeChooser); - QLabel* label = new QLabel(tr("Choose action group:"), this); - layoutForWindowTypeChooser->addWidget(label); + m_actionGroupLabel = new QLabel(this); + layoutForWindowTypeChooser->addWidget(m_actionGroupLabel); m_typeChooser = new QComboBox(this); layoutForWindowTypeChooser->addWidget(m_typeChooser); @@ -50,13 +50,6 @@ CAcceleratorSettingsPage::CAcceleratorSettingsPage(QWidget *parent) m_keyChooserStack = new QStackedWidget(this); - m_application.title = tr("Main Window"); - m_general = WindowType(tr("All text windows")); - m_bible = WindowType(tr("Bible windows")); - m_commentary = WindowType(tr("Commentary windows")); - m_lexicon = WindowType(tr("Lexicon windows")); - m_book = WindowType(tr("Book windows")); - m_typeChooser->addItem(m_application.title); m_typeChooser->addItem(m_general.title); m_typeChooser->addItem(m_bible.title); @@ -130,10 +123,29 @@ CAcceleratorSettingsPage::CAcceleratorSettingsPage(QWidget *parent) slotKeyChooserTypeChanged(m_application.title); m_typeChooser->setFocus(Qt::MouseFocusReason); - qDebug() << "CAcceleratorSettingsPage::CAcceleratorSettingsPage end"; + + retranslateUi(); } -CAcceleratorSettingsPage::~CAcceleratorSettingsPage() { +void CAcceleratorSettingsPage::retranslateUi() { + setHeaderText(tr("Shortcuts")); + + m_actionGroupLabel->setText(tr("Choose action group:")); + + m_application.title = tr("Main Window"); + m_general.title = tr("All text windows"); + m_bible.title = tr("Bible windows"); + m_commentary.title = tr("Commentary windows"); + m_lexicon.title = tr("Lexicon windows"); + m_book.title = tr("Book windows"); + + m_typeChooser->clear(); + m_typeChooser->addItem(m_application.title); + m_typeChooser->addItem(m_general.title); + m_typeChooser->addItem(m_bible.title); + m_typeChooser->addItem(m_commentary.title); + m_typeChooser->addItem(m_lexicon.title); + m_typeChooser->addItem(m_book.title); } // complete the keyChangeRequest @@ -247,11 +259,3 @@ void CAcceleratorSettingsPage::slotKeyChooserTypeChanged(const QString& title) { m_keyChooserStack->setCurrentIndex(index); } - -const QIcon &CAcceleratorSettingsPage::icon() const { - return util::directory::getIcon(CResMgr::settings::keys::icon); -} - -QString CAcceleratorSettingsPage::header() const { - return tr("Shortcuts"); -} diff --git a/src/frontend/settingsdialogs/cacceleratorsettings.h b/src/frontend/settingsdialogs/cacceleratorsettings.h index 999e3d0..1bd4173 100644 --- a/src/frontend/settingsdialogs/cacceleratorsettings.h +++ b/src/frontend/settingsdialogs/cacceleratorsettings.h @@ -19,24 +19,28 @@ class BtActionCollection; class BtShortcutsEditor; +class CConfigurationDialog; class QComboBox; +class QLabel; class QStackedWidget; /** - @author The BibleTime team <info@bibletime.info> -*/ -class CAcceleratorSettingsPage : public BtConfigPage { + * @brief The shortcut settings page. + * @author The BibleTime team <info@bibletime.info> + */ +class CAcceleratorSettingsPage: public BtConfigDialog::Page { + Q_OBJECT - public: - CAcceleratorSettingsPage(QWidget *parent = 0); - ~CAcceleratorSettingsPage(); + + public: /* Methods: */ + + CAcceleratorSettingsPage(CConfigurationDialog *parent = 0); + void save(); - /** Reimplemented from BtConfigPage. */ - virtual const QIcon &icon() const; + protected: /* Methods: */ - /** Reimplemented from BtConfigPage. */ - virtual QString header() const; + void retranslateUi(); protected slots: @@ -74,6 +78,7 @@ class CAcceleratorSettingsPage : public BtConfigPage { WindowType m_lexicon; WindowType m_book; + QLabel *m_actionGroupLabel; QComboBox* m_typeChooser; QStackedWidget* m_keyChooserStack; diff --git a/src/frontend/settingsdialogs/cconfigurationdialog.cpp b/src/frontend/settingsdialogs/cconfigurationdialog.cpp index e1d68ca..4c5bf1b 100644 --- a/src/frontend/settingsdialogs/cconfigurationdialog.cpp +++ b/src/frontend/settingsdialogs/cconfigurationdialog.cpp @@ -62,13 +62,13 @@ CConfigurationDialog::CConfigurationDialog(QWidget * parent, BtActionCollection* m_bbox->addButton(QDialogButtonBox::Apply); m_bbox->addButton(QDialogButtonBox::Cancel); util::prepareDialogBox(m_bbox); - addButtonBox(m_bbox); + setButtonBox(m_bbox); bool ok = connect(m_bbox, SIGNAL(clicked(QAbstractButton *)), SLOT(slotButtonClicked(QAbstractButton *))); Q_ASSERT(ok); loadDialogSettings(); - slotChangePage(0); + setCurrentPage(0); } CConfigurationDialog::~CConfigurationDialog() { @@ -103,7 +103,7 @@ void CConfigurationDialog::loadDialogSettings() { move(CBTConfig::get(CBTConfig::configDialogPosX), CBTConfig::get(CBTConfig::configDialogPosY)); } -void CConfigurationDialog::saveDialogSettings() { +void CConfigurationDialog::saveDialogSettings() const { CBTConfig::set(CBTConfig::configDialogWidth, size().width()); CBTConfig::set(CBTConfig::configDialogHeight, size().height()); CBTConfig::set(CBTConfig::configDialogPosX, x()); diff --git a/src/frontend/settingsdialogs/cconfigurationdialog.h b/src/frontend/settingsdialogs/cconfigurationdialog.h index e0fbf93..d38b4e4 100644 --- a/src/frontend/settingsdialogs/cconfigurationdialog.h +++ b/src/frontend/settingsdialogs/cconfigurationdialog.h @@ -46,7 +46,7 @@ class CConfigurationDialog : public BtConfigDialog { void loadDialogSettings(); // Save the settings to the resource file - void saveDialogSettings(); + void saveDialogSettings() const; signals: void signalSettingsChanged(); diff --git a/src/frontend/settingsdialogs/cdisplaysettings.cpp b/src/frontend/settingsdialogs/cdisplaysettings.cpp index dd390a6..6af4547 100644 --- a/src/frontend/settingsdialogs/cdisplaysettings.cpp +++ b/src/frontend/settingsdialogs/cdisplaysettings.cpp @@ -17,6 +17,7 @@ #include "backend/config/cbtconfig.h" #include "backend/managers/cdisplaytemplatemgr.h" #include "backend/rendering/cdisplayrendering.h" +#include "frontend/settingsdialogs/cconfigurationdialog.h" #include "util/cresmgr.h" #include "util/directory.h" #include "util/tool.h" @@ -44,29 +45,20 @@ QSize CWebViewerWidget::sizeHint () const { // ************************ /** Initializes the startup section of the OD. */ -CDisplaySettingsPage::CDisplaySettingsPage(QWidget *parent) - : BtConfigPage(parent) +CDisplaySettingsPage::CDisplaySettingsPage(CConfigurationDialog *parent) + : BtConfigDialog::Page(util::directory::getIcon(CResMgr::settings::startup::icon), parent) { - Q_ASSERT(qobject_cast<QVBoxLayout*>(layout()) != 0); - QVBoxLayout *mainLayout = static_cast<QVBoxLayout*>(layout()); + QVBoxLayout *mainLayout = new QVBoxLayout(this); { //startup logo m_showLogoCheck = new QCheckBox(this); - m_showLogoCheck->setText(tr("Show startup logo")); - m_showLogoCheck->setToolTip(tr("Show the BibleTime logo on startup")); - m_showLogoCheck->setChecked(CBTConfig::get(CBTConfig::logo)); mainLayout->addWidget(m_showLogoCheck); } mainLayout->addSpacing(20); - mainLayout->addWidget( - util::tool::explanationLabel( - this, - tr("Display templates"), - tr("Display templates define how text is displayed.") - ) - ); + m_explanationLabel = new QLabel(this); + mainLayout->addWidget(m_explanationLabel); QHBoxLayout* hboxlayout = new QHBoxLayout(); @@ -74,9 +66,9 @@ CDisplaySettingsPage::CDisplaySettingsPage(QWidget *parent) connect( m_styleChooserCombo, SIGNAL( activated( int ) ), this, SLOT( updateStylePreview() ) ); - QLabel* availableLabel = new QLabel(tr("Available display styles:"), this); - availableLabel->setBuddy(m_styleChooserCombo); - hboxlayout->addWidget(availableLabel); + m_availableLabel = new QLabel(this); + m_availableLabel->setBuddy(m_styleChooserCombo); + hboxlayout->addWidget(m_availableLabel); hboxlayout->addWidget( m_styleChooserCombo ); hboxlayout->addStretch(); mainLayout->addLayout( hboxlayout ); @@ -84,35 +76,50 @@ CDisplaySettingsPage::CDisplaySettingsPage(QWidget *parent) QWidget* webViewWidget = new CWebViewerWidget(this); QLayout* webViewLayout = new QVBoxLayout(webViewWidget); m_stylePreviewViewer = new QWebView(webViewWidget); - QLabel* previewLabel = new QLabel(tr("Style preview"), webViewWidget); - previewLabel->setBuddy(m_stylePreviewViewer); - webViewLayout->addWidget(previewLabel); + m_previewLabel = new QLabel(webViewWidget); + m_previewLabel->setBuddy(m_stylePreviewViewer); + webViewLayout->addWidget(m_previewLabel); webViewLayout->addWidget(m_stylePreviewViewer); webViewWidget->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Expanding); mainLayout->addWidget(webViewWidget); - m_styleChooserCombo->addItems( - CDisplayTemplateMgr::instance()->availableTemplates() - ); + CDisplayTemplateMgr * tMgr = CDisplayTemplateMgr::instance(); + m_styleChooserCombo->addItems(tMgr->availableTemplates()); for (int i = 0; i < m_styleChooserCombo->count(); ++i) { - if ( m_styleChooserCombo->itemText(i) == CBTConfig::get(CBTConfig::displayStyle) ) { - m_styleChooserCombo->setCurrentIndex( i ); + if (m_styleChooserCombo->itemText(i) == CDisplayTemplateMgr::activeTemplateName()) { + m_styleChooserCombo->setCurrentIndex(i); break; } } - updateStylePreview(); //render it + retranslateUi(); // also calls updateStylePreview(); +} + +void CDisplaySettingsPage::retranslateUi() { + setHeaderText(tr("Display")); + + util::tool::initExplanationLabel( + m_explanationLabel, + tr("Display templates"), + tr("Display templates define how text is displayed.") + ); + + m_showLogoCheck->setText(tr("Show startup logo")); + m_showLogoCheck->setToolTip(tr("Show the BibleTime logo on startup")); + + m_availableLabel->setText(tr("Available display styles:")); + m_previewLabel->setText(tr("Style preview")); + + updateStylePreview(); } void CDisplaySettingsPage::updateStylePreview() { //update the style preview widget - qDebug() << "CDisplaySettingsPage::updateStylePreview"; using namespace Rendering; const QString styleName = m_styleChooserCombo->currentText(); - qDebug() << "style name: " << styleName; CTextRendering::KeyTree tree; CTextRendering::KeyTreeItem::Settings settings; @@ -152,34 +159,16 @@ void CDisplaySettingsPage::updateStylePreview() { .arg(tr("But he who does the truth comes to the light, that his works may be revealed, that they have been done in God.")), settings)); - const QString oldStyleName = CBTConfig::get - (CBTConfig::displayStyle); - //qDebug() << "old style name: " << oldStyleName; - CBTConfig::set - (CBTConfig::displayStyle, styleName); - //qDebug() << "new style name: " << CBTConfig::get(CBTConfig::displayStyle); + /// \todo Remove the following hack: + const QString oldStyleName = CDisplayTemplateMgr::activeTemplateName(); + CBTConfig::set(CBTConfig::displayStyle, styleName); CDisplayRendering render; m_stylePreviewViewer->setHtml( render.renderKeyTree(tree)); - CBTConfig::set - (CBTConfig::displayStyle, oldStyleName); - qDebug() << "CDisplaySettingsPage::updateStylePreview end"; + CBTConfig::set(CBTConfig::displayStyle, oldStyleName); } void CDisplaySettingsPage::save() { - CBTConfig::set - ( CBTConfig::logo, m_showLogoCheck->isChecked() ); - CBTConfig::set - ( CBTConfig::displayStyle, m_styleChooserCombo->currentText() ); -} - -// implement the BtConfigPage methods - -const QIcon &CDisplaySettingsPage::icon() const { - return util::directory::getIcon(CResMgr::settings::startup::icon); -} - -QString CDisplaySettingsPage::header() const { - return tr("Display"); + CBTConfig::set(CBTConfig::logo, m_showLogoCheck->isChecked()); + CBTConfig::set(CBTConfig::displayStyle, m_styleChooserCombo->currentText()); } - diff --git a/src/frontend/settingsdialogs/cdisplaysettings.h b/src/frontend/settingsdialogs/cdisplaysettings.h index fe46679..b18a26f 100644 --- a/src/frontend/settingsdialogs/cdisplaysettings.h +++ b/src/frontend/settingsdialogs/cdisplaysettings.h @@ -15,30 +15,39 @@ #include <QWidget> +class CConfigurationDialog; class QCheckBox; class QComboBox; +class QLabel; class QWebView; -class CDisplaySettingsPage : public BtConfigPage { +class CDisplaySettingsPage: public BtConfigDialog::Page { + Q_OBJECT - public: - CDisplaySettingsPage(QWidget *parent = 0); + + public: /* Methods: */ + + CDisplaySettingsPage(CConfigurationDialog *parent = 0); + void save(); - /** Reimplemented from BtConfigPage. */ - virtual const QIcon &icon() const; + protected: /* Methods: */ - /** Reimplemented from BtConfigPage. */ - virtual QString header() const; + void retranslateUi(); protected slots: /** Update the style preview widget. */ void updateStylePreview(); - private: + private: /* Fields: */ + QCheckBox* m_showLogoCheck; + QLabel *m_explanationLabel; QComboBox* m_styleChooserCombo; + QLabel *m_availableLabel; QWebView* m_stylePreviewViewer; + QLabel *m_previewLabel; + }; #endif diff --git a/src/frontend/settingsdialogs/cfontchooser.cpp b/src/frontend/settingsdialogs/cfontchooser.cpp deleted file mode 100644 index 81a8868..0000000 --- a/src/frontend/settingsdialogs/cfontchooser.cpp +++ /dev/null @@ -1,337 +0,0 @@ -/********* -* -* This file is part of BibleTime's source code, http://www.bibletime.info/. -* -* Copyright 1999-2011 by the BibleTime developers. -* The BibleTime source code is licensed under the GNU General Public License version 2.0. -* -**********/ - -#include "frontend/settingsdialogs/cfontchooser.h" - -#include <QWidget> -#include <QFontDatabase> -#include <QFrame> -#include <QLabel> -#include <QListWidget> -#include <QListWidgetItem> -#include <QVBoxLayout> -#include <QWebSettings> -#include <QWebView> -#include "frontend/settingsdialogs/clistwidget.h" - - -// *********************** -// Container for KHTHMView to control its size -class WebViewerWidget : public QWidget { - public: - WebViewerWidget(QWidget* parent = 0); - ~WebViewerWidget(); - virtual QSize sizeHint () const; -}; - -WebViewerWidget::WebViewerWidget(QWidget* parent) - : QWidget(parent) { -} - -WebViewerWidget::~WebViewerWidget() { -} - -QSize WebViewerWidget::sizeHint () const { - return QSize(100, 100); -} -// ************************ - - - -CFontChooser::CFontChooser(QWidget* parent) - : QFrame(parent), m_fontWidget(0), - m_fontListWidget(0), m_styleListWidget(0), m_sizeListWidget(0) { - setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred); - createLayout(); - connectListWidgets(); - loadFonts(); - setFrameStyle(QFrame::Box); - setFrameShadow(QFrame::Raised); -} - - -CFontChooser::~CFontChooser() { -} - - -void CFontChooser::createFontAreaLayout() { - QHBoxLayout* fontStyleSizeHBoxLayout = new QHBoxLayout(); - - // font column - QVBoxLayout* fontLayout = new QVBoxLayout(); - fontStyleSizeHBoxLayout->addLayout(fontLayout); - - QLabel* fontLabel = new QLabel(tr("Font name:")); - fontLayout->addWidget(fontLabel); - - m_fontListWidget = new CListWidget(); - m_fontListWidget->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::MinimumExpanding); - m_fontListWidget->setMinimumHeight(50); - fontLayout->addWidget(m_fontListWidget); - - // style column - QVBoxLayout* styleLayout = new QVBoxLayout(); - fontStyleSizeHBoxLayout->addLayout(styleLayout); - - QLabel* styleLabel = new QLabel(tr("Font style:")); - styleLayout->addWidget(styleLabel); - - m_styleListWidget = new CListWidget(); - m_styleListWidget->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::MinimumExpanding); - m_styleListWidget->setMinimumHeight(50); - m_styleListWidget->setCharWidth(12); - styleLayout->addWidget(m_styleListWidget); - - // size column - QVBoxLayout* sizeLayout = new QVBoxLayout(); - fontStyleSizeHBoxLayout->addLayout(sizeLayout); - - QLabel* sizeLabel = new QLabel(tr("Size:")); - sizeLayout->addWidget(sizeLabel); - - m_sizeListWidget = new CListWidget(); - m_sizeListWidget->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::MinimumExpanding); - m_sizeListWidget->setMinimumHeight(50); - m_sizeListWidget->setCharWidth(5); - sizeLayout->addWidget(m_sizeListWidget); - - m_vBoxLayout->addLayout(fontStyleSizeHBoxLayout); -} - - -void CFontChooser::createLayout() { - m_vBoxLayout = new QVBoxLayout(this); - createFontAreaLayout(); - createTextAreaLayout(); -} - - -void CFontChooser::createTextAreaLayout() { - QWidget* webViewWidget = new WebViewerWidget(this); - QLayout* webViewLayout = new QVBoxLayout(webViewWidget); - - webViewWidget->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Fixed); - - m_webView = new QWebView(webViewWidget); - webViewLayout->addWidget(m_webView); - m_vBoxLayout->addWidget(webViewWidget); -} - - -void CFontChooser::connectListWidgets() { - - bool ok = connect( - m_fontListWidget, - SIGNAL(currentItemChanged(QListWidgetItem *, QListWidgetItem *)), - this, - SLOT(fontChanged(QListWidgetItem *, QListWidgetItem *))); - Q_ASSERT(ok); - - ok = connect( - m_styleListWidget, - SIGNAL(currentItemChanged(QListWidgetItem *, QListWidgetItem *)), - this, - SLOT(styleChanged(QListWidgetItem *, QListWidgetItem *))); - Q_ASSERT(ok); - - ok = connect( - m_sizeListWidget, - SIGNAL(currentItemChanged(QListWidgetItem *, QListWidgetItem *)), - this, - SLOT(sizeChanged(QListWidgetItem *, QListWidgetItem *))); - Q_ASSERT(ok); -} - - -void CFontChooser::fontChanged(QListWidgetItem* current, QListWidgetItem* /*previous*/) { - if (current == 0) - return; - QString fontFamily = current->text(); - m_font.setFamily(fontFamily); - loadStyles(fontFamily); - outputHtmlText(); - emit fontSelected(m_font); -} - - -QString CFontChooser::formatAsHtml(const QString& text) { - - QString htmlText; - htmlText.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"); - htmlText.append("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n"); - htmlText.append("<html xmlns=\"http://www.w3.org/1999/xhtml\">\n"); - htmlText.append("<head>\n"); - htmlText.append(" <style type=\"text/css\">\n"); - htmlText.append(" *[lang=en] { font-family:#FONT-FAMILY#; font-size:#FONT-SIZE#pt; font-weight:#FONT-WEIGHT#; font-style:#FONT-STYLE#; }\n"); - htmlText.append(" </style>\n"); - htmlText.append("</head>\n"); - htmlText.append("<body>\n"); - htmlText.append(" <div>\n"); - htmlText.append(" <div style=\"display: inline;\" lang=\"en\">\n"); - htmlText.append(text); - htmlText.append(" </div>\n"); - htmlText.append("</body>\n"); - htmlText.append("</html>\n"); - return htmlText; -} - - -void CFontChooser::loadFonts() { - m_fontListWidget->clear(); - QFontDatabase database; - foreach (QString font, database.families()) { - m_fontListWidget->addItem(font); - } - // This triggers loading the styles for the first font - m_fontListWidget->setCurrentRow(0); -} - - -void CFontChooser::loadStyles(const QString& font) { - m_styleListWidget->clear(); - QFontDatabase database; - foreach (QString style, database.styles(font)) { - m_styleListWidget->addItem(style); - // This triggers loading the sizes for the first style - restoreListWidgetValue(m_styleListWidget, m_choosenStyle); - } -} - - -void CFontChooser::loadSizes(const QString& font, const QString& style) { - - QString saveText = saveListWidgetValue(m_sizeListWidget); - - // Put new values into listWidget - m_sizeListWidget->clear(); - QFontDatabase database; - foreach (int size, database.pointSizes(font, style)) { - m_sizeListWidget->addItem(QString::number(size)); - } - - restoreListWidgetValue(m_sizeListWidget, saveText); -} - - -void CFontChooser::outputHtmlText() { - QString text = formatAsHtml(m_htmlText); - text.replace("#FONT-FAMILY#", m_font.family()); - text.replace("#FONT-SIZE#", QString::number(m_font.pointSize())); - text.replace("#FONT-WEIGHT#", (m_font.bold() ? "bold" : "normal") ); - text.replace("#FONT-STYLE#", m_font.italic() ? "italic" : "normal"); - m_webView->setHtml(text); -} - - -void CFontChooser::restoreListWidgetValue(QListWidget* listWidget, const QString& value) { - if (value == "") { - listWidget->setCurrentRow(0); - return; - } - - for (int i = 0; i < listWidget->count(); i++) { - if (listWidget->item(i)->text() == value) { - listWidget->setCurrentRow(i); - return; - } - } - listWidget->setCurrentRow(0); -} - - -QString CFontChooser::saveListWidgetValue(QListWidget* listWidget) { - QString saveText; - int row = listWidget->currentRow(); - if (row >= 0) { - saveText = listWidget->item(row)->text(); - } - return saveText; -} - - -void CFontChooser::setFont(const QFont& font) { - disconnect(m_fontListWidget, 0, 0, 0); - disconnect(m_styleListWidget, 0, 0, 0); - disconnect(m_sizeListWidget, 0, 0, 0); - - // set the font - m_font = font; - restoreListWidgetValue(m_fontListWidget, m_font.family()); - - // set the style - loadStyles( m_font.family()); - QFontDatabase database; - QString styleString = database.styleString(m_font); - m_choosenStyle = styleString; - restoreListWidgetValue(m_styleListWidget, styleString); - - // set the size - loadSizes(m_font.family(), styleString); - restoreListWidgetValue(m_sizeListWidget, QString::number(m_font.pointSize()) ); - - outputHtmlText(); - connectListWidgets(); -} - - -void CFontChooser::setFontStyle(const QString& styleString, QFont* font) { - if (styleString.contains("bold", Qt::CaseInsensitive)) - font->setBold(true); - else - font->setBold(false); - - if (styleString.contains("italic", Qt::CaseInsensitive) || styleString.contains("oblique", Qt::CaseInsensitive) ) - font->setItalic(true); - else - font->setItalic(false); -} - - -void CFontChooser::setSampleText(const QString& htmlText) { - m_htmlText = htmlText; - outputHtmlText(); -} - - -void CFontChooser::sizeChanged(QListWidgetItem* current, QListWidgetItem* /*previous*/) { - if (current == 0) - return; - - QString size = m_sizeListWidget->currentItem()->text(); - m_font.setPointSize(size.toInt()); - - outputHtmlText(); - emit fontSelected(m_font); -} - - -QSize CFontChooser::sizeHint() const { - return QSize(170, 100); -} - -void CFontChooser::styleChanged(QListWidgetItem* current, QListWidgetItem* /*previous*/) { - if (current == 0) - return; - - QString styleString = current->text(); - setFontStyle(styleString, &m_font); - - // Save style if the user choose it - bool focus = m_styleListWidget->hasFocus(); - if (focus) - m_choosenStyle = styleString; - - QString font = m_fontListWidget->currentItem()->text(); - loadSizes(font, styleString); - - outputHtmlText(); - emit fontSelected(m_font); -} - - diff --git a/src/frontend/settingsdialogs/cswordsettings.cpp b/src/frontend/settingsdialogs/cswordsettings.cpp index 39e48e8..42c3833 100644 --- a/src/frontend/settingsdialogs/cswordsettings.cpp +++ b/src/frontend/settingsdialogs/cswordsettings.cpp @@ -11,7 +11,7 @@ #include <QCheckBox> #include <QComboBox> -#include <QGridLayout> +#include <QFormLayout> #include <QLabel> #include <QList> #include <QString> @@ -20,127 +20,81 @@ #include <QVBoxLayout> #include <QWidget> #include "backend/config/cbtconfig.h" +#include "frontend/settingsdialogs/cconfigurationdialog.h" #include "util/cresmgr.h" #include "util/directory.h" #include "util/tool.h" -CSwordSettingsPage::CSwordSettingsPage(QWidget *parent) - : BtConfigPage(parent) -{ - Q_ASSERT(qobject_cast<QVBoxLayout*>(layout()) != 0); - QVBoxLayout *vbox = static_cast<QVBoxLayout*>(layout()); - - QTabWidget* tabWidget = new QTabWidget(); - vbox->addWidget(tabWidget); - - m_worksTab = new StandardWorksTab(); - m_filtersTab = new TextFiltersTab(); - tabWidget->addTab(m_worksTab, tr("Standard works")); - tabWidget->addTab(m_filtersTab, tr("Text filters")); -} - -//Standard works tab - -StandardWorksTab::StandardWorksTab() - : QWidget(0) { - typedef QList<CSwordModuleInfo*>::const_iterator MLCI; - - // move: tabCtl->addTab(currentTab, tr("Standard works")); - QGridLayout* gridLayout = new QGridLayout(this); //the last row is for stretching available space - gridLayout->setSizeConstraint(QLayout::SetMinimumSize); - - gridLayout->addWidget( - util::tool::explanationLabel( - this, "", - tr("Standard works are used when no particular work is specified, for example " - "when a hyperlink into a Bible or lexicon was clicked.")), - 0, 0, 1, 2 /*fill the horizontal space*/ - ); - - //Create selection boxes - - m_standardBibleCombo = new QComboBox(this); - QLabel* label = new QLabel( tr("Bible:"), this); - label->setAlignment(Qt::AlignRight); - label->setBuddy(m_standardBibleCombo); - ////label->setAutoResize(true); //? not found in docs - m_standardBibleCombo->setToolTip(tr("The standard Bible is used when a hyperlink into a Bible is clicked")); - - gridLayout->addWidget(label, 1, 0); - gridLayout->addWidget(m_standardBibleCombo, 1, 1); - - m_standardCommentaryCombo = new QComboBox(this); - label = new QLabel( tr("Commentary:"), this); - label->setAlignment(Qt::AlignRight); - label->setBuddy(m_standardCommentaryCombo); - //label->setAutoResize(true); - m_standardCommentaryCombo->setToolTip(tr("The standard commentary is used when a hyperlink into a commentary is clicked")); - - gridLayout->addWidget(label, 2, 0); - gridLayout->addWidget(m_standardCommentaryCombo, 2, 1); - - m_standardLexiconCombo = new QComboBox(this); - label = new QLabel(tr("Lexicon:"), this); - label->setAlignment(Qt::AlignRight); - label->setBuddy(m_standardLexiconCombo); - //label->setAutoResize(true); - m_standardLexiconCombo->setToolTip(tr("The standard lexicon is used when a hyperlink into a lexicon is clicked")); +/******************************************************************************* + StandardWorksTab +*******************************************************************************/ - gridLayout->addWidget(label, 3, 0); - gridLayout->addWidget(m_standardLexiconCombo, 3, 1); +class StandardWorksTab: public QWidget { - m_standardDailyDevotionalCombo = new QComboBox(this); - label = new QLabel(tr("Daily devotional:"), this); - label->setAlignment(Qt::AlignRight); - label->setBuddy(m_standardDailyDevotionalCombo); - //label->setAutoResize(true); - m_standardDailyDevotionalCombo->setToolTip(tr("The standard devotional will be used to display a short start up devotional")); + public: /* Methods: */ - gridLayout->addWidget(label, 4, 0); - gridLayout->addWidget(m_standardDailyDevotionalCombo, 4, 1); + StandardWorksTab(CSwordSettingsPage *parent); - m_standardHebrewStrongCombo = new QComboBox(this); - label = new QLabel(tr("Hebrew Strong's lexicon:"), this); - label->setAlignment(Qt::AlignRight); - label->setBuddy(m_standardHebrewStrongCombo); - //label->setAutoResize(true); - m_standardHebrewStrongCombo->setToolTip(tr("The standard Hebrew lexicon is used when a hyperlink into a Hebrew lexicon is clicked")); + void save(); - gridLayout->addWidget(label, 5, 0); - gridLayout->addWidget(m_standardHebrewStrongCombo, 5, 1); + protected: /* Methods: */ - m_standardGreekStrongCombo = new QComboBox(this); - label = new QLabel(tr("Greek Strong's lexicon:"), this); - label->setAlignment(Qt::AlignRight); - label->setBuddy(m_standardGreekStrongCombo); - //label->setAutoResize(true); - m_standardGreekStrongCombo->setToolTip(tr("The standard Greek lexicon is used when a hyperlink into a Greek lexicon is clicked")); + void retranslateUi(); - gridLayout->addWidget(label, 6, 0); - gridLayout->addWidget(m_standardGreekStrongCombo, 6, 1); + private: /* Fields: */ - m_standardHebrewMorphCombo = new QComboBox(this); - label = new QLabel( tr("Hebrew morphological lexicon:"), this); - label->setAlignment(Qt::AlignRight); - label->setBuddy(m_standardHebrewMorphCombo); - //label->setAutoResize(true); - m_standardHebrewMorphCombo->setToolTip(tr("The standard morphological lexicon for Hebrew texts is used when a hyperlink of a morphological tag in a Hebrew text is clicked")); + QLabel *m_explanationLabel; - gridLayout->addWidget(label, 7, 0); - gridLayout->addWidget(m_standardHebrewMorphCombo, 7, 1); +#define STANDARD_WORKS_TAB_FIELD(name) \ + QLabel *m_ ## name ## Label; \ + QComboBox *m_ ## name ## Combo - m_standardGreekMorphCombo = new QComboBox(this); - label = new QLabel(tr("Greek morphological lexicon:"), this); - label->setAlignment(Qt::AlignRight); - label->setBuddy(m_standardGreekMorphCombo); - //label->setAutoResize(true); - m_standardGreekMorphCombo->setToolTip(tr("The standard morphological lexicon for Greek texts is used when a hyperlink of a morphological tag in a Greek text is clicked")); + STANDARD_WORKS_TAB_FIELD(standardBible); + STANDARD_WORKS_TAB_FIELD(standardCommentary); + STANDARD_WORKS_TAB_FIELD(standardLexicon); + STANDARD_WORKS_TAB_FIELD(standardDailyDevotional); + STANDARD_WORKS_TAB_FIELD(standardHebrewStrongsLexicon); + STANDARD_WORKS_TAB_FIELD(standardGreekStrongsLexicon); + STANDARD_WORKS_TAB_FIELD(standardHebrewMorphLexicon); + STANDARD_WORKS_TAB_FIELD(standardGreekMorphLexicon); +}; - gridLayout->addWidget(label, 8, 0); - gridLayout->addWidget(m_standardGreekMorphCombo, 8, 1); +StandardWorksTab::StandardWorksTab(CSwordSettingsPage *parent) + : QWidget(parent) +{ + typedef QList<CSwordModuleInfo*>::const_iterator MLCI; - gridLayout->setRowStretch(9, 5); + QVBoxLayout *mainLayout = new QVBoxLayout(this); + mainLayout->setMargin(5); + mainLayout->setSpacing(2); + + m_explanationLabel = new QLabel(this); + m_explanationLabel->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Preferred); + m_explanationLabel->setMaximumHeight(50); + m_explanationLabel->setMinimumWidth(300); + mainLayout->addWidget(m_explanationLabel); + + QFormLayout *formLayout = new QFormLayout; + +#define STANDARD_WORKS_TAB_ADD_ROW(name) \ + if (true) { \ + m_ ## name ## Label = new QLabel(this); \ + m_ ## name ## Combo = new QComboBox(this); \ + formLayout->addRow(m_ ## name ## Label, m_ ## name ## Combo); \ + } else (void) 0 + + STANDARD_WORKS_TAB_ADD_ROW(standardBible); + STANDARD_WORKS_TAB_ADD_ROW(standardCommentary); + STANDARD_WORKS_TAB_ADD_ROW(standardLexicon); + STANDARD_WORKS_TAB_ADD_ROW(standardDailyDevotional); + STANDARD_WORKS_TAB_ADD_ROW(standardHebrewStrongsLexicon); + STANDARD_WORKS_TAB_ADD_ROW(standardGreekStrongsLexicon); + STANDARD_WORKS_TAB_ADD_ROW(standardHebrewMorphLexicon); + STANDARD_WORKS_TAB_ADD_ROW(standardGreekMorphLexicon); + + mainLayout->addLayout(formLayout); + mainLayout->addStretch(); //fill the comboboxes with the right modules @@ -159,19 +113,19 @@ StandardWorksTab::StandardWorksTab() case CSwordModuleInfo::Lexicon: { bool inserted = false; if ((*it)->has(CSwordModuleInfo::HebrewDef)) { - m_standardHebrewStrongCombo->addItem(modDescript); + m_standardHebrewStrongsLexiconCombo->addItem(modDescript); inserted = true; } if ((*it)->has(CSwordModuleInfo::GreekDef)) { - m_standardGreekStrongCombo->addItem(modDescript); + m_standardGreekStrongsLexiconCombo->addItem(modDescript); inserted = true; } if ((*it)->has(CSwordModuleInfo::HebrewParse)) { - m_standardHebrewMorphCombo->addItem(modDescript); + m_standardHebrewMorphLexiconCombo->addItem(modDescript); inserted = true; } if ((*it)->has(CSwordModuleInfo::GreekParse)) { - m_standardGreekMorphCombo->addItem(modDescript); + m_standardGreekMorphLexiconCombo->addItem(modDescript); inserted = true; } if ((*it)->category() == CSwordModuleInfo::DailyDevotional) { @@ -193,34 +147,23 @@ StandardWorksTab::StandardWorksTab() QList<QComboBox*> comboList; QStringList moduleList; +#define STANDARD_WORKS_TAB_CASE(name) \ + case CBTConfig::name: \ + comboList.append(m_ ## name ## Combo); \ + break + for (int i = 0; i <= (int)CBTConfig::lastModuleType; ++i) { //fill the combobox list in the right order (i.e. same order as the CBTConfig::module enum list) CBTConfig::modules moduleType = (CBTConfig::modules)(i); switch (moduleType) { - case CBTConfig::standardBible: - comboList.append(m_standardBibleCombo); - break; - case CBTConfig::standardCommentary: - comboList.append(m_standardCommentaryCombo); - break; - case CBTConfig::standardLexicon: - comboList.append(m_standardLexiconCombo); - break; - case CBTConfig::standardDailyDevotional: - comboList.append(m_standardDailyDevotionalCombo); - break; - case CBTConfig::standardHebrewStrongsLexicon: - comboList.append(m_standardHebrewStrongCombo); - break; - case CBTConfig::standardGreekStrongsLexicon: - comboList.append(m_standardGreekStrongCombo); - break; - case CBTConfig::standardHebrewMorphLexicon: - comboList.append(m_standardHebrewMorphCombo); - break; - case CBTConfig::standardGreekMorphLexicon: - comboList.append(m_standardGreekMorphCombo); - break; + STANDARD_WORKS_TAB_CASE(standardBible); + STANDARD_WORKS_TAB_CASE(standardCommentary); + STANDARD_WORKS_TAB_CASE(standardLexicon); + STANDARD_WORKS_TAB_CASE(standardDailyDevotional); + STANDARD_WORKS_TAB_CASE(standardHebrewStrongsLexicon); + STANDARD_WORKS_TAB_CASE(standardGreekStrongsLexicon); + STANDARD_WORKS_TAB_CASE(standardHebrewMorphLexicon); + STANDARD_WORKS_TAB_CASE(standardGreekMorphLexicon); } ; //switch @@ -252,136 +195,201 @@ StandardWorksTab::StandardWorksTab() } } } + + retranslateUi(); } +void StandardWorksTab::save() { + for (int i = 0; i <= (int)CBTConfig::lastModuleType; ++i) { + QString moduleDescription; + -TextFiltersTab::TextFiltersTab() { - QVBoxLayout* layout = new QVBoxLayout(this); - layout->setMargin(5); - QWidget* eLabel = util::tool::explanationLabel( - this, "", - tr("Filters control the appearance of text. Here you can specify " - "default settings for all filters. You can override these " - "settings in each display window.") - ); - eLabel->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Preferred); - eLabel->setMaximumHeight(50); - eLabel->setMinimumWidth(300); - layout->setSpacing(2); - layout->addWidget(eLabel); +#define STANDARD_WORKS_TAB_SCASE(name) \ + case CBTConfig::name: \ + moduleDescription = m_ ## name ## Combo->currentText(); \ + break; - m_lineBreaksCheck = new QCheckBox(this); - m_lineBreaksCheck->setText(tr("Insert line break after each verse")); - m_lineBreaksCheck->setChecked(CBTConfig::get(CBTConfig::lineBreaks)); - layout->addWidget(m_lineBreaksCheck); + CBTConfig::modules moduleType = (CBTConfig::modules)(i); + switch (moduleType) { + STANDARD_WORKS_TAB_SCASE(standardBible); + STANDARD_WORKS_TAB_SCASE(standardCommentary); + STANDARD_WORKS_TAB_SCASE(standardLexicon); + STANDARD_WORKS_TAB_SCASE(standardDailyDevotional); + STANDARD_WORKS_TAB_SCASE(standardHebrewStrongsLexicon); + STANDARD_WORKS_TAB_SCASE(standardGreekStrongsLexicon); + STANDARD_WORKS_TAB_SCASE(standardHebrewMorphLexicon); + STANDARD_WORKS_TAB_SCASE(standardGreekMorphLexicon); + default: + qWarning("Unhandled module type."); + }; - m_verseNumbersCheck = new QCheckBox(this); - m_verseNumbersCheck->setText(tr("Show verse numbers")); - m_verseNumbersCheck->setChecked(CBTConfig::get(CBTConfig::verseNumbers)); - layout->addWidget(m_verseNumbersCheck); + CSwordModuleInfo * const module = CSwordBackend::instance()->findModuleByDescription(moduleDescription); + CBTConfig::set(moduleType, module); + } +} - m_headingsCheck = new QCheckBox(this); - m_headingsCheck->setText(tr("Show section headings")); - m_headingsCheck->setChecked(CBTConfig::get(CBTConfig::headings)); - layout->addWidget(m_headingsCheck); +void StandardWorksTab::retranslateUi() { + util::tool::initExplanationLabel( + m_explanationLabel, "", + tr("Standard works are used when no particular work is specified, for example " + "when a hyperlink into a Bible or lexicon was clicked.")); + m_standardBibleLabel->setText(tr("Bible:")); + m_standardBibleCombo->setToolTip(tr("The standard Bible is used when a hyperlink into a Bible is clicked")); - m_scriptureReferencesCheck = new QCheckBox(this); - m_scriptureReferencesCheck->setText(tr("Show scripture cross-references")); - m_scriptureReferencesCheck->setChecked(CBTConfig::get(CBTConfig::scriptureReferences)); - layout->addWidget(m_scriptureReferencesCheck); + m_standardCommentaryLabel->setText(tr("Commentary:")); + m_standardCommentaryCombo->setToolTip(tr("The standard commentary is used when a hyperlink into a commentary is clicked")); - m_greekAccentsCheck = new QCheckBox(this); - m_greekAccentsCheck->setText(tr("Show Greek accents")); - m_greekAccentsCheck->setChecked(CBTConfig::get(CBTConfig::greekAccents)); - layout->addWidget(m_greekAccentsCheck); + m_standardLexiconLabel->setText(tr("Lexicon:")); + m_standardLexiconCombo->setToolTip(tr("The standard lexicon is used when a hyperlink into a lexicon is clicked")); - m_hebrewPointsCheck = new QCheckBox(this); - m_hebrewPointsCheck->setText(tr("Show Hebrew vowel points")); - m_hebrewPointsCheck->setChecked(CBTConfig::get(CBTConfig::hebrewPoints)); - layout->addWidget(m_hebrewPointsCheck); + m_standardDailyDevotionalLabel->setText(tr("Daily devotional:")); + m_standardDailyDevotionalCombo->setToolTip(tr("The standard devotional will be used to display a short start up devotional")); - m_hebrewCantillationCheck = new QCheckBox(this); - m_hebrewCantillationCheck->setText(tr("Show Hebrew cantillation marks")); - m_hebrewCantillationCheck->setChecked(CBTConfig::get(CBTConfig::hebrewCantillation)); - layout->addWidget(m_hebrewCantillationCheck); + m_standardHebrewStrongsLexiconLabel->setText(tr("Hebrew Strong's lexicon:")); + m_standardHebrewStrongsLexiconCombo->setToolTip(tr("The standard Hebrew lexicon is used when a hyperlink into a Hebrew lexicon is clicked")); - m_morphSegmentationCheck = new QCheckBox(this); - m_morphSegmentationCheck->setText(tr("Show morph segmentation")); - m_morphSegmentationCheck->setChecked(CBTConfig::get(CBTConfig::morphSegmentation)); - layout->addWidget(m_morphSegmentationCheck); + m_standardGreekStrongsLexiconLabel->setText(tr("Greek Strong's lexicon:")); + m_standardGreekStrongsLexiconCombo->setToolTip(tr("The standard Greek lexicon is used when a hyperlink into a Greek lexicon is clicked")); - m_textualVariantsCheck = new QCheckBox(this); - m_textualVariantsCheck->setText(tr("Use textual variants")); - m_textualVariantsCheck->setChecked(CBTConfig::get(CBTConfig::textualVariants)); - layout->addWidget(m_textualVariantsCheck); + m_standardHebrewMorphLexiconLabel->setText(tr("Hebrew morphological lexicon:")); + m_standardHebrewMorphLexiconCombo->setToolTip(tr("The standard morphological lexicon for Hebrew texts is used when a hyperlink of a morphological tag in a Hebrew text is clicked")); - layout->addStretch(4); + m_standardGreekMorphLexiconLabel->setText(tr("Greek morphological lexicon:")); + m_standardGreekMorphLexiconCombo->setToolTip(tr("The standard morphological lexicon for Greek texts is used when a hyperlink of a morphological tag in a Greek text is clicked")); } -void CSwordSettingsPage::save() { - m_worksTab->save(); - m_filtersTab->save(); -} -const QIcon &CSwordSettingsPage::icon() const { - return util::directory::getIcon(CResMgr::settings::sword::icon); +/******************************************************************************* + TextFiltersTab +*******************************************************************************/ + +class TextFiltersTab: public QWidget { + + public: /* Methods: */ + + TextFiltersTab(CSwordSettingsPage *parent); + + void save(); + + protected: /* Methods: */ + + void retranslateUi(); + + private: /* Fields: */ + + QLabel *m_explanationLabel; + +#define TEXT_FILTERS_TAB_FIELD(name) QCheckBox *m_ ## name ## Check + + TEXT_FILTERS_TAB_FIELD(lineBreaks); + TEXT_FILTERS_TAB_FIELD(verseNumbers); + TEXT_FILTERS_TAB_FIELD(headings); + TEXT_FILTERS_TAB_FIELD(hebrewPoints); + TEXT_FILTERS_TAB_FIELD(hebrewCantillation); + TEXT_FILTERS_TAB_FIELD(morphSegmentation); + TEXT_FILTERS_TAB_FIELD(greekAccents); + TEXT_FILTERS_TAB_FIELD(textualVariants); + TEXT_FILTERS_TAB_FIELD(scriptureReferences); + +}; + +TextFiltersTab::TextFiltersTab(CSwordSettingsPage *parent) + : QWidget(parent) +{ + QVBoxLayout *layout = new QVBoxLayout(this); + layout->setMargin(5); + layout->setSpacing(2); + + m_explanationLabel = new QLabel(this); + m_explanationLabel->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Preferred); + m_explanationLabel->setMaximumHeight(50); + m_explanationLabel->setMinimumWidth(300); + layout->addWidget(m_explanationLabel); + +#define TEXT_FILTERS_TAB_ADD_ROW(name) \ + m_ ## name ## Check = new QCheckBox(this); \ + m_ ## name ## Check->setChecked(CBTConfig::get(CBTConfig::name)); \ + layout->addWidget(m_ ## name ## Check); + + TEXT_FILTERS_TAB_ADD_ROW(lineBreaks); + TEXT_FILTERS_TAB_ADD_ROW(verseNumbers); + TEXT_FILTERS_TAB_ADD_ROW(headings); + TEXT_FILTERS_TAB_ADD_ROW(hebrewPoints); + TEXT_FILTERS_TAB_ADD_ROW(hebrewCantillation); + TEXT_FILTERS_TAB_ADD_ROW(morphSegmentation); + TEXT_FILTERS_TAB_ADD_ROW(greekAccents); + TEXT_FILTERS_TAB_ADD_ROW(textualVariants); + TEXT_FILTERS_TAB_ADD_ROW(scriptureReferences); + + layout->addStretch(4); + + retranslateUi(); } -QString CSwordSettingsPage::header() const { - return tr("Desk"); +void TextFiltersTab::save() { +#define TEXT_FILTERS_TAB_SAVE(name) CBTConfig::set(CBTConfig::name, m_ ## name ## Check->isChecked()) + + TEXT_FILTERS_TAB_SAVE(lineBreaks); + TEXT_FILTERS_TAB_SAVE(verseNumbers); + TEXT_FILTERS_TAB_SAVE(headings); + TEXT_FILTERS_TAB_SAVE(hebrewPoints); + TEXT_FILTERS_TAB_SAVE(hebrewCantillation); + TEXT_FILTERS_TAB_SAVE(morphSegmentation); + TEXT_FILTERS_TAB_SAVE(greekAccents); + TEXT_FILTERS_TAB_SAVE(textualVariants); + TEXT_FILTERS_TAB_SAVE(scriptureReferences); } -void StandardWorksTab::save() { - for (int i = 0; i <= (int)CBTConfig::lastModuleType; ++i) { - QString moduleDescription = QString::null; - CBTConfig::modules moduleType = (CBTConfig::modules)(i); - switch (moduleType) { - case CBTConfig::standardBible: - moduleDescription = m_standardBibleCombo->currentText(); - break; - case CBTConfig::standardCommentary: - moduleDescription = m_standardCommentaryCombo->currentText(); - break; - case CBTConfig::standardLexicon: - moduleDescription = m_standardLexiconCombo->currentText(); - break; - case CBTConfig::standardDailyDevotional: - moduleDescription = m_standardDailyDevotionalCombo->currentText(); - break; - case CBTConfig::standardHebrewStrongsLexicon: - moduleDescription = m_standardHebrewStrongCombo->currentText(); - break; - case CBTConfig::standardGreekStrongsLexicon: - moduleDescription = m_standardGreekStrongCombo->currentText(); - break; - case CBTConfig::standardHebrewMorphLexicon: - moduleDescription = m_standardHebrewMorphCombo->currentText(); - break; - case CBTConfig::standardGreekMorphLexicon: - moduleDescription = m_standardGreekMorphCombo->currentText(); - break; - default: - qWarning("Unhandled module type."); - }; +void TextFiltersTab::retranslateUi() { + util::tool::initExplanationLabel(m_explanationLabel, "", + tr("Filters control the appearance of text. Here you can specify " + "default settings for all filters. You can override these " + "settings in each display window.")); - CSwordModuleInfo * const module = CSwordBackend::instance()->findModuleByDescription(moduleDescription); - CBTConfig::set(moduleType, module); - } + m_lineBreaksCheck->setText(tr("Insert line break after each verse")); + m_verseNumbersCheck->setText(tr("Show verse numbers")); + m_headingsCheck->setText(tr("Show section headings")); + m_scriptureReferencesCheck->setText(tr("Show scripture cross-references")); + m_greekAccentsCheck->setText(tr("Show Greek accents")); + m_hebrewPointsCheck->setText(tr("Show Hebrew vowel points")); + m_hebrewCantillationCheck->setText(tr("Show Hebrew cantillation marks")); + m_morphSegmentationCheck->setText(tr("Show morph segmentation")); + m_textualVariantsCheck->setText(tr("Use textual variants")); } +/******************************************************************************* + CSwordSettingsPage +*******************************************************************************/ -void TextFiltersTab::save() { - CBTConfig::set(CBTConfig::lineBreaks, m_lineBreaksCheck->isChecked()); - CBTConfig::set(CBTConfig::verseNumbers, m_verseNumbersCheck->isChecked()); - CBTConfig::set(CBTConfig::headings, m_headingsCheck->isChecked()); - CBTConfig::set(CBTConfig::scriptureReferences, m_scriptureReferencesCheck->isChecked()); - CBTConfig::set(CBTConfig::hebrewPoints, m_hebrewPointsCheck->isChecked()); - CBTConfig::set(CBTConfig::hebrewCantillation, m_hebrewCantillationCheck->isChecked()); - CBTConfig::set(CBTConfig::morphSegmentation, m_morphSegmentationCheck->isChecked()); - CBTConfig::set(CBTConfig::greekAccents, m_greekAccentsCheck->isChecked()); - CBTConfig::set(CBTConfig::textualVariants, m_textualVariantsCheck->isChecked()); +CSwordSettingsPage::CSwordSettingsPage(CConfigurationDialog *parent) + : BtConfigDialog::Page(util::directory::getIcon(CResMgr::settings::sword::icon), parent) +{ + static const QString nullString; + + m_tabWidget = new QTabWidget(this); + m_worksTab = new StandardWorksTab(this); + m_tabWidget->addTab(m_worksTab, nullString); + + m_filtersTab = new TextFiltersTab(this); + m_tabWidget->addTab(m_filtersTab, nullString); + + + QVBoxLayout *mainLayout = new QVBoxLayout(this); + mainLayout->addWidget(m_tabWidget); + + retranslateUi(); } +void CSwordSettingsPage::retranslateUi() { + setHeaderText(tr("Desk")); + + m_tabWidget->setTabText(m_tabWidget->indexOf(m_worksTab), tr("Standard works")); + m_tabWidget->setTabText(m_tabWidget->indexOf(m_filtersTab), tr("Text filters")); +} +void CSwordSettingsPage::save() { + m_worksTab->save(); + m_filtersTab->save(); +} diff --git a/src/frontend/settingsdialogs/cswordsettings.h b/src/frontend/settingsdialogs/cswordsettings.h index b4684db..01f5829 100644 --- a/src/frontend/settingsdialogs/cswordsettings.h +++ b/src/frontend/settingsdialogs/cswordsettings.h @@ -14,64 +14,30 @@ #include <QWidget> -class QCheckBox; -class QComboBox; +class CConfigurationDialog; class StandardWorksTab; class TextFiltersTab; -class CSwordSettingsPage : public BtConfigPage { - Q_OBJECT - public: - CSwordSettingsPage(QWidget *parent = 0); +class CSwordSettingsPage: public BtConfigDialog::Page { - void save(); + Q_OBJECT - /** Reimplemented from BtConfigPage. */ - virtual const QIcon &icon() const; + public: /* Methods: */ - /** Reimplemented from BtConfigPage. */ - virtual QString header() const; + CSwordSettingsPage(CConfigurationDialog *parent = 0); - private: - StandardWorksTab* m_worksTab; - TextFiltersTab* m_filtersTab; -}; + void save(); -//Tab pages. To be used only in Sword settings page. + protected: /* Methods: */ -class StandardWorksTab: public QWidget { - Q_OBJECT - public: - StandardWorksTab(); - void save(); + void retranslateUi(); - private: - QComboBox* m_standardBibleCombo; - QComboBox* m_standardCommentaryCombo; - QComboBox* m_standardLexiconCombo; - QComboBox* m_standardDailyDevotionalCombo; - QComboBox* m_standardHebrewStrongCombo; - QComboBox* m_standardGreekStrongCombo; - QComboBox* m_standardHebrewMorphCombo; - QComboBox* m_standardGreekMorphCombo; -}; + private: /* Fields: */ -class TextFiltersTab : public QWidget { - Q_OBJECT - public: - TextFiltersTab(); - void save(); + QTabWidget *m_tabWidget; + StandardWorksTab *m_worksTab; + TextFiltersTab *m_filtersTab; - private: - QCheckBox* m_lineBreaksCheck; - QCheckBox* m_verseNumbersCheck; - QCheckBox* m_headingsCheck; - QCheckBox* m_hebrewPointsCheck; - QCheckBox* m_hebrewCantillationCheck; - QCheckBox* m_morphSegmentationCheck; - QCheckBox* m_greekAccentsCheck; - QCheckBox* m_textualVariantsCheck; - QCheckBox* m_scriptureReferencesCheck; }; #endif diff --git a/src/frontend/tips/bttipdialog.cpp b/src/frontend/tips/bttipdialog.cpp index ed0a409..5c4052d 100644 --- a/src/frontend/tips/bttipdialog.cpp +++ b/src/frontend/tips/bttipdialog.cpp @@ -11,6 +11,7 @@ #include "backend/config/cbtconfig.h" #include "util/cresmgr.h" +#include "util/dialogutil.h" #include "util/directory.h" #include <QCheckBox> @@ -85,6 +86,8 @@ BtTipDialog::BtTipDialog(QWidget *parent, Qt::WindowFlags wflags) m_buttonBox = new QDialogButtonBox(QDialogButtonBox::Close, Qt::Horizontal, this); + util::prepareDialogBox(m_buttonBox); + QPushButton *nextButton; nextButton = m_buttonBox->addButton(tr("Next Tip"), QDialogButtonBox::ActionRole); @@ -137,7 +140,7 @@ void BtTipDialog::initTips() { m_tips << tr("To create a bookmark drag any verse reference from a Bible or commentary work" " into the Bookmarks window. An arrow will indicate the position that the bookmark will" " go when you release the cursor. Other works will have a reference in the upper left" - " corner that can be used to create a bookmark."); + " corner that can be used to create a bookmark."); m_tips << tr("To change a bookmark title or description, right click on the bookmark" " and select the Edit Bookmark menu. After finishing the edit the description can be" @@ -156,19 +159,23 @@ void BtTipDialog::initTips() { " border between the window and another window."); m_tips << tr("You can search for Strong's numbers in a work. Start with a work that has Strong's" - " numbers and hover over a word. Right click the word and use the Strong's Search" - " menu. A search dialog will appear that allows you to see the use of the same" - " Strong's number in other locations of the work."); + " numbers and hover over a word. Right click the word and use the Strong's Search" + " menu. A search dialog will appear that allows you to see the use of the same" + " Strong's number in other locations of the work."); m_tips << tr("You can save personal notes for specific verses references. You must install" - " the Personal commentary. Open the Bookshelf Manager, choose Crosswire as the" - " source and look under Commentary and English. Once installed, use the" - " Bookshelf window and right click the Personal commentary. Use either the" - " Edit Plain Text menu or the Edit HTML menu to open the work in write mode."); + " the Personal commentary. Open the Bookshelf Manager, choose Crosswire as the" + " source and look under Commentary and English. Once installed, use the" + " Bookshelf window and right click the Personal commentary. Use either the" + " Edit Plain Text menu or the Edit HTML menu to open the work in write mode."); m_tips << tr("You can view Strong's number information in the MAG window by hovering over" - " a word in a Bible work that has Strong's numbers. You should have the StrongsGreek" - " and StrongsHebrew lexicons from Crosswire installed."); + " a word in a Bible work that has Strong's numbers. You should have the StrongsGreek" + " and StrongsHebrew lexicons from Crosswire installed."); + + m_tips << tr("You can save your open windows in a session. Such a session can easily be restored" + " later on. You can save as many sessions as you like. The session feature can be" + " accessed under the Window menu entry."); } void BtTipDialog::displayTip() { diff --git a/src/main.cpp b/src/main.cpp index 6f2c9b2..1af6e1a 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -7,10 +7,13 @@ * **********/ +#include <cstdlib> #include <iostream> +#include <QDateTime> #ifndef NO_DBUS #include <QDBusConnection> #endif +#include <QFile> #include <QLocale> #include <QTextCodec> #include <QTranslator> @@ -19,6 +22,7 @@ #include "bibletime.h" #include "bibletime_dbus_adaptor.h" #include "bibletimeapp.h" +#include "frontend/settingsdialogs/btlanguagesettings.h" #include "util/directory.h" @@ -117,49 +121,57 @@ int parseCommandLine(bool &showDebugMessages, bool &ignoreSession, Console messaging. *******************************************************************************/ -bool showDebugMessages = false; - -#ifdef Q_WS_WIN - -FILE *out_fd = 0; -#define DEBUG_STREAM (out_fd != 0 ? out_fd :\ - out_fd = fopen(QDir::homePath().append("/BibleTime Debug.txt").toLocal8Bit().data(),"w")) -#define CLOSE_DEBUG_STREAM { if (out_fd != 0) fclose(out_fd); } - +#if QT_VERSION >= 0x040600 +QScopedPointer<QFile> debugStream; #else - -#define DEBUG_STREAM (stderr) -#define CLOSE_DEBUG_STREAM - +struct DebugStreamPtr { + QFile * m_f; + inline DebugStreamPtr() : m_f(0) {} + inline ~DebugStreamPtr() { delete m_f; } + inline void reset(QFile * f) { m_f = f; } + inline QFile * operator->() const { + Q_ASSERT(m_f); + return m_f; + } +} debugStream; #endif +bool showDebugMessages = false; void myMessageOutput( QtMsgType type, const char *msg ) { - //we use this messagehandler to switch debugging off in final releases - FILE* outFd = 0; + // We use this messagehandler to switch debugging off in final releases switch (type) { case QtDebugMsg: - if (showDebugMessages) { //only show messages if they are enabled! - outFd = DEBUG_STREAM; - if (outFd != 0) - fprintf(outFd, "(BibleTime " BT_VERSION ") Debug: %s\n", msg); + if (showDebugMessages) { // Only show messages if they are enabled! + debugStream->write("(BibleTime " BT_VERSION ") Debug: "); + debugStream->write(msg); + debugStream->write("\n"); + debugStream->flush(); } break; case QtWarningMsg: #ifndef QT_NO_DEBUG // don't show in release builds so users don't get our debug warnings - outFd = DEBUG_STREAM; - if (outFd != 0) - fprintf(outFd, "(BibleTime " BT_VERSION ") WARNING: %s\n", msg); + debugStream->write("(BibleTime " BT_VERSION ") WARNING: "); + debugStream->write(msg); + debugStream->write("\n"); + debugStream->flush(); #endif break; - case QtFatalMsg: case QtCriticalMsg: - outFd = DEBUG_STREAM; - if (outFd != 0) - fprintf(outFd, - "(BibleTime " BT_VERSION ") _FATAL_: %s\nPlease report this bug! " - "(http://www.bibletime.info/development_help.html)", - msg); - abort(); // dump core on purpose + debugStream->write("(BibleTime " BT_VERSION ") CRITICAL: "); + debugStream->write(msg); + debugStream->write("\nPlease report this bug! " + "(http://www.bibletime.info/development_help.html)"); + debugStream->flush(); + break; + case QtFatalMsg: + debugStream->write("(BibleTime " BT_VERSION ") FATAL: "); + debugStream->write(msg); + debugStream->write("\nPlease report this bug! " + "(http://www.bibletime.info/development_help.html)"); + + // Dump core on purpose (see qInstallMsgHandler documentation): + debugStream->close(); + abort(); } } @@ -168,8 +180,8 @@ void myMessageOutput( QtMsgType type, const char *msg ) { *******************************************************************************/ void registerMetaTypes() { - qRegisterMetaType<FilterOptions>(); - qRegisterMetaType<DisplayOptions>(); + qRegisterMetaType<FilterOptions>("FilterOptions"); + qRegisterMetaType<DisplayOptions>("DisplayOptions"); qRegisterMetaTypeStreamOperators<BtBookshelfTreeModel::Grouping>("BtBookshelfTreeModel::Grouping"); } @@ -196,12 +208,23 @@ int main(int argc, char* argv[]) { return EXIT_FAILURE; } + // Initialize random number generator: + srand(qHash(QDateTime::currentDateTime().toString(Qt::ISODate))); + + // Setup debugging: #ifdef Q_WS_WIN // Use the default Qt message handler if --debug is not specified // This works with Visual Studio debugger Output Window - if (showDebugMessages) -#endif + if (showDebugMessages) { + debugStream.reset(new QFile(QDir::homePath().append("/BibleTime Debug.txt"))); + debugStream->open(QIODevice::WriteOnly | QIODevice::Text); + qInstallMsgHandler(myMessageOutput); + } +#else + debugStream.reset(new QFile); + debugStream->open(stderr, QIODevice::WriteOnly | QIODevice::Text); qInstallMsgHandler(myMessageOutput); +#endif #ifdef Q_WS_WIN @@ -252,8 +275,15 @@ int main(int argc, char* argv[]) { app.setProperty("--debug", QVariant(showDebugMessages)); -// setSignalHandler(signalHandler); + /* + Set book names language if not set. This is a hack. We do this call here, + because we need to keep the setting displayed in BtLanguageSettingsPage in + sync with the language of the book names displayed, so that both would + always use the same setting. + */ + BtLanguageSettingsPage::resetLanguage(); /// \todo refactor this hack + // Initialize display template manager: if (!app.initDisplayTemplateManager()) return EXIT_FAILURE; BibleTime *mainWindow = new BibleTime(); @@ -283,7 +313,6 @@ int main(int argc, char* argv[]) { mainWindow->slotOpenTipDialog(); r = app.exec(); - CLOSE_DEBUG_STREAM; return r; } diff --git a/src/util/btmodules.cpp b/src/util/btmodules.cpp new file mode 100644 index 0000000..784fd2a --- /dev/null +++ b/src/util/btmodules.cpp @@ -0,0 +1,37 @@ +/********* +* +* This file is part of BibleTime's source code, http://www.bibletime.info/. +* +* Copyright 1999-2011 by the BibleTime developers. +* The BibleTime source code is licensed under the GNU General Public License version 2.0. +* +**********/ + +#include "btmodules.h" + +#include "backend/managers/cswordbackend.h" + + +bool equalModuleCategories(const QString& name1, const QString& name2) { + CSwordModuleInfo* m1 = CSwordBackend::instance()->findModuleByName(name1); + CSwordModuleInfo* m2 = CSwordBackend::instance()->findModuleByName(name2); + if (m1 == 0 || m2 == 0) + return false; + if (m1->category() == m2->category()) { + return true; + } + return false; +} + +int leftLikeParallelModules(const QStringList modules) { + // Count the number of leftmost modules that are of the same category + int leftLikeModules = 0; + for (int i = 0; i < modules.count(); i++) { + if ( ! equalModuleCategories(modules.at(0), modules.at(i))) { + break; + } + leftLikeModules++; + } + return leftLikeModules; +} + diff --git a/src/util/btmodules.h b/src/util/btmodules.h new file mode 100644 index 0000000..2532e42 --- /dev/null +++ b/src/util/btmodules.h @@ -0,0 +1,16 @@ +/********* +* +* This file is part of BibleTime's source code, http://www.bibletime.info/. +* +* Copyright 1999-2011 by the BibleTime developers. +* The BibleTime source code is licensed under the GNU General Public License version 2.0. +* +**********/ + +#include <QString> +#include <QStringList> + +bool equalModuleCategories(const QString& name1, const QString& name2); + +int leftLikeParallelModules(const QStringList modules); + diff --git a/src/util/btsignal.h b/src/util/btsignal.h index ff4afa1..6f05226 100644 --- a/src/util/btsignal.h +++ b/src/util/btsignal.h @@ -30,11 +30,16 @@ class BtSignal : public QObject { inline BtSignal(QObject *parent = 0) : QObject(parent) {}; /** + Immediately emits the beforeChanged() signal. + */ + inline void emitBeforeChanged() { emit beforeChanged(); } + /** Immediately emits the changed() signal. */ inline void emitChanged() { emit changed(); } signals: + void beforeChanged(); void changed(); }; #endif diff --git a/src/util/cresmgr.cpp b/src/util/cresmgr.cpp index 2fc26d4..908c5f3 100644 --- a/src/util/cresmgr.cpp +++ b/src/util/cresmgr.cpp @@ -68,6 +68,15 @@ const QString icon = "questionable.svg"; namespace mainMenu { //Main menu namespace view { //Main menu->View +namespace showBookshelf { +const QString icon = "books.svg"; +} +namespace showBookmarks { +const QString icon = "bookmark.svg"; +} +namespace showMag { +const QString icon = "document_magnifier.svg"; +} namespace showMainIndex { const QString icon = "view_index.svg"; const QKeySequence accel(Qt::Key_F9); diff --git a/src/util/cresmgr.h b/src/util/cresmgr.h index 7ba8760..89bcfa5 100644 --- a/src/util/cresmgr.h +++ b/src/util/cresmgr.h @@ -71,6 +71,15 @@ extern const QString icon; namespace mainMenu { //Main menu namespace view { //Main menu->View +namespace showBookshelf { +extern const QString icon; +} +namespace showBookmarks { +extern const QString icon; +} +namespace showMag { +extern const QString icon; +} namespace showMainIndex { extern const QString icon; extern const QKeySequence accel; diff --git a/src/util/dialogutil.cpp b/src/util/dialogutil.cpp index 39672d3..661e314 100644 --- a/src/util/dialogutil.cpp +++ b/src/util/dialogutil.cpp @@ -26,8 +26,13 @@ void replaceText(QDialogButtonBox *box, QDialogButtonBox::StandardButton flag, } } -QMessageBox::StandardButton bt_messageBox(QMessageBox::Icon icon, QWidget * parent, const QString & title, const QString & text, QMessageBox::StandardButtons buttons, QMessageBox::StandardButton defaultButton) { - qDebug() << "BT message box warning/information/critical"; +QMessageBox::StandardButton bt_messageBox(QMessageBox::Icon icon, + QWidget * parent, + const QString &title, + const QString &text, + QMessageBox::StandardButtons buttons, + QMessageBox::StandardButton defaultButton) +{ QMessageBox messageBox(icon, title, text, QMessageBox::Ok, parent); messageBox.setTextFormat(Qt::RichText); //We need the button box to translate the strings (the idea of this whole function) |