diff --git a/CMakeLists.txt b/CMakeLists.txt index 3629089..1b42b43 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,69 +1,72 @@ project(kjots) cmake_minimum_required(VERSION 2.8.12) find_package(ECM 5.16.0 REQUIRED NO_MODULE) set(CMAKE_MODULE_PATH ${CMAKE_SOURCE_DIR}/cmake/modules ${ECM_MODULE_PATH}) include(ECMAddTests) include(CMakePackageConfigHelpers) include(FeatureSummary) include(KDEInstallDirs) include(KDECMakeSettings) include(KDECompilerSettings NO_POLICY_SCOPE) include(ECMInstallIcons) include(ECMQtDeclareLoggingCategory) include(ECMAddAppIcon) set(KJOTS_VERSION "5.0.2") set(KF5_VERSION "5.16.0") # Only what is in Applications/15.12 set(KDEPIMLIBS_LIB_VERSION "5.1.0") set(KMIME_LIB_VERSION "4.87.0") set(PIMTEXTEDIT_LIB_VERSION "4.91.0") set(KONTACTINTERFACE_LIB_VERSION "4.82.0") #Qt Packages set(QT_REQUIRED_VERSION "5.6.0") find_package(Qt5 ${QT_REQUIRED_VERSION} CONFIG REQUIRED DBus PrintSupport) # KF5 Packages find_package(KF5KCMUtils ${KF5_VERSION} CONFIG REQUIRED) find_package(KF5KIO ${KF5_VERSION} CONFIG REQUIRED) find_package(KF5Config ${KF5_VERSION} CONFIG REQUIRED) find_packagE(KF5ConfigWidgets ${KF5_VERSION} CONFIG REQUIRED) find_package(KF5Parts ${KF5_VERSION} CONFIG REQUIRED) find_package(KF5Bookmarks ${KF5_VERSION} CONFIG REQUIRED) find_package(KF5XmlGui ${KF5_VERSION} CONFIG REQUIRED) find_package(KF5TextWidgets ${KF5_VERSION} CONFIG REQUIRED) # PIM packages find_package(KF5Akonadi ${KDEPIMLIBS_LIB_VERSION} CONFIG REQUIRED) find_package(KF5Mime ${KMIME_LIB_VERSION} CONFIG REQUIRED) find_package(KF5AkonadiNotes ${KDEPIMLIBS_LIB_VERSION} CONFIG REQUIRED) find_package(KF5PimTextEdit ${PIMTEXTEDIT_LIB_VERSION} CONFIG REQUIRED) find_package(KF5KontactInterface ${KONTACTINTERFACE_LIB_VERSION} CONFIG REQUIRED) find_package(Grantlee5 "5.0" CONFIG REQUIRED) find_package(Xsltproc) +##################### Definitions ##################### +add_definitions(-DQT_NO_KEYWORDS) + ##################### Targets ####################### add_subdirectory(src) add_subdirectory(icons) ##################### Install ###################### install(DIRECTORY themes DESTINATION ${DATA_INSTALL_DIR}/kjots PATTERN *.svn EXCLUDE ) install(FILES data/org.kde.kjots.appdata.xml DESTINATION ${CMAKE_INSTALL_METAINFODIR} ) install(FILES data/org.kde.kjots.desktop DESTINATION ${XDG_APPS_INSTALL_DIR} ) diff --git a/src/KJotsMain.h b/src/KJotsMain.h index e00af7d..f4a241f 100644 --- a/src/KJotsMain.h +++ b/src/KJotsMain.h @@ -1,56 +1,53 @@ // // kjots // // Copyright (C) 1997 Christoph Neerfeld // Copyright (C) 2002, 2003 Aaron J. Seigo // Copyright (C) 2003 Stanislav Kljuhhin // Copyright (C) 2005-2006 Jaison Lee // Copyright (C) 2007-2008 Stephen Kelly // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. // #ifndef KJOTSMAIN_H #define KJOTSMAIN_H #include class KJotsWidget; class KJotsMain : public KXmlGuiWindow { Q_OBJECT public: - KJotsMain(); + explicit KJotsMain(); -public slots: +public Q_SLOTS: void updateCaption(QString); void onQuit(); void activeAnchorChanged(const QString &, const QString &); protected: - /** - Reimplemented from KMainWindow - */ - /* reimp */ bool queryClose(); + bool queryClose() override; private: KJotsWidget *component; }; #endif // KJotsMainNew_included /* ex: set tabstop=4 softtabstop=4 shiftwidth=4 expandtab: */ diff --git a/src/akonadi_next/notecreatorandselector.h b/src/akonadi_next/notecreatorandselector.h index e52add9..998d1f4 100644 --- a/src/akonadi_next/notecreatorandselector.h +++ b/src/akonadi_next/notecreatorandselector.h @@ -1,77 +1,77 @@ /* Copyright (C) 2010 Klarälvdalens Datakonsult AB, a KDAB Group company, info@kdab.net, author Stephen Kelly This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef NOTECREATORANDSELECTOR_H #define NOTECREATORANDSELECTOR_H #include #include #include #include class KJob; namespace Akonotes { /** * @brief Creates and selects the newly created note. * * The note is created in the supplied collection. That collection is * selected in the primaryModel. The new note is selected in the * secondaryModel. If the secondaryModel is null, the primaryModel is * used to select the note too. That is relevant for mixed tree models like * KJots uses. */ class NoteCreatorAndSelector : public QObject { Q_OBJECT public: explicit NoteCreatorAndSelector(QItemSelectionModel *primaryModel, - QItemSelectionModel *secondaryModel = 0, - QObject *parent = Q_NULLPTR); + QItemSelectionModel *secondaryModel = nullptr, + QObject *parent = nullptr); virtual ~NoteCreatorAndSelector(); void createNote(const Akonadi::Collection &containerCollection); private: void doCreateNote(); private Q_SLOTS: void trySelectCollection(); void noteCreationFinished(KJob *job); void trySelectNote(); private: QItemSelectionModel *m_primarySelectionModel; QItemSelectionModel *m_secondarySelectionModel; Akonadi::Collection::Id m_containerCollectionId; Akonadi::Item::Id m_newNoteId; QTimer *m_giveupTimer; }; } #endif diff --git a/src/kjotsbookmarks.cpp b/src/kjotsbookmarks.cpp index 84d2c8e..4ec0f15 100644 --- a/src/kjotsbookmarks.cpp +++ b/src/kjotsbookmarks.cpp @@ -1,76 +1,72 @@ // // kjotsbookmarks // // Copyright (C) 1997 Christoph Neerfeld // Copyright (C) 2002, 2003 Aaron J. Seigo // Copyright (C) 2003 Stanislav Kljuhhin // Copyright (C) 2005-2006 Jaison Lee // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. // #include "kjotsbookmarks.h" #include #include "kjotsmodel.h" #include "kjotstreeview.h" KJotsBookmarks::KJotsBookmarks(KJotsTreeView *treeView) : m_treeView(treeView) { } -KJotsBookmarks::~KJotsBookmarks() -{ -} - void KJotsBookmarks::openBookmark(const KBookmark &bookmark, Qt::MouseButtons, Qt::KeyboardModifiers) { #if 0 QModelIndexList rows = m_treeView->model()->match(QModelIndex(), KJotsModel::EntityUrlRole, bookmark.url().url()); if (rows.isEmpty()) { return; } // Arbitrarily chooses the first one if multiple are returned. return m_treeView->selectionModel()->select(rows.at(0), QItemSelectionModel::ClearAndSelect); #endif } QUrl KJotsBookmarks::currentUrl() const { #if 0 //QT5 QModelIndexList rows = m_treeView->selectionModel()->selectedRows(); if (rows.size() != 1) { return QString(); } #if 0 return rows.at(0).data(EntityTreeModel::EntityUrlRole).toString(); #else return QString(); #endif #else return QUrl(); #endif } QString KJotsBookmarks::currentTitle() const { return m_treeView->captionForSelection(QLatin1String(": ")); } diff --git a/src/kjotsbookmarks.h b/src/kjotsbookmarks.h index 9f48838..9f436ea 100644 --- a/src/kjotsbookmarks.h +++ b/src/kjotsbookmarks.h @@ -1,48 +1,47 @@ // // kjotsbookmarks // // Copyright (C) 1997 Christoph Neerfeld // Copyright (C) 2002, 2003 Aaron J. Seigo // Copyright (C) 2003 Stanislav Kljuhhin // Copyright (C) 2005-2006 Jaison Lee // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. // #ifndef KJOTSBOOKMARKS #define KJOTSBOOKMARKS #include class KJotsTreeView; class KJotsBookmarks : public QObject, public KBookmarkOwner { Q_OBJECT public: explicit KJotsBookmarks(KJotsTreeView *treeView); - ~KJotsBookmarks(); - virtual QUrl currentUrl() const; - virtual QString currentTitle() const; - virtual void openBookmark(const KBookmark &bm, Qt::MouseButtons mb, Qt::KeyboardModifiers km); + QUrl currentUrl() const override; + QString currentTitle() const override; + void openBookmark(const KBookmark &bm, Qt::MouseButtons mb, Qt::KeyboardModifiers km) override; private: KJotsTreeView *m_treeView; }; #endif /* ex: set tabstop=4 softtabstop=4 shiftwidth=4 expandtab: */ diff --git a/src/kjotsbookshelfentryvalidator.cpp b/src/kjotsbookshelfentryvalidator.cpp index 3f3ae08..52d9163 100644 --- a/src/kjotsbookshelfentryvalidator.cpp +++ b/src/kjotsbookshelfentryvalidator.cpp @@ -1,63 +1,58 @@ /* This file is part of KJots. Copyright (c) 2008 Stephen Kelly This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "kjotsbookshelfentryvalidator.h" KJotsBookshelfEntryValidator::KJotsBookshelfEntryValidator(QAbstractItemModel *model, QObject *parent) : QValidator(parent) { m_model = model; } -KJotsBookshelfEntryValidator::~KJotsBookshelfEntryValidator() -{ - -} - QValidator::State KJotsBookshelfEntryValidator::validate(QString &input, int &pos) const { - Q_UNUSED(pos); + Q_UNUSED(pos) if (!m_model) { return Invalid; } if (input.isEmpty()) { return Intermediate; } - QModelIndexList list = m_model->match( - m_model->index(0, 0), - Qt::DisplayRole, - input, - Qt::MatchStartsWith | Qt::MatchFixedString | Qt::MatchWrap); + const QModelIndexList list = m_model->match( + m_model->index(0, 0), + Qt::DisplayRole, + input, + Qt::MatchStartsWith | Qt::MatchFixedString | Qt::MatchWrap); if (list.empty()) { return Invalid; } else { - foreach (const QModelIndex &index, list) { + for (const QModelIndex &index : list) { if (0 == QString::compare(m_model->data(index).toString(), input, Qt::CaseInsensitive)) { return Acceptable; } return Intermediate; } } return Invalid; } diff --git a/src/kjotsbookshelfentryvalidator.h b/src/kjotsbookshelfentryvalidator.h index 3026d94..7c23809 100644 --- a/src/kjotsbookshelfentryvalidator.h +++ b/src/kjotsbookshelfentryvalidator.h @@ -1,68 +1,63 @@ /* This file is part of KJots. Copyright (c) 2008 Stephen Kelly This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef KJOTSBOOKSHELFENTRYVALIDATOR #define KJOTSBOOKSHELFENTRYVALIDATOR #include #include /** This class is a validator intended to be used with an editable QComboBox. \a validate returns the state of whether the text in the lineedit matches one of the items in the model. All matching is attempted on the first column of the model. */ class KJotsBookshelfEntryValidator : public QValidator { Q_OBJECT public: /** Create a new Validator for Entries in the KJots bookshelf. @param parent The parent object. @param model The model to use to validate the input. */ - explicit KJotsBookshelfEntryValidator(QAbstractItemModel *model, QObject *parent = 0); + explicit KJotsBookshelfEntryValidator(QAbstractItemModel *model, QObject *parent = nullptr); /** - Destructor. - */ - ~KJotsBookshelfEntryValidator(); - - /** - Reimplemented. Returns the state of whether \p input matches one of the items in the model. + Returns the state of whether \p input matches one of the items in the model. If the text does not match any item in the model, the state is Invalid. If the text is empty, the state is Intermediate. If the text matches the start of one or more items in the model, the state is Intermediate. If the text matches one of the items in the model exactly, the state is Acceptable. \return The validation state. */ - virtual QValidator::State validate(QString &input, int &pos) const; + QValidator::State validate(QString &input, int &pos) const override; private: QAbstractItemModel *m_model; }; #endif diff --git a/src/kjotsbrowser.cpp b/src/kjotsbrowser.cpp index 69bdf7b..902a5d9 100644 --- a/src/kjotsbrowser.cpp +++ b/src/kjotsbrowser.cpp @@ -1,87 +1,83 @@ // // kjots // // Copyright (C) 1997 Christoph Neerfeld // Copyright (C) 2002, 2003 Aaron J. Seigo // Copyright (C) 2003 Stanislav Kljuhhin // Copyright (C) 2005-2006 Jaison Lee // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. // //Own Header #include "kjotsbrowser.h" #include #include #include #include KJotsBrowser::KJotsBrowser(QItemSelectionModel *selectionModel, QWidget *parent) : QTextBrowser(parent), m_itemSelectionModel(selectionModel) { setWordWrapMode(QTextOption::WordWrap); } -KJotsBrowser::~KJotsBrowser() -{ -} - void KJotsBrowser::delayedInitialization() { connect(this, &KJotsBrowser::anchorClicked, this, &KJotsBrowser::linkClicked); } /*! \brief Handle link clicks. */ void KJotsBrowser::linkClicked(const QUrl &link) { //Stop QTextBrowser from being stupid by giving it an invalid url. QUrl url; setSource(url); QString anchor = link.fragment(); if (link.toString().startsWith(QLatin1String("#")) && (anchor.startsWith(QLatin1String("book_")) || anchor.startsWith(QLatin1String("page_")))) { scrollToAnchor(anchor); return; } if (link.scheme() == QLatin1String("kjots")) { const quint64 targetId = link.path().mid(1).toULongLong(); if (link.host().endsWith(QLatin1String("book"))) { const QModelIndex colIndex = Akonadi::EntityTreeModel::modelIndexForCollection(m_itemSelectionModel->model(), Akonadi::Collection(targetId)); if (!colIndex.isValid()) { return; } m_itemSelectionModel->select(colIndex, QItemSelectionModel::ClearAndSelect); } else { Q_ASSERT(link.host().endsWith(QLatin1String("page"))); const QModelIndexList itemIndexes = Akonadi::EntityTreeModel::modelIndexesForItem(m_itemSelectionModel->model(), Akonadi::Item(targetId)); if (itemIndexes.size() != 1) { return; } m_itemSelectionModel->select(itemIndexes.first(), QItemSelectionModel::ClearAndSelect); } } else { new KRun(link, this); } } /* ex: set tabstop=4 softtabstop=4 shiftwidth=4 expandtab: */ diff --git a/src/kjotsbrowser.h b/src/kjotsbrowser.h index af42d85..607767a 100644 --- a/src/kjotsbrowser.h +++ b/src/kjotsbrowser.h @@ -1,47 +1,46 @@ // // kjots // // Copyright (C) 1997 Christoph Neerfeld // Copyright (C) 2002, 2003 Aaron J. Seigo // Copyright (C) 2003 Stanislav Kljuhhin // Copyright (C) 2005-2006 Jaison Lee // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. // #ifndef KJOTSBROWSER_H #define KJOTSBROWSER_H #include class QItemSelectionModel; class KJotsBrowser : public QTextBrowser { Q_OBJECT public: explicit KJotsBrowser(QItemSelectionModel *selectionModel, QWidget *); - virtual ~KJotsBrowser(); void delayedInitialization(); -protected slots: +protected Q_SLOTS: void linkClicked(const QUrl &); private: QItemSelectionModel *m_itemSelectionModel; }; #endif /* ex: set tabstop=4 softtabstop=4 shiftwidth=4 expandtab: */ diff --git a/src/kjotsconfigdlg.cpp b/src/kjotsconfigdlg.cpp index 6d02c51..301d210 100644 --- a/src/kjotsconfigdlg.cpp +++ b/src/kjotsconfigdlg.cpp @@ -1,81 +1,77 @@ /* Copyright (c) 2009 Montel Laurent This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "kjotsconfigdlg.h" #include #include #include #include KJotsConfigDlg::KJotsConfigDlg(const QString &title, QWidget *parent) : KCMultiDialog(parent) { setWindowTitle(title); setFaceType(KPageDialog::List); setStandardButtons(QDialogButtonBox::Ok | QDialogButtonBox::Cancel | QDialogButtonBox::RestoreDefaults); button(QDialogButtonBox::Ok)->setDefault(true); addModule(QLatin1String("kjots_config_misc")); connect(button(QDialogButtonBox::Ok), &QPushButton::clicked, this, &KJotsConfigDlg::slotOk); } -KJotsConfigDlg::~KJotsConfigDlg() -{ -} - void KJotsConfigDlg::slotOk() { } KJotsConfigMisc::KJotsConfigMisc(QWidget *parent, const QVariantList &args) : KCModule(parent, args) { QHBoxLayout *lay = new QHBoxLayout(this); - miscPage = new confPageMisc(0); + miscPage = new confPageMisc(nullptr); lay->addWidget(miscPage); connect(miscPage->autoSaveInterval, static_cast(&QSpinBox::valueChanged), this, &KJotsConfigMisc::modified); connect(miscPage->autoSave, &QCheckBox::stateChanged, this, &KJotsConfigMisc::modified); load(); } void KJotsConfigMisc::modified() { - emit changed(true); + Q_EMIT changed(true); } void KJotsConfigMisc::load() { KConfig config(QLatin1String("kjotsrc")); KConfigGroup group = config.group("kjots"); miscPage->autoSaveInterval->setValue(group.readEntry("AutoSaveInterval", 5)); miscPage->autoSave->setChecked(group.readEntry("AutoSave", true)); - emit changed(false); + Q_EMIT changed(false); } void KJotsConfigMisc::save() { KConfig config(QLatin1String("kjotsrc")); KConfigGroup group = config.group("kjots"); group.writeEntry("AutoSaveInterval", miscPage->autoSaveInterval->value()); group.writeEntry("AutoSave", miscPage->autoSave->isChecked()); group.sync(); - emit changed(false); + Q_EMIT changed(false); } #include "moc_kjotsconfigdlg.cpp" diff --git a/src/kjotsconfigdlg.h b/src/kjotsconfigdlg.h index 9678396..0a3dfe5 100644 --- a/src/kjotsconfigdlg.h +++ b/src/kjotsconfigdlg.h @@ -1,68 +1,64 @@ /* Copyright (c) 2009 Montel Laurent This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef KJOTSCONFIGDLG_H #define KJOTSCONFIGDLG_H #include #include #include "ui_confpagemisc.h" class confPageMisc : public QWidget, public Ui::confPageMisc { Q_OBJECT public: explicit confPageMisc(QWidget *parent) : QWidget(parent) { setupUi(this); } }; class KJotsConfigMisc : public KCModule { Q_OBJECT public: explicit KJotsConfigMisc(QWidget *parent, const QVariantList &args = QVariantList()); - /** Reimplemented from KCModule. */ - virtual void load(); - - /** Reimplemented form KCModule. */ - virtual void save(); -private slots: + void load() override; + void save() override; +private Q_SLOTS: void modified(); private: confPageMisc *miscPage; }; class KJotsConfigDlg : public KCMultiDialog { Q_OBJECT public: KJotsConfigDlg(const QString &title, QWidget *parent); - ~KJotsConfigDlg(); -public slots: +public Q_SLOTS: void slotOk(); }; #endif /* KJOTSCONFIGDLG_H */ diff --git a/src/kjotsedit.cpp b/src/kjotsedit.cpp index 2b9dddf..c7d946f 100644 --- a/src/kjotsedit.cpp +++ b/src/kjotsedit.cpp @@ -1,424 +1,421 @@ // // kjots // // Copyright (C) 1997 Christoph Neerfeld // Copyright (C) 2002, 2003 Aaron J. Seigo // Copyright (C) 2003 Stanislav Kljuhhin // Copyright (C) 2005-2006 Jaison Lee // Copyright (C) 2007-2008 Stephen Kelly // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. // //Own Header #include "kjotsedit.h" #include #include #include #include #include #include #include #include #include #include #include //#include #include "kjotslinkdialog.h" #include #include #include #include #include "kjotsmodel.h" #include "noteshared/notelockattribute.h" #include "noteshared/noteeditorutils.h" Q_DECLARE_METATYPE(QTextDocument *) Q_DECLARE_METATYPE(QTextCursor) using namespace Akonadi; KJotsEdit::KJotsEdit(QItemSelectionModel *selectionModel, QWidget *parent) : KRichTextWidget(parent), - actionCollection(0), + actionCollection(nullptr), allowAutoDecimal(false), m_selectionModel(selectionModel) { setAcceptRichText(true); setWordWrapMode(QTextOption::WordWrap); setCheckSpellingEnabled(true); setRichTextSupport(FullTextFormattingSupport | FullListSupport | SupportAlignment | SupportRuleLine | SupportFormatPainting); setFocusPolicy(Qt::StrongFocus); connect(m_selectionModel, &QItemSelectionModel::selectionChanged, this, &KJotsEdit::selectionChanged); connect(m_selectionModel->model(), SIGNAL(dataChanged(QModelIndex,QModelIndex)), SLOT(tryDisableEditing())); } -KJotsEdit::~KJotsEdit() -{ -} - void KJotsEdit::mousePopupMenuImplementation(const QPoint &pos) { QMenu *popup = mousePopupMenu(); if (popup) { popup->addSeparator(); QAction *act = actionCollection->action(QLatin1String("copyIntoTitle")); popup->addAction(act); act = actionCollection->action(QLatin1String("insert_checkmark")); act->setEnabled(!isReadOnly()); popup->addAction(act); if (!qApp->clipboard()->text().isEmpty()) { act = actionCollection->action(QLatin1String("paste_plain_text")); act->setEnabled(!isReadOnly()); popup->addAction(act); } aboutToShowContextMenu(popup); popup->exec(pos); delete popup; } } void KJotsEdit::delayedInitialization(KActionCollection *collection) { actionCollection = collection; connect(actionCollection->action(QLatin1String("auto_bullet")), SIGNAL(triggered()), SLOT(onAutoBullet())); connect(actionCollection->action(QLatin1String("auto_decimal")), SIGNAL(triggered()), SLOT(onAutoDecimal())); //auto decimal list connect(actionCollection->action(QLatin1String("manage_link")), SIGNAL(triggered()), SLOT(onLinkify())); connect(actionCollection->action(QLatin1String("insert_checkmark")), SIGNAL(triggered()), SLOT(addCheckmark())); connect(actionCollection->action(QLatin1String("manual_save")), SIGNAL(triggered()), SLOT(savePage())); connect(actionCollection->action(QLatin1String("insert_date")), SIGNAL(triggered()), SLOT(insertDate())); connect(actionCollection->action(QLatin1String("insert_image")), SIGNAL(triggered()), SLOT(insertImage())); } void KJotsEdit::insertDate() { NoteShared::NoteEditorUtils().insertDate(this); } void KJotsEdit::insertImage() { QTextCursor cursor = textCursor(); NoteShared::NoteEditorUtils().insertImage(document(), cursor, this); } void KJotsEdit::selectionChanged(const QItemSelection &selected, const QItemSelection &deselected) { Q_UNUSED(selected) Q_UNUSED(deselected) tryDisableEditing(); } void KJotsEdit::tryDisableEditing() { if (!m_selectionModel->hasSelection()) { return setReadOnly(true); } QModelIndexList list = m_selectionModel->selectedRows(); if (list.size() != 1) { return setReadOnly(true); } Item item = list.first().data(EntityTreeModel::ItemRole).value(); if (!item.isValid()) { return setReadOnly(true); } if (item.hasAttribute()) { return setReadOnly(true); } setReadOnly(false); } void KJotsEdit::onBookshelfSelection(void) { // TODO: PORT. Review and remove. Possibly keep the bug workaround. #if 0 QList selection = bookshelf->selectedItems(); int selectionSize = selection.size(); if (selectionSize != 1) { disableEditing(); } else { KJotsPage *newPage = dynamic_cast(selection[0]); if (!newPage) { disableEditing(); } else { setEnabled(newPage->isEditable()); setReadOnly(!newPage->isEditable()); if (currentPage != newPage) { if (currentPage) { currentPage->setCursor(textCursor()); } currentPage = newPage; setDocument(currentPage->body()); if (!currentPage->getCursor().isNull()) { setTextCursor(currentPage->getCursor()); } QStackedWidget *stack = static_cast(parent()); stack->setCurrentWidget(this); setFocus(); if (textCursor().atStart()) { // Reflect formatting when switching pages and the first word is formatted // Work-around for qrextedit bug. The format does not seem to exist // before the first character. Submitted to qt-bugs, id 192886. moveCursor(QTextCursor::Right); moveCursor(QTextCursor::Left); } } } } #endif } void KJotsEdit::onAutoBullet(void) { KTextEdit::AutoFormatting currentFormatting = autoFormatting(); //TODO: set line spacing properly. if (currentFormatting == KTextEdit::AutoBulletList) { setAutoFormatting(KTextEdit::AutoNone); actionCollection->action(QLatin1String("auto_bullet"))->setChecked(false); } else { setAutoFormatting(KTextEdit::AutoBulletList); actionCollection->action(QLatin1String("auto_bullet"))->setChecked(true); } } void KJotsEdit::createAutoDecimalList(void) { //this is an adaptation of Qt's createAutoBulletList() function for creating a bulleted list, except in this case I use it to create a decimal list. QTextCursor cursor = textCursor(); cursor.beginEditBlock(); QTextBlockFormat blockFmt = cursor.blockFormat(); QTextListFormat listFmt; listFmt.setStyle(QTextListFormat::ListDecimal); listFmt.setIndent(blockFmt.indent() + 1); blockFmt.setIndent(0); cursor.setBlockFormat(blockFmt); cursor.createList(listFmt); cursor.endEditBlock(); setTextCursor(cursor); } void KJotsEdit::DecimalList(void) { QTextCursor cursor = textCursor(); if (cursor.currentList()) { return; } QString blockText = cursor.block().text(); if (blockText.length() == 2 && blockText == QLatin1String("1.")) { cursor.movePosition(QTextCursor::StartOfLine, QTextCursor::KeepAnchor); cursor.removeSelectedText(); createAutoDecimalList(); } } void KJotsEdit::onAutoDecimal(void) { if (allowAutoDecimal == true) { allowAutoDecimal = false; disconnect(this, &KJotsEdit::textChanged, this, &KJotsEdit::DecimalList); actionCollection->action(QLatin1String("auto_decimal"))->setChecked(false); } else { allowAutoDecimal = true; connect(this, &KJotsEdit::textChanged, this, &KJotsEdit::DecimalList); actionCollection->action(QLatin1String("auto_decimal"))->setChecked(true); } } void KJotsEdit::onLinkify(void) { selectLinkText(); QPointer linkDialog = new KJotsLinkDialog(const_cast(m_selectionModel->model()), this); linkDialog->setLinkText(currentLinkText()); linkDialog->setLinkUrl(currentLinkUrl()); if (linkDialog->exec()) { updateLink(linkDialog->linkUrl(), linkDialog->linkText()); } delete linkDialog; } void KJotsEdit::addCheckmark(void) { QTextCursor cursor = textCursor(); NoteShared::NoteEditorUtils().addCheckmark(cursor); } bool KJotsEdit::canInsertFromMimeData(const QMimeData *source) const { if (source->formats().contains(QLatin1String("kjots/internal_link"))) { return true; } else if (source->hasUrls()) { return true; } else { return KTextEdit::canInsertFromMimeData(source); } } void KJotsEdit::insertFromMimeData(const QMimeData *source) { if (source->formats().contains(QLatin1String("kjots/internal_link"))) { insertHtml(QLatin1String(source->data(QLatin1String("kjots/internal_link")))); } else if (source->hasUrls()) { - foreach (const QUrl &url, source->urls()) { + const QList urls = source->urls(); + for (const QUrl &url : urls) { if (url.isValid()) { QString html = QString::fromLatin1("%2 ") .arg(QString::fromUtf8(url.toEncoded())) .arg(url.toString(QUrl::RemovePassword)); insertHtml(html); } } } else if (source->hasHtml()) { // Don't have an action to set top and bottom margins on paragraphs yet. // Remove the margins for all inserted html. // qDebug() << source->html(); QString str = source->html(); int styleBegin = 0; while ((styleBegin = str.indexOf(QLatin1String("style=\""), styleBegin, Qt::CaseInsensitive) + 7) != (-1 + 7)) { int styleEnd = str.indexOf(QLatin1Char('"'), styleBegin); int styleFragmentStart = styleBegin; int styleFragmentEnd = styleBegin; while ((styleFragmentEnd = str.indexOf(QLatin1String(";"), styleFragmentEnd) + 1) != (-1 + 1)) { if (styleFragmentEnd > styleEnd) { break; } int fragmentLength = styleFragmentEnd - styleFragmentStart; if (str.mid(styleFragmentStart, fragmentLength).contains(QLatin1String("margin"), Qt::CaseInsensitive)) { str.remove(styleFragmentStart, fragmentLength); styleEnd -= fragmentLength; styleFragmentEnd = styleFragmentStart; if (styleBegin == styleEnd) { str.remove(styleBegin - 7, 7 + 1); // remove the now empty style attribute. } } else { styleFragmentStart = styleFragmentEnd; } } styleBegin = styleEnd; } // qDebug() << str; insertHtml(str); } else { KTextEdit::insertFromMimeData(source); } } void KJotsEdit::mouseReleaseEvent(QMouseEvent *event) { // TODO: PORT #if 0 if ((event->modifiers() & Qt::ControlModifier) && (event->button() & Qt::LeftButton) && !anchorAt(event->pos()).isEmpty()) { QUrl anchor(anchorAt(event->pos())); if (anchor.scheme() == "kjots") { quint64 target = anchor.path().mid(1).toULongLong(); bookshelf->jumpToId(target); } else { new KRun(anchor, this); } } #endif KTextEdit::mouseReleaseEvent(event); } void KJotsEdit::pastePlainText() { QString text = qApp->clipboard()->text(); if (!text.isEmpty()) { insertPlainText(text); } } bool KJotsEdit::event(QEvent *event) { if (event->type() == QEvent::WindowDeactivate) { savePage(); } return KRichTextWidget::event(event); } void KJotsEdit::focusOutEvent(QFocusEvent *event) { savePage(); KRichTextWidget::focusOutEvent(event); } void KJotsEdit::savePage() { if (!document()->isModified()) { return; } QModelIndexList rows = m_selectionModel->selectedRows(); if (rows.size() != 1) { return; } QModelIndex index = rows.at(0); Item item = index.data(EntityTreeModel::ItemRole).value(); if (!item.isValid()) { return; } if (!item.hasPayload()) { return; } QAbstractItemModel *model = const_cast(m_selectionModel->model()); document()->setModified(false); document()->setProperty("textCursor", QVariant::fromValue(textCursor())); model->setData(index, QVariant::fromValue(document()), KJotsModel::DocumentRole); } /* ex: set tabstop=4 softtabstop=4 shiftwidth=4 expandtab: */ diff --git a/src/kjotsedit.h b/src/kjotsedit.h index 39b5128..ebd7588 100644 --- a/src/kjotsedit.h +++ b/src/kjotsedit.h @@ -1,79 +1,78 @@ // // kjots // // Copyright (C) 1997 Christoph Neerfeld // Copyright (C) 2002, 2003 Aaron J. Seigo // Copyright (C) 2003 Stanislav Kljuhhin // Copyright (C) 2005-2006 Jaison Lee // Copyright (C) 2007-2008 Stephen Kelly // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. // #ifndef KJOTSEDIT_H #define KJOTSEDIT_H #include class QItemSelection; class QItemSelectionModel; class KActionCollection; class KJotsEdit : public KRichTextWidget { Q_OBJECT public: explicit KJotsEdit(QItemSelectionModel *selectionModel, QWidget *); - virtual ~KJotsEdit(); void delayedInitialization(KActionCollection *); - virtual bool canInsertFromMimeData(const QMimeData *) const; - virtual void insertFromMimeData(const QMimeData *); + bool canInsertFromMimeData(const QMimeData *) const override; + void insertFromMimeData(const QMimeData *) override; protected: /** Override to make ctrl+click follow links */ - virtual void mouseReleaseEvent(QMouseEvent *); + void mouseReleaseEvent(QMouseEvent *) override; - virtual void focusOutEvent(QFocusEvent *); + void focusOutEvent(QFocusEvent *) override; - virtual bool event(QEvent *event); + bool event(QEvent *event) override; -public slots: +public Q_SLOTS: void mousePopupMenuImplementation(const QPoint &pos); void selectionChanged(const QItemSelection &selected, const QItemSelection &deselected); void tryDisableEditing(); void onBookshelfSelection(void); void onAutoBullet(void); void onLinkify(void); void addCheckmark(void); void onAutoDecimal(void); void DecimalList(void); void pastePlainText(void); void savePage(); void insertDate(); void insertImage(); private: void createAutoDecimalList(); KActionCollection *actionCollection; bool allowAutoDecimal; QItemSelectionModel *m_selectionModel; }; #endif // __KJOTSEDIT_H /* ex: set tabstop=4 softtabstop=4 shiftwidth=4 expandtab: */ diff --git a/src/kjotslinkdialog.h b/src/kjotslinkdialog.h index 23500bc..574231a 100644 --- a/src/kjotslinkdialog.h +++ b/src/kjotslinkdialog.h @@ -1,81 +1,81 @@ // // kjots // // Copyright (C) 2008 Stephen Kelly // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. // #ifndef KJOTSLINKDIALOG_H #define KJOTSLINKDIALOG_H #include class QLabel; class QAbstractItemModel; class QString; class QRadioButton; class QTreeView; class QComboBox; class QLineEdit; class KJotsLinkDialog : public QDialog { Q_OBJECT public: - explicit KJotsLinkDialog(QAbstractItemModel *kjotsModel, QWidget *parent = 0); + explicit KJotsLinkDialog(QAbstractItemModel *kjotsModel, QWidget *parent = nullptr); /** * Returns the link text shown in the dialog * @param linkText The initial text */ void setLinkText(const QString &linkText); /** * Sets the target link url shown in the dialog * @param linkUrl The initial link target url */ void setLinkUrl(const QString &linkUrl); /** * Returns the link text entered by the user. * @return The link text */ QString linkText() const; /** * Returns the target link url entered by the user. * @return The link url */ QString linkUrl() const; -public slots: +public Q_SLOTS: void trySetEntry(const QString &text); private: QLabel *textLabel; QLineEdit *textLineEdit; QLabel *linkUrlLabel; QLineEdit *linkUrlLineEdit; QComboBox *hrefCombo; QRadioButton *linkUrlLineEditRadioButton; QRadioButton *hrefComboRadioButton; QTreeView *tree; QAbstractItemModel *m_kjotsModel; QAbstractItemModel *m_descendantsProxyModel; }; #endif diff --git a/src/kjotslockjob.cpp b/src/kjotslockjob.cpp index 2cd49bd..d4d70a6 100644 --- a/src/kjotslockjob.cpp +++ b/src/kjotslockjob.cpp @@ -1,74 +1,69 @@ /* Copyright (C) 2010 Klarälvdalens Datakonsult AB, a KDAB Group company, info@kdab.net, author Stephen Kelly This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "kjotslockjob.h" #include #include #include "noteshared/notelockattribute.h" KJotsLockJob::KJotsLockJob(const Akonadi::Collection::List &collections, const Akonadi::Item::List &items, KJotsLockJob::Type type, QObject *parent) : Job(parent), m_collections(collections), m_items(items), m_type(type) { } KJotsLockJob::KJotsLockJob(const Akonadi::Collection::List &collections, const Akonadi::Item::List &items, QObject *parent) : Job(parent), m_collections(collections), m_items(items), m_type(LockJob) { } -KJotsLockJob::~KJotsLockJob() -{ - -} - void KJotsLockJob::doStart() { - foreach (const Akonadi::Collection &_col, m_collections) { + for (const Akonadi::Collection &_col : qAsConst(m_collections)) { Akonadi::Collection col = _col; if (m_type == LockJob) { col.addAttribute(new NoteShared::NoteLockAttribute()); } else { col.removeAttribute(); } new Akonadi::CollectionModifyJob(col, this); } - foreach (const Akonadi::Item &_item, m_items) { + for (const Akonadi::Item &_item : qAsConst(m_items)) { Akonadi::Item item = _item; if (m_type == LockJob) { item.addAttribute(new NoteShared::NoteLockAttribute()); } else { item.removeAttribute(); } new Akonadi::ItemModifyJob(item, this); } } void KJotsLockJob::slotResult(KJob *job) { Akonadi::Job::slotResult(job); if (!hasSubjobs()) { emitResult(); } } diff --git a/src/kjotslockjob.h b/src/kjotslockjob.h index 766f4a9..e1f6254 100644 --- a/src/kjotslockjob.h +++ b/src/kjotslockjob.h @@ -1,55 +1,52 @@ /* Copyright (C) 2010 Klarälvdalens Datakonsult AB, a KDAB Group company, info@kdab.net, author Stephen Kelly This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef KJOTS_LOCK_JOB_H #define KJOTS_LOCK_JOB_H #include #include #include class KJotsLockJob : Akonadi::Job { Q_OBJECT public: enum Type { LockJob, UnlockJob }; - KJotsLockJob(const Akonadi::Collection::List &collections, const Akonadi::Item::List &items, Type type = LockJob, QObject *parent = 0); - KJotsLockJob(const Akonadi::Collection::List &collections, const Akonadi::Item::List &items, QObject *parent = 0); - - ~KJotsLockJob(); - + explicit KJotsLockJob(const Akonadi::Collection::List &collections, const Akonadi::Item::List &items, Type type = LockJob, QObject *parent = nullptr); + explicit KJotsLockJob(const Akonadi::Collection::List &collections, const Akonadi::Item::List &items, QObject *parent = nullptr); protected: - virtual void doStart(); + void doStart() override; protected Q_SLOTS: - virtual void slotResult(KJob *job); + void slotResult(KJob *job) override; private: Akonadi::Collection::List m_collections; Akonadi::Item::List m_items; Type m_type; }; #endif diff --git a/src/kjotsmodel.h b/src/kjotsmodel.h index 72aa40b..650429c 100644 --- a/src/kjotsmodel.h +++ b/src/kjotsmodel.h @@ -1,103 +1,103 @@ /* This file is part of KJots. Copyright (c) 2009 Stephen Kelly This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef KJOTSMODEL_H #define KJOTSMODEL_H #include class QTextDocument; namespace Akonadi { class ChangeRecorder; } using namespace Akonadi; /** * A wrapper QObject making some book and page properties available to Grantlee. */ class KJotsEntity : public QObject { Q_OBJECT Q_PROPERTY(QString title READ title) Q_PROPERTY(QString content READ content) Q_PROPERTY(QString plainContent READ plainContent) Q_PROPERTY(qint64 entityId READ entityId) Q_PROPERTY(bool isBook READ isBook) Q_PROPERTY(bool isPage READ isPage) Q_PROPERTY(QVariantList entities READ entities) Q_PROPERTY(QVariantList breadcrumbs READ breadcrumbs) public: - explicit KJotsEntity(const QModelIndex &index, QObject *parent = 0); + explicit KJotsEntity(const QModelIndex &index, QObject *parent = nullptr); void setIndex(const QModelIndex &index); bool isBook() const; bool isPage() const; QString title() const; QString content() const; QString plainContent() const; qint64 entityId() const; QVariantList entities() const; QVariantList breadcrumbs() const; private: QPersistentModelIndex m_index; }; class KJotsModel : public EntityTreeModel { Q_OBJECT public: - explicit KJotsModel(ChangeRecorder *monitor, QObject *parent = 0); - virtual ~KJotsModel(); + explicit KJotsModel(ChangeRecorder *monitor, QObject *parent = nullptr); + ~KJotsModel() override; enum KJotsRoles { GrantleeObjectRole = EntityTreeModel::UserRole, DocumentRole, DocumentCursorPositionRole }; // We don't reimplement the Collection overload. using EntityTreeModel::entityData; - virtual QVariant entityData(const Akonadi::Item &item, int column, int role = Qt::DisplayRole) const; + QVariant entityData(const Akonadi::Item &item, int column, int role = Qt::DisplayRole) const override; - QVariant data(const QModelIndex &index, int role) const; + QVariant data(const QModelIndex &index, int role) const override; - virtual bool setData(const QModelIndex &index, const QVariant &value, int role = Qt::EditRole); + bool setData(const QModelIndex &index, const QVariant &value, int role = Qt::EditRole) override; private: QHash m_colors; mutable QHash m_documents; QHash m_cursorPositions; }; #endif diff --git a/src/kjotspart.h b/src/kjotspart.h index ef98c15..140ee1a 100644 --- a/src/kjotspart.h +++ b/src/kjotspart.h @@ -1,75 +1,75 @@ /* This file is part of KJots. Copyright (c) 2008 Stephen Kelly This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. As a special exception, permission is given to link this program with any edition of Qt, and distribute the resulting executable, without including the source code for Qt in the source distribution. */ #ifndef KJOTSPART_H #define KJOTSPART_H #include #include class QWidget; class KAboutData; class KJotsWidget; /** * This is a "Part". It that does all the real work in a KPart * application. * * @short Main Part * @author Stephen Kelly * @version 0.1 */ class KJotsPart : public KParts::ReadOnlyPart { Q_OBJECT public: /** * Default constructor */ KJotsPart(QWidget *parentWidget, QObject *parent, const QVariantList &); /** * Destructor */ - virtual ~KJotsPart(); + ~KJotsPart() override; static KAboutData *createAboutData(); protected: /** * This must be implemented by each part */ - virtual bool openFile(); + bool openFile() override; protected Q_SLOTS: void delayedInitialization(); void activeAnchorChanged(const QString &, const QString &); private: void initAction(); KJotsWidget *mComponent; KParts::StatusBarExtension *mStatusBar; }; #endif // KJOTSPART_H diff --git a/src/kjotsreplacenextdialog.h b/src/kjotsreplacenextdialog.h index 7f24563..721aecf 100644 --- a/src/kjotsreplacenextdialog.h +++ b/src/kjotsreplacenextdialog.h @@ -1,57 +1,57 @@ // // kjots // // Copyright (C) 2008 Stephen Kelly // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. // #ifndef KJOTSREPLACENEXTDIALOG_H #define KJOTSREPLACENEXTDIALOG_H #include class QString; class QLabel; // Mostly stolen from kdelibs/kdeui/findreplace/kreplace.cpp class KJotsReplaceNextDialog : public QDialog { Q_OBJECT public: enum Answer { All, Skip, Replace, Close }; explicit KJotsReplaceNextDialog(QWidget *parent); void setLabel(const QString &pattern, const QString &replacement); Answer answer() const { return m_answer; } -protected slots: +protected Q_SLOTS: void onHandleAll(void); void onHandleSkip(void); void onHandleReplace(void); private: QLabel *m_mainLabel; Answer m_answer; }; #endif diff --git a/src/kjotssortproxymodel.cpp b/src/kjotssortproxymodel.cpp index db4ad1f..3cf8277 100644 --- a/src/kjotssortproxymodel.cpp +++ b/src/kjotssortproxymodel.cpp @@ -1,99 +1,94 @@ /* This file is part of KJots. Copyright (c) 2010 Stephen Kelly This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "kjotssortproxymodel.h" #include #include KJotsSortProxyModel::KJotsSortProxyModel(QObject *parent) : QSortFilterProxyModel(parent) { setDynamicSortFilter(true); } -KJotsSortProxyModel::~KJotsSortProxyModel() -{ - -} - bool KJotsSortProxyModel::lessThan(const QModelIndex &left, const QModelIndex &right) const { const Akonadi::Collection::Id colId = left.data(Akonadi::EntityTreeModel::ParentCollectionRole).value().id(); if (colId < 0 || m_alphaSorted.contains(colId) || !m_dateTimeSorted.contains(colId)) { return QSortFilterProxyModel::lessThan(left, right); } const Akonadi::Item leftItem = left.data(Akonadi::EntityTreeModel::ItemRole).value(); const Akonadi::Item rightItem = right.data(Akonadi::EntityTreeModel::ItemRole).value(); if (!leftItem.isValid() || !rightItem.isValid()) { return true; } const KMime::Message::Ptr leftNote = leftItem.payload(); const KMime::Message::Ptr rightNote = rightItem.payload(); return leftNote->date()->dateTime() < rightNote->date()->dateTime(); } Akonadi::Collection::Id KJotsSortProxyModel::collectionId(const QModelIndex &parent) const { const QModelIndex childIndex = index(0, 0, parent); if (!childIndex.isValid()) { return -1; } const Akonadi::Collection collection = childIndex.data(Akonadi::EntityTreeModel::ParentCollectionRole).value(); if (!collection.isValid()) { return -1; } return collection.id(); } void KJotsSortProxyModel::sortChildrenAlphabetically(const QModelIndex &parent) { const Akonadi::Collection::Id id = collectionId(parent); if (id < 0) { return; } m_dateTimeSorted.remove(id); m_alphaSorted.insert(id); invalidate(); } void KJotsSortProxyModel::sortChildrenByCreationTime(const QModelIndex &parent) { const Akonadi::Collection::Id id = collectionId(parent); if (id < 0) { return; } m_alphaSorted.remove(id); m_dateTimeSorted.insert(id); invalidate(); } diff --git a/src/kjotssortproxymodel.h b/src/kjotssortproxymodel.h index 721010a..653a09c 100644 --- a/src/kjotssortproxymodel.h +++ b/src/kjotssortproxymodel.h @@ -1,50 +1,49 @@ /* This file is part of KJots. Copyright (c) 2010 Stephen Kelly This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef KJOTSSORTPROXYMODEL_H #define KJOTSSORTPROXYMODEL_H #include #include class KJotsSortProxyModel : public QSortFilterProxyModel { Q_OBJECT public: - explicit KJotsSortProxyModel(QObject *parent = 0); - ~KJotsSortProxyModel(); + explicit KJotsSortProxyModel(QObject *parent = nullptr); void sortChildrenAlphabetically(const QModelIndex &parent); void sortChildrenByCreationTime(const QModelIndex &parent); protected: - virtual bool lessThan(const QModelIndex &left, const QModelIndex &right) const; + bool lessThan(const QModelIndex &left, const QModelIndex &right) const override; private: Akonadi::Collection::Id collectionId(const QModelIndex &parent) const; private: QSet m_alphaSorted; QSet m_dateTimeSorted; }; #endif diff --git a/src/kjotstreeview.cpp b/src/kjotstreeview.cpp index 9886a39..520a127 100644 --- a/src/kjotstreeview.cpp +++ b/src/kjotstreeview.cpp @@ -1,222 +1,221 @@ /* This file is part of KJots. Copyright (c) 2009 Stephen Kelly This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "kjotstreeview.h" #include "kjotsmodel.h" #include #include #include #include #include #include #include #include #include #include #include using namespace Akonadi; KJotsTreeView::KJotsTreeView(KXMLGUIClient *xmlGuiClient, QWidget *parent) : EntityTreeView(xmlGuiClient, parent), m_xmlGuiClient(xmlGuiClient) { } void KJotsTreeView::contextMenuEvent(QContextMenuEvent *event) { QMenu *popup = new QMenu(this); QModelIndexList rows = selectionModel()->selectedRows(); const bool noselection = rows.isEmpty(); const bool singleselection = rows.size() == 1; const bool multiselection = rows.size() > 1; popup->addAction(m_xmlGuiClient->actionCollection()->action(QLatin1String("new_book"))); if (singleselection) { popup->addAction(m_xmlGuiClient->actionCollection()->action(QLatin1String("new_page"))); popup->addAction(m_xmlGuiClient->actionCollection()->action(QLatin1String("rename_entry"))); popup->addAction(m_xmlGuiClient->actionCollection()->action(QLatin1String("copy_link_address"))); popup->addAction(m_xmlGuiClient->actionCollection()->action(QLatin1String("change_color"))); popup->addAction(m_xmlGuiClient->actionCollection()->action(QLatin1String("sort_children_alpha"))); popup->addAction(m_xmlGuiClient->actionCollection()->action(QLatin1String("sort_children_by_date"))); } if (!noselection) { popup->addAction(m_xmlGuiClient->actionCollection()->action(QLatin1String("save_to"))); } popup->addSeparator(); popup->addAction(m_xmlGuiClient->actionCollection()->action(QLatin1String("lock"))); popup->addAction(m_xmlGuiClient->actionCollection()->action(QLatin1String("unlock"))); if (singleselection) { Item item = rows.at(0).data(KJotsModel::ItemRole).value(); if (item.isValid()) { popup->addAction(m_xmlGuiClient->actionCollection()->action(QLatin1String("del_page"))); } else { popup->addAction(m_xmlGuiClient->actionCollection()->action(QLatin1String("del_folder"))); } } if (multiselection) { popup->addAction(m_xmlGuiClient->actionCollection()->action(QLatin1String("del_mult"))); } popup->exec(event->globalPos()); delete popup; } void KJotsTreeView::delayedInitialization() { connect(m_xmlGuiClient->actionCollection()->action(QLatin1String("rename_entry")), &QAction::triggered, this, &KJotsTreeView::renameEntry); connect(m_xmlGuiClient->actionCollection()->action(QLatin1String("copy_link_address")), &QAction::triggered, this, &KJotsTreeView::copyLinkAddress); connect(m_xmlGuiClient->actionCollection()->action(QLatin1String("change_color")), &QAction::triggered, this, &KJotsTreeView::changeColor); } QString KJotsTreeView::captionForSelection(const QString &sep) const { QString caption; QModelIndexList selection = selectionModel()->selectedRows(); int selectionSize = selection.size(); if (selectionSize > 1) { caption = i18n("Multiple selections"); } else if (selectionSize == 1) { QModelIndex index = selection.at(0); while (index.isValid()) { QModelIndex parentBook = index.parent(); if (parentBook.isValid()) { caption = sep + index.data().toString() + caption; } else { caption = index.data().toString() + caption; } index = parentBook; } } return caption; } void KJotsTreeView::renameEntry() { QModelIndexList rows = selectionModel()->selectedRows(); if (rows.size() != 1) { return; } QModelIndex idx = rows.at(0); QString title = idx.data().toString(); Item item = idx.data(KJotsModel::ItemRole).value(); if (item.isValid()) { Q_ASSERT(item.hasPayload()); if (!item.hasPayload()) { return; } bool ok; const QString name = QInputDialog::getText(this, i18n("Rename Page"), i18n("Page title:"), QLineEdit::Normal, title, &ok); if (ok) { model()->setData(idx, name, Qt::EditRole); } return; } Collection col = idx.data(KJotsModel::CollectionRole).value(); Q_ASSERT(col.isValid()); if (!col.isValid()) { return; } bool ok; const QString name = QInputDialog::getText(this, i18n("Rename Book"), i18n("Book name:"), QLineEdit::Normal, title, &ok); if (ok) { model()->setData(idx, name, Qt::EditRole); } } void KJotsTreeView::copyLinkAddress() { QModelIndexList rows = selectionModel()->selectedRows(); if (rows.size() != 1) { return; } QModelIndex idx = rows.at(0); QString title = idx.data().toString(); Item item = idx.data(KJotsModel::ItemRole).value(); QMimeData *mimeData = new QMimeData(); QString link; if (item.isValid()) { Q_ASSERT(item.hasPayload()); if (!item.hasPayload()) { return; } link = QString::fromLatin1("%2").arg(item.url().url()).arg(title); } else { Collection col = idx.data(KJotsModel::CollectionRole).value(); Q_ASSERT(col.isValid()); if (!col.isValid()) { return; } link = QString::fromLatin1("%2").arg(col.url().url()).arg(title); } mimeData->setData(QLatin1String("kjots/internal_link"), link.toUtf8()); mimeData->setText(title); QApplication::clipboard()->setMimeData(mimeData); } void KJotsTreeView::changeColor() { QColor myColor; myColor = QColorDialog::getColor(); if (myColor.isValid()) { - QModelIndexList rows = selectionModel()->selectedRows(); - - foreach (const QModelIndex &idx, rows) { + const QModelIndexList rows = selectionModel()->selectedRows(); + for (const QModelIndex &idx : rows) { model()->setData(idx, myColor, Qt::BackgroundRole); } } } diff --git a/src/kjotstreeview.h b/src/kjotstreeview.h index 7475602..c8fd255 100644 --- a/src/kjotstreeview.h +++ b/src/kjotstreeview.h @@ -1,51 +1,51 @@ /* This file is part of KJots. Copyright (c) 2009 Stephen Kelly This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef KJOTSTREEVIEW_H #define KJOTSTREEVIEW_H #include class KXMLGUIClient; class KJotsTreeView : public Akonadi::EntityTreeView { Q_OBJECT public: - explicit KJotsTreeView(KXMLGUIClient *xmlGuiClient, QWidget *parent = 0); + explicit KJotsTreeView(KXMLGUIClient *xmlGuiClient, QWidget *parent = nullptr); void delayedInitialization(); QString captionForSelection(const QString &sep) const; protected: - virtual void contextMenuEvent(QContextMenuEvent *event); + void contextMenuEvent(QContextMenuEvent *event) override; -protected slots: +protected Q_SLOTS: void renameEntry(); void copyLinkAddress(); void changeColor(); private: KXMLGUIClient *m_xmlGuiClient; }; #endif diff --git a/src/kjotswidget.cpp b/src/kjotswidget.cpp index e343bbd..9609b7d 100644 --- a/src/kjotswidget.cpp +++ b/src/kjotswidget.cpp @@ -1,1874 +1,1874 @@ /* This file is part of KJots. Copyright (C) 1997 Christoph Neerfeld Copyright (C) 2002, 2003 Aaron J. Seigo Copyright (C) 2003 Stanislav Kljuhhin Copyright (C) 2005-2006 Jaison Lee Copyright (C) 2007-2009 Stephen Kelly This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "kjotswidget.h" // Qt #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include // Akonadi #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "akonadi_next/note.h" #include "akonadi_next/notecreatorandselector.h" // Grantlee #include #include #include // KDE #include #include #include #include #include #include #include #include #include #include #include #include #include // KMime #include // KJots #include "kjotsbookmarks.h" #include "kjotssortproxymodel.h" #include "kjotsmodel.h" #include "kjotsedit.h" #include "kjotstreeview.h" #include "kjotsconfigdlg.h" #include "kjotsreplacenextdialog.h" #include "KJotsSettings.h" #include "kjotslockjob.h" #include "kjotsbrowser.h" #include "noteshared/notelockattribute.h" #include "localresourcecreator.h" #include Q_DECLARE_METATYPE(QTextDocument *) Q_DECLARE_METATYPE(QTextCursor) using namespace Akonadi; using namespace Grantlee; KJotsWidget::KJotsWidget(QWidget *parent, KXMLGUIClient *xmlGuiClient, Qt::WindowFlags f) : QWidget(parent, f), m_xmlGuiClient(xmlGuiClient) { Akonadi::ControlGui::widgetNeedsAkonadi(this); KConfigGroup migrationCfg(KSharedConfig::openConfig(), "General"); const bool autoCreate = migrationCfg.readEntry("AutoCreateResourceOnStart", true); migrationCfg.writeEntry("AutoCreateResourceOnStart", autoCreate); migrationCfg.sync(); if (autoCreate) { LocalResourceCreator *creator = new LocalResourceCreator(this); creator->createIfMissing(); } m_splitter = new QSplitter(this); m_splitter->setStretchFactor(1, 1); // I think we can live without this //m_splitter->setOpaqueResize(KGlobalSettings::opaqueResize()); QHBoxLayout *layout = new QHBoxLayout(this); layout->setMargin(0); m_templateEngine = new Engine(this); // We don't have custom plugins, so this should not be needed //m_templateEngine->setPluginPaths(KStd.findDirs("lib", QString())); m_loader = QSharedPointer(new FileSystemTemplateLoader()); m_loader->setTemplateDirs(QStandardPaths::locateAll(QStandardPaths::GenericDataLocation, QStringLiteral("kjots/themes"), QStandardPaths::LocateDirectory)); m_loader->setTheme(QLatin1String("default")); m_templateEngine->addTemplateLoader(m_loader); treeview = new KJotsTreeView(xmlGuiClient, m_splitter); ItemFetchScope scope; scope.fetchFullPayload(true); // Need to have full item when adding it to the internal data structure scope.fetchAttribute< EntityDisplayAttribute >(); scope.fetchAttribute< NoteShared::NoteLockAttribute >(); ChangeRecorder *monitor = new ChangeRecorder(this); monitor->fetchCollection(true); monitor->setItemFetchScope(scope); monitor->setCollectionMonitored(Collection::root()); monitor->setMimeTypeMonitored(Akonotes::Note::mimeType()); m_kjotsModel = new KJotsModel(monitor, this); m_sortProxyModel = new KJotsSortProxyModel(this); m_sortProxyModel->setSourceModel(m_kjotsModel); m_orderProxy = new EntityOrderProxyModel(this); m_orderProxy->setSourceModel(m_sortProxyModel); KConfigGroup cfg(KSharedConfig::openConfig(), "KJotsEntityOrder"); m_orderProxy->setOrderConfig(cfg); treeview->setModel(m_orderProxy); treeview->setSelectionMode(QAbstractItemView::ExtendedSelection); treeview->setEditTriggers(QAbstractItemView::DoubleClicked); connect(treeview->selectionModel(), SIGNAL(selectionChanged(QItemSelection,QItemSelection)), SLOT(selectionChanged(QItemSelection,QItemSelection))); selProxy = new KSelectionProxyModel(treeview->selectionModel(), this); selProxy->setSourceModel(treeview->model()); // TODO: Write a QAbstractItemView subclass to render kjots selection. connect(selProxy, &KSelectionProxyModel::dataChanged, this, &KJotsWidget::renderSelection); connect(selProxy, &KSelectionProxyModel::rowsInserted, this, &KJotsWidget::renderSelection); connect(selProxy, &KSelectionProxyModel::rowsRemoved, this, &KJotsWidget::renderSelection); stackedWidget = new QStackedWidget(m_splitter); KActionCollection *actionCollection = xmlGuiClient->actionCollection(); editor = new KJotsEdit(treeview->selectionModel(), stackedWidget); actionCollection->addActions(editor->createActions()); stackedWidget->addWidget(editor); layout->addWidget(m_splitter); browser = new KJotsBrowser(treeview->selectionModel(), stackedWidget); stackedWidget->addWidget(browser); stackedWidget->setCurrentWidget(browser); QAction *action; action = actionCollection->addAction(QLatin1String("go_next_book")); action->setText(i18n("Next Book")); action->setIcon(QIcon::fromTheme(QLatin1String("go-down"))); actionCollection->setDefaultShortcut(action, QKeySequence(Qt::CTRL + Qt::Key_D)); connect(action, &QAction::triggered, this, &KJotsWidget::nextBook); connect(this, &KJotsWidget::canGoNextBookChanged, action, &QAction::setEnabled); action = actionCollection->addAction(QLatin1String("go_prev_book")); action->setText(i18n("Previous Book")); action->setIcon(QIcon::fromTheme(QLatin1String("go-up"))); actionCollection->setDefaultShortcut(action, QKeySequence(Qt::CTRL + Qt::SHIFT + Qt::Key_D)); connect(action, &QAction::triggered, this, &KJotsWidget::prevBook); connect(this, &KJotsWidget::canGoPreviousBookChanged, action, &QAction::setEnabled); action = actionCollection->addAction(QLatin1String("go_next_page")); action->setText(i18n("Next Page")); action->setIcon(QIcon::fromTheme(QLatin1String("go-next"))); actionCollection->setDefaultShortcut(action, QKeySequence(Qt::CTRL + Qt::Key_PageDown)); connect(action, &QAction::triggered, this, &KJotsWidget::nextPage); connect(this, &KJotsWidget::canGoNextPageChanged, action, &QAction::setEnabled); action = actionCollection->addAction(QLatin1String("go_prev_page")); action->setText(i18n("Previous Page")); action->setIcon(QIcon::fromTheme(QLatin1String("go-previous"))); actionCollection->setDefaultShortcut(action, QKeySequence(Qt::CTRL + Qt::Key_PageUp)); connect(action, &QAction::triggered, this, &KJotsWidget::prevPage); connect(this, &KJotsWidget::canGoPreviousPageChanged, action, &QAction::setEnabled); action = actionCollection->addAction(QLatin1String("new_page")); action->setText(i18n("&New Page")); actionCollection->setDefaultShortcut(action, QKeySequence(Qt::CTRL + Qt::Key_N)); action->setIcon(QIcon::fromTheme(QLatin1String("document-new"))); connect(action, &QAction::triggered, this, &KJotsWidget::newPage); action = actionCollection->addAction(QLatin1String("new_book")); action->setText(i18n("New &Book...")); actionCollection->setDefaultShortcut(action, QKeySequence(Qt::CTRL + Qt::SHIFT + Qt::Key_N)); action->setIcon(QIcon::fromTheme(QLatin1String("address-book-new"))); connect(action, &QAction::triggered, this, &KJotsWidget::newBook); action = actionCollection->addAction(QLatin1String("del_page")); action->setText(i18n("&Delete Page")); actionCollection->setDefaultShortcut(action, QKeySequence(Qt::CTRL + Qt::Key_Delete)); action->setIcon(QIcon::fromTheme(QLatin1String("edit-delete-page"))); connect(action, &QAction::triggered, this, &KJotsWidget::deletePage); action = actionCollection->addAction(QLatin1String("del_folder")); action->setText(i18n("Delete Boo&k")); actionCollection->setDefaultShortcut(action, QKeySequence(Qt::CTRL + Qt::SHIFT + Qt::Key_Delete)); action->setIcon(QIcon::fromTheme(QLatin1String("edit-delete"))); connect(action, &QAction::triggered, this, &KJotsWidget::deleteBook); action = actionCollection->addAction(QLatin1String("del_mult")); action->setText(i18n("Delete Selected")); action->setIcon(QIcon::fromTheme(QLatin1String("edit-delete"))); connect(action, &QAction::triggered, this, &KJotsWidget::deleteMultiple); action = actionCollection->addAction(QLatin1String("manual_save")); action->setText(i18n("Manual Save")); action->setIcon(QIcon::fromTheme(QLatin1String("document-save"))); actionCollection->setDefaultShortcut(action, QKeySequence(Qt::CTRL + Qt::Key_S)); action = actionCollection->addAction(QLatin1String("auto_bullet")); action->setText(i18n("Auto Bullets")); action->setIcon(QIcon::fromTheme(QLatin1String("format-list-unordered"))); action->setCheckable(true); action = actionCollection->addAction(QLatin1String("auto_decimal")); action->setText(i18n("Auto Decimal List")); action->setIcon(QIcon::fromTheme(QLatin1String("format-list-ordered"))); action->setCheckable(true); action = actionCollection->addAction(QLatin1String("manage_link")); action->setText(i18n("Link")); action->setIcon(QIcon::fromTheme(QLatin1String("insert-link"))); action = actionCollection->addAction(QLatin1String("insert_image")); action->setText(i18n("Insert Image")); action->setIcon(QIcon::fromTheme(QLatin1String("insert-image"))); action = actionCollection->addAction(QLatin1String("insert_checkmark")); action->setText(i18n("Insert Checkmark")); action->setIcon(QIcon::fromTheme(QLatin1String("checkmark"))); action->setEnabled(false); action = actionCollection->addAction(QLatin1String("rename_entry")); action->setText(i18n("Rename...")); action->setIcon(QIcon::fromTheme(QLatin1String("edit-rename"))); actionCollection->setDefaultShortcut(action, QKeySequence(Qt::CTRL + Qt::Key_M)); action = actionCollection->addAction(QLatin1String("insert_date")); action->setText(i18n("Insert Date")); actionCollection->setDefaultShortcut(action, QKeySequence(Qt::CTRL + Qt::SHIFT + Qt::Key_I)); action->setIcon(QIcon::fromTheme(QLatin1String("view-calendar-time-spent"))); action = actionCollection->addAction(QLatin1String("change_color")); action->setIcon(QIcon::fromTheme(QLatin1String("format-fill-color"))); action->setText(i18n("Change Color...")); action = actionCollection->addAction(QLatin1String("copy_link_address")); action->setText(i18n("Copy Link Address")); action = actionCollection->addAction(QLatin1String("lock")); action->setText(i18n("Lock Selected")); action->setIcon(QIcon::fromTheme(QLatin1String("emblem-locked"))); connect(action, &QAction::triggered, this, &KJotsWidget::actionLock); action = actionCollection->addAction(QLatin1String("unlock")); action->setText(i18n("Unlock Selected")); action->setIcon(QIcon::fromTheme(QLatin1String("emblem-unlocked"))); connect(action, &QAction::triggered, this, &KJotsWidget::actionUnlock); action = actionCollection->addAction(QLatin1String("sort_children_alpha")); action->setText(i18n("Sort children alphabetically")); connect(action, &QAction::triggered, this, &KJotsWidget::actionSortChildrenAlpha); action = actionCollection->addAction(QLatin1String("sort_children_by_date")); action->setText(i18n("Sort children by creation date")); connect(action, &QAction::triggered, this, &KJotsWidget::actionSortChildrenByDate); action = KStandardAction::cut(editor, SLOT(cut()), actionCollection); connect(editor, &KJotsEdit::copyAvailable, action, &QAction::setEnabled); action->setEnabled(false); action = KStandardAction::copy(this, SLOT(copy()), actionCollection); connect(editor, &KJotsEdit::copyAvailable, action, &QAction::setEnabled); connect(browser, &KJotsBrowser::copyAvailable, action, &QAction::setEnabled); action->setEnabled(false); KStandardAction::pasteText(editor, SLOT(paste()), actionCollection); KStandardAction::undo(editor, SLOT(undo()), actionCollection); KStandardAction::redo(editor, SLOT(redo()), actionCollection); KStandardAction::selectAll(editor, SLOT(selectAll()), actionCollection); action = actionCollection->addAction(QLatin1String("copyIntoTitle")); action->setText(i18n("Copy &into Page Title")); actionCollection->setDefaultShortcut(action, QKeySequence(Qt::CTRL + Qt::Key_T)); action->setIcon(QIcon::fromTheme(QLatin1String("edit-copy"))); connect(action, &QAction::triggered, this, &KJotsWidget::copySelectionToTitle); connect(editor, &KJotsEdit::copyAvailable, action, &QAction::setEnabled); action->setEnabled(false); action = actionCollection->addAction(QLatin1String("paste_plain_text")); action->setText(i18nc("@action Paste the text in the clipboard without rich text formatting.", "Paste Plain Text")); connect(action, &QAction::triggered, editor, &KJotsEdit::pastePlainText); KStandardAction::preferences(this, SLOT(configure()), actionCollection); bookmarkMenu = actionCollection->add(QLatin1String("bookmarks")); bookmarkMenu->setText(i18n("&Bookmarks")); KJotsBookmarks *bookmarks = new KJotsBookmarks(treeview); KBookmarkMenu *bmm = new KBookmarkMenu( KBookmarkManager::managerForFile( QStandardPaths::standardLocations(QStandardPaths::AppDataLocation).first() + QStringLiteral("/kjots/bookmarks.xml"), QStringLiteral("kjots")), bookmarks, bookmarkMenu->menu()); // "Add bookmark" and "make text bold" actions have conflicting shortcuts (ctrl + b) // Make add_bookmark use ctrl+shift+b to resolve that. QAction *bm_action = bmm->addBookmarkAction(); actionCollection->addAction(QStringLiteral("add_bookmark"), bm_action); actionCollection->setDefaultShortcut(bm_action, Qt::CTRL | Qt::SHIFT | Qt::Key_B); actionCollection->addAction(QStringLiteral("edit_bookmark"), bmm->editBookmarksAction()); actionCollection->addAction(QStringLiteral("add_bookmarks_list"), bmm->bookmarkTabsAsFolderAction()); KStandardAction::find(this, SLOT(onShowSearch()), actionCollection); action = KStandardAction::findNext(this, SLOT(onRepeatSearch()), actionCollection); action->setEnabled(false); KStandardAction::replace(this, SLOT(onShowReplace()), actionCollection); action = actionCollection->addAction(QLatin1String("save_to")); action->setText(i18n("Rename...")); action->setIcon(QIcon::fromTheme(QLatin1String("edit-rename"))); actionCollection->setDefaultShortcut(action, QKeySequence(Qt::CTRL + Qt::Key_M)); KActionMenu *exportMenu = actionCollection->add(QLatin1String("save_to")); exportMenu->setText(i18n("Export")); exportMenu->setIcon(QIcon::fromTheme(QLatin1String("document-export"))); action = actionCollection->addAction(QLatin1String("save_to_ascii")); action->setText(i18n("To Text File...")); action->setIcon(QIcon::fromTheme(QLatin1String("text-plain"))); connect(action, &QAction::triggered, this, &KJotsWidget::exportSelectionToPlainText); exportMenu->menu()->addAction(action); action = actionCollection->addAction(QLatin1String("save_to_html")); action->setText(i18n("To HTML File...")); action->setIcon(QIcon::fromTheme(QLatin1String("text-html"))); connect(action, &QAction::triggered, this, &KJotsWidget::exportSelectionToHtml); exportMenu->menu()->addAction(action); action = actionCollection->addAction(QLatin1String("save_to_book")); action->setText(i18n("To Book File...")); action->setIcon(QIcon::fromTheme(QLatin1String("x-office-address-book"))); connect(action, &QAction::triggered, this, &KJotsWidget::exportSelectionToXml); exportMenu->menu()->addAction(action); KStandardAction::print(this, SLOT(printSelection()), actionCollection); KStandardAction::printPreview(this, SLOT(printPreviewSelection()), actionCollection); if (!KJotsSettings::splitterSizes().isEmpty()) { m_splitter->setSizes(KJotsSettings::splitterSizes()); } QTimer::singleShot(0, this, SLOT(delayedInitialization())); connect(treeview->selectionModel(), SIGNAL(selectionChanged(QItemSelection,QItemSelection)), SLOT(updateMenu())); connect(treeview->selectionModel(), SIGNAL(selectionChanged(QItemSelection,QItemSelection)), SLOT(updateCaption())); connect(m_kjotsModel, &Akonadi::EntityTreeModel::modelAboutToBeReset, this, &KJotsWidget::saveState); connect(m_kjotsModel, &Akonadi::EntityTreeModel::modelReset, this, &KJotsWidget::restoreState); restoreState(); QDBusConnection::sessionBus().registerObject(QLatin1String("/KJotsWidget"), this, QDBusConnection::ExportScriptableContents); } KJotsWidget::~KJotsWidget() { saveState(); } void KJotsWidget::restoreState() { ETMViewStateSaver *saver = new ETMViewStateSaver; saver->setView(treeview); KConfigGroup cfg(KSharedConfig::openConfig(), "TreeState"); saver->restoreState(cfg); } void KJotsWidget::saveState() { ETMViewStateSaver saver; saver.setView(treeview); KConfigGroup cfg(KSharedConfig::openConfig(), "TreeState"); saver.saveState(cfg); cfg.sync(); } void KJotsWidget::delayedInitialization() { migrateNoteData(QLatin1String("kjotsmigrator")); // Disable nigration of data from KNotes as that app still exists in 4.5. // migrateNoteData( "kres-migrator", "notes" ); //TODO: Save previous searches in settings file? searchDialog = new KFindDialog(this, 0, QStringList(), false); QGridLayout *layout = new QGridLayout(searchDialog->findExtension()); layout->setMargin(0); searchAllPages = new QCheckBox(i18n("Search all pages"), searchDialog->findExtension()); layout->addWidget(searchAllPages, 0, 0); connect(searchDialog, &KFindDialog::okClicked, this, &KJotsWidget::onStartSearch); connect(searchDialog, &KFindDialog::cancelClicked, this, &KJotsWidget::onEndSearch); connect(treeview->selectionModel(), SIGNAL(selectionChanged(QItemSelection,QItemSelection)), SLOT(onUpdateSearch())); connect(searchDialog, &KFindDialog::optionsChanged, this, &KJotsWidget::onUpdateSearch); connect(searchAllPages, &QCheckBox::stateChanged, this, &KJotsWidget::onUpdateSearch); replaceDialog = new KReplaceDialog(this, 0, searchHistory, replaceHistory, false); QGridLayout *layout2 = new QGridLayout(replaceDialog->findExtension()); layout2->setMargin(0); replaceAllPages = new QCheckBox(i18n("Search all pages"), replaceDialog->findExtension()); layout2->addWidget(replaceAllPages, 0, 0); connect(replaceDialog, &KReplaceDialog::okClicked, this, &KJotsWidget::onStartReplace); connect(replaceDialog, &KReplaceDialog::cancelClicked, this, &KJotsWidget::onEndReplace); connect(replaceDialog, &KReplaceDialog::optionsChanged, this, &KJotsWidget::onUpdateReplace); connect(replaceAllPages, &QCheckBox::stateChanged, this, &KJotsWidget::onUpdateReplace); // Actions are enabled or disabled based on whether the selection is a single page, a single book // multiple selections, or no selection. // // The entryActions are enabled for all single pages and single books, and the multiselectionActions // are enabled when the user has made multiple selections. // // Some actions are in neither (eg, new book) and are available even when there is no selection. // // Some actions are in both, so that they are available for valid selections, but not available // for invalid selections (eg, print/find are disabled when there is no selection) KActionCollection *actionCollection = m_xmlGuiClient->actionCollection(); // Actions for a single item selection. entryActions.insert(actionCollection->action(QLatin1String(KStandardAction::name(KStandardAction::Find)))); entryActions.insert(actionCollection->action(QLatin1String(KStandardAction::name(KStandardAction::Print)))); entryActions.insert(actionCollection->action(QLatin1String("rename_entry"))); entryActions.insert(actionCollection->action(QLatin1String("change_color"))); entryActions.insert(actionCollection->action(QLatin1String("save_to"))); entryActions.insert(actionCollection->action(QLatin1String("copy_link_address"))); // Actions that are used only when a page is selected. pageActions.insert(actionCollection->action(QLatin1String(KStandardAction::name(KStandardAction::Cut)))); pageActions.insert(actionCollection->action(QLatin1String(KStandardAction::name(KStandardAction::Paste)))); pageActions.insert(actionCollection->action(QLatin1String(KStandardAction::name(KStandardAction::Replace)))); pageActions.insert(actionCollection->action(QLatin1String("del_page"))); pageActions.insert(actionCollection->action(QLatin1String("insert_date"))); pageActions.insert(actionCollection->action(QLatin1String("auto_bullet"))); pageActions.insert(actionCollection->action(QLatin1String("auto_decimal"))); pageActions.insert(actionCollection->action(QLatin1String("manage_link"))); pageActions.insert(actionCollection->action(QLatin1String("insert_checkmark"))); // Actions that are used only when a book is selected. bookActions.insert(actionCollection->action(QLatin1String("save_to_book"))); bookActions.insert(actionCollection->action(QLatin1String("del_folder"))); bookActions.insert(actionCollection->action(QLatin1String("sort_children_alpha"))); bookActions.insert(actionCollection->action(QLatin1String("sort_children_by_date"))); // Actions that are used when multiple items are selected. multiselectionActions.insert(actionCollection->action(QLatin1String(KStandardAction::name(KStandardAction::Find)))); multiselectionActions.insert(actionCollection->action(QLatin1String(KStandardAction::name(KStandardAction::Print)))); multiselectionActions.insert(actionCollection->action(QLatin1String("del_mult"))); multiselectionActions.insert(actionCollection->action(QLatin1String("save_to"))); multiselectionActions.insert(actionCollection->action(QLatin1String("change_color"))); m_autosaveTimer = new QTimer(this); updateConfiguration(); connect(m_autosaveTimer, &QTimer::timeout, editor, &KJotsEdit::savePage); connect(treeview->selectionModel(), SIGNAL(selectionChanged(QItemSelection,QItemSelection)), m_autosaveTimer, SLOT(start())); treeview->delayedInitialization(); editor->delayedInitialization(m_xmlGuiClient->actionCollection()); browser->delayedInitialization(); connect(treeview->itemDelegate(), SIGNAL(closeEditor(QWidget*,QAbstractItemDelegate::EndEditHint)), SLOT(bookshelfEditItemFinished(QWidget*,QAbstractItemDelegate::EndEditHint))); connect(editor, SIGNAL(currentCharFormatChanged(QTextCharFormat)), SLOT(currentCharFormatChanged(QTextCharFormat))); updateMenu(); } void KJotsWidget::bookshelfEditItemFinished(QWidget *, QAbstractItemDelegate::EndEditHint) { // Make sure the editor gets focus again after naming a new book/page. activeEditor()->setFocus(); } void KJotsWidget::currentCharFormatChanged(const QTextCharFormat &fmt) { QString selectedAnchor = fmt.anchorHref(); if (selectedAnchor != activeAnchor) { activeAnchor = selectedAnchor; if (!selectedAnchor.isEmpty()) { QTextCursor c(editor->textCursor()); editor->selectLinkText(&c); QString selectedText = c.selectedText(); if (!selectedText.isEmpty()) { - emit activeAnchorChanged(selectedAnchor, selectedText); + Q_EMIT activeAnchorChanged(selectedAnchor, selectedText); } } else { - emit activeAnchorChanged(QString(), QString()); + Q_EMIT activeAnchorChanged(QString(), QString()); } } } void KJotsWidget::migrateNoteData(const QString &migrator, const QString &type) { // Akonadi migration KConfig config(migrator + QLatin1String("rc")); KConfigGroup migrationCfg(&config, "Migration"); const bool enabled = migrationCfg.readEntry("Enabled", true); const bool completed = migrationCfg.readEntry("Completed", false); const int currentVersion = migrationCfg.readEntry("Version", 0); const int targetVersion = migrationCfg.readEntry("TargetVersion", 1); if (enabled && !completed && currentVersion < targetVersion) { qDebug() << "Performing Akonadi migration. Good luck!"; KProcess proc; QStringList args = QStringList() << QLatin1String("--interactive-on-change"); if (!type.isEmpty()) { args << QLatin1String("--type") << type; } const QString path = QStandardPaths::findExecutable(migrator); proc.setProgram(path, args); proc.start(); bool result = proc.waitForStarted(); if (result) { result = proc.waitForFinished(); } if (result && proc.exitCode() == 0) { qDebug() << "Akonadi migration has been successful"; } else { // exit code 1 means it is already running, so we are probably called by a migrator instance qCritical() << "Akonadi migration failed!"; qCritical() << "command was: " << proc.program(); qCritical() << "exit code: " << proc.exitCode(); qCritical() << "stdout: " << proc.readAllStandardOutput(); qCritical() << "stderr: " << proc.readAllStandardError(); } migrationCfg.writeEntry("Version", targetVersion); migrationCfg.writeEntry("Completed", true); migrationCfg.sync(); } } inline QTextEdit *KJotsWidget::activeEditor() { if (browser->isVisible()) { return browser; } else { return editor; } } void KJotsWidget::updateMenu() { QModelIndexList selection = treeview->selectionModel()->selectedRows(); int selectionSize = selection.size(); if (!selectionSize) { // no (meaningful?) selection - foreach (QAction *action, multiselectionActions) { + for (QAction *action : qAsConst(multiselectionActions)) { action->setEnabled(false); } - foreach (QAction *action, entryActions) { + for (QAction *action : qAsConst(entryActions)) { action->setEnabled(false); } - foreach (QAction *action, bookActions) { + for (QAction *action : qAsConst(bookActions)) { action->setEnabled(false); } - foreach (QAction *action, pageActions) { + for (QAction *action : qAsConst(pageActions)) { action->setEnabled(false); } editor->setActionsEnabled(false); } else if (selectionSize > 1) { - foreach (QAction *action, entryActions) { + for (QAction *action : qAsConst(entryActions)) { action->setEnabled(false); } - foreach (QAction *action, bookActions) { + for (QAction *action : qAsConst(bookActions)) { action->setEnabled(false); } - foreach (QAction *action, pageActions) { + for (QAction *action : qAsConst(pageActions)) { action->setEnabled(false); } - foreach (QAction *action, multiselectionActions) { + for (QAction *action : qAsConst(multiselectionActions)) { action->setEnabled(true); } editor->setActionsEnabled(false); } else { - foreach (QAction *action, multiselectionActions) { + for (QAction *action : qAsConst(multiselectionActions)) { action->setEnabled(false); } - foreach (QAction *action, entryActions) { + for (QAction *action : qAsConst(entryActions)) { action->setEnabled(true); } QModelIndex idx = selection.at(0); Collection col = idx.data(KJotsModel::CollectionRole).value(); if (col.isValid()) { - foreach (QAction *action, pageActions) { + for (QAction *action : qAsConst(pageActions)) { action->setEnabled(false); } const bool colIsRootCollection = (col.parentCollection() == Collection::root()); - foreach (QAction *action, bookActions) { + for (QAction *action : qAsConst(bookActions)) { if (action->objectName() == QLatin1String("del_folder") && colIsRootCollection) { action->setEnabled(false); } else { action->setEnabled(true); } } editor->setActionsEnabled(false); } else { - foreach (QAction *action, pageActions) { + for (QAction *action : qAsConst(pageActions)) { if (action->objectName() == QLatin1String(name(KStandardAction::Cut))) { action->setEnabled(activeEditor()->textCursor().hasSelection()); } else { action->setEnabled(true); } } - foreach (QAction *action, bookActions) { + for (QAction *action : qAsConst(bookActions)) { action->setEnabled(false); } editor->setActionsEnabled(true); } } } void KJotsWidget::copy() { activeEditor()->copy(); } void KJotsWidget::configure() { // create a new preferences dialog... KJotsConfigDlg *dialog = new KJotsConfigDlg(i18n("Settings"), this); connect(dialog, SIGNAL(configCommitted()), SLOT(updateConfiguration())); dialog->show(); } void KJotsWidget::updateConfiguration() { if (KJotsSettings::autoSave()) { m_autosaveTimer->setInterval(KJotsSettings::autoSaveInterval() * 1000 * 60); m_autosaveTimer->start(); } else { m_autosaveTimer->stop(); } } void KJotsWidget::copySelectionToTitle() { QString newTitle(editor->textCursor().selectedText()); if (!newTitle.isEmpty()) { QModelIndexList rows = treeview->selectionModel()->selectedRows(); if (rows.size() != 1) { return; } QModelIndex idx = rows.at(0); treeview->model()->setData(idx, newTitle); } } void KJotsWidget::deleteMultiple() { - QModelIndexList selectedRows = treeview->selectionModel()->selectedRows(); + const QModelIndexList selectedRows = treeview->selectionModel()->selectedRows(); if (KMessageBox::questionYesNo(this, i18n("Do you really want to delete all selected books and pages?"), i18n("Delete?"), KStandardGuiItem::del(), KStandardGuiItem::cancel(), QString(), KMessageBox::Dangerous) != KMessageBox::Yes) { return; } - foreach (const QModelIndex &index, selectedRows) { + for (const QModelIndex &index : selectedRows) { bool ok; qlonglong id = index.data(EntityTreeModel::ItemIdRole).toLongLong(&ok); Q_ASSERT(ok); if (id >= 0) { new ItemDeleteJob(Item(id), this); } else { id = index.data(EntityTreeModel::CollectionIdRole).toLongLong(&ok); Q_ASSERT(ok); if (id >= 0) { new CollectionDeleteJob(Collection(id), this); } } } } void KJotsWidget::deletePage() { QModelIndexList selectedRows = treeview->selectionModel()->selectedRows(); if (selectedRows.size() != 1) { return; } const QModelIndex idx = selectedRows.at(0); Item item = idx.data(EntityTreeModel::ItemRole).value(); if (!item.isValid()) { return; } if (item.hasAttribute()) { KMessageBox::information(topLevelWidget(), i18n("This page is locked. You can only delete it when you first unlock it."), i18n("Item is locked")); return; } if (KMessageBox::warningContinueCancel(topLevelWidget(), i18nc("remove the page, by title", "Are you sure you want to delete the page %1?", idx.data().toString()), i18n("Delete"), KStandardGuiItem::del(), KStandardGuiItem::cancel(), QLatin1String("DeletePageWarning")) == KMessageBox::Cancel) { return; } (void) new Akonadi::ItemDeleteJob(item, this); } void KJotsWidget::deleteBook() { QModelIndexList selectedRows = treeview->selectionModel()->selectedRows(); if (selectedRows.size() != 1) { return; } const QModelIndex idx = selectedRows.at(0); Collection col = idx.data(EntityTreeModel::CollectionRole).value(); if (!col.isValid()) { return; } if (col.parentCollection() == Collection::root()) { return; } if (col.hasAttribute()) { KMessageBox::information(topLevelWidget(), i18n("This book is locked. You can only delete it when you first unlock it."), i18n("Item is locked")); return; } if (KMessageBox::warningContinueCancel(topLevelWidget(), i18nc("remove the book, by title", "Are you sure you want to delete the book %1?", idx.data().toString()), i18n("Delete"), KStandardGuiItem::del(), KStandardGuiItem::cancel(), QLatin1String("DeleteBookWarning")) == KMessageBox::Cancel) { return; } (void) new Akonadi::CollectionDeleteJob(col, this); } void KJotsWidget::newBook() { QModelIndexList selectedRows = treeview->selectionModel()->selectedRows(); if (selectedRows.size() != 1) { return; } Collection col = selectedRows.at(0).data(EntityTreeModel::CollectionRole).value(); if (!col.isValid()) { return; } Collection newCollection; newCollection.setParentCollection(col); QString title = i18nc("The default name for new books.", "New Book"); newCollection.setName(KRandom::randomString(10)); newCollection.setContentMimeTypes(QStringList() << Akonadi::Collection::mimeType() << Akonotes::Note::mimeType()); Akonadi::EntityDisplayAttribute *eda = new Akonadi::EntityDisplayAttribute(); eda->setIconName(QLatin1String("x-office-address-book")); eda->setDisplayName(title); newCollection.addAttribute(eda); Akonadi::CollectionCreateJob *job = new Akonadi::CollectionCreateJob(newCollection); connect(job, &Akonadi::CollectionCreateJob::result, this, &KJotsWidget::newBookResult); } void KJotsWidget::newPage() { QModelIndexList selectedRows = treeview->selectionModel()->selectedRows(); if (selectedRows.size() != 1) { return; } Item item = selectedRows.at(0).data(EntityTreeModel::ItemRole).value(); Collection col; if (item.isValid()) { col = selectedRows.at(0).data(EntityTreeModel::ParentCollectionRole).value(); } else { col = selectedRows.at(0).data(EntityTreeModel::CollectionRole).value(); } if (!col.isValid()) { return; } doCreateNewPage(col); } void KJotsWidget::doCreateNewPage(const Collection &collection) { Akonotes::NoteCreatorAndSelector *creatorAndSelector = new Akonotes::NoteCreatorAndSelector(treeview->selectionModel()); creatorAndSelector->createNote(collection); } void KJotsWidget::newPageResult(KJob *job) { if (job->error()) { qDebug() << job->errorString(); } } void KJotsWidget::newBookResult(KJob *job) { if (job->error()) { qDebug() << job->errorString(); return; } Akonadi::CollectionCreateJob *createJob = qobject_cast(job); if (!createJob) { return; } const Collection collection = createJob->collection(); if (!collection.isValid()) { return; } doCreateNewPage(collection); } QString KJotsWidget::renderSelectionToHtml() { QHash hash; QList objectList; const int rows = selProxy->rowCount(); const int column = 0; for (int row = 0; row < rows; ++row) { QModelIndex idx = selProxy->index(row, column, QModelIndex()); QObject *obj = idx.data(KJotsModel::GrantleeObjectRole).value(); KJotsEntity *kjotsEntity = qobject_cast(obj); kjotsEntity->setIndex(idx); objectList << QVariant::fromValue(static_cast(kjotsEntity)); } hash.insert(QLatin1String("entities"), objectList); hash.insert(QLatin1String("i18n_TABLE_OF_CONTENTS"), i18nc("Header for 'Table of contents' section of rendered output", "Table of contents")); Context c(hash); Template t = m_templateEngine->loadByName(QLatin1String("template.html")); QString result = t->render(&c); // TODO: handle errors. return result; } QString KJotsWidget::renderSelectionToPlainText() { QHash hash; QList objectList; const int rows = selProxy->rowCount(); const int column = 0; for (int row = 0; row < rows; ++row) { QModelIndex idx = selProxy->index(row, column, QModelIndex()); QObject *obj = idx.data(KJotsModel::GrantleeObjectRole).value(); KJotsEntity *kjotsEntity = qobject_cast(obj); kjotsEntity->setIndex(idx); objectList << QVariant::fromValue(static_cast(kjotsEntity)); } hash.insert(QLatin1String("entities"), objectList); hash.insert(QLatin1String("i18n_TABLE_OF_CONTENTS"), i18nc("Header for 'Table of contents' section of rendered output", "Table of contents")); Context c(hash); Template t = m_templateEngine->loadByName(QLatin1String("template.txt")); QString result = t->render(&c); // TODO: handle errors. return result; } QString KJotsWidget::renderSelectionToXml() { QHash hash; QList objectList; const int rows = selProxy->rowCount(); const int column = 0; for (int row = 0; row < rows; ++row) { QModelIndex idx = selProxy->index(row, column, QModelIndex()); QObject *obj = idx.data(KJotsModel::GrantleeObjectRole).value(); KJotsEntity *kjotsEntity = qobject_cast(obj); kjotsEntity->setIndex(idx); objectList << QVariant::fromValue(static_cast(kjotsEntity)); } hash.insert(QLatin1String("entities"), objectList); Context c(hash); QString currentTheme = m_loader->themeName(); m_loader->setTheme(QLatin1String("xml_output")); Template t = m_templateEngine->loadByName(QLatin1String("template.xml")); QString result = t->render(&c); m_loader->setTheme(currentTheme); return result; } void KJotsWidget::renderSelection() { const int rows = selProxy->rowCount(); // If the selection is a single page, present it for editing... if (rows == 1) { QModelIndex idx = selProxy->index(0, 0, QModelIndex()); QTextDocument *document = idx.data(KJotsModel::DocumentRole).value(); if (document) { editor->setDocument(document); QTextCursor textCursor = document->property("textCursor").value(); if (!textCursor.isNull()) { editor->setTextCursor(textCursor); } stackedWidget->setCurrentWidget(editor); editor->setFocus(); return; } // else fallthrough } // ... Otherwise, render the selection read-only. QTextDocument doc; QTextCursor cursor(&doc); browser->setHtml(renderSelectionToHtml()); stackedWidget->setCurrentWidget(browser); } QString KJotsWidget::getThemeFromUser() { return QString(); #if 0 bool ok; QString text = QInputDialog::getText(this, i18n("Change Theme"), tr("Theme name:"), QLineEdit::Normal, m_loader->themeName(), &ok); if (!ok || text.isEmpty()) { return QLatin1String("default"); } return text; #endif } void KJotsWidget::changeTheme() { #if 0 m_loader->setTheme(getThemeFromUser()); renderSelection(); #endif } void KJotsWidget::exportSelectionToHtml() { QString currentTheme = m_loader->themeName(); QString themeName = getThemeFromUser(); if (themeName.isEmpty()) { themeName = QLatin1String("default"); } m_loader->setTheme(themeName); QString filename = QFileDialog::getSaveFileName(); if (!filename.isEmpty()) { QFile exportFile(filename); if (!exportFile.open(QIODevice::WriteOnly | QIODevice::Text)) { m_loader->setTheme(currentTheme); - KMessageBox::error(0, i18n("Error opening internal file.")); + KMessageBox::error(nullptr, i18n("Error opening internal file.")); return; } exportFile.write(renderSelectionToHtml().toUtf8()); exportFile.close(); } m_loader->setTheme(currentTheme); } void KJotsWidget::exportSelectionToPlainText() { QString currentTheme = m_loader->themeName(); m_loader->setTheme(QLatin1String("plain_text")); QString filename = QFileDialog::getSaveFileName(); if (!filename.isEmpty()) { QFile exportFile(filename); if (!exportFile.open(QIODevice::WriteOnly | QIODevice::Text)) { m_loader->setTheme(currentTheme); - KMessageBox::error(0, i18n("Error opening internal file.")); + KMessageBox::error(nullptr, i18n("Error opening internal file.")); return; } exportFile.write(renderSelectionToPlainText().toUtf8()); exportFile.close(); } m_loader->setTheme(currentTheme); } void KJotsWidget::exportSelectionToXml() { QString currentTheme = m_loader->themeName(); m_loader->setTheme(QLatin1String("xml_output")); QString filename = QFileDialog::getSaveFileName(); if (!filename.isEmpty()) { QFile exportFile(filename); if (!exportFile.open(QIODevice::WriteOnly | QIODevice::Text)) { m_loader->setTheme(currentTheme); - KMessageBox::error(0, i18n("Error opening internal file.")); + KMessageBox::error(nullptr, i18n("Error opening internal file.")); return; } exportFile.write(renderSelectionToXml().toUtf8()); exportFile.close(); } m_loader->setTheme(currentTheme); } void KJotsWidget::printPreviewSelection() { QPrinter printer(QPrinter::HighResolution); printer.setDocName(QLatin1String("KJots_Print")); printer.setFullPage(false); printer.setCreator(QLatin1String("KJots")); - QPrintPreviewDialog previewdlg(&printer, 0); + QPrintPreviewDialog previewdlg(&printer, nullptr); print(printer); previewdlg.exec(); } void KJotsWidget::printSelection() { QPrinter printer(QPrinter::HighResolution); printer.setDocName(QLatin1String("KJots_Print")); printer.setFullPage(false); printer.setCreator(QLatin1String("KJots")); //Not supported in Qt? //printer->setPageSelection(QPrinter::ApplicationSide); //KPrinter::pageList() only works with ApplicationSide. ApplicationSide //requires min/max pages. How am I supposed to tell how many pages there //are before I setup the printer? QPointer printDialog = new QPrintDialog(&printer, this); QAbstractPrintDialog::PrintDialogOptions options = printDialog->enabledOptions(); options &= ~QAbstractPrintDialog::PrintPageRange; if (activeEditor()->textCursor().hasSelection()) { options |= QAbstractPrintDialog::PrintSelection; } printDialog->setEnabledOptions(options); printDialog->setWindowTitle(i18n("Send To Printer")); if (printDialog->exec() == QDialog::Accepted) { print(printer); } delete printDialog; } void KJotsWidget::print(QPrinter &printer) { QTextDocument printDocument; if (printer.printRange() == QPrinter::Selection) { printDocument.setHtml(activeEditor()->textCursor().selection().toHtml()); } else { //QTextCursor printCursor ( &printDocument ); QString currentTheme = m_loader->themeName(); m_loader->setTheme(QLatin1String("default")); printDocument.setHtml(renderSelectionToHtml()); m_loader->setTheme(currentTheme); } QPainter p(&printer); // Check that there is a valid device to print to. if (p.isActive()) { QTextDocument *doc = &printDocument; QRectF body = QRectF(QPointF(0, 0), doc->pageSize()); QPointF pageNumberPos; QAbstractTextDocumentLayout *layout = doc->documentLayout(); layout->setPaintDevice(p.device()); const int dpiy = p.device()->logicalDpiY(); const int margin = (int)((2 / 2.54) * dpiy); // 2 cm margins QTextFrameFormat fmt = doc->rootFrame()->frameFormat(); fmt.setMargin(margin); doc->rootFrame()->setFrameFormat(fmt); body = QRectF(0, 0, p.device()->width(), p.device()->height()); pageNumberPos = QPointF(body.width() - margin, body.height() - margin + QFontMetrics(doc->defaultFont(), p.device()).ascent() + 5 * p.device()->logicalDpiY() / 72); doc->setPageSize(body.size()); int docCopies = printer.numCopies(); for (int copy = 0; copy < docCopies; ++copy) { int lastPage = layout->pageCount(); for (int page = 1; page <= lastPage ; ++page) { p.save(); p.translate(body.left(), body.top() - (page - 1) * body.height()); QRectF view(0, (page - 1) * body.height(), body.width(), body.height()); QAbstractTextDocumentLayout *layout = doc->documentLayout(); QAbstractTextDocumentLayout::PaintContext ctx; p.setClipRect(view); ctx.clip = view; // don't use the system palette text as default text color, on HP/UX // for example that's white, and white text on white paper doesn't // look that nice ctx.palette.setColor(QPalette::Text, Qt::black); layout->draw(&p, ctx); if (!pageNumberPos.isNull()) { p.setClipping(false); p.setFont(QFont(doc->defaultFont())); const QString pageString = QString::number(page); p.drawText(qRound(pageNumberPos.x() - p.fontMetrics().width(pageString)), qRound(pageNumberPos.y() + view.top()), pageString); } p.restore(); if ((page + 1) <= lastPage) { printer.newPage(); } } } } } void KJotsWidget::selectNext(int role, int step) { QModelIndexList list = treeview->selectionModel()->selectedRows(); Q_ASSERT(list.size() == 1); QModelIndex idx = list.at(0); const int column = idx.column(); QModelIndex sibling = idx.sibling(idx.row() + step, column); while (sibling.isValid()) { if (sibling.data(role).toInt() >= 0) { treeview->selectionModel()->select(sibling, QItemSelectionModel::SelectCurrent); return; } sibling = sibling.sibling(sibling.row() + step, column); } qWarning() << "No valid selection"; } void KJotsWidget::nextBook() { return selectNext(EntityTreeModel::CollectionIdRole, 1); } void KJotsWidget::nextPage() { return selectNext(EntityTreeModel::ItemIdRole, 1); } void KJotsWidget::prevBook() { return selectNext(EntityTreeModel::CollectionIdRole, -1); } void KJotsWidget::prevPage() { return selectNext(EntityTreeModel::ItemIdRole, -1); } bool KJotsWidget::canGo(int role, int step) const { QModelIndexList list = treeview->selectionModel()->selectedRows(); if (list.size() != 1) { return false; } QModelIndex currentIdx = list.at(0); const int column = currentIdx.column(); Q_ASSERT(currentIdx.isValid()); QModelIndex sibling = currentIdx.sibling(currentIdx.row() + step, column); while (sibling.isValid() && sibling != currentIdx) { if (sibling.data(role).toInt() >= 0) { return true; } sibling = sibling.sibling(sibling.row() + step, column); } return false; } bool KJotsWidget::canGoNextPage() const { return canGo(EntityTreeModel::ItemIdRole, 1); } bool KJotsWidget::canGoPreviousPage() const { return canGo(EntityTreeModel::ItemIdRole, -1); } bool KJotsWidget::canGoNextBook() const { return canGo(EntityTreeModel::CollectionIdRole, 1); } bool KJotsWidget::canGoPreviousBook() const { return canGo(EntityTreeModel::CollectionIdRole, -1); } void KJotsWidget::selectionChanged(const QItemSelection &selected, const QItemSelection &deselected) { - Q_UNUSED(selected); + Q_UNUSED(selected) - emit canGoNextBookChanged(canGoPreviousBook()); - emit canGoNextPageChanged(canGoNextPage()); - emit canGoPreviousBookChanged(canGoPreviousBook()); - emit canGoPreviousPageChanged(canGoPreviousPage()); + Q_EMIT canGoNextBookChanged(canGoPreviousBook()); + Q_EMIT canGoNextPageChanged(canGoNextPage()); + Q_EMIT canGoPreviousBookChanged(canGoPreviousBook()); + Q_EMIT canGoPreviousPageChanged(canGoPreviousPage()); if (deselected.size() == 1) { editor->document()->setProperty("textCursor", QVariant::fromValue(editor->textCursor())); if (editor->document()->isModified()) { treeview->model()->setData(deselected.indexes().first(), QVariant::fromValue(editor->document()), KJotsModel::DocumentRole); } } } /*! Shows the search dialog when "Find" is selected. */ void KJotsWidget::onShowSearch() { onUpdateSearch(); QTextEdit *browserOrEditor = activeEditor(); if (browserOrEditor->textCursor().hasSelection()) { searchDialog->setHasSelection(true); long dialogOptions = searchDialog->options(); dialogOptions |= KFind::SelectedText; searchDialog->setOptions(dialogOptions); } else { searchDialog->setHasSelection(false); } searchDialog->setFindHistory(searchHistory); searchDialog->show(); onUpdateSearch(); } /*! Updates the search dialog if the user is switching selections while it is open. */ void KJotsWidget::onUpdateSearch() { if (searchDialog->isVisible()) { long searchOptions = searchDialog->options(); if (searchOptions & KFind::SelectedText) { searchAllPages->setCheckState(Qt::Unchecked); searchAllPages->setEnabled(false); } else { searchAllPages->setEnabled(true); } if (searchAllPages->checkState() == Qt::Checked) { searchOptions &= ~KFind::SelectedText; searchDialog->setOptions(searchOptions); searchDialog->setHasSelection(false); } else { if (activeEditor()->textCursor().hasSelection()) { searchDialog->setHasSelection(true); } } if (activeEditor()->textCursor().hasSelection()) { if (searchAllPages->checkState() == Qt::Unchecked) { searchDialog->setHasSelection(true); } } else { searchOptions &= ~KFind::SelectedText; searchDialog->setOptions(searchOptions); searchDialog->setHasSelection(false); } } } /*! Called when the user presses OK in the search dialog. */ void KJotsWidget::onStartSearch() { QString searchPattern = searchDialog->pattern(); if (!searchHistory.contains(searchPattern)) { searchHistory.prepend(searchPattern); } QTextEdit *browserOrEditor = activeEditor(); QTextCursor cursor = browserOrEditor->textCursor(); long searchOptions = searchDialog->options(); if (searchOptions & KFind::FromCursor) { searchPos = cursor.position(); searchBeginPos = 0; cursor.movePosition(QTextCursor::End); searchEndPos = cursor.position(); } else { if (searchOptions & KFind::SelectedText) { searchBeginPos = cursor.selectionStart(); searchEndPos = cursor.selectionEnd(); } else { searchBeginPos = 0; cursor.movePosition(QTextCursor::End); searchEndPos = cursor.position(); } if (searchOptions & KFind::FindBackwards) { searchPos = searchEndPos; } else { searchPos = searchBeginPos; } } m_xmlGuiClient->actionCollection()->action(QLatin1String(KStandardAction::name(KStandardAction::FindNext)))->setEnabled(true); onRepeatSearch(); } /*! Called when user chooses "Find Next" */ void KJotsWidget::onRepeatSearch() { if (search(false) == 0) { - KMessageBox::sorry(0, i18n("No matches found.")); + KMessageBox::sorry(nullptr, i18n("No matches found.")); m_xmlGuiClient->actionCollection()->action(QLatin1String(KStandardAction::name(KStandardAction::FindNext)))->setEnabled(false); } } /*! Called when user presses Cancel in find dialog. */ void KJotsWidget::onEndSearch() { m_xmlGuiClient->actionCollection()->action(QLatin1String(KStandardAction::name(KStandardAction::FindNext)))->setEnabled(false); } /*! Shows the replace dialog when "Replace" is selected. */ void KJotsWidget::onShowReplace() { Q_ASSERT(editor->isVisible()); if (editor->textCursor().hasSelection()) { replaceDialog->setHasSelection(true); long dialogOptions = replaceDialog->options(); dialogOptions |= KFind::SelectedText; replaceDialog->setOptions(dialogOptions); } else { replaceDialog->setHasSelection(false); } replaceDialog->setFindHistory(searchHistory); replaceDialog->setReplacementHistory(replaceHistory); replaceDialog->show(); onUpdateReplace(); } /*! Updates the replace dialog if the user is switching selections while it is open. */ void KJotsWidget::onUpdateReplace() { if (replaceDialog->isVisible()) { long replaceOptions = replaceDialog->options(); if (replaceOptions & KFind::SelectedText) { replaceAllPages->setCheckState(Qt::Unchecked); replaceAllPages->setEnabled(false); } else { replaceAllPages->setEnabled(true); } if (replaceAllPages->checkState() == Qt::Checked) { replaceOptions &= ~KFind::SelectedText; replaceDialog->setOptions(replaceOptions); replaceDialog->setHasSelection(false); } else { if (activeEditor()->textCursor().hasSelection()) { replaceDialog->setHasSelection(true); } } } } /*! Called when the user presses OK in the replace dialog. */ void KJotsWidget::onStartReplace() { QString searchPattern = replaceDialog->pattern(); if (!searchHistory.contains(searchPattern)) { searchHistory.prepend(searchPattern); } QString replacePattern = replaceDialog->replacement(); if (!replaceHistory.contains(replacePattern)) { replaceHistory.prepend(replacePattern); } QTextCursor cursor = editor->textCursor(); long replaceOptions = replaceDialog->options(); if (replaceOptions & KFind::FromCursor) { replacePos = cursor.position(); replaceBeginPos = 0; cursor.movePosition(QTextCursor::End); replaceEndPos = cursor.position(); } else { if (replaceOptions & KFind::SelectedText) { replaceBeginPos = cursor.selectionStart(); replaceEndPos = cursor.selectionEnd(); } else { replaceBeginPos = 0; cursor.movePosition(QTextCursor::End); replaceEndPos = cursor.position(); } if (replaceOptions & KFind::FindBackwards) { replacePos = replaceEndPos; } else { replacePos = replaceBeginPos; } } replaceStartPage = treeview->selectionModel()->selectedRows().first(); //allow KReplaceDialog to exit so the user can see. QTimer::singleShot(0, this, SLOT(onRepeatReplace())); } /*! Only called after onStartReplace. Kept the name scheme for consistancy. */ void KJotsWidget::onRepeatReplace() { - KJotsReplaceNextDialog *dlg = 0; + KJotsReplaceNextDialog *dlg = nullptr; QString searchPattern = replaceDialog->pattern(); QString replacePattern = replaceDialog->replacement(); int found = 0; int replaced = 0; long replaceOptions = replaceDialog->options(); if (replaceOptions & KReplaceDialog::PromptOnReplace) { dlg = new KJotsReplaceNextDialog(this); } - forever { + while (true) { if (!search(true)) { break; } QTextCursor cursor = editor->textCursor(); if (!cursor.hasSelection()) { break; } else { ++found; } QString replacementText = replacePattern; if (replaceOptions & KReplaceDialog::BackReference) { QRegExp regExp(searchPattern, (replaceOptions & Qt::CaseSensitive) ? Qt::CaseSensitive : Qt::CaseInsensitive, QRegExp::RegExp2); regExp.indexIn(cursor.selectedText()); int capCount = regExp.captureCount(); for (int i = 0; i <= capCount; ++i) { QString c = QString::fromLatin1("\\%1").arg(i); replacementText.replace(c, regExp.cap(i)); } } if (replaceOptions & KReplaceDialog::PromptOnReplace) { dlg->setLabel(cursor.selectedText(), replacementText); if (!dlg->exec()) { break; } if (dlg->answer() != KJotsReplaceNextDialog::Skip) { cursor.insertText(replacementText); editor->setTextCursor(cursor); ++replaced; } if (dlg->answer() == KJotsReplaceNextDialog::All) { replaceOptions |= ~KReplaceDialog::PromptOnReplace; } } else { cursor.insertText(replacementText); editor->setTextCursor(cursor); ++replaced; } } if (replaced == found) { - KMessageBox::information(0, i18np("Replaced 1 occurrence.", "Replaced %1 occurrences.", replaced)); + KMessageBox::information(nullptr, i18np("Replaced 1 occurrence.", "Replaced %1 occurrences.", replaced)); } else if (replaced < found) { - KMessageBox::information(0, + KMessageBox::information(nullptr, i18np("Replaced %2 of 1 occurrence.", "Replaced %2 of %1 occurrences.", found, replaced)); } if (dlg) { delete dlg; } } /*! Called when user presses Cancel in replace dialog. Just a placeholder for now. */ void KJotsWidget::onEndReplace() { } /*! Searches for the given pattern, with the given options. This is huge and unwieldly function, but the operation we're performing is huge and unwieldly. */ int KJotsWidget::search(bool replacing) { int rc = 0; int *beginPos = replacing ? &replaceBeginPos : &searchBeginPos; int *endPos = replacing ? &replaceEndPos : &searchEndPos; long options = replacing ? replaceDialog->options() : searchDialog->options(); QString pattern = replacing ? replaceDialog->pattern() : searchDialog->pattern(); int *curPos = replacing ? &replacePos : &searchPos; QModelIndex startPage = replacing ? replaceStartPage : treeview->selectionModel()->selectedRows().first(); bool allPages = false; QCheckBox *box = replacing ? replaceAllPages : searchAllPages; if (box->isEnabled() && box->checkState() == Qt::Checked) { allPages = true; } - QTextDocument::FindFlags findFlags = 0; + QTextDocument::FindFlags findFlags; if (options & Qt::CaseSensitive) { findFlags |= QTextDocument::FindCaseSensitively; } if (options & KFind::WholeWordsOnly) { findFlags |= QTextDocument::FindWholeWords; } if (options & KFind::FindBackwards) { findFlags |= QTextDocument::FindBackward; } // We will find a match or return 0 int attempts = 0; - forever { + while (true) { ++attempts; QTextEdit *browserOrEditor = activeEditor(); QTextDocument *theDoc = browserOrEditor->document(); QTextCursor cursor; if (options & KFind::RegularExpression) { QRegExp regExp(pattern, (options & Qt::CaseSensitive) ? Qt::CaseSensitive : Qt::CaseInsensitive, QRegExp::RegExp2); cursor = theDoc->find(regExp, *curPos, findFlags); } else { cursor = theDoc->find(pattern, *curPos, findFlags); } if (cursor.hasSelection()) { if (cursor.selectionStart() >= *beginPos && cursor.selectionEnd() <= *endPos) { browserOrEditor->setTextCursor(cursor); browserOrEditor->ensureCursorVisible(); *curPos = (options & KFind::FindBackwards) ? cursor.selectionStart() : cursor.selectionEnd(); rc = 1; break; } } //No match. Determine what to do next. if (replacing && !(options & KFind::FromCursor) && !allPages) { break; } if ((options & KFind::FromCursor) && !allPages) { if (KMessageBox::questionYesNo(this, i18n("End of search area reached. Do you want to wrap around and continue?")) == KMessageBox::No) { rc = 3; break; } } if (allPages) { if (options & KFind::FindBackwards) { if (canGoPreviousPage()) { prevPage(); } } else { if (canGoNextPage()) { nextPage(); } } if (startPage == treeview->selectionModel()->selectedRows().first()) { rc = 0; break; } *beginPos = 0; cursor = editor->textCursor(); cursor.movePosition(QTextCursor::End); *endPos = cursor.position(); *curPos = (options & KFind::FindBackwards) ? *endPos : *beginPos; continue; } // By now, we should have figured out what to do. In all remaining cases we // will automatically loop and try to "find next" from the top/bottom, because // I like this behavior the best. if (attempts <= 1) { *curPos = (options & KFind::FindBackwards) ? *endPos : *beginPos; } else { // We've already tried the loop and failed to find anything. Bail. rc = 0; break; } } return rc; } void KJotsWidget::updateCaption() { - emit captionChanged(treeview->captionForSelection(QLatin1String(" / "))); + Q_EMIT captionChanged(treeview->captionForSelection(QLatin1String(" / "))); } void KJotsWidget::dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight) { QModelIndexList rows = treeview->selectionModel()->selectedRows(); if (rows.size() != 1) { return; } QItemSelection changed(topLeft, bottomRight); if (changed.contains(rows.first())) { - emit captionChanged(treeview->captionForSelection(QLatin1String(" / "))); + Q_EMIT captionChanged(treeview->captionForSelection(QLatin1String(" / "))); } } bool KJotsWidget::queryClose() { KJotsSettings::setSplitterSizes(m_splitter->sizes()); KJotsSettings::self()->save(); m_orderProxy->saveOrder(); return true; } void KJotsWidget::actionLock() { - QModelIndexList selection = treeview->selectionModel()->selectedRows(); + const QModelIndexList selection = treeview->selectionModel()->selectedRows(); if (selection.isEmpty()) { return; } Collection::List collections; Item::List items; - foreach (const QModelIndex &idx, selection) { + for (const QModelIndex &idx : selection) { Collection col = idx.data(EntityTreeModel::CollectionRole).value(); if (col.isValid()) { collections << col; } else { Item item = idx.data(EntityTreeModel::ItemRole).value(); if (item.isValid()) { items << item; } } } if (collections.isEmpty() && items.isEmpty()) { return; } KJotsLockJob *job = new KJotsLockJob(collections, items, this); } void KJotsWidget::actionUnlock() { - QModelIndexList selection = treeview->selectionModel()->selectedRows(); + const QModelIndexList selection = treeview->selectionModel()->selectedRows(); if (selection.isEmpty()) { return; } Collection::List collections; Item::List items; - foreach (const QModelIndex &idx, selection) { + for (const QModelIndex &idx : selection) { Collection col = idx.data(EntityTreeModel::CollectionRole).value(); if (col.isValid()) { collections << col; } else { Item item = idx.data(EntityTreeModel::ItemRole).value(); if (item.isValid()) { items << item; } } } if (collections.isEmpty() && items.isEmpty()) { return; } KJotsLockJob *job = new KJotsLockJob(collections, items, KJotsLockJob::UnlockJob, this); } void KJotsWidget::actionSortChildrenAlpha() { - QModelIndexList selection = treeview->selectionModel()->selectedRows(); + const QModelIndexList selection = treeview->selectionModel()->selectedRows(); - foreach (const QModelIndex &index, selection) { + for (const QModelIndex &index : selection) { const QPersistentModelIndex persistent(index); m_sortProxyModel->sortChildrenAlphabetically(m_orderProxy->mapToSource(index)); m_orderProxy->clearOrder(persistent); } } void KJotsWidget::actionSortChildrenByDate() { - QModelIndexList selection = treeview->selectionModel()->selectedRows(); + const QModelIndexList selection = treeview->selectionModel()->selectedRows(); - foreach (const QModelIndex &index, selection) { + for (const QModelIndex &index : selection) { const QPersistentModelIndex persistent(index); m_sortProxyModel->sortChildrenByCreationTime(m_orderProxy->mapToSource(index)); m_orderProxy->clearOrder(persistent); } } diff --git a/src/kjotswidget.h b/src/kjotswidget.h index 81a7b3b..ae8b1f3 100644 --- a/src/kjotswidget.h +++ b/src/kjotswidget.h @@ -1,209 +1,209 @@ /* This file is part of KJots. Copyright (C) 1997 Christoph Neerfeld Copyright (C) 2002, 2003 Aaron J. Seigo Copyright (C) 2003 Stanislav Kljuhhin Copyright (C) 2005-2006 Jaison Lee Copyright (C) 2007-2009 Stephen Kelly This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef KJOTSWIDGET_H #define KJOTSWIDGET_H #include #include #include #include #include #include class QCheckBox; class QTextEdit; class QTextCharFormat; class QSplitter; class QStackedWidget; class QModelIndex; class KActionMenu; class KFindDialog; class KJob; class KReplaceDialog; class KSelectionProxyModel; class KJotsBrowser; class KXMLGUIClient; namespace Akonadi { class EntityTreeModel; class EntityOrderProxyModel; } namespace Grantlee { class Engine; } class KJotsEdit; class KJotsTreeView; class KJotsSortProxyModel; class KJotsWidget : public QWidget { Q_OBJECT Q_CLASSINFO("D-Bus Interface", "org.kde.KJotsWidget") public: - KJotsWidget(QWidget *parent, KXMLGUIClient *xmlGuiclient, Qt::WindowFlags f = 0); + explicit KJotsWidget(QWidget *parent, KXMLGUIClient *xmlGuiclient, Qt::WindowFlags f = 0); ~KJotsWidget(); QTextEdit *activeEditor(); -public slots: +public Q_SLOTS: void prevPage(); void nextPage(); void prevBook(); void nextBook(); bool canGoNextPage() const; bool canGoPreviousPage() const; bool canGoNextBook() const; bool canGoPreviousBook() const; void updateCaption(); void updateMenu(); void doCreateNewPage(const Akonadi::Collection &collection); Q_SCRIPTABLE void newPage(); Q_SCRIPTABLE void newBook(); Q_SCRIPTABLE bool queryClose(); -signals: +Q_SIGNALS: void canGoNextPageChanged(bool); void canGoPreviousPageChanged(bool); void canGoNextBookChanged(bool); void canGoPreviousBookChanged(bool); void captionChanged(const QString &newCaption); /** Signals that the text cursor in the editor is now on a different anchor, or not on an anchor anymore. @param anchorTarget The href of the focused anchor. @param anchorText The display text of the focused anchor. */ void activeAnchorChanged(const QString &anchorTarget, const QString &anchorText); protected: QString renderSelectionToHtml(); QString renderSelectionToXml(); QString renderSelectionToPlainText(); QString getThemeFromUser(); void selectNext(int role, int step); int search(bool); void migrateNoteData(const QString &migrator, const QString &type = QString()); -protected slots: +protected Q_SLOTS: void renderSelection(); void changeTheme(); void exportSelectionToHtml(); void exportSelectionToPlainText(); void exportSelectionToXml(); void printSelection(); void printPreviewSelection(); void deletePage(); void deleteBook(); void deleteMultiple(); -private slots: +private Q_SLOTS: void delayedInitialization(); void selectionChanged(const QItemSelection &selected, const QItemSelection &deselected); void dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight); void bookshelfEditItemFinished(QWidget *, QAbstractItemDelegate::EndEditHint); bool canGo(int role, int step) const; void newPageResult(KJob *job); void newBookResult(KJob *job); void copySelectionToTitle(); void copy(); void configure(); void onShowSearch(); void onUpdateSearch(); void onStartSearch(); void onRepeatSearch(); void onEndSearch(); void onShowReplace(); void onUpdateReplace(); void onStartReplace(); void onRepeatReplace(); void onEndReplace(); void actionLock(); void actionUnlock(); void actionSortChildrenAlpha(); void actionSortChildrenByDate(); void saveState(); void restoreState(); void currentCharFormatChanged(const QTextCharFormat &); void updateConfiguration(); private: void print(QPrinter &printer); KXMLGUIClient *m_xmlGuiClient; KJotsEdit *editor; KJotsBrowser *browser; QStackedWidget *stackedWidget; KActionMenu *bookmarkMenu; Akonadi::EntityTreeModel *m_kjotsModel; KSelectionProxyModel *selProxy; KJotsSortProxyModel *m_sortProxyModel; Akonadi::EntityOrderProxyModel *m_orderProxy; KJotsTreeView *treeview; QSplitter *m_splitter; QTimer *m_autosaveTimer; QString activeAnchor; Grantlee::Engine *m_templateEngine; QSharedPointer m_loader; KFindDialog *searchDialog; QStringList searchHistory; int searchBeginPos, searchEndPos, searchPos; QCheckBox *searchAllPages; KReplaceDialog *replaceDialog; QStringList replaceHistory; int replaceBeginPos, replaceEndPos, replacePos; QCheckBox *replaceAllPages; QModelIndex replaceStartPage; QSet entryActions, pageActions, bookActions, multiselectionActions; }; #endif diff --git a/src/knowitimporter.cpp b/src/knowitimporter.cpp index 2daa05f..d08d54e 100644 --- a/src/knowitimporter.cpp +++ b/src/knowitimporter.cpp @@ -1,255 +1,256 @@ /* * This file is part of KJots * * Copyright 2008 Stephen Kelly * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301 USA */ #include "knowitimporter.h" #include #include #include #include #include #include #include KnowItImporter::KnowItImporter() { } void KnowItImporter::importFromUrl(const QUrl &url) { // TODO PORT #if 0 KJotsBook *book = new KJotsBook(); buildNoteTree(url); // foreach () // qDebug(); buildDomDocument(); QTemporaryFile file; //code was file.setPrefix( QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation) + QLatin1Char('/') + "kjots/" ) ; //Add to constructor and adapt if necessay: QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation) + QLatin1Char('/') + "kjots/" QLatin1String("/myapp_XXXXXX.txt") //code was file.setSuffix( ".book" ); //Add to constructor and adapt if necessay: QDir::tempPath() + QLatin1String("/myapp_XXXXXX") + QLatin1String( ".book" ) file.setAutoRemove(false); if (file.open()) { file.write("\n\n\n"); file.write(m_domDoc.toByteArray()); file.write("\n"); qDebug() << file.fileName(); QString newFileName = file.fileName(); file.close(); book->openBook(newFileName); } return book; #endif } QDomElement KnowItImporter::addNote(const KnowItNote ¬e) { QDomElement newElement; int childNotesCount = m_childNotes[ note.id ].size(); // int childNotesCount = note.childNotes.size(); qDebug() << note.title << childNotesCount; if (childNotesCount > 0) { newElement = m_domDoc.createElement(QLatin1String("KJotsBook")); } else { newElement = m_domDoc.createElement(QLatin1String("KJotsPage")); } QDomElement titleTag = m_domDoc.createElement(QLatin1String("Title")); titleTag.appendChild(m_domDoc.createTextNode(note.title)); newElement.appendChild(titleTag); QDomElement idTag = m_domDoc.createElement(QLatin1String("ID")); idTag.appendChild(m_domDoc.createTextNode(QLatin1String("0"))); // Gets a valid id later. newElement.appendChild(idTag); if (childNotesCount > 0) { QDomElement openTag = m_domDoc.createElement(QLatin1String("Open")); openTag.appendChild(m_domDoc.createTextNode(QLatin1String("1"))); newElement.appendChild(openTag); QDomElement titlePage = m_domDoc.createElement(QLatin1String("KJotsPage")); QDomElement titlePageTitleTag = m_domDoc.createElement(QLatin1String("Title")); titlePageTitleTag.appendChild(m_domDoc.createTextNode(note.title)); titlePage.appendChild(titlePageTitleTag); QDomElement titlePageIdTag = m_domDoc.createElement(QLatin1String("ID")); titlePageIdTag.appendChild(m_domDoc.createTextNode(QLatin1String("0"))); // Gets a valid id later. titlePage.appendChild(titlePageIdTag); QDomElement titlePageTextTag = m_domDoc.createElement(QLatin1String("Text")); titlePageTextTag.appendChild(m_domDoc.createCDATASection(note.content)); titlePage.appendChild(titlePageTextTag); newElement.appendChild(titlePage); - foreach (int id, m_childNotes[ note.id ]) { + const QList ids = m_childNotes[ note.id ]; + for (int id : ids) { QDomElement e = addNote(m_noteHash.value(id)); newElement.appendChild(e); } } else { QString contents = note.content; if (note.links.size() > 0) { if (contents.endsWith(QLatin1String(""))) { contents.chop(14); } contents.append(QLatin1String("

Links:

\n
    \n")); for (int i = 0; i < note.links.size(); ++i) { qDebug() << "link" << note.links[i].first << note.links[i].second; contents.append(QString::fromLatin1("
  • %2
  • \n") .arg(note.links[i].first) .arg(note.links[i].second)); } contents.append(QLatin1String("
")); } QDomElement textTag = m_domDoc.createElement(QLatin1String("Text")); textTag.appendChild(m_domDoc.createCDATASection(contents)); newElement.appendChild(textTag); } return newElement; } void KnowItImporter::buildDomDocument() { QDomElement parent = m_domDoc.createElement(QLatin1String("KJotsBook")); QDomElement titleTag = m_domDoc.createElement(QLatin1String("Title")); titleTag.appendChild(m_domDoc.createTextNode(i18nc("Name for the top level book created to hold the imported data.", "KNowIt Import"))); parent.appendChild(titleTag); QDomElement idTag = m_domDoc.createElement(QLatin1String("ID")); idTag.appendChild(m_domDoc.createTextNode(QLatin1String("0"))); // Gets a valid id later. parent.appendChild(idTag); QDomElement openTag = m_domDoc.createElement(QLatin1String("Open")); openTag.appendChild(m_domDoc.createTextNode(QLatin1String("1"))); parent.appendChild(openTag); m_domDoc.appendChild(parent); - foreach (const KnowItNote &n, m_notes) { + for (const KnowItNote &n : qAsConst(m_notes)) { QDomElement e = addNote(n); parent.appendChild(e); qDebug() << n.title; } qDebug() << m_domDoc.toString(); } void KnowItImporter::buildNoteTree(const QUrl &url) { QFile knowItFile(url.toLocalFile()); if (knowItFile.open(QIODevice::ReadOnly | QIODevice::Text)) { QSet entryHeaders; entryHeaders << "\\NewEntry" << "\\CurrentEntry"; int id = 1; QTextStream in(&knowItFile); while (!in.atEnd()) { QString line = in.readLine(); qDebug() << "got line: " << line; if (line.trimmed().isEmpty()) { continue; } - foreach (const QByteArray &header, entryHeaders) { + for (const QByteArray &header : qAsConst(entryHeaders)) { if (line.startsWith(QLatin1String(header))) { qDebug() << "init" << line << header; line = line.right(line.size() - header.size()).trimmed(); qDebug() << "header tag removed: " << line; QStringList list = line.split(QLatin1Char(' ')); int startOfTitle = line.indexOf(QLatin1Char(' ')); bool ok = false; qDebug() << "depth" << list.at(0).trimmed(); int depth = list.at(0).trimmed().toInt(&ok); qDebug() << ok << "valid depth"; if (ok) { QString title = line.right(line.size() - startOfTitle).trimmed(); KnowItNote n; n.title = title; n.depth = depth; n.id = id; if (depth == 0) { n.parent = 0; } else { n.parent = m_lastNoteAtLevel[depth - 1].id; } QString contentLine = in.readLine(); //QList< QPair > links; QString contents; QString url; QString target; while ((!in.atEnd()) && (!contentLine.trimmed().isEmpty())) { qDebug() << contentLine; if (contentLine.startsWith(QLatin1String("\\Link"))) { url = contentLine.right(contentLine.size() - 5).trimmed(); contentLine = in.readLine(); continue; } if (contentLine.startsWith(QLatin1String("\\Descr"))) { target = contentLine.right(contentLine.size() - 6).trimmed(); contentLine = in.readLine(); continue; } if (!url.isEmpty() && !target.isEmpty()) { QPair< QString, QString > link; link.first = url; link.second = target; n.links << link; url.clear(); target.clear(); } contents.append(contentLine); contentLine = in.readLine(); } n.content = contents; m_noteHash.insert(id, n); m_childNotes[n.parent].append(id); id++; if (m_lastNoteAtLevel.size() == depth) { m_lastNoteAtLevel.append(n); } else { m_lastNoteAtLevel[depth] = n; } if (depth == 0) { m_notes.append(n); } } break; // If found first header, don't check for second one. } } // Foreach header. } // At end of stream } // File open. } diff --git a/src/kontact_plugin/kjots_plugin.cpp b/src/kontact_plugin/kjots_plugin.cpp index 8e7cc53..66e7ed5 100644 --- a/src/kontact_plugin/kjots_plugin.cpp +++ b/src/kontact_plugin/kjots_plugin.cpp @@ -1,102 +1,98 @@ /* Copyright (C) 2016 Daniel Vrátil This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. As a special exception, permission is given to link this program with any edition of Qt, and distribute the resulting executable, without including the source code for Qt in the source distribution. */ #include "kjots_plugin.h" #include "kjotspart.h" //#include "akregator_options.h" //#include "partinterface.h" #include #include #include #include #include #include EXPORT_KONTACT_PLUGIN(KJotsPlugin, kjots) KJotsPlugin::KJotsPlugin(KontactInterface::Core *core, const QVariantList &) : KontactInterface::Plugin(core, core, "kjots") { setComponentName(QStringLiteral("kjots"), QStringLiteral("kjots")); mUniqueAppWatcher = new KontactInterface::UniqueAppWatcher( new KontactInterface::UniqueAppHandlerFactory(), this); } -KJotsPlugin::~KJotsPlugin() -{ -} - void KJotsPlugin::setHelpText(QAction *action, const QString &text) { action->setStatusTip(text); action->setToolTip(text); if (action->whatsThis().isEmpty()) { action->setWhatsThis(text); } } bool KJotsPlugin::isRunningStandalone() const { return mUniqueAppWatcher->isRunningStandalone(); } QStringList KJotsPlugin::invisibleToolbarActions() const { return { QStringLiteral("new_page"), QStringLiteral("new_book") }; } KParts::ReadOnlyPart *KJotsPlugin::createPart() { KParts::ReadOnlyPart *part = loadPart(); if (!part) { - return Q_NULLPTR; + return nullptr; } return part; } QStringList KJotsPlugin::configModules() const { QStringList modules; modules << QStringLiteral("PIM/kjots.desktop"); return modules; } void KJotsUniqueAppHandler::loadCommandLineOptions(QCommandLineParser *parser) { - Q_UNUSED(parser); + Q_UNUSED(parser) } int KJotsUniqueAppHandler::activate(const QStringList &args, const QString &workingDir) { // Ensure part is loaded (void)plugin()->part(); return KontactInterface::UniqueAppHandler::activate(args, workingDir); } #include "kjots_plugin.moc" diff --git a/src/kontact_plugin/kjots_plugin.h b/src/kontact_plugin/kjots_plugin.h index 7c94128..cd62373 100644 --- a/src/kontact_plugin/kjots_plugin.h +++ b/src/kontact_plugin/kjots_plugin.h @@ -1,74 +1,73 @@ /* Copyright (C) 2016 Daniel Vrátil This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public Licensea along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. As a special exception, permission is given to link this program with any edition of Qt, and distribute the resulting executable, without including the source code for Qt in the source distribution. */ #ifndef KJOTS_PLUGIN_H #define KJOTS_PLUGIN_H #include namespace KontactInterface { class Plugin; } class KJotsUniqueAppHandler : public KontactInterface::UniqueAppHandler { Q_OBJECT public: explicit KJotsUniqueAppHandler(KontactInterface::Plugin *plugin) : KontactInterface::UniqueAppHandler(plugin) { } int activate(const QStringList &args, const QString &workingDir) Q_DECL_OVERRIDE; void loadCommandLineOptions(QCommandLineParser *parser) Q_DECL_OVERRIDE; }; class KJotsPlugin : public KontactInterface::Plugin { Q_OBJECT public: KJotsPlugin(KontactInterface::Core *core, const QVariantList &); - ~KJotsPlugin(); int weight() const Q_DECL_OVERRIDE { return 475; } virtual QStringList configModules() const; bool isRunningStandalone() const Q_DECL_OVERRIDE; QStringList invisibleToolbarActions() const Q_DECL_OVERRIDE; protected: KParts::ReadOnlyPart *createPart() Q_DECL_OVERRIDE; KontactInterface::UniqueAppWatcher *mUniqueAppWatcher; private: void setHelpText(QAction *action, const QString &text); }; #endif diff --git a/src/localresourcecreator.cpp b/src/localresourcecreator.cpp index 4898584..d370f20 100644 --- a/src/localresourcecreator.cpp +++ b/src/localresourcecreator.cpp @@ -1,175 +1,175 @@ /* Copyright (C) 2010 Klarälvdalens Datakonsult AB, a KDAB Group company, info@kdab.net, author Stephen Kelly This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "localresourcecreator.h" #include "akonadi_next/note.h" #include #include #include #include #include #include #include #include #include #include #include LocalResourceCreator::LocalResourceCreator(QObject *parent) : NoteShared::LocalResourceCreator(parent) { } void LocalResourceCreator::finishCreateResource() { Akonadi::CollectionFetchJob *collectionFetchJob = new Akonadi::CollectionFetchJob(Akonadi::Collection::root(), Akonadi::CollectionFetchJob::FirstLevel, this); connect(collectionFetchJob, &Akonadi::CollectionFetchJob::result, this, &LocalResourceCreator::rootFetchFinished); } void LocalResourceCreator::rootFetchFinished(KJob *job) { if (job->error()) { qWarning() << job->errorString(); deleteLater(); return; } Akonadi::CollectionFetchJob *lastCollectionFetchJob = qobject_cast(job); if (!lastCollectionFetchJob) { deleteLater(); return; } Akonadi::Collection::List list = lastCollectionFetchJob->collections(); if (list.isEmpty()) { qWarning() << "Couldn't find new collection in resource"; deleteLater(); return; } - foreach (const Akonadi::Collection &col, list) { + for (const Akonadi::Collection &col : qAsConst(list)) { Akonadi::AgentInstance instance = Akonadi::AgentManager::self()->instance(col.resource()); if (instance.type().identifier() == akonadiNotesInstanceName()) { Akonadi::CollectionFetchJob *collectionFetchJob = new Akonadi::CollectionFetchJob(col, Akonadi::CollectionFetchJob::FirstLevel, this); collectionFetchJob->setProperty("FetchedCollection", col.id()); connect(collectionFetchJob, &Akonadi::CollectionFetchJob::result, this, &LocalResourceCreator::topLevelFetchFinished); return; } } Q_ASSERT(!"Couldn't find new collection"); deleteLater(); } void LocalResourceCreator::topLevelFetchFinished(KJob *job) { if (job->error()) { qWarning() << job->errorString(); deleteLater(); return; } Akonadi::CollectionFetchJob *lastCollectionFetchJob = qobject_cast(job); if (!lastCollectionFetchJob) { deleteLater(); return; } Akonadi::Collection::List list = lastCollectionFetchJob->collections(); if (!list.isEmpty()) { deleteLater(); return; } Akonadi::Collection::Id id = lastCollectionFetchJob->property("FetchedCollection").toLongLong(); Akonadi::Collection collection; collection.setParentCollection(Akonadi::Collection(id)); QString title = i18nc("The default name for new books.", "New Book"); collection.setName(KRandom::randomString(10)); collection.setContentMimeTypes(QStringList() << Akonadi::Collection::mimeType() << Akonotes::Note::mimeType()); Akonadi::EntityDisplayAttribute *eda = new Akonadi::EntityDisplayAttribute(); eda->setIconName(QLatin1String("x-office-address-book")); eda->setDisplayName(title); collection.addAttribute(eda); Akonadi::CollectionCreateJob *createJob = new Akonadi::CollectionCreateJob(collection, this); connect(createJob, &Akonadi::CollectionCreateJob::result, this, &LocalResourceCreator::createFinished); } void LocalResourceCreator::createFinished(KJob *job) { if (job->error()) { qWarning() << job->errorString(); deleteLater(); return; } Akonadi::CollectionCreateJob *collectionCreateJob = qobject_cast(job); if (!collectionCreateJob) { deleteLater(); return; } Akonadi::Item item; item.setParentCollection(collectionCreateJob->collection()); item.setMimeType(Akonotes::Note::mimeType()); KMime::Message::Ptr note(new KMime::Message()); QString title = i18nc("The default name for new pages.", "New Page"); QByteArray encoding("utf-8"); note->subject(true)->fromUnicodeString(title, encoding); note->contentType(true)->setMimeType("text/plain"); note->date(true)->setDateTime(QDateTime::currentDateTime()); note->from(true)->fromUnicodeString(QLatin1String("Kjots@kde4"), encoding); // Need a non-empty body part so that the serializer regards this as a valid message. note->mainBodyPart()->fromUnicodeString(QLatin1String(" ")); note->assemble(); item.setPayload(note); Akonadi::EntityDisplayAttribute *eda = new Akonadi::EntityDisplayAttribute(); eda->setIconName(QLatin1String("text-plain")); item.addAttribute(eda); Akonadi::ItemCreateJob *itemCreateJob = new Akonadi::ItemCreateJob(item, collectionCreateJob->collection(), this); connect(itemCreateJob, &Akonadi::ItemCreateJob::result, this, &LocalResourceCreator::itemCreateFinished); } void LocalResourceCreator::itemCreateFinished(KJob *job) { if (job->error()) { qWarning() << job->errorString(); } deleteLater(); } diff --git a/src/localresourcecreator.h b/src/localresourcecreator.h index 6d795d7..d212ed7 100644 --- a/src/localresourcecreator.h +++ b/src/localresourcecreator.h @@ -1,51 +1,51 @@ /* Copyright (C) 2010 Klarälvdalens Datakonsult AB, a KDAB Group company, info@kdab.net, author Stephen Kelly This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef LOCALRESOURCECREATOR_H #define LOCALRESOURCECREATOR_H #include #include "noteshared/localresourcecreator.h" class KJob; /** * @brief Creates a notes resource, a book and a page if one does not already exist. */ class LocalResourceCreator : public NoteShared::LocalResourceCreator { Q_OBJECT public: - explicit LocalResourceCreator(QObject *parent = 0); + explicit LocalResourceCreator(QObject *parent = nullptr); protected: - virtual void finishCreateResource(); + void finishCreateResource() override; -private slots: +private Q_SLOTS: void rootFetchFinished(KJob *job); void topLevelFetchFinished(KJob *job); void createFinished(KJob *job); void itemCreateFinished(KJob *job); }; #endif diff --git a/src/noteshared/localresourcecreator.cpp b/src/noteshared/localresourcecreator.cpp index 26e5d32..a5314d4 100644 --- a/src/noteshared/localresourcecreator.cpp +++ b/src/noteshared/localresourcecreator.cpp @@ -1,121 +1,121 @@ /* Copyright (c) 2013-2015 Montel Laurent based on localresourcecreator from kjots This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License, version 2, as published by the Free Software Foundation. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "localresourcecreator.h" #include #include #pragma message("port QT5") #include "maildirsettings.h" #include #include "noteshared_debug.h" #include #include using namespace NoteShared; LocalResourceCreator::LocalResourceCreator(QObject *parent) : QObject(parent) { } QString LocalResourceCreator::akonadiNotesInstanceName() { return QStringLiteral("akonadi_akonotes_resource"); } void LocalResourceCreator::createIfMissing() { - Akonadi::AgentInstance::List instances = Akonadi::AgentManager::self()->instances(); + const Akonadi::AgentInstance::List instances = Akonadi::AgentManager::self()->instances(); bool found = false; - foreach (const Akonadi::AgentInstance &instance, instances) { + for (const Akonadi::AgentInstance &instance : instances) { if (instance.type().identifier() == akonadiNotesInstanceName()) { found = true; break; } } if (found) { deleteLater(); return; } createInstance(); } void LocalResourceCreator::createInstance() { Akonadi::AgentType notesType = Akonadi::AgentManager::self()->type(akonadiNotesInstanceName()); Akonadi::AgentInstanceCreateJob *job = new Akonadi::AgentInstanceCreateJob(notesType); connect(job, &Akonadi::AgentInstanceCreateJob::result, this, &LocalResourceCreator::slotInstanceCreated); job->start(); } void LocalResourceCreator::slotInstanceCreated(KJob *job) { if (job->error()) { qCWarning(NOTESHARED_LOG) << job->errorString(); deleteLater(); return; } Akonadi::AgentInstanceCreateJob *createJob = qobject_cast(job); Akonadi::AgentInstance instance = createJob->instance(); instance.setName(i18nc("Default name for resource holding notes", "Local Notes")); org::kde::Akonadi::Maildir::Settings *iface = new org::kde::Akonadi::Maildir::Settings( QLatin1String("org.freedesktop.Akonadi.Resource.") + instance.identifier(), QStringLiteral("/Settings"), QDBusConnection::sessionBus(), this); // TODO: Make errors user-visible. if (!iface->isValid()) { qCWarning(NOTESHARED_LOG) << "Failed to obtain D-Bus interface for remote configuration."; delete iface; deleteLater(); return; } delete iface; instance.reconfigure(); Akonadi::ResourceSynchronizationJob *syncJob = new Akonadi::ResourceSynchronizationJob(instance, this); connect(syncJob, &Akonadi::ResourceSynchronizationJob::result, this, &LocalResourceCreator::slotSyncDone); syncJob->start(); } void LocalResourceCreator::slotSyncDone(KJob *job) { if (job->error()) { qCWarning(NOTESHARED_LOG) << "Synchronizing the resource failed:" << job->errorString(); deleteLater(); return; } qCWarning(NOTESHARED_LOG) << "Instance synchronized"; } void LocalResourceCreator::finishCreateResource() { deleteLater(); } diff --git a/src/noteshared/localresourcecreator.h b/src/noteshared/localresourcecreator.h index c644445..5024ec5 100644 --- a/src/noteshared/localresourcecreator.h +++ b/src/noteshared/localresourcecreator.h @@ -1,48 +1,48 @@ /* Copyright (c) 2013-2015 Montel Laurent This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License, version 2, as published by the Free Software Foundation. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef NOTESHAREDLOCALRESOURCECREATOR_H #define NOTESHAREDLOCALRESOURCECREATOR_H #include class KJob; namespace NoteShared { class LocalResourceCreator : public QObject { Q_OBJECT public: - explicit LocalResourceCreator(QObject *parent = Q_NULLPTR); + explicit LocalResourceCreator(QObject *parent = nullptr); void createIfMissing(); static QString akonadiNotesInstanceName(); protected: virtual void finishCreateResource(); private: void createInstance(); private Q_SLOTS: void slotInstanceCreated(KJob *job); void slotSyncDone(KJob *job); }; } #endif diff --git a/src/noteshared/notelockattribute.cpp b/src/noteshared/notelockattribute.cpp index f012001..42cb099 100644 --- a/src/noteshared/notelockattribute.cpp +++ b/src/noteshared/notelockattribute.cpp @@ -1,58 +1,53 @@ /* Copyright (C) 2010 Klarälvdalens Datakonsult AB, a KDAB Group company, info@kdab.net, author Stephen Kelly This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "notelockattribute.h" #include using namespace NoteShared; NoteLockAttribute::NoteLockAttribute() : Akonadi::Attribute() { } -NoteLockAttribute::~NoteLockAttribute() -{ - -} - NoteLockAttribute *NoteLockAttribute::clone() const { return new NoteLockAttribute(); } void NoteLockAttribute::deserialize(const QByteArray &data) { - Q_UNUSED(data); + Q_UNUSED(data) } QByteArray NoteLockAttribute::serialized() const { return "-"; } QByteArray NoteLockAttribute::type() const { //We can't change this name! static const QByteArray sType("KJotsLockAttribute"); return sType; } diff --git a/src/noteshared/notelockattribute.h b/src/noteshared/notelockattribute.h index c6272aa..f010e2f 100644 --- a/src/noteshared/notelockattribute.h +++ b/src/noteshared/notelockattribute.h @@ -1,45 +1,44 @@ /* Copyright (C) 2010 Klarälvdalens Datakonsult AB, a KDAB Group company, info@kdab.net, author Stephen Kelly This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef KJOTS_LOCK_ATTRIBUTE_H #define KJOTS_LOCK_ATTRIBUTE_H #include namespace NoteShared { class NoteLockAttribute : public Akonadi::Attribute { public: - NoteLockAttribute(); - ~NoteLockAttribute(); + explicit NoteLockAttribute(); QByteArray type() const Q_DECL_OVERRIDE; NoteLockAttribute *clone() const Q_DECL_OVERRIDE; QByteArray serialized() const Q_DECL_OVERRIDE; void deserialize(const QByteArray &data) Q_DECL_OVERRIDE; }; } #endif