diff --git a/.clang-format b/.clang-format index 232c21cb7..9038ae5cb 100644 --- a/.clang-format +++ b/.clang-format @@ -50,7 +50,7 @@ BreakConstructorInitializersBeforeComma: false BreakConstructorInitializers: BeforeColon BreakAfterJavaFieldAnnotations: false BreakStringLiterals: true -ColumnLimit: 80 +ColumnLimit: 100 CommentPragmas: '^ IWYU pragma:' CompactNamespaces: false ConstructorInitializerAllOnOneLineOrOnePerLine: true diff --git a/.git-blame-ignore-revs b/.git-blame-ignore-revs new file mode 100644 index 000000000..bee71d393 --- /dev/null +++ b/.git-blame-ignore-revs @@ -0,0 +1,3 @@ +ee2b94b4dd6ae24077da9ed9bf54b2162f578518 +232056ddbd0d78196ea1d3091a07b94ab672a479 +18a3d6f5060b89a7217dd23e0bc2d956084bd34b diff --git a/src/api/noteapi.cpp b/src/api/noteapi.cpp index 47577f36a..cee66c0c5 100644 --- a/src/api/noteapi.cpp +++ b/src/api/noteapi.cpp @@ -132,7 +132,7 @@ bool NoteApi::removeTag(QString tagName) { * @param newName new file name (without file-extension) * @return true if the note was renamed */ -bool NoteApi::renameNoteFile(const QString &newName) { +bool NoteApi::renameNoteFile(const QString& newName) { Note note = Note::fetch(_id); if (note.isFetched()) { @@ -147,9 +147,7 @@ bool NoteApi::renameNoteFile(const QString &newName) { * * @return bool */ -bool NoteApi::allowDifferentFileName() { - return Note::allowDifferentFileName(); -} +bool NoteApi::allowDifferentFileName() { return Note::allowDifferentFileName(); } /** * Fetches all notes @@ -181,8 +179,7 @@ QQmlListProperty NoteApi::fetchAll(int limit, int offset) { * @return */ QString NoteApi::toMarkdownHtml(bool forExport) { - return _note.toMarkdownHtml(NoteFolder::currentLocalPath(), 980, forExport, - true, true); + return _note.toMarkdownHtml(NoteFolder::currentLocalPath(), 980, forExport, true, true); } /** @@ -195,8 +192,7 @@ QString NoteApi::getFileURLFromFileName(const QString& localFileName) { return _note.getFileURLFromFileName(localFileName); } -void NoteApi::copy(const Note ¬e) -{ +void NoteApi::copy(const Note& note) { _note = note; if (_note.isFetched()) { diff --git a/src/api/noteapi.h b/src/api/noteapi.h index 45937e72c..b3b595585 100644 --- a/src/api/noteapi.h +++ b/src/api/noteapi.h @@ -19,8 +19,7 @@ class NoteApi : public QObject, public Note { Q_PROPERTY(QString relativeNoteFileDirPath READ relativeNoteSubFolderPath() CONSTANT) Q_PROPERTY(int noteSubFolderId READ getNoteSubFolderId() CONSTANT) Q_PROPERTY(QString noteText READ getNoteText() WRITE setNoteText()) - Q_PROPERTY(QString decryptedNoteText READ fetchDecryptedNoteText() - WRITE setDecryptedNoteText()) + Q_PROPERTY(QString decryptedNoteText READ fetchDecryptedNoteText() WRITE setDecryptedNoteText()) Q_PROPERTY(QDateTime fileCreated READ getFileCreated() CONSTANT) Q_PROPERTY(QDateTime fileLastModified READ getFileLastModified() CONSTANT) Q_PROPERTY(bool hasDirtyData READ getHasDirtyData() CONSTANT) @@ -40,8 +39,7 @@ class NoteApi : public QObject, public Note { Q_INVOKABLE bool addTag(const QString &tagName); Q_INVOKABLE bool removeTag(QString tagName); Q_INVOKABLE bool renameNoteFile(const QString &newName); - Q_INVOKABLE QQmlListProperty fetchAll(int limit = -1, - int offset = -1); + Q_INVOKABLE QQmlListProperty fetchAll(int limit = -1, int offset = -1); Q_INVOKABLE QString toMarkdownHtml(bool forExport = true); Q_INVOKABLE QString getFileURLFromFileName(const QString &localFileName); Q_INVOKABLE static bool allowDifferentFileName(); diff --git a/src/api/notesubfolderapi.cpp b/src/api/notesubfolderapi.cpp index b36a9396b..f34fc00ff 100644 --- a/src/api/notesubfolderapi.cpp +++ b/src/api/notesubfolderapi.cpp @@ -18,7 +18,7 @@ NoteSubFolderApi *NoteSubFolderApi::fetch(int id) { } NoteSubFolderApi *NoteSubFolderApi::fromNoteSubFolder(const NoteSubFolder ¬eSubFolder) { - auto* noteSubFolderApi = new NoteSubFolderApi(); + auto *noteSubFolderApi = new NoteSubFolderApi(); noteSubFolderApi->fetch(noteSubFolder.getId()); return noteSubFolderApi; } @@ -36,7 +36,7 @@ QQmlListProperty NoteSubFolderApi::notes() { while (itr.hasNext()) { Note note = itr.next(); - auto* noteApi = new NoteApi(); + auto *noteApi = new NoteApi(); noteApi->fetch(note.getId()); _notes.append(noteApi); } @@ -54,8 +54,7 @@ QQmlListProperty NoteSubFolderApi::notes() { * @param id int the id of the note subfolder * @return NoteSubFolderApi* */ -NoteSubFolderApi *NoteSubFolderApi::fetchNoteSubFolderById(int id) -{ +NoteSubFolderApi *NoteSubFolderApi::fetchNoteSubFolderById(int id) { auto *noteSubFolder = new NoteSubFolderApi(); noteSubFolder->fetch(id); return noteSubFolder; @@ -67,8 +66,7 @@ NoteSubFolderApi *NoteSubFolderApi::fetchNoteSubFolderById(int id) * @param parentId int the id of the parent note subfolder * @return QList */ -QList NoteSubFolderApi::fetchNoteSubFoldersByParentId(int parentId) -{ +QList NoteSubFolderApi::fetchNoteSubFoldersByParentId(int parentId) { QList noteSubFolderApis; const auto noteSubFolders = NoteSubFolder::fetchAllByParentId(parentId); @@ -83,10 +81,6 @@ NoteSubFolderApi *NoteSubFolderApi::activeNoteSubFolder() { return fetchNoteSubFolderById(NoteSubFolder::activeNoteSubFolderId()); } -QString NoteSubFolderApi::relativePath() { - return _noteSubFolder.relativePath(); -} +QString NoteSubFolderApi::relativePath() { return _noteSubFolder.relativePath(); } -QString NoteSubFolderApi::fullPath() { - return _noteSubFolder.fullPath(); -} +QString NoteSubFolderApi::fullPath() { return _noteSubFolder.fullPath(); } diff --git a/src/api/notesubfolderapi.h b/src/api/notesubfolderapi.h index fa6a551c4..273b346fb 100644 --- a/src/api/notesubfolderapi.h +++ b/src/api/notesubfolderapi.h @@ -24,7 +24,7 @@ class NoteSubFolderApi : public QObject, public NoteSubFolder { Q_INVOKABLE static NoteSubFolderApi *fetchNoteSubFolderById(int id); Q_INVOKABLE static NoteSubFolderApi *activeNoteSubFolder(); - Q_INVOKABLE static QList fetchNoteSubFoldersByParentId(int parentId); + Q_INVOKABLE static QList fetchNoteSubFoldersByParentId(int parentId); Q_INVOKABLE QQmlListProperty notes(); Q_INVOKABLE QString relativePath(); diff --git a/src/api/tagapi.cpp b/src/api/tagapi.cpp index b536d36db..b207e5534 100644 --- a/src/api/tagapi.cpp +++ b/src/api/tagapi.cpp @@ -40,8 +40,7 @@ TagApi* TagApi::fromTag(const Tag& tag) { return tagApi; } -void TagApi::copy(const Tag &tag) -{ +void TagApi::copy(const Tag& tag) { this->_id = tag.getId(); _name = tag.getName(); _parentId = tag.getParentId(); @@ -53,7 +52,7 @@ void TagApi::copy(const Tag &tag) */ QQmlListProperty TagApi::notes() { _notes.clear(); - + Tag tag = Tag::fetch(_id); QVector notes = tag.fetchAllLinkedNotes(); diff --git a/src/api/tagapi.h b/src/api/tagapi.h index eeccda286..49cefaaeb 100644 --- a/src/api/tagapi.h +++ b/src/api/tagapi.h @@ -20,6 +20,6 @@ class TagApi : public QObject, public Tag { Q_INVOKABLE TagApi *fetchByName(const QString &name, int parentId = 0); Q_INVOKABLE QStringList getParentTagNames(); Q_INVOKABLE QQmlListProperty notes(); - static TagApi* fromTag(const Tag& tag); - void copy(const Tag& t); + static TagApi *fromTag(const Tag &tag); + void copy(const Tag &t); }; diff --git a/src/dialogs/aboutdialog.cpp b/src/dialogs/aboutdialog.cpp index 3cca06ae2..b3f183ab2 100644 --- a/src/dialogs/aboutdialog.cpp +++ b/src/dialogs/aboutdialog.cpp @@ -11,8 +11,7 @@ #include "ui_aboutdialog.h" #include "version.h" -AboutDialog::AboutDialog(QWidget *parent) - : MasterDialog(parent), ui(new Ui::AboutDialog) { +AboutDialog::AboutDialog(QWidget *parent) : MasterDialog(parent), ui(new Ui::AboutDialog) { ui->setupUi(this); // load the about.html @@ -28,17 +27,14 @@ AboutDialog::AboutDialog(QWidget *parent) } // fill in the variables - html.replace(QLatin1String("QT_VERSION_STR"), - QStringLiteral(QT_VERSION_STR)); + html.replace(QLatin1String("QT_VERSION_STR"), QStringLiteral(QT_VERSION_STR)); html.replace(QLatin1String("BUILD_NUMBER"), QString::number(BUILD)); html.replace(QLatin1String("BUILD_DATE"), __DATE__); html.replace(QLatin1String("VERSION"), QStringLiteral(VERSION)); html.replace(QLatin1String("RELEASE"), release); - html.replace(QLatin1String("CURRENT_YEAR"), - QString::number(date.year())); + html.replace(QLatin1String("CURRENT_YEAR"), QString::number(date.year())); - ui->textBrowser->document()->setDefaultStyleSheet( - Utils::Misc::genericCSS()); + ui->textBrowser->document()->setDefaultStyleSheet(Utils::Misc::genericCSS()); // put the html to the text browser in the about dialog ui->textBrowser->setHtml(html); diff --git a/src/dialogs/actiondialog.cpp b/src/dialogs/actiondialog.cpp index 44eda2817..4de6f62d3 100644 --- a/src/dialogs/actiondialog.cpp +++ b/src/dialogs/actiondialog.cpp @@ -1,9 +1,9 @@ #include "actiondialog.h" -//#include +// #include #include -#include #include +#include #include #include "ui_actiondialog.h" @@ -27,7 +27,9 @@ void ActionDialog::refreshUi() { QList menuList = _menuBar->findChildren(QString(), Qt::FindDirectChildrenOnly); - Q_FOREACH (QMenu *menu, menuList) { buildActionTreeForMenu(menu); } + Q_FOREACH (QMenu *menu, menuList) { + buildActionTreeForMenu(menu); + } ui->actionTreeWidget->setRootIsDecorated(false); ui->actionTreeWidget->expandAll(); @@ -42,8 +44,7 @@ void ActionDialog::refreshUi() { * @param menu * @param parentItem */ -void ActionDialog::buildActionTreeForMenu(QMenu *menu, - QTreeWidgetItem *parentItem) { +void ActionDialog::buildActionTreeForMenu(QMenu *menu, QTreeWidgetItem *parentItem) { QString menuText = menu->title().remove(QStringLiteral("&")); if (menuText.isEmpty()) { @@ -60,8 +61,7 @@ void ActionDialog::buildActionTreeForMenu(QMenu *menu, } // search for sub-menus in the menu - QList menuList = - menu->findChildren(QString(), Qt::FindDirectChildrenOnly); + QList menuList = menu->findChildren(QString(), Qt::FindDirectChildrenOnly); // build the tree for that sub-menu Q_FOREACH (QMenu *subMenu, menuList) { @@ -103,8 +103,7 @@ ActionDialog::~ActionDialog() { delete ui; } * @param item * @param column */ -void ActionDialog::on_actionTreeWidget_itemDoubleClicked(QTreeWidgetItem *item, - int column) { +void ActionDialog::on_actionTreeWidget_itemDoubleClicked(QTreeWidgetItem *item, int column) { Q_UNUSED(column); if (item == nullptr) { @@ -119,8 +118,7 @@ void ActionDialog::on_actionTreeWidget_itemDoubleClicked(QTreeWidgetItem *item, // search for actions in the parent of the menu bar // for some reasons not all actions are children of the menu bar - QList actionList = - _menuBar->parent()->findChildren(objectName); + QList actionList = _menuBar->parent()->findChildren(objectName); // close the dialog close(); @@ -140,10 +138,9 @@ void ActionDialog::on_actionLineEdit_textChanged(const QString &arg1) { // search for the text Utils::Gui::searchForTextInTreeWidget( ui->actionTreeWidget, arg1, - Utils::Gui::TreeWidgetSearchFlags( - Utils::Gui::TreeWidgetSearchFlag::TooltipSearch | - Utils::Gui::TreeWidgetSearchFlag::AllColumnsSearch | - Utils::Gui::TreeWidgetSearchFlag::EveryWordSearch)); + Utils::Gui::TreeWidgetSearchFlags(Utils::Gui::TreeWidgetSearchFlag::TooltipSearch | + Utils::Gui::TreeWidgetSearchFlag::AllColumnsSearch | + Utils::Gui::TreeWidgetSearchFlag::EveryWordSearch)); } /** @@ -169,8 +166,7 @@ bool ActionDialog::eventFilter(QObject *obj, QEvent *event) { } else if (obj == ui->actionTreeWidget) { // trigger the action if return was pressed in the tree widget if (keyEvent->key() == Qt::Key_Return) { - on_actionTreeWidget_itemDoubleClicked( - ui->actionTreeWidget->currentItem(), 0); + on_actionTreeWidget_itemDoubleClicked(ui->actionTreeWidget->currentItem(), 0); return true; } diff --git a/src/dialogs/actiondialog.h b/src/dialogs/actiondialog.h index 112902eda..620c50f89 100644 --- a/src/dialogs/actiondialog.h +++ b/src/dialogs/actiondialog.h @@ -18,8 +18,7 @@ class ActionDialog : public MasterDialog { void refreshUi(); private slots: - void on_actionTreeWidget_itemDoubleClicked(QTreeWidgetItem *item, - int column); + void on_actionTreeWidget_itemDoubleClicked(QTreeWidgetItem *item, int column); void on_actionLineEdit_textChanged(const QString &arg1); @@ -30,6 +29,5 @@ class ActionDialog : public MasterDialog { Ui::ActionDialog *ui; QMenuBar *_menuBar; - void buildActionTreeForMenu(QMenu *menu, - QTreeWidgetItem *parentItem = nullptr); + void buildActionTreeForMenu(QMenu *menu, QTreeWidgetItem *parentItem = nullptr); }; diff --git a/src/dialogs/attachmentdialog.cpp b/src/dialogs/attachmentdialog.cpp index d47386ce8..8188d1813 100644 --- a/src/dialogs/attachmentdialog.cpp +++ b/src/dialogs/attachmentdialog.cpp @@ -61,8 +61,7 @@ void AttachmentDialog::on_fileEdit_textChanged(const QString &arg1) { return; } - ui->downloadButton->setVisible( - url.scheme().startsWith(QLatin1String("http"))); + ui->downloadButton->setVisible(url.scheme().startsWith(QLatin1String("http"))); if (url.scheme() == QLatin1String("file")) { ui->fileEdit->setText(url.toLocalFile()); @@ -73,9 +72,8 @@ void AttachmentDialog::on_fileEdit_textChanged(const QString &arg1) { QMimeDatabase db; QMimeType type = db.mimeTypeForFile(arg1); - ui->infoLabel->setText( - Utils::Misc::toHumanReadableByteSize(fileInfo.size()) + " - " + - type.comment()); + ui->infoLabel->setText(Utils::Misc::toHumanReadableByteSize(fileInfo.size()) + " - " + + type.comment()); } } @@ -89,8 +87,7 @@ void AttachmentDialog::on_downloadButton_clicked() { QNetworkRequest networkRequest(url); #if QT_VERSION < QT_VERSION_CHECK(5, 9, 0) - networkRequest.setAttribute(QNetworkRequest::FollowRedirectsAttribute, - true); + networkRequest.setAttribute(QNetworkRequest::FollowRedirectsAttribute, true); #else networkRequest.setAttribute(QNetworkRequest::RedirectPolicyAttribute, true); #endif @@ -110,13 +107,11 @@ void AttachmentDialog::on_downloadButton_clicked() { /** * Shows the download progress */ -void AttachmentDialog::downloadProgress(qint64 bytesReceived, - qint64 bytesTotal) { +void AttachmentDialog::downloadProgress(qint64 bytesReceived, qint64 bytesTotal) { ui->downloadProgressBar->setMaximum(static_cast(bytesTotal)); ui->downloadProgressBar->setValue(static_cast(bytesReceived)); - ui->downloadSizeLabel->setText( - Utils::Misc::toHumanReadableByteSize(bytesReceived) + " / " + - Utils::Misc::toHumanReadableByteSize(bytesTotal)); + ui->downloadSizeLabel->setText(Utils::Misc::toHumanReadableByteSize(bytesReceived) + " / " + + Utils::Misc::toHumanReadableByteSize(bytesTotal)); } /** @@ -140,12 +135,10 @@ void AttachmentDialog::slotReplyFinished(QNetworkReply *reply) { if (reply->error() != QNetworkReply::NoError && reply->error() != QNetworkReply::OperationCanceledError) { _accept = false; - QMessageBox::critical( - nullptr, tr("Download error"), - tr("Error while downloading:\n%1").arg(reply->errorString())); + QMessageBox::critical(nullptr, tr("Download error"), + tr("Error while downloading:\n%1").arg(reply->errorString())); - qWarning() - << QStringLiteral("Network error: %1").arg(reply->errorString()); + qWarning() << QStringLiteral("Network error: %1").arg(reply->errorString()); return; } @@ -162,17 +155,16 @@ void AttachmentDialog::slotReplyFinished(QNetworkReply *reply) { } } - auto *tempFile = - new QTemporaryFile(QDir::tempPath() + "/QOwnNotes-XXXXXX." + suffix); + auto *tempFile = new QTemporaryFile(QDir::tempPath() + "/QOwnNotes-XXXXXX." + suffix); // we want to keep the file to be used in the update process tempFile->setAutoRemove(false); // get a temporary file if (!tempFile->open()) { - QMessageBox::critical(nullptr, tr("File error"), - tr("Could not open temporary file:\n%1") - .arg(tempFile->errorString())); + QMessageBox::critical( + nullptr, tr("File error"), + tr("Could not open temporary file:\n%1").arg(tempFile->errorString())); return; } @@ -193,9 +185,8 @@ void AttachmentDialog::slotReplyFinished(QNetworkReply *reply) { QFile file(filePath); if (!file.open(QIODevice::WriteOnly)) { - QMessageBox::critical( - nullptr, tr("File error"), - tr("Could not store downloaded file:\n%1").arg(file.errorString())); + QMessageBox::critical(nullptr, tr("File error"), + tr("Could not store downloaded file:\n%1").arg(file.errorString())); return; } diff --git a/src/dialogs/commandbar.cpp b/src/dialogs/commandbar.cpp index f1cc85aaf..87d155d6d 100644 --- a/src/dialogs/commandbar.cpp +++ b/src/dialogs/commandbar.cpp @@ -1,49 +1,41 @@ #include "commandbar.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include #include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "libraries/fuzzy/kfuzzymatcher.h" #include "models/commandmodel.h" #include "utils/misc.h" -#include "libraries/fuzzy/kfuzzymatcher.h" -class CommandBarFilterModel : public QSortFilterProxyModel -{ -public: - CommandBarFilterModel(QObject *parent = nullptr) - : QSortFilterProxyModel(parent) - { - } +class CommandBarFilterModel : public QSortFilterProxyModel { + public: + CommandBarFilterModel(QObject *parent = nullptr) : QSortFilterProxyModel(parent) {} - Q_SLOT void setFilterString(const QString &string) - { + Q_SLOT void setFilterString(const QString &string) { beginResetModel(); m_pattern = string; endResetModel(); } -protected: - bool lessThan(const QModelIndex &sourceLeft, const QModelIndex &sourceRight) const override - { + protected: + bool lessThan(const QModelIndex &sourceLeft, const QModelIndex &sourceRight) const override { const int l = sourceLeft.data(CommandModel::Score).toInt(); const int r = sourceRight.data(CommandModel::Score).toInt(); return l < r; } - bool filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const override - { - if (m_pattern.isEmpty()) - return true; + bool filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const override { + if (m_pattern.isEmpty()) return true; const auto idx = sourceModel()->index(sourceRow, 0, sourceParent); const QString str = idx.data().toString(); @@ -53,20 +45,16 @@ protected: return res.matched; } -private: + private: QString m_pattern; }; -class CommandBarStyleDelegate : public QStyledItemDelegate -{ -public: - CommandBarStyleDelegate(QObject *parent = nullptr) - : QStyledItemDelegate(parent) - { - } +class CommandBarStyleDelegate : public QStyledItemDelegate { + public: + CommandBarStyleDelegate(QObject *parent = nullptr) : QStyledItemDelegate(parent) {} - void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const override - { + void paint(QPainter *painter, const QStyleOptionViewItem &option, + const QModelIndex &index) const override { QStyleOptionViewItem options = option; initStyleOption(&options, index); @@ -77,10 +65,14 @@ public: const auto strs = index.data().toString().split(QLatin1Char(':')); QString str = strs.at(1); const QString nameColor = option.palette.color(QPalette::Link).name(); - str = KFuzzyMatcher::toFuzzyMatchedDisplayString(m_filterString, str, QStringLiteral("").arg(nameColor), QStringLiteral("")); -// fts::to_fuzzy_matched_display_string(m_filterString, str, QStringLiteral("").arg(nameColor), QStringLiteral("")); + str = KFuzzyMatcher::toFuzzyMatchedDisplayString( + m_filterString, str, QStringLiteral("").arg(nameColor), + QStringLiteral("")); + // fts::to_fuzzy_matched_display_string(m_filterString, str, QStringLiteral("").arg(nameColor), QStringLiteral("")); - const QString component = QStringLiteral("") + strs.at(0) + QStringLiteral(": "); + const QString component = QStringLiteral("") + strs.at(0) + + QStringLiteral(": "); doc.setHtml(component + str); doc.setDocumentMargin(2); @@ -94,16 +86,18 @@ public: painter->fillRect(option.rect, option.palette.base()); } - options.text = QString(); // clear old text - options.widget->style()->drawControl(QStyle::CE_ItemViewItem, &options, painter, options.widget); + options.text = QString(); // clear old text + options.widget->style()->drawControl(QStyle::CE_ItemViewItem, &options, painter, + options.widget); // fix stuff for rtl - // QTextDocument doesn't work with RTL text out of the box so we give it a hand here by increasing - // the text width to our rect size. Icon displacement is also calculated here because 'translate()' - // later will not work. + // QTextDocument doesn't work with RTL text out of the box so we give it a hand here by + // increasing the text width to our rect size. Icon displacement is also calculated here + // because 'translate()' later will not work. const bool rtl = original.isRightToLeft(); if (rtl) { - auto r = options.widget->style()->subElementRect(QStyle::SE_ItemViewItemText, &options, options.widget); + auto r = options.widget->style()->subElementRect(QStyle::SE_ItemViewItemText, &options, + options.widget); auto hasIcon = index.data(Qt::DecorationRole).value().isNull(); if (hasIcon) doc.setTextWidth(r.width() - 25); @@ -115,8 +109,7 @@ public: painter->translate(option.rect.x(), option.rect.y()); // leave space for icon - if (!rtl) - painter->translate(25, 0); + if (!rtl) painter->translate(25, 0); QAbstractTextDocumentLayout::PaintContext ctx; ctx.palette.setColor(QPalette::Text, options.palette.text().color()); @@ -125,26 +118,19 @@ public: painter->restore(); } -public Q_SLOTS: - void setFilterString(const QString &text) - { - m_filterString = text; - } + public Q_SLOTS: + void setFilterString(const QString &text) { m_filterString = text; } -private: + private: QString m_filterString; }; -class ShortcutStyleDelegate : public QStyledItemDelegate -{ -public: - ShortcutStyleDelegate(QObject *parent = nullptr) - : QStyledItemDelegate(parent) - { - } +class ShortcutStyleDelegate : public QStyledItemDelegate { + public: + ShortcutStyleDelegate(QObject *parent = nullptr) : QStyledItemDelegate(parent) {} - void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const override - { + void paint(QPainter *painter, const QStyleOptionViewItem &option, + const QModelIndex &index) const override { QStyleOptionViewItem options = option; initStyleOption(&options, index); @@ -163,8 +149,9 @@ public: painter->fillRect(option.rect, option.palette.base()); } - options.text = QString(); // clear old text - options.widget->style()->drawControl(QStyle::CE_ItemViewItem, &options, painter, options.widget); + options.text = QString(); // clear old text + options.widget->style()->drawControl(QStyle::CE_ItemViewItem, &options, painter, + options.widget); if (!strs.isEmpty()) { // collect button-style pixmaps @@ -185,8 +172,8 @@ public: int py = option.rect.y() + plusRect.height() / 2; int total = btnRects.size(); int i = 0; - painter->setRenderHint(QPainter::Antialiasing); // :) - for (const auto& pxm : btnRects) { + painter->setRenderHint(QPainter::Antialiasing); // :) + for (const auto &pxm : btnRects) { // draw rounded rect shadown painter->setPen(Qt::NoPen); QRect r(dx, y, pxm.first.width(), pxm.first.height()); @@ -206,7 +193,8 @@ public: // draw '+' if (i + 1 < total) { dx += pxm.first.width() + 8; - painter->drawText(QPoint(dx, py + (pxm.first.height() / 2)), QStringLiteral("+")); + painter->drawText(QPoint(dx, py + (pxm.first.height() / 2)), + QStringLiteral("+")); dx += plusRect.width() + 8; } i++; @@ -217,9 +205,7 @@ public: } }; -CommandBar::CommandBar(QWidget *parent) - : QMenu(parent) -{ +CommandBar::CommandBar(QWidget *parent) : QMenu(parent) { QVBoxLayout *layout = new QVBoxLayout(); layout->setSpacing(0); layout->setContentsMargins(4, 4, 4, 4); @@ -237,8 +223,8 @@ CommandBar::CommandBar(QWidget *parent) m_model = new CommandModel(this); - CommandBarStyleDelegate* delegate = new CommandBarStyleDelegate(this); - ShortcutStyleDelegate* del = new ShortcutStyleDelegate(this); + CommandBarStyleDelegate *delegate = new CommandBarStyleDelegate(this); + ShortcutStyleDelegate *del = new ShortcutStyleDelegate(this); m_treeView->setItemDelegateForColumn(0, delegate); m_treeView->setItemDelegateForColumn(1, del); @@ -248,9 +234,11 @@ CommandBar::CommandBar(QWidget *parent) m_proxyModel->setFilterKeyColumn(0); connect(m_lineEdit, &QLineEdit::returnPressed, this, &CommandBar::slotReturnPressed); - connect(m_lineEdit, &QLineEdit::textChanged, m_proxyModel, &CommandBarFilterModel::setFilterString); - connect(m_lineEdit, &QLineEdit::textChanged, delegate, &CommandBarStyleDelegate::setFilterString); - connect(m_lineEdit, &QLineEdit::textChanged, this, [this](){ + connect(m_lineEdit, &QLineEdit::textChanged, m_proxyModel, + &CommandBarFilterModel::setFilterString); + connect(m_lineEdit, &QLineEdit::textChanged, delegate, + &CommandBarStyleDelegate::setFilterString); + connect(m_lineEdit, &QLineEdit::textChanged, this, [this]() { m_treeView->viewport()->update(); reselectFirst(); }); @@ -271,8 +259,7 @@ CommandBar::CommandBar(QWidget *parent) setHidden(true); } -void CommandBar::updateBar(const QVector > &actions) -{ +void CommandBar::updateBar(const QVector> &actions) { m_model->refresh(actions); reselectFirst(); @@ -281,13 +268,15 @@ void CommandBar::updateBar(const QVector > &actions) setFocus(); } -bool CommandBar::eventFilter(QObject *obj, QEvent *event) -{ - // catch key presses + shortcut overrides to allow to have ESC as application wide shortcut, too, see bug 409856 +bool CommandBar::eventFilter(QObject *obj, QEvent *event) { + // catch key presses + shortcut overrides to allow to have ESC as application wide shortcut, + // too, see bug 409856 if (event->type() == QEvent::KeyPress || event->type() == QEvent::ShortcutOverride) { QKeyEvent *keyEvent = static_cast(event); if (obj == m_lineEdit) { - const bool forward2list = (keyEvent->key() == Qt::Key_Up) || (keyEvent->key() == Qt::Key_Down) || (keyEvent->key() == Qt::Key_PageUp) || (keyEvent->key() == Qt::Key_PageDown); + const bool forward2list = + (keyEvent->key() == Qt::Key_Up) || (keyEvent->key() == Qt::Key_Down) || + (keyEvent->key() == Qt::Key_PageUp) || (keyEvent->key() == Qt::Key_PageDown); if (forward2list) { QCoreApplication::sendEvent(m_treeView, event); return true; @@ -300,8 +289,10 @@ bool CommandBar::eventFilter(QObject *obj, QEvent *event) return true; } } else { - const bool forward2input = (keyEvent->key() != Qt::Key_Up) && (keyEvent->key() != Qt::Key_Down) && (keyEvent->key() != Qt::Key_PageUp) && (keyEvent->key() != Qt::Key_PageDown) && (keyEvent->key() != Qt::Key_Tab) && - (keyEvent->key() != Qt::Key_Backtab); + const bool forward2input = + (keyEvent->key() != Qt::Key_Up) && (keyEvent->key() != Qt::Key_Down) && + (keyEvent->key() != Qt::Key_PageUp) && (keyEvent->key() != Qt::Key_PageDown) && + (keyEvent->key() != Qt::Key_Tab) && (keyEvent->key() != Qt::Key_Backtab); if (forward2input) { QCoreApplication::sendEvent(m_lineEdit, event); return true; @@ -310,7 +301,8 @@ bool CommandBar::eventFilter(QObject *obj, QEvent *event) } // hide on focus out, if neither input field nor list have focus! - else if (event->type() == QEvent::FocusOut && !(m_lineEdit->hasFocus() || m_treeView->hasFocus())) { + else if (event->type() == QEvent::FocusOut && + !(m_lineEdit->hasFocus() || m_treeView->hasFocus())) { m_lineEdit->clear(); hide(); return true; @@ -319,15 +311,14 @@ bool CommandBar::eventFilter(QObject *obj, QEvent *event) return QWidget::eventFilter(obj, event); } -void CommandBar::slotReturnPressed() -{ - auto act = m_proxyModel->data(m_treeView->currentIndex(), Qt::UserRole).value(); +void CommandBar::slotReturnPressed() { + auto act = m_proxyModel->data(m_treeView->currentIndex(), Qt::UserRole).value(); if (act) { // if the action is a menu, we take all its actions // and reload our dialog with these instead. if (auto menu = act->menu()) { auto menuActions = menu->actions(); - QVector> list; + QVector> list; list.reserve(menuActions.size()); // if there are no actions, trigger load actions @@ -353,14 +344,12 @@ void CommandBar::slotReturnPressed() hide(); } -void CommandBar::reselectFirst() -{ +void CommandBar::reselectFirst() { QModelIndex index = m_proxyModel->index(0, 0); m_treeView->setCurrentIndex(index); } -void CommandBar::updateViewGeometry() -{ +void CommandBar::updateViewGeometry() { m_treeView->resizeColumnToContents(0); m_treeView->resizeColumnToContents(1); diff --git a/src/dialogs/commandbar.h b/src/dialogs/commandbar.h index 6906e1af2..0d4232fd2 100644 --- a/src/dialogs/commandbar.h +++ b/src/dialogs/commandbar.h @@ -9,28 +9,27 @@ class CommandModel; class CommandBarFilterModel; class QLineEdit; -class CommandBar : public QMenu -{ +class CommandBar : public QMenu { Q_OBJECT -public: - explicit CommandBar(QWidget *parent = nullptr); + public: + explicit CommandBar(QWidget* parent = nullptr); void updateBar(const QVector>& actions); void updateViewGeometry(); -protected: - bool eventFilter(QObject *obj, QEvent *event) override; + protected: + bool eventFilter(QObject* obj, QEvent* event) override; -private Q_SLOTS: + private Q_SLOTS: void slotReturnPressed(); void reselectFirst(); -private: + private: QTreeView* m_treeView; QLineEdit* m_lineEdit; CommandModel* m_model; CommandBarFilterModel* m_proxyModel; }; -#endif // COMMANDBAR_H +#endif // COMMANDBAR_H diff --git a/src/dialogs/dictionarymanagerdialog.cpp b/src/dialogs/dictionarymanagerdialog.cpp index 05e72eca8..33c48372c 100644 --- a/src/dialogs/dictionarymanagerdialog.cpp +++ b/src/dialogs/dictionarymanagerdialog.cpp @@ -30,8 +30,7 @@ DictionaryManagerDialog::DictionaryManagerDialog(QWidget *parent) addDictionaryItem(tr("Amharic"), QStringLiteral("am_ET")); addDictionaryItem(tr("Ancient Greek"), QStringLiteral("grc_GR")); addDictionaryItem(tr("Arabic"), QStringLiteral("ar")); - addDictionaryItem(tr("Aragonese"), QStringLiteral("an_ES"), - QStringLiteral("Aragonés")); + addDictionaryItem(tr("Aragonese"), QStringLiteral("an_ES"), QStringLiteral("Aragonés")); addDictionaryItem(tr("Armenian"), QStringLiteral("hy")); addDictionaryItem(tr("Albanian"), QStringLiteral("sq_AL")); addDictionaryItem(tr("Basque"), QStringLiteral("eu")); @@ -47,52 +46,40 @@ DictionaryManagerDialog::DictionaryManagerDialog(QWidget *parent) addDictionaryItem(tr("Czech"), QStringLiteral("cs_CZ")); addDictionaryItem(tr("Danish"), QStringLiteral("da_DK")); addDictionaryItem(tr("Dutch"), QStringLiteral("nl_NL")); - addDictionaryItem(tr("English (American)"), QStringLiteral("en"), - QStringLiteral("en_US")); - addDictionaryItem(tr("English (Australian)"), QStringLiteral("en"), - QStringLiteral("en_AU")); - addDictionaryItem(tr("English (British)"), QStringLiteral("en"), - QStringLiteral("en_GB")); - addDictionaryItem(tr("English (Canadian)"), QStringLiteral("en"), - QStringLiteral("en_CA")); + addDictionaryItem(tr("English (American)"), QStringLiteral("en"), QStringLiteral("en_US")); + addDictionaryItem(tr("English (Australian)"), QStringLiteral("en"), QStringLiteral("en_AU")); + addDictionaryItem(tr("English (British)"), QStringLiteral("en"), QStringLiteral("en_GB")); + addDictionaryItem(tr("English (Canadian)"), QStringLiteral("en"), QStringLiteral("en_CA")); addDictionaryItem(tr("English (Medical Dictionary)"), QStringLiteral("en"), QStringLiteral("en-medical")); - addDictionaryItem(tr("English (South African)"), QStringLiteral("en"), - QStringLiteral("en_ZA")); + addDictionaryItem(tr("English (South African)"), QStringLiteral("en"), QStringLiteral("en_ZA")); addDictionaryItem(tr("Esperanto"), QStringLiteral("eo")); addDictionaryItem(tr("Estonian"), QStringLiteral("et_EE")); addDictionaryItem(tr("Faroese"), QStringLiteral("fo")); - addDictionaryItem(tr("French"), QStringLiteral("fr_FR"), - QStringLiteral("fr")); + addDictionaryItem(tr("French"), QStringLiteral("fr_FR"), QStringLiteral("fr")); addDictionaryItem(tr("Friulian"), QStringLiteral("fur_IT")); addDictionaryItem(tr("Gaelic"), QStringLiteral("gd_GB")); - addDictionaryItem(tr("Galician"), QStringLiteral("gl"), - QStringLiteral("gl_ES")); + addDictionaryItem(tr("Galician"), QStringLiteral("gl"), QStringLiteral("gl_ES")); addDictionaryItem(tr("Georgian"), QStringLiteral("ka_GE")); - addDictionaryItem(tr("German (Austrian)"), QStringLiteral("de"), - QStringLiteral("de_AT_frami")); + addDictionaryItem(tr("German (Austrian)"), QStringLiteral("de"), QStringLiteral("de_AT_frami")); addDictionaryItem(tr("German (Classical Spelling)"), QStringLiteral("de"), QStringLiteral("de_DE-oldspell")); - addDictionaryItem(tr("German (German)"), QStringLiteral("de"), - QStringLiteral("de_DE_frami")); - addDictionaryItem(tr("German (Swiss)"), QStringLiteral("de"), - QStringLiteral("de_CH_frami")); + addDictionaryItem(tr("German (German)"), QStringLiteral("de"), QStringLiteral("de_DE_frami")); + addDictionaryItem(tr("German (Swiss)"), QStringLiteral("de"), QStringLiteral("de_CH_frami")); addDictionaryItem(tr("German (Medical Dictionary)"), QStringLiteral("de"), QStringLiteral("de-medical")); addDictionaryItem(tr("Greek"), QStringLiteral("el_GR")); - addDictionaryItem(tr("Modern Greek (Polytonic Greek)"), - QStringLiteral("el_GR"), QStringLiteral("el-polyton")); + addDictionaryItem(tr("Modern Greek (Polytonic Greek)"), QStringLiteral("el_GR"), + QStringLiteral("el-polyton")); addDictionaryItem(tr("Gujarati"), QStringLiteral("gu_IN")); addDictionaryItem(tr("Gurani"), QStringLiteral("gug")); addDictionaryItem(tr("Hebrew"), QStringLiteral("he_IL")); addDictionaryItem(tr("Hindi"), QStringLiteral("hi_IN")); addDictionaryItem(tr("Hungarian"), QStringLiteral("hu_HU")); addDictionaryItem(tr("Icelandic"), QStringLiteral("is")); - addDictionaryItem(tr("Indonesian"), QStringLiteral("id"), - QStringLiteral("id_ID")); + addDictionaryItem(tr("Indonesian"), QStringLiteral("id"), QStringLiteral("id_ID")); addDictionaryItem(tr("Italian"), QStringLiteral("it_IT")); - addDictionaryItem(tr("Kaszebsczi"), QStringLiteral("csb_PL"), - QStringLiteral("Kaszebsczi")); + addDictionaryItem(tr("Kaszebsczi"), QStringLiteral("csb_PL"), QStringLiteral("Kaszebsczi")); addDictionaryItem(tr("Kazakh"), QStringLiteral("kk")); addDictionaryItem(tr("Khmer"), QStringLiteral("km_KH")); addDictionaryItem(tr("Komi (Russia)"), QStringLiteral("koi")); @@ -104,24 +91,20 @@ DictionaryManagerDialog::DictionaryManagerDialog(QWidget *parent) addDictionaryItem(tr("Latvian"), QStringLiteral("lv_LV")); addDictionaryItem(tr("Lithuanian"), QStringLiteral("lt_LT")); addDictionaryItem(tr("Low German / Low Saxon"), QStringLiteral("nds")); - addDictionaryItem(tr("Luxembourgish (Letzeburgesch)"), - QStringLiteral("lb")); + addDictionaryItem(tr("Luxembourgish (Letzeburgesch)"), QStringLiteral("lb")); addDictionaryItem(tr("Macedonian"), QStringLiteral("mk")); addDictionaryItem(tr("Malayalam"), QStringLiteral("ml_IN")); addDictionaryItem(tr("Mongolian"), QStringLiteral("mn")); addDictionaryItem(tr("Nepali"), QStringLiteral("ne_NP")); - addDictionaryItem(tr("Norwegian (Bokmål)"), QStringLiteral("no"), - QStringLiteral("nb_NO")); - addDictionaryItem(tr("Norwegian (Nynorsk)"), QStringLiteral("no"), - QStringLiteral("nn_NO")); + addDictionaryItem(tr("Norwegian (Bokmål)"), QStringLiteral("no"), QStringLiteral("nb_NO")); + addDictionaryItem(tr("Norwegian (Nynorsk)"), QStringLiteral("no"), QStringLiteral("nn_NO")); addDictionaryItem(tr("Occitan"), QStringLiteral("oc_FR")); addDictionaryItem(tr("Papiamentu"), QStringLiteral("pap_CW")); addDictionaryItem(tr("Persian"), QStringLiteral("fa_IR")); addDictionaryItem(tr("Polish"), QStringLiteral("pl_PL")); addDictionaryItem(tr("Portugese (Brazilian)"), QStringLiteral("pt_BR")); addDictionaryItem(tr("Portugese"), QStringLiteral("pt_PT")); - addDictionaryItem(tr("Romanian"), QStringLiteral("ro"), - QStringLiteral("ro_RO")); + addDictionaryItem(tr("Romanian"), QStringLiteral("ro"), QStringLiteral("ro_RO")); addDictionaryItem(tr("Romansh"), QStringLiteral("rm")); addDictionaryItem(tr("Russian"), QStringLiteral("ru_RU")); addDictionaryItem(tr("Russian Medical Dictionary"), QStringLiteral("ru_RU"), @@ -129,15 +112,13 @@ DictionaryManagerDialog::DictionaryManagerDialog(QWidget *parent) addDictionaryItem(tr("Rusyn / Ruthene (Slovakia)"), QStringLiteral("sk_SK"), QStringLiteral("rue_SK")); addDictionaryItem(tr("Serbian (Cyrillic)"), QStringLiteral("sr")); - addDictionaryItem(tr("Serbian (Latin)"), QStringLiteral("sr"), - QStringLiteral("sr-Latn")); + addDictionaryItem(tr("Serbian (Latin)"), QStringLiteral("sr"), QStringLiteral("sr-Latn")); addDictionaryItem(tr("Shona"), QStringLiteral("sn_ZW")); addDictionaryItem(tr("Sindhi"), QStringLiteral("sd")); addDictionaryItem(tr("Sinhala"), QStringLiteral("si_LK")); addDictionaryItem(tr("Slovak"), QStringLiteral("sk_SK")); addDictionaryItem(tr("Slovenian"), QStringLiteral("sl_SI")); - addDictionaryItem(tr("Spanish"), QStringLiteral("es"), - QStringLiteral("es_ANY")); + addDictionaryItem(tr("Spanish"), QStringLiteral("es"), QStringLiteral("es_ANY")); addDictionaryItem(tr("Swahili"), QStringLiteral("sw_TZ")); addDictionaryItem(tr("Swedish"), QStringLiteral("sv_SE")); addDictionaryItem(tr("Tagalog"), QStringLiteral("tl_PH")); @@ -153,8 +134,7 @@ DictionaryManagerDialog::DictionaryManagerDialog(QWidget *parent) addDictionaryItem(tr("Uzbek"), QStringLiteral("uz_UZ")); addDictionaryItem(tr("Venda"), QStringLiteral("ve_ZA")); addDictionaryItem(tr("Venetian"), QStringLiteral("vec_IT")); - addDictionaryItem(tr("Vietnamese"), QStringLiteral("vi"), - QStringLiteral("vi_VN")); + addDictionaryItem(tr("Vietnamese"), QStringLiteral("vi"), QStringLiteral("vi_VN")); addDictionaryItem(tr("Welsh"), QStringLiteral("cy_GB")); addDictionaryItem(tr("Xhosa"), QStringLiteral("xh_ZA")); addDictionaryItem(tr("Zulu"), QStringLiteral("zu_ZA")); @@ -180,8 +160,7 @@ DictionaryManagerDialog::~DictionaryManagerDialog() { delete ui; } -void DictionaryManagerDialog::addDictionaryItem(const QString &name, - const QString &pathPart, +void DictionaryManagerDialog::addDictionaryItem(const QString &name, const QString &pathPart, QString fileNamePart) { if (fileNamePart.isEmpty()) { fileNamePart = pathPart; @@ -214,9 +193,7 @@ void DictionaryManagerDialog::setupMainSplitter() { // restore splitter sizes QSettings settings; QByteArray state = - settings - .value(QStringLiteral("DictionaryManagerDialog/mainSplitterState")) - .toByteArray(); + settings.value(QStringLiteral("DictionaryManagerDialog/mainSplitterState")).toByteArray(); _mainSplitter->restoreState(state); ui->gridLayout->layout()->addWidget(_mainSplitter); @@ -227,9 +204,8 @@ void DictionaryManagerDialog::setupMainSplitter() { */ void DictionaryManagerDialog::storeSettings() { QSettings settings; - settings.setValue( - QStringLiteral("DictionaryManagerDialog/mainSplitterState"), - _mainSplitter->saveState()); + settings.setValue(QStringLiteral("DictionaryManagerDialog/mainSplitterState"), + _mainSplitter->saveState()); } void DictionaryManagerDialog::on_downloadButton_clicked() { @@ -245,8 +221,7 @@ void DictionaryManagerDialog::on_downloadButton_clicked() { return; } - QString url = - item->data(0, Qt::UserRole).toString() + QStringLiteral(".dic"); + QString url = item->data(0, Qt::UserRole).toString() + QStringLiteral(".dic"); downloadFile(url); } @@ -254,8 +229,7 @@ void DictionaryManagerDialog::downloadFile(const QString &url) { QNetworkRequest networkRequest(url); #if QT_VERSION < QT_VERSION_CHECK(5, 9, 0) - networkRequest.setAttribute(QNetworkRequest::FollowRedirectsAttribute, - true); + networkRequest.setAttribute(QNetworkRequest::FollowRedirectsAttribute, true); #else networkRequest.setAttribute(QNetworkRequest::RedirectPolicyAttribute, true); #endif @@ -292,12 +266,10 @@ void DictionaryManagerDialog::slotReplyFinished(QNetworkReply *reply) { if (reply->error() != QNetworkReply::NoError && reply->error() != QNetworkReply::OperationCanceledError) { - QMessageBox::critical( - nullptr, tr("Download error"), - tr("Error while downloading:\n%1").arg(reply->errorString())); + QMessageBox::critical(nullptr, tr("Download error"), + tr("Error while downloading:\n%1").arg(reply->errorString())); - qWarning() - << QStringLiteral("Network error: %1").arg(reply->errorString()); + qWarning() << QStringLiteral("Network error: %1").arg(reply->errorString()); return; } @@ -305,13 +277,11 @@ void DictionaryManagerDialog::slotReplyFinished(QNetworkReply *reply) { QFileInfo info(urlPath); QString suffix = info.completeSuffix(); - QFile file(Utils::Misc::localDictionariesPath() + QStringLiteral("/") + - info.fileName()); + QFile file(Utils::Misc::localDictionariesPath() + QStringLiteral("/") + info.fileName()); if (!file.open(QIODevice::WriteOnly)) { - QMessageBox::critical( - nullptr, tr("File error"), - tr("Could not store downloaded file:\n%1").arg(file.errorString())); + QMessageBox::critical(nullptr, tr("File error"), + tr("Could not store downloaded file:\n%1").arg(file.errorString())); return; } @@ -324,8 +294,7 @@ void DictionaryManagerDialog::slotReplyFinished(QNetworkReply *reply) { auto *item = ui->remoteDictionaryTreeWidget->currentItem(); if (item != nullptr) { - QString url = - item->data(0, Qt::UserRole).toString() + QStringLiteral(".aff"); + QString url = item->data(0, Qt::UserRole).toString() + QStringLiteral(".aff"); downloadFile(url); } } else { @@ -342,14 +311,12 @@ void DictionaryManagerDialog::on_downloadCancelButton_clicked() { /** * Shows the download progress */ -void DictionaryManagerDialog::downloadProgress(qint64 bytesReceived, - qint64 bytesTotal) { +void DictionaryManagerDialog::downloadProgress(qint64 bytesReceived, qint64 bytesTotal) { QString text = Utils::Misc::toHumanReadableByteSize(bytesReceived); // bytesTotal can be set to -1 if not available if (bytesTotal > -1) { - text += QStringLiteral(" / ") + - Utils::Misc::toHumanReadableByteSize(bytesTotal); + text += QStringLiteral(" / ") + Utils::Misc::toHumanReadableByteSize(bytesTotal); } else { // set to 4 MB bytesTotal = 4194304; @@ -390,8 +357,7 @@ void DictionaryManagerDialog::loadLocalDictionaries() { qDebug() << files; } -QString DictionaryManagerDialog::getDictionaryName( - const QString &fileNamePart) { +QString DictionaryManagerDialog::getDictionaryName(const QString &fileNamePart) { foreach (Dictionary dict, _dictionaryList) { if (dict.fileNamePart == fileNamePart) { return dict.name; @@ -402,8 +368,7 @@ QString DictionaryManagerDialog::getDictionaryName( } void DictionaryManagerDialog::on_deleteLocalDictionaryButton_clicked() { - foreach (QTreeWidgetItem *item, - ui->localDictionaryTreeWidget->selectedItems()) { + foreach (QTreeWidgetItem *item, ui->localDictionaryTreeWidget->selectedItems()) { const QString &fileNamePart = item->data(0, Qt::UserRole).toString(); if (deleteLocalDictionaryFile(fileNamePart + QStringLiteral(".aff"))) { @@ -415,47 +380,39 @@ void DictionaryManagerDialog::on_deleteLocalDictionaryButton_clicked() { qApp->setProperty("needsRestart", true); } -bool DictionaryManagerDialog::deleteLocalDictionaryFile( - const QString &fileName) { - QFile file(Utils::Misc::localDictionariesPath() + QStringLiteral("/") + - fileName); +bool DictionaryManagerDialog::deleteLocalDictionaryFile(const QString &fileName) { + QFile file(Utils::Misc::localDictionariesPath() + QStringLiteral("/") + fileName); if (!file.remove()) { - QMessageBox::critical( - nullptr, tr("File error"), - tr("Could not remove dictionary file:\n%1").arg(fileName)); + QMessageBox::critical(nullptr, tr("File error"), + tr("Could not remove dictionary file:\n%1").arg(fileName)); return false; } return true; } -void DictionaryManagerDialog:: - on_remoteDictionaryTreeWidget_itemSelectionChanged() { - ui->downloadButton->setDisabled( - ui->remoteDictionaryTreeWidget->selectedItems().count() == 0); +void DictionaryManagerDialog::on_remoteDictionaryTreeWidget_itemSelectionChanged() { + ui->downloadButton->setDisabled(ui->remoteDictionaryTreeWidget->selectedItems().count() == 0); } -void DictionaryManagerDialog:: - on_localDictionaryTreeWidget_itemSelectionChanged() { +void DictionaryManagerDialog::on_localDictionaryTreeWidget_itemSelectionChanged() { ui->deleteLocalDictionaryButton->setDisabled( ui->localDictionaryTreeWidget->selectedItems().count() == 0); } -void DictionaryManagerDialog::on_searchDictionaryEdit_textChanged( - const QString &arg1) { +void DictionaryManagerDialog::on_searchDictionaryEdit_textChanged(const QString &arg1) { Utils::Gui::searchForTextInTreeWidget(ui->remoteDictionaryTreeWidget, arg1); } -void DictionaryManagerDialog::on_remoteDictionaryTreeWidget_itemDoubleClicked( - QTreeWidgetItem *item, int column) { +void DictionaryManagerDialog::on_remoteDictionaryTreeWidget_itemDoubleClicked(QTreeWidgetItem *item, + int column) { Q_UNUSED(item) Q_UNUSED(column) on_downloadButton_clicked(); } -void DictionaryManagerDialog::on_disableExternalDictionariesCheckBox_toggled( - bool checked) { +void DictionaryManagerDialog::on_disableExternalDictionariesCheckBox_toggled(bool checked) { QSettings settings; settings.setValue(QStringLiteral("disableExternalDictionaries"), checked); qApp->setProperty("needsRestart", true); diff --git a/src/dialogs/dictionarymanagerdialog.h b/src/dialogs/dictionarymanagerdialog.h index 00f53b336..487d52511 100644 --- a/src/dialogs/dictionarymanagerdialog.h +++ b/src/dialogs/dictionarymanagerdialog.h @@ -41,8 +41,7 @@ class DictionaryManagerDialog : public MasterDialog { void on_searchDictionaryEdit_textChanged(const QString &arg1); - void on_remoteDictionaryTreeWidget_itemDoubleClicked(QTreeWidgetItem *item, - int column); + void on_remoteDictionaryTreeWidget_itemDoubleClicked(QTreeWidgetItem *item, int column); void on_disableExternalDictionariesCheckBox_toggled(bool checked); diff --git a/src/dialogs/evernoteimportdialog.cpp b/src/dialogs/evernoteimportdialog.cpp index 2bd337079..48a3358b6 100644 --- a/src/dialogs/evernoteimportdialog.cpp +++ b/src/dialogs/evernoteimportdialog.cpp @@ -15,8 +15,8 @@ #include #if (QT_VERSION < QT_VERSION_CHECK(6, 0, 0)) - #include - #include +#include +#include #endif #include @@ -35,26 +35,18 @@ EvernoteImportDialog::EvernoteImportDialog(QWidget *parent) QSettings settings; ui->imageImportCheckBox->setChecked( - settings - .value(QStringLiteral("EvernoteImport/ImageImportCheckBoxChecked"), - true) - .toBool()); + settings.value(QStringLiteral("EvernoteImport/ImageImportCheckBoxChecked"), true).toBool()); ui->attachmentImportCheckBox->setChecked( - settings - .value(QStringLiteral( - "EvernoteImport/AttachmentImportCheckBoxChecked"), - true) + settings.value(QStringLiteral("EvernoteImport/AttachmentImportCheckBoxChecked"), true) .toBool()); } EvernoteImportDialog::~EvernoteImportDialog() { QSettings settings; - settings.setValue( - QStringLiteral("EvernoteImport/ImageImportCheckBoxChecked"), - ui->imageImportCheckBox->isChecked()); - settings.setValue( - QStringLiteral("EvernoteImport/AttachmentImportCheckBoxChecked"), - ui->attachmentImportCheckBox->isChecked()); + settings.setValue(QStringLiteral("EvernoteImport/ImageImportCheckBoxChecked"), + ui->imageImportCheckBox->isChecked()); + settings.setValue(QStringLiteral("EvernoteImport/AttachmentImportCheckBoxChecked"), + ui->attachmentImportCheckBox->isChecked()); storeMetaDataTreeWidgetItemsCheckedState(); @@ -130,8 +122,7 @@ int EvernoteImportDialog::countNotes(const QString &data) { * * @param content */ -QString EvernoteImportDialog::importImages(const Note ¬e, QString content, - QXmlQuery query) { +QString EvernoteImportDialog::importImages(const Note ¬e, QString content, QXmlQuery query) { query.setQuery(QStringLiteral("resource")); QXmlResultItems result; @@ -154,9 +145,8 @@ QString EvernoteImportDialog::importImages(const Note ¬e, QString content, query.setQuery(QStringLiteral("mime/text()")); query.evaluateTo(&mime); - QRegularExpression mimeExpression( - QStringLiteral("(.+)?\\/(.+)?"), - QRegularExpression::CaseInsensitiveOption); + QRegularExpression mimeExpression(QStringLiteral("(.+)?\\/(.+)?"), + QRegularExpression::CaseInsensitiveOption); QRegularExpressionMatch mimeMatch = mimeExpression.match(mime); if (mimeMatch.hasMatch()) { @@ -194,9 +184,8 @@ QString EvernoteImportDialog::importImages(const Note ¬e, QString content, // if there is no object id set we generate the hash ourselves if (objectId.isEmpty()) { - objectId = QString(QCryptographicHash::hash( - QByteArray::fromBase64(data.toLatin1()), - QCryptographicHash::Md5) + objectId = QString(QCryptographicHash::hash(QByteArray::fromBase64(data.toLatin1()), + QCryptographicHash::Md5) .toHex()); } @@ -275,8 +264,7 @@ QString EvernoteImportDialog::importImages(const Note ¬e, QString content, * * @param content */ -QString EvernoteImportDialog::importAttachments(const Note ¬e, - QString content, +QString EvernoteImportDialog::importAttachments(const Note ¬e, QString content, QXmlQuery query) { query.setQuery(QStringLiteral("resource")); @@ -299,9 +287,8 @@ QString EvernoteImportDialog::importAttachments(const Note ¬e, query.setQuery(QStringLiteral("mime/text()")); query.evaluateTo(&mime); - QRegularExpression mimeExpression( - QStringLiteral("(.+)?\\/(.+)?"), - QRegularExpression::CaseInsensitiveOption); + QRegularExpression mimeExpression(QStringLiteral("(.+)?\\/(.+)?"), + QRegularExpression::CaseInsensitiveOption); QRegularExpressionMatch mimeMatch = mimeExpression.match(mime); if (mimeMatch.hasMatch()) { @@ -338,9 +325,8 @@ QString EvernoteImportDialog::importAttachments(const Note ¬e, // if there is no object id set we generate the hash ourselves if (objectId.isEmpty()) { - objectId = QString(QCryptographicHash::hash( - QByteArray::fromBase64(data.toLatin1()), - QCryptographicHash::Md5) + objectId = QString(QCryptographicHash::hash(QByteArray::fromBase64(data.toLatin1()), + QCryptographicHash::Md5) .toHex()); } @@ -396,8 +382,7 @@ QString EvernoteImportDialog::importAttachments(const Note ¬e, MediaFileData mediaFileData = mediaFileDataHash[objectId]; // get the Markdown code for the file data entry - QString markdownCode = - getMarkdownForAttachmentFileData(note, mediaFileData); + QString markdownCode = getMarkdownForAttachmentFileData(note, mediaFileData); if (!markdownCode.isEmpty()) { // replace media tag with Markdown code @@ -417,8 +402,7 @@ QString EvernoteImportDialog::importAttachments(const Note ¬e, MediaFileData mediaFileData = hashIterator.value(); // get the Markdown code for the file data entry - QString markdownCode = - getMarkdownForAttachmentFileData(note, mediaFileData); + QString markdownCode = getMarkdownForAttachmentFileData(note, mediaFileData); content += "\n" + markdownCode; } @@ -563,8 +547,7 @@ QString EvernoteImportDialog::generateMetaDataMarkdown(QXmlQuery query) { QString resultText; QString tableText; QList items = ui->metaDataTreeWidget->findItems( - QStringLiteral("*"), - Qt::MatchWrap | Qt::MatchWildcard | Qt::MatchRecursive); + QStringLiteral("*"), Qt::MatchWrap | Qt::MatchWildcard | Qt::MatchRecursive); Q_FOREACH (QTreeWidgetItem *item, items) { if (item->checkState(0) != Qt::Checked) { @@ -583,8 +566,7 @@ QString EvernoteImportDialog::generateMetaDataMarkdown(QXmlQuery query) { continue; } - tableText += QStringLiteral("| ") + name + (" | ") + attribute + - QStringLiteral(" |\n"); + tableText += QStringLiteral("| ") + name + (" | ") + attribute + QStringLiteral(" |\n"); } if (!tableText.isEmpty()) { @@ -606,9 +588,9 @@ QString EvernoteImportDialog::generateMetaDataMarkdown(QXmlQuery query) { * @param parentItem * @return */ -QTreeWidgetItem *EvernoteImportDialog::addMetaDataTreeWidgetItem( - const QString &name, const QString &attributeName, - QTreeWidgetItem *parentItem) { +QTreeWidgetItem *EvernoteImportDialog::addMetaDataTreeWidgetItem(const QString &name, + const QString &attributeName, + QTreeWidgetItem *parentItem) { auto *item = new QTreeWidgetItem(); item->setText(0, name); @@ -622,12 +604,9 @@ QTreeWidgetItem *EvernoteImportDialog::addMetaDataTreeWidgetItem( QSettings settings; auto metaDataUnCheckedList = - settings - .value(QStringLiteral("EvernoteImport/MetaDataUnCheckedList")) - .toStringList(); - item->setCheckState(0, metaDataUnCheckedList.contains(attributeName) - ? Qt::Unchecked - : Qt::Checked); + settings.value(QStringLiteral("EvernoteImport/MetaDataUnCheckedList")).toStringList(); + item->setCheckState( + 0, metaDataUnCheckedList.contains(attributeName) ? Qt::Unchecked : Qt::Checked); parentItem->addChild(item); } @@ -639,58 +618,42 @@ QTreeWidgetItem *EvernoteImportDialog::addMetaDataTreeWidgetItem( * Setup the metadata tree widget items */ void EvernoteImportDialog::setupMetaDataTreeWidgetItems() { - auto *basicAttributesItem = - addMetaDataTreeWidgetItem(tr("Basic attributes")); - addMetaDataTreeWidgetItem(tr("Created date"), QStringLiteral("created"), - basicAttributesItem); - addMetaDataTreeWidgetItem(tr("Updated date"), QStringLiteral("updated"), - basicAttributesItem); + auto *basicAttributesItem = addMetaDataTreeWidgetItem(tr("Basic attributes")); + addMetaDataTreeWidgetItem(tr("Created date"), QStringLiteral("created"), basicAttributesItem); + addMetaDataTreeWidgetItem(tr("Updated date"), QStringLiteral("updated"), basicAttributesItem); auto *noteAttributesItem = addMetaDataTreeWidgetItem(tr("Note attributes")); - addMetaDataTreeWidgetItem(tr("Subject date"), - QStringLiteral("note-attributes/subject-date"), + addMetaDataTreeWidgetItem(tr("Subject date"), QStringLiteral("note-attributes/subject-date"), noteAttributesItem); - addMetaDataTreeWidgetItem(tr("Latitude"), - QStringLiteral("note-attributes/latitude"), + addMetaDataTreeWidgetItem(tr("Latitude"), QStringLiteral("note-attributes/latitude"), noteAttributesItem); - addMetaDataTreeWidgetItem(tr("Longitude"), - QStringLiteral("note-attributes/longitude"), + addMetaDataTreeWidgetItem(tr("Longitude"), QStringLiteral("note-attributes/longitude"), noteAttributesItem); - addMetaDataTreeWidgetItem(tr("Altitude"), - QStringLiteral("note-attributes/altitude"), + addMetaDataTreeWidgetItem(tr("Altitude"), QStringLiteral("note-attributes/altitude"), noteAttributesItem); - addMetaDataTreeWidgetItem(tr("Author"), - QStringLiteral("note-attributes/author"), + addMetaDataTreeWidgetItem(tr("Author"), QStringLiteral("note-attributes/author"), noteAttributesItem); - addMetaDataTreeWidgetItem(tr("Source"), - QStringLiteral("note-attributes/source"), + addMetaDataTreeWidgetItem(tr("Source"), QStringLiteral("note-attributes/source"), noteAttributesItem); - addMetaDataTreeWidgetItem(tr("Source URL"), - QStringLiteral("note-attributes/source-url"), + addMetaDataTreeWidgetItem(tr("Source URL"), QStringLiteral("note-attributes/source-url"), + noteAttributesItem); + addMetaDataTreeWidgetItem(tr("Source application"), + QStringLiteral("note-attributes/source-application"), noteAttributesItem); - addMetaDataTreeWidgetItem( - tr("Source application"), - QStringLiteral("note-attributes/source-application"), - noteAttributesItem); addMetaDataTreeWidgetItem(tr("Reminder order"), - QStringLiteral("note-attributes/reminder-order"), + QStringLiteral("note-attributes/reminder-order"), noteAttributesItem); + addMetaDataTreeWidgetItem(tr("Reminder time"), QStringLiteral("note-attributes/reminder-time"), noteAttributesItem); - addMetaDataTreeWidgetItem(tr("Reminder time"), - QStringLiteral("note-attributes/reminder-time"), + addMetaDataTreeWidgetItem(tr("Reminder done time"), + QStringLiteral("note-attributes/reminder-done-time"), noteAttributesItem); - addMetaDataTreeWidgetItem( - tr("Reminder done time"), - QStringLiteral("note-attributes/reminder-done-time"), - noteAttributesItem); - addMetaDataTreeWidgetItem(tr("Place name"), - QStringLiteral("note-attributes/place-name"), + addMetaDataTreeWidgetItem(tr("Place name"), QStringLiteral("note-attributes/place-name"), noteAttributesItem); - addMetaDataTreeWidgetItem(tr("Content class"), - QStringLiteral("note-attributes/content-class"), + addMetaDataTreeWidgetItem(tr("Content class"), QStringLiteral("note-attributes/content-class"), + noteAttributesItem); + addMetaDataTreeWidgetItem(tr("Application data"), + QStringLiteral("note-attributes/application-data"), noteAttributesItem); - addMetaDataTreeWidgetItem( - tr("Application data"), - QStringLiteral("note-attributes/application-data"), noteAttributesItem); } /** @@ -698,8 +661,7 @@ void EvernoteImportDialog::setupMetaDataTreeWidgetItems() { */ void EvernoteImportDialog::storeMetaDataTreeWidgetItemsCheckedState() { QList items = ui->metaDataTreeWidget->findItems( - QStringLiteral("*"), - Qt::MatchWrap | Qt::MatchWildcard | Qt::MatchRecursive); + QStringLiteral("*"), Qt::MatchWrap | Qt::MatchWildcard | Qt::MatchRecursive); QSettings settings; QStringList metaDataUnCheckedList; @@ -720,8 +682,7 @@ void EvernoteImportDialog::storeMetaDataTreeWidgetItemsCheckedState() { */ bool EvernoteImportDialog::isMetaDataChecked() { QList items = ui->metaDataTreeWidget->findItems( - QStringLiteral("*"), - Qt::MatchWrap | Qt::MatchWildcard | Qt::MatchRecursive); + QStringLiteral("*"), Qt::MatchWrap | Qt::MatchWildcard | Qt::MatchRecursive); Q_FOREACH (QTreeWidgetItem *item, items) { if (item->checkState(0) == Qt::Checked) { @@ -790,9 +751,8 @@ QString EvernoteImportDialog::getMarkdownForAttachmentFileData( QString fileName = mediaFileData.fileName; // create a temporary file for the attachment - auto *tempFile = - new QTemporaryFile(QDir::tempPath() + QDir::separator() + - QStringLiteral("media-XXXXXX.") + suffix); + auto *tempFile = new QTemporaryFile(QDir::tempPath() + QDir::separator() + + QStringLiteral("media-XXXXXX.") + suffix); if (!tempFile->open()) { return QString(); diff --git a/src/dialogs/evernoteimportdialog.h b/src/dialogs/evernoteimportdialog.h index 87126a1a5..06af472e3 100644 --- a/src/dialogs/evernoteimportdialog.h +++ b/src/dialogs/evernoteimportdialog.h @@ -40,19 +40,16 @@ class EvernoteImportDialog : public MasterDialog { void initNoteCount(const QString &data); - QString getMarkdownForMediaFileData(Note note, - const MediaFileData &mediaFileData); + QString getMarkdownForMediaFileData(Note note, const MediaFileData &mediaFileData); - QString getMarkdownForAttachmentFileData( - Note note, const MediaFileData &mediaFileData); + QString getMarkdownForAttachmentFileData(Note note, const MediaFileData &mediaFileData); - QTreeWidgetItem *addMetaDataTreeWidgetItem( - const QString &name, const QString &attributeName = QString(), - QTreeWidgetItem *parentItem = nullptr); + QTreeWidgetItem *addMetaDataTreeWidgetItem(const QString &name, + const QString &attributeName = QString(), + QTreeWidgetItem *parentItem = nullptr); bool isMetaDataChecked(); - /** These require xml patterns **/ #if (QT_VERSION < QT_VERSION_CHECK(6, 0, 0)) void importNotes(const QString &data); @@ -63,8 +60,7 @@ class EvernoteImportDialog : public MasterDialog { void tagNote(QXmlQuery &query, Note ¬e); - QString importAttachments(const Note ¬e, QString content, - QXmlQuery query); + QString importAttachments(const Note ¬e, QString content, QXmlQuery query); QString generateMetaDataMarkdown(QXmlQuery query); #endif diff --git a/src/dialogs/filedialog.cpp b/src/dialogs/filedialog.cpp index 7e155234b..3fc169897 100644 --- a/src/dialogs/filedialog.cpp +++ b/src/dialogs/filedialog.cpp @@ -32,10 +32,8 @@ FileDialog::FileDialog(const QString& name) { setDirectory(path); // store the directory for the next time the dialog opens - connect(this, SIGNAL(fileSelected(QString)), this, - SLOT(storeDirectory(QString))); - connect(this, SIGNAL(filesSelected(QStringList)), this, - SLOT(storeDirectory(QStringList))); + connect(this, SIGNAL(fileSelected(QString)), this, SLOT(storeDirectory(QString))); + connect(this, SIGNAL(filesSelected(QStringList)), this, SLOT(storeDirectory(QStringList))); } } diff --git a/src/dialogs/imagedialog.cpp b/src/dialogs/imagedialog.cpp index 2c7a08fbb..19405ae57 100644 --- a/src/dialogs/imagedialog.cpp +++ b/src/dialogs/imagedialog.cpp @@ -12,8 +12,7 @@ #include "filedialog.h" #include "ui_imagedialog.h" -ImageDialog::ImageDialog(QWidget *parent) - : MasterDialog(parent), ui(new Ui::ImageDialog) { +ImageDialog::ImageDialog(QWidget *parent) : MasterDialog(parent), ui(new Ui::ImageDialog) { _imageFile = nullptr; _tempFile = nullptr; _rubberBand = nullptr; @@ -61,15 +60,11 @@ ImageDialog::~ImageDialog() { delete ui; } -bool ImageDialog::isDisableCopying() { - return ui->disableCopyingCheckBox->isChecked(); -} +bool ImageDialog::isDisableCopying() { return ui->disableCopyingCheckBox->isChecked(); } QFile *ImageDialog::getImageFile() { return _imageFile; } -QString ImageDialog::getFilePathOrUrl() { - return ui->fileEdit->text().trimmed(); -} +QString ImageDialog::getFilePathOrUrl() { return ui->fileEdit->text().trimmed(); } QString ImageDialog::getImageTitle() { return ui->titleEdit->text(); } @@ -129,11 +124,10 @@ void ImageDialog::setPixmap(const QPixmap &pixmap, bool updateBase) { void ImageDialog::on_buttonBox_accepted() { // if the image was manipulated or from the clipboard we will store it into // a temporary file - if (ui->fileEdit->text().trimmed().isEmpty() || _imageWasCropped || - _imageWasDownloaded || + if (ui->fileEdit->text().trimmed().isEmpty() || _imageWasCropped || _imageWasDownloaded || ui->widthSpinBox->value() != _basePixmap.width()) { - _tempFile = new QTemporaryFile(QDir::tempPath() + QDir::separator() + - "qownnotes-media-XXXXXX.png"); + _tempFile = + new QTemporaryFile(QDir::tempPath() + QDir::separator() + "qownnotes-media-XXXXXX.png"); if (_tempFile->open()) { // save temporary png image @@ -216,8 +210,7 @@ void ImageDialog::on_fileEdit_textChanged(const QString &arg1) { void ImageDialog::on_disableCopyingCheckBox_toggled(bool checked) { ui->scaleFrame->setDisabled(checked); - ui->graphicsView->setDragMode(checked ? QGraphicsView::NoDrag - : QGraphicsView::RubberBandDrag); + ui->graphicsView->setDragMode(checked ? QGraphicsView::NoDrag : QGraphicsView::RubberBandDrag); if (checked) { // reset scaling @@ -225,8 +218,7 @@ void ImageDialog::on_disableCopyingCheckBox_toggled(bool checked) { } } -void ImageDialog::on_graphicsView_rubberBandChanged(QRect viewportRect, - QPointF fromScenePoint, +void ImageDialog::on_graphicsView_rubberBandChanged(QRect viewportRect, QPointF fromScenePoint, QPointF toScenePoint) { if (viewportRect.isEmpty()) { // dragging has stopped _rubberBand = new QRubberBand(QRubberBand::Rectangle, ui->graphicsView); @@ -235,8 +227,8 @@ void ImageDialog::on_graphicsView_rubberBandChanged(QRect viewportRect, // we need to adapt the rubberband by the content margins of the // graphics view - _lastRubberBandViewportRect.adjust(margin.left(), margin.top(), - margin.left(), margin.top()); + _lastRubberBandViewportRect.adjust(margin.left(), margin.top(), margin.left(), + margin.top()); _rubberBand->setGeometry(_lastRubberBandViewportRect); _rubberBand->show(); @@ -266,8 +258,7 @@ void ImageDialog::on_graphicsView_rubberBandChanged(QRect viewportRect, } // swap coordinates if the drag was "reversed" - if (fromScenePointI.x() > toScenePointI.x() && - fromScenePointI.y() > toScenePointI.y()) { + if (fromScenePointI.x() > toScenePointI.x() && fromScenePointI.y() > toScenePointI.y()) { _rubberBandSceneRect = QRect(toScenePointI, fromScenePointI); } else { _rubberBandSceneRect = QRect(fromScenePointI, toScenePointI); diff --git a/src/dialogs/imagedialog.h b/src/dialogs/imagedialog.h index 43f468b2a..2c07efe61 100644 --- a/src/dialogs/imagedialog.h +++ b/src/dialogs/imagedialog.h @@ -39,8 +39,7 @@ class ImageDialog : public MasterDialog { void on_disableCopyingCheckBox_toggled(bool checked); - void on_graphicsView_rubberBandChanged(QRect viewportRect, - QPointF fromScenePoint, + void on_graphicsView_rubberBandChanged(QRect viewportRect, QPointF fromScenePoint, QPointF toScenePoint); void on_cropButton_clicked(); diff --git a/src/dialogs/issueassistantdialog.cpp b/src/dialogs/issueassistantdialog.cpp index 2ddbeaa35..5e722ff2d 100644 --- a/src/dialogs/issueassistantdialog.cpp +++ b/src/dialogs/issueassistantdialog.cpp @@ -28,10 +28,10 @@ IssueAssistantDialog::IssueAssistantDialog(QWidget *parent) SLOT(allowIssuePageNextButton())); QObject::connect(ui->questionPlainTextEdit, SIGNAL(textChanged()), this, SLOT(allowIssuePageNextButton())); - QObject::connect(ui->expectedBehaviourPlainTextEdit, SIGNAL(textChanged()), - this, SLOT(allowIssuePageNextButton())); - QObject::connect(ui->actualBehaviourPlainTextEdit, SIGNAL(textChanged()), - this, SLOT(allowIssuePageNextButton())); + QObject::connect(ui->expectedBehaviourPlainTextEdit, SIGNAL(textChanged()), this, + SLOT(allowIssuePageNextButton())); + QObject::connect(ui->actualBehaviourPlainTextEdit, SIGNAL(textChanged()), this, + SLOT(allowIssuePageNextButton())); QObject::connect(ui->stepsPlainTextEdit, SIGNAL(textChanged()), this, SLOT(allowIssuePageNextButton())); QObject::connect(ui->logOutputPlainTextEdit, SIGNAL(textChanged()), this, @@ -43,8 +43,7 @@ IssueAssistantDialog::IssueAssistantDialog(QWidget *parent) IssueAssistantDialog::~IssueAssistantDialog() { delete ui; } void IssueAssistantDialog::on_nextButton_clicked() { - MetricsService::instance()->sendVisitIfEnabled( - QStringLiteral("issue-assistant-dialog/next")); + MetricsService::instance()->sendVisitIfEnabled(QStringLiteral("issue-assistant-dialog/next")); int index = ui->stackedWidget->currentIndex(); int maxIndex = ui->stackedWidget->count() - 1; @@ -68,13 +67,11 @@ void IssueAssistantDialog::allowIssuePageNextButton() const { } if (ui->expectedBehaviourPlainTextEdit->isVisible()) { - allow = allow && - ui->expectedBehaviourPlainTextEdit->toPlainText().length() >= 10; + allow = allow && ui->expectedBehaviourPlainTextEdit->toPlainText().length() >= 10; } if (ui->actualBehaviourPlainTextEdit->isVisible()) { - allow = allow && - ui->actualBehaviourPlainTextEdit->toPlainText().length() >= 10; + allow = allow && ui->actualBehaviourPlainTextEdit->toPlainText().length() >= 10; } if (ui->stepsPlainTextEdit->isVisible()) { @@ -87,9 +84,9 @@ void IssueAssistantDialog::allowIssuePageNextButton() const { void IssueAssistantDialog::allowLogPageNextButton() const { bool allow = true; -// if (ui->issueTypeComboBox->currentIndex() == ProblemIssueType) { -// allow = ui->logOutputPlainTextEdit->toPlainText().length() >= 10; -// } + // if (ui->issueTypeComboBox->currentIndex() == ProblemIssueType) { + // allow = ui->logOutputPlainTextEdit->toPlainText().length() >= 10; + // } ui->nextButton->setEnabled(allow); } @@ -166,14 +163,11 @@ void IssueAssistantDialog::generateSubmitPageContent() const { break; case FeatureRequestIssueType: case ProblemIssueType: - body += - "#### Expected behaviour\n\n" + - ui->expectedBehaviourPlainTextEdit->toPlainText().trimmed() + - "\n\n"; + body += "#### Expected behaviour\n\n" + + ui->expectedBehaviourPlainTextEdit->toPlainText().trimmed() + "\n\n"; body += "#### Actual behaviour\n\n" + - ui->actualBehaviourPlainTextEdit->toPlainText().trimmed() + - "\n\n"; + ui->actualBehaviourPlainTextEdit->toPlainText().trimmed() + "\n\n"; body += "#### Steps to reproduce\n\n" + ui->stepsPlainTextEdit->toPlainText().trimmed() + "\n\n"; @@ -185,21 +179,18 @@ void IssueAssistantDialog::generateSubmitPageContent() const { body += "#### Relevant log output in the Log panel\n\n" "
Expand\n\n```\n" + - ui->logOutputPlainTextEdit->toPlainText().trimmed() + - "\n```\n
\n\n"; + ui->logOutputPlainTextEdit->toPlainText().trimmed() + "\n```\n\n\n"; body += "#### Information about the application, settings and " "environment\n\n
Expand\n\n" + - ui->debugOutputPlainTextEdit->toPlainText().trimmed() + - "\n
\n\n"; + ui->debugOutputPlainTextEdit->toPlainText().trimmed() + "\n\n\n"; ui->bodyPlainTextEdit->setPlainText(body); } void IssueAssistantDialog::on_backButton_clicked() { - MetricsService::instance()->sendVisitIfEnabled( - QStringLiteral("issue-assistant-dialog/back")); + MetricsService::instance()->sendVisitIfEnabled(QStringLiteral("issue-assistant-dialog/back")); int index = ui->stackedWidget->currentIndex(); @@ -234,15 +225,13 @@ void IssueAssistantDialog::on_issueTypeComboBox_currentIndexChanged(int index) { void IssueAssistantDialog::on_refreshLogButton_clicked() { refreshLogOutput(); } void IssueAssistantDialog::on_postButton_clicked() { - MetricsService::instance()->sendVisitIfEnabled( - QStringLiteral("issue-assistant-dialog/post")); + MetricsService::instance()->sendVisitIfEnabled(QStringLiteral("issue-assistant-dialog/post")); QClipboard *clipboard = QApplication::clipboard(); clipboard->setText(ui->bodyPlainTextEdit->toPlainText()); QUrl url("https://github.com/pbek/QOwnNotes/issues/new?title=" + - QUrl::toPercentEncoding(ui->submitTitleLineEdit->text()) + - "&body=" + + QUrl::toPercentEncoding(ui->submitTitleLineEdit->text()) + "&body=" + QUrl::toPercentEncoding("Please paste the text from the issue " "assistant here. It should be already in " "your clipboard.")); @@ -264,10 +253,9 @@ void IssueAssistantDialog::on_searchIssueButton_clicked() { } void IssueAssistantDialog::on_newIssueButton_clicked() { - if (Utils::Gui::question( - this, QStringLiteral("Create new issue"), - QStringLiteral("Reset this dialog and create a new issue?"), - QStringLiteral("issue-dialog-new-issue")) != QMessageBox::Yes) { + if (Utils::Gui::question(this, QStringLiteral("Create new issue"), + QStringLiteral("Reset this dialog and create a new issue?"), + QStringLiteral("issue-dialog-new-issue")) != QMessageBox::Yes) { return; } diff --git a/src/dialogs/issueassistantdialog.h b/src/dialogs/issueassistantdialog.h index 5d9831aba..98e72680c 100644 --- a/src/dialogs/issueassistantdialog.h +++ b/src/dialogs/issueassistantdialog.h @@ -12,12 +12,7 @@ class IssueAssistantDialog : public MasterDialog { Q_OBJECT public: - enum IssueAssistantPages { - IssuePage, - LogOutputPage, - DebugSettingsPage, - SubmitPage - }; + enum IssueAssistantPages { IssuePage, LogOutputPage, DebugSettingsPage, SubmitPage }; enum IssueTypes { ProblemIssueType, diff --git a/src/dialogs/joplinimportdialog.cpp b/src/dialogs/joplinimportdialog.cpp index d7116e35d..c66a69f90 100644 --- a/src/dialogs/joplinimportdialog.cpp +++ b/src/dialogs/joplinimportdialog.cpp @@ -13,7 +13,7 @@ #include "filedialog.h" #include "ui_joplinimportdialog.h" -JoplinImportDialog::JoplinImportDialog(QWidget *parent) +JoplinImportDialog::JoplinImportDialog(QWidget* parent) : MasterDialog(parent), ui(new Ui::JoplinImportDialog) { ui->setupUi(this); @@ -26,56 +26,39 @@ JoplinImportDialog::JoplinImportDialog(QWidget *parent) bool showFolders = NoteFolder::isCurrentShowSubfolders(); if (!showFolders) { - ui->folderImportCheckBox->setToolTip(QObject::tr( - "Turned on note subfolders for the current note folder to be " - "able to import folders.")); + ui->folderImportCheckBox->setToolTip( + QObject::tr("Turned on note subfolders for the current note folder to be " + "able to import folders.")); } ui->folderImportCheckBox->setEnabled(showFolders); ui->folderImportCheckBox->setChecked( - settings.value( - QStringLiteral("JoplinImport/FolderImportCheckBoxChecked"), true) - .toBool() && showFolders); + settings.value(QStringLiteral("JoplinImport/FolderImportCheckBoxChecked"), true).toBool() && + showFolders); ui->tagImportCheckBox->setChecked( - settings - .value(QStringLiteral("JoplinImport/TagImportCheckBoxChecked"), - true) - .toBool()); + settings.value(QStringLiteral("JoplinImport/TagImportCheckBoxChecked"), true).toBool()); ui->metadataImportCheckBox->setChecked( - settings - .value(QStringLiteral("JoplinImport/MetadataImportCheckBoxChecked"), - true) - .toBool()); - ui->imageImportCheckBox->setChecked( - settings - .value(QStringLiteral("JoplinImport/ImageImportCheckBoxChecked"), - true) + settings.value(QStringLiteral("JoplinImport/MetadataImportCheckBoxChecked"), true) .toBool()); + ui->imageImportCheckBox->setChecked( + settings.value(QStringLiteral("JoplinImport/ImageImportCheckBoxChecked"), true).toBool()); ui->attachmentImportCheckBox->setChecked( - settings - .value(QStringLiteral( - "JoplinImport/AttachmentImportCheckBoxChecked"), - true) + settings.value(QStringLiteral("JoplinImport/AttachmentImportCheckBoxChecked"), true) .toBool()); } JoplinImportDialog::~JoplinImportDialog() { QSettings settings; - settings.setValue( - QStringLiteral("JoplinImport/FolderImportCheckBoxChecked"), - ui->folderImportCheckBox->isChecked()); - settings.setValue( - QStringLiteral("JoplinImport/TagImportCheckBoxChecked"), - ui->tagImportCheckBox->isChecked()); - settings.setValue( - QStringLiteral("JoplinImport/MetadataImportCheckBoxChecked"), - ui->metadataImportCheckBox->isChecked()); - settings.setValue( - QStringLiteral("JoplinImport/ImageImportCheckBoxChecked"), - ui->imageImportCheckBox->isChecked()); - settings.setValue( - QStringLiteral("JoplinImport/AttachmentImportCheckBoxChecked"), - ui->attachmentImportCheckBox->isChecked()); + settings.setValue(QStringLiteral("JoplinImport/FolderImportCheckBoxChecked"), + ui->folderImportCheckBox->isChecked()); + settings.setValue(QStringLiteral("JoplinImport/TagImportCheckBoxChecked"), + ui->tagImportCheckBox->isChecked()); + settings.setValue(QStringLiteral("JoplinImport/MetadataImportCheckBoxChecked"), + ui->metadataImportCheckBox->isChecked()); + settings.setValue(QStringLiteral("JoplinImport/ImageImportCheckBoxChecked"), + ui->imageImportCheckBox->isChecked()); + settings.setValue(QStringLiteral("JoplinImport/AttachmentImportCheckBoxChecked"), + ui->attachmentImportCheckBox->isChecked()); delete ui; } @@ -127,7 +110,7 @@ void JoplinImportDialog::on_importButton_clicked() { ui->progressBar->setMaximum(files.count()); ui->progressBar->show(); - foreach(QString fileName, files) { + foreach (QString fileName, files) { QCoreApplication::processEvents(); QString filePath = dir.path() + "/" + fileName; QFile file(filePath); @@ -138,51 +121,50 @@ void JoplinImportDialog::on_importButton_clicked() { } const QString text = file.readAll(); - auto textLines = text.split(QRegularExpression( - QStringLiteral(R"((\r\n)|(\n\r)|\r|\n)"))); + auto textLines = text.split(QRegularExpression(QStringLiteral(R"((\r\n)|(\n\r)|\r|\n)"))); const auto id = fileName.remove(QRegularExpression("\\.md$")); // check if text contains a note - if (text.contains(QRegularExpression( - "^type_: 1$", QRegularExpression::MultilineOption))) { + if (text.contains(QRegularExpression("^type_: 1$", QRegularExpression::MultilineOption))) { _noteData[id] = text; // don't increase the progress bar yet continue; } // check if text contains a folder - if (text.contains(QRegularExpression( - "^type_: 2$", QRegularExpression::MultilineOption))) { + if (text.contains(QRegularExpression("^type_: 2$", QRegularExpression::MultilineOption))) { _folderData[id] = text; } // check if text contains an image or attachment - else if (text.contains(QRegularExpression( - "^type_: 4$", QRegularExpression::MultilineOption))) { - if (text.contains(QRegularExpression( - "^mime: image/", QRegularExpression::MultilineOption))) { + else if (text.contains( + QRegularExpression("^type_: 4$", QRegularExpression::MultilineOption))) { + if (text.contains( + QRegularExpression("^mime: image/", QRegularExpression::MultilineOption))) { _imageData[id] = text; } else { _attachmentData[id] = text; } } // check if text contains a tag - else if (text.contains(QRegularExpression( - "^type_: 5$", QRegularExpression::MultilineOption))) { + else if (text.contains( + QRegularExpression("^type_: 5$", QRegularExpression::MultilineOption))) { _tagData[id] = textLines[0]; } // check if text contains a tag assignment - else if (text.contains(QRegularExpression( - "^type_: 6$", QRegularExpression::MultilineOption))) { - auto noteIdMatch = QRegularExpression("^note_id: (.+)$", - QRegularExpression::MultilineOption).match(text); + else if (text.contains( + QRegularExpression("^type_: 6$", QRegularExpression::MultilineOption))) { + auto noteIdMatch = + QRegularExpression("^note_id: (.+)$", QRegularExpression::MultilineOption) + .match(text); QString noteId; if (noteIdMatch.hasMatch()) { noteId = noteIdMatch.captured(1); } - auto tagIdMatch = QRegularExpression("^tag_id: (.+)$", - QRegularExpression::MultilineOption).match(text); + auto tagIdMatch = + QRegularExpression("^tag_id: (.+)$", QRegularExpression::MultilineOption) + .match(text); QString tagId; if (tagIdMatch.hasMatch()) { @@ -242,8 +224,8 @@ NoteSubFolder JoplinImportDialog::importFolder(const QString& id, const QString& } auto parentSubFolder = NoteSubFolder(); - auto parentIdMatch = QRegularExpression("^parent_id: (.+)$", - QRegularExpression::MultilineOption).match(text); + auto parentIdMatch = + QRegularExpression("^parent_id: (.+)$", QRegularExpression::MultilineOption).match(text); // check if we need to create the parent first if (parentIdMatch.hasMatch()) { @@ -254,8 +236,7 @@ NoteSubFolder JoplinImportDialog::importFolder(const QString& id, const QString& } } - auto textLines = text.split(QRegularExpression( - QStringLiteral(R"((\r\n)|(\n\r)|\r|\n)"))); + auto textLines = text.split(QRegularExpression(QStringLiteral(R"((\r\n)|(\n\r)|\r|\n)"))); auto folderName = textLines.at(0).trimmed(); @@ -298,16 +279,15 @@ NoteSubFolder JoplinImportDialog::importFolder(const QString& id, const QString& */ bool JoplinImportDialog::importNote(const QString& id, const QString& text, const QString& dirPath) { - auto textLines = text.split(QRegularExpression( - QStringLiteral(R"((\r\n)|(\n\r)|\r|\n)"))); + auto textLines = text.split(QRegularExpression(QStringLiteral(R"((\r\n)|(\n\r)|\r|\n)"))); auto title = textLines.at(0); title.remove(QRegularExpression("^[\\d+\\.]+")); auto noteText = Note::createNoteHeader(title.trimmed()); noteText += text.trimmed(); - auto parts = noteText.split(QRegularExpression("^id: " + id + "$", - QRegularExpression::MultilineOption)); + auto parts = + noteText.split(QRegularExpression("^id: " + id + "$", QRegularExpression::MultilineOption)); Note note = Note(); QString newNoteText; @@ -321,8 +301,9 @@ bool JoplinImportDialog::importNote(const QString& id, const QString& text, note.setNoteText(newNoteText); if (ui->folderImportCheckBox->isChecked()) { - auto parentIdMatch = QRegularExpression("^parent_id: (.+)$", - QRegularExpression::MultilineOption).match(text); + auto parentIdMatch = + QRegularExpression("^parent_id: (.+)$", QRegularExpression::MultilineOption) + .match(text); // check if we need to create note sub-folders if (parentIdMatch.hasMatch()) { @@ -374,7 +355,7 @@ int JoplinImportDialog::getImportCount() const { return _importCount; } void JoplinImportDialog::tagNote(const QString& id, const Note& note) { QStringList tagAssignmentData = _tagAssignmentData[id]; - foreach(QString tagId, tagAssignmentData) { + foreach (QString tagId, tagAssignmentData) { QString tagName = _tagData[tagId]; // create a new tag if it doesn't exist @@ -399,8 +380,7 @@ void JoplinImportDialog::tagNote(const QString& id, const Note& note) { */ void JoplinImportDialog::handleImages(Note& note, const QString& dirPath) { QString noteText = note.getNoteText(); - auto i = QRegularExpression(R"(!\[([^\]]*)\]\(:\/([\w\d]+)\))") - .globalMatch(noteText); + auto i = QRegularExpression(R"(!\[([^\]]*)\]\(:\/([\w\d]+)\))").globalMatch(noteText); while (i.hasNext()) { QRegularExpressionMatch match = i.next(); @@ -411,8 +391,7 @@ void JoplinImportDialog::handleImages(Note& note, const QString& dirPath) { importImage(note, dirPath, noteText, imageTag, imageId, imageName); } - i = QRegularExpression(R"()") - .globalMatch(noteText); + i = QRegularExpression(R"()").globalMatch(noteText); while (i.hasNext()) { QRegularExpressionMatch match = i.next(); @@ -435,22 +414,22 @@ void JoplinImportDialog::importImage(Note& note, const QString& dirPath, QString // qDebug() << __func__ << " - 'imageData': " << imageData; QString fileExtension; - auto fileExtensionMatch = QRegularExpression("^file_extension: (.+)$", - QRegularExpression::MultilineOption).match(imageData); + auto fileExtensionMatch = + QRegularExpression("^file_extension: (.+)$", QRegularExpression::MultilineOption) + .match(imageData); if (fileExtensionMatch.hasMatch()) { fileExtension = fileExtensionMatch.captured(1); } else { // if the extension wasn't set we'll try to get it from the original file - auto imageDataLines = imageData.split(QRegularExpression( - QStringLiteral(R"((\r\n)|(\n\r)|\r|\n)"))); + auto imageDataLines = + imageData.split(QRegularExpression(QStringLiteral(R"((\r\n)|(\n\r)|\r|\n)"))); auto originalFileName = imageDataLines[0]; auto fileInfo = QFileInfo(originalFileName); fileExtension = fileInfo.suffix(); } - auto *mediaFile = new QFile(dirPath + "/resources/" + imageId + - "." + fileExtension); + auto* mediaFile = new QFile(dirPath + "/resources/" + imageId + "." + fileExtension); qDebug() << __func__ << " - 'mediaFile': " << mediaFile; @@ -458,8 +437,7 @@ void JoplinImportDialog::importImage(Note& note, const QString& dirPath, QString return; } - QString mediaMarkdown = note.getInsertMediaMarkdown( - mediaFile, false, false, imageName); + QString mediaMarkdown = note.getInsertMediaMarkdown(mediaFile, false, false, imageName); qDebug() << __func__ << " - 'mediaMarkdown': " << mediaMarkdown; noteText.replace(imageTag, mediaMarkdown); @@ -473,8 +451,7 @@ void JoplinImportDialog::importImage(Note& note, const QString& dirPath, QString */ void JoplinImportDialog::handleAttachments(Note& note, const QString& dirPath) { QString noteText = note.getNoteText(); - auto i = QRegularExpression(R"([^!](\[([^\]]*)\]\(:\/([\w\d]+)\)))") - .globalMatch(noteText); + auto i = QRegularExpression(R"([^!](\[([^\]]*)\]\(:\/([\w\d]+)\)))").globalMatch(noteText); while (i.hasNext()) { QRegularExpressionMatch match = i.next(); @@ -487,22 +464,22 @@ void JoplinImportDialog::handleAttachments(Note& note, const QString& dirPath) { qDebug() << __func__ << " - 'attachmentId': " << attachmentId; QString fileExtension; - auto fileExtensionMatch = QRegularExpression("^file_extension: (.+)$", - QRegularExpression::MultilineOption).match(attachmentData); + auto fileExtensionMatch = + QRegularExpression("^file_extension: (.+)$", QRegularExpression::MultilineOption) + .match(attachmentData); if (fileExtensionMatch.hasMatch()) { fileExtension = fileExtensionMatch.captured(1); } else { // if the extension wasn't set we'll try to get it from the original file - auto attachmentDataLines = attachmentData.split(QRegularExpression( - QStringLiteral(R"((\r\n)|(\n\r)|\r|\n)"))); + auto attachmentDataLines = + attachmentData.split(QRegularExpression(QStringLiteral(R"((\r\n)|(\n\r)|\r|\n)"))); auto originalFileName = attachmentDataLines[0]; auto fileInfo = QFileInfo(originalFileName); fileExtension = fileInfo.suffix(); } - auto *mediaFile = new QFile(dirPath + "/resources/" + attachmentId + - "." + fileExtension); + auto* mediaFile = new QFile(dirPath + "/resources/" + attachmentId + "." + fileExtension); qDebug() << __func__ << " - 'mediaFile': " << mediaFile; @@ -510,8 +487,7 @@ void JoplinImportDialog::handleAttachments(Note& note, const QString& dirPath) { continue; } - QString mediaMarkdown = note.getInsertAttachmentMarkdown( - mediaFile, attachmentName); + QString mediaMarkdown = note.getInsertAttachmentMarkdown(mediaFile, attachmentName); qDebug() << __func__ << " - 'mediaMarkdown': " << mediaMarkdown; noteText.replace(attachmentTag, mediaMarkdown); diff --git a/src/dialogs/joplinimportdialog.h b/src/dialogs/joplinimportdialog.h index 2934796f7..dba88cefa 100644 --- a/src/dialogs/joplinimportdialog.h +++ b/src/dialogs/joplinimportdialog.h @@ -1,9 +1,9 @@ #pragma once -#include "masterdialog.h" - #include +#include "masterdialog.h" + namespace Ui { class JoplinImportDialog; } @@ -22,35 +22,33 @@ class JoplinImportDialog : public MasterDialog { }; public: - explicit JoplinImportDialog(QWidget *parent = 0); + explicit JoplinImportDialog(QWidget* parent = 0); ~JoplinImportDialog() override; int getImportCount() const; -private slots: + private slots: void on_directoryButton_clicked(); void on_importButton_clicked(); private: - Ui::JoplinImportDialog *ui; + Ui::JoplinImportDialog* ui; int _importCount; QString _dirPath; - QHash _noteData; - QHash _folderData; - QHash _tagData; - QHash _tagAssignmentData; - QHash _imageData; - QHash _attachmentData; - QHash _importedFolders; + QHash _noteData; + QHash _folderData; + QHash _tagData; + QHash _tagAssignmentData; + QHash _imageData; + QHash _attachmentData; + QHash _importedFolders; - bool importNote(const QString& id, const QString& text, - const QString& dirPath); + bool importNote(const QString& id, const QString& text, const QString& dirPath); void tagNote(const QString& id, const Note& note); void handleImages(Note& note, const QString& dirPath); void handleAttachments(Note& note, const QString& dirPath); bool importFolders(); - NoteSubFolder importFolder(const QString &id, const QString &text); - void importImage(Note ¬e, const QString &dirPath, QString& noteText, - const QString &imageTag, const QString &imageId, - const QString &imageName = ""); + NoteSubFolder importFolder(const QString& id, const QString& text); + void importImage(Note& note, const QString& dirPath, QString& noteText, const QString& imageTag, + const QString& imageId, const QString& imageName = ""); }; diff --git a/src/dialogs/linkdialog.cpp b/src/dialogs/linkdialog.cpp index 2d21b7980..675af7739 100644 --- a/src/dialogs/linkdialog.cpp +++ b/src/dialogs/linkdialog.cpp @@ -24,7 +24,8 @@ LinkDialog::LinkDialog(int page, const QString &dialogTitle, QWidget *parent) on_tabWidget_currentChanged(page); // disallow ] characters, because they will break markdown links - ui->nameLineEdit->setValidator(new QRegularExpressionValidator(QRegularExpression(R"([^\]]*)"))); + ui->nameLineEdit->setValidator( + new QRegularExpressionValidator(QRegularExpression(R"([^\]]*)"))); firstVisibleNoteListRow = 0; if (!dialogTitle.isEmpty()) { @@ -86,9 +87,8 @@ void LinkDialog::on_searchLineEdit_textChanged(const QString &arg1) { } QString LinkDialog::getSelectedNoteName() const { - return ui->notesListWidget->currentRow() > -1 - ? ui->notesListWidget->currentItem()->text() - : QString(); + return ui->notesListWidget->currentRow() > -1 ? ui->notesListWidget->currentItem()->text() + : QString(); } Note LinkDialog::getSelectedNote() const { @@ -96,15 +96,15 @@ Note LinkDialog::getSelectedNote() const { return {}; } - const int noteId = - ui->notesListWidget->currentItem()->data(Qt::UserRole).toInt(); + const int noteId = ui->notesListWidget->currentItem()->data(Qt::UserRole).toInt(); return Note::fetch(noteId); } QString LinkDialog::getSelectedHeading() const { - return ui->headingListWidget->selectedItems().isEmpty() ? - "" : ui->headingListWidget->currentItem()->text(); + return ui->headingListWidget->selectedItems().isEmpty() + ? "" + : ui->headingListWidget->currentItem()->text(); } QString LinkDialog::getURL() const { @@ -117,17 +117,11 @@ QString LinkDialog::getURL() const { return url; } -QString LinkDialog::getLinkName() const { - return ui->nameLineEdit->text().trimmed(); -} +QString LinkDialog::getLinkName() const { return ui->nameLineEdit->text().trimmed(); } -void LinkDialog::setLinkName(const QString &text) { - ui->nameLineEdit->setText(text); -} +void LinkDialog::setLinkName(const QString &text) { ui->nameLineEdit->setText(text); } -QString LinkDialog::getLinkDescription() const { - return ui->descriptionLineEdit->text().trimmed(); -} +QString LinkDialog::getLinkDescription() const { return ui->descriptionLineEdit->text().trimmed(); } // // Event filters on the NoteSearchDialog @@ -139,15 +133,12 @@ bool LinkDialog::eventFilter(QObject *obj, QEvent *event) { // set focus to the notes list if Key_Down or Key_Tab were pressed // in the search line edit - if ((keyEvent->key() == Qt::Key_Down) || - (keyEvent->key() == Qt::Key_Tab)) { + if ((keyEvent->key() == Qt::Key_Down) || (keyEvent->key() == Qt::Key_Tab)) { // choose another selected item if current item is invisible auto item = ui->notesListWidget->currentItem(); - if ((item != nullptr) && - ui->notesListWidget->currentItem()->isHidden() && + if ((item != nullptr) && ui->notesListWidget->currentItem()->isHidden() && (this->firstVisibleNoteListRow >= 0)) { - ui->notesListWidget->setCurrentRow( - this->firstVisibleNoteListRow); + ui->notesListWidget->setCurrentRow(this->firstVisibleNoteListRow); } // give the keyboard focus to the notes list widget @@ -162,8 +153,7 @@ bool LinkDialog::eventFilter(QObject *obj, QEvent *event) { // set focus to the notes list if Key_Down or Key_Tab were pressed // in the search line edit - if ((keyEvent->key() == Qt::Key_Down) || - (keyEvent->key() == Qt::Key_Tab)) { + if ((keyEvent->key() == Qt::Key_Down) || (keyEvent->key() == Qt::Key_Tab)) { // give the keyboard focus to the heading list widget ui->headingListWidget->setFocus(); return true; @@ -176,8 +166,7 @@ bool LinkDialog::eventFilter(QObject *obj, QEvent *event) { // set focus to the note text edit if Key_Return or Key_Tab // were pressed in the notes list - if ((keyEvent->key() == Qt::Key_Return) || - (keyEvent->key() == Qt::Key_Tab)) { + if ((keyEvent->key() == Qt::Key_Return) || (keyEvent->key() == Qt::Key_Tab)) { ui->headingSearchLineEdit->setFocus(); return true; @@ -218,11 +207,10 @@ QString LinkDialog::getTitleForUrl(const QUrl &url) { } // parse title from webpage - QRegularExpression regex( - QStringLiteral(R"((.*)<\/title>)"), - QRegularExpression::MultilineOption | - QRegularExpression::DotMatchesEverythingOption | - QRegularExpression::InvertedGreedinessOption); + QRegularExpression regex(QStringLiteral(R"(<title>(.*)<\/title>)"), + QRegularExpression::MultilineOption | + QRegularExpression::DotMatchesEverythingOption | + QRegularExpression::InvertedGreedinessOption); QRegularExpressionMatch match = regex.match(html); QString title = match.captured(1); @@ -249,34 +237,28 @@ QString LinkDialog::getTitleForUrl(const QUrl &url) { void LinkDialog::addFileUrl() { QSettings settings; // load last url - QUrl fileUrl = - settings.value(QStringLiteral("LinkDialog/lastSelectedFileUrl")) - .toUrl(); + QUrl fileUrl = settings.value(QStringLiteral("LinkDialog/lastSelectedFileUrl")).toUrl(); if (Utils::Misc::isInPortableMode()) { fileUrl = QUrl(QStringLiteral("file://") + - Utils::Misc::prependPortableDataPathIfNeeded( - Utils::Misc::removeIfStartsWith( - fileUrl.toLocalFile(), QStringLiteral("/")))); + Utils::Misc::prependPortableDataPathIfNeeded(Utils::Misc::removeIfStartsWith( + fileUrl.toLocalFile(), QStringLiteral("/")))); } - fileUrl = QFileDialog::getOpenFileUrl(this, tr("Select file to link to"), - fileUrl); + fileUrl = QFileDialog::getOpenFileUrl(this, tr("Select file to link to"), fileUrl); QString fileUrlString = fileUrl.toString(QUrl::FullyEncoded); if (Utils::Misc::isInPortableMode()) { fileUrlString = QStringLiteral("file://") + QUrl(QStringLiteral("../") + - Utils::Misc::makePathRelativeToPortableDataPathIfNeeded( - fileUrl.toLocalFile())) + Utils::Misc::makePathRelativeToPortableDataPathIfNeeded(fileUrl.toLocalFile())) .toString(QUrl::FullyEncoded); } if (!fileUrlString.isEmpty()) { // store url for the next time - settings.setValue(QStringLiteral("LinkDialog/lastSelectedFileUrl"), - fileUrlString); + settings.setValue(QStringLiteral("LinkDialog/lastSelectedFileUrl"), fileUrlString); // write the file-url to the url text-edit ui->urlEdit->setText(fileUrlString); @@ -290,27 +272,24 @@ void LinkDialog::addDirectoryUrl() { QSettings settings; // load last url QUrl directoryUrl = - settings.value(QStringLiteral("LinkDialog/lastSelectedDirectoryUrl")) - .toUrl(); + settings.value(QStringLiteral("LinkDialog/lastSelectedDirectoryUrl")).toUrl(); if (Utils::Misc::isInPortableMode()) { directoryUrl = QUrl(QStringLiteral("file://") + - Utils::Misc::prependPortableDataPathIfNeeded( - Utils::Misc::removeIfStartsWith(directoryUrl.toLocalFile(), - QStringLiteral("/")))); + Utils::Misc::prependPortableDataPathIfNeeded(Utils::Misc::removeIfStartsWith( + directoryUrl.toLocalFile(), QStringLiteral("/")))); } - directoryUrl = QFileDialog::getExistingDirectoryUrl( - this, tr("Select directory to link to"), directoryUrl); + directoryUrl = + QFileDialog::getExistingDirectoryUrl(this, tr("Select directory to link to"), directoryUrl); QString directoryUrlString = directoryUrl.toString(QUrl::FullyEncoded); if (Utils::Misc::isInPortableMode()) { directoryUrlString = QStringLiteral("file://") + - QUrl(QStringLiteral("../") + - Utils::Misc::makePathRelativeToPortableDataPathIfNeeded( - directoryUrl.toLocalFile())) + QUrl(QStringLiteral("../") + Utils::Misc::makePathRelativeToPortableDataPathIfNeeded( + directoryUrl.toLocalFile())) .toString(QUrl::FullyEncoded); } @@ -332,8 +311,7 @@ void LinkDialog::on_urlEdit_textChanged(const QString &arg1) { } // try to get the title of the webpage if no link name was set - if (url.scheme().startsWith(QStringLiteral("http")) && - ui->nameLineEdit->text().isEmpty()) { + if (url.scheme().startsWith(QStringLiteral("http")) && ui->nameLineEdit->text().isEmpty()) { const QString title = getTitleForUrl(url); if (!title.isEmpty()) { @@ -346,19 +324,16 @@ void LinkDialog::setupFileUrlMenu() { auto *addMenu = new QMenu(this); QAction *addFileAction = addMenu->addAction(tr("Select file to link to")); - addFileAction->setIcon(QIcon::fromTheme( - QStringLiteral("document-open"), - QIcon(QStringLiteral( - ":icons/breeze-qownnotes/16x16/document-open.svg")))); + addFileAction->setIcon( + QIcon::fromTheme(QStringLiteral("document-open"), + QIcon(QStringLiteral(":icons/breeze-qownnotes/16x16/document-open.svg")))); connect(addFileAction, SIGNAL(triggered()), this, SLOT(addFileUrl())); - QAction *addDirectoryAction = - addMenu->addAction(tr("Select directory to link to")); - addDirectoryAction->setIcon(QIcon::fromTheme( - QStringLiteral("folder"), - QIcon(QStringLiteral(":icons/breeze-qownnotes/16x16/folder.svg")))); - connect(addDirectoryAction, SIGNAL(triggered()), this, - SLOT(addDirectoryUrl())); + QAction *addDirectoryAction = addMenu->addAction(tr("Select directory to link to")); + addDirectoryAction->setIcon( + QIcon::fromTheme(QStringLiteral("folder"), + QIcon(QStringLiteral(":icons/breeze-qownnotes/16x16/folder.svg")))); + connect(addDirectoryAction, SIGNAL(triggered()), this, SLOT(addDirectoryUrl())); ui->fileUrlButton->setMenu(addMenu); } diff --git a/src/dialogs/linkdialog.h b/src/dialogs/linkdialog.h index e5c2db12d..e2c37a73b 100644 --- a/src/dialogs/linkdialog.h +++ b/src/dialogs/linkdialog.h @@ -14,10 +14,7 @@ class LinkDialog : public MasterDialog { Q_OBJECT public: - enum LinkDialogPages { - TextLinkPage, - NoteLinkPage - }; + enum LinkDialogPages { TextLinkPage, NoteLinkPage }; explicit LinkDialog(int page, const QString &dialogTitle = QString(), QWidget *parent = nullptr); @@ -42,14 +39,13 @@ class LinkDialog : public MasterDialog { void on_headingSearchLineEdit_textChanged(const QString &arg1); - void on_notesListWidget_currentItemChanged(QListWidgetItem *current, - QListWidgetItem *previous); + void on_notesListWidget_currentItemChanged(QListWidgetItem *current, QListWidgetItem *previous); void on_headingListWidget_doubleClicked(const QModelIndex &index); void on_tabWidget_currentChanged(int index); -private: + private: Ui::LinkDialog *ui; int firstVisibleNoteListRow; bool eventFilter(QObject *obj, QEvent *event) override; diff --git a/src/dialogs/localtrashdialog.cpp b/src/dialogs/localtrashdialog.cpp index bcf000463..3647097f5 100644 --- a/src/dialogs/localtrashdialog.cpp +++ b/src/dialogs/localtrashdialog.cpp @@ -21,8 +21,7 @@ class LocalTrashTreeWidgetItem : public QTreeWidgetItem { // allow sorting for the date column if (column == 1) { - return data(column, Qt::UserRole).toInt() < - other.data(column, Qt::UserRole).toInt(); + return data(column, Qt::UserRole).toInt() < other.data(column, Qt::UserRole).toInt(); } return text(column).toLower() < other.text(column).toLower(); @@ -45,18 +44,16 @@ LocalTrashDialog::LocalTrashDialog(QWidget *parent) button->setToolTip(tr("Restore selected notes")); button->setProperty("ActionRole", Restore); button->setDefault(false); - button->setIcon(QIcon::fromTheme( - QStringLiteral("view-restore"), - QIcon(":/icons/breeze-qownnotes/16x16/view-restore.svg"))); + button->setIcon(QIcon::fromTheme(QStringLiteral("view-restore"), + QIcon(":/icons/breeze-qownnotes/16x16/view-restore.svg"))); ui->buttonBox->addButton(button, QDialogButtonBox::ActionRole); button = new QPushButton(tr("Remove"), this); button->setToolTip(tr("Remove selected notes")); button->setProperty("ActionRole", Remove); button->setDefault(false); - button->setIcon(QIcon::fromTheme( - QStringLiteral("edit-delete"), - QIcon(":/icons/breeze-qownnotes/16x16/edit-delete.svg"))); + button->setIcon(QIcon::fromTheme(QStringLiteral("edit-delete"), + QIcon(":/icons/breeze-qownnotes/16x16/edit-delete.svg"))); ui->buttonBox->addButton(button, QDialogButtonBox::ActionRole); // button = new QPushButton(tr("Cancel")); @@ -92,19 +89,16 @@ void LocalTrashDialog::loadTrashedNotes() { item->setText(1, trashItem.getCreated().toString()); item->setData(0, Qt::UserRole, trashItem.getId()); // add timestamp data to allow sorting - item->setData(1, Qt::UserRole, - trashItem.getCreated().toMSecsSinceEpoch()); + item->setData(1, Qt::UserRole, trashItem.getCreated().toMSecsSinceEpoch()); - QString toolTipText = tr("File will be restored to: %1") - .arg(trashItem.restorationFilePath()); + QString toolTipText = + tr("File will be restored to: %1").arg(trashItem.restorationFilePath()); // mark missing items if file is missing if (!trashItem.fileExists()) { item->setIcon( - 0, - QIcon::fromTheme( - QStringLiteral("edit-delete"), - QIcon(":/icons/breeze-qownnotes/16x16/edit-delete.svg"))); + 0, QIcon::fromTheme(QStringLiteral("edit-delete"), + QIcon(":/icons/breeze-qownnotes/16x16/edit-delete.svg"))); toolTipText = tr("File <strong>%1</strong> isn't readable and can't" " be restored!") .arg(trashItem.fullFilePath()); @@ -128,8 +122,7 @@ void LocalTrashDialog::setupMainSplitter() { // restore splitter sizes QSettings settings; - QByteArray state = - settings.value(QStringLiteral("localTrashSplitterSizes")).toByteArray(); + QByteArray state = settings.value(QStringLiteral("localTrashSplitterSizes")).toByteArray(); trashSplitter->restoreState(state); ui->gridLayout->layout()->addWidget(trashSplitter); @@ -139,8 +132,7 @@ void LocalTrashDialog::setupMainSplitter() { void LocalTrashDialog::storeSettings() { // store the splitter sizes QSettings settings; - settings.setValue(QStringLiteral("localTrashSplitterSizes"), - trashSplitter->saveState()); + settings.setValue(QStringLiteral("localTrashSplitterSizes"), trashSplitter->saveState()); } LocalTrashDialog::~LocalTrashDialog() { delete ui; } @@ -171,8 +163,8 @@ void LocalTrashDialog::dialogButtonClicked(QAbstractButton *button) { * @param current * @param previous */ -void LocalTrashDialog::on_trashTreeWidget_currentItemChanged( - QTreeWidgetItem *current, QTreeWidgetItem *previous) { +void LocalTrashDialog::on_trashTreeWidget_currentItemChanged(QTreeWidgetItem *current, + QTreeWidgetItem *previous) { Q_UNUSED(previous); int trashItemId = current->data(0, Qt::UserRole).toInt(); TrashItem trashItem = TrashItem::fetch(trashItemId); @@ -191,17 +183,15 @@ void LocalTrashDialog::restoreSelectedTrashItems() { return; } - if (Utils::Gui::question(this, tr("Restore selected notes"), - tr("Restore <strong>%n</strong> selected note(s)?", - "", selectedItemsCount), - QStringLiteral("local-trash-restore-notes")) == - QMessageBox::Yes) { + if (Utils::Gui::question( + this, tr("Restore selected notes"), + tr("Restore <strong>%n</strong> selected note(s)?", "", selectedItemsCount), + QStringLiteral("local-trash-restore-notes")) == QMessageBox::Yes) { const QSignalBlocker blocker(ui->trashTreeWidget); Q_UNUSED(blocker) int restoreCount = 0; - Q_FOREACH (QTreeWidgetItem *item, - ui->trashTreeWidget->selectedItems()) { + Q_FOREACH (QTreeWidgetItem *item, ui->trashTreeWidget->selectedItems()) { int id = item->data(0, Qt::UserRole).toInt(); TrashItem trashItem = TrashItem::fetch(id); bool wasRestored = trashItem.restoreFile(); @@ -215,10 +205,9 @@ void LocalTrashDialog::restoreSelectedTrashItems() { } } - Utils::Gui::information( - this, tr("Notes restored"), - tr("<strong>%n</strong> note(s) were restored", "", restoreCount), - QStringLiteral("local-trash-notes-restored")); + Utils::Gui::information(this, tr("Notes restored"), + tr("<strong>%n</strong> note(s) were restored", "", restoreCount), + QStringLiteral("local-trash-notes-restored")); if (restoreCount > 0) { loadTrashedNotes(); @@ -236,17 +225,15 @@ void LocalTrashDialog::removeSelectedTrashItems() { return; } - if (Utils::Gui::question(this, tr("Remove selected notes"), - tr("Remove <strong>%n</strong> selected note(s)?", - "", selectedItemsCount), - QStringLiteral("local-trash-remove-notes")) == - QMessageBox::Yes) { + if (Utils::Gui::question( + this, tr("Remove selected notes"), + tr("Remove <strong>%n</strong> selected note(s)?", "", selectedItemsCount), + QStringLiteral("local-trash-remove-notes")) == QMessageBox::Yes) { const QSignalBlocker blocker(ui->trashTreeWidget); Q_UNUSED(blocker) int removeCount = 0; - Q_FOREACH (QTreeWidgetItem *item, - ui->trashTreeWidget->selectedItems()) { + Q_FOREACH (QTreeWidgetItem *item, ui->trashTreeWidget->selectedItems()) { int id = item->data(0, Qt::UserRole).toInt(); TrashItem trashItem = TrashItem::fetch(id); bool wasRestored = trashItem.remove(true); @@ -260,10 +247,9 @@ void LocalTrashDialog::removeSelectedTrashItems() { } } - Utils::Gui::information( - this, tr("Notes removed"), - tr("<strong>%n</strong> note(s) were removed", "", removeCount), - QStringLiteral("local-trash-notes-removed")); + Utils::Gui::information(this, tr("Notes removed"), + tr("<strong>%n</strong> note(s) were removed", "", removeCount), + QStringLiteral("local-trash-notes-removed")); if (removeCount > 0) { loadTrashedNotes(); diff --git a/src/dialogs/localtrashdialog.h b/src/dialogs/localtrashdialog.h index 7329d9762..ff4f3c8b4 100644 --- a/src/dialogs/localtrashdialog.h +++ b/src/dialogs/localtrashdialog.h @@ -1,8 +1,9 @@ #pragma once -#include "masterdialog.h" #include <QStringList> +#include "masterdialog.h" + namespace Ui { class LocalTrashDialog; } @@ -22,8 +23,7 @@ class LocalTrashDialog : public MasterDialog { private slots: void storeSettings(); void dialogButtonClicked(QAbstractButton *button); - void on_trashTreeWidget_currentItemChanged(QTreeWidgetItem *current, - QTreeWidgetItem *previous); + void on_trashTreeWidget_currentItemChanged(QTreeWidgetItem *current, QTreeWidgetItem *previous); void on_searchLineEdit_textChanged(const QString &arg1); private: diff --git a/src/dialogs/masterdialog.cpp b/src/dialogs/masterdialog.cpp index af81c0d98..840f8bcd5 100644 --- a/src/dialogs/masterdialog.cpp +++ b/src/dialogs/masterdialog.cpp @@ -8,9 +8,7 @@ #include "services/metricsservice.h" -MasterDialog::MasterDialog(QWidget *parent) : QDialog(parent) { - installEventFilter(this); -} +MasterDialog::MasterDialog(QWidget *parent) : QDialog(parent) { installEventFilter(this); } void MasterDialog::closeEvent(QCloseEvent *event) { // storeGeometrySettings(); @@ -46,9 +44,7 @@ bool MasterDialog::eventFilter(QObject *obj, QEvent *event) { * * @return settings key */ -const QString MasterDialog::getGeometrySettingKey() const { - return objectName() + "/geometry"; -} +const QString MasterDialog::getGeometrySettingKey() const { return objectName() + "/geometry"; } void MasterDialog::show() { handleOpenDialog(); @@ -71,15 +67,13 @@ int MasterDialog::exec() { void MasterDialog::handleOpenDialog() { // restore the geometry of the dialog QSettings settings; - QByteArray geometryData = - settings.value(getGeometrySettingKey()).toByteArray(); + QByteArray geometryData = settings.value(getGeometrySettingKey()).toByteArray(); // restore the geometry if there is some data if (geometryData.length() > 0) { restoreGeometry(geometryData); } else { - const QRect screenGeometry = - QGuiApplication::primaryScreen()->availableGeometry(); + const QRect screenGeometry = QGuiApplication::primaryScreen()->availableGeometry(); // maximize the dialog window if it looks like that it doesn't fit on // the current screen @@ -95,13 +89,11 @@ void MasterDialog::handleOpenDialog() { } } -void MasterDialog::setIgnoreReturnKey(bool ignore) { - _ignoreReturnKey = ignore; -} +void MasterDialog::setIgnoreReturnKey(bool ignore) { _ignoreReturnKey = ignore; } void MasterDialog::keyPressEvent(QKeyEvent *keyEvent) { - if (_ignoreReturnKey && (keyEvent->key() == Qt::Key_Enter || - keyEvent->key() == Qt::Key_Return)) { + if (_ignoreReturnKey && + (keyEvent->key() == Qt::Key_Enter || keyEvent->key() == Qt::Key_Return)) { return; } diff --git a/src/dialogs/notedialog.cpp b/src/dialogs/notedialog.cpp index f86dd6e3a..36bbb6023 100644 --- a/src/dialogs/notedialog.cpp +++ b/src/dialogs/notedialog.cpp @@ -3,19 +3,17 @@ #include <entities/note.h> #include <entities/notefolder.h> +#include <QDebug> #include <QDesktopServices> #include <QSettings> -#include <QDebug> #include "ui_notedialog.h" -NoteDialog::NoteDialog(QWidget *parent) - : MasterDialog(parent), ui(new Ui::NoteDialog) { +NoteDialog::NoteDialog(QWidget *parent) : MasterDialog(parent), ui(new Ui::NoteDialog) { ui->setupUi(this); ui->textEdit->initSearchFrame(ui->searchFrame); ui->textEdit->setReadOnly(true); - ui->tabWidget->setCurrentIndex( - QSettings().value("NoteDialog/tabWidgetIndex").toInt()); + ui->tabWidget->setCurrentIndex(QSettings().value("NoteDialog/tabWidgetIndex").toInt()); // set the note text view font QFont font; @@ -41,12 +39,9 @@ void NoteDialog::on_noteTextView_anchorClicked(const QUrl &url) { qDebug() << __func__ << " - 'url': " << url; const QString scheme = url.scheme(); - if ((scheme == QStringLiteral("note") || - scheme == QStringLiteral("noteid") || - scheme == QStringLiteral("task") || - scheme == QStringLiteral("checkbox")) || - (scheme == QStringLiteral("file") && - Note::fileUrlIsNoteInCurrentNoteFolder(url))) { + if ((scheme == QStringLiteral("note") || scheme == QStringLiteral("noteid") || + scheme == QStringLiteral("task") || scheme == QStringLiteral("checkbox")) || + (scheme == QStringLiteral("file") && Note::fileUrlIsNoteInCurrentNoteFolder(url))) { return; } diff --git a/src/dialogs/notedialog.h b/src/dialogs/notedialog.h index 4f6a94cb9..7cabb8733 100644 --- a/src/dialogs/notedialog.h +++ b/src/dialogs/notedialog.h @@ -17,12 +17,12 @@ class NoteDialog : public MasterDialog { ~NoteDialog(); void setNote(Note ¬e); -private slots: + private slots: void on_noteTextView_anchorClicked(const QUrl &url); void on_tabWidget_currentChanged(int index); -private: + private: Ui::NoteDialog *ui; }; diff --git a/src/dialogs/notediffdialog.cpp b/src/dialogs/notediffdialog.cpp index a6c76967e..a574a6809 100644 --- a/src/dialogs/notediffdialog.cpp +++ b/src/dialogs/notediffdialog.cpp @@ -22,8 +22,8 @@ NoteDiffDialog::NoteDiffDialog(QWidget *parent, const QString &html) _notificationNoneCheckBox = new QCheckBox(this); _notificationNoneCheckBox->setHidden(true); _notificationButtonGroup->addButton(_notificationNoneCheckBox); - connect(_notificationButtonGroup, SIGNAL(buttonPressed(QAbstractButton *)), - this, SLOT(notificationButtonGroupPressed(QAbstractButton *))); + connect(_notificationButtonGroup, SIGNAL(buttonPressed(QAbstractButton *)), this, + SLOT(notificationButtonGroupPressed(QAbstractButton *))); this->ui->textEdit->setHtml(html); @@ -81,15 +81,13 @@ void NoteDiffDialog::dialogButtonClicked(QAbstractButton *button) { // set the setting to ignore all external changes if (ui->ignoreAllExternalChangesCheckBox->isChecked()) { QSettings settings; - settings.setValue(QStringLiteral("ignoreAllExternalModifications"), - true); + settings.setValue(QStringLiteral("ignoreAllExternalModifications"), true); } // set the setting to accept all external changes if (ui->acceptAllExternalChangesCheckBox->isChecked()) { QSettings settings; - settings.setValue(QStringLiteral("acceptAllExternalModifications"), - true); + settings.setValue(QStringLiteral("acceptAllExternalModifications"), true); } this->close(); diff --git a/src/dialogs/notediffdialog.h b/src/dialogs/notediffdialog.h index e84af2e8b..1cb921582 100644 --- a/src/dialogs/notediffdialog.h +++ b/src/dialogs/notediffdialog.h @@ -23,8 +23,7 @@ class NoteDiffDialog : public MasterDialog { Cancel }; - explicit NoteDiffDialog(QWidget *parent = nullptr, - const QString &html = QString()); + explicit NoteDiffDialog(QWidget *parent = nullptr, const QString &html = QString()); ~NoteDiffDialog(); int resultActionRole(); diff --git a/src/dialogs/passworddialog.cpp b/src/dialogs/passworddialog.cpp index fcd6b865d..8ab1ed230 100644 --- a/src/dialogs/passworddialog.cpp +++ b/src/dialogs/passworddialog.cpp @@ -4,16 +4,14 @@ #include "ui_passworddialog.h" -PasswordDialog::PasswordDialog(QWidget *parent, const QString &labelText, - bool doubleEnterPassword) +PasswordDialog::PasswordDialog(QWidget *parent, const QString &labelText, bool doubleEnterPassword) : MasterDialog(parent), ui(new Ui::PasswordDialog) { _doubleEnterPassword = doubleEnterPassword; ui->setupUi(this); ui->passwordLineEdit2->setVisible(doubleEnterPassword); - ui->buttonBox->button(QDialogButtonBox::Ok) - ->setEnabled(!doubleEnterPassword); + ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(!doubleEnterPassword); ui->errorLabel->setVisible(false); if (!labelText.isEmpty()) { @@ -44,8 +42,7 @@ void PasswordDialog::on_passwordLineEdit2_textChanged(const QString &arg1) { bool PasswordDialog::checkIfPasswordsAreEqual() { bool equal = ui->passwordLineEdit->text() == ui->passwordLineEdit2->text(); - ui->errorLabel->setVisible(!equal && - !ui->passwordLineEdit2->text().isEmpty()); + ui->errorLabel->setVisible(!equal && !ui->passwordLineEdit2->text().isEmpty()); ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(equal); return equal; diff --git a/src/dialogs/passworddialog.h b/src/dialogs/passworddialog.h index 4f84c7395..0ac127497 100644 --- a/src/dialogs/passworddialog.h +++ b/src/dialogs/passworddialog.h @@ -11,8 +11,7 @@ class PasswordDialog : public MasterDialog { Q_OBJECT public: - explicit PasswordDialog(QWidget *parent = nullptr, - const QString &labelText = QString(), + explicit PasswordDialog(QWidget *parent = nullptr, const QString &labelText = QString(), bool doubleEnterPassword = false); ~PasswordDialog(); QString password(); diff --git a/src/dialogs/scriptrepositorydialog.cpp b/src/dialogs/scriptrepositorydialog.cpp index a2094bd39..f5479e3a8 100644 --- a/src/dialogs/scriptrepositorydialog.cpp +++ b/src/dialogs/scriptrepositorydialog.cpp @@ -23,8 +23,7 @@ #include "ui_scriptrepositorydialog.h" -ScriptRepositoryDialog::ScriptRepositoryDialog(QWidget *parent, - bool checkForUpdates) +ScriptRepositoryDialog::ScriptRepositoryDialog(QWidget *parent, bool checkForUpdates) : MasterDialog(parent), ui(new Ui::ScriptRepositoryDialog) { ui->setupUi(this); setupMainSplitter(); @@ -53,8 +52,7 @@ ScriptRepositoryDialog::ScriptRepositoryDialog(QWidget *parent, ui->overviewLabel->setText(tr("All scripts are up-to-date.")); searchForUpdates(); } else { - QObject::connect(ui->scriptTreeWidget->verticalScrollBar(), - SIGNAL(valueChanged(int)), this, + QObject::connect(ui->scriptTreeWidget->verticalScrollBar(), SIGNAL(valueChanged(int)), this, SLOT(scriptTreeWidgetSliderValueChanged(int))); searchScript(); @@ -121,8 +119,7 @@ void ScriptRepositoryDialog::searchScript(int page) { _page = page; #if QT_VERSION < QT_VERSION_CHECK(5, 9, 0) - networkRequest.setAttribute(QNetworkRequest::FollowRedirectsAttribute, - true); + networkRequest.setAttribute(QNetworkRequest::FollowRedirectsAttribute, true); #else networkRequest.setAttribute(QNetworkRequest::RedirectPolicyAttribute, true); #endif @@ -155,16 +152,14 @@ void ScriptRepositoryDialog::searchForUpdates() { QNetworkRequest networkRequest(url); #if QT_VERSION < QT_VERSION_CHECK(5, 9, 0) - networkRequest.setAttribute(QNetworkRequest::FollowRedirectsAttribute, - true); + networkRequest.setAttribute(QNetworkRequest::FollowRedirectsAttribute, true); #else networkRequest.setAttribute(QNetworkRequest::RedirectPolicyAttribute, true); #endif #if (QT_VERSION < QT_VERSION_CHECK(5, 15, 0)) // try to ensure the network is accessible - _networkManager->setNetworkAccessible( - QNetworkAccessManager::Accessible); + _networkManager->setNetworkAccessible(QNetworkAccessManager::Accessible); #endif _networkManager->get(networkRequest); @@ -174,9 +169,7 @@ void ScriptRepositoryDialog::searchForUpdates() { /** * Does a script search */ -void ScriptRepositoryDialog::on_searchScriptEdit_returnPressed() { - searchScript(); -} +void ScriptRepositoryDialog::on_searchScriptEdit_returnPressed() { searchScript(); } /** * Handles all the network replies @@ -228,8 +221,7 @@ void ScriptRepositoryDialog::parseCodeSearchReply(const QByteArray &arr) { qDebug() << __func__ << " - 'path': " << path; QRegularExpressionMatch match = - QRegularExpression(QStringLiteral("(.+)\\/info\\.json")) - .match(path); + QRegularExpression(QStringLiteral("(.+)\\/info\\.json")).match(path); if (!match.hasMatch()) { continue; @@ -247,16 +239,14 @@ void ScriptRepositoryDialog::parseCodeSearchReply(const QByteArray &arr) { QNetworkRequest networkRequest(url); #if QT_VERSION < QT_VERSION_CHECK(5, 9, 0) - networkRequest.setAttribute(QNetworkRequest::FollowRedirectsAttribute, - true); + networkRequest.setAttribute(QNetworkRequest::FollowRedirectsAttribute, true); #else networkRequest.setAttribute(QNetworkRequest::RedirectPolicyAttribute, true); #endif #if (QT_VERSION < QT_VERSION_CHECK(5, 15, 0)) // try to ensure the network is accessible - _networkManager->setNetworkAccessible( - QNetworkAccessManager::Accessible); + _networkManager->setNetworkAccessible(QNetworkAccessManager::Accessible); #endif _networkManager->get(networkRequest); @@ -299,8 +289,7 @@ void ScriptRepositoryDialog::parseInfoQMLReply(const QByteArray &arr) { QString jsonData = QString(arr); // check if script item already exists in tree widget - if (Utils::Gui::userDataInTreeWidgetExists(ui->scriptTreeWidget, - jsonData)) { + if (Utils::Gui::userDataInTreeWidgetExists(ui->scriptTreeWidget, jsonData)) { return; } @@ -318,8 +307,7 @@ void ScriptRepositoryDialog::parseInfoQMLReply(const QByteArray &arr) { ui->scriptTreeWidget->resizeColumnToContents(0); if (_page == 1) { - ui->scriptTreeWidget->setCurrentItem( - ui->scriptTreeWidget->topLevelItem(0)); + ui->scriptTreeWidget->setCurrentItem(ui->scriptTreeWidget->topLevelItem(0)); } } @@ -335,9 +323,7 @@ void ScriptRepositoryDialog::setupMainSplitter() { // restore splitter sizes QSettings settings; QByteArray state = - settings - .value(QStringLiteral("ScriptRepositoryDialog/mainSplitterState")) - .toByteArray(); + settings.value(QStringLiteral("ScriptRepositoryDialog/mainSplitterState")).toByteArray(); _mainSplitter->restoreState(state); ui->gridLayout->layout()->addWidget(_mainSplitter); @@ -348,9 +334,8 @@ void ScriptRepositoryDialog::setupMainSplitter() { */ void ScriptRepositoryDialog::storeSettings() { QSettings settings; - settings.setValue( - QStringLiteral("ScriptRepositoryDialog/mainSplitterState"), - _mainSplitter->saveState()); + settings.setValue(QStringLiteral("ScriptRepositoryDialog/mainSplitterState"), + _mainSplitter->saveState()); } /** @@ -359,8 +344,8 @@ void ScriptRepositoryDialog::storeSettings() { * @param current * @param previous */ -void ScriptRepositoryDialog::on_scriptTreeWidget_currentItemChanged( - QTreeWidgetItem *current, QTreeWidgetItem *previous) { +void ScriptRepositoryDialog::on_scriptTreeWidget_currentItemChanged(QTreeWidgetItem *current, + QTreeWidgetItem *previous) { Q_UNUSED(current); Q_UNUSED(previous); @@ -387,21 +372,17 @@ void ScriptRepositoryDialog::reloadCurrentScriptInfo() { ui->versionLabel->setText(infoJson.version); ui->minAppVersionLabel->setText(infoJson.minAppVersion); ui->minAppVersionLabel->setHidden(infoJson.minAppVersion.isEmpty()); - ui->minAppVersionHeadlineLabel->setVisible( - ui->minAppVersionLabel->isVisible()); + ui->minAppVersionHeadlineLabel->setVisible(ui->minAppVersionLabel->isVisible()); ui->descriptionLabel->setText(infoJson.description); ui->authorLabel->setText(infoJson.richAuthorText); ui->authorHeadlineLabel->setText( - (infoJson.richAuthorList.count() > 1 ? tr("Authors") : tr("Author")) + - ":"); + (infoJson.richAuthorList.count() > 1 ? tr("Authors") : tr("Author")) + ":"); ui->platformLabel->setText(infoJson.richPlatformText); - ui->platformHeadlineLabel->setText((infoJson.platformList.count() > 1 - ? tr("Supported platforms") - : tr("Supported platform")) + - ":"); - ui->repositoryLinkLabel->setText( - "<a href=\"https://github.com/qownnotes/scripts/tree/master/" + - infoJson.identifier + "\">" + tr("Open repository") + "</a>"); + ui->platformHeadlineLabel->setText( + (infoJson.platformList.count() > 1 ? tr("Supported platforms") : tr("Supported platform")) + + ":"); + ui->repositoryLinkLabel->setText("<a href=\"https://github.com/qownnotes/scripts/tree/master/" + + infoJson.identifier + "\">" + tr("Open repository") + "</a>"); Script script = Script::fetchByIdentifier(infoJson.identifier); if (script.isFetched()) { @@ -435,8 +416,7 @@ void ScriptRepositoryDialog::reloadCurrentScriptInfo() { * @return */ QJsonObject ScriptRepositoryDialog::getCurrentInfoJsonObject() { - QJsonDocument jsonResponse = - QJsonDocument::fromJson(getCurrentInfoJsonString().toUtf8()); + QJsonDocument jsonResponse = QJsonDocument::fromJson(getCurrentInfoJsonString().toUtf8()); QJsonObject jsonObject = jsonResponse.object(); return jsonObject; @@ -468,8 +448,7 @@ void ScriptRepositoryDialog::on_installButton_clicked() { return; } - QString identifier = - jsonObject.value(QStringLiteral("identifier")).toString(); + QString identifier = jsonObject.value(QStringLiteral("identifier")).toString(); if (identifier.isEmpty()) { return; @@ -481,20 +460,18 @@ void ScriptRepositoryDialog::on_installButton_clicked() { // check if platform is supported if (!infoJson.platformSupported && - QMessageBox::information( - this, tr("Platform not supported!"), - tr("Your platform is not supported by this script!\n" - "Do you want to install it anyway?"), - tr("Install"), tr("Cancel"), QString(), 0, 1) != 0) { + QMessageBox::information(this, tr("Platform not supported!"), + tr("Your platform is not supported by this script!\n" + "Do you want to install it anyway?"), + tr("Install"), tr("Cancel"), QString(), 0, 1) != 0) { return; } // check if app version is supported if (!infoJson.appVersionSupported) { - QMessageBox::information( - this, tr("Update app"), - tr("Please don't forget to update your installation of " - "QOwnNotes to make this script work!")); + QMessageBox::information(this, tr("Update app"), + tr("Please don't forget to update your installation of " + "QOwnNotes to make this script work!")); } ui->installButton->setEnabled(false); @@ -537,8 +514,7 @@ void ScriptRepositoryDialog::on_installButton_clicked() { QUrl resourceUrl = script.remoteFileUrl(resourceFileName); qDebug() << "Downloading: " << resourceUrl; - auto *file = - new QFile(scriptRepositoryPath + "/" + resourceFileName); + auto *file = new QFile(scriptRepositoryPath + "/" + resourceFileName); if (!Utils::Misc::downloadUrlToFile(resourceUrl, file)) { filesWereDownloaded = false; @@ -556,8 +532,7 @@ void ScriptRepositoryDialog::on_installButton_clicked() { if (filesWereDownloaded) { script.store(); - MetricsService::instance()->sendVisitIfEnabled( - "script-repository/install/" + identifier); + MetricsService::instance()->sendVisitIfEnabled("script-repository/install/" + identifier); reloadCurrentScriptInfo(); _lastInstalledScript = script; @@ -574,18 +549,13 @@ void ScriptRepositoryDialog::on_installButton_clicked() { } } -void ScriptRepositoryDialog::on_searchScriptEdit_textChanged( - const QString &arg1) { +void ScriptRepositoryDialog::on_searchScriptEdit_textChanged(const QString &arg1) { // list all scripts again if the search bar was cleared if (!_checkForUpdates && arg1.isEmpty()) { searchScript(); } } -void ScriptRepositoryDialog::on_loadMoreScriptsButton_clicked() { - loadMoreItems(); -} +void ScriptRepositoryDialog::on_loadMoreScriptsButton_clicked() { loadMoreItems(); } -Script ScriptRepositoryDialog::getLastInstalledScript() { - return _lastInstalledScript; -} +Script ScriptRepositoryDialog::getLastInstalledScript() { return _lastInstalledScript; } diff --git a/src/dialogs/scriptrepositorydialog.h b/src/dialogs/scriptrepositorydialog.h index 21b454ba2..824337cdd 100644 --- a/src/dialogs/scriptrepositorydialog.h +++ b/src/dialogs/scriptrepositorydialog.h @@ -17,8 +17,7 @@ class ScriptRepositoryDialog : public MasterDialog { Q_OBJECT public: - explicit ScriptRepositoryDialog(QWidget *parent = nullptr, - bool checkForUpdates = false); + explicit ScriptRepositoryDialog(QWidget *parent = nullptr, bool checkForUpdates = false); ~ScriptRepositoryDialog(); Script getLastInstalledScript(); diff --git a/src/dialogs/serverbookmarksimportdialog.cpp b/src/dialogs/serverbookmarksimportdialog.cpp index b766d9615..07765c9ad 100644 --- a/src/dialogs/serverbookmarksimportdialog.cpp +++ b/src/dialogs/serverbookmarksimportdialog.cpp @@ -9,8 +9,7 @@ #include "services/websocketserverservice.h" #include "ui_serverbookmarksimportdialog.h" -ServerBookmarksImportDialog::ServerBookmarksImportDialog( - const QJSValue &bookmarks, QWidget *parent) +ServerBookmarksImportDialog::ServerBookmarksImportDialog(const QJSValue &bookmarks, QWidget *parent) : MasterDialog(parent), ui(new Ui::ServerBookmarksImportDialog) { ui->setupUi(this); ui->infoLabel->clear(); @@ -30,8 +29,7 @@ ServerBookmarksImportDialog::ServerBookmarksImportDialog( while (bookmarksIterator.hasNext()) { bookmarksIterator.next(); - QJSValue property = - bookmarksIterator.value().property(QStringLiteral("url")); + QJSValue property = bookmarksIterator.value().property(QStringLiteral("url")); if (property.isUndefined()) { continue; @@ -43,28 +41,20 @@ ServerBookmarksImportDialog::ServerBookmarksImportDialog( continue; } - title = bookmarksIterator.value() - .property(QStringLiteral("title")) - .toString(); + title = bookmarksIterator.value().property(QStringLiteral("title")).toString(); description = bookmarksIterator.value() .property(QStringLiteral("description")) .toString() .remove(QStringLiteral("#")); - tags = bookmarksIterator.value() - .property(QStringLiteral("tags")) - .toVariant() - .toStringList(); + tags = + bookmarksIterator.value().property(QStringLiteral("tags")).toVariant().toStringList(); Q_FOREACH (QString tag, tags) { - description.prepend( - "#" + tag.replace(QLatin1String(" "), QLatin1String("-")) + - " "); + description.prepend("#" + tag.replace(QLatin1String(" "), QLatin1String("-")) + " "); } #if (QT_VERSION >= QT_VERSION_CHECK(5, 4, 0)) - QJsonObject data{{"name", title}, - {"url", url}, - {"description", description.trimmed()}}; + QJsonObject data{{"name", title}, {"url", url}, {"description", description.trimmed()}}; #else QJsonObject data; data.insert("name", title); @@ -85,8 +75,7 @@ ServerBookmarksImportDialog::ServerBookmarksImportDialog( #endif ui->progressBar->setMaximum(bookmarksCount); - ui->infoLabel->setText(tr("<strong>%n bookmarks</strong> found on server", - "", bookmarksCount)); + ui->infoLabel->setText(tr("<strong>%n bookmarks</strong> found on server", "", bookmarksCount)); ui->importButton->setEnabled(bookmarksCount > 0); ui->progressBar->setEnabled(bookmarksCount > 0); } @@ -94,7 +83,6 @@ ServerBookmarksImportDialog::ServerBookmarksImportDialog( ServerBookmarksImportDialog::~ServerBookmarksImportDialog() { delete ui; } void ServerBookmarksImportDialog::on_importButton_clicked() { - QJsonArray bookmarkList = - WebSocketServerService::createBookmarks(jsonObject); + QJsonArray bookmarkList = WebSocketServerService::createBookmarks(jsonObject); ui->progressBar->setValue(bookmarkList.count()); } diff --git a/src/dialogs/serverbookmarksimportdialog.h b/src/dialogs/serverbookmarksimportdialog.h index 05f194031..a0d0b0b66 100644 --- a/src/dialogs/serverbookmarksimportdialog.h +++ b/src/dialogs/serverbookmarksimportdialog.h @@ -14,8 +14,7 @@ class ServerBookmarksImportDialog : public MasterDialog { Q_OBJECT public: - explicit ServerBookmarksImportDialog(const QJSValue &bookmarks, - QWidget *parent = 0); + explicit ServerBookmarksImportDialog(const QJSValue &bookmarks, QWidget *parent = 0); ~ServerBookmarksImportDialog(); private slots: diff --git a/src/dialogs/settingsdialog.cpp b/src/dialogs/settingsdialog.cpp index fff8a25f3..6e3205b8c 100644 --- a/src/dialogs/settingsdialog.cpp +++ b/src/dialogs/settingsdialog.cpp @@ -10,8 +10,8 @@ #include <services/cryptoservice.h> #include <services/metricsservice.h> #include <services/scriptingservice.h> -#include <services/websocketserverservice.h> #include <services/webappclientservice.h> +#include <services/websocketserverservice.h> #include <utils/gui.h> #include <utils/misc.h> #include <widgets/scriptsettingwidget.h> @@ -25,10 +25,12 @@ #include <QFontDatabase> #include <QFontDialog> #include <QInputDialog> +#include <QJsonDocument> #include <QKeySequence> #include <QKeySequenceEdit> #include <QMenu> #include <QMessageBox> +#include <QPointer> #include <QRegularExpression> #include <QRegularExpressionMatch> #include <QSettings> @@ -36,11 +38,9 @@ #include <QStatusBar> #include <QStyleFactory> #include <QTextBrowser> -#include <QToolBar> #include <QTimer> -#include <QJsonDocument> +#include <QToolBar> #include <utility> -#include <QPointer> #include "build_number.h" #include "dialogs/websockettokendialog.h" @@ -60,8 +60,7 @@ SettingsDialog::SettingsDialog(int page, QWidget *parent) : MasterDialog(parent), ui(new Ui::SettingsDialog) { ui->setupUi(this); - bool fromWelcomeDialog = - parent->objectName() == QLatin1String("WelcomeDialog"); + bool fromWelcomeDialog = parent->objectName() == QLatin1String("WelcomeDialog"); MainWindow *mainWindow = MainWindow::instance(); @@ -100,8 +99,7 @@ SettingsDialog::SettingsDialog(int page, QWidget *parent) ui->connectionTestLabel->hide(); ui->darkModeInfoLabel->hide(); ui->connectButton->setDefault(true); - ui->noteSaveIntervalTime->setToolTip( - ui->noteSaveIntervalTimeLabel->toolTip()); + ui->noteSaveIntervalTime->setToolTip(ui->noteSaveIntervalTimeLabel->toolTip()); ui->removeCustomNoteFileExtensionButton->setDisabled(true); ui->calDavCalendarGroupBox->hide(); _newScriptName = tr("New script"); @@ -118,27 +116,22 @@ SettingsDialog::SettingsDialog(int page, QWidget *parent) #endif _noteNotificationButtonGroup = new QButtonGroup(this); - _noteNotificationButtonGroup->addButton( - ui->notifyAllExternalModificationsCheckBox); - _noteNotificationButtonGroup->addButton( - ui->ignoreAllExternalModificationsCheckBox); - _noteNotificationButtonGroup->addButton( - ui->acceptAllExternalModificationsCheckBox); + _noteNotificationButtonGroup->addButton(ui->notifyAllExternalModificationsCheckBox); + _noteNotificationButtonGroup->addButton(ui->ignoreAllExternalModificationsCheckBox); + _noteNotificationButtonGroup->addButton(ui->acceptAllExternalModificationsCheckBox); // create a hidden checkbox so we can un-check above checkboxes _noteNotificationNoneCheckBox = new QCheckBox(this); _noteNotificationNoneCheckBox->setHidden(true); _noteNotificationButtonGroup->addButton(_noteNotificationNoneCheckBox); - connect(_noteNotificationButtonGroup, - SIGNAL(buttonPressed(QAbstractButton *)), this, + connect(_noteNotificationButtonGroup, SIGNAL(buttonPressed(QAbstractButton *)), this, SLOT(noteNotificationButtonGroupPressed(QAbstractButton *))); resetOKLabelData(); // add the QOwnNotesAPI minimum version number to the info text QString html = ui->installInfoTextLabel1->text(); - html.replace(QLatin1String("QOWNNOTESAPI_MIN_VERSION"), - QOWNNOTESAPI_MIN_VERSION); + html.replace(QLatin1String("QOWNNOTESAPI_MIN_VERSION"), QOWNNOTESAPI_MIN_VERSION); ui->installInfoTextLabel1->setText(html); // do the network proxy tab setup @@ -199,13 +192,11 @@ SettingsDialog::SettingsDialog(int page, QWidget *parent) ui->toolbarEditor->setTargetWindow(MainWindow::instance()); ui->toolbarEditor->setCustomToolbarRemovalOnly(true); - QStringList disabledToolbarNames(QStringList() - << QStringLiteral("windowToolbar") - << QStringLiteral("customActionsToolbar")); + QStringList disabledToolbarNames(QStringList() << QStringLiteral("windowToolbar") + << QStringLiteral("customActionsToolbar")); ui->toolbarEditor->setDisabledToolbarNames(disabledToolbarNames); - QStringList disabledMenuNames(QStringList() - << QStringLiteral("noteFoldersMenu")); + QStringList disabledMenuNames(QStringList() << QStringLiteral("noteFoldersMenu")); ui->toolbarEditor->setDisabledMenuNames(disabledMenuNames); // QStringList disabledMenuActionNames(QStringList() << ""); @@ -214,74 +205,52 @@ SettingsDialog::SettingsDialog(int page, QWidget *parent) ui->toolbarEditor->updateBars(); // show the log file path - ui->logFileLabel->setText( - QDir::toNativeSeparators(Utils::Misc::logFilePath())); + ui->logFileLabel->setText(QDir::toNativeSeparators(Utils::Misc::logFilePath())); // replace the "ownCloud" text by "ownCloud / NextCloud" replaceOwnCloudText(); // declare that we need to restart the application if certain settings // are changed - connect(ui->languageListWidget, SIGNAL(itemSelectionChanged()), this, + connect(ui->languageListWidget, SIGNAL(itemSelectionChanged()), this, SLOT(needRestart())); + connect(ui->internalIconThemeCheckBox, SIGNAL(toggled(bool)), this, SLOT(needRestart())); + connect(ui->systemIconThemeCheckBox, SIGNAL(toggled(bool)), this, SLOT(needRestart())); + connect(ui->darkModeTrayIconCheckBox, SIGNAL(toggled(bool)), this, SLOT(needRestart())); + connect(ui->darkModeIconThemeCheckBox, SIGNAL(toggled(bool)), this, SLOT(needRestart())); + connect(ui->darkModeColorsCheckBox, SIGNAL(toggled(bool)), this, SLOT(needRestart())); + connect(ui->darkModeCheckBox, SIGNAL(toggled(bool)), this, SLOT(needRestart())); + connect(ui->allowOnlyOneAppInstanceCheckBox, SIGNAL(toggled(bool)), this, SLOT(needRestart())); + connect(ui->showSystemTrayCheckBox, SIGNAL(toggled(bool)), this, SLOT(needRestart())); + connect(ui->startHiddenCheckBox, SIGNAL(toggled(bool)), this, SLOT(needRestart())); + connect(ui->fullyHighlightedBlockquotesCheckBox, SIGNAL(toggled(bool)), this, SLOT(needRestart())); - connect(ui->internalIconThemeCheckBox, SIGNAL(toggled(bool)), this, - SLOT(needRestart())); - connect(ui->systemIconThemeCheckBox, SIGNAL(toggled(bool)), this, - SLOT(needRestart())); - connect(ui->darkModeTrayIconCheckBox, SIGNAL(toggled(bool)), this, - SLOT(needRestart())); - connect(ui->darkModeIconThemeCheckBox, SIGNAL(toggled(bool)), this, - SLOT(needRestart())); - connect(ui->darkModeColorsCheckBox, SIGNAL(toggled(bool)), this, - SLOT(needRestart())); - connect(ui->darkModeCheckBox, SIGNAL(toggled(bool)), this, - SLOT(needRestart())); - connect(ui->allowOnlyOneAppInstanceCheckBox, SIGNAL(toggled(bool)), this, - SLOT(needRestart())); - connect(ui->showSystemTrayCheckBox, SIGNAL(toggled(bool)), this, - SLOT(needRestart())); - connect(ui->startHiddenCheckBox, SIGNAL(toggled(bool)), this, - SLOT(needRestart())); - connect(ui->fullyHighlightedBlockquotesCheckBox, SIGNAL(toggled(bool)), - this, SLOT(needRestart())); - connect(ui->noteEditCentralWidgetCheckBox, SIGNAL(toggled(bool)), this, - SLOT(needRestart())); - connect(ui->noteFolderButtonsCheckBox, SIGNAL(toggled(bool)), this, - SLOT(needRestart())); - connect(ui->noteListPreviewCheckBox, SIGNAL(toggled(bool)), this, - SLOT(needRestart())); - connect(ui->vimModeCheckBox, SIGNAL(toggled(bool)), this, - SLOT(needRestart())); - connect(ui->disableCursorBlinkingCheckBox, SIGNAL(toggled(bool)), this, - SLOT(needRestart())); - connect(ui->ignoreNoteSubFoldersLineEdit, SIGNAL(textChanged(QString)), - this, SLOT(needRestart())); - connect(ui->enableSocketServerCheckBox, SIGNAL(toggled(bool)), this, - SLOT(needRestart())); - connect(ui->enableWebApplicationCheckBox, SIGNAL(toggled(bool)), this, - SLOT(needRestart())); - connect(ui->webAppServerUrlLineEdit, SIGNAL(textChanged(QString)), this, - SLOT(needRestart())); - connect(ui->webAppTokenLineEdit, SIGNAL(textChanged(QString)), this, + connect(ui->noteEditCentralWidgetCheckBox, SIGNAL(toggled(bool)), this, SLOT(needRestart())); + connect(ui->noteFolderButtonsCheckBox, SIGNAL(toggled(bool)), this, SLOT(needRestart())); + connect(ui->noteListPreviewCheckBox, SIGNAL(toggled(bool)), this, SLOT(needRestart())); + connect(ui->vimModeCheckBox, SIGNAL(toggled(bool)), this, SLOT(needRestart())); + connect(ui->disableCursorBlinkingCheckBox, SIGNAL(toggled(bool)), this, SLOT(needRestart())); + connect(ui->ignoreNoteSubFoldersLineEdit, SIGNAL(textChanged(QString)), this, SLOT(needRestart())); + connect(ui->enableSocketServerCheckBox, SIGNAL(toggled(bool)), this, SLOT(needRestart())); + connect(ui->enableWebApplicationCheckBox, SIGNAL(toggled(bool)), this, SLOT(needRestart())); + connect(ui->webAppServerUrlLineEdit, SIGNAL(textChanged(QString)), this, SLOT(needRestart())); + connect(ui->webAppTokenLineEdit, SIGNAL(textChanged(QString)), this, SLOT(needRestart())); // connect(ui->layoutWidget, SIGNAL(settingsStored()), // this, SLOT(needRestart())); // connect the panel sort radio buttons connect(ui->notesPanelSortAlphabeticalRadioButton, SIGNAL(toggled(bool)), ui->notesPanelOrderGroupBox, SLOT(setEnabled(bool))); - connect(ui->noteSubfoldersPanelShowRootFolderNameCheckBox, - SIGNAL(toggled(bool)), ui->noteSubfoldersPanelShowFullPathCheckBox, - SLOT(setEnabled(bool))); - connect(ui->noteSubfoldersPanelSortAlphabeticalRadioButton, - SIGNAL(toggled(bool)), ui->noteSubfoldersPanelOrderGroupBox, - SLOT(setEnabled(bool))); + connect(ui->noteSubfoldersPanelShowRootFolderNameCheckBox, SIGNAL(toggled(bool)), + ui->noteSubfoldersPanelShowFullPathCheckBox, SLOT(setEnabled(bool))); + connect(ui->noteSubfoldersPanelSortAlphabeticalRadioButton, SIGNAL(toggled(bool)), + ui->noteSubfoldersPanelOrderGroupBox, SLOT(setEnabled(bool))); connect(ui->tagsPanelSortAlphabeticalRadioButton, SIGNAL(toggled(bool)), ui->tagsPanelOrderGroupBox, SLOT(setEnabled(bool))); // handle cloud connection storing - connect(ui->cloudServerConnectionNameLineEdit, SIGNAL(textChanged(QString)), - this, SLOT(storeSelectedCloudConnection())); + connect(ui->cloudServerConnectionNameLineEdit, SIGNAL(textChanged(QString)), this, + SLOT(storeSelectedCloudConnection())); connect(ui->serverUrlEdit, SIGNAL(textChanged(QString)), this, SLOT(storeSelectedCloudConnection())); connect(ui->userNameEdit, SIGNAL(textChanged(QString)), this, @@ -305,14 +274,12 @@ SettingsDialog::SettingsDialog(int page, QWidget *parent) ui->leftSideFrame->setVisible(false); } - if (!ui->noteListPreviewCheckBox->text().contains( - QLatin1String("(experimental)"))) { - ui->noteListPreviewCheckBox->setText( - ui->noteListPreviewCheckBox->text() + " (experimental)"); + if (!ui->noteListPreviewCheckBox->text().contains(QLatin1String("(experimental)"))) { + ui->noteListPreviewCheckBox->setText(ui->noteListPreviewCheckBox->text() + + " (experimental)"); } - if (!ui->enableNoteTreeCheckBox->text().contains( - QLatin1String("work in progress"))) { + if (!ui->enableNoteTreeCheckBox->text().contains(QLatin1String("work in progress"))) { ui->enableNoteTreeCheckBox->setText(ui->enableNoteTreeCheckBox->text() + " (work in progress)"); } @@ -322,14 +289,13 @@ SettingsDialog::SettingsDialog(int page, QWidget *parent) "https://chrome.google.com/webstore/detail/qownnotes-web-companion/" "pkgkfnampapjbopomdpnkckbjdnpkbkp", "https://addons.mozilla.org/firefox/addon/qownnotes-web-companion")); - ui->webAppLabel->setText(ui->webAppLabel->text().arg( - "https://app.qownnotes.org/")); + ui->webAppLabel->setText(ui->webAppLabel->text().arg("https://app.qownnotes.org/")); ui->bookmarkTagLabel->setText(ui->bookmarkTagLabel->text().arg( "https://www.qownnotes.org/getting-started/browser-extension.html")); ui->helpTranslateLabel->setText(ui->helpTranslateLabel->text().arg( "https://www.qownnotes.org/contributing/translation.html")); - ui->commandLineSnippetManagerLabel->setText(ui->commandLineSnippetManagerLabel->text().arg( - "https://github.com/qownnotes/qc")); + ui->commandLineSnippetManagerLabel->setText( + ui->commandLineSnippetManagerLabel->text().arg("https://github.com/qownnotes/qc")); ui->commandSnippetTagLabel->setText(ui->commandSnippetTagLabel->text().arg( "https://www.qownnotes.org/getting-started/command-line-snippet-manager.html")); ui->commandSnippetsNoteNameLabel->hide(); @@ -353,8 +319,7 @@ void SettingsDialog::resetOKLabelData() { * @return */ bool SettingsDialog::connectionTestCanBeStarted() const { - return ui->ownCloudSupportCheckBox->isChecked() && - !ui->serverUrlEdit->text().isEmpty(); + return ui->ownCloudSupportCheckBox->isChecked() && !ui->serverUrlEdit->text().isEmpty(); } /** @@ -372,58 +337,47 @@ void SettingsDialog::replaceOwnCloudText() const { Utils::Misc::replaceOwnCloudText(ui->userNameEdit->placeholderText())); ui->passwordEdit->setPlaceholderText( Utils::Misc::replaceOwnCloudText(ui->passwordEdit->placeholderText())); - ui->ownCloudGroupBox->setTitle( - Utils::Misc::replaceOwnCloudText(ui->ownCloudGroupBox->title())); - ui->ownCloudServerUrlLabel->setText(Utils::Misc::replaceOwnCloudText( - ui->ownCloudServerUrlLabel->text(), true)); - ui->check2Label->setText( - Utils::Misc::replaceOwnCloudText(ui->check2Label->text())); - ui->ownCloudServerAppPageButton->setText(Utils::Misc::replaceOwnCloudText( - ui->ownCloudServerAppPageButton->text(), true)); + ui->ownCloudGroupBox->setTitle(Utils::Misc::replaceOwnCloudText(ui->ownCloudGroupBox->title())); + ui->ownCloudServerUrlLabel->setText( + Utils::Misc::replaceOwnCloudText(ui->ownCloudServerUrlLabel->text(), true)); + ui->check2Label->setText(Utils::Misc::replaceOwnCloudText(ui->check2Label->text())); + ui->ownCloudServerAppPageButton->setText( + Utils::Misc::replaceOwnCloudText(ui->ownCloudServerAppPageButton->text(), true)); ui->ownCloudServerAppPageButton->setToolTip( - Utils::Misc::replaceOwnCloudText( - ui->ownCloudServerAppPageButton->toolTip())); + Utils::Misc::replaceOwnCloudText(ui->ownCloudServerAppPageButton->toolTip())); ui->ownCloudServerAppPasswordPageButton->setText( - Utils::Misc::replaceOwnCloudText( - ui->ownCloudServerAppPasswordPageButton->text(), true)); + Utils::Misc::replaceOwnCloudText(ui->ownCloudServerAppPasswordPageButton->text(), true)); ui->ownCloudServerAppPasswordPageButton->setToolTip( - Utils::Misc::replaceOwnCloudText( - ui->ownCloudServerAppPasswordPageButton->toolTip())); - ui->connectButton->setText( - Utils::Misc::replaceOwnCloudText(ui->connectButton->text(), true)); - ui->connectButton->setToolTip( - Utils::Misc::replaceOwnCloudText(ui->connectButton->toolTip())); + Utils::Misc::replaceOwnCloudText(ui->ownCloudServerAppPasswordPageButton->toolTip())); + ui->connectButton->setText(Utils::Misc::replaceOwnCloudText(ui->connectButton->text(), true)); + ui->connectButton->setToolTip(Utils::Misc::replaceOwnCloudText(ui->connectButton->toolTip())); ui->installInfoTextLabel1->setText( Utils::Misc::replaceOwnCloudText(ui->installInfoTextLabel1->text())); ui->installInfoTextLabel2->setText( Utils::Misc::replaceOwnCloudText(ui->installInfoTextLabel2->text())); ui->installInfoTextLabel3->setText( Utils::Misc::replaceOwnCloudText(ui->installInfoTextLabel3->text())); - ui->cloudInfoLabel->setText( - Utils::Misc::replaceOwnCloudText(ui->cloudInfoLabel->text())); - ui->todoInfoLabel->setText( - Utils::Misc::replaceOwnCloudText(ui->todoInfoLabel->text())); + ui->cloudInfoLabel->setText(Utils::Misc::replaceOwnCloudText(ui->cloudInfoLabel->text())); + ui->todoInfoLabel->setText(Utils::Misc::replaceOwnCloudText(ui->todoInfoLabel->text())); QTreeWidgetItem *item = ui->settingsTreeWidget->topLevelItem(OwnCloudPage); item->setText(0, Utils::Misc::replaceOwnCloudText(item->text(0))); // note folder settings - ui->noteFolderRemotePathLabel->setText(Utils::Misc::replaceOwnCloudText( - ui->noteFolderRemotePathLabel->text())); - ui->noteFolderRemotePathListLabel->setText(Utils::Misc::replaceOwnCloudText( - ui->noteFolderRemotePathListLabel->text())); + ui->noteFolderRemotePathLabel->setText( + Utils::Misc::replaceOwnCloudText(ui->noteFolderRemotePathLabel->text())); + ui->noteFolderRemotePathListLabel->setText( + Utils::Misc::replaceOwnCloudText(ui->noteFolderRemotePathListLabel->text())); ui->useOwnCloudPathButton->setText( Utils::Misc::replaceOwnCloudText(ui->useOwnCloudPathButton->text())); - ui->noteFolderRemotePathButton->setToolTip(Utils::Misc::replaceOwnCloudText( - ui->noteFolderRemotePathButton->toolTip())); + ui->noteFolderRemotePathButton->setToolTip( + Utils::Misc::replaceOwnCloudText(ui->noteFolderRemotePathButton->toolTip())); ui->noteFolderRemotePathLineEdit->setToolTip( - Utils::Misc::replaceOwnCloudText( - ui->noteFolderRemotePathLineEdit->toolTip())); + Utils::Misc::replaceOwnCloudText(ui->noteFolderRemotePathLineEdit->toolTip())); // task settings ui->defaultOwnCloudCalendarRadioButton->setText( - Utils::Misc::replaceOwnCloudText( - ui->defaultOwnCloudCalendarRadioButton->text())); + Utils::Misc::replaceOwnCloudText(ui->defaultOwnCloudCalendarRadioButton->text())); } /** @@ -432,11 +386,9 @@ void SettingsDialog::replaceOwnCloudText() const { * * @param button */ -void SettingsDialog::noteNotificationButtonGroupPressed( - QAbstractButton *button) { +void SettingsDialog::noteNotificationButtonGroupPressed(QAbstractButton *button) { if (button->isChecked()) { - QTimer::singleShot(100, this, - SLOT(noteNotificationNoneCheckBoxCheck())); + QTimer::singleShot(100, this, SLOT(noteNotificationNoneCheckBoxCheck())); } } @@ -470,15 +422,14 @@ void SettingsDialog::initPortableModePage() { bool isInPortableMode = Utils::Misc::isInPortableMode(); QString status = isInPortableMode ? tr("enabled") : tr("disabled"); - QString text = "<p>" + tr("Portable mode is currently:") + " <strong>" + - status + "</strong></p>"; + QString text = + "<p>" + tr("Portable mode is currently:") + " <strong>" + status + "</strong></p>"; text += tr("In portable mode") + ":<ul><li>" + tr("the internal sqlite database and the settings will be stored " "inside a <code>Data</code> folder at the binary's " "location") + - "</li><li>" + tr("the settings will be stored in an ini file") + - "</li><li>" + + "</li><li>" + tr("the settings will be stored in an ini file") + "</li><li>" + tr("the note folders, script paths and path to an external editor " "will be automatically stored relative to the " "<code>Data</code> folder so that the correct note " @@ -503,8 +454,7 @@ void SettingsDialog::initPortableModePage() { } // inject some generic CSS styles - ui->portableModeInfoTextBrowser->document()->setDefaultStyleSheet( - Utils::Misc::genericCSS()); + ui->portableModeInfoTextBrowser->document()->setDefaultStyleSheet(Utils::Misc::genericCSS()); ui->portableModeInfoTextBrowser->setHtml(text); } @@ -530,8 +480,8 @@ void SettingsDialog::setupProxyPage() { connect(ui->authRequiredcheckBox, SIGNAL(toggled(bool)), ui->authWidgets, SLOT(setEnabled(bool))); - connect(ui->manualProxyRadioButton, SIGNAL(toggled(bool)), - ui->manualSettings, SLOT(setEnabled(bool))); + connect(ui->manualProxyRadioButton, SIGNAL(toggled(bool)), ui->manualSettings, + SLOT(setEnabled(bool))); connect(ui->manualProxyRadioButton, SIGNAL(toggled(bool)), ui->typeComboBox, SLOT(setEnabled(bool))); @@ -559,10 +509,8 @@ void SettingsDialog::loadProxySettings() { QSettings settings; // load current proxy settings - int type = settings - .value(QStringLiteral("networking/proxyType"), - QNetworkProxy::NoProxy) - .toInt(); + int type = + settings.value(QStringLiteral("networking/proxyType"), QNetworkProxy::NoProxy).toInt(); switch (type) { case QNetworkProxy::NoProxy: ui->noProxyRadioButton->setChecked(true); @@ -581,12 +529,10 @@ void SettingsDialog::loadProxySettings() { ui->hostLineEdit->setText( settings.value(QStringLiteral("networking/proxyHostName")).toString()); - ui->portSpinBox->setValue( - settings.value(QStringLiteral("networking/proxyPort"), 8080).toInt()); + ui->portSpinBox->setValue(settings.value(QStringLiteral("networking/proxyPort"), 8080).toInt()); ui->authRequiredcheckBox->setChecked( settings.value(QStringLiteral("networking/proxyNeedsAuth")).toBool()); - ui->userLineEdit->setText( - settings.value(QStringLiteral("networking/proxyUser")).toString()); + ui->userLineEdit->setText(settings.value(QStringLiteral("networking/proxyUser")).toString()); ui->passwordLineEdit->setText(CryptoService::instance()->decryptToString( settings.value(QStringLiteral("networking/proxyPassword")).toString())); } @@ -603,20 +549,15 @@ void SettingsDialog::storeProxySettings() { } else if (ui->systemProxyRadioButton->isChecked()) { proxyType = QNetworkProxy::DefaultProxy; } else if (ui->manualProxyRadioButton->isChecked()) { - proxyType = ui->typeComboBox->itemData(ui->typeComboBox->currentIndex()) - .toInt(); + proxyType = ui->typeComboBox->itemData(ui->typeComboBox->currentIndex()).toInt(); settings.setValue(QStringLiteral("networking/proxyNeedsAuth"), ui->authRequiredcheckBox->isChecked()); - settings.setValue(QStringLiteral("networking/proxyUser"), - ui->userLineEdit->text()); + settings.setValue(QStringLiteral("networking/proxyUser"), ui->userLineEdit->text()); settings.setValue(QStringLiteral("networking/proxyPassword"), - CryptoService::instance()->encryptToString( - ui->passwordLineEdit->text())); - settings.setValue(QStringLiteral("networking/proxyHostName"), - ui->hostLineEdit->text()); - settings.setValue(QStringLiteral("networking/proxyPort"), - ui->portSpinBox->value()); + CryptoService::instance()->encryptToString(ui->passwordLineEdit->text())); + settings.setValue(QStringLiteral("networking/proxyHostName"), ui->hostLineEdit->text()); + settings.setValue(QStringLiteral("networking/proxyPort"), ui->portSpinBox->value()); } settings.setValue(QStringLiteral("networking/proxyType"), proxyType); @@ -632,11 +573,10 @@ void SettingsDialog::storeProxySettings() { */ void SettingsDialog::startConnectionTest() { ui->connectionTestLabel->hide(); - OwnCloudService *ownCloud = - OwnCloudService::instance(true, _selectedCloudConnection.getId()); + OwnCloudService *ownCloud = OwnCloudService::instance(true, _selectedCloudConnection.getId()); ownCloud->settingsConnectionTest(this); - ui->check8Label->setText(tr("notes path <b>%1</b> found on server") - .arg(NoteFolder::currentRemotePath(false))); + ui->check8Label->setText( + tr("notes path <b>%1</b> found on server").arg(NoteFolder::currentRemotePath(false))); } /** @@ -662,19 +602,16 @@ void SettingsDialog::storeSelectedCloudConnection() { // store previously selected cloud connection if (_selectedCloudConnection.isFetched()) { // TODO: update combobox if name changed - if (_selectedCloudConnection.getName() != - ui->cloudServerConnectionNameLineEdit->text()) { + if (_selectedCloudConnection.getName() != ui->cloudServerConnectionNameLineEdit->text()) { updateComboBox = true; } } - _selectedCloudConnection.setName( - ui->cloudServerConnectionNameLineEdit->text()); + _selectedCloudConnection.setName(ui->cloudServerConnectionNameLineEdit->text()); _selectedCloudConnection.setServerUrl(url); _selectedCloudConnection.setUsername(ui->userNameEdit->text()); _selectedCloudConnection.setPassword(ui->passwordEdit->text()); - _selectedCloudConnection.setAppQOwnNotesAPIEnabled( - ui->appQOwnNotesAPICheckBox->isChecked()); + _selectedCloudConnection.setAppQOwnNotesAPIEnabled(ui->appQOwnNotesAPICheckBox->isChecked()); _selectedCloudConnection.store(); if (updateComboBox) { @@ -690,8 +627,7 @@ void SettingsDialog::storeSettings() { ui->ownCloudSupportCheckBox->isChecked()); settings.setValue(QStringLiteral("todoCalendarSupport"), ui->todoCalendarSupportCheckBox->isChecked()); - settings.setValue(QStringLiteral("insertTimeFormat"), - ui->timeFormatLineEdit->text()); + settings.setValue(QStringLiteral("insertTimeFormat"), ui->timeFormatLineEdit->text()); settings.setValue(QStringLiteral("disableAutomaticUpdateDialog"), ui->disableAutomaticUpdateDialogCheckBox->isChecked()); settings.setValue(QStringLiteral("notifyAllExternalModifications"), @@ -700,22 +636,18 @@ void SettingsDialog::storeSettings() { ui->ignoreAllExternalModificationsCheckBox->isChecked()); settings.setValue(QStringLiteral("acceptAllExternalModifications"), ui->acceptAllExternalModificationsCheckBox->isChecked()); - settings.setValue( - QStringLiteral("ignoreAllExternalNoteFolderChanges"), - ui->ignoreAllExternalNoteFolderChangesCheckBox->isChecked()); + settings.setValue(QStringLiteral("ignoreAllExternalNoteFolderChanges"), + ui->ignoreAllExternalNoteFolderChangesCheckBox->isChecked()); settings.setValue(QStringLiteral("newNoteAskHeadline"), ui->newNoteAskHeadlineCheckBox->isChecked()); - settings.setValue(QStringLiteral("useUNIXNewline"), - ui->useUNIXNewlineCheckBox->isChecked()); + settings.setValue(QStringLiteral("useUNIXNewline"), ui->useUNIXNewlineCheckBox->isChecked()); settings.setValue(QStringLiteral("restoreCursorPosition"), ui->restoreCursorPositionCheckBox->isChecked()); settings.setValue(QStringLiteral("restoreLastNoteAtStartup"), ui->restoreLastNoteAtStartupCheckBox->isChecked()); - settings.setValue(QStringLiteral("noteSaveIntervalTime"), - ui->noteSaveIntervalTime->value()); - settings.setValue( - QStringLiteral("defaultNoteFileExtension"), - ui->defaultNoteFileExtensionListWidget->currentItem()->text()); + settings.setValue(QStringLiteral("noteSaveIntervalTime"), ui->noteSaveIntervalTime->value()); + settings.setValue(QStringLiteral("defaultNoteFileExtension"), + ui->defaultNoteFileExtensionListWidget->currentItem()->text()); settings.setValue(QStringLiteral("localTrash/supportEnabled"), ui->localTrashEnabledCheckBox->isChecked()); settings.setValue(QStringLiteral("localTrash/autoCleanupEnabled"), @@ -735,10 +667,8 @@ void SettingsDialog::storeSettings() { settings.setValue(QStringLiteral("overrideInterfaceFontSize"), ui->overrideInterfaceFontSizeGroupBox->isChecked()); - settings.setValue(QStringLiteral("interfaceFontSize"), - ui->interfaceFontSizeSpinBox->value()); - settings.setValue(QStringLiteral("itemHeight"), - ui->itemHeightSpinBox->value()); + settings.setValue(QStringLiteral("interfaceFontSize"), ui->interfaceFontSizeSpinBox->value()); + settings.setValue(QStringLiteral("itemHeight"), ui->itemHeightSpinBox->value()); settings.setValue(QStringLiteral("MainWindow/mainToolBar.iconSize"), ui->toolbarIconSizeSpinBox->value()); settings.setValue(QStringLiteral("allowOnlyOneAppInstance"), @@ -753,29 +683,24 @@ void SettingsDialog::storeSettings() { ui->fullyHighlightedBlockquotesCheckBox->isChecked()); settings.setValue(QStringLiteral("noteEditIsCentralWidget"), ui->noteEditCentralWidgetCheckBox->isChecked()); - settings.setValue(QStringLiteral("restoreNoteTabs"), - ui->restoreNoteTabsCheckBox->isChecked()); + settings.setValue(QStringLiteral("restoreNoteTabs"), ui->restoreNoteTabsCheckBox->isChecked()); settings.setValue(QStringLiteral("useNoteFolderButtons"), ui->noteFolderButtonsCheckBox->isChecked()); settings.setValue(QStringLiteral("MainWindow/noteTextView.rtl"), ui->noteTextViewRTLCheckBox->isChecked()); - settings.setValue( - QStringLiteral("MainWindow/noteTextView.ignoreCodeFontSize"), - ui->noteTextViewIgnoreCodeFontSizeCheckBox->isChecked()); + settings.setValue(QStringLiteral("MainWindow/noteTextView.ignoreCodeFontSize"), + ui->noteTextViewIgnoreCodeFontSizeCheckBox->isChecked()); settings.setValue(QStringLiteral("MainWindow/noteTextView.underline"), ui->noteTextViewUnderlineCheckBox->isChecked()); settings.setValue(QStringLiteral("MainWindow/noteTextView.useEditorStyles"), ui->noteTextViewUseEditorStylesCheckBox->isChecked()); - settings.setValue( - QStringLiteral("MainWindow/noteTextView.useInternalExportStyling"), - ui->useInternalExportStylingCheckBox->isChecked()); - settings.setValue( - QStringLiteral("MainWindow/noteTextView.refreshDebounceTime"), - ui->noteTextViewRefreshDebounceTimeSpinBox->value()); + settings.setValue(QStringLiteral("MainWindow/noteTextView.useInternalExportStyling"), + ui->useInternalExportStylingCheckBox->isChecked()); + settings.setValue(QStringLiteral("MainWindow/noteTextView.refreshDebounceTime"), + ui->noteTextViewRefreshDebounceTimeSpinBox->value()); settings.setValue(QStringLiteral("Debug/fakeOldVersionNumber"), ui->oldVersionNumberCheckBox->isChecked()); - settings.setValue(QStringLiteral("Debug/fileLogging"), - ui->fileLoggingCheckBox->isChecked()); + settings.setValue(QStringLiteral("Debug/fileLogging"), ui->fileLoggingCheckBox->isChecked()); settings.setValue(QStringLiteral("Editor/autoBracketClosing"), ui->autoBracketClosingCheckBox->isChecked()); settings.setValue(QStringLiteral("Editor/autoBracketRemoval"), @@ -788,40 +713,31 @@ void SettingsDialog::storeSettings() { ui->highlightCurrentLineCheckBox->isChecked()); settings.setValue(QStringLiteral("Editor/editorWidthInDFMOnly"), ui->editorWidthInDFMOnlyCheckBox->isChecked()); - settings.setValue(QStringLiteral("Editor/vimMode"), - ui->vimModeCheckBox->isChecked()); + settings.setValue(QStringLiteral("Editor/vimMode"), ui->vimModeCheckBox->isChecked()); settings.setValue(QStringLiteral("Editor/disableCursorBlinking"), ui->disableCursorBlinkingCheckBox->isChecked()); - settings.setValue(QStringLiteral("Editor/useTabIndent"), - ui->useTabIndentCheckBox->isChecked()); - settings.setValue(QStringLiteral("Editor/indentSize"), - ui->indentSizeSpinBox->value()); + settings.setValue(QStringLiteral("Editor/useTabIndent"), ui->useTabIndentCheckBox->isChecked()); + settings.setValue(QStringLiteral("Editor/indentSize"), ui->indentSizeSpinBox->value()); - if (!settings.value(QStringLiteral("appMetrics/disableTracking")) - .toBool() && + if (!settings.value(QStringLiteral("appMetrics/disableTracking")).toBool() && ui->appMetricsCheckBox->isChecked()) { - MetricsService::instance()->sendVisit( - QStringLiteral("settings/app-metrics-disabled")); + MetricsService::instance()->sendVisit(QStringLiteral("settings/app-metrics-disabled")); } settings.setValue(QStringLiteral("appMetrics/disableTracking"), ui->appMetricsCheckBox->isChecked()); - if (!settings.value(QStringLiteral("appMetrics/disableAppHeartbeat")) - .toBool() && + if (!settings.value(QStringLiteral("appMetrics/disableAppHeartbeat")).toBool() && ui->appHeartbeatCheckBox->isChecked()) { - MetricsService::instance()->sendVisit( - QStringLiteral("settings/app-heartbeat-disabled")); + MetricsService::instance()->sendVisit(QStringLiteral("settings/app-heartbeat-disabled")); } settings.setValue(QStringLiteral("appMetrics/disableAppHeartbeat"), ui->appHeartbeatCheckBox->isChecked()); - settings.setValue(QStringLiteral("darkModeColors"), - ui->darkModeColorsCheckBox->isChecked()); + settings.setValue(QStringLiteral("darkModeColors"), ui->darkModeColorsCheckBox->isChecked()); - settings.setValue(QStringLiteral("darkMode"), - ui->darkModeCheckBox->isChecked()); + settings.setValue(QStringLiteral("darkMode"), ui->darkModeCheckBox->isChecked()); settings.setValue(QStringLiteral("darkModeTrayIcon"), ui->darkModeTrayIconCheckBox->isChecked()); @@ -832,8 +748,7 @@ void SettingsDialog::storeSettings() { settings.setValue(QStringLiteral("internalIconTheme"), ui->internalIconThemeCheckBox->isChecked()); - settings.setValue(QStringLiteral("systemIconTheme"), - ui->systemIconThemeCheckBox->isChecked()); + settings.setValue(QStringLiteral("systemIconTheme"), ui->systemIconThemeCheckBox->isChecked()); QStringList todoCalendarUrlList; QStringList todoCalendarDisplayNameList; @@ -852,12 +767,10 @@ void SettingsDialog::storeSettings() { } // store the tasks calendar data to the settings - settings.setValue(QStringLiteral("ownCloud/todoCalendarUrlList"), - todoCalendarUrlList); + settings.setValue(QStringLiteral("ownCloud/todoCalendarUrlList"), todoCalendarUrlList); settings.setValue(QStringLiteral("ownCloud/todoCalendarDisplayNameList"), todoCalendarDisplayNameList); - settings.setValue(QStringLiteral("ownCloud/todoCalendarEnabledList"), - todoCalendarEnabledList); + settings.setValue(QStringLiteral("ownCloud/todoCalendarEnabledList"), todoCalendarEnabledList); settings.setValue(QStringLiteral("ownCloud/todoCalendarEnabledUrlList"), todoCalendarEnabledUrlList); @@ -871,18 +784,15 @@ void SettingsDialog::storeSettings() { todoCalendarBackend = OwnCloudService::LegacyOwnCloudCalendar; } - settings.setValue(QStringLiteral("ownCloud/todoCalendarBackend"), - todoCalendarBackend); - settings.setValue( - QStringLiteral("ownCloud/todoCalendarCloudConnectionId"), - ui->calendarCloudConnectionComboBox->currentData().toInt()); + settings.setValue(QStringLiteral("ownCloud/todoCalendarBackend"), todoCalendarBackend); + settings.setValue(QStringLiteral("ownCloud/todoCalendarCloudConnectionId"), + ui->calendarCloudConnectionComboBox->currentData().toInt()); settings.setValue(QStringLiteral("ownCloud/todoCalendarCalDAVServerUrl"), ui->calDavServerUrlEdit->text()); settings.setValue(QStringLiteral("ownCloud/todoCalendarCalDAVUsername"), ui->calDavUsernameEdit->text()); settings.setValue(QStringLiteral("ownCloud/todoCalendarCalDAVPassword"), - CryptoService::instance()->encryptToString( - ui->calDavPasswordEdit->text())); + CryptoService::instance()->encryptToString(ui->calDavPasswordEdit->text())); settings.setValue(QStringLiteral("networking/ignoreSSLErrors"), ui->ignoreSSLErrorsCheckBox->isChecked()); @@ -894,8 +804,7 @@ void SettingsDialog::storeSettings() { noteFileExtensionList.append(item->text()); } noteFileExtensionList.removeDuplicates(); - settings.setValue(QStringLiteral("noteFileExtensionList"), - noteFileExtensionList); + settings.setValue(QStringLiteral("noteFileExtensionList"), noteFileExtensionList); // store the font settings storeFontSettings(); @@ -916,21 +825,18 @@ void SettingsDialog::storeSettings() { storeScriptListEnabledState(); // store image scaling settings - settings.setValue(QStringLiteral("imageScaleDown"), - ui->imageScaleDownCheckBox->isChecked()); + settings.setValue(QStringLiteral("imageScaleDown"), ui->imageScaleDownCheckBox->isChecked()); settings.setValue(QStringLiteral("imageScaleDownMaximumHeight"), ui->maximumImageHeightSpinBox->value()); settings.setValue(QStringLiteral("imageScaleDownMaximumWidth"), ui->maximumImageWidthSpinBox->value()); // store git settings - settings.setValue(QStringLiteral("gitExecutablePath"), - Utils::Misc::makePathRelativeToPortableDataPathIfNeeded( - ui->gitPathLineEdit->text())); - settings.setValue(QStringLiteral("gitCommitInterval"), - ui->gitCommitIntervalTime->value()); - settings.setValue(QStringLiteral("gitLogCommand"), - ui->gitLogCommandLineEdit->text()); + settings.setValue( + QStringLiteral("gitExecutablePath"), + Utils::Misc::makePathRelativeToPortableDataPathIfNeeded(ui->gitPathLineEdit->text())); + settings.setValue(QStringLiteral("gitCommitInterval"), ui->gitCommitIntervalTime->value()); + settings.setValue(QStringLiteral("gitLogCommand"), ui->gitLogCommandLineEdit->text()); // store Panels settings storePanelSettings(); @@ -944,39 +850,31 @@ void SettingsDialog::storeSettings() { } // store the cursor width - settings.setValue(QStringLiteral("cursorWidth"), - ui->cursorWidthSpinBox->value()); + settings.setValue(QStringLiteral("cursorWidth"), ui->cursorWidthSpinBox->value()); settings.setValue(QStringLiteral("SearchEngineId"), ui->searchEngineSelectionComboBox->currentData().toInt()); - settings.setValue(QStringLiteral("ShowSystemTray"), - ui->showSystemTrayCheckBox->isChecked()); - settings.setValue(QStringLiteral("StartHidden"), - ui->startHiddenCheckBox->isChecked()); - settings.setValue( - QStringLiteral("automaticNoteFolderDatabaseClosing"), - ui->automaticNoteFolderDatabaseClosingCheckBox->isChecked()); - settings.setValue(QStringLiteral("legacyLinking"), - ui->legacyLinkingCheckBox->isChecked()); + settings.setValue(QStringLiteral("ShowSystemTray"), ui->showSystemTrayCheckBox->isChecked()); + settings.setValue(QStringLiteral("StartHidden"), ui->startHiddenCheckBox->isChecked()); + settings.setValue(QStringLiteral("automaticNoteFolderDatabaseClosing"), + ui->automaticNoteFolderDatabaseClosingCheckBox->isChecked()); + settings.setValue(QStringLiteral("legacyLinking"), ui->legacyLinkingCheckBox->isChecked()); settings.setValue(QStringLiteral("webSocketServerService/port"), ui->webSocketServerServicePortSpinBox->value()); settings.setValue(QStringLiteral("webSocketServerService/bookmarksTag"), ui->bookmarksTagLineEdit->text()); - settings.setValue( - QStringLiteral("webSocketServerService/bookmarksNoteName"), - ui->bookmarksNoteNameLineEdit->text()); + settings.setValue(QStringLiteral("webSocketServerService/bookmarksNoteName"), + ui->bookmarksNoteNameLineEdit->text()); settings.setValue(QStringLiteral("webSocketServerService/commandSnippetsTag"), ui->commandSnippetsTagLineEdit->text()); - settings.setValue( - QStringLiteral("webSocketServerService/commandSnippetsNoteName"), - ui->commandSnippetsNoteNameLineEdit->text()); + settings.setValue(QStringLiteral("webSocketServerService/commandSnippetsNoteName"), + ui->commandSnippetsNoteNameLineEdit->text()); settings.setValue(QStringLiteral("webAppClientService/serverUrl"), ui->webAppServerUrlLineEdit->text()); - settings.setValue(QStringLiteral("webAppClientService/token"), - ui->webAppTokenLineEdit->text()); + settings.setValue(QStringLiteral("webAppClientService/token"), ui->webAppTokenLineEdit->text()); } /** @@ -987,8 +885,7 @@ void SettingsDialog::storePanelSettings() { // Notes Panel Options ui->notesPanelSortAlphabeticalRadioButton->isChecked() ? settings.setValue(QStringLiteral("notesPanelSort"), SORT_ALPHABETICAL) - : settings.setValue(QStringLiteral("notesPanelSort"), - SORT_BY_LAST_CHANGE); + : settings.setValue(QStringLiteral("notesPanelSort"), SORT_BY_LAST_CHANGE); ui->notesPanelOrderDescendingRadioButton->isChecked() ? settings.setValue(QStringLiteral("notesPanelOrder"), ORDER_DESCENDING) : settings.setValue(QStringLiteral("notesPanelOrder"), ORDER_ASCENDING); @@ -997,47 +894,37 @@ void SettingsDialog::storePanelSettings() { settings.setValue(QStringLiteral("noteSubfoldersPanelHideSearch"), ui->noteSubfoldersPanelHideSearchCheckBox->isChecked()); - settings.setValue( - QStringLiteral("noteSubfoldersPanelDisplayAsFullTree"), - ui->noteSubfoldersPanelDisplayAsFullTreeCheckBox->isChecked()); + settings.setValue(QStringLiteral("noteSubfoldersPanelDisplayAsFullTree"), + ui->noteSubfoldersPanelDisplayAsFullTreeCheckBox->isChecked()); - settings.setValue( - QStringLiteral("noteSubfoldersPanelShowRootFolderName"), - ui->noteSubfoldersPanelShowRootFolderNameCheckBox->isChecked()); + settings.setValue(QStringLiteral("noteSubfoldersPanelShowRootFolderName"), + ui->noteSubfoldersPanelShowRootFolderNameCheckBox->isChecked()); - settings.setValue( - QStringLiteral("noteSubfoldersPanelShowNotesRecursively"), - ui->noteSubfoldersPanelShowNotesRecursivelyCheckBox->isChecked()); + settings.setValue(QStringLiteral("noteSubfoldersPanelShowNotesRecursively"), + ui->noteSubfoldersPanelShowNotesRecursivelyCheckBox->isChecked()); - settings.setValue( - QStringLiteral("disableSavedSearchesAutoCompletion"), - ui->disableSavedSearchesAutoCompletionCheckBox->isChecked()); + settings.setValue(QStringLiteral("disableSavedSearchesAutoCompletion"), + ui->disableSavedSearchesAutoCompletionCheckBox->isChecked()); - settings.setValue(QStringLiteral("showMatches"), - ui->showMatchesCheckBox->isChecked()); + settings.setValue(QStringLiteral("showMatches"), ui->showMatchesCheckBox->isChecked()); settings.setValue(QStringLiteral("noteSubfoldersPanelShowFullPath"), ui->noteSubfoldersPanelShowFullPathCheckBox->isChecked()); ui->noteSubfoldersPanelSortAlphabeticalRadioButton->isChecked() - ? settings.setValue(QStringLiteral("noteSubfoldersPanelSort"), - SORT_ALPHABETICAL) - : settings.setValue(QStringLiteral("noteSubfoldersPanelSort"), - SORT_BY_LAST_CHANGE); + ? settings.setValue(QStringLiteral("noteSubfoldersPanelSort"), SORT_ALPHABETICAL) + : settings.setValue(QStringLiteral("noteSubfoldersPanelSort"), SORT_BY_LAST_CHANGE); ui->noteSubfoldersPanelOrderDescendingRadioButton->isChecked() - ? settings.setValue(QStringLiteral("noteSubfoldersPanelOrder"), - ORDER_DESCENDING) - : settings.setValue(QStringLiteral("noteSubfoldersPanelOrder"), - ORDER_ASCENDING); + ? settings.setValue(QStringLiteral("noteSubfoldersPanelOrder"), ORDER_DESCENDING) + : settings.setValue(QStringLiteral("noteSubfoldersPanelOrder"), ORDER_ASCENDING); const QSignalBlocker blocker(ui->ignoreNoteSubFoldersLineEdit); settings.setValue(QStringLiteral("ignoreNoteSubFolders"), ui->ignoreNoteSubFoldersLineEdit->text()); const QSignalBlocker blocker2(ui->ignoredNoteFilesLineEdit); - settings.setValue(QStringLiteral("ignoredNoteFiles"), - ui->ignoredNoteFilesLineEdit->text()); + settings.setValue(QStringLiteral("ignoredNoteFiles"), ui->ignoredNoteFilesLineEdit->text()); // Tags Panel Options settings.setValue(QStringLiteral("tagsPanelHideSearch"), @@ -1047,13 +934,11 @@ void SettingsDialog::storePanelSettings() { settings.setValue(QStringLiteral("taggingShowNotesRecursively"), ui->taggingShowNotesRecursivelyCheckBox->isChecked()); - settings.setValue(QStringLiteral("noteListPreview"), - ui->noteListPreviewCheckBox->isChecked()); + settings.setValue(QStringLiteral("noteListPreview"), ui->noteListPreviewCheckBox->isChecked()); ui->tagsPanelSortAlphabeticalRadioButton->isChecked() ? settings.setValue(QStringLiteral("tagsPanelSort"), SORT_ALPHABETICAL) - : settings.setValue(QStringLiteral("tagsPanelSort"), - SORT_BY_LAST_CHANGE); + : settings.setValue(QStringLiteral("tagsPanelSort"), SORT_BY_LAST_CHANGE); ui->tagsPanelOrderDescendingRadioButton->isChecked() ? settings.setValue(QStringLiteral("tagsPanelOrder"), ORDER_DESCENDING) @@ -1066,8 +951,7 @@ void SettingsDialog::storePanelSettings() { settings.setValue(QStringLiteral("navigationPanelAutoSelect"), ui->navigationPanelAutoSelectCheckBox->isChecked()); - settings.setValue(QStringLiteral("enableNoteTree"), - ui->enableNoteTreeCheckBox->isChecked()); + settings.setValue(QStringLiteral("enableNoteTree"), ui->enableNoteTreeCheckBox->isChecked()); } /** @@ -1075,12 +959,10 @@ void SettingsDialog::storePanelSettings() { */ void SettingsDialog::storeFontSettings() { QSettings settings; - settings.setValue(QStringLiteral("MainWindow/noteTextEdit.font"), - noteTextEditFont.toString()); + settings.setValue(QStringLiteral("MainWindow/noteTextEdit.font"), noteTextEditFont.toString()); settings.setValue(QStringLiteral("MainWindow/noteTextEdit.code.font"), noteTextEditCodeFont.toString()); - settings.setValue(QStringLiteral("MainWindow/noteTextView.font"), - noteTextViewFont.toString()); + settings.setValue(QStringLiteral("MainWindow/noteTextView.font"), noteTextViewFont.toString()); settings.setValue(QStringLiteral("MainWindow/noteTextView.code.font"), noteTextViewCodeFont.toString()); } @@ -1090,64 +972,48 @@ void SettingsDialog::readSettings() { // set current note folder list item QListWidgetItem *noteFolderListItem = Utils::Gui::getListWidgetItemWithUserData( - ui->noteFolderListWidget, NoteFolder::currentNoteFolderId()); + ui->noteFolderListWidget, NoteFolder::currentNoteFolderId()); if (noteFolderListItem != nullptr) { ui->noteFolderListWidget->setCurrentItem(noteFolderListItem); } - ui->ownCloudSupportCheckBox->setChecked( - OwnCloudService::isOwnCloudSupportEnabled()); + ui->ownCloudSupportCheckBox->setChecked(OwnCloudService::isOwnCloudSupportEnabled()); on_ownCloudSupportCheckBox_toggled(); - ui->todoCalendarSupportCheckBox->setChecked( - OwnCloudService::isTodoCalendarSupportEnabled()); + ui->todoCalendarSupportCheckBox->setChecked(OwnCloudService::isTodoCalendarSupportEnabled()); on_todoCalendarSupportCheckBox_toggled(); ui->serverUrlEdit->setText(_selectedCloudConnection.getServerUrl()); ui->userNameEdit->setText(_selectedCloudConnection.getUsername()); ui->passwordEdit->setText(_selectedCloudConnection.getPassword()); - ui->appQOwnNotesAPICheckBox->setChecked( - _selectedCloudConnection.getAppQOwnNotesAPIEnabled()); - ui->timeFormatLineEdit->setText( - settings.value(QStringLiteral("insertTimeFormat")).toString()); + ui->appQOwnNotesAPICheckBox->setChecked(_selectedCloudConnection.getAppQOwnNotesAPIEnabled()); + ui->timeFormatLineEdit->setText(settings.value(QStringLiteral("insertTimeFormat")).toString()); // prepend the portable data path if we are in portable mode - ui->externalEditorPathLineEdit->setText( - Utils::Misc::prependPortableDataPathIfNeeded( - settings.value(QStringLiteral("externalEditorPath")).toString(), - true)); + ui->externalEditorPathLineEdit->setText(Utils::Misc::prependPortableDataPathIfNeeded( + settings.value(QStringLiteral("externalEditorPath")).toString(), true)); ui->disableAutomaticUpdateDialogCheckBox->setChecked( - settings.value(QStringLiteral("disableAutomaticUpdateDialog")) - .toBool()); + settings.value(QStringLiteral("disableAutomaticUpdateDialog")).toBool()); ui->notifyAllExternalModificationsCheckBox->setChecked( - settings.value(QStringLiteral("notifyAllExternalModifications")) - .toBool()); + settings.value(QStringLiteral("notifyAllExternalModifications")).toBool()); ui->ignoreAllExternalModificationsCheckBox->setChecked( - settings.value(QStringLiteral("ignoreAllExternalModifications")) - .toBool()); + settings.value(QStringLiteral("ignoreAllExternalModifications")).toBool()); ui->acceptAllExternalModificationsCheckBox->setChecked( - settings.value(QStringLiteral("acceptAllExternalModifications")) - .toBool()); + settings.value(QStringLiteral("acceptAllExternalModifications")).toBool()); ui->ignoreAllExternalNoteFolderChangesCheckBox->setChecked( - settings.value(QStringLiteral("ignoreAllExternalNoteFolderChanges")) - .toBool()); + settings.value(QStringLiteral("ignoreAllExternalNoteFolderChanges")).toBool()); ui->newNoteAskHeadlineCheckBox->setChecked( settings.value(QStringLiteral("newNoteAskHeadline")).toBool()); ui->useUNIXNewlineCheckBox->setChecked( settings.value(QStringLiteral("useUNIXNewline")).toBool()); ui->localTrashEnabledCheckBox->setChecked( - settings.value(QStringLiteral("localTrash/supportEnabled"), true) - .toBool()); + settings.value(QStringLiteral("localTrash/supportEnabled"), true).toBool()); ui->localTrashClearCheckBox->setChecked( - settings.value(QStringLiteral("localTrash/autoCleanupEnabled"), true) - .toBool()); + settings.value(QStringLiteral("localTrash/autoCleanupEnabled"), true).toBool()); ui->localTrashClearTimeSpinBox->setValue( - settings.value(QStringLiteral("localTrash/autoCleanupDays"), 30) - .toInt()); - ui->enableSocketServerCheckBox->setChecked( - Utils::Misc::isSocketServerEnabled()); + settings.value(QStringLiteral("localTrash/autoCleanupDays"), 30).toInt()); + ui->enableSocketServerCheckBox->setChecked(Utils::Misc::isSocketServerEnabled()); on_enableSocketServerCheckBox_toggled(); - ui->enableWebApplicationCheckBox->setChecked( - Utils::Misc::isWebAppSupportEnabled()); + ui->enableWebApplicationCheckBox->setChecked(Utils::Misc::isWebAppSupportEnabled()); on_enableWebApplicationCheckBox_toggled(); #ifdef Q_OS_MAC @@ -1157,28 +1023,20 @@ void SettingsDialog::readSettings() { #endif ui->restoreCursorPositionCheckBox->setChecked( - settings - .value(QStringLiteral("restoreCursorPosition"), - restoreCursorPositionDefault) + settings.value(QStringLiteral("restoreCursorPosition"), restoreCursorPositionDefault) .toBool()); ui->restoreLastNoteAtStartupCheckBox->setChecked( - settings.value(QStringLiteral("restoreLastNoteAtStartup"), true) - .toBool()); + settings.value(QStringLiteral("restoreLastNoteAtStartup"), true).toBool()); ui->noteSaveIntervalTime->setValue( settings.value(QStringLiteral("noteSaveIntervalTime"), 10).toInt()); ui->noteTextViewRTLCheckBox->setChecked( settings.value(QStringLiteral("MainWindow/noteTextView.rtl")).toBool()); ui->noteTextViewIgnoreCodeFontSizeCheckBox->setChecked( - settings - .value(QStringLiteral("MainWindow/noteTextView.ignoreCodeFontSize"), - true) + settings.value(QStringLiteral("MainWindow/noteTextView.ignoreCodeFontSize"), true) .toBool()); ui->noteTextViewUnderlineCheckBox->setChecked( - settings - .value(QStringLiteral("MainWindow/noteTextView.underline"), true) - .toBool()); - ui->noteTextViewUseEditorStylesCheckBox->setChecked( - Utils::Misc::isPreviewUseEditorStyles()); + settings.value(QStringLiteral("MainWindow/noteTextView.underline"), true).toBool()); + ui->noteTextViewUseEditorStylesCheckBox->setChecked(Utils::Misc::isPreviewUseEditorStyles()); ui->noteTextViewRefreshDebounceTimeSpinBox->setValue( Utils::Misc::getPreviewRefreshDebounceTime()); ui->useInternalExportStylingCheckBox->setChecked( @@ -1189,37 +1047,29 @@ void SettingsDialog::readSettings() { settings.value(QStringLiteral("Debug/fileLogging")).toBool()); on_fileLoggingCheckBox_toggled(ui->fileLoggingCheckBox->isChecked()); ui->autoBracketClosingCheckBox->setChecked( - settings.value(QStringLiteral("Editor/autoBracketClosing"), true) - .toBool()); + settings.value(QStringLiteral("Editor/autoBracketClosing"), true).toBool()); ui->autoBracketRemovalCheckBox->setChecked( - settings.value(QStringLiteral("Editor/autoBracketRemoval"), true) - .toBool()); + settings.value(QStringLiteral("Editor/autoBracketRemoval"), true).toBool()); ui->removeTrailingSpacesCheckBox->setChecked( settings.value(QStringLiteral("Editor/removeTrailingSpaces")).toBool()); ui->showLineNumbersInEditorCheckBox->setChecked( settings.value(QStringLiteral("Editor/showLineNumbers")).toBool()); ui->highlightCurrentLineCheckBox->setChecked( - settings.value(QStringLiteral("Editor/highlightCurrentLine"), true) - .toBool()); + settings.value(QStringLiteral("Editor/highlightCurrentLine"), true).toBool()); ui->editorWidthInDFMOnlyCheckBox->setChecked( - settings.value(QStringLiteral("Editor/editorWidthInDFMOnly"), true) - .toBool()); - ui->vimModeCheckBox->setChecked( - settings.value(QStringLiteral("Editor/vimMode")).toBool()); + settings.value(QStringLiteral("Editor/editorWidthInDFMOnly"), true).toBool()); + ui->vimModeCheckBox->setChecked(settings.value(QStringLiteral("Editor/vimMode")).toBool()); ui->disableCursorBlinkingCheckBox->setChecked( - settings.value(QStringLiteral("Editor/disableCursorBlinking")) - .toBool()); + settings.value(QStringLiteral("Editor/disableCursorBlinking")).toBool()); ui->useTabIndentCheckBox->setChecked( settings.value(QStringLiteral("Editor/useTabIndent")).toBool()); ui->indentSizeSpinBox->setValue(Utils::Misc::indentSize()); ui->markdownHighlightingCheckBox->setChecked( - settings.value(QStringLiteral("markdownHighlightingEnabled"), true) - .toBool()); + settings.value(QStringLiteral("markdownHighlightingEnabled"), true).toBool()); ui->fullyHighlightedBlockquotesCheckBox->setChecked( settings.value(QStringLiteral("fullyHighlightedBlockquotes")).toBool()); ui->noteEditCentralWidgetCheckBox->setChecked( - settings.value(QStringLiteral("noteEditIsCentralWidget"), true) - .toBool()); + settings.value(QStringLiteral("noteEditIsCentralWidget"), true).toBool()); ui->restoreNoteTabsCheckBox->setChecked( settings.value(QStringLiteral("restoreNoteTabs"), true).toBool()); ui->noteFolderButtonsCheckBox->setChecked( @@ -1229,18 +1079,15 @@ void SettingsDialog::readSettings() { ui->closeTodoListAfterSaveCheckBox->setChecked( settings.value(QStringLiteral("closeTodoListAfterSave")).toBool()); ui->toolbarIconSizeSpinBox->setValue( - settings.value(QStringLiteral("MainWindow/mainToolBar.iconSize")) - .toInt()); + settings.value(QStringLiteral("MainWindow/mainToolBar.iconSize")).toInt()); const QSignalBlocker overrideInterfaceFontSizeGroupBoxBlocker( ui->overrideInterfaceFontSizeGroupBox); Q_UNUSED(overrideInterfaceFontSizeGroupBoxBlocker) - const QSignalBlocker interfaceFontSizeSpinBoxBlocker( - ui->interfaceFontSizeSpinBox); + const QSignalBlocker interfaceFontSizeSpinBoxBlocker(ui->interfaceFontSizeSpinBox); Q_UNUSED(interfaceFontSizeSpinBoxBlocker) ui->overrideInterfaceFontSizeGroupBox->setChecked( - settings.value(QStringLiteral("overrideInterfaceFontSize"), false) - .toBool()); + settings.value(QStringLiteral("overrideInterfaceFontSize"), false).toBool()); ui->interfaceFontSizeSpinBox->setValue( settings.value(QStringLiteral("interfaceFontSize"), 11).toInt()); @@ -1249,12 +1096,10 @@ void SettingsDialog::readSettings() { treeWidget.addTopLevelItem(treeWidgetItem); int height = treeWidget.visualItemRect(treeWidgetItem).height(); - ui->itemHeightSpinBox->setValue( - settings.value(QStringLiteral("itemHeight"), height).toInt()); + ui->itemHeightSpinBox->setValue(settings.value(QStringLiteral("itemHeight"), height).toInt()); - selectListWidgetValue( - ui->languageListWidget, - settings.value(QStringLiteral("interfaceLanguage")).toString()); + selectListWidgetValue(ui->languageListWidget, + settings.value(QStringLiteral("interfaceLanguage")).toString()); const QSignalBlocker blocker(ui->appMetricsCheckBox); Q_UNUSED(blocker) @@ -1262,22 +1107,19 @@ void SettingsDialog::readSettings() { settings.value(QStringLiteral("appMetrics/disableTracking")).toBool()); ui->appHeartbeatCheckBox->setChecked( - settings.value(QStringLiteral("appMetrics/disableAppHeartbeat")) - .toBool()); + settings.value(QStringLiteral("appMetrics/disableAppHeartbeat")).toBool()); ui->darkModeColorsCheckBox->setChecked( settings.value(QStringLiteral("darkModeColors")).toBool()); const QSignalBlocker darkModeCheckBoxBlocker(ui->darkModeCheckBox); Q_UNUSED(darkModeCheckBoxBlocker) - ui->darkModeCheckBox->setChecked( - settings.value(QStringLiteral("darkMode")).toBool()); + ui->darkModeCheckBox->setChecked(settings.value(QStringLiteral("darkMode")).toBool()); ui->darkModeTrayIconCheckBox->setChecked( settings.value(QStringLiteral("darkModeTrayIcon")).toBool()); - ui->darkModeIconThemeCheckBox->setChecked( - Utils::Misc::isDarkModeIconTheme()); + ui->darkModeIconThemeCheckBox->setChecked(Utils::Misc::isDarkModeIconTheme()); ui->internalIconThemeCheckBox->setChecked( settings.value(QStringLiteral("internalIconTheme")).toBool()); @@ -1289,26 +1131,21 @@ void SettingsDialog::readSettings() { handleDarkModeCheckBoxToggled(); noteTextEditFont.fromString( - settings.value(QStringLiteral("MainWindow/noteTextEdit.font")) - .toString()); + settings.value(QStringLiteral("MainWindow/noteTextEdit.font")).toString()); setFontLabel(ui->noteTextEditFontLabel, noteTextEditFont); noteTextEditCodeFont.fromString( - settings.value(QStringLiteral("MainWindow/noteTextEdit.code.font")) - .toString()); + settings.value(QStringLiteral("MainWindow/noteTextEdit.code.font")).toString()); setFontLabel(ui->noteTextEditCodeFontLabel, noteTextEditCodeFont); // load note text view font - QString fontString = - settings.value(QStringLiteral("MainWindow/noteTextView.font")) - .toString(); + QString fontString = settings.value(QStringLiteral("MainWindow/noteTextView.font")).toString(); // store the current font if there isn't any set yet if (fontString.isEmpty()) { auto *textEdit = new QTextEdit(); fontString = textEdit->font().toString(); - settings.setValue(QStringLiteral("MainWindow/noteTextView.font"), - fontString); + settings.setValue(QStringLiteral("MainWindow/noteTextView.font"), fontString); delete textEdit; } @@ -1316,9 +1153,7 @@ void SettingsDialog::readSettings() { setFontLabel(ui->noteTextViewFontLabel, noteTextViewFont); // load note text view code font - fontString = - settings.value(QStringLiteral("MainWindow/noteTextView.code.font")) - .toString(); + fontString = settings.value(QStringLiteral("MainWindow/noteTextView.code.font")).toString(); // set a default note text view code font if (fontString.isEmpty()) { @@ -1326,8 +1161,7 @@ void SettingsDialog::readSettings() { on_noteTextViewCodeResetButton_clicked(); fontString = noteTextViewCodeFont.toString(); - settings.setValue(QStringLiteral("MainWindow/noteTextView.code.font"), - fontString); + settings.setValue(QStringLiteral("MainWindow/noteTextView.code.font"), fontString); } else { noteTextViewCodeFont.fromString(fontString); } @@ -1369,25 +1203,19 @@ void SettingsDialog::readSettings() { Q_UNUSED(blocker6) ui->ignoreNonTodoCalendarsCheckBox->setChecked( - settings.value(QStringLiteral("ownCloud/ignoreNonTodoCalendars"), true) - .toBool()); + settings.value(QStringLiteral("ownCloud/ignoreNonTodoCalendars"), true).toBool()); ui->calDavServerUrlEdit->setText( - settings.value(QStringLiteral("ownCloud/todoCalendarCalDAVServerUrl")) - .toString()); + settings.value(QStringLiteral("ownCloud/todoCalendarCalDAVServerUrl")).toString()); ui->calDavUsernameEdit->setText( - settings.value(QStringLiteral("ownCloud/todoCalendarCalDAVUsername")) - .toString()); + settings.value(QStringLiteral("ownCloud/todoCalendarCalDAVUsername")).toString()); ui->calDavPasswordEdit->setText(CryptoService::instance()->decryptToString( - settings.value(QStringLiteral("ownCloud/todoCalendarCalDAVPassword")) - .toString())); + settings.value(QStringLiteral("ownCloud/todoCalendarCalDAVPassword")).toString())); QStringList todoCalendarUrlList = - settings.value(QStringLiteral("ownCloud/todoCalendarUrlList")) - .toStringList(); + settings.value(QStringLiteral("ownCloud/todoCalendarUrlList")).toStringList(); QStringList todoCalendarDisplayNameList = - settings.value(QStringLiteral("ownCloud/todoCalendarDisplayNameList")) - .toStringList(); + settings.value(QStringLiteral("ownCloud/todoCalendarDisplayNameList")).toStringList(); int todoCalendarUrlListCount = todoCalendarUrlList.count(); int todoCalendarDisplayNameListCount = todoCalendarDisplayNameList.count(); @@ -1417,17 +1245,15 @@ void SettingsDialog::readSettings() { addCustomNoteFileExtension(fileExtension); } - auto noteFileExtensionItems = ui->defaultNoteFileExtensionListWidget-> - findItems(Note::defaultNoteFileExtension(), Qt::MatchExactly); + auto noteFileExtensionItems = ui->defaultNoteFileExtensionListWidget->findItems( + Note::defaultNoteFileExtension(), Qt::MatchExactly); if (noteFileExtensionItems.count() > 0) { - ui->defaultNoteFileExtensionListWidget->setCurrentItem( - noteFileExtensionItems.at(0)); + ui->defaultNoteFileExtensionListWidget->setCurrentItem(noteFileExtensionItems.at(0)); } bool ignoreSSLErrors = - settings.value(QStringLiteral("networking/ignoreSSLErrors"), true) - .toBool(); + settings.value(QStringLiteral("networking/ignoreSSLErrors"), true).toBool(); ui->ignoreSSLErrorsCheckBox->setChecked(ignoreSSLErrors); ui->letsEncryptInfoLabel->setVisible(ignoreSSLErrors); @@ -1438,14 +1264,11 @@ void SettingsDialog::readSettings() { loadShortcutSettings(); // load image scaling settings - bool scaleImageDown = - settings.value(QStringLiteral("imageScaleDown"), false).toBool(); + bool scaleImageDown = settings.value(QStringLiteral("imageScaleDown"), false).toBool(); ui->maximumImageHeightSpinBox->setValue( - settings.value(QStringLiteral("imageScaleDownMaximumHeight"), 1024) - .toInt()); + settings.value(QStringLiteral("imageScaleDownMaximumHeight"), 1024).toInt()); ui->maximumImageWidthSpinBox->setValue( - settings.value(QStringLiteral("imageScaleDownMaximumWidth"), 1024) - .toInt()); + settings.value(QStringLiteral("imageScaleDownMaximumWidth"), 1024).toInt()); ui->imageScaleDownCheckBox->setChecked(scaleImageDown); ui->imageScalingFrame->setVisible(scaleImageDown); @@ -1454,8 +1277,7 @@ void SettingsDialog::readSettings() { settings.value(QStringLiteral("gitExecutablePath")).toString(), true)); ui->gitCommitIntervalTime->setValue( settings.value(QStringLiteral("gitCommitInterval"), 30).toInt()); - ui->gitLogCommandLineEdit->setText( - settings.value(QStringLiteral("gitLogCommand")).toString()); + ui->gitLogCommandLineEdit->setText(settings.value(QStringLiteral("gitLogCommand")).toString()); // read panel settings readPanelSettings(); @@ -1466,34 +1288,26 @@ void SettingsDialog::readSettings() { initCloudConnectionComboBox(); // set the cursor width spinbox value - ui->cursorWidthSpinBox->setValue( - settings.value(QStringLiteral("cursorWidth"), 1).toInt()); + ui->cursorWidthSpinBox->setValue(settings.value(QStringLiteral("cursorWidth"), 1).toInt()); const QSignalBlocker blocker8(this->ui->showSystemTrayCheckBox); Q_UNUSED(blocker8) - bool showSystemTray = - settings.value(QStringLiteral("ShowSystemTray")).toBool(); + bool showSystemTray = settings.value(QStringLiteral("ShowSystemTray")).toBool(); ui->showSystemTrayCheckBox->setChecked(showSystemTray); ui->startHiddenCheckBox->setEnabled(showSystemTray); - ui->startHiddenCheckBox->setChecked( - settings.value(QStringLiteral("StartHidden")).toBool()); + ui->startHiddenCheckBox->setChecked(settings.value(QStringLiteral("StartHidden")).toBool()); if (!showSystemTray) { ui->startHiddenCheckBox->setChecked(false); } ui->automaticNoteFolderDatabaseClosingCheckBox->setChecked( Utils::Misc::doAutomaticNoteFolderDatabaseClosing()); - ui->legacyLinkingCheckBox->setChecked( - settings.value(QStringLiteral("legacyLinking")).toBool()); + ui->legacyLinkingCheckBox->setChecked(settings.value(QStringLiteral("legacyLinking")).toBool()); - ui->webSocketServerServicePortSpinBox->setValue( - WebSocketServerService::getSettingsPort()); - ui->bookmarksTagLineEdit->setText( - WebSocketServerService::getBookmarksTag()); - ui->bookmarksNoteNameLineEdit->setText( - WebSocketServerService::getBookmarksNoteName()); - ui->commandSnippetsTagLineEdit->setText( - WebSocketServerService::getCommandSnippetsTag()); + ui->webSocketServerServicePortSpinBox->setValue(WebSocketServerService::getSettingsPort()); + ui->bookmarksTagLineEdit->setText(WebSocketServerService::getBookmarksTag()); + ui->bookmarksNoteNameLineEdit->setText(WebSocketServerService::getBookmarksNoteName()); + ui->commandSnippetsTagLineEdit->setText(WebSocketServerService::getCommandSnippetsTag()); ui->commandSnippetsNoteNameLineEdit->setText( WebSocketServerService::getCommandSnippetsNoteName()); @@ -1509,27 +1323,24 @@ void SettingsDialog::initSearchEngineComboBox() const { // Iterates over the search engines and adds them // to the combobox - QHash<int, Utils::Misc::SearchEngine> searchEngines = - Utils::Misc::getSearchEnginesHashMap(); + QHash<int, Utils::Misc::SearchEngine> searchEngines = Utils::Misc::getSearchEnginesHashMap(); ui->searchEngineSelectionComboBox->clear(); Q_FOREACH (int id, Utils::Misc::getSearchEnginesIds()) { Utils::Misc::SearchEngine searchEngine = searchEngines[id]; - ui->searchEngineSelectionComboBox->addItem(searchEngine.name, - QString::number(id)); + ui->searchEngineSelectionComboBox->addItem(searchEngine.name, QString::number(id)); } // Sets the current selected item to the search engine // selected previously // while also handling the case in which the saved key has // been removed from the hash table - int savedEngineId = settings - .value(QStringLiteral("SearchEngineId"), - Utils::Misc::getDefaultSearchEngineId()) - .toInt(); - int savedEngineIndex = ui->searchEngineSelectionComboBox->findData( - QVariant(savedEngineId).toString()); + int savedEngineId = + settings.value(QStringLiteral("SearchEngineId"), Utils::Misc::getDefaultSearchEngineId()) + .toInt(); + int savedEngineIndex = + ui->searchEngineSelectionComboBox->findData(QVariant(savedEngineId).toString()); savedEngineIndex = (savedEngineIndex == -1) ? 0 : savedEngineIndex; ui->searchEngineSelectionComboBox->setCurrentIndex(savedEngineIndex); } @@ -1549,8 +1360,7 @@ void SettingsDialog::loadInterfaceStyleComboBox() const { } QSettings settings; - QString interfaceStyle = - settings.value(QStringLiteral("interfaceStyle")).toString(); + QString interfaceStyle = settings.value(QStringLiteral("interfaceStyle")).toString(); if (!interfaceStyle.isEmpty()) { ui->interfaceStyleComboBox->setCurrentText(interfaceStyle); @@ -1566,45 +1376,35 @@ void SettingsDialog::loadInterfaceStyleComboBox() const { void SettingsDialog::readPanelSettings() { QSettings settings; // Notes Panel Options - if (settings.value(QStringLiteral("notesPanelSort"), SORT_BY_LAST_CHANGE) - .toInt() == SORT_ALPHABETICAL) { + if (settings.value(QStringLiteral("notesPanelSort"), SORT_BY_LAST_CHANGE).toInt() == + SORT_ALPHABETICAL) { ui->notesPanelSortAlphabeticalRadioButton->setChecked(true); ui->notesPanelOrderGroupBox->setEnabled(true); } else { ui->notesPanelSortByLastChangeRadioButton->setChecked(true); ui->notesPanelOrderGroupBox->setEnabled(false); } - settings.value(QStringLiteral("notesPanelOrder")).toInt() == - ORDER_DESCENDING + settings.value(QStringLiteral("notesPanelOrder")).toInt() == ORDER_DESCENDING ? ui->notesPanelOrderDescendingRadioButton->setChecked(true) : ui->notesPanelOrderAscendingRadioButton->setChecked(true); // Note Subfoldes Panel Options ui->noteSubfoldersPanelHideSearchCheckBox->setChecked( - settings.value(QStringLiteral("noteSubfoldersPanelHideSearch")) - .toBool()); + settings.value(QStringLiteral("noteSubfoldersPanelHideSearch")).toBool()); ui->noteSubfoldersPanelDisplayAsFullTreeCheckBox->setChecked( - settings - .value(QStringLiteral("noteSubfoldersPanelDisplayAsFullTree"), true) - .toBool()); + settings.value(QStringLiteral("noteSubfoldersPanelDisplayAsFullTree"), true).toBool()); ui->noteSubfoldersPanelShowNotesRecursivelyCheckBox->setChecked( - settings - .value(QStringLiteral("noteSubfoldersPanelShowNotesRecursively")) - .toBool()); + settings.value(QStringLiteral("noteSubfoldersPanelShowNotesRecursively")).toBool()); ui->disableSavedSearchesAutoCompletionCheckBox->setChecked( - settings.value(QStringLiteral("disableSavedSearchesAutoCompletion")) - .toBool()); + settings.value(QStringLiteral("disableSavedSearchesAutoCompletion")).toBool()); ui->showMatchesCheckBox->setChecked( settings.value(QStringLiteral("showMatches"), true).toBool()); - if (settings - .value(QStringLiteral("noteSubfoldersPanelShowRootFolderName"), - true) - .toBool()) { + if (settings.value(QStringLiteral("noteSubfoldersPanelShowRootFolderName"), true).toBool()) { ui->noteSubfoldersPanelShowRootFolderNameCheckBox->setChecked(true); ui->noteSubfoldersPanelShowFullPathCheckBox->setEnabled(true); } else { @@ -1613,11 +1413,9 @@ void SettingsDialog::readPanelSettings() { } ui->noteSubfoldersPanelShowFullPathCheckBox->setChecked( - settings.value(QStringLiteral("noteSubfoldersPanelShowFullPath")) - .toBool()); + settings.value(QStringLiteral("noteSubfoldersPanelShowFullPath")).toBool()); - if (settings.value(QStringLiteral("noteSubfoldersPanelSort")).toInt() == - SORT_ALPHABETICAL) { + if (settings.value(QStringLiteral("noteSubfoldersPanelSort")).toInt() == SORT_ALPHABETICAL) { ui->noteSubfoldersPanelSortAlphabeticalRadioButton->setChecked(true); ui->noteSubfoldersPanelOrderGroupBox->setEnabled(true); } else { @@ -1625,8 +1423,7 @@ void SettingsDialog::readPanelSettings() { ui->noteSubfoldersPanelOrderGroupBox->setEnabled(false); } - settings.value(QStringLiteral("noteSubfoldersPanelOrder")).toInt() == - ORDER_DESCENDING + settings.value(QStringLiteral("noteSubfoldersPanelOrder")).toInt() == ORDER_DESCENDING ? ui->noteSubfoldersPanelOrderDescendingRadioButton->setChecked(true) : ui->noteSubfoldersPanelOrderAscendingRadioButton->setChecked(true); @@ -1640,8 +1437,7 @@ void SettingsDialog::readPanelSettings() { settings.value(QStringLiteral("taggingShowNotesRecursively")).toBool()); ui->noteListPreviewCheckBox->setChecked(Utils::Misc::isNoteListPreview()); - if (settings.value(QStringLiteral("tagsPanelSort")).toInt() == - SORT_ALPHABETICAL) { + if (settings.value(QStringLiteral("tagsPanelSort")).toInt() == SORT_ALPHABETICAL) { ui->tagsPanelSortAlphabeticalRadioButton->setChecked(true); ui->tagsPanelOrderGroupBox->setEnabled(true); } else { @@ -1654,9 +1450,7 @@ void SettingsDialog::readPanelSettings() { : ui->tagsPanelOrderAscendingRadioButton->setChecked(true); ui->ignoreNoteSubFoldersLineEdit->setText( - settings - .value(QStringLiteral("ignoreNoteSubFolders"), - IGNORED_NOTE_SUBFOLDERS_DEFAULT) + settings.value(QStringLiteral("ignoreNoteSubFolders"), IGNORED_NOTE_SUBFOLDERS_DEFAULT) .toString()); ui->ignoredNoteFilesLineEdit->setText( @@ -1686,10 +1480,8 @@ void SettingsDialog::loadShortcutSettings() { bool darkMode = settings.value(QStringLiteral("darkMode")).toBool(); QPalette palette; - QColor shortcutButtonActiveColor = - darkMode ? Qt::white : palette.color(QPalette::ButtonText); - QColor shortcutButtonInactiveColor = - darkMode ? Qt::darkGray : palette.color(QPalette::Mid); + QColor shortcutButtonActiveColor = darkMode ? Qt::white : palette.color(QPalette::ButtonText); + QColor shortcutButtonInactiveColor = darkMode ? Qt::darkGray : palette.color(QPalette::Mid); const QList<QMenu *> menus = mainWindow->menuList(); ui->shortcutSearchLineEdit->clear(); @@ -1697,16 +1489,15 @@ void SettingsDialog::loadShortcutSettings() { ui->shortcutTreeWidget->setColumnCount(3); // shortcuts on toolbars and note folders don't work yet - auto disabledMenuNames = QStringList() << QStringLiteral("menuToolbars") - << QStringLiteral("noteFoldersMenu"); + auto disabledMenuNames = QStringList() + << QStringLiteral("menuToolbars") << QStringLiteral("noteFoldersMenu"); - const QIcon disableShortcutButtonIcon = QIcon::fromTheme( - QStringLiteral("dialog-cancel"), - QIcon(QStringLiteral( - ":icons/breeze-qownnotes/16x16/dialog-cancel.svg"))); - const QIcon clearButtonIcon = QIcon::fromTheme(QStringLiteral("edit-clear"), - QIcon(":/icons/breeze-qownnotes/16x16/" - "edit-clear.svg")); + const QIcon disableShortcutButtonIcon = + QIcon::fromTheme(QStringLiteral("dialog-cancel"), + QIcon(QStringLiteral(":icons/breeze-qownnotes/16x16/dialog-cancel.svg"))); + const QIcon clearButtonIcon = + QIcon::fromTheme(QStringLiteral("edit-clear"), QIcon(":/icons/breeze-qownnotes/16x16/" + "edit-clear.svg")); // loop through all menus for (const QMenu *menu : menus) { @@ -1739,10 +1530,8 @@ void SettingsDialog::loadShortcutSettings() { keyWidget->setClearButtonIcon(clearButtonIcon); keyWidget->setNoneText(tr("Undefined shortcut")); keyWidget->setShortcutButtonActiveColor(shortcutButtonActiveColor); - keyWidget->setShortcutButtonInactiveColor( - shortcutButtonInactiveColor); - keyWidget->setToolTip(tr("Assign a new shortcut"), - tr("Reset to default shortcut")); + keyWidget->setShortcutButtonInactiveColor(shortcutButtonInactiveColor); + keyWidget->setToolTip(tr("Assign a new shortcut"), tr("Reset to default shortcut")); keyWidget->setDefaultKeySequence(action->data().toString()); const QString &shortcutSettingKey = @@ -1751,22 +1540,18 @@ void SettingsDialog::loadShortcutSettings() { // try to load the key sequence from the settings, because // action->shortcut() is empty if menubar was disabled! - keyWidget->setKeySequence(settingFound ? - settings.value(shortcutSettingKey).toString() : - action->data().toString()); + keyWidget->setKeySequence(settingFound ? settings.value(shortcutSettingKey).toString() + : action->data().toString()); - connect( - keyWidget, &QKeySequenceWidget::keySequenceAccepted, this, - [this, actionObjectName]() { keySequenceEvent(actionObjectName); }); + connect(keyWidget, &QKeySequenceWidget::keySequenceAccepted, this, + [this, actionObjectName]() { keySequenceEvent(actionObjectName); }); auto *disableShortcutButton = new QPushButton(); disableShortcutButton->setToolTip(tr("Clear shortcut")); disableShortcutButton->setIcon(disableShortcutButtonIcon); connect(disableShortcutButton, &QPushButton::pressed, this, - [keyWidget]() { - keyWidget->setKeySequence(QKeySequence("")); - }); + [keyWidget]() { keyWidget->setKeySequence(QKeySequence("")); }); // create a frame for the key widget for the local shortcut and // the shortcut disabling button @@ -1785,13 +1570,12 @@ void SettingsDialog::loadShortcutSettings() { globalShortcutKeyWidget->setClearButtonIcon(clearButtonIcon); globalShortcutKeyWidget->setNoneText(tr("Undefined shortcut")); globalShortcutKeyWidget->setShortcutButtonActiveColor(shortcutButtonActiveColor); - globalShortcutKeyWidget->setShortcutButtonInactiveColor( - shortcutButtonInactiveColor); + globalShortcutKeyWidget->setShortcutButtonInactiveColor(shortcutButtonInactiveColor); globalShortcutKeyWidget->setToolTip(tr("Assign a new shortcut"), - tr("Reset to default shortcut")); + tr("Reset to default shortcut")); globalShortcutKeyWidget->setKeySequence( - settings.value(QStringLiteral("GlobalShortcuts/MainWindow-") - + actionObjectName).toString()); + settings.value(QStringLiteral("GlobalShortcuts/MainWindow-") + actionObjectName) + .toString()); ui->shortcutTreeWidget->setItemWidget(actionItem, 2, globalShortcutKeyWidget); @@ -1843,9 +1627,8 @@ void SettingsDialog::keySequenceEvent(const QString &objectName) { continue; } - const auto keySequenceWidgets = - ui->shortcutTreeWidget->itemWidget(shortcutItem, 1) - ->findChildren<QKeySequenceWidget *>(); + const auto keySequenceWidgets = ui->shortcutTreeWidget->itemWidget(shortcutItem, 1) + ->findChildren<QKeySequenceWidget *>(); if (keySequenceWidgets.count() == 0) { continue; @@ -1862,8 +1645,7 @@ void SettingsDialog::keySequenceEvent(const QString &objectName) { tr("The shortcut <strong>%1</strong> is already " "assigned to <strong>%2</strong>! Do you want to " "jump to the shortcut?") - .arg(eventKeySequence.toString(), - shortcutItem->text(0)), + .arg(eventKeySequence.toString(), shortcutItem->text(0)), QStringLiteral("settings-shortcut-already-assigned"), QMessageBox::Yes | QMessageBox::Cancel, QMessageBox::Yes) == QMessageBox::Yes) { @@ -1882,8 +1664,7 @@ void SettingsDialog::keySequenceEvent(const QString &objectName) { * Finds a QKeySequenceWidget in the shortcutTreeWidget by the objectName * of the assigned menu action */ -QKeySequenceWidget *SettingsDialog::findKeySequenceWidget( - const QString &objectName) { +QKeySequenceWidget *SettingsDialog::findKeySequenceWidget(const QString &objectName) { // loop all top level tree widget items (menus) for (int i = 0; i < ui->shortcutTreeWidget->topLevelItemCount(); i++) { QTreeWidgetItem *menuItem = ui->shortcutTreeWidget->topLevelItem(i); @@ -1894,9 +1675,8 @@ QKeySequenceWidget *SettingsDialog::findKeySequenceWidget( QString name = shortcutItem->data(1, Qt::UserRole).toString(); if (name == objectName) { - const auto keySequenceWidgets = - ui->shortcutTreeWidget->itemWidget(shortcutItem, 1) - ->findChildren<QKeySequenceWidget *>(); + const auto keySequenceWidgets = ui->shortcutTreeWidget->itemWidget(shortcutItem, 1) + ->findChildren<QKeySequenceWidget *>(); if (keySequenceWidgets.count() > 0) { return keySequenceWidgets.at(0); @@ -1921,9 +1701,8 @@ void SettingsDialog::storeShortcutSettings() { // loop all tree widget items of the menu (action shortcuts) for (int j = 0; j < menuItem->childCount(); j++) { QTreeWidgetItem *shortcutItem = menuItem->child(j); - const auto keySequenceWidgets = - ui->shortcutTreeWidget->itemWidget(shortcutItem, 1) - ->findChildren<QKeySequenceWidget *>(); + const auto keySequenceWidgets = ui->shortcutTreeWidget->itemWidget(shortcutItem, 1) + ->findChildren<QKeySequenceWidget *>(); if (keySequenceWidgets.count() == 0) { continue; @@ -1937,8 +1716,7 @@ void SettingsDialog::storeShortcutSettings() { continue; } - const QString actionObjectName = - shortcutItem->data(1, Qt::UserRole).toString(); + const QString actionObjectName = shortcutItem->data(1, Qt::UserRole).toString(); // handle local shortcut QKeySequence keySequence = keyWidget->keySequence(); @@ -1971,11 +1749,10 @@ void SettingsDialog::storeShortcutSettings() { /** * Selects a value in a list widget, that is hidden in the whatsThis parameter */ -void SettingsDialog::selectListWidgetValue(QListWidget *listWidget, - const QString &value) { +void SettingsDialog::selectListWidgetValue(QListWidget *listWidget, const QString &value) { // get all items from the list widget - QList<QListWidgetItem *> items = listWidget->findItems( - QStringLiteral("*"), Qt::MatchWrap | Qt::MatchWildcard); + QList<QListWidgetItem *> items = + listWidget->findItems(QStringLiteral("*"), Qt::MatchWrap | Qt::MatchWildcard); // select the right item in the selector Q_FOREACH (QListWidgetItem *item, items) { if (item->whatsThis() == value) { @@ -1992,11 +1769,10 @@ void SettingsDialog::selectListWidgetValue(QListWidget *listWidget, * Checks if a value, that is hidden in the whatsThis parameter exists in a * list widget */ -bool SettingsDialog::listWidgetValueExists(QListWidget *listWidget, - const QString &value) { +bool SettingsDialog::listWidgetValueExists(QListWidget *listWidget, const QString &value) { // get all items from the list widget - QList<QListWidgetItem *> items = listWidget->findItems( - QStringLiteral("*"), Qt::MatchWrap | Qt::MatchWildcard); + QList<QListWidgetItem *> items = + listWidget->findItems(QStringLiteral("*"), Qt::MatchWrap | Qt::MatchWildcard); // checks if the value exists Q_FOREACH (QListWidgetItem *item, items) { if (item->whatsThis() == value) { @@ -2022,8 +1798,7 @@ QString SettingsDialog::getSelectedListWidgetValue(QListWidget *listWidget) { } void SettingsDialog::setFontLabel(QLineEdit *label, const QFont &font) { - label->setText(font.family() + " (" + QString::number(font.pointSize()) + - ")"); + label->setText(font.family() + " (" + QString::number(font.pointSize()) + ")"); label->setFont(font); } @@ -2031,8 +1806,8 @@ void SettingsDialog::outputSettings() { // store some data for Utils::Misc::generateDebugInformation storeOwncloudDebugData(); - QString output = Utils::Misc::generateDebugInformation( - ui->gitHubLineBreaksCheckBox->isChecked()); + QString output = + Utils::Misc::generateDebugInformation(ui->gitHubLineBreaksCheckBox->isChecked()); ui->debugInfoTextEdit->setPlainText(output); } @@ -2045,8 +1820,7 @@ void SettingsDialog::outputSettings() { * @param appVersion * @param serverVersion */ -void SettingsDialog::connectTestCallback(bool appIsValid, QString appVersion, - QString serverVersion, +void SettingsDialog::connectTestCallback(bool appIsValid, QString appVersion, QString serverVersion, QString notesPathExistsText, QString connectionErrorMessage) { this->appIsValid = appIsValid; @@ -2060,15 +1834,13 @@ void SettingsDialog::connectTestCallback(bool appIsValid, QString appVersion, if (appIsValid) { ui->connectionTestLabel->setStyleSheet(QStringLiteral("color: green;")); - ui->connectionTestLabel->setText( - tr("The connection was made successfully!\n" - "Server version: %1\nQOwnNotesAPI version: %2") - .arg(serverVersion, appVersion)); + ui->connectionTestLabel->setText(tr("The connection was made successfully!\n" + "Server version: %1\nQOwnNotesAPI version: %2") + .arg(serverVersion, appVersion)); } else { // hide password if (!ui->passwordEdit->text().isEmpty()) { - connectionErrorMessage.replace(ui->passwordEdit->text(), - QLatin1String("***")); + connectionErrorMessage.replace(ui->passwordEdit->text(), QLatin1String("***")); } ui->connectionTestLabel->setStyleSheet(QStringLiteral("color: red;")); @@ -2090,8 +1862,7 @@ void SettingsDialog::connectTestCallback(bool appIsValid, QString appVersion, * @param text * @param color */ -void SettingsDialog::setOKLabelData(int number, const QString &text, - OKLabelStatus status) { +void SettingsDialog::setOKLabelData(int number, const QString &text, OKLabelStatus status) { QLabel *label; switch (number) { @@ -2142,12 +1913,11 @@ void SettingsDialog::setOKLabelData(int number, const QString &text, label->setStyleSheet("color: " + color); } -void SettingsDialog::refreshTodoCalendarList( - const QList<CalDAVCalendarData> &items, bool forceReadCheckedState) { +void SettingsDialog::refreshTodoCalendarList(const QList<CalDAVCalendarData> &items, + bool forceReadCheckedState) { // we want to read the checked state from the settings if the // tasks calendar list was not empty - bool readCheckedState = - forceReadCheckedState ? true : ui->todoCalendarListWidget->count() > 0; + bool readCheckedState = forceReadCheckedState ? true : ui->todoCalendarListWidget->count() > 0; // clear the tasks calendar list ui->todoCalendarListWidget->clear(); @@ -2158,12 +1928,10 @@ void SettingsDialog::refreshTodoCalendarList( QSettings settings; QStringList todoCalendarEnabledList = - settings.value(QStringLiteral("ownCloud/todoCalendarEnabledList")) - .toStringList(); + settings.value(QStringLiteral("ownCloud/todoCalendarEnabledList")).toStringList(); - QUrl serverUrl(ui->calDavCalendarRadioButton->isChecked() - ? ui->calDavServerUrlEdit->text() - : ui->serverUrlEdit->text()); + QUrl serverUrl(ui->calDavCalendarRadioButton->isChecked() ? ui->calDavServerUrlEdit->text() + : ui->serverUrlEdit->text()); // return if server url isn't valid if (!serverUrl.isValid()) { @@ -2174,9 +1942,8 @@ void SettingsDialog::refreshTodoCalendarList( QString serverUrlPath = serverUrl.path(); if (!serverUrlPath.isEmpty()) { // remove the path from the end because we already got it in the url - serverUrlText.replace( - QRegularExpression(QRegularExpression::escape(serverUrlPath) + "$"), - QLatin1String("")); + serverUrlText.replace(QRegularExpression(QRegularExpression::escape(serverUrlPath) + "$"), + QLatin1String("")); } QListIterator<CalDAVCalendarData> itr(items); @@ -2219,13 +1986,12 @@ void SettingsDialog::refreshTodoCalendarList( // eventually check if item was checked Qt::CheckState checkedState = readCheckedState - ? (todoCalendarEnabledList.contains(name) ? Qt::Checked - : Qt::Unchecked) + ? (todoCalendarEnabledList.contains(name) ? Qt::Checked : Qt::Unchecked) : Qt::Checked; item->setCheckState(checkedState); - item->setFlags(Qt::ItemIsDragEnabled | Qt::ItemIsDropEnabled | - Qt::ItemIsEnabled | Qt::ItemIsUserCheckable); + item->setFlags(Qt::ItemIsDragEnabled | Qt::ItemIsDropEnabled | Qt::ItemIsEnabled | + Qt::ItemIsUserCheckable); item->setToolTip(url); ui->todoCalendarListWidget->addItem(item); } @@ -2244,8 +2010,7 @@ void SettingsDialog::on_buttonBox_clicked(QAbstractButton *button) { } void SettingsDialog::on_ownCloudServerAppPageButton_clicked() { - QDesktopServices::openUrl( - QUrl(ui->serverUrlEdit->text() + "/index.php/settings/apps")); + QDesktopServices::openUrl(QUrl(ui->serverUrlEdit->text() + "/index.php/settings/apps")); } void SettingsDialog::on_noteTextEditButton_clicked() { @@ -2271,9 +2036,8 @@ void SettingsDialog::on_noteTextEditButton_clicked() { void SettingsDialog::on_noteTextEditCodeButton_clicked() { bool ok; - QFont font = - Utils::Gui::fontDialogGetFont(&ok, noteTextEditCodeFont, this, - QString(), QFontDialog::MonospacedFonts); + QFont font = Utils::Gui::fontDialogGetFont(&ok, noteTextEditCodeFont, this, QString(), + QFontDialog::MonospacedFonts); if (ok) { noteTextEditCodeFont = font; setFontLabel(ui->noteTextEditCodeFontLabel, noteTextEditCodeFont); @@ -2300,9 +2064,8 @@ void SettingsDialog::on_noteTextViewButton_clicked() { void SettingsDialog::on_noteTextViewCodeButton_clicked() { bool ok; - QFont font = - Utils::Gui::fontDialogGetFont(&ok, noteTextViewCodeFont, this, - QString(), QFontDialog::MonospacedFonts); + QFont font = Utils::Gui::fontDialogGetFont(&ok, noteTextViewCodeFont, this, QString(), + QFontDialog::MonospacedFonts); if (ok) { noteTextViewCodeFont = font; setFontLabel(ui->noteTextViewCodeFontLabel, noteTextViewCodeFont); @@ -2329,33 +2092,31 @@ void SettingsDialog::reloadCalendarList() { ownCloud->settingsGetCalendarList(this); } -void SettingsDialog::on_defaultOwnCloudCalendarRadioButton_toggled( - bool checked) { +void SettingsDialog::on_defaultOwnCloudCalendarRadioButton_toggled(bool checked) { if (checked) { on_reloadCalendarListButton_clicked(); } } -void SettingsDialog::on_legacyOwnCloudCalendarRadioButton_toggled( - bool checked) { +void SettingsDialog::on_legacyOwnCloudCalendarRadioButton_toggled(bool checked) { if (checked) { on_reloadCalendarListButton_clicked(); } } void SettingsDialog::on_reinitializeDatabaseButton_clicked() { - if (QMessageBox::information( - this, tr("Database"), - tr("Do you really want to clear the local database? " - "This will also remove your configured note " - "folders and your cached todo items!"), - tr("Clear &database"), tr("&Cancel"), QString(), 1) == 0) { + if (QMessageBox::information(this, tr("Database"), + tr("Do you really want to clear the local database? " + "This will also remove your configured note " + "folders and your cached todo items!"), + tr("Clear &database"), tr("&Cancel"), QString(), 1) == 0) { DatabaseService::reinitializeDiskDatabase(); NoteFolder::migrateToNoteFolders(); - Utils::Gui::information(this, tr("Database"), - tr("The Database was reinitialized. Please restart the application now!"), - QStringLiteral("database-reinitialized")); + Utils::Gui::information( + this, tr("Database"), + tr("The Database was reinitialized. Please restart the application now!"), + QStringLiteral("database-reinitialized")); } } @@ -2363,11 +2124,10 @@ void SettingsDialog::on_reinitializeDatabaseButton_clicked() { * @brief Stores the debug information to a markdown file */ void SettingsDialog::on_saveDebugInfoButton_clicked() { - Utils::Gui::information( - this, tr("Debug information"), - tr("Please don't use this in the issue tracker, " - "copy the debug information text directly into the issue."), - QStringLiteral("debug-save")); + Utils::Gui::information(this, tr("Debug information"), + tr("Please don't use this in the issue tracker, " + "copy the debug information text directly into the issue."), + QStringLiteral("debug-save")); FileDialog dialog(QStringLiteral("SaveDebugInfo")); dialog.setFileMode(QFileDialog::AnyFile); @@ -2399,13 +2159,12 @@ void SettingsDialog::on_saveDebugInfoButton_clicked() { void SettingsDialog::on_appMetricsCheckBox_toggled(bool checked) { if (checked) { int reply; - reply = QMessageBox::question( - this, tr("Disable usage tracking"), - tr("Anonymous usage data helps to decide what parts of " - "QOwnNotes to improve next and to find and fix bugs." - "<br />Please disable it only if you really can't live" - " with it.<br /><br />Really disable usage tracking?"), - QMessageBox::Yes | QMessageBox::No, QMessageBox::No); + reply = QMessageBox::question(this, tr("Disable usage tracking"), + tr("Anonymous usage data helps to decide what parts of " + "QOwnNotes to improve next and to find and fix bugs." + "<br />Please disable it only if you really can't live" + " with it.<br /><br />Really disable usage tracking?"), + QMessageBox::Yes | QMessageBox::No, QMessageBox::No); if (reply == QMessageBox::No) { const QSignalBlocker blocker(ui->appMetricsCheckBox); Q_UNUSED(blocker) @@ -2418,12 +2177,11 @@ void SettingsDialog::on_appMetricsCheckBox_toggled(bool checked) { * Allows the user to clear all settings and the database and exit the app */ void SettingsDialog::on_clearAppDataAndExitButton_clicked() { - if (QMessageBox::information( - this, tr("Clear app data and exit"), - tr("Do you really want to clear all settings, remove the " - "database and exit QOwnNotes?\n\n" - "Your notes will stay intact!"), - tr("Clear and &exit"), tr("&Cancel"), QString(), 1) == 0) { + if (QMessageBox::information(this, tr("Clear app data and exit"), + tr("Do you really want to clear all settings, remove the " + "database and exit QOwnNotes?\n\n" + "Your notes will stay intact!"), + tr("Clear and &exit"), tr("&Cancel"), QString(), 1) == 0) { QSettings settings; settings.clear(); DatabaseService::removeDiskDatabase(); @@ -2562,8 +2320,8 @@ void SettingsDialog::on_ignoreSSLErrorsCheckBox_toggled(bool checked) { * Does the note folder page setup */ void SettingsDialog::setupNoteFolderPage() { -// const QSignalBlocker blocker(ui->noteFolderListWidget); - //Q_UNUSED(blocker) + // const QSignalBlocker blocker(ui->noteFolderListWidget); + // Q_UNUSED(blocker) // hide the owncloud server settings ui->noteFolderEditFrame->setEnabled(NoteFolder::countAll() > 0); @@ -2590,16 +2348,14 @@ void SettingsDialog::setupNoteFolderPage() { ui->noteFolderRemoveButton->setEnabled(noteFoldersCount > 1); // set local path placeholder text - ui->noteFolderLocalPathLineEdit->setPlaceholderText( - Utils::Misc::defaultNotesPath()); + ui->noteFolderLocalPathLineEdit->setPlaceholderText(Utils::Misc::defaultNotesPath()); noteFolderRemotePathTreeStatusBar = new QStatusBar(this); - ui->noteFolderRemotePathTreeWidgetFrame->layout()->addWidget( - noteFolderRemotePathTreeStatusBar); + ui->noteFolderRemotePathTreeWidgetFrame->layout()->addWidget(noteFolderRemotePathTreeStatusBar); } -void SettingsDialog::on_noteFolderListWidget_currentItemChanged( - QListWidgetItem *current, QListWidgetItem *previous) { +void SettingsDialog::on_noteFolderListWidget_currentItemChanged(QListWidgetItem *current, + QListWidgetItem *previous) { Q_UNUSED(previous) setNoteFolderRemotePathTreeWidgetFrameVisibility(false); @@ -2608,24 +2364,19 @@ void SettingsDialog::on_noteFolderListWidget_currentItemChanged( _selectedNoteFolder = NoteFolder::fetch(noteFolderId); if (_selectedNoteFolder.isFetched()) { ui->noteFolderNameLineEdit->setText(_selectedNoteFolder.getName()); - ui->noteFolderLocalPathLineEdit->setText( - _selectedNoteFolder.getLocalPath()); - ui->noteFolderRemotePathLineEdit->setText( - _selectedNoteFolder.getRemotePath()); - ui->noteFolderShowSubfoldersCheckBox->setChecked( - _selectedNoteFolder.isShowSubfolders()); + ui->noteFolderLocalPathLineEdit->setText(_selectedNoteFolder.getLocalPath()); + ui->noteFolderRemotePathLineEdit->setText(_selectedNoteFolder.getRemotePath()); + ui->noteFolderShowSubfoldersCheckBox->setChecked(_selectedNoteFolder.isShowSubfolders()); ui->allowDifferentNoteFileNameCheckBox->setChecked( - _selectedNoteFolder.settingsValue(QStringLiteral("allowDifferentNoteFileName")).toBool()); - ui->noteFolderGitCommitCheckBox->setChecked( - _selectedNoteFolder.isUseGit()); - Utils::Gui::setComboBoxIndexByUserData( - ui->noteFolderCloudConnectionComboBox, - _selectedNoteFolder.getCloudConnectionId()); + _selectedNoteFolder.settingsValue(QStringLiteral("allowDifferentNoteFileName")) + .toBool()); + ui->noteFolderGitCommitCheckBox->setChecked(_selectedNoteFolder.isUseGit()); + Utils::Gui::setComboBoxIndexByUserData(ui->noteFolderCloudConnectionComboBox, + _selectedNoteFolder.getCloudConnectionId()); const QSignalBlocker blocker(ui->noteFolderActiveCheckBox); Q_UNUSED(blocker) - ui->noteFolderActiveCheckBox->setChecked( - _selectedNoteFolder.isCurrent()); + ui->noteFolderActiveCheckBox->setChecked(_selectedNoteFolder.isCurrent()); } } @@ -2647,8 +2398,7 @@ void SettingsDialog::on_noteFolderAddButton_clicked() { ui->noteFolderListWidget->addItem(item); // set the current row - ui->noteFolderListWidget->setCurrentRow( - ui->noteFolderListWidget->count() - 1); + ui->noteFolderListWidget->setCurrentRow(ui->noteFolderListWidget->count() - 1); // enable the remove button ui->noteFolderRemoveButton->setEnabled(true); @@ -2667,35 +2417,31 @@ void SettingsDialog::on_noteFolderRemoveButton_clicked() { return; } - if (Utils::Gui::question( - this, tr("Remove note folder"), - tr("Remove the current note folder <strong>%1</strong>?") - .arg(_selectedNoteFolder.getName()), - QStringLiteral("remove-note-folder")) == QMessageBox::Yes) { + if (Utils::Gui::question(this, tr("Remove note folder"), + tr("Remove the current note folder <strong>%1</strong>?") + .arg(_selectedNoteFolder.getName()), + QStringLiteral("remove-note-folder")) == QMessageBox::Yes) { bool wasCurrent = _selectedNoteFolder.isCurrent(); QSettings settings; // remove saved searches - QString settingsKey = "savedSearches/noteFolder-" + - QString::number(_selectedNoteFolder.getId()); + QString settingsKey = + "savedSearches/noteFolder-" + QString::number(_selectedNoteFolder.getId()); settings.remove(settingsKey); // remove tree widget expand state setting - settingsKey = NoteSubFolder::treeWidgetExpandStateSettingsKey( - _selectedNoteFolder.getId()); + settingsKey = NoteSubFolder::treeWidgetExpandStateSettingsKey(_selectedNoteFolder.getId()); settings.remove(settingsKey); // remove the note folder from the database _selectedNoteFolder.remove(); // remove the list item - ui->noteFolderListWidget->takeItem( - ui->noteFolderListWidget->currentRow()); + ui->noteFolderListWidget->takeItem(ui->noteFolderListWidget->currentRow()); // disable the remove button if there is only one item left - ui->noteFolderRemoveButton->setEnabled( - ui->noteFolderListWidget->count() > 1); + ui->noteFolderRemoveButton->setEnabled(ui->noteFolderListWidget->count() > 1); // if the removed note folder was the current folder we set the first // note folder as new current one @@ -2712,9 +2458,7 @@ void SettingsDialog::on_noteFolderRemoveButton_clicked() { * Updates the name of the current note folder edit */ void SettingsDialog::on_noteFolderNameLineEdit_editingFinished() { - QString text = ui->noteFolderNameLineEdit->text() - .remove(QStringLiteral("\n")) - .trimmed(); + QString text = ui->noteFolderNameLineEdit->text().remove(QStringLiteral("\n")).trimmed(); text.truncate(50); // fallback to directory name in case name edit is empty @@ -2749,8 +2493,7 @@ void SettingsDialog::on_noteFolderRemotePathLineEdit_editingFinished() { void SettingsDialog::on_noteFolderLocalPathButton_clicked() { QString dir = QFileDialog::getExistingDirectory( - this, - tr("Please select the folder where your notes will get stored to"), + this, tr("Please select the folder where your notes will get stored to"), _selectedNoteFolder.getLocalPath(), QFileDialog::ShowDirsOnly); QDir d = QDir(dir); @@ -2784,11 +2527,10 @@ void SettingsDialog::on_noteFolderRemotePathButton_clicked() { setNoteFolderRemotePathTreeWidgetFrameVisibility(true); - noteFolderRemotePathTreeStatusBar->showMessage( - tr("Loading folders from server")); + noteFolderRemotePathTreeStatusBar->showMessage(tr("Loading folders from server")); - OwnCloudService *ownCloud = OwnCloudService::instance( - true, _selectedNoteFolder.getCloudConnectionId()); + OwnCloudService *ownCloud = + OwnCloudService::instance(true, _selectedNoteFolder.getCloudConnectionId()); ownCloud->settingsGetFileList(this, QLatin1String("")); } @@ -2812,16 +2554,15 @@ void SettingsDialog::setNoteFolderRemotePathList(QStringList pathList) { } } -void SettingsDialog::addPathToNoteFolderRemotePathTreeWidget( - QTreeWidgetItem *parent, const QString &path) { +void SettingsDialog::addPathToNoteFolderRemotePathTreeWidget(QTreeWidgetItem *parent, + const QString &path) { if (path.isEmpty()) { return; } QStringList pathPartList = path.split(QStringLiteral("/")); QString pathPart = pathPartList.takeFirst(); - QTreeWidgetItem *item = - findNoteFolderRemotePathTreeWidgetItem(parent, pathPart); + QTreeWidgetItem *item = findNoteFolderRemotePathTreeWidgetItem(parent, pathPart); const QSignalBlocker blocker(ui->noteFolderRemotePathTreeWidget); Q_UNUSED(blocker) @@ -2838,18 +2579,15 @@ void SettingsDialog::addPathToNoteFolderRemotePathTreeWidget( } if (pathPartList.count() > 0) { - addPathToNoteFolderRemotePathTreeWidget( - item, pathPartList.join(QStringLiteral("/"))); + addPathToNoteFolderRemotePathTreeWidget(item, pathPartList.join(QStringLiteral("/"))); } } -QTreeWidgetItem *SettingsDialog::findNoteFolderRemotePathTreeWidgetItem( - QTreeWidgetItem *parent, const QString &text) { +QTreeWidgetItem *SettingsDialog::findNoteFolderRemotePathTreeWidgetItem(QTreeWidgetItem *parent, + const QString &text) { if (parent == nullptr) { - for (int i = 0; - i < ui->noteFolderRemotePathTreeWidget->topLevelItemCount(); i++) { - QTreeWidgetItem *item = - ui->noteFolderRemotePathTreeWidget->topLevelItem(i); + for (int i = 0; i < ui->noteFolderRemotePathTreeWidget->topLevelItemCount(); i++) { + QTreeWidgetItem *item = ui->noteFolderRemotePathTreeWidget->topLevelItem(i); if (item->text(0) == text) { return item; } @@ -2870,18 +2608,16 @@ void SettingsDialog::on_noteFolderRemotePathTreeWidget_currentItemChanged( QTreeWidgetItem *current, QTreeWidgetItem *previous) { Q_UNUSED(previous) - QString folderName = - generatePathFromCurrentNoteFolderRemotePathItem(current); + QString folderName = generatePathFromCurrentNoteFolderRemotePathItem(current); noteFolderRemotePathTreeStatusBar->showMessage( tr("Loading folders in '%1' from server").arg(current->text(0))); - OwnCloudService *ownCloud = OwnCloudService::instance( - true, _selectedNoteFolder.getCloudConnectionId()); + OwnCloudService *ownCloud = + OwnCloudService::instance(true, _selectedNoteFolder.getCloudConnectionId()); ownCloud->settingsGetFileList(this, folderName); } -void SettingsDialog::on_noteFolderCloudConnectionComboBox_currentIndexChanged( - int index) { +void SettingsDialog::on_noteFolderCloudConnectionComboBox_currentIndexChanged(int index) { Q_UNUSED(index) _selectedNoteFolder.setCloudConnectionId( ui->noteFolderCloudConnectionComboBox->currentData().toInt()); @@ -2909,23 +2645,21 @@ void SettingsDialog::on_useOwnCloudPathButton_clicked() { /** * Recursively generates the path string from the tree widget items */ -QString SettingsDialog::generatePathFromCurrentNoteFolderRemotePathItem( - QTreeWidgetItem *item) { +QString SettingsDialog::generatePathFromCurrentNoteFolderRemotePathItem(QTreeWidgetItem *item) { if (item == nullptr) { return QString(); } QTreeWidgetItem *parent = item->parent(); if (parent != nullptr) { - return generatePathFromCurrentNoteFolderRemotePathItem(parent) + - QStringLiteral("/") + item->text(0); + return generatePathFromCurrentNoteFolderRemotePathItem(parent) + QStringLiteral("/") + + item->text(0); } return item->text(0); } -void SettingsDialog::setNoteFolderRemotePathTreeWidgetFrameVisibility( - bool visible) { +void SettingsDialog::setNoteFolderRemotePathTreeWidgetFrameVisibility(bool visible) { ui->noteFolderRemotePathTreeWidgetFrame->setVisible(visible); ui->noteFolderVerticalSpacerFrame->setVisible(!visible); @@ -2941,48 +2675,38 @@ void SettingsDialog::setupScriptingPage() { // reload the script list reloadScriptList(); - QString issueUrl = - QStringLiteral("https://github.com/pbek/QOwnNotes/issues"); - QString documentationUrl = QStringLiteral( - "https://www.qownnotes.org/scripting/"); - ui->scriptInfoLabel->setText( - tr("Take a look at the <a href=\"%1\">Scripting documentation</a> " - "to get started fast.") - .arg(documentationUrl) + - "<br>" + - tr("If you need access to a certain functionality in " - "QOwnNotes please open an issue on the " - "<a href=\"%1\"> QOwnNotes issue page</a>.") - .arg(issueUrl)); + QString issueUrl = QStringLiteral("https://github.com/pbek/QOwnNotes/issues"); + QString documentationUrl = QStringLiteral("https://www.qownnotes.org/scripting/"); + ui->scriptInfoLabel->setText(tr("Take a look at the <a href=\"%1\">Scripting documentation</a> " + "to get started fast.") + .arg(documentationUrl) + + "<br>" + + tr("If you need access to a certain functionality in " + "QOwnNotes please open an issue on the " + "<a href=\"%1\"> QOwnNotes issue page</a>.") + .arg(issueUrl)); /* * Setup the "add script" button menu */ auto *addScriptMenu = new QMenu(this); - QAction *searchScriptAction = - addScriptMenu->addAction(tr("Search script repository")); - searchScriptAction->setIcon( - QIcon::fromTheme(QStringLiteral("edit-find"), - QIcon(":icons/breeze-qownnotes/16x16/edit-find.svg"))); + QAction *searchScriptAction = addScriptMenu->addAction(tr("Search script repository")); + searchScriptAction->setIcon(QIcon::fromTheme( + QStringLiteral("edit-find"), QIcon(":icons/breeze-qownnotes/16x16/edit-find.svg"))); searchScriptAction->setToolTip( tr("Find a script in the script " "repository")); - connect(searchScriptAction, SIGNAL(triggered()), this, - SLOT(searchScriptInRepository())); + connect(searchScriptAction, SIGNAL(triggered()), this, SLOT(searchScriptInRepository())); - QAction *updateScriptAction = - addScriptMenu->addAction(tr("Check for script updates")); + QAction *updateScriptAction = addScriptMenu->addAction(tr("Check for script updates")); updateScriptAction->setIcon(QIcon::fromTheme( - QStringLiteral("svn-update"), - QIcon(":icons/breeze-qownnotes/16x16/svn-update.svg"))); - connect(updateScriptAction, SIGNAL(triggered()), this, - SLOT(checkForScriptUpdates())); + QStringLiteral("svn-update"), QIcon(":icons/breeze-qownnotes/16x16/svn-update.svg"))); + connect(updateScriptAction, SIGNAL(triggered()), this, SLOT(checkForScriptUpdates())); QAction *addAction = addScriptMenu->addAction(tr("Add local script")); - addAction->setIcon(QIcon::fromTheme( - QStringLiteral("document-new"), - QIcon(":icons/breeze-qownnotes/16x16/document-new.svg"))); + addAction->setIcon(QIcon::fromTheme(QStringLiteral("document-new"), + QIcon(":icons/breeze-qownnotes/16x16/document-new.svg"))); addAction->setToolTip(tr("Add an existing, local script")); connect(addAction, SIGNAL(triggered()), this, SLOT(addLocalScript())); @@ -3003,8 +2727,7 @@ void SettingsDialog::reloadScriptList() const { auto *item = new QListWidgetItem(script.getName()); item->setData(Qt::UserRole, script.getId()); item->setFlags(item->flags() | Qt::ItemIsUserCheckable); - item->setCheckState(script.getEnabled() ? Qt::Checked - : Qt::Unchecked); + item->setCheckState(script.getEnabled() ? Qt::Checked : Qt::Unchecked); ui->scriptListWidget->addItem(item); } @@ -3060,8 +2783,7 @@ void SettingsDialog::on_scriptRemoveButton_clicked() { if (Utils::Gui::question( this, tr("Remove script"), - tr("Remove the current script <strong>%1</strong>?") - .arg(_selectedScript.getName()), + tr("Remove the current script <strong>%1</strong>?").arg(_selectedScript.getName()), QStringLiteral("remove-script")) == QMessageBox::Yes) { // remove the script from the database _selectedScript.remove(); @@ -3154,8 +2876,8 @@ void SettingsDialog::on_scriptPathButton_clicked() { /** * Loads the current script in the UI when the current item changed */ -void SettingsDialog::on_scriptListWidget_currentItemChanged( - QListWidgetItem *current, QListWidgetItem *previous) { +void SettingsDialog::on_scriptListWidget_currentItemChanged(QListWidgetItem *current, + QListWidgetItem *previous) { Q_UNUSED(current) Q_UNUSED(previous) @@ -3177,8 +2899,7 @@ void SettingsDialog::reloadCurrentScriptPage() { int scriptId = item->data(Qt::UserRole).toInt(); _selectedScript = Script::fetch(scriptId); if (_selectedScript.isFetched()) { - ui->scriptNameLabel->setText("<b>" + _selectedScript.getName() + - "</b>"); + ui->scriptNameLabel->setText("<b>" + _selectedScript.getName() + "</b>"); ui->scriptPathLineEdit->setText(_selectedScript.getScriptPath()); ui->scriptEditFrame->setEnabled(true); @@ -3208,8 +2929,7 @@ void SettingsDialog::reloadCurrentScriptPage() { // get the registered script settings variables QList<QVariant> variables = - ScriptingService::instance()->getSettingsVariables( - _selectedScript.getId()); + ScriptingService::instance()->getSettingsVariables(_selectedScript.getId()); bool hasScriptSettings = variables.count() > 0; ui->scriptSettingsFrame->setVisible(hasScriptSettings); @@ -3219,7 +2939,9 @@ void SettingsDialog::reloadCurrentScriptPage() { // scriptSettingsFrame QList<ScriptSettingWidget *> widgets = ui->scriptSettingsFrame->findChildren<ScriptSettingWidget *>(); - Q_FOREACH (ScriptSettingWidget *widget, widgets) { delete widget; } + Q_FOREACH (ScriptSettingWidget *widget, widgets) { + delete widget; + } foreach (QVariant variable, variables) { QMap<QString, QVariant> varMap = variable.toMap(); @@ -3230,8 +2952,7 @@ void SettingsDialog::reloadCurrentScriptPage() { // QString name = varMap["name"].toString(); - ui->scriptSettingsFrame->layout()->addWidget( - scriptSettingWidget); + ui->scriptSettingsFrame->layout()->addWidget(scriptSettingWidget); } } @@ -3256,11 +2977,9 @@ void SettingsDialog::validateCurrentScript() { // check the script validity if the path is not empty if (!path.isEmpty()) { QString errorMessage; - bool result = - ScriptingService::validateScript(_selectedScript, errorMessage); - QString validationText = - result ? tr("Your script seems to be valid") - : tr("There were script errors:\n%1").arg(errorMessage); + bool result = ScriptingService::validateScript(_selectedScript, errorMessage); + QString validationText = result ? tr("Your script seems to be valid") + : tr("There were script errors:\n%1").arg(errorMessage); ui->scriptValidationLabel->setText(validationText); ui->scriptValidationLabel->setStyleSheet( QStringLiteral("color: %1;").arg(result ? "green" : "red")); @@ -3327,17 +3046,16 @@ void SettingsDialog::on_scriptReloadEngineButton_clicked() { void SettingsDialog::on_addCustomNoteFileExtensionButton_clicked() { bool ok; QString fileExtension; - fileExtension = QInputDialog::getText( - this, tr("File extension"), tr("Please enter a new note file extension:"), - QLineEdit::Normal, fileExtension, &ok); + fileExtension = QInputDialog::getText(this, tr("File extension"), + tr("Please enter a new note file extension:"), + QLineEdit::Normal, fileExtension, &ok); if (!ok) { return; } // make sure the file extension doesn't start with a point - fileExtension = Utils::Misc::removeIfStartsWith(std::move(fileExtension), - QStringLiteral(".")); + fileExtension = Utils::Misc::removeIfStartsWith(std::move(fileExtension), QStringLiteral(".")); QListWidgetItem *item = addCustomNoteFileExtension(fileExtension); @@ -3349,12 +3067,11 @@ void SettingsDialog::on_addCustomNoteFileExtensionButton_clicked() { /** * Adds a custom note file extension */ -QListWidgetItem *SettingsDialog::addCustomNoteFileExtension( - QString fileExtension) { +QListWidgetItem *SettingsDialog::addCustomNoteFileExtension(QString fileExtension) { fileExtension = fileExtension.trimmed(); - if (ui->defaultNoteFileExtensionListWidget->findItems( - fileExtension, Qt::MatchExactly).count() > 0) { + if (ui->defaultNoteFileExtensionListWidget->findItems(fileExtension, Qt::MatchExactly).count() > + 0) { return nullptr; } @@ -3383,10 +3100,11 @@ void SettingsDialog::on_removeCustomNoteFileExtensionButton_clicked() { auto *item = ui->defaultNoteFileExtensionListWidget->currentItem(); if (Utils::Gui::question(this, tr("Remove note file extension"), - tr("Do you really want to remove the note file extension " - "<strong>%1</strong>? You will not see files with this " - "extension in the note list any more!").arg(item->text()), - QStringLiteral("remove-note-file-extension")) != QMessageBox::Yes) { + tr("Do you really want to remove the note file extension " + "<strong>%1</strong>? You will not see files with this " + "extension in the note list any more!") + .arg(item->text()), + QStringLiteral("remove-note-file-extension")) != QMessageBox::Yes) { return; } @@ -3399,27 +3117,22 @@ void SettingsDialog::on_removeCustomNoteFileExtensionButton_clicked() { /** * Updates a custom file extension */ -void SettingsDialog::on_defaultNoteFileExtensionListWidget_itemChanged( - QListWidgetItem *item) { +void SettingsDialog::on_defaultNoteFileExtensionListWidget_itemChanged(QListWidgetItem *item) { // make sure the file extension doesn't start with a point QString fileExtension = - Utils::Misc::removeIfStartsWith(item->text(), QStringLiteral(".")) - .trimmed(); + Utils::Misc::removeIfStartsWith(item->text(), QStringLiteral(".")).trimmed(); if (fileExtension != item->text()) { item->setText(fileExtension); } } -void SettingsDialog::on_darkModeCheckBox_toggled() { - handleDarkModeCheckBoxToggled(true, true); -} +void SettingsDialog::on_darkModeCheckBox_toggled() { handleDarkModeCheckBoxToggled(true, true); } /** * Toggles the dark mode colors check box with the dark mode checkbox */ -void SettingsDialog::handleDarkModeCheckBoxToggled(bool updateCheckBoxes, - bool updateSchema) { +void SettingsDialog::handleDarkModeCheckBoxToggled(bool updateCheckBoxes, bool updateSchema) { bool checked = ui->darkModeCheckBox->isChecked(); ui->darkModeColorsCheckBox->setEnabled(!checked); @@ -3450,10 +3163,8 @@ void SettingsDialog::on_noteFolderShowSubfoldersCheckBox_toggled(bool checked) { _selectedNoteFolder.store(); } -void SettingsDialog::on_allowDifferentNoteFileNameCheckBox_toggled(bool checked) -{ - _selectedNoteFolder.setSettingsValue(QStringLiteral("allowDifferentNoteFileName"), - checked); +void SettingsDialog::on_allowDifferentNoteFileNameCheckBox_toggled(bool checked) { + _selectedNoteFolder.setSettingsValue(QStringLiteral("allowDifferentNoteFileName"), checked); } /** @@ -3469,41 +3180,38 @@ void SettingsDialog::on_gitHubLineBreaksCheckBox_toggled(bool checked) { * * @param arg1 */ -void SettingsDialog::on_shortcutSearchLineEdit_textChanged( - const QString &arg1) { +void SettingsDialog::on_shortcutSearchLineEdit_textChanged(const QString &arg1) { // get all items - QList<QTreeWidgetItem *> allItems = ui->shortcutTreeWidget->findItems( - QString(), Qt::MatchContains | Qt::MatchRecursive); + QList<QTreeWidgetItem *> allItems = + ui->shortcutTreeWidget->findItems(QString(), Qt::MatchContains | Qt::MatchRecursive); // search text if at least one character was entered if (arg1.count() >= 1) { // search for items in the description - QList<QTreeWidgetItem *> foundItems = ui->shortcutTreeWidget->findItems( - arg1, Qt::MatchContains | Qt::MatchRecursive); + QList<QTreeWidgetItem *> foundItems = + ui->shortcutTreeWidget->findItems(arg1, Qt::MatchContains | Qt::MatchRecursive); // hide all not found items Q_FOREACH (QTreeWidgetItem *item, allItems) { bool foundKeySequence = false; - auto *keyWidget = dynamic_cast<QKeySequenceWidget *>( - ui->shortcutTreeWidget->itemWidget(item, 1)); + auto *keyWidget = + dynamic_cast<QKeySequenceWidget *>(ui->shortcutTreeWidget->itemWidget(item, 1)); // search in the local shortcut text if (keyWidget != nullptr) { QKeySequence keySequence = keyWidget->keySequence(); - foundKeySequence = - keySequence.toString().contains(arg1, Qt::CaseInsensitive); + foundKeySequence = keySequence.toString().contains(arg1, Qt::CaseInsensitive); } // search in the global shortcut text if (!foundKeySequence) { - keyWidget = dynamic_cast<QKeySequenceWidget *>( - ui->shortcutTreeWidget->itemWidget(item, 2)); + keyWidget = + dynamic_cast<QKeySequenceWidget *>(ui->shortcutTreeWidget->itemWidget(item, 2)); if (keyWidget != nullptr) { QKeySequence keySequence = keyWidget->keySequence(); - foundKeySequence = - keySequence.toString().contains(arg1, Qt::CaseInsensitive); + foundKeySequence = keySequence.toString().contains(arg1, Qt::CaseInsensitive); } } @@ -3520,12 +3228,14 @@ void SettingsDialog::on_shortcutSearchLineEdit_textChanged( } } else { // show all items otherwise - Q_FOREACH (QTreeWidgetItem *item, allItems) { item->setHidden(false); } + Q_FOREACH (QTreeWidgetItem *item, allItems) { + item->setHidden(false); + } } } -void SettingsDialog::on_settingsTreeWidget_currentItemChanged( - QTreeWidgetItem *current, QTreeWidgetItem *previous) { +void SettingsDialog::on_settingsTreeWidget_currentItemChanged(QTreeWidgetItem *current, + QTreeWidgetItem *previous) { Q_UNUSED(previous) const int currentIndex = current->whatsThis(0).toInt(); @@ -3610,8 +3320,7 @@ void SettingsDialog::initMainSplitter() { // restore tag frame splitter state QSettings settings; QByteArray state = - settings.value(QStringLiteral("SettingsDialog/mainSplitterState")) - .toByteArray(); + settings.value(QStringLiteral("SettingsDialog/mainSplitterState")).toByteArray(); _mainSplitter->restoreState(state); } @@ -3634,10 +3343,8 @@ void SettingsDialog::closeEvent(QCloseEvent *event) { void SettingsDialog::storeOwncloudDebugData() const { QSettings settings; settings.setValue(QStringLiteral("ownCloudInfo/appIsValid"), appIsValid); - settings.setValue(QStringLiteral("ownCloudInfo/notesPathExistsText"), - notesPathExistsText); - settings.setValue(QStringLiteral("ownCloudInfo/serverVersion"), - serverVersion); + settings.setValue(QStringLiteral("ownCloudInfo/notesPathExistsText"), notesPathExistsText); + settings.setValue(QStringLiteral("ownCloudInfo/serverVersion"), serverVersion); settings.setValue(QStringLiteral("ownCloudInfo/connectionErrorMessage"), connectionErrorMessage); } @@ -3698,8 +3405,7 @@ void SettingsDialog::on_toolbarIconSizeResetButton_clicked() { void SettingsDialog::on_ignoreNonTodoCalendarsCheckBox_toggled(bool checked) { QSettings settings; - settings.setValue(QStringLiteral("ownCloud/ignoreNonTodoCalendars"), - checked); + settings.setValue(QStringLiteral("ownCloud/ignoreNonTodoCalendars"), checked); } void SettingsDialog::on_applyToolbarButton_clicked() { @@ -3720,8 +3426,7 @@ void SettingsDialog::on_applyToolbarButton_clicked() { // don't store the custom actions toolbar and toolbars that are // not in the toolbar edit widget any more (for some reason they // are still found by findChildren) - if (name == QLatin1String("customActionsToolbar") || - !toolbarObjectNames.contains(name)) { + if (name == QLatin1String("customActionsToolbar") || !toolbarObjectNames.contains(name)) { continue; } @@ -3738,28 +3443,25 @@ void SettingsDialog::on_applyToolbarButton_clicked() { // settings.remove(""); // settings.endGroup(); - settings.beginWriteArray(QStringLiteral("toolbar"), - toolbarContainers.size()); + settings.beginWriteArray(QStringLiteral("toolbar"), toolbarContainers.size()); for (int i = 0; i < toolbarContainers.size(); i++) { settings.setArrayIndex(i); settings.setValue(QStringLiteral("name"), toolbarContainers[i].name); settings.setValue(QStringLiteral("title"), toolbarContainers[i].title); - settings.setValue(QStringLiteral("items"), - toolbarContainers[i].actions); + settings.setValue(QStringLiteral("items"), toolbarContainers[i].actions); } settings.endArray(); } void SettingsDialog::on_resetToolbarPushButton_clicked() { - if (QMessageBox::information( - this, tr("Reset toolbars and exit"), - tr("Do you really want to reset all toolbars? " - "The application will be closed in the process, the " - "default toolbars will be restored when you start it " - "again."), - tr("Reset and &exit"), tr("&Cancel"), QLatin1String(""), 1) == 0) { + if (QMessageBox::information(this, tr("Reset toolbars and exit"), + tr("Do you really want to reset all toolbars? " + "The application will be closed in the process, the " + "default toolbars will be restored when you start it " + "again."), + tr("Reset and &exit"), tr("&Cancel"), QLatin1String(""), 1) == 0) { QSettings settings; // remove all settings in the group @@ -3787,8 +3489,8 @@ void SettingsDialog::on_imageScaleDownCheckBox_toggled(bool checked) { * @param arg1 */ void SettingsDialog::on_searchLineEdit_textChanged(const QString &arg1) { - QList<QTreeWidgetItem *> allItems = ui->settingsTreeWidget->findItems( - QString(), Qt::MatchContains | Qt::MatchRecursive); + QList<QTreeWidgetItem *> allItems = + ui->settingsTreeWidget->findItems(QString(), Qt::MatchContains | Qt::MatchRecursive); // search text if at least one character was entered if (arg1.count() >= 1) { @@ -3857,7 +3559,9 @@ void SettingsDialog::on_searchLineEdit_textChanged(const QString &arg1) { } } else { // show all items otherwise - Q_FOREACH (QTreeWidgetItem *item, allItems) { item->setHidden(false); } + Q_FOREACH (QTreeWidgetItem *item, allItems) { + item->setHidden(false); + } } } @@ -3867,8 +3571,7 @@ void SettingsDialog::on_searchLineEdit_textChanged(const QString &arg1) { * @param widget * @param pageIndexList */ -void SettingsDialog::addToSearchIndexList(QWidget *widget, - QList<int> &pageIndexList) { +void SettingsDialog::addToSearchIndexList(QWidget *widget, QList<int> &pageIndexList) { // get the page id of the widget int pageIndex = findSettingsPageIndexOfWidget(widget); @@ -3954,8 +3657,8 @@ void SettingsDialog::on_setGitPathToolButton_clicked() { } #ifdef Q_OS_WIN - QStringList filters = QStringList() << tr("Executable files") + " (*.exe)" - << tr("All files") + " (*)"; + QStringList filters = QStringList() + << tr("Executable files") + " (*.exe)" << tr("All files") + " (*)"; #else QStringList filters = QStringList() << tr("All files") + " (*)"; #endif @@ -3996,8 +3699,8 @@ void SettingsDialog::searchScriptInRepository(bool checkForUpdates) { // select the last installed script if (lastInstalledScript.isFetched()) { - auto item = Utils::Gui::getListWidgetItemWithUserData( - ui->scriptListWidget, lastInstalledScript.getId()); + auto item = Utils::Gui::getListWidgetItemWithUserData(ui->scriptListWidget, + lastInstalledScript.getId()); ui->scriptListWidget->setCurrentItem(item); } @@ -4026,8 +3729,7 @@ void SettingsDialog::on_scriptListWidget_itemChanged(QListWidgetItem *item) { reloadCurrentScriptPage(); } -void SettingsDialog::on_interfaceStyleComboBox_currentTextChanged( - const QString &arg1) { +void SettingsDialog::on_interfaceStyleComboBox_currentTextChanged(const QString &arg1) { QApplication::setStyle(arg1); // if the interface style was set to automatic we need a restart @@ -4039,9 +3741,7 @@ void SettingsDialog::on_interfaceStyleComboBox_currentTextChanged( /** * Reset the cursor width spin box value */ -void SettingsDialog::on_cursorWidthResetButton_clicked() { - ui->cursorWidthSpinBox->setValue(1); -} +void SettingsDialog::on_cursorWidthResetButton_clicked() { ui->cursorWidthSpinBox->setValue(1); } /** * Also enable the single instance feature if the system tray icon is turned on @@ -4065,10 +3765,9 @@ void SettingsDialog::on_showSystemTrayCheckBox_toggled(bool checked) { * Resets the overrides for all message boxes */ void SettingsDialog::on_resetMessageBoxesButton_clicked() { - if (QMessageBox::question( - this, tr("Reset message boxes"), - tr("Do you really want to reset the overrides of all message " - "boxes?")) == QMessageBox::Yes) { + if (QMessageBox::question(this, tr("Reset message boxes"), + tr("Do you really want to reset the overrides of all message " + "boxes?")) == QMessageBox::Yes) { QSettings settings; // remove all settings in the group @@ -4139,12 +3838,10 @@ void SettingsDialog::on_importSettingsButton_clicked() { "scripts you were using. " "You also will need to adjust some settings, especially " "across platforms, but your notes will stay intact!") + - "\n\n" + - tr("The application will be restarted after the import.") + + "\n\n" + tr("The application will be restarted after the import.") + Utils::Misc::appendSingleAppInstanceTextIfNeeded(); - if (QMessageBox::question(this, title, text, - QMessageBox::Yes | QMessageBox::No, + if (QMessageBox::question(this, title, text, QMessageBox::Yes | QMessageBox::No, QMessageBox::No) == QMessageBox::No) { return; } @@ -4211,8 +3908,7 @@ void SettingsDialog::on_overrideInterfaceFontSizeGroupBox_toggled(bool arg1) { } void SettingsDialog::on_webSocketServerServicePortResetButton_clicked() { - ui->webSocketServerServicePortSpinBox->setValue( - WebSocketServerService::getDefaultPort()); + ui->webSocketServerServicePortSpinBox->setValue(WebSocketServerService::getDefaultPort()); } void SettingsDialog::on_enableSocketServerCheckBox_toggled() { @@ -4264,10 +3960,9 @@ void SettingsDialog::initCloudConnectionComboBox(int selectedId) { } Q_FOREACH (CloudConnection cloudConnection, CloudConnection::fetchAll()) { - ui->cloudConnectionComboBox->addItem(cloudConnection.getName(), - cloudConnection.getId()); - ui->noteFolderCloudConnectionComboBox->addItem( - cloudConnection.getName(), cloudConnection.getId()); + ui->cloudConnectionComboBox->addItem(cloudConnection.getName(), cloudConnection.getId()); + ui->noteFolderCloudConnectionComboBox->addItem(cloudConnection.getName(), + cloudConnection.getId()); ui->calendarCloudConnectionComboBox->addItem(cloudConnection.getName(), cloudConnection.getId()); @@ -4281,9 +3976,8 @@ void SettingsDialog::initCloudConnectionComboBox(int selectedId) { ui->cloudConnectionComboBox->setCurrentIndex(currentIndex); on_cloudConnectionComboBox_currentIndexChanged(currentIndex); - Utils::Gui::setComboBoxIndexByUserData( - ui->noteFolderCloudConnectionComboBox, - _selectedNoteFolder.getCloudConnectionId()); + Utils::Gui::setComboBoxIndexByUserData(ui->noteFolderCloudConnectionComboBox, + _selectedNoteFolder.getCloudConnectionId()); Utils::Gui::setComboBoxIndexByUserData( ui->calendarCloudConnectionComboBox, CloudConnection::currentTodoCalendarCloudConnection().getId()); @@ -4305,13 +3999,11 @@ void SettingsDialog::on_cloudConnectionComboBox_currentIndexChanged(int index) { const QSignalBlocker blocker5(ui->appQOwnNotesAPICheckBox); Q_UNUSED(blocker5) - ui->cloudServerConnectionNameLineEdit->setText( - _selectedCloudConnection.getName()); + ui->cloudServerConnectionNameLineEdit->setText(_selectedCloudConnection.getName()); ui->serverUrlEdit->setText(_selectedCloudConnection.getServerUrl()); ui->userNameEdit->setText(_selectedCloudConnection.getUsername()); ui->passwordEdit->setText(_selectedCloudConnection.getPassword()); - ui->appQOwnNotesAPICheckBox->setChecked( - _selectedCloudConnection.getAppQOwnNotesAPIEnabled()); + ui->appQOwnNotesAPICheckBox->setChecked(_selectedCloudConnection.getAppQOwnNotesAPIEnabled()); ui->cloudConnectionRemoveButton->setDisabled( CloudConnection::fetchUsedCloudConnectionsIds().contains(id)); } @@ -4344,13 +4036,11 @@ void SettingsDialog::on_cloudConnectionRemoveButton_clicked() { initCloudConnectionComboBox(); } -void SettingsDialog::on_calendarCloudConnectionComboBox_currentIndexChanged( - int index) { +void SettingsDialog::on_calendarCloudConnectionComboBox_currentIndexChanged(int index) { Q_UNUSED(index) QSettings settings; - settings.setValue( - QStringLiteral("ownCloud/todoCalendarCloudConnectionId"), - ui->calendarCloudConnectionComboBox->currentData().toInt()); + settings.setValue(QStringLiteral("ownCloud/todoCalendarCloudConnectionId"), + ui->calendarCloudConnectionComboBox->currentData().toInt()); on_reloadCalendarListButton_clicked(); } @@ -4367,10 +4057,9 @@ void SettingsDialog::on_copyDebugInfoButton_clicked() { QClipboard *clipboard = QApplication::clipboard(); clipboard->setText(ui->debugInfoTextEdit->toPlainText()); - Utils::Gui::information( - this, tr("Debug information"), - tr("The debug information was copied to the clipboard."), - QStringLiteral("debug-clipboard")); + Utils::Gui::information(this, tr("Debug information"), + tr("The debug information was copied to the clipboard."), + QStringLiteral("debug-clipboard")); } void SettingsDialog::on_ownCloudServerAppPasswordPageButton_clicked() { @@ -4388,27 +4077,25 @@ void SettingsDialog::on_noteTextViewUseEditorStylesCheckBox_toggled(bool checked void SettingsDialog::on_databaseIntegrityCheckButton_clicked() { if (DatabaseService::checkDiskDatabaseIntegrity()) { - Utils::Gui::information( - this, tr("Database"), - tr("The integrity of the disk database is valid."), - QStringLiteral("database-integrity-check-valid")); + Utils::Gui::information(this, tr("Database"), + tr("The integrity of the disk database is valid."), + QStringLiteral("database-integrity-check-valid")); } else { - Utils::Gui::warning( - this, tr("Database"), - tr("The integrity of the disk database is not valid!"), - QStringLiteral("database-integrity-check-not-valid")); + Utils::Gui::warning(this, tr("Database"), + tr("The integrity of the disk database is not valid!"), + QStringLiteral("database-integrity-check-not-valid")); } } void SettingsDialog::on_webAppServerUrlResetButton_clicked() { - ui->webAppServerUrlLineEdit->setText( - WebAppClientService::getDefaultServerUrl()); + ui->webAppServerUrlLineEdit->setText(WebAppClientService::getDefaultServerUrl()); } void SettingsDialog::on_webAppShowTokenButton_clicked() { - ui->webAppTokenLineEdit->setEchoMode( - ui->webAppTokenLineEdit->echoMode() == QLineEdit::EchoMode::Password ? - QLineEdit::EchoMode::Normal : QLineEdit::EchoMode::Password); + ui->webAppTokenLineEdit->setEchoMode(ui->webAppTokenLineEdit->echoMode() == + QLineEdit::EchoMode::Password + ? QLineEdit::EchoMode::Normal + : QLineEdit::EchoMode::Password); } void SettingsDialog::on_webAppCopyTokenButton_clicked() { @@ -4456,8 +4143,7 @@ void SettingsDialog::on_loginFlowButton_clicked() { QJsonObject pollData; // Initiate the Nextcloud Login flow v2 - if (!OwnCloudService::initiateLoginFlowV2( - ui->serverUrlEdit->text(), pollData)) { + if (!OwnCloudService::initiateLoginFlowV2(ui->serverUrlEdit->text(), pollData)) { return; } @@ -4491,8 +4177,7 @@ void SettingsDialog::on_loginFlowButton_clicked() { return; } - -// qDebug() << __func__ << " - 'data': " << data; + // qDebug() << __func__ << " - 'data': " << data; // Wait until there is a JSON result if (!data.startsWith('{')) { @@ -4509,8 +4194,7 @@ void SettingsDialog::on_loginFlowButton_clicked() { // Try to fetch the account id QString accountId = OwnCloudService::fetchNextcloudAccountId( - ui->serverUrlEdit->text(), ui->userNameEdit->text(), - ui->passwordEdit->text()); + ui->serverUrlEdit->text(), ui->userNameEdit->text(), ui->passwordEdit->text()); if (!alive) { return; @@ -4520,7 +4204,7 @@ void SettingsDialog::on_loginFlowButton_clicked() { _selectedCloudConnection.store(); QMessageBox::information(this, QObject::tr("Login flow succeeded"), - QObject::tr("Username and password were set successfully!")); + QObject::tr("Username and password were set successfully!")); ui->loginFlowButton->show(); ui->loginFlowCancelButton->hide(); diff --git a/src/dialogs/settingsdialog.h b/src/dialogs/settingsdialog.h index 1d176a61e..23f170bef 100644 --- a/src/dialogs/settingsdialog.h +++ b/src/dialogs/settingsdialog.h @@ -66,9 +66,8 @@ class SettingsDialog : public MasterDialog { ~SettingsDialog(); - void connectTestCallback(bool appIsValid, QString appVersion, - QString serverVersion, QString notesPathExistsText, - QString connectionErrorMessage); + void connectTestCallback(bool appIsValid, QString appVersion, QString serverVersion, + QString notesPathExistsText, QString connectionErrorMessage); void setOKLabelData(int number, const QString &text, OKLabelStatus status); @@ -143,8 +142,8 @@ class SettingsDialog : public MasterDialog { void on_noteFolderRemotePathButton_clicked(); - void on_noteFolderRemotePathTreeWidget_currentItemChanged( - QTreeWidgetItem *current, QTreeWidgetItem *previous); + void on_noteFolderRemotePathTreeWidget_currentItemChanged(QTreeWidgetItem *current, + QTreeWidgetItem *previous); void on_useOwnCloudPathButton_clicked(); @@ -167,8 +166,7 @@ class SettingsDialog : public MasterDialog { void on_removeCustomNoteFileExtensionButton_clicked(); - void on_defaultNoteFileExtensionListWidget_itemChanged( - QListWidgetItem *item); + void on_defaultNoteFileExtensionListWidget_itemChanged(QListWidgetItem *item); void on_darkModeCheckBox_toggled(); @@ -319,7 +317,7 @@ class SettingsDialog : public MasterDialog { void on_noteTextViewRefreshDebounceTimeResetButton_clicked(); -private: + private: Ui::SettingsDialog *ui; QStatusBar *noteFolderRemotePathTreeStatusBar; QFont noteTextEditFont; @@ -349,11 +347,9 @@ private: void outputSettings(); - static void selectListWidgetValue(QListWidget *listWidget, - const QString &value); + static void selectListWidgetValue(QListWidget *listWidget, const QString &value); - static bool listWidgetValueExists(QListWidget *listWidget, - const QString &value); + static bool listWidgetValueExists(QListWidget *listWidget, const QString &value); static QString getSelectedListWidgetValue(QListWidget *listWidget); @@ -363,14 +359,12 @@ private: void setupNoteFolderPage(); - QTreeWidgetItem *findNoteFolderRemotePathTreeWidgetItem( - QTreeWidgetItem *parent, const QString &text); + QTreeWidgetItem *findNoteFolderRemotePathTreeWidgetItem(QTreeWidgetItem *parent, + const QString &text); - void addPathToNoteFolderRemotePathTreeWidget(QTreeWidgetItem *parent, - const QString &path); + void addPathToNoteFolderRemotePathTreeWidget(QTreeWidgetItem *parent, const QString &path); - QString generatePathFromCurrentNoteFolderRemotePathItem( - QTreeWidgetItem *item); + QString generatePathFromCurrentNoteFolderRemotePathItem(QTreeWidgetItem *item); void setNoteFolderRemotePathTreeWidgetFrameVisibility(bool visi); @@ -426,8 +420,7 @@ private: void initCloudConnectionComboBox(int selectedId = -1); - void handleDarkModeCheckBoxToggled(bool updateCheckBoxes = false, - bool updateSchema = false); + void handleDarkModeCheckBoxToggled(bool updateCheckBoxes = false, bool updateSchema = false); void resetOKLabelData(); }; diff --git a/src/dialogs/sharedialog.cpp b/src/dialogs/sharedialog.cpp index 85a9be365..dbf43f039 100644 --- a/src/dialogs/sharedialog.cpp +++ b/src/dialogs/sharedialog.cpp @@ -36,10 +36,8 @@ void ShareDialog::updateDialog() { ui->linkCheckBox->setChecked(note.isShared()); ui->linkUrlLineEdit->setVisible(note.isShared()); ui->linkUrlLineEdit->setText(note.getShareUrl()); - ui->infoLabel1->setText( - Utils::Misc::replaceOwnCloudText(ui->infoLabel1->text())); - ui->linkCheckBox->setText( - Utils::Misc::replaceOwnCloudText(ui->linkCheckBox->text())); + ui->infoLabel1->setText(Utils::Misc::replaceOwnCloudText(ui->infoLabel1->text())); + ui->linkCheckBox->setText(Utils::Misc::replaceOwnCloudText(ui->linkCheckBox->text())); ui->editCheckBox->setVisible(note.isShared()); ui->editCheckBox->setChecked(note.isShareEditAllowed()); } @@ -62,11 +60,10 @@ void ShareDialog::on_linkCheckBox_toggled(bool checked) { Utils::Gui::information( this, QString(), - Utils::Misc::replaceOwnCloudText( - tr("Keep in mind that you still have to sync your " - "notes with your server by using the ownCloud " - "desktop sync tool to be able to share notes with " - "others!")), + Utils::Misc::replaceOwnCloudText(tr("Keep in mind that you still have to sync your " + "notes with your server by using the ownCloud " + "desktop sync tool to be able to share notes with " + "others!")), QStringLiteral("share-sync-information")); } else { // remove the share diff --git a/src/dialogs/storedattachmentsdialog.cpp b/src/dialogs/storedattachmentsdialog.cpp index bdd29c004..c569ce572 100644 --- a/src/dialogs/storedattachmentsdialog.cpp +++ b/src/dialogs/storedattachmentsdialog.cpp @@ -41,8 +41,8 @@ void StoredAttachmentsDialog::refreshAttachmentFiles() { return; } - QStringList attachmentFiles = attachmentsDir.entryList( - QStringList(QStringLiteral("*")), QDir::Files, QDir::Time); + QStringList attachmentFiles = + attachmentsDir.entryList(QStringList(QStringLiteral("*")), QDir::Files, QDir::Time); attachmentFiles.removeDuplicates(); QVector<Note> noteList = Note::fetchAll(); @@ -53,42 +53,42 @@ void StoredAttachmentsDialog::refreshAttachmentFiles() { ui->progressBar->show(); Q_FOREACH (Note note, noteList) { - QStringList attachmentsFileList = note.getAttachmentsFileList(); - // we don't want to keep the whole note text - note.setNoteText(""); + QStringList attachmentsFileList = note.getAttachmentsFileList(); + // we don't want to keep the whole note text + note.setNoteText(""); - Q_FOREACH (const QString &fileName, attachmentsFileList) { - // remove all found attachments from the files list if _orphanedAttachmentsOnly is enabled - if (_orphanedAttachmentsOnly) { - attachmentFiles.removeAll(fileName); - } + Q_FOREACH (const QString &fileName, attachmentsFileList) { + // remove all found attachments from the files list if _orphanedAttachmentsOnly is + // enabled + if (_orphanedAttachmentsOnly) { + attachmentFiles.removeAll(fileName); + } - if (!_fileNoteList[fileName].contains(note)) { - _fileNoteList[fileName].append(note); - } - } - - ui->progressBar->setValue(ui->progressBar->value() + 1); + if (!_fileNoteList[fileName].contains(note)) { + _fileNoteList[fileName].append(note); + } } + ui->progressBar->setValue(ui->progressBar->value() + 1); + } + ui->progressBar->hide(); ui->fileTreeWidget->clear(); Q_FOREACH (QString fileName, attachmentFiles) { - auto *item = new QTreeWidgetItem(); - item->setText(0, fileName); - item->setData(0, Qt::UserRole, fileName); - item->setFlags(item->flags() | Qt::ItemIsEditable); + auto *item = new QTreeWidgetItem(); + item->setText(0, fileName); + item->setData(0, Qt::UserRole, fileName); + item->setFlags(item->flags() | Qt::ItemIsEditable); - QString filePath = getFilePath(item); - QFileInfo info(filePath); - item->setToolTip( - 0, tr("Last modified at %1").arg(info.lastModified().toString()) + - QStringLiteral("\n") + - Utils::Misc::toHumanReadableByteSize(info.size())); + QString filePath = getFilePath(item); + QFileInfo info(filePath); + item->setToolTip(0, tr("Last modified at %1").arg(info.lastModified().toString()) + + QStringLiteral("\n") + + Utils::Misc::toHumanReadableByteSize(info.size())); - ui->fileTreeWidget->addTopLevelItem(item); - } + ui->fileTreeWidget->addTopLevelItem(item); + } // Re-apply search text on_searchLineEdit_textChanged(ui->searchLineEdit->text()); @@ -97,8 +97,7 @@ void StoredAttachmentsDialog::refreshAttachmentFiles() { // jump to the first item if (attachmentFiles.count() > 0) { - auto *event = - new QKeyEvent(QEvent::KeyPress, Qt::Key_Home, Qt::NoModifier); + auto *event = new QKeyEvent(QEvent::KeyPress, Qt::Key_Home, Qt::NoModifier); QApplication::postEvent(ui->fileTreeWidget, event); } } @@ -109,8 +108,8 @@ void StoredAttachmentsDialog::refreshAttachmentFiles() { * @param current * @param previous */ -void StoredAttachmentsDialog::on_fileTreeWidget_currentItemChanged( - QTreeWidgetItem *current, QTreeWidgetItem *previous) { +void StoredAttachmentsDialog::on_fileTreeWidget_currentItemChanged(QTreeWidgetItem *current, + QTreeWidgetItem *previous) { Q_UNUSED(current); Q_UNUSED(previous); loadCurrentFileDetails(); @@ -137,8 +136,7 @@ void StoredAttachmentsDialog::loadCurrentFileDetails() { ui->typeLabel->setText(type.comment()); QFileInfo fileInfo(filePath); - QString fileSizeText = - Utils::Misc::toHumanReadableByteSize(fileInfo.size()); + QString fileSizeText = Utils::Misc::toHumanReadableByteSize(fileInfo.size()); ui->sizeLabel->setText(fileSizeText); ui->infoFrame->setEnabled(true); @@ -149,21 +147,20 @@ void StoredAttachmentsDialog::loadCurrentFileDetails() { auto notes = _fileNoteList[fileName]; ui->noteTreeWidget->clear(); - Q_FOREACH(Note note, notes) { - auto *item = new QTreeWidgetItem(); - item->setText(0, note.getName()); - item->setData(0, Qt::UserRole, note.getId()); - Utils::Gui::setTreeWidgetItemToolTipForNote(item, note); + Q_FOREACH (Note note, notes) { + auto *item = new QTreeWidgetItem(); + item->setText(0, note.getName()); + item->setData(0, Qt::UserRole, note.getId()); + Utils::Gui::setTreeWidgetItemToolTipForNote(item, note); - NoteSubFolder noteSubFolder = note.getNoteSubFolder(); - if (noteSubFolder.isFetched()) { - item->setToolTip(0, tr("Path: %1").arg( - noteSubFolder.relativePath())); - } - - ui->noteTreeWidget->addTopLevelItem(item); + NoteSubFolder noteSubFolder = note.getNoteSubFolder(); + if (noteSubFolder.isFetched()) { + item->setToolTip(0, tr("Path: %1").arg(noteSubFolder.relativePath())); } + ui->noteTreeWidget->addTopLevelItem(item); + } + ui->notesFrame->show(); } else { ui->notesFrame->hide(); @@ -181,8 +178,7 @@ QString StoredAttachmentsDialog::getFilePath(QTreeWidgetItem *item) { return QString(); } - QString fileName = NoteFolder::currentAttachmentsPath() + - QDir::separator() + + QString fileName = NoteFolder::currentAttachmentsPath() + QDir::separator() + item->data(0, Qt::UserRole).toString(); return fileName; } @@ -197,11 +193,10 @@ void StoredAttachmentsDialog::on_deleteButton_clicked() { return; } - if (Utils::Gui::question(this, tr("Delete selected files"), - tr("Delete <strong>%n</strong> selected file(s)?", - "", selectedItemsCount), - QStringLiteral("delete-attachment-files")) != - QMessageBox::Yes) { + if (Utils::Gui::question( + this, tr("Delete selected files"), + tr("Delete <strong>%n</strong> selected file(s)?", "", selectedItemsCount), + QStringLiteral("delete-attachment-files")) != QMessageBox::Yes) { return; } @@ -229,8 +224,7 @@ bool StoredAttachmentsDialog::eventFilter(QObject *obj, QEvent *event) { if (obj == ui->fileTreeWidget) { // delete the currently selected attachments - if ((keyEvent->key() == Qt::Key_Delete) || - (keyEvent->key() == Qt::Key_Backspace)) { + if ((keyEvent->key() == Qt::Key_Delete) || (keyEvent->key() == Qt::Key_Backspace)) { on_deleteButton_clicked(); return true; } @@ -260,10 +254,8 @@ void StoredAttachmentsDialog::on_insertButton_clicked() { Q_FOREACH (QTreeWidgetItem *item, ui->fileTreeWidget->selectedItems()) { QString filePath = getFilePath(item); QFileInfo fileInfo(filePath); - QString attachmentsUrlString = - note.attachmentUrlStringForFileName(fileInfo.fileName()); - QString attachmentLink = - "[" + fileInfo.baseName() + "](" + attachmentsUrlString + ")\n"; + QString attachmentsUrlString = note.attachmentUrlStringForFileName(fileInfo.fileName()); + QString attachmentLink = "[" + fileInfo.baseName() + "](" + attachmentsUrlString + ")\n"; textEdit->insertPlainText(attachmentLink); } @@ -292,8 +284,7 @@ void StoredAttachmentsDialog::on_openFolderButton_clicked() { Utils::Misc::openFolderSelect(filePath); } -void StoredAttachmentsDialog::on_fileTreeWidget_customContextMenuRequested( - const QPoint &pos) { +void StoredAttachmentsDialog::on_fileTreeWidget_customContextMenuRequested(const QPoint &pos) { // don't open the most of the context menu if no tags are selected const bool hasSelected = ui->fileTreeWidget->selectedItems().count() > 0; @@ -336,25 +327,22 @@ void StoredAttachmentsDialog::refreshAndJumpToFileName(const QString &fileName) refreshAttachmentFiles(); // look for the item to jump back to - auto item = Utils::Gui::getTreeWidgetItemWithUserData( - ui->fileTreeWidget, fileName); + auto item = Utils::Gui::getTreeWidgetItemWithUserData(ui->fileTreeWidget, fileName); #if QT_VERSION >= QT_VERSION_CHECK(5, 4, 0) // set the previous item with a timer (didn't work without timer) - QTimer::singleShot(0, this, [this, item] () { - ui->fileTreeWidget->setCurrentItem(item); - }); + QTimer::singleShot(0, this, [this, item]() { ui->fileTreeWidget->setCurrentItem(item); }); #endif } void StoredAttachmentsDialog::on_searchLineEdit_textChanged(const QString &arg1) { - Utils::Gui::searchForTextInTreeWidget(ui->fileTreeWidget, arg1, - Utils::Gui::TreeWidgetSearchFlags( - Utils::Gui::TreeWidgetSearchFlag::EveryWordSearch)); + Utils::Gui::searchForTextInTreeWidget( + ui->fileTreeWidget, arg1, + Utils::Gui::TreeWidgetSearchFlags(Utils::Gui::TreeWidgetSearchFlag::EveryWordSearch)); } -void StoredAttachmentsDialog::on_fileTreeWidget_itemDoubleClicked( - QTreeWidgetItem *item, int column) { +void StoredAttachmentsDialog::on_fileTreeWidget_itemDoubleClicked(QTreeWidgetItem *item, + int column) { Q_UNUSED(item) Q_UNUSED(column) on_insertButton_clicked(); @@ -378,8 +366,8 @@ void StoredAttachmentsDialog::openCurrentNote() { mainWindow->openCurrentNoteInTab(); } -void StoredAttachmentsDialog::on_noteTreeWidget_itemDoubleClicked( - QTreeWidgetItem *item, int column) { +void StoredAttachmentsDialog::on_noteTreeWidget_itemDoubleClicked(QTreeWidgetItem *item, + int column) { Q_UNUSED(item) Q_UNUSED(column) openCurrentNote(); @@ -390,12 +378,9 @@ void StoredAttachmentsDialog::on_checkBox_toggled(bool checked) { refreshAttachmentFiles(); } -void StoredAttachmentsDialog::on_refreshButton_clicked() { - refreshAttachmentFiles(); -} +void StoredAttachmentsDialog::on_refreshButton_clicked() { refreshAttachmentFiles(); } -void StoredAttachmentsDialog::on_fileTreeWidget_itemChanged( - QTreeWidgetItem *item, int column) { +void StoredAttachmentsDialog::on_fileTreeWidget_itemChanged(QTreeWidgetItem *item, int column) { Q_UNUSED(column) QString oldFileName = item->data(0, Qt::UserRole).toString(); @@ -405,20 +390,21 @@ void StoredAttachmentsDialog::on_fileTreeWidget_itemChanged( qDebug() << __func__ << " - 'oldFileName': " << oldFileName; qDebug() << __func__ << " - 'newFileName': " << newFileName; - const QString oldFilePath = NoteFolder::currentAttachmentsPath() + - QDir::separator() + oldFileName; + const QString oldFilePath = + NoteFolder::currentAttachmentsPath() + QDir::separator() + oldFileName; QFile oldFile(oldFilePath); if (!oldFile.exists()) { QMessageBox::warning(this, tr("File doesn't exist"), tr("The file <strong>%1</strong> doesn't exist, " - "you cannot rename it!").arg(oldFilePath)); + "you cannot rename it!") + .arg(oldFilePath)); item->setText(0, oldFileName); return; } - const QString newFilePath = NoteFolder::currentAttachmentsPath() + - QDir::separator() + newFileName; + const QString newFilePath = + NoteFolder::currentAttachmentsPath() + QDir::separator() + newFileName; QFile newFile(newFilePath); if (newFile.exists()) { @@ -449,11 +435,11 @@ void StoredAttachmentsDialog::on_fileTreeWidget_itemChanged( } if (Utils::Gui::questionNoSkipOverride( - nullptr, QObject::tr("File name changed"), - QObject::tr("%n note(s) are using this attachment. Would you also " - "like to rename those attachments in the note(s)?", - "", affectedNotesCount), - QStringLiteral("note-replace-attachments")) != QMessageBox::Yes) { + nullptr, QObject::tr("File name changed"), + QObject::tr("%n note(s) are using this attachment. Would you also " + "like to rename those attachments in the note(s)?", + "", affectedNotesCount), + QStringLiteral("note-replace-attachments")) != QMessageBox::Yes) { refreshAndJumpToFileName(newFileName); return; } @@ -465,8 +451,8 @@ void StoredAttachmentsDialog::on_fileTreeWidget_itemChanged( QString text = note.getNoteText(); text.replace(QRegularExpression(R"((\[.*?\])\((.*?attachments\/.*?)()" + - QRegularExpression::escape(oldFileName) + ")\\)"), - "\\1(\\2" + newFileName + ")"); + QRegularExpression::escape(oldFileName) + ")\\)"), + "\\1(\\2" + newFileName + ")"); note.storeNewText(text); } @@ -480,8 +466,7 @@ void StoredAttachmentsDialog::on_fileTreeWidget_itemChanged( } } -void StoredAttachmentsDialog::on_noteTreeWidget_customContextMenuRequested( - const QPoint &pos) { +void StoredAttachmentsDialog::on_noteTreeWidget_customContextMenuRequested(const QPoint &pos) { // don't open the most of the context menu if no tags are selected const bool hasSelected = ui->noteTreeWidget->selectedItems().count() > 0; diff --git a/src/dialogs/storedattachmentsdialog.h b/src/dialogs/storedattachmentsdialog.h index a0d4134e5..a6dd9b085 100644 --- a/src/dialogs/storedattachmentsdialog.h +++ b/src/dialogs/storedattachmentsdialog.h @@ -1,7 +1,7 @@ #pragma once -#include "masterdialog.h" #include "entities/note.h" +#include "masterdialog.h" class QTreeWidgetItem; class QEvent; @@ -21,8 +21,7 @@ class StoredAttachmentsDialog : public MasterDialog { bool eventFilter(QObject *obj, QEvent *event); private slots: - void on_fileTreeWidget_currentItemChanged(QTreeWidgetItem *current, - QTreeWidgetItem *previous); + void on_fileTreeWidget_currentItemChanged(QTreeWidgetItem *current, QTreeWidgetItem *previous); void on_deleteButton_clicked(); @@ -48,7 +47,7 @@ class StoredAttachmentsDialog : public MasterDialog { void on_noteTreeWidget_customContextMenuRequested(const QPoint &pos); -private: + private: Ui::StoredAttachmentsDialog *ui; bool _orphanedAttachmentsOnly = false; QHash<QString, QVector<Note>> _fileNoteList; diff --git a/src/dialogs/storedimagesdialog.cpp b/src/dialogs/storedimagesdialog.cpp index d4359e653..536a30398 100644 --- a/src/dialogs/storedimagesdialog.cpp +++ b/src/dialogs/storedimagesdialog.cpp @@ -8,12 +8,12 @@ #include <QDebug> #include <QDir> -#include <QMenu> #include <QFileInfo> #include <QGraphicsPixmapItem> #include <QKeyEvent> -#include <QTreeWidgetItem> +#include <QMenu> #include <QTimer> +#include <QTreeWidgetItem> #include <QtWidgets/QMessageBox> #include "ui_storedimagesdialog.h" @@ -38,8 +38,8 @@ void StoredImagesDialog::refreshMediaFiles() { return; } - QStringList mediaFiles = mediaDir.entryList( - QStringList(QStringLiteral("*")), QDir::Files, QDir::Time); + QStringList mediaFiles = + mediaDir.entryList(QStringList(QStringLiteral("*")), QDir::Files, QDir::Time); mediaFiles.removeDuplicates(); QVector<Note> noteList = Note::fetchAll(); @@ -50,42 +50,41 @@ void StoredImagesDialog::refreshMediaFiles() { ui->progressBar->show(); Q_FOREACH (Note note, noteList) { - QStringList mediaFileList = note.getMediaFileList(); - // we don't want to keep the whole note text - note.setNoteText(""); + QStringList mediaFileList = note.getMediaFileList(); + // we don't want to keep the whole note text + note.setNoteText(""); - Q_FOREACH (QString fileName, mediaFileList) { - // remove all found images from the files list if _orphanedImagesOnly is enabled - if (_orphanedImagesOnly) { - mediaFiles.removeAll(fileName); - } + Q_FOREACH (QString fileName, mediaFileList) { + // remove all found images from the files list if _orphanedImagesOnly is enabled + if (_orphanedImagesOnly) { + mediaFiles.removeAll(fileName); + } - if (!_fileNoteList[fileName].contains(note)) { - _fileNoteList[fileName].append(note); - } - } - - ui->progressBar->setValue(ui->progressBar->value() + 1); + if (!_fileNoteList[fileName].contains(note)) { + _fileNoteList[fileName].append(note); + } } + ui->progressBar->setValue(ui->progressBar->value() + 1); + } + ui->progressBar->hide(); ui->fileTreeWidget->clear(); Q_FOREACH (QString fileName, mediaFiles) { - auto *item = new QTreeWidgetItem(); - item->setText(0, fileName); - item->setData(0, Qt::UserRole, fileName); - item->setFlags(item->flags() | Qt::ItemIsEditable); + auto *item = new QTreeWidgetItem(); + item->setText(0, fileName); + item->setData(0, Qt::UserRole, fileName); + item->setFlags(item->flags() | Qt::ItemIsEditable); - QString filePath = getFilePath(item); - QFileInfo info(filePath); - item->setToolTip( - 0, tr("Last modified at %1").arg(info.lastModified().toString()) + - QStringLiteral("\n") + - Utils::Misc::toHumanReadableByteSize(info.size())); + QString filePath = getFilePath(item); + QFileInfo info(filePath); + item->setToolTip(0, tr("Last modified at %1").arg(info.lastModified().toString()) + + QStringLiteral("\n") + + Utils::Misc::toHumanReadableByteSize(info.size())); - ui->fileTreeWidget->addTopLevelItem(item); - } + ui->fileTreeWidget->addTopLevelItem(item); + } // Re-apply search text on_searchLineEdit_textChanged(ui->searchLineEdit->text()); @@ -94,8 +93,7 @@ void StoredImagesDialog::refreshMediaFiles() { // jump to the first item if (mediaFiles.count() > 0) { - auto *event = - new QKeyEvent(QEvent::KeyPress, Qt::Key_Home, Qt::NoModifier); + auto *event = new QKeyEvent(QEvent::KeyPress, Qt::Key_Home, Qt::NoModifier); QApplication::postEvent(ui->fileTreeWidget, event); } } @@ -106,8 +104,8 @@ void StoredImagesDialog::refreshMediaFiles() { * @param current * @param previous */ -void StoredImagesDialog::on_fileTreeWidget_currentItemChanged( - QTreeWidgetItem *current, QTreeWidgetItem *previous) { +void StoredImagesDialog::on_fileTreeWidget_currentItemChanged(QTreeWidgetItem *current, + QTreeWidgetItem *previous) { Q_UNUSED(current); Q_UNUSED(previous); loadCurrentFileDetails(); @@ -137,21 +135,20 @@ void StoredImagesDialog::loadCurrentFileDetails() { auto notes = _fileNoteList[fileName]; ui->noteTreeWidget->clear(); - Q_FOREACH(Note note, notes) { - auto *item = new QTreeWidgetItem(); - item->setText(0, note.getName()); - item->setData(0, Qt::UserRole, note.getId()); - Utils::Gui::setTreeWidgetItemToolTipForNote(item, note); + Q_FOREACH (Note note, notes) { + auto *item = new QTreeWidgetItem(); + item->setText(0, note.getName()); + item->setData(0, Qt::UserRole, note.getId()); + Utils::Gui::setTreeWidgetItemToolTipForNote(item, note); - NoteSubFolder noteSubFolder = note.getNoteSubFolder(); - if (noteSubFolder.isFetched()) { - item->setToolTip(0, tr("Path: %1").arg( - noteSubFolder.relativePath())); - } - - ui->noteTreeWidget->addTopLevelItem(item); + NoteSubFolder noteSubFolder = note.getNoteSubFolder(); + if (noteSubFolder.isFetched()) { + item->setToolTip(0, tr("Path: %1").arg(noteSubFolder.relativePath())); } + ui->noteTreeWidget->addTopLevelItem(item); + } + ui->notesFrame->show(); } else { ui->notesFrame->hide(); @@ -169,8 +166,8 @@ QString StoredImagesDialog::getFilePath(QTreeWidgetItem *item) { return QString(); } - QString fileName = NoteFolder::currentMediaPath() + QDir::separator() + - item->data(0, Qt::UserRole).toString(); + QString fileName = + NoteFolder::currentMediaPath() + QDir::separator() + item->data(0, Qt::UserRole).toString(); return fileName; } @@ -184,11 +181,10 @@ void StoredImagesDialog::on_deleteButton_clicked() { return; } - if (Utils::Gui::question(this, tr("Delete selected files"), - tr("Delete <strong>%n</strong> selected file(s)?", - "", selectedItemsCount), - QStringLiteral("delete-image-files")) != - QMessageBox::Yes) { + if (Utils::Gui::question( + this, tr("Delete selected files"), + tr("Delete <strong>%n</strong> selected file(s)?", "", selectedItemsCount), + QStringLiteral("delete-image-files")) != QMessageBox::Yes) { return; } @@ -216,8 +212,7 @@ bool StoredImagesDialog::eventFilter(QObject *obj, QEvent *event) { if (obj == ui->fileTreeWidget) { // delete the currently selected images - if ((keyEvent->key() == Qt::Key_Delete) || - (keyEvent->key() == Qt::Key_Backspace)) { + if ((keyEvent->key() == Qt::Key_Delete) || (keyEvent->key() == Qt::Key_Backspace)) { on_deleteButton_clicked(); return true; } @@ -248,10 +243,8 @@ void StoredImagesDialog::on_insertButton_clicked() { Q_FOREACH (QTreeWidgetItem *item, ui->fileTreeWidget->selectedItems()) { QString filePath = getFilePath(item); QFileInfo fileInfo(filePath); - QString mediaUrlString = - note.mediaUrlStringForFileName(fileInfo.fileName()); - QString imageLink = - "![" + fileInfo.baseName() + "](" + mediaUrlString + ")\n"; + QString mediaUrlString = note.mediaUrlStringForFileName(fileInfo.fileName()); + QString imageLink = "![" + fileInfo.baseName() + "](" + mediaUrlString + ")\n"; textEdit->insertPlainText(imageLink); } @@ -264,9 +257,9 @@ void StoredImagesDialog::on_checkBox_toggled(bool checked) { } void StoredImagesDialog::on_searchLineEdit_textChanged(const QString &arg1) { - Utils::Gui::searchForTextInTreeWidget(ui->fileTreeWidget, arg1, - Utils::Gui::TreeWidgetSearchFlags( - Utils::Gui::TreeWidgetSearchFlag::EveryWordSearch)); + Utils::Gui::searchForTextInTreeWidget( + ui->fileTreeWidget, arg1, + Utils::Gui::TreeWidgetSearchFlags(Utils::Gui::TreeWidgetSearchFlag::EveryWordSearch)); } /** @@ -275,8 +268,7 @@ void StoredImagesDialog::on_searchLineEdit_textChanged(const QString &arg1) { * @param item * @param column */ -void StoredImagesDialog::on_fileTreeWidget_itemDoubleClicked( - QTreeWidgetItem *item, int column) { +void StoredImagesDialog::on_fileTreeWidget_itemDoubleClicked(QTreeWidgetItem *item, int column) { Q_UNUSED(item) Q_UNUSED(column) on_insertButton_clicked(); @@ -306,19 +298,15 @@ void StoredImagesDialog::openCurrentNote() { * @param item * @param column */ -void StoredImagesDialog::on_noteTreeWidget_itemDoubleClicked( - QTreeWidgetItem *item, int column) { +void StoredImagesDialog::on_noteTreeWidget_itemDoubleClicked(QTreeWidgetItem *item, int column) { Q_UNUSED(item) Q_UNUSED(column) openCurrentNote(); } -void StoredImagesDialog::on_refreshButton_clicked() { - refreshMediaFiles(); -} +void StoredImagesDialog::on_refreshButton_clicked() { refreshMediaFiles(); } -void StoredImagesDialog::on_fileTreeWidget_itemChanged( - QTreeWidgetItem *item, int column) { +void StoredImagesDialog::on_fileTreeWidget_itemChanged(QTreeWidgetItem *item, int column) { Q_UNUSED(column) QString oldFileName = item->data(0, Qt::UserRole).toString(); @@ -328,20 +316,19 @@ void StoredImagesDialog::on_fileTreeWidget_itemChanged( qDebug() << __func__ << " - 'oldFileName': " << oldFileName; qDebug() << __func__ << " - 'newFileName': " << newFileName; - const QString oldFilePath = NoteFolder::currentMediaPath() + - QDir::separator() + oldFileName; + const QString oldFilePath = NoteFolder::currentMediaPath() + QDir::separator() + oldFileName; QFile oldFile(oldFilePath); if (!oldFile.exists()) { QMessageBox::warning(this, tr("File doesn't exist"), tr("The file <strong>%1</strong> doesn't exist, " - "you cannot rename it!").arg(oldFilePath)); + "you cannot rename it!") + .arg(oldFilePath)); item->setText(0, oldFileName); return; } - const QString newFilePath = NoteFolder::currentMediaPath() + - QDir::separator() + newFileName; + const QString newFilePath = NoteFolder::currentMediaPath() + QDir::separator() + newFileName; QFile newFile(newFilePath); if (newFile.exists()) { @@ -372,11 +359,11 @@ void StoredImagesDialog::on_fileTreeWidget_itemChanged( } if (Utils::Gui::questionNoSkipOverride( - nullptr, QObject::tr("File name changed"), - QObject::tr("%n note(s) are using this image. Would you also " - "like to rename those images in the note(s)?", - "", affectedNotesCount), - QStringLiteral("note-replace-images")) != QMessageBox::Yes) { + nullptr, QObject::tr("File name changed"), + QObject::tr("%n note(s) are using this image. Would you also " + "like to rename those images in the note(s)?", + "", affectedNotesCount), + QStringLiteral("note-replace-images")) != QMessageBox::Yes) { refreshAndJumpToFileName(newFileName); return; } @@ -388,8 +375,8 @@ void StoredImagesDialog::on_fileTreeWidget_itemChanged( QString text = note.getNoteText(); text.replace(QRegularExpression(R"((!\[.*?\])\((.*?media\/.*?)()" + - QRegularExpression::escape(oldFileName) + ")\\)"), - "\\1(\\2" + newFileName + ")"); + QRegularExpression::escape(oldFileName) + ")\\)"), + "\\1(\\2" + newFileName + ")"); note.storeNewText(text); } @@ -408,19 +395,15 @@ void StoredImagesDialog::refreshAndJumpToFileName(const QString &fileName) { refreshMediaFiles(); // look for the item to jump back to - auto item = Utils::Gui::getTreeWidgetItemWithUserData( - ui->fileTreeWidget, fileName); + auto item = Utils::Gui::getTreeWidgetItemWithUserData(ui->fileTreeWidget, fileName); #if QT_VERSION >= QT_VERSION_CHECK(5, 4, 0) // set the previous item with a timer (didn't work without timer) - QTimer::singleShot(0, this, [this, item] () { - ui->fileTreeWidget->setCurrentItem(item); - }); + QTimer::singleShot(0, this, [this, item]() { ui->fileTreeWidget->setCurrentItem(item); }); #endif } -void StoredImagesDialog::on_fileTreeWidget_customContextMenuRequested( - const QPoint &pos) { +void StoredImagesDialog::on_fileTreeWidget_customContextMenuRequested(const QPoint &pos) { // don't open the most of the context menu if no tags are selected const bool hasSelected = ui->fileTreeWidget->selectedItems().count() > 0; @@ -458,8 +441,7 @@ void StoredImagesDialog::on_fileTreeWidget_customContextMenuRequested( } } -void StoredImagesDialog::on_noteTreeWidget_customContextMenuRequested( - const QPoint &pos) { +void StoredImagesDialog::on_noteTreeWidget_customContextMenuRequested(const QPoint &pos) { // don't open the most of the context menu if no tags are selected const bool hasSelected = ui->noteTreeWidget->selectedItems().count() > 0; diff --git a/src/dialogs/storedimagesdialog.h b/src/dialogs/storedimagesdialog.h index 4f7906c22..e180e124f 100644 --- a/src/dialogs/storedimagesdialog.h +++ b/src/dialogs/storedimagesdialog.h @@ -1,7 +1,7 @@ #pragma once -#include "masterdialog.h" #include "entities/note.h" +#include "masterdialog.h" class QTreeWidgetItem; @@ -20,8 +20,7 @@ class StoredImagesDialog : public MasterDialog { bool eventFilter(QObject *obj, QEvent *event) override; private slots: - void on_fileTreeWidget_currentItemChanged(QTreeWidgetItem *current, - QTreeWidgetItem *previous); + void on_fileTreeWidget_currentItemChanged(QTreeWidgetItem *current, QTreeWidgetItem *previous); void on_deleteButton_clicked(); @@ -47,7 +46,7 @@ class StoredImagesDialog : public MasterDialog { void on_openFolderButton_clicked(); -private: + private: Ui::StoredImagesDialog *ui; bool _orphanedImagesOnly = false; QHash<QString, QVector<Note>> _fileNoteList; diff --git a/src/dialogs/tabledialog.cpp b/src/dialogs/tabledialog.cpp index a0ea4e16b..e04e2e3bf 100644 --- a/src/dialogs/tabledialog.cpp +++ b/src/dialogs/tabledialog.cpp @@ -2,16 +2,15 @@ #include <mainwindow.h> -#include <QDebug> #include <QClipboard> +#include <QDebug> #include "filedialog.h" #include "libraries/qtcsv/src/include/reader.h" #include "ui_tabledialog.h" #include "widgets/qownnotesmarkdowntextedit.h" -TableDialog::TableDialog(QWidget *parent) - : MasterDialog(parent), ui(new Ui::TableDialog) { +TableDialog::TableDialog(QWidget *parent) : MasterDialog(parent), ui(new Ui::TableDialog) { ui->setupUi(this); // ignore the return key so we can better edit text in the table @@ -40,8 +39,7 @@ void TableDialog::on_createTableWidget_itemSelectionChanged() { */ updateMaxItems(); - const QList<QTableWidgetSelectionRange> &list = - ui->createTableWidget->selectedRanges(); + const QList<QTableWidgetSelectionRange> &list = ui->createTableWidget->selectedRanges(); if (list.isEmpty()) { return; @@ -50,8 +48,7 @@ void TableDialog::on_createTableWidget_itemSelectionChanged() { #if (QT_VERSION >= QT_VERSION_CHECK(5, 6, 0)) QTableWidgetSelectionRange range = list.constFirst(); #else - QTableWidgetSelectionRange range = - list.first(); + QTableWidgetSelectionRange range = list.first(); #endif ui->rowSpinBox->setValue(std::max<int>(_maxRows, range.rowCount())); @@ -94,8 +91,7 @@ void TableDialog::on_buttonBox_accepted() { * Imports the CSV file */ void TableDialog::importCSV() { - QString filePath = _tempFile != nullptr ? - _tempFile->fileName() : ui->fileLineEdit->text(); + QString filePath = _tempFile != nullptr ? _tempFile->fileName() : ui->fileLineEdit->text(); if (filePath.isEmpty()) { return; @@ -107,9 +103,8 @@ void TableDialog::importCSV() { separator.replace("\\t", "\t"); // read data from file - QList<QStringList> readData = QtCSV::Reader::readToList( - filePath, separator, - ui->textDelimiterComboBox->currentText()); + QList<QStringList> readData = + QtCSV::Reader::readToList(filePath, separator, ui->textDelimiterComboBox->currentText()); // loop through all rows for (int row = 0; row < readData.size(); ++row) { @@ -144,18 +139,15 @@ void TableDialog::createMarkdownTable() { QString text = QStringLiteral("\n\n"); int colWidth = ui->columnWidthSpinBox->value(); QString space = QStringLiteral(" ").repeated(colWidth); - QString headline = - QStringLiteral("-").repeated(ui->separatorColumnWidthSpinBox->value()); + QString headline = QStringLiteral("-").repeated(ui->separatorColumnWidthSpinBox->value()); for (int row = 0; row < ui->rowSpinBox->value(); row++) { // add all columns of the row for (int col = 0; col < ui->columnSpinBox->value(); col++) { auto item = ui->createTableWidget->item(row, col); QString itemText = item != nullptr ? item->text() : QString(); - text += - QStringLiteral("|") + - (itemText.isEmpty() ? space - : itemText.leftJustified(colWidth, ' ')); + text += QStringLiteral("|") + + (itemText.isEmpty() ? space : itemText.leftJustified(colWidth, ' ')); } text += QStringLiteral("|\n"); @@ -189,8 +181,7 @@ void TableDialog::on_headlineCheckBox_toggled(bool checked) { */ void TableDialog::on_fileButton_clicked() { ui->csvFileTextEdit->clear(); - QStringList filters = QStringList() << tr("CSV files") + " (*.csv)" - << tr("All files") + " (*)"; + QStringList filters = QStringList() << tr("CSV files") + " (*.csv)" << tr("All files") + " (*)"; FileDialog dialog(QStringLiteral("CSVTableImport")); dialog.setFileMode(QFileDialog::AnyFile); dialog.setAcceptMode(QFileDialog::AcceptOpen); @@ -256,7 +247,7 @@ void TableDialog::on_clipboardButton_clicked() { ui->csvFileTextEdit->setPlainText(text); _tempFile = new QTemporaryFile(QDir::tempPath() + QDir::separator() + - QStringLiteral("table-XXXXXX.csv")); + QStringLiteral("table-XXXXXX.csv")); if (!_tempFile->open()) { _tempFile = nullptr; @@ -274,15 +265,13 @@ void TableDialog::on_clipboardButton_clicked() { } } -void TableDialog::updateSeparator( - const QString &text) const { - const QStringList list = { "\t", ";", "," }; +void TableDialog::updateSeparator(const QString &text) const { + const QStringList list = {"\t", ";", ","}; - foreach(const QString &character, list) { + foreach (const QString &character, list) { if (text.contains(character)) { // set separator if found - ui->separatorComboBox->setCurrentText( - character == "\t" ? "\\t" : character); + ui->separatorComboBox->setCurrentText(character == "\t" ? "\\t" : character); return; } diff --git a/src/dialogs/tabledialog.h b/src/dialogs/tabledialog.h index f06b0a26d..8154a2fe0 100644 --- a/src/dialogs/tabledialog.h +++ b/src/dialogs/tabledialog.h @@ -1,9 +1,9 @@ #pragma once -#include "masterdialog.h" - #include <QTemporaryFile> +#include "masterdialog.h" + namespace Ui { class TableDialog; } @@ -30,7 +30,7 @@ class TableDialog : public MasterDialog { void on_clipboardButton_clicked(); -private: + private: enum Tab { CreateTab, ImportTab }; Ui::TableDialog *ui; diff --git a/src/dialogs/tagadddialog.cpp b/src/dialogs/tagadddialog.cpp index c34f4b068..9def86c8a 100644 --- a/src/dialogs/tagadddialog.cpp +++ b/src/dialogs/tagadddialog.cpp @@ -2,8 +2,7 @@ #include "ui_tagadddialog.h" -TagAddDialog::TagAddDialog(QWidget *parent) - : MasterDialog(parent), ui(new Ui::TagAddDialog) { +TagAddDialog::TagAddDialog(QWidget *parent) : MasterDialog(parent), ui(new Ui::TagAddDialog) { ui->setupUi(this); ui->nameLineEdit->setFocus(); resize(1, 1); diff --git a/src/dialogs/tododialog.cpp b/src/dialogs/tododialog.cpp index 11212c5dc..dd3f4fb22 100644 --- a/src/dialogs/tododialog.cpp +++ b/src/dialogs/tododialog.cpp @@ -98,40 +98,32 @@ void TodoDialog::setupUi() { ui->newItemEdit->setFocus(); // adding shortcuts, that weren't working when defined in the ui file - auto *shortcut = - new QShortcut(QKeySequence(QStringLiteral("Ctrl+S")), this); - QObject::connect(shortcut, SIGNAL(activated()), this, - SLOT(on_saveButton_clicked())); + auto *shortcut = new QShortcut(QKeySequence(QStringLiteral("Ctrl+S")), this); + QObject::connect(shortcut, SIGNAL(activated()), this, SLOT(on_saveButton_clicked())); shortcut = new QShortcut(QKeySequence(QStringLiteral("Ctrl+I")), this); - QObject::connect(shortcut, SIGNAL(activated()), this, - SLOT(onSaveAndInsertButtonClicked())); + QObject::connect(shortcut, SIGNAL(activated()), this, SLOT(onSaveAndInsertButtonClicked())); shortcut = new QShortcut(QKeySequence(QStringLiteral("Ctrl+R")), this); - QObject::connect(shortcut, SIGNAL(activated()), this, - SLOT(on_removeButton_clicked())); + QObject::connect(shortcut, SIGNAL(activated()), this, SLOT(on_removeButton_clicked())); /* * setup the note button menu */ auto *noteMenu = new QMenu(this); - QAction *insertAction = - noteMenu->addAction(tr("Save and insert into note")); + QAction *insertAction = noteMenu->addAction(tr("Save and insert into note")); insertAction->setIcon(QIcon::fromTheme( - QStringLiteral("document-save"), - QIcon(":icons/breeze-qownnotes/16x16/document-save.svg"))); + QStringLiteral("document-save"), QIcon(":icons/breeze-qownnotes/16x16/document-save.svg"))); insertAction->setToolTip( tr("Save the current todo item and insert a link" " to it into the current note")); - connect(insertAction, SIGNAL(triggered()), this, - SLOT(onSaveAndInsertButtonClicked())); + connect(insertAction, SIGNAL(triggered()), this, SLOT(onSaveAndInsertButtonClicked())); QAction *importAction = noteMenu->addAction(tr("Import as note")); - importAction->setIcon(QIcon::fromTheme( - QStringLiteral("document-import"), - QIcon(":icons/breeze-qownnotes/16x16/document-import.svg"))); + importAction->setIcon( + QIcon::fromTheme(QStringLiteral("document-import"), + QIcon(":icons/breeze-qownnotes/16x16/document-import.svg"))); importAction->setToolTip(tr("Import the current todo item as new note")); - connect(importAction, SIGNAL(triggered()), this, - SLOT(onImportAsNoteButtonClicked())); + connect(importAction, SIGNAL(triggered()), this, SLOT(onImportAsNoteButtonClicked())); ui->noteButton->setMenu(noteMenu); @@ -142,21 +134,17 @@ void TodoDialog::setupUi() { QAction *reloadAction = reloadMenu->addAction(tr("Reload from server")); reloadAction->setIcon(QIcon::fromTheme( - QStringLiteral("view-refresh"), - QIcon(":icons/breeze-qownnotes/16x16/view-refresh.svg"))); + QStringLiteral("view-refresh"), QIcon(":icons/breeze-qownnotes/16x16/view-refresh.svg"))); reloadAction->setToolTip(tr("Reload tasks from server")); connect(reloadAction, SIGNAL(triggered()), this, SLOT(reloadTodoList())); - QAction *clearCacheAction = - reloadMenu->addAction(tr("Clear cache and reload")); + QAction *clearCacheAction = reloadMenu->addAction(tr("Clear cache and reload")); clearCacheAction->setIcon(QIcon::fromTheme( - QStringLiteral("trash-empty"), - QIcon(":icons/breeze-qownnotes/16x16/trash-empty.svg"))); + QStringLiteral("trash-empty"), QIcon(":icons/breeze-qownnotes/16x16/trash-empty.svg"))); clearCacheAction->setToolTip( tr("Clear calendar cache and reload tasks " "from server")); - connect(clearCacheAction, SIGNAL(triggered()), this, - SLOT(clearCacheAndReloadTodoList())); + connect(clearCacheAction, SIGNAL(triggered()), this, SLOT(clearCacheAndReloadTodoList())); ui->reloadTodoListButton->setMenu(reloadMenu); } @@ -176,13 +164,11 @@ void TodoDialog::refreshUi() { Q_UNUSED(blocker) bool showCompletedItems = - settings.value(QStringLiteral("TodoDialog/showCompletedItems")) - .toBool(); + settings.value(QStringLiteral("TodoDialog/showCompletedItems")).toBool(); ui->showCompletedItemsCheckBox->setChecked(showCompletedItems); bool showDueTodayItemsOnly = - settings.value(QStringLiteral("TodoDialog/showDueTodayItemsOnly")) - .toBool(); + settings.value(QStringLiteral("TodoDialog/showDueTodayItemsOnly")).toBool(); ui->showDueTodayItemsOnlyCheckBox->setChecked(showDueTodayItemsOnly); } @@ -196,9 +182,8 @@ void TodoDialog::refreshUi() { ui->todoListSelector->setCurrentIndex(index); } else { // if we didn't find the index store the new current item - settings.setValue( - QStringLiteral("TodoDialog/todoListSelectorSelectedItem"), - ui->todoListSelector->currentText()); + settings.setValue(QStringLiteral("TodoDialog/todoListSelectorSelectedItem"), + ui->todoListSelector->currentText()); } // hide the reminder date time select @@ -216,9 +201,7 @@ void TodoDialog::setupMainSplitter() { // restore splitter sizes QSettings settings; - QByteArray state = - settings.value(QStringLiteral("TodoDialog/mainSplitterState")) - .toByteArray(); + QByteArray state = settings.value(QStringLiteral("TodoDialog/mainSplitterState")).toByteArray(); this->mainSplitter->restoreState(state); ui->gridLayout->layout()->addWidget(this->mainSplitter); @@ -234,8 +217,7 @@ void TodoDialog::loadTodoListData() { QSettings settings; ui->todoListSelector->clear(); ui->todoListSelector->addItems( - settings.value(QStringLiteral("ownCloud/todoCalendarEnabledList")) - .toStringList()); + settings.value(QStringLiteral("ownCloud/todoCalendarEnabledList")).toStringList()); } /** @@ -266,8 +248,7 @@ void TodoDialog::reloadTodoListItems() { int itemCount = calendarItemList.count(); MetricsService::instance()->sendEventIfEnabled( QStringLiteral("todo/list/loaded"), QStringLiteral("todo"), - QStringLiteral("todo list loaded"), - QString::number(itemCount) + " todo items", itemCount); + QStringLiteral("todo list loaded"), QString::number(itemCount) + " todo items", itemCount); { const QSignalBlocker blocker(ui->todoItemTreeWidget); @@ -313,13 +294,11 @@ void TodoDialog::reloadTodoListItems() { item->setText(0, calItem.getSummary()); item->setData(0, Qt::UserRole, uid); item->setData(0, Qt::UserRole + 1, relatedUid); - item->setCheckState( - 0, calItem.isCompleted() ? Qt::Checked : Qt::Unchecked); + item->setCheckState(0, calItem.isCompleted() ? Qt::Checked : Qt::Unchecked); item->setText(1, calItem.getAlarmDate().toString()); item->setData(1, Qt::DisplayRole, calItem.getAlarmDate()); - item->setFlags(Qt::ItemIsDragEnabled | Qt::ItemIsDropEnabled | - Qt::ItemIsEnabled | Qt::ItemIsUserCheckable | - Qt::ItemIsSelectable); + item->setFlags(Qt::ItemIsDragEnabled | Qt::ItemIsDropEnabled | Qt::ItemIsEnabled | + Qt::ItemIsUserCheckable | Qt::ItemIsSelectable); if (relatedUid.isEmpty()) { ui->todoItemTreeWidget->addTopLevelItem(item); @@ -345,8 +324,8 @@ void TodoDialog::reloadTodoListItems() { continue; } - auto parentItem = Utils::Gui::getTreeWidgetItemWithUserData( - ui->todoItemTreeWidget, relatedUid); + auto parentItem = + Utils::Gui::getTreeWidgetItemWithUserData(ui->todoItemTreeWidget, relatedUid); if (parentItem != nullptr) { parentItem->addChild(item); @@ -360,7 +339,6 @@ void TodoDialog::reloadTodoListItems() { ui->todoItemTreeWidget->resizeColumnToContents(0); ui->todoItemTreeWidget->resizeColumnToContents(1); - // set the current row of the task list to the first row jumpToTodoListItem(); @@ -392,8 +370,7 @@ void TodoDialog::jumpToTodoListItem() { // try to find a possible last created calendar item if ((item == nullptr) && lastCreatedCalendarItem.isFetched()) { - item = findTodoItemTreeWidgetItemByUID( - lastCreatedCalendarItem.getUid()); + item = findTodoItemTreeWidgetItemByUID(lastCreatedCalendarItem.getUid()); // clear the last created calendar item if we found it in the list if (item != nullptr) { @@ -403,8 +380,7 @@ void TodoDialog::jumpToTodoListItem() { if (item == nullptr) { // try to find the currently selected calendar item - item = - findTodoItemTreeWidgetItemByUID(currentCalendarItem.getUid()); + item = findTodoItemTreeWidgetItemByUID(currentCalendarItem.getUid()); } if (item != nullptr) { @@ -440,10 +416,8 @@ void TodoDialog::resetEditFrameControls() { * @return Returns the tree widget item of the task item in the task tree, * returns null if not found */ -QTreeWidgetItem *TodoDialog::findTodoItemTreeWidgetItemByUID( - const QString &uid) { - return Utils::Gui::getTreeWidgetItemWithUserData(ui->todoItemTreeWidget, - uid); +QTreeWidgetItem *TodoDialog::findTodoItemTreeWidgetItemByUID(const QString &uid) { + return Utils::Gui::getTreeWidgetItemWithUserData(ui->todoItemTreeWidget, uid); } void TodoDialog::storeSettings() { @@ -474,9 +448,8 @@ void TodoDialog::updateCurrentCalendarItemWithFormData() { currentCalendarItem.setSummary(ui->summaryEdit->text()); currentCalendarItem.setDescription(ui->descriptionEdit->toPlainText()); currentCalendarItem.setModified(QDateTime::currentDateTime()); - currentCalendarItem.setAlarmDate(ui->reminderCheckBox->isChecked() - ? ui->reminderDateTimeEdit->dateTime() - : QDateTime()); + currentCalendarItem.setAlarmDate( + ui->reminderCheckBox->isChecked() ? ui->reminderDateTimeEdit->dateTime() : QDateTime()); currentCalendarItem.store(); } @@ -531,8 +504,7 @@ void TodoDialog::on_showCompletedItemsCheckBox_clicked() { } void TodoDialog::on_saveButton_clicked() { - MetricsService::instance()->sendVisitIfEnabled( - QStringLiteral("todo/item/stored")); + MetricsService::instance()->sendVisitIfEnabled(QStringLiteral("todo/item/stored")); updateCurrentCalendarItemWithFormData(); @@ -563,9 +535,7 @@ void TodoDialog::todoItemLoadingProgressBarIncrement() { ui->todoItemLoadingProgressBar->setValue(value); } -void TodoDialog::todoItemLoadingProgressBarHide() { - ui->todoItemLoadingProgressBar->hide(); -} +void TodoDialog::todoItemLoadingProgressBarHide() { ui->todoItemLoadingProgressBar->hide(); } void TodoDialog::todoItemLoadingProgressBarSetMaximum(int value) { ui->todoItemLoadingProgressBar->setMaximum(value); @@ -573,8 +543,7 @@ void TodoDialog::todoItemLoadingProgressBarSetMaximum(int value) { } void TodoDialog::todoItemLoadingProgressBarHideIfOnMaximum() { - if (ui->todoItemLoadingProgressBar->value() >= - ui->todoItemLoadingProgressBar->maximum()) { + if (ui->todoItemLoadingProgressBar->value() >= ui->todoItemLoadingProgressBar->maximum()) { ui->todoItemLoadingProgressBar->hide(); } } @@ -585,10 +554,9 @@ void TodoDialog::on_todoItemLoadingProgressBar_valueChanged(int value) { todoItemLoadingProgressBarHideIfOnMaximum(); } -void TodoDialog::createNewTodoItem(const QString &name, - const QString &relatedUid) { - CalendarItem calItem = CalendarItem::createNewTodoItem( - name, ui->todoListSelector->currentText(), relatedUid); +void TodoDialog::createNewTodoItem(const QString &name, const QString &relatedUid) { + CalendarItem calItem = + CalendarItem::createNewTodoItem(name, ui->todoListSelector->currentText(), relatedUid); lastCreatedCalendarItem = calItem; // set the focus to the description edit after we loaded the tasks @@ -615,16 +583,14 @@ void TodoDialog::on_newItemEdit_returnPressed() { * @brief Removes the currently selected task from the ownCloud server */ void TodoDialog::on_removeButton_clicked() { - if (Utils::Gui::question( - this, tr("Remove todo item"), - tr("Remove the selected todo item?\nThis cannot be undone!"), - QStringLiteral("remove-todo-items")) == QMessageBox::Yes) { + if (Utils::Gui::question(this, tr("Remove todo item"), + tr("Remove the selected todo item?\nThis cannot be undone!"), + QStringLiteral("remove-todo-items")) == QMessageBox::Yes) { CalendarItem calItem = currentCalendarItem; // remove the calendar item from the list widget // (this will update the currentCalendarItem) - ui->todoItemTreeWidget->removeItemWidget( - ui->todoItemTreeWidget->currentItem(), 0); + ui->todoItemTreeWidget->removeItemWidget(ui->todoItemTreeWidget->currentItem(), 0); // remove the calendar item from the database calItem.remove(); @@ -676,13 +642,12 @@ void TodoDialog::on_newItemEdit_textChanged() { // search todo item if at least 2 characters were entered if (arg1.count() >= 2) { - QList<QString> uidList = CalendarItem::searchAsUidList( - arg1, ui->todoListSelector->currentText()); + QList<QString> uidList = + CalendarItem::searchAsUidList(arg1, ui->todoListSelector->currentText()); // hide all not found items Q_FOREACH (QTreeWidgetItem *item, allItems) { - bool show = - uidList.indexOf(item->data(0, Qt::UserRole).toString()) > -1; + bool show = uidList.indexOf(item->data(0, Qt::UserRole).toString()) > -1; item->setHidden(!show); } @@ -696,7 +661,9 @@ void TodoDialog::on_newItemEdit_textChanged() { } } else { // show all items otherwise - Q_FOREACH (QTreeWidgetItem *item, allItems) { item->setHidden(false); } + Q_FOREACH (QTreeWidgetItem *item, allItems) { + item->setHidden(false); + } } // let's highlight the text from the search line edit @@ -742,14 +709,12 @@ bool TodoDialog::eventFilter(QObject *obj, QEvent *event) { if (obj == ui->newItemEdit) { // set focus to the task list if Key_Down or Key_Tab // were pressed in the new item edit - if ((keyEvent->key() == Qt::Key_Down) || - (keyEvent->key() == Qt::Key_Tab)) { + if ((keyEvent->key() == Qt::Key_Down) || (keyEvent->key() == Qt::Key_Tab)) { // choose another selected item if current item is invisible auto *item = ui->todoItemTreeWidget->currentItem(); if ((item != nullptr) && item->isHidden() && (firstVisibleTodoItemTreeItem != nullptr)) { - ui->todoItemTreeWidget->setCurrentItem( - firstVisibleTodoItemTreeItem); + ui->todoItemTreeWidget->setCurrentItem(firstVisibleTodoItemTreeItem); } // give the keyboard focus to the task list widget @@ -799,9 +764,7 @@ void TodoDialog::onSaveAndInsertButtonClicked() { QString taskUrl = "task://" + currentCalendarItem.getUid(); // insert a link to the task in the current note - QString summaryText = selectedText.isEmpty() - ? currentCalendarItem.getSummary() - : selectedText; + QString summaryText = selectedText.isEmpty() ? currentCalendarItem.getSummary() : selectedText; QString insertText = "[" + summaryText + "](" + taskUrl + ")"; MainWindow::instance()->activeNoteTextEdit()->textCursor().insertText(insertText); @@ -818,8 +781,7 @@ void TodoDialog::onImportAsNoteButtonClicked() { // create a new note with the task text MainWindow::instance()->createNewNote( name, text, - MainWindow::CreateNewNoteOptions( - MainWindow::CreateNewNoteOption::UseNameAsHeadline)); + MainWindow::CreateNewNoteOptions(MainWindow::CreateNewNoteOption::UseNameAsHeadline)); } /** @@ -827,8 +789,8 @@ void TodoDialog::onImportAsNoteButtonClicked() { * @param current * @param previous */ -void TodoDialog::on_todoItemTreeWidget_currentItemChanged( - QTreeWidgetItem *current, QTreeWidgetItem *previous) { +void TodoDialog::on_todoItemTreeWidget_currentItemChanged(QTreeWidgetItem *current, + QTreeWidgetItem *previous) { Q_UNUSED(previous) // in case all items were removed @@ -837,8 +799,7 @@ void TodoDialog::on_todoItemTreeWidget_currentItemChanged( return; } - MetricsService::instance()->sendVisitIfEnabled( - QStringLiteral("todo/item/changed")); + MetricsService::instance()->sendVisitIfEnabled(QStringLiteral("todo/item/changed")); QString uid = current->data(0, Qt::UserRole).toString(); @@ -874,8 +835,7 @@ void TodoDialog::on_todoItemTreeWidget_currentItemChanged( * @param item * @param column */ -void TodoDialog::on_todoItemTreeWidget_itemChanged(QTreeWidgetItem *item, - int column) { +void TodoDialog::on_todoItemTreeWidget_itemChanged(QTreeWidgetItem *item, int column) { Q_UNUSED(column) QString uid = item->data(0, Qt::UserRole).toString(); @@ -909,9 +869,8 @@ void TodoDialog::on_todoItemTreeWidget_customContextMenuRequested(QPoint pos) { if (selectedItem) { if (selectedItem == newTaskAction) { bool ok; - QString name = QInputDialog::getText( - this, tr("Create new sub-task"), tr("Name:"), QLineEdit::Normal, - tr("New sub-task"), &ok); + QString name = QInputDialog::getText(this, tr("Create new sub-task"), tr("Name:"), + QLineEdit::Normal, tr("New sub-task"), &ok); if (ok) { createNewTodoItem(name, item->data(0, Qt::UserRole).toString()); diff --git a/src/dialogs/tododialog.h b/src/dialogs/tododialog.h index 5e3d6cc2a..81894d492 100644 --- a/src/dialogs/tododialog.h +++ b/src/dialogs/tododialog.h @@ -18,8 +18,7 @@ class TodoDialog : public MasterDialog { Q_OBJECT public: - explicit TodoDialog(const QString &taskUid = QString(), - QWidget *parent = nullptr); + explicit TodoDialog(const QString &taskUid = QString(), QWidget *parent = nullptr); ~TodoDialog(); void reloadTodoListItems(); @@ -55,7 +54,7 @@ class TodoDialog : public MasterDialog { void on_todoItemTreeWidget_customContextMenuRequested(QPoint pos); void on_showDueTodayItemsOnlyCheckBox_clicked(); -private: + private: Ui::TodoDialog *ui; QSplitter *mainSplitter; CalendarItem currentCalendarItem; diff --git a/src/dialogs/trashdialog.cpp b/src/dialogs/trashdialog.cpp index 0c6535ed0..ef3a1ef44 100644 --- a/src/dialogs/trashdialog.cpp +++ b/src/dialogs/trashdialog.cpp @@ -27,17 +27,16 @@ TrashDialog::TrashDialog(const QJSValue ¬es, QWidget *parent) ui->buttonBox->clear(); button = new QPushButton(tr("&Restore selected note on server")); - button->setToolTip(Utils::Misc::replaceOwnCloudText( - tr("<h3>Slower, but with note versions</h3>" - "<p>The note will be restored on your ownCloud " - "server with all versions.</p>" - "<p>You will have to wait until it is synced to " - "QOwnNotes by ownCloud sync.</p>"))); + button->setToolTip( + Utils::Misc::replaceOwnCloudText(tr("<h3>Slower, but with note versions</h3>" + "<p>The note will be restored on your ownCloud " + "server with all versions.</p>" + "<p>You will have to wait until it is synced to " + "QOwnNotes by ownCloud sync.</p>"))); button->setProperty("ActionRole", RestoreOnServer); button->setDefault(false); - button->setIcon(QIcon::fromTheme( - QStringLiteral("view-restore"), - QIcon(":/icons/breeze-qownnotes/16x16/view-restore.svg"))); + button->setIcon(QIcon::fromTheme(QStringLiteral("view-restore"), + QIcon(":/icons/breeze-qownnotes/16x16/view-restore.svg"))); ui->buttonBox->addButton(button, QDialogButtonBox::ActionRole); button = new QPushButton(tr("&Download selected note")); @@ -49,25 +48,22 @@ TrashDialog::TrashDialog(const QJSValue ¬es, QWidget *parent) "<p>You can always restore the note and its versions later.</p>"))); button->setProperty("ActionRole", Download); button->setDefault(false); - button->setIcon(QIcon::fromTheme( - QStringLiteral("edit-download"), - QIcon(":/icons/breeze-qownnotes/16x16/edit-download.svg"))); + button->setIcon(QIcon::fromTheme(QStringLiteral("edit-download"), + QIcon(":/icons/breeze-qownnotes/16x16/edit-download.svg"))); ui->buttonBox->addButton(button, QDialogButtonBox::ActionRole); button = new QPushButton(tr("&Delete")); button->setToolTip(tr("Delete selected note on server")); button->setProperty("ActionRole", DeleteOnServer); button->setDefault(false); - button->setIcon(QIcon::fromTheme( - QStringLiteral("edit-delete"), - QIcon(":/icons/breeze-qownnotes/16x16/edit-delete.svg"))); + button->setIcon(QIcon::fromTheme(QStringLiteral("edit-delete"), + QIcon(":/icons/breeze-qownnotes/16x16/edit-delete.svg"))); ui->buttonBox->addButton(button, QDialogButtonBox::ActionRole); button = new QPushButton(tr("&Cancel")); button->setProperty("ActionRole", Cancel); - button->setIcon(QIcon::fromTheme( - QStringLiteral("dialog-cancel"), - QIcon(":/icons/breeze-qownnotes/16x16/dialog-cancel.svg"))); + button->setIcon(QIcon::fromTheme(QStringLiteral("dialog-cancel"), + QIcon(":/icons/breeze-qownnotes/16x16/dialog-cancel.svg"))); button->setDefault(true); ui->buttonBox->addButton(button, QDialogButtonBox::ActionRole); @@ -90,8 +86,7 @@ TrashDialog::TrashDialog(const QJSValue ¬es, QWidget *parent) while (notesIterator.hasNext()) { notesIterator.next(); - QJSValue property = - notesIterator.value().property(QStringLiteral("noteName")); + QJSValue property = notesIterator.value().property(QStringLiteral("noteName")); if (property.isUndefined()) { continue; @@ -103,16 +98,10 @@ TrashDialog::TrashDialog(const QJSValue ¬es, QWidget *parent) continue; } - dateString = notesIterator.value() - .property(QStringLiteral("dateString")) - .toString(); - data = - notesIterator.value().property(QStringLiteral("data")).toString(); - timestamp = - notesIterator.value().property(QStringLiteral("timestamp")).toInt(); - QString fileName = notesIterator.value() - .property(QStringLiteral("fileName")) - .toString(); + dateString = notesIterator.value().property(QStringLiteral("dateString")).toString(); + data = notesIterator.value().property(QStringLiteral("data")).toString(); + timestamp = notesIterator.value().property(QStringLiteral("timestamp")).toInt(); + QString fileName = notesIterator.value().property(QStringLiteral("fileName")).toString(); auto *item = new QListWidgetItem(); item->setText(itemName); @@ -137,8 +126,7 @@ void TrashDialog::setupMainSplitter() { // restore splitter sizes QSettings settings; - QByteArray state = - settings.value(QStringLiteral("trashSplitterSizes")).toByteArray(); + QByteArray state = settings.value(QStringLiteral("trashSplitterSizes")).toByteArray(); trashSplitter->restoreState(state); ui->gridLayout->layout()->addWidget(trashSplitter); @@ -148,8 +136,7 @@ void TrashDialog::setupMainSplitter() { void TrashDialog::storeSettings() { // store the splitter sizes QSettings settings; - settings.setValue(QStringLiteral("trashSplitterSizes"), - trashSplitter->saveState()); + settings.setValue(QStringLiteral("trashSplitterSizes"), trashSplitter->saveState()); } TrashDialog::~TrashDialog() { delete ui; } @@ -163,20 +150,17 @@ void TrashDialog::dialogButtonClicked(QAbstractButton *button) { int actionRole = button->property("ActionRole").toInt(); QString name = ui->trashListWidget->currentItem()->text(); - QString fileName = - ui->trashListWidget->currentItem()->data(Qt::UserRole).toString(); + QString fileName = ui->trashListWidget->currentItem()->data(Qt::UserRole).toString(); switch (actionRole) { case Download: { - QString text = - dataList->value(ui->trashListWidget->currentRow()); + QString text = dataList->value(ui->trashListWidget->currentRow()); MainWindow::instance()->createNewNote(name, text); break; } case RestoreOnServer: { - int timestamp = this->timestampList->value( - ui->trashListWidget->currentRow()); + int timestamp = this->timestampList->value(ui->trashListWidget->currentRow()); qDebug() << name << timestamp; MainWindow::instance()->restoreTrashedNoteOnServer(fileName, timestamp); @@ -184,34 +168,29 @@ void TrashDialog::dialogButtonClicked(QAbstractButton *button) { } case DeleteOnServer: { - if (Utils::Gui::question( - this, tr("Delete note on server"), - tr("Delete selected trashed note on server?"), - "trashdialog-delete", - QMessageBox::Yes | QMessageBox::No, - QMessageBox::No) == QMessageBox::No) { + if (Utils::Gui::question(this, tr("Delete note on server"), + tr("Delete selected trashed note on server?"), + "trashdialog-delete", QMessageBox::Yes | QMessageBox::No, + QMessageBox::No) == QMessageBox::No) { return; } - const int timestamp = this->timestampList->value( - ui->trashListWidget->currentRow()); + const int timestamp = this->timestampList->value(ui->trashListWidget->currentRow()); auto currentItem = ui->trashListWidget->currentItem(); OwnCloudService *ownCloud = OwnCloudService::instance(); ui->trashListWidget->setDisabled(true); ui->buttonBox->setDisabled(true); // delete trashed note on server - const int statusCode = ownCloud->deleteTrashedNoteOnServer( - fileName, timestamp); + const int statusCode = ownCloud->deleteTrashedNoteOnServer(fileName, timestamp); if (statusCode >= 200 && statusCode < 300) { delete currentItem; } else { - Utils::Gui::warning( - this, tr("Error while deleting note"), - tr("Deleting trashed note failed with status code: %1").arg( - QString::number(statusCode)), - "trashdialog-delete-failed"); + Utils::Gui::warning(this, tr("Error while deleting note"), + tr("Deleting trashed note failed with status code: %1") + .arg(QString::number(statusCode)), + "trashdialog-delete-failed"); } ui->trashListWidget->setDisabled(false); diff --git a/src/dialogs/updatedialog.cpp b/src/dialogs/updatedialog.cpp index c92900046..cd3fc969c 100644 --- a/src/dialogs/updatedialog.cpp +++ b/src/dialogs/updatedialog.cpp @@ -18,8 +18,7 @@ #include "ui_updatedialog.h" -UpdateDialog::UpdateDialog(QWidget *parent, const QString &changesHtml, - const QString &releaseUrl, +UpdateDialog::UpdateDialog(QWidget *parent, const QString &changesHtml, const QString &releaseUrl, const QString &releaseVersionString) : MasterDialog(parent), ui(new Ui::UpdateDialog) { ui->setupUi(this); @@ -33,8 +32,7 @@ UpdateDialog::UpdateDialog(QWidget *parent, const QString &changesHtml, "https://www.qownnotes.org/contributing/get-involved.html")); // inject some generic CSS styles - ui->changeLogEdit->document()->setDefaultStyleSheet( - Utils::Misc::genericCSS()); + ui->changeLogEdit->document()->setDefaultStyleSheet(Utils::Misc::genericCSS()); // ui->label_4->setText("<style>" + Utils::Misc::genericCSS() + // "</style>" + ui->label_4->text()); @@ -51,8 +49,8 @@ UpdateDialog::UpdateDialog(QWidget *parent, const QString &changesHtml, _updateButton = new QPushButton(tr("&Update")); _updateButton->setProperty("ActionRole", Update); _updateButton->setDefault(true); - _updateButton->setIcon(QIcon::fromTheme( - "svn-update", QIcon(":/icons/breeze-qownnotes/16x16/svn-update.svg"))); + _updateButton->setIcon( + QIcon::fromTheme("svn-update", QIcon(":/icons/breeze-qownnotes/16x16/svn-update.svg"))); ui->buttonBox->addButton(_updateButton, QDialogButtonBox::ActionRole); #ifdef Q_OS_LINUX @@ -66,9 +64,8 @@ UpdateDialog::UpdateDialog(QWidget *parent, const QString &changesHtml, } #endif - button->setIcon(QIcon::fromTheme( - QStringLiteral("edit-download"), - QIcon(":/icons/breeze-qownnotes/16x16/edit-download.svg"))); + button->setIcon(QIcon::fromTheme(QStringLiteral("edit-download"), + QIcon(":/icons/breeze-qownnotes/16x16/edit-download.svg"))); ui->buttonBox->addButton(button, QDialogButtonBox::ActionRole); button = new QPushButton(tr("&Skip version")); @@ -83,16 +80,15 @@ UpdateDialog::UpdateDialog(QWidget *parent, const QString &changesHtml, button->setToolTip(tr("Don't show this dialog automatically")); button->setProperty("ActionRole", Disable); button->setDefault(false); - button->setIcon(QIcon::fromTheme(QStringLiteral("window-close"), - QIcon(":/icons/breeze-qownnotes/16x16/" - "window-close.svg"))); + button->setIcon( + QIcon::fromTheme(QStringLiteral("window-close"), QIcon(":/icons/breeze-qownnotes/16x16/" + "window-close.svg"))); ui->buttonBox->addButton(button, QDialogButtonBox::ActionRole); button = new QPushButton(tr("&Cancel"), this); button->setProperty("ActionRole", Cancel); - button->setIcon(QIcon::fromTheme( - QStringLiteral("dialog-cancel"), - QIcon(":/icons/breeze-qownnotes/16x16/dialog-cancel.svg"))); + button->setIcon(QIcon::fromTheme(QStringLiteral("dialog-cancel"), + QIcon(":/icons/breeze-qownnotes/16x16/dialog-cancel.svg"))); button->setDefault(false); ui->buttonBox->addButton(button, QDialogButtonBox::ActionRole); @@ -129,15 +125,13 @@ void UpdateDialog::dialogButtonClicked(QAbstractButton *button) { switch (actionRole) { case Skip: { QSettings settings; - settings.setValue(QStringLiteral("skipVersion"), - this->releaseVersionString); + settings.setValue(QStringLiteral("skipVersion"), this->releaseVersionString); qDebug() << "skip version"; break; } case Disable: { QSettings settings; - settings.setValue(QStringLiteral("disableAutomaticUpdateDialog"), - true); + settings.setValue(QStringLiteral("disableAutomaticUpdateDialog"), true); qDebug() << "disable dialog"; break; } @@ -145,8 +139,7 @@ void UpdateDialog::dialogButtonClicked(QAbstractButton *button) { QString release = qApp->property("release").toString(); // if the release was build by the CI systems download the new // release - if ((release == QLatin1String("Travis CI")) || - (release == QLatin1String("AppVeyor"))) { + if ((release == QLatin1String("Travis CI")) || (release == QLatin1String("AppVeyor"))) { // download the new release QDesktopServices::openUrl(QUrl(releaseUrl.toUtf8())); } else if ((release == QLatin1String("AppImage"))) { @@ -154,8 +147,8 @@ void UpdateDialog::dialogButtonClicked(QAbstractButton *button) { QDesktopServices::openUrl(QUrl(releaseUrl.toUtf8())); } else { // open the installation page - QDesktopServices::openUrl(QUrl( - QStringLiteral("https://www.qownnotes.org/installation"))); + QDesktopServices::openUrl( + QUrl(QStringLiteral("https://www.qownnotes.org/installation"))); } break; } @@ -184,17 +177,14 @@ void UpdateDialog::dialogButtonClicked(QAbstractButton *button) { #if (QT_VERSION < QT_VERSION_CHECK(5, 9, 0)) // we really need redirects for GitHub urls! - networkRequest.setAttribute( - QNetworkRequest::FollowRedirectsAttribute, true); + networkRequest.setAttribute(QNetworkRequest::FollowRedirectsAttribute, true); #else - networkRequest.setAttribute( - QNetworkRequest::RedirectPolicyAttribute, true); + networkRequest.setAttribute(QNetworkRequest::RedirectPolicyAttribute, true); #endif #if (QT_VERSION < QT_VERSION_CHECK(5, 15, 0)) // try to ensure the network is accessible - _networkManager->setNetworkAccessible( - QNetworkAccessManager::Accessible); + _networkManager->setNetworkAccessible(QNetworkAccessManager::Accessible); #endif QNetworkReply *reply = _networkManager->get(networkRequest); @@ -217,8 +207,7 @@ void UpdateDialog::dialogButtonClicked(QAbstractButton *button) { /** * Shows the download progress */ -void UpdateDialog::releaseDownloadProgress(qint64 bytesReceived, - qint64 bytesTotal) { +void UpdateDialog::releaseDownloadProgress(qint64 bytesReceived, qint64 bytesTotal) { ui->downloadProgressBar->setMaximum(static_cast<int>(bytesTotal)); ui->downloadProgressBar->setValue(static_cast<int>(bytesReceived)); } @@ -243,9 +232,8 @@ void UpdateDialog::slotReplyFinished(QNetworkReply *reply) { qDebug() << __func__ << " - 'data.size': " << data.size(); if (reply->error() != QNetworkReply::NoError) { - QMessageBox::critical( - 0, tr("Download error"), - tr("Error while downloading:\n%1").arg(reply->errorString())); + QMessageBox::critical(0, tr("Download error"), + tr("Error while downloading:\n%1").arg(reply->errorString())); qWarning() << tr("network error: %1").arg(reply->errorString()); _updateButton->setDisabled(false); @@ -261,17 +249,16 @@ void UpdateDialog::slotReplyFinished(QNetworkReply *reply) { QString suffix = "download"; #endif - QTemporaryFile *tempFile = - new QTemporaryFile(QDir::tempPath() + "/QOwnNotes-XXXXXX." + suffix); + QTemporaryFile *tempFile = new QTemporaryFile(QDir::tempPath() + "/QOwnNotes-XXXXXX." + suffix); // we want to keep the file to be used in the update process tempFile->setAutoRemove(false); // get a temporary file if (!tempFile->open()) { - QMessageBox::critical(0, tr("File error"), - tr("Could not open temporary file:\n%1") - .arg(tempFile->errorString())); + QMessageBox::critical( + 0, tr("File error"), + tr("Could not open temporary file:\n%1").arg(tempFile->errorString())); return; } @@ -289,9 +276,8 @@ void UpdateDialog::slotReplyFinished(QNetworkReply *reply) { QFile file(filePath); if (!file.open(QIODevice::WriteOnly)) { - QMessageBox::critical( - 0, tr("File error"), - tr("Could not store downloaded file:\n%1").arg(file.errorString())); + QMessageBox::critical(0, tr("File error"), + tr("Could not store downloaded file:\n%1").arg(file.errorString())); return; } @@ -337,14 +323,13 @@ bool UpdateDialog::initializeMacOSUpdateProcess(const QString &releaseUrl) { QString applicationsPath = QStringLiteral("/Applications"); if (applicationDirPath.endsWith(appPathPart)) { - applicationsPath = Utils::Misc::removeIfEndsWith( - std::move(applicationDirPath), appPathPart); + applicationsPath = + Utils::Misc::removeIfEndsWith(std::move(applicationDirPath), appPathPart); } if (Utils::Gui::question(this, tr("Proceed with update"), tr("Do you want to update and restart QOwnNotes?"), - QStringLiteral("update-and-restart")) != - QMessageBox::Yes) { + QStringLiteral("update-and-restart")) != QMessageBox::Yes) { return false; } @@ -357,9 +342,8 @@ bool UpdateDialog::initializeMacOSUpdateProcess(const QString &releaseUrl) { QFile f(updaterPath); if (!f.exists()) { - QMessageBox::critical( - 0, tr("Error"), - tr("Could not find updater file:\n%1").arg(f.fileName())); + QMessageBox::critical(0, tr("Error"), + tr("Could not find updater file:\n%1").arg(f.fileName())); return false; } @@ -368,25 +352,23 @@ bool UpdateDialog::initializeMacOSUpdateProcess(const QString &releaseUrl) { QTextStream ts(&f); QString scriptContent = ts.readAll(); f.close(); - scriptContent.replace(QLatin1String("\"$QOWNNOTES_RELEASE_URL\""), - "\"" + releaseUrl + "\""); - scriptContent.replace( - QLatin1String("\"$QOWNNOTES_APPLICATIONS_PATH\""), - "\"" + QDir::toNativeSeparators(applicationsPath) + "\""); + scriptContent.replace(QLatin1String("\"$QOWNNOTES_RELEASE_URL\""), "\"" + releaseUrl + "\""); + scriptContent.replace(QLatin1String("\"$QOWNNOTES_APPLICATIONS_PATH\""), + "\"" + QDir::toNativeSeparators(applicationsPath) + "\""); // we need a temporary script file with hardcoded parameters because some // users were not able to get parameters via the system environment - QTemporaryFile *tempFile = new QTemporaryFile( - QDir::tempPath() + "/QOwnNotes-Updater-XXXXXX.command"); + QTemporaryFile *tempFile = + new QTemporaryFile(QDir::tempPath() + "/QOwnNotes-Updater-XXXXXX.command"); // we want to keep the file to be used in the update process tempFile->setAutoRemove(false); // get a temporary file if (!tempFile->open()) { - QMessageBox::critical(0, tr("File error"), - tr("Could not open temporary file:\n%1") - .arg(tempFile->errorString())); + QMessageBox::critical( + 0, tr("File error"), + tr("Could not open temporary file:\n%1").arg(tempFile->errorString())); return false; } @@ -394,8 +376,7 @@ bool UpdateDialog::initializeMacOSUpdateProcess(const QString &releaseUrl) { tempFile->write(scriptContent.toLatin1()); // setting executable permissions to the updater script - tempFile->setPermissions(QFile::ExeUser | QFile::ReadUser | - QFile::WriteUser); + tempFile->setPermissions(QFile::ExeUser | QFile::ReadUser | QFile::WriteUser); // file->fileName() only holds a value after file->open() QString updaterFilePath = tempFile->fileName(); @@ -440,9 +421,9 @@ bool UpdateDialog::initializeLinuxUpdateProcess(const QString &filePath) { if (!fileInfo.isWritable()) { QMessageBox::critical(0, tr("Permission error"), - tr("Your QOwnNotes executable '%1' is not writeable! It must be " - "writeable by the current user in order to be updated.") - .arg(appPath)); + tr("Your QOwnNotes executable '%1' is not writeable! It must be " + "writeable by the current user in order to be updated.") + .arg(appPath)); return false; } @@ -452,9 +433,9 @@ bool UpdateDialog::initializeLinuxUpdateProcess(const QString &filePath) { // make the new AppImage executable if (!updateFile.setPermissions(updateFile.permissions() | QFileDevice::ExeOwner)) { QMessageBox::critical(0, tr("Permission error"), - tr("The temporary file '%1' could not be made executable! " - "You need to replace '%2' yourself.") - .arg(filePath, appPath)); + tr("The temporary file '%1' could not be made executable! " + "You need to replace '%2' yourself.") + .arg(filePath, appPath)); return false; } @@ -462,9 +443,9 @@ bool UpdateDialog::initializeLinuxUpdateProcess(const QString &filePath) { // remove the current binary if (!file.remove()) { QMessageBox::critical(0, tr("File error"), - tr("Your old QOwnNotes executable '%1' could not be removed! " - "You need to replace it yourself with '%2'.") - .arg(appPath, filePath)); + tr("Your old QOwnNotes executable '%1' could not be removed! " + "You need to replace it yourself with '%2'.") + .arg(appPath, filePath)); return false; } @@ -472,9 +453,9 @@ bool UpdateDialog::initializeLinuxUpdateProcess(const QString &filePath) { // rename the new AppImage to the path of the current binary if (!updateFile.rename(appPath)) { QMessageBox::critical(0, tr("File error"), - tr("Your old QOwnNotes executable '%1' could not be replaced " - "by the new file '%2'! You need to replace it yourself.") - .arg(appPath, filePath)); + tr("Your old QOwnNotes executable '%1' could not be replaced " + "by the new file '%2'! You need to replace it yourself.") + .arg(appPath, filePath)); return false; } @@ -513,75 +494,67 @@ bool UpdateDialog::initializeWindowsUpdateProcess(const QString &filePath) { QString updaterPath = pathPrefix + "-updater.bat"; QString unzipPath = pathPrefix + "-unzip.exe"; - QFile updaterSourceFile(QCoreApplication::applicationDirPath() + - "/update.bat"); - QFile unzipSourceFile(QCoreApplication::applicationDirPath() + - "/unzip.exe"); + QFile updaterSourceFile(QCoreApplication::applicationDirPath() + "/update.bat"); + QFile unzipSourceFile(QCoreApplication::applicationDirPath() + "/unzip.exe"); // check if updater script exists if (!updaterSourceFile.exists()) { - QMessageBox::critical(0, tr("Error"), - tr("Updater script '%1' doesn't exist!") - .arg(updaterSourceFile.fileName())); + QMessageBox::critical( + 0, tr("Error"), + tr("Updater script '%1' doesn't exist!").arg(updaterSourceFile.fileName())); return false; } // check if unzip executable exists if (!unzipSourceFile.exists()) { - QMessageBox::critical(0, tr("Error"), - tr("Updater unzip executable '%1' doesn't exist!") - .arg(unzipSourceFile.fileName())); + QMessageBox::critical( + 0, tr("Error"), + tr("Updater unzip executable '%1' doesn't exist!").arg(unzipSourceFile.fileName())); return false; } // copy updater script if (!updaterSourceFile.copy(updaterPath)) { - QMessageBox::critical( - 0, tr("Error"), - tr("Could not copy updater script '%1' to '%2'!") - .arg(updaterSourceFile.fileName(), unzipPath)); + QMessageBox::critical(0, tr("Error"), + tr("Could not copy updater script '%1' to '%2'!") + .arg(updaterSourceFile.fileName(), unzipPath)); return false; } // copy unzip executable script if (!unzipSourceFile.copy(unzipPath)) { - QMessageBox::critical( - 0, tr("Error"), - tr("Could not copy updater script '%1' to '%2'!") - .arg(updaterSourceFile.fileName(), unzipPath)); + QMessageBox::critical(0, tr("Error"), + tr("Could not copy updater script '%1' to '%2'!") + .arg(updaterSourceFile.fileName(), unzipPath)); return false; } // check if updater script exists in temporary folder QFile updaterFile(updaterPath); if (!updaterFile.exists()) { - QMessageBox::critical( - 0, tr("Error"), - tr("Couldn't find updater script: %1").arg(updaterPath)); + QMessageBox::critical(0, tr("Error"), + tr("Couldn't find updater script: %1").arg(updaterPath)); return false; } // check if unzip executable exists in temporary folder QFile unzipFile(unzipPath); if (!unzipFile.exists()) { - QMessageBox::critical( - 0, tr("Error"), - tr("Couldn't find unzip executable: %1").arg(unzipPath)); + QMessageBox::critical(0, tr("Error"), + tr("Couldn't find unzip executable: %1").arg(unzipPath)); return false; } - if (Utils::Gui::question( - this, tr("Proceed with update"), - tr("The download is now finished. Do you want to update and " - "restart QOwnNotes?"), - QStringLiteral("update-and-restart")) != QMessageBox::Yes) { + if (Utils::Gui::question(this, tr("Proceed with update"), + tr("The download is now finished. Do you want to update and " + "restart QOwnNotes?"), + QStringLiteral("update-and-restart")) != QMessageBox::Yes) { return false; } QStringList parameters(QStringList() << QDir::toNativeSeparators(filePath) - << QDir::toNativeSeparators( - QCoreApplication::applicationDirPath()) + << QDir::toNativeSeparators(QCoreApplication::applicationDirPath()) << QDir::toNativeSeparators(unzipPath)); if (Utils::Misc::isInPortableMode()) { @@ -600,9 +573,7 @@ bool UpdateDialog::initializeWindowsUpdateProcess(const QString &filePath) { /** * Checks if the update dialog is open */ -bool UpdateDialog::isUpdateDialogOpen() { - return qApp->property("isUpdateDialogOpen").toBool(); -} +bool UpdateDialog::isUpdateDialogOpen() { return qApp->property("isUpdateDialogOpen").toBool(); } /** * Sets if the update dialog is open diff --git a/src/dialogs/updatedialog.h b/src/dialogs/updatedialog.h index 76f01eef7..24e4acc8e 100644 --- a/src/dialogs/updatedialog.h +++ b/src/dialogs/updatedialog.h @@ -15,8 +15,7 @@ class UpdateDialog : public MasterDialog { Q_OBJECT public: - explicit UpdateDialog(QWidget *parent = nullptr, - const QString &changesHtml = QString(), + explicit UpdateDialog(QWidget *parent = nullptr, const QString &changesHtml = QString(), const QString &releaseUrl = QString(), const QString &releaseVersionString = QString()); ~UpdateDialog(); diff --git a/src/dialogs/versiondialog.cpp b/src/dialogs/versiondialog.cpp index 30e07c0f2..6af5390a1 100644 --- a/src/dialogs/versiondialog.cpp +++ b/src/dialogs/versiondialog.cpp @@ -29,16 +29,14 @@ VersionDialog::VersionDialog(const QJSValue &versions, QWidget *parent) button = new QPushButton(tr("&Restore selected version")); button->setProperty("ActionRole", Restore); button->setDefault(false); - button->setIcon(QIcon::fromTheme( - QStringLiteral("edit-download"), - QIcon(":/icons/breeze-qownnotes/16x16/edit-download.svg"))); + button->setIcon(QIcon::fromTheme(QStringLiteral("edit-download"), + QIcon(":/icons/breeze-qownnotes/16x16/edit-download.svg"))); ui->buttonBox->addButton(button, QDialogButtonBox::ActionRole); button = new QPushButton(tr("&Cancel")); button->setProperty("ActionRole", Cancel); - button->setIcon(QIcon::fromTheme( - QStringLiteral("dialog-cancel"), - QIcon(":/icons/breeze-qownnotes/16x16/dialog-cancel.svg"))); + button->setIcon(QIcon::fromTheme(QStringLiteral("dialog-cancel"), + QIcon(":/icons/breeze-qownnotes/16x16/dialog-cancel.svg"))); button->setDefault(true); ui->buttonBox->addButton(button, QDialogButtonBox::ActionRole); @@ -63,8 +61,8 @@ VersionDialog::VersionDialog(const QJSValue &versions, QWidget *parent) // iterate over the versions while (versionsIterator.hasNext()) { versionsIterator.next(); - QJSValue property = versionsIterator.value().property( - QStringLiteral("humanReadableTimestamp")); + QJSValue property = + versionsIterator.value().property(QStringLiteral("humanReadableTimestamp")); if (property.isUndefined()) { continue; @@ -77,17 +75,13 @@ VersionDialog::VersionDialog(const QJSValue &versions, QWidget *parent) } diffHtml = "<style>" + Utils::Misc::genericCSS() + "</style>" + - versionsIterator.value() - .property(QStringLiteral("diffHtml")) - .toString(); + versionsIterator.value().property(QStringLiteral("diffHtml")).toString(); diffHtml.replace(QLatin1String("\\n"), QLatin1String("¶<br />")); diffHtml.replace(QLatin1String("\n"), QLatin1String("<br />")); ui->versionListWidget->addItem(itemName); diffList->append(diffHtml); - dataList->append(versionsIterator.value() - .property(QStringLiteral("data")) - .toString()); + dataList->append(versionsIterator.value().property(QStringLiteral("data")).toString()); } ui->versionListWidget->setCurrentRow(0); @@ -102,8 +96,7 @@ void VersionDialog::setupMainSplitter() { // restore splitter sizes QSettings settings; - QByteArray state = - settings.value(QStringLiteral("versionSplitterSizes")).toByteArray(); + QByteArray state = settings.value(QStringLiteral("versionSplitterSizes")).toByteArray(); versionSplitter->restoreState(state); ui->gridLayout->addWidget(versionSplitter); @@ -112,8 +105,7 @@ void VersionDialog::setupMainSplitter() { void VersionDialog::storeSettings() { // store the splitter sizes QSettings settings; - settings.setValue(QStringLiteral("versionSplitterSizes"), - versionSplitter->saveState()); + settings.setValue(QStringLiteral("versionSplitterSizes"), versionSplitter->saveState()); } VersionDialog::~VersionDialog() { delete ui; } diff --git a/src/dialogs/websockettokendialog.cpp b/src/dialogs/websockettokendialog.cpp index e6dfb8852..09bc65f7e 100644 --- a/src/dialogs/websockettokendialog.cpp +++ b/src/dialogs/websockettokendialog.cpp @@ -12,9 +12,7 @@ WebSocketTokenDialog::WebSocketTokenDialog(QWidget *parent) ui->setupUi(this); QSettings settings; - QString token = - settings.value(QStringLiteral("webSocketServerService/token")) - .toString(); + QString token = settings.value(QStringLiteral("webSocketServerService/token")).toString(); if (token.isEmpty()) { on_generateButton_clicked(); @@ -24,9 +22,7 @@ WebSocketTokenDialog::WebSocketTokenDialog(QWidget *parent) } } -QString WebSocketTokenDialog::generateToken() const { - return Utils::Misc::generateRandomString(8); -} +QString WebSocketTokenDialog::generateToken() const { return Utils::Misc::generateRandomString(8); } WebSocketTokenDialog::~WebSocketTokenDialog() { delete ui; } @@ -45,6 +41,5 @@ void WebSocketTokenDialog::on_generateButton_clicked() { void WebSocketTokenDialog::on_buttonBox_accepted() { QSettings settings; - settings.setValue(QStringLiteral("webSocketServerService/token"), - ui->tokenLineEdit->text()); + settings.setValue(QStringLiteral("webSocketServerService/token"), ui->tokenLineEdit->text()); } diff --git a/src/dialogs/welcomedialog.cpp b/src/dialogs/welcomedialog.cpp index 0a0d6399a..746448029 100644 --- a/src/dialogs/welcomedialog.cpp +++ b/src/dialogs/welcomedialog.cpp @@ -12,16 +12,13 @@ #include "settingsdialog.h" #include "ui_welcomedialog.h" -WelcomeDialog::WelcomeDialog(QWidget *parent) - : MasterDialog(parent), ui(new Ui::WelcomeDialog) { +WelcomeDialog::WelcomeDialog(QWidget *parent) : MasterDialog(parent), ui(new Ui::WelcomeDialog) { ui->setupUi(this); ui->layoutWidget->setManualSettingsStoring(false); // replace ownCloud text - ui->subHeadlineLabel->setText( - Utils::Misc::replaceOwnCloudText(ui->subHeadlineLabel->text())); - ui->groupBox_2->setTitle( - Utils::Misc::replaceOwnCloudText(ui->groupBox_2->title())); + ui->subHeadlineLabel->setText(Utils::Misc::replaceOwnCloudText(ui->subHeadlineLabel->text())); + ui->groupBox_2->setTitle(Utils::Misc::replaceOwnCloudText(ui->groupBox_2->title())); ui->label->setText(Utils::Misc::replaceOwnCloudText(ui->label->text())); ui->label_4->setText(Utils::Misc::replaceOwnCloudText(ui->label_4->text())); ui->ownCloudSettingsButton->setText( @@ -30,8 +27,7 @@ WelcomeDialog::WelcomeDialog(QWidget *parent) // if note layout has already been set, we can finish settings in the first // step QSettings settings; - _allowFinishButton = - settings.contains(QStringLiteral("workspace-initial/windowState")); + _allowFinishButton = settings.contains(QStringLiteral("workspace-initial/windowState")); ui->finishButton->setEnabled(_allowFinishButton); ui->backButton->setEnabled(false); @@ -46,15 +42,13 @@ WelcomeDialog::WelcomeDialog(QWidget *parent) WelcomeDialog::~WelcomeDialog() { delete ui; } void WelcomeDialog::on_cancelButton_clicked() { - MetricsService::instance()->sendVisitIfEnabled( - QStringLiteral("welcome-dialog/cancel")); + MetricsService::instance()->sendVisitIfEnabled(QStringLiteral("welcome-dialog/cancel")); done(QDialog::Rejected); } void WelcomeDialog::on_nextButton_clicked() { - MetricsService::instance()->sendVisitIfEnabled( - QStringLiteral("welcome-dialog/next")); + MetricsService::instance()->sendVisitIfEnabled(QStringLiteral("welcome-dialog/next")); int index = ui->stackedWidget->currentIndex(); int maxIndex = ui->stackedWidget->count() - 1; @@ -96,14 +90,12 @@ bool WelcomeDialog::handleNoteFolderSetup() { // everything is all right, the path already exists _allowFinishButton = true; - Utils::Misc::printInfo( - QStringLiteral("Note path '%1' exists.").arg(_notesPath)); + Utils::Misc::printInfo(QStringLiteral("Note path '%1' exists.").arg(_notesPath)); } else { if (ui->createNoteFolderCheckBox->isChecked()) { - Utils::Misc::printInfo( - QString("Note path '%1' doesn't exist yet and will " - "be created.") - .arg(_notesPath)); + Utils::Misc::printInfo(QString("Note path '%1' doesn't exist yet and will " + "be created.") + .arg(_notesPath)); // mkpath should only return true if the path was created, but we // want to double-check because there were some troubles on Windows @@ -114,16 +106,14 @@ bool WelcomeDialog::handleNoteFolderSetup() { _allowFinishButton = true; Utils::Misc::printInfo( - QStringLiteral("Note path '%1' was now created.") - .arg(_notesPath)); + QStringLiteral("Note path '%1' was now created.").arg(_notesPath)); } else { qWarning() << "Cannot create note path with mkpath!"; showNoteFolderErrorMessage( tr("Cannot create note path! You have to create " "the note folder manually!")); MetricsService::instance()->sendVisitIfEnabled( - QStringLiteral( - "welcome-dialog/note-folder/cannot-create-mkpath")); + QStringLiteral("welcome-dialog/note-folder/cannot-create-mkpath")); } } else { qWarning() << "Cannot create note path!"; @@ -164,16 +154,14 @@ void WelcomeDialog::storeNoteFolderSettings() { // make the path relative to the portable data path if we are in // portable mode - settings.setValue( - QStringLiteral("notesPath"), - Utils::Misc::makePathRelativeToPortableDataPathIfNeeded(_notesPath)); + settings.setValue(QStringLiteral("notesPath"), + Utils::Misc::makePathRelativeToPortableDataPathIfNeeded(_notesPath)); settings.setValue(QStringLiteral("showNoteSubFolders"), ui->showNoteSubFoldersCheckBox->isChecked()); } void WelcomeDialog::on_backButton_clicked() { - MetricsService::instance()->sendVisitIfEnabled( - QStringLiteral("welcome-dialog/back")); + MetricsService::instance()->sendVisitIfEnabled(QStringLiteral("welcome-dialog/back")); int index = ui->stackedWidget->currentIndex(); @@ -187,8 +175,7 @@ void WelcomeDialog::on_backButton_clicked() { } void WelcomeDialog::on_finishButton_clicked() { - MetricsService::instance()->sendVisitIfEnabled( - QStringLiteral("welcome-dialog/finished")); + MetricsService::instance()->sendVisitIfEnabled(QStringLiteral("welcome-dialog/finished")); if (ui->stackedWidget->currentIndex() == WelcomePages::NoteFolderPage) { if (!handleNoteFolderSetup()) return; } else { @@ -203,9 +190,8 @@ void WelcomeDialog::on_noteFolderButton_clicked() { QStringLiteral("welcome-dialog/set-note-folder")); QString dir = QFileDialog::getExistingDirectory( - this, - tr("Please select the folder where your notes will get stored to"), - _notesPath, QFileDialog::ShowDirsOnly); + this, tr("Please select the folder where your notes will get stored to"), _notesPath, + QFileDialog::ShowDirsOnly); QDir d = QDir(dir); @@ -213,14 +199,12 @@ void WelcomeDialog::on_noteFolderButton_clicked() { #ifdef Q_OS_WIN32 // check if user chose a different drive in portable mode if (Utils::Misc::isInPortableMode() && - Utils::Misc::portableDataPath().toLower().at(0) != - dir.toLower().at(0)) { - QMessageBox::information( - this, tr("Note folder"), - tr("Keep in mind that the note folder will be " - "stored relative to the directory where QOwnNotes " - "resides in portable mode! So you need to stay on the " - "same drive.")); + Utils::Misc::portableDataPath().toLower().at(0) != dir.toLower().at(0)) { + QMessageBox::information(this, tr("Note folder"), + tr("Keep in mind that the note folder will be " + "stored relative to the directory where QOwnNotes " + "resides in portable mode! So you need to stay on the " + "same drive.")); return; } @@ -248,7 +232,6 @@ void WelcomeDialog::on_networkSettingsButton_clicked() { } void WelcomeDialog::closeEvent(QCloseEvent *event) { - MetricsService::instance()->sendVisitIfEnabled( - QStringLiteral("welcome-dialog/close")); + MetricsService::instance()->sendVisitIfEnabled(QStringLiteral("welcome-dialog/close")); MasterDialog::closeEvent(event); } diff --git a/src/entities/bookmark.cpp b/src/entities/bookmark.cpp index 8985e7d8d..0fe86dd62 100644 --- a/src/entities/bookmark.cpp +++ b/src/entities/bookmark.cpp @@ -20,8 +20,7 @@ Bookmark::Bookmark() { description = QString(); } -Bookmark::Bookmark(QString url, QString name, QStringList tagList, - QString description) { +Bookmark::Bookmark(QString url, QString name, QStringList tagList, QString description) { this->url = std::move(url); this->name = std::move(name); this->tags = std::move(tagList); @@ -30,26 +29,20 @@ Bookmark::Bookmark(QString url, QString name, QStringList tagList, QJsonObject Bookmark::jsonObject() const { QJsonObject bookmarkObject; - bookmarkObject.insert(QStringLiteral("name"), - QJsonValue::fromVariant(name)); + bookmarkObject.insert(QStringLiteral("name"), QJsonValue::fromVariant(name)); bookmarkObject.insert(QStringLiteral("url"), QJsonValue::fromVariant(url)); - bookmarkObject.insert(QStringLiteral("tags"), - QJsonValue::fromVariant(tags)); - bookmarkObject.insert(QStringLiteral("description"), - QJsonValue::fromVariant(description)); + bookmarkObject.insert(QStringLiteral("tags"), QJsonValue::fromVariant(tags)); + bookmarkObject.insert(QStringLiteral("description"), QJsonValue::fromVariant(description)); return bookmarkObject; } QDebug operator<<(QDebug dbg, const Bookmark &bookmark) { - dbg.nospace() << "Bookmark: <name>" << bookmark.name << " <url>" - << bookmark.url << " <tags>" << bookmark.tags - << " <description>" << bookmark.description; + dbg.nospace() << "Bookmark: <name>" << bookmark.name << " <url>" << bookmark.url << " <tags>" + << bookmark.tags << " <description>" << bookmark.description; return dbg.space(); } -bool Bookmark::operator==(const Bookmark &bookmark) const { - return url == bookmark.url; -} +bool Bookmark::operator==(const Bookmark &bookmark) const { return url == bookmark.url; } /** * Parses bookmarks from a text @@ -57,16 +50,14 @@ bool Bookmark::operator==(const Bookmark &bookmark) const { * @param text * @return */ -QVector<Bookmark> Bookmark::parseBookmarks(const QString &text, - bool withBasicUrls) { +QVector<Bookmark> Bookmark::parseBookmarks(const QString &text, bool withBasicUrls) { QRegularExpressionMatchIterator i; QVector<Bookmark> bookmarks; // parse bookmark links like `- [name](http://link) #tag1 #tag2 the // description text` with optional tags and description - i = QRegularExpression( - QStringLiteral(R"([-*]\s+\[(.+?)\]\(([\w-]+://.+?)\)(.*)$)"), - QRegularExpression::MultilineOption) + i = QRegularExpression(QStringLiteral(R"([-*]\s+\[(.+?)\]\(([\w-]+://.+?)\)(.*)$)"), + QRegularExpression::MultilineOption) .globalMatch(text); while (i.hasNext()) { @@ -79,16 +70,15 @@ QVector<Bookmark> Bookmark::parseBookmarks(const QString &text, if (!additionalText.isEmpty()) { QRegularExpressionMatchIterator addIterator = - QRegularExpression(QStringLiteral(R"(#([^\s#]+))")) - .globalMatch(additionalText); + QRegularExpression(QStringLiteral(R"(#([^\s#]+))")).globalMatch(additionalText); while (addIterator.hasNext()) { QRegularExpressionMatch addMatch = addIterator.next(); QString tag = addMatch.captured(1).trimmed(); if (!tags.contains(tag)) { tags << tag; - additionalText.remove(QRegularExpression( - "#" + QRegularExpression::escape(tag) + "\\b")); + additionalText.remove( + QRegularExpression("#" + QRegularExpression::escape(tag) + "\\b")); } } @@ -105,22 +95,19 @@ QVector<Bookmark> Bookmark::parseBookmarks(const QString &text, if (withBasicUrls) { // parse named links like [name](http://my.site.com) - i = QRegularExpression(QStringLiteral(R"(\[(.+?)\]\(([\w-]+://.+?)\))")) - .globalMatch(text); + i = QRegularExpression(QStringLiteral(R"(\[(.+?)\]\(([\w-]+://.+?)\))")).globalMatch(text); while (i.hasNext()) { QRegularExpressionMatch match = i.next(); QString name = match.captured(1); QString url = match.captured(2); - auto bookmark = - Bookmark(url, name, QStringList() << QStringLiteral("current")); + auto bookmark = Bookmark(url, name, QStringList() << QStringLiteral("current")); bookmark.mergeInList(bookmarks); } // parse links like <http://my.site.com> - i = QRegularExpression(QStringLiteral(R"(<([\w-]+://.+?)>)")) - .globalMatch(text); + i = QRegularExpression(QStringLiteral(R"(<([\w-]+://.+?)>)")).globalMatch(text); while (i.hasNext()) { QRegularExpressionMatch match = i.next(); @@ -139,8 +126,7 @@ QVector<Bookmark> Bookmark::parseBookmarks(const QString &text, * * @return */ -QString Bookmark::bookmarksWebServiceJsonText( - const QVector<Bookmark> &bookmarks) { +QString Bookmark::bookmarksWebServiceJsonText(const QVector<Bookmark> &bookmarks) { QJsonArray bookmarkObjectList; QJsonArray noteFolderObjectList; @@ -154,15 +140,12 @@ QString Bookmark::bookmarksWebServiceJsonText( } QJsonObject bookmarkResultObject; - bookmarkResultObject.insert(QStringLiteral("type"), - QJsonValue::fromVariant("bookmarks")); + bookmarkResultObject.insert(QStringLiteral("type"), QJsonValue::fromVariant("bookmarks")); bookmarkResultObject.insert(QStringLiteral("data"), bookmarkObjectList); bookmarkResultObject.insert(QStringLiteral("noteFolderName"), NoteFolder::currentNoteFolder().getName()); - bookmarkResultObject.insert(QStringLiteral("noteFolders"), - noteFolderObjectList); - bookmarkResultObject.insert(QStringLiteral("noteFolderId"), - NoteFolder::currentNoteFolderId()); + bookmarkResultObject.insert(QStringLiteral("noteFolders"), noteFolderObjectList); + bookmarkResultObject.insert(QStringLiteral("noteFolderId"), NoteFolder::currentNoteFolderId()); QJsonDocument doc(bookmarkResultObject); @@ -174,8 +157,7 @@ QString Bookmark::bookmarksWebServiceJsonText( * * @return */ -QString Bookmark::parsedBookmarksWebServiceJsonText(const QString &text, - bool withBasicUrls) { +QString Bookmark::parsedBookmarksWebServiceJsonText(const QString &text, bool withBasicUrls) { return bookmarksWebServiceJsonText(parseBookmarks(text, withBasicUrls)); } diff --git a/src/entities/bookmark.h b/src/entities/bookmark.h index a2b6d3dec..5d5041c69 100644 --- a/src/entities/bookmark.h +++ b/src/entities/bookmark.h @@ -12,17 +12,14 @@ class Bookmark { public: Bookmark(); - explicit Bookmark(QString url, QString name = QString(), - QStringList tagList = QStringList(), + explicit Bookmark(QString url, QString name = QString(), QStringList tagList = QStringList(), QString description = QString()); friend QDebug operator<<(QDebug dbg, const Bookmark &bookmark); QJsonObject jsonObject() const; - static QVector<Bookmark> parseBookmarks(const QString &text, - bool withBasicUrls = false); - static QString bookmarksWebServiceJsonText( - const QVector<Bookmark> &bookmarks); - static QString parsedBookmarksWebServiceJsonText( - const QString &text, bool withBasicUrls = false); + static QVector<Bookmark> parseBookmarks(const QString &text, bool withBasicUrls = false); + static QString bookmarksWebServiceJsonText(const QVector<Bookmark> &bookmarks); + static QString parsedBookmarksWebServiceJsonText(const QString &text, + bool withBasicUrls = false); bool operator==(const Bookmark &bookmark) const; static void mergeInList(QVector<Bookmark> &bookmarks, Bookmark &bookmark); static void mergeListInList(const QVector<Bookmark> &sourceBookmarks, diff --git a/src/entities/calendaritem.cpp b/src/entities/calendaritem.cpp index 76bf8f309..86d0a5e5c 100644 --- a/src/entities/calendaritem.cpp +++ b/src/entities/calendaritem.cpp @@ -45,17 +45,13 @@ int CalendarItem::getPriority() { return this->priority; } bool CalendarItem::getHasDirtyData() { return this->hasDirtyData; } -QString CalendarItem::getLastModifiedString() { - return this->lastModifiedString; -} +QString CalendarItem::getLastModifiedString() { return this->lastModifiedString; } QString CalendarItem::getETag() { return this->etag; } QDateTime CalendarItem::getAlarmDate() { return this->alarmDate; } -void CalendarItem::setLastModifiedString(const QString &text) { - this->lastModifiedString = text; -} +void CalendarItem::setLastModifiedString(const QString &text) { this->lastModifiedString = text; } void CalendarItem::setETag(const QString &text) { this->etag = text; } @@ -65,29 +61,19 @@ void CalendarItem::setUrl(const QUrl &url) { this->url = url.toString(); } void CalendarItem::setCalendar(const QString &text) { this->calendar = text; } -void CalendarItem::setDescription(const QString &text) { - this->description = text; -} +void CalendarItem::setDescription(const QString &text) { this->description = text; } void CalendarItem::setICSData(const QString &text) { this->icsData = text; } void CalendarItem::setUid(const QString &text) { this->uid = text; } -void CalendarItem::setRelatedUid(const QString &text) { - this->relatedUid = text; -} +void CalendarItem::setRelatedUid(const QString &text) { this->relatedUid = text; } -void CalendarItem::setCreated(const QDateTime &dateTime) { - this->created = dateTime; -} +void CalendarItem::setCreated(const QDateTime &dateTime) { this->created = dateTime; } -void CalendarItem::setModified(const QDateTime &dateTime) { - this->modified = dateTime; -} +void CalendarItem::setModified(const QDateTime &dateTime) { this->modified = dateTime; } -void CalendarItem::setAlarmDate(const QDateTime &dateTime) { - this->alarmDate = dateTime; -} +void CalendarItem::setAlarmDate(const QDateTime &dateTime) { this->alarmDate = dateTime; } void CalendarItem::setPriority(int value) { this->priority = value; } @@ -107,9 +93,9 @@ void CalendarItem::updateCompleted(bool value) { * translated * @return */ -bool CalendarItem::addCalendarItemForRequest( - const QString &calendar, const QUrl &url, const QString &etag, - const QString &lastModifiedString) { +bool CalendarItem::addCalendarItemForRequest(const QString &calendar, const QUrl &url, + const QString &etag, + const QString &lastModifiedString) { QSqlDatabase db = QSqlDatabase::database(QStringLiteral("disk")); QSqlQuery query(db); @@ -120,8 +106,7 @@ bool CalendarItem::addCalendarItemForRequest( query.bindValue(QStringLiteral(":calendar"), calendar); query.bindValue(QStringLiteral(":url"), url); query.bindValue(QStringLiteral(":etag"), etag); - query.bindValue(QStringLiteral(":last_modified_string"), - lastModifiedString); + query.bindValue(QStringLiteral(":last_modified_string"), lastModifiedString); return query.exec(); } @@ -157,8 +142,7 @@ CalendarItem CalendarItem::fetch(int id) { return calendarItem; } -CalendarItem CalendarItem::fetchByUrlAndCalendar(const QString &url, - const QString &calendar) { +CalendarItem CalendarItem::fetchByUrlAndCalendar(const QString &url, const QString &calendar) { CalendarItem calendarItem; QSqlDatabase db = QSqlDatabase::database(QStringLiteral("disk")); QSqlQuery query(db); @@ -183,8 +167,7 @@ CalendarItem CalendarItem::fetchByUid(const QString &uid) { QSqlDatabase db = QSqlDatabase::database(QStringLiteral("disk")); QSqlQuery query(db); - query.prepare( - QStringLiteral("SELECT * FROM calendarItem WHERE uid = :uid")); + query.prepare(QStringLiteral("SELECT * FROM calendarItem WHERE uid = :uid")); query.bindValue(QStringLiteral(":uid"), uid); if (!query.exec()) { @@ -201,8 +184,7 @@ CalendarItem CalendarItem::fetchByUrl(const QUrl &url) { QSqlDatabase db = QSqlDatabase::database(QStringLiteral("disk")); QSqlQuery query(db); - query.prepare( - QStringLiteral("SELECT * FROM calendarItem WHERE url = :url")); + query.prepare(QStringLiteral("SELECT * FROM calendarItem WHERE url = :url")); query.bindValue(QStringLiteral(":url"), url); if (!query.exec()) { @@ -257,8 +239,7 @@ bool CalendarItem::fillFromQuery(const QSqlQuery &query) { this->summary = query.value(QStringLiteral("summary")).toString(); this->url = query.value(QStringLiteral("url")).toString(); this->description = query.value(QStringLiteral("description")).toString(); - this->hasDirtyData = - query.value(QStringLiteral("has_dirty_data")).toInt() == 1; + this->hasDirtyData = query.value(QStringLiteral("has_dirty_data")).toInt() == 1; this->completed = query.value(QStringLiteral("completed")).toInt() == 1; this->priority = query.value(QStringLiteral("priority")).toInt(); this->uid = query.value(QStringLiteral("uid")).toString(); @@ -266,13 +247,11 @@ bool CalendarItem::fillFromQuery(const QSqlQuery &query) { this->calendar = query.value(QStringLiteral("calendar")).toString(); this->icsData = query.value(QStringLiteral("ics_data")).toString(); this->etag = query.value(QStringLiteral("etag")).toString(); - this->lastModifiedString = - query.value(QStringLiteral("last_modified_string")).toString(); + this->lastModifiedString = query.value(QStringLiteral("last_modified_string")).toString(); this->alarmDate = query.value(QStringLiteral("alarm_date")).toDateTime(); this->created = query.value(QStringLiteral("created")).toDateTime(); this->modified = query.value(QStringLiteral("modified")).toDateTime(); - this->completedDate = - query.value(QStringLiteral("completed_date")).toDateTime(); + this->completedDate = query.value(QStringLiteral("completed_date")).toDateTime(); this->sortPriority = query.value(QStringLiteral("sort_priority")).toInt(); return true; @@ -391,8 +370,7 @@ QList<QUrl> CalendarItem::fetchAllUrlsByCalendar(const QString &calendar) { QSqlQuery query(db); QList<QUrl> urlList; - query.prepare(QStringLiteral( - "SELECT url FROM calendarItem WHERE calendar = :calendar")); + query.prepare(QStringLiteral("SELECT url FROM calendarItem WHERE calendar = :calendar")); query.bindValue(QStringLiteral(":calendar"), calendar); if (!query.exec()) { @@ -434,8 +412,7 @@ QList<CalendarItem> CalendarItem::search(const QString &text) { /** * Returns a list of UIDs for the search in the TodoDialog */ -QList<QString> CalendarItem::searchAsUidList(const QString &text, - const QString &calendar) { +QList<QString> CalendarItem::searchAsUidList(const QString &text, const QString &calendar) { QSqlDatabase db = QSqlDatabase::database(QStringLiteral("disk")); QSqlQuery query(db); QList<QString> resultList; @@ -522,16 +499,14 @@ bool CalendarItem::store() { query.bindValue(QStringLiteral(":summary"), this->summary); query.bindValue(QStringLiteral(":url"), this->url); query.bindValue(QStringLiteral(":description"), this->description); - query.bindValue(QStringLiteral(":has_dirty_data"), - this->hasDirtyData ? 1 : 0); + query.bindValue(QStringLiteral(":has_dirty_data"), this->hasDirtyData ? 1 : 0); query.bindValue(QStringLiteral(":completed"), this->completed ? 1 : 0); query.bindValue(QStringLiteral(":calendar"), this->calendar); query.bindValue(QStringLiteral(":uid"), this->uid); query.bindValue(QStringLiteral(":related_uid"), this->relatedUid); query.bindValue(QStringLiteral(":ics_data"), this->icsData); query.bindValue(QStringLiteral(":etag"), this->etag); - query.bindValue(QStringLiteral(":last_modified_string"), - this->lastModifiedString); + query.bindValue(QStringLiteral(":last_modified_string"), this->lastModifiedString); query.bindValue(QStringLiteral(":alarm_date"), this->alarmDate); query.bindValue(QStringLiteral(":priority"), this->priority); query.bindValue(QStringLiteral(":created"), this->created); @@ -570,18 +545,14 @@ QString CalendarItem::generateNewICSData() { icsDataHash[QStringLiteral("DESCRIPTION")] = description; icsDataHash[QStringLiteral("UID")] = uid; icsDataHash[QStringLiteral("PRIORITY")] = QString::number(priority); - icsDataHash[QStringLiteral("PERCENT-COMPLETE")] = - QString::number(completed ? 100 : 0); - icsDataHash[QStringLiteral("STATUS")] = - completed ? "COMPLETED" : "NEEDS-ACTION"; + icsDataHash[QStringLiteral("PERCENT-COMPLETE")] = QString::number(completed ? 100 : 0); + icsDataHash[QStringLiteral("STATUS")] = completed ? "COMPLETED" : "NEEDS-ACTION"; // icsDataHash["CREATED"] = // created.toUTC().toString(ICS_DATETIME_FORMAT); // icsDataHash["LAST-MODIFIED"] = // modified.toUTC().toString(ICS_DATETIME_FORMAT); - icsDataHash[QStringLiteral("CREATED")] = - created.toString(ICS_DATETIME_FORMAT); - icsDataHash[QStringLiteral("LAST-MODIFIED")] = - modified.toString(ICS_DATETIME_FORMAT); + icsDataHash[QStringLiteral("CREATED")] = created.toString(ICS_DATETIME_FORMAT); + icsDataHash[QStringLiteral("LAST-MODIFIED")] = modified.toString(ICS_DATETIME_FORMAT); if (!relatedUid.isEmpty()) { icsDataHash[QStringLiteral("RELATED-TO")] = relatedUid; @@ -590,8 +561,7 @@ QString CalendarItem::generateNewICSData() { if (completed) { // icsDataHash["COMPLETED"] = // completedDate.toUTC().toString(ICS_DATETIME_FORMAT); - icsDataHash[QStringLiteral("COMPLETED")] = - completedDate.toString(ICS_DATETIME_FORMAT); + icsDataHash[QStringLiteral("COMPLETED")] = completedDate.toString(ICS_DATETIME_FORMAT); } else { // remove the "COMPLETED" ics data attribute if the task item is not // completed @@ -603,8 +573,7 @@ QString CalendarItem::generateNewICSData() { // set the alarm if needed if (alarmDate.isValid()) { - icsDataHash[QStringLiteral("DUE")] = - alarmDate.toString(ICS_DATETIME_FORMAT); + icsDataHash[QStringLiteral("DUE")] = alarmDate.toString(ICS_DATETIME_FORMAT); // Nextcloud seems to have problem with the VALARM block // addVALARMBlockToICS(); @@ -701,8 +670,7 @@ bool CalendarItem::deleteAllByCalendar(const QString &calendar) { QSqlDatabase db = QSqlDatabase::database(QStringLiteral("disk")); QSqlQuery query(db); - query.prepare( - QStringLiteral("DELETE FROM calendarItem WHERE calendar = :calendar")); + query.prepare(QStringLiteral("DELETE FROM calendarItem WHERE calendar = :calendar")); query.bindValue(QStringLiteral(":calendar"), calendar); if (!query.exec()) { qWarning() << __func__ << ": " << query.lastError(); @@ -740,20 +708,17 @@ bool CalendarItem::updateWithICSData(const QString &icsData) { ? icsDataHash[QStringLiteral("SUMMARY")].trimmed() : QString(); completed = icsDataHash.contains(QStringLiteral("PERCENT-COMPLETE")) - ? icsDataHash[QStringLiteral("PERCENT-COMPLETE")] == - QLatin1String("100") + ? icsDataHash[QStringLiteral("PERCENT-COMPLETE")] == QLatin1String("100") : false; // also take the completed status into account if (!completed) { - completed = - icsDataHash.contains(QStringLiteral("STATUS")) && - icsDataHash[QStringLiteral("STATUS")] == QLatin1String("COMPLETED"); + completed = icsDataHash.contains(QStringLiteral("STATUS")) && + icsDataHash[QStringLiteral("STATUS")] == QLatin1String("COMPLETED"); } - uid = icsDataHash.contains(QStringLiteral("UID")) - ? icsDataHash[QStringLiteral("UID")] - : QString(); + uid = icsDataHash.contains(QStringLiteral("UID")) ? icsDataHash[QStringLiteral("UID")] + : QString(); relatedUid = icsDataHash.contains(QStringLiteral("RELATED-TO")) ? icsDataHash[QStringLiteral("RELATED-TO")] : QString(); @@ -764,23 +729,23 @@ bool CalendarItem::updateWithICSData(const QString &icsData) { ? icsDataHash[QStringLiteral("PRIORITY")].toInt() : 0; created = icsDataHash.contains(QStringLiteral("CREATED")) - ? getDateTimeFromString(icsDataHash[QStringLiteral("CREATED")]) - : QDateTime::currentDateTime(); + ? getDateTimeFromString(icsDataHash[QStringLiteral("CREATED")]) + : QDateTime::currentDateTime(); modified = icsDataHash.contains(QStringLiteral("LAST-MODIFIED")) - ? getDateTimeFromString(icsDataHash[QStringLiteral("LAST-MODIFIED")]) - : QDateTime::currentDateTime(); + ? getDateTimeFromString(icsDataHash[QStringLiteral("LAST-MODIFIED")]) + : QDateTime::currentDateTime(); // workaround to check if we have a alarm description, so that on empty // descriptions the alarm description isn't taken - QString alarmDescription = getICSDataAttributeInBlock( - QStringLiteral("VALARM"), QStringLiteral("DESCRIPTION")); + QString alarmDescription = + getICSDataAttributeInBlock(QStringLiteral("VALARM"), QStringLiteral("DESCRIPTION")); if ((!description.isEmpty()) && (!alarmDescription.isEmpty()) && (description == alarmDescription)) { description = QString(); } - QString alarmDateString = getICSDataAttributeInBlock( - QStringLiteral("VALARM"), QStringLiteral("TRIGGER;VALUE=DATE-TIME")); + QString alarmDateString = getICSDataAttributeInBlock(QStringLiteral("VALARM"), + QStringLiteral("TRIGGER;VALUE=DATE-TIME")); // Nextcloud seems to store the reminder date in the DUE field alarmDate = icsDataHash.contains(QStringLiteral("DUE")) @@ -807,8 +772,7 @@ QDateTime CalendarItem::getDateTimeFromString(const QString &dateString) { // see: https://github.com/pbek/QOwnNotes/issues/1966 if (!dateTime.isValid()) { dateTime = QDateTime::fromString(dateString, ICS_DATETIME_FORMAT_UTC); - dateTime = QDateTime(dateTime.date(), dateTime.time(), Qt::UTC) - .toLocalTime(); + dateTime = QDateTime(dateTime.date(), dateTime.time(), Qt::UTC).toLocalTime(); } return dateTime; @@ -899,8 +863,7 @@ bool CalendarItem::addVALARMBlockToICS() { QString value = icsDataHash.value(key); // look for the VTODO begin block - if (key.startsWith(QLatin1String("BEGIN")) && - (value == QLatin1String("VTODO"))) { + if (key.startsWith(QLatin1String("BEGIN")) && (value == QLatin1String("VTODO"))) { foundBegin = true; } @@ -916,18 +879,15 @@ bool CalendarItem::addVALARMBlockToICS() { icsDataHashCopy[addKey] = QLatin1String("VALARM"); icsDataKeyListCopy.insert(i, addKey); - addKey = - findFreeHashKey(&icsDataHashCopy, QStringLiteral("ACTION")); + addKey = findFreeHashKey(&icsDataHashCopy, QStringLiteral("ACTION")); icsDataHashCopy[addKey] = QLatin1String("DISPLAY"); icsDataKeyListCopy.insert(++i, addKey); - addKey = findFreeHashKey(&icsDataHashCopy, - QStringLiteral("DESCRIPTION")); + addKey = findFreeHashKey(&icsDataHashCopy, QStringLiteral("DESCRIPTION")); icsDataHashCopy[addKey] = QLatin1String("Reminder"); icsDataKeyListCopy.insert(++i, addKey); - addKey = findFreeHashKey(&icsDataHashCopy, - QStringLiteral("TRIGGER;VALUE=DATE-TIME")); + addKey = findFreeHashKey(&icsDataHashCopy, QStringLiteral("TRIGGER;VALUE=DATE-TIME")); icsDataHashCopy[addKey] = alarmDateString; icsDataKeyListCopy.insert(++i, addKey); @@ -1023,8 +983,7 @@ void CalendarItem::generateICSDataHash() { * @param number * @return */ -QString CalendarItem::findFreeHashKey(QHash<QString, QString> *hash, - QString key, int number) { +QString CalendarItem::findFreeHashKey(QHash<QString, QString> *hash, QString key, int number) { // give up after 1000 tries if (number >= 1000) { return key; @@ -1069,16 +1028,14 @@ QString CalendarItem::decodeICSDataLine(QString line) { return line; } -CalendarItem CalendarItem::createNewTodoItem(const QString &summary, - const QString &calendar, +CalendarItem CalendarItem::createNewTodoItem(const QString &summary, const QString &calendar, const QString &relatedUid) { QString uuidString = Utils::Misc::createUuidString(); CalendarItem calItem; calItem.setSummary(summary); calItem.setCalendar(calendar); calItem.setRelatedUid(relatedUid); - calItem.setUrl( - QUrl(getCurrentCalendarUrl() + "qownnotes-" + uuidString + ".ics")); + calItem.setUrl(QUrl(getCurrentCalendarUrl() + "qownnotes-" + uuidString + ".ics")); calItem.setICSData( "BEGIN:VCALENDAR\nVERSION:2.0\nPRODID:ownCloud Calendar" "\nCALSCALE:GREGORIAN\nBEGIN:VTODO\nEND:VTODO" @@ -1093,8 +1050,7 @@ CalendarItem CalendarItem::createNewTodoItem(const QString &summary, if (calItem.store()) { qDebug() << __func__ << " - 'calItem': " << calItem; - qDebug() << __func__ - << " - 'calItem.getICSData()': " << calItem.getICSData(); + qDebug() << __func__ << " - 'calItem.getICSData()': " << calItem.getICSData(); } return calItem; @@ -1109,17 +1065,13 @@ int CalendarItem::getCurrentCalendarIndex() { QSettings settings; QString todoListSelectorSelectedItem = - settings - .value(QStringLiteral("TodoDialog/todoListSelectorSelectedItem")) - .toString(); + settings.value(QStringLiteral("TodoDialog/todoListSelectorSelectedItem")).toString(); if (!todoListSelectorSelectedItem.isEmpty()) { QStringList todoCalendarEnabledList = - settings.value(QStringLiteral("ownCloud/todoCalendarEnabledList")) - .toStringList(); + settings.value(QStringLiteral("ownCloud/todoCalendarEnabledList")).toStringList(); // search for the text in the todoCalendarEnabledList - int index = - todoCalendarEnabledList.indexOf(todoListSelectorSelectedItem); + int index = todoCalendarEnabledList.indexOf(todoListSelectorSelectedItem); if (index >= 0) { // return the index of the task list selector if we found it @@ -1141,9 +1093,7 @@ QString CalendarItem::getCurrentCalendarUrl() { if (index >= 0) { QStringList todoCalendarEnabledUrlList = - settings - .value(QStringLiteral("ownCloud/todoCalendarEnabledUrlList")) - .toStringList(); + settings.value(QStringLiteral("ownCloud/todoCalendarEnabledUrlList")).toStringList(); return todoCalendarEnabledUrlList.at(index); } @@ -1163,9 +1113,8 @@ void CalendarItem::alertTodoReminders() { QListIterator<CalendarItem> itr(calendarItemList); while (itr.hasNext()) { CalendarItem calItem = itr.next(); - QMessageBox::information( - nullptr, QStringLiteral("Reminder"), - "Reminder: <strong>" + calItem.getSummary() + "</strong>"); + QMessageBox::information(nullptr, QStringLiteral("Reminder"), + "Reminder: <strong>" + calItem.getSummary() + "</strong>"); } } @@ -1188,9 +1137,8 @@ int CalendarItem::countAll() { } QDebug operator<<(QDebug dbg, const CalendarItem &calendarItem) { - dbg.nospace() << "CalendarItem: <id>" << calendarItem.id << " <summary>" - << calendarItem.summary << " <url>" << calendarItem.url - << " <relatedUid>" << calendarItem.relatedUid + dbg.nospace() << "CalendarItem: <id>" << calendarItem.id << " <summary>" << calendarItem.summary + << " <url>" << calendarItem.url << " <relatedUid>" << calendarItem.relatedUid << " <calendar>" << calendarItem.calendar; return dbg.space(); } diff --git a/src/entities/calendaritem.h b/src/entities/calendaritem.h index c53daa8cb..2022a86a2 100644 --- a/src/entities/calendaritem.h +++ b/src/entities/calendaritem.h @@ -15,8 +15,7 @@ class CalendarItem { int getId(); bool getHasDirtyData(); - static bool addCalendarItem(const QString &name, const QString &fileName, - const QString &text); + static bool addCalendarItem(const QString &name, const QString &fileName, const QString &text); static CalendarItem fetch(int id); static QList<CalendarItem> search(const QString &text); static CalendarItem calendarItemFromQuery(const QSqlQuery &query); @@ -29,11 +28,9 @@ class CalendarItem { bool remove(); bool isFetched(); bool isCompleted(); - static CalendarItem fetchByUrlAndCalendar(const QString &url, - const QString &calendar); - static bool addCalendarItemForRequest(const QString &calendar, - const QUrl &url, const QString &etag, - const QString &lastModifiedString); + static CalendarItem fetchByUrlAndCalendar(const QString &url, const QString &calendar); + static bool addCalendarItemForRequest(const QString &calendar, const QUrl &url, + const QString &etag, const QString &lastModifiedString); static QList<CalendarItem> fetchAllByCalendar(const QString &calendar); static bool deleteAllByCalendar(const QString &calendar); QString getUrl(); @@ -58,9 +55,8 @@ class CalendarItem { void setETag(const QString &text); static QList<QUrl> fetchAllUrlsByCalendar(const QString &calendar); void setCalendar(const QString &text); - static CalendarItem createNewTodoItem( - const QString &summary, const QString &calendar, - const QString &relatedUid = QLatin1String("")); + static CalendarItem createNewTodoItem(const QString &summary, const QString &calendar, + const QString &relatedUid = QLatin1String("")); void setUrl(const QUrl &url); void setUid(const QString &text); void setRelatedUid(const QString &text); @@ -76,8 +72,7 @@ class CalendarItem { void setAlarmDate(const QDateTime &dateTime); static QList<CalendarItem> fetchAllForReminderAlert(); static void alertTodoReminders(); - static QList<QString> searchAsUidList(const QString &text, - const QString &calendar); + static QList<QString> searchAsUidList(const QString &text, const QString &calendar); static QList<CalendarItem> fetchAllForSystemTray(int limit = 10); static bool removeAll(); static int countAll(); @@ -104,13 +99,11 @@ class CalendarItem { QHash<QString, QString> icsDataHash; QStringList icsDataKeyList; static QString decodeICSDataLine(QString line); - static QString findFreeHashKey(QHash<QString, QString> *hash, QString key, - int number = 0); + static QString findFreeHashKey(QHash<QString, QString> *hash, QString key, int number = 0); void generateICSDataHash(); void updateICSDataKeyListFromHash(); void updateSortPriority(); - QString getICSDataAttributeInBlock(const QString &block, - const QString &attributeName); + QString getICSDataAttributeInBlock(const QString &block, const QString &attributeName); bool removeICSDataBlock(const QString &block); bool addVALARMBlockToICS(); static QDateTime getDateTimeFromString(const QString &dateString); diff --git a/src/entities/cloudconnection.cpp b/src/entities/cloudconnection.cpp index a6b8b0161..947384230 100644 --- a/src/entities/cloudconnection.cpp +++ b/src/entities/cloudconnection.cpp @@ -17,10 +17,7 @@ #include "services/databaseservice.h" CloudConnection::CloudConnection() - : name(QString()), - serverUrl(QString()), - username(QString()), - password(QString()) { + : name(QString()), serverUrl(QString()), username(QString()), password(QString()) { id = 0; priority = 0; } @@ -31,9 +28,7 @@ QString CloudConnection::getName() { return this->name; } QString CloudConnection::getServerUrl() { return this->serverUrl; } -QString CloudConnection::getServerUrlPath() { - return QUrl(this->serverUrl).path(); -} +QString CloudConnection::getServerUrlPath() { return QUrl(this->serverUrl).path(); } QString CloudConnection::getServerUrlWithoutPath() { QString serverUrlWithoutPath = serverUrl; @@ -42,8 +37,7 @@ QString CloudConnection::getServerUrlWithoutPath() { if (!serverUrlPath.isEmpty()) { // remove the path from the server url serverUrlWithoutPath.replace( - QRegularExpression(QRegularExpression::escape(serverUrlPath) + "$"), - QString()); + QRegularExpression(QRegularExpression::escape(serverUrlPath) + "$"), QString()); } return serverUrlWithoutPath; @@ -64,8 +58,7 @@ CloudConnection CloudConnection::firstCloudConnection() { return list.count() > 0 ? list[0] : CloudConnection(); } -CloudConnection CloudConnection::currentCloudConnection( - bool ignoreTableWarning) { +CloudConnection CloudConnection::currentCloudConnection(bool ignoreTableWarning) { NoteFolder noteFolder = NoteFolder::currentNoteFolder(); const int id = noteFolder.getCloudConnectionId(); @@ -74,40 +67,31 @@ CloudConnection CloudConnection::currentCloudConnection( CloudConnection CloudConnection::currentTodoCalendarCloudConnection() { QSettings settings; - const int id = - settings - .value(QStringLiteral("ownCloud/todoCalendarCloudConnectionId"), - firstCloudConnection().getId()) - .toInt(); + const int id = settings + .value(QStringLiteral("ownCloud/todoCalendarCloudConnectionId"), + firstCloudConnection().getId()) + .toInt(); return CloudConnection::fetch(id); } -void CloudConnection::setName(const QString &text) { - this->name = text.trimmed(); -} +void CloudConnection::setName(const QString &text) { this->name = text.trimmed(); } -void CloudConnection::setServerUrl(const QString &text) { - this->serverUrl = text.trimmed(); -} +void CloudConnection::setServerUrl(const QString &text) { this->serverUrl = text.trimmed(); } -void CloudConnection::setUsername(const QString &text) { - this->username = text.trimmed(); -} +void CloudConnection::setUsername(const QString &text) { this->username = text.trimmed(); } -void CloudConnection::setAccountId(const QString &text) { - this->accountId = text.trimmed(); -} +void CloudConnection::setAccountId(const QString &text) { this->accountId = text.trimmed(); } -void CloudConnection::setPassword(const QString &text) { - this->password = text.trimmed(); -} +void CloudConnection::setPassword(const QString &text) { this->password = text.trimmed(); } void CloudConnection::setPriority(int value) { this->priority = value; } -void CloudConnection::setAppQOwnNotesAPIEnabled(bool value) { this->appQOwnNotesAPIEnabled = value; } +void CloudConnection::setAppQOwnNotesAPIEnabled(bool value) { + this->appQOwnNotesAPIEnabled = value; +} -bool CloudConnection::create(const QString &name, const QString &serverUrl, - const QString &username, const QString &password) { +bool CloudConnection::create(const QString &name, const QString &serverUrl, const QString &username, + const QString &password) { QSqlDatabase db = QSqlDatabase::database(QStringLiteral("disk")); QSqlQuery query(db); @@ -130,8 +114,7 @@ CloudConnection CloudConnection::fetch(int id, bool ignoreTableWarning) { CloudConnection cloudConnection; - query.prepare( - QStringLiteral("SELECT * FROM cloudConnection WHERE id = :id")); + query.prepare(QStringLiteral("SELECT * FROM cloudConnection WHERE id = :id")); query.bindValue(QStringLiteral(":id"), id); if (!query.exec()) { @@ -149,8 +132,7 @@ int CloudConnection::countAll() { QSqlDatabase db = QSqlDatabase::database(QStringLiteral("disk")); QSqlQuery query(db); - query.prepare( - QStringLiteral("SELECT COUNT(*) AS cnt FROM cloudConnection")); + query.prepare(QStringLiteral("SELECT COUNT(*) AS cnt FROM cloudConnection")); if (!query.exec()) { qWarning() << __func__ << ": " << query.lastError(); @@ -176,8 +158,7 @@ bool CloudConnection::remove() { } } -CloudConnection CloudConnection::cloudConnectionFromQuery( - const QSqlQuery &query) { +CloudConnection CloudConnection::cloudConnectionFromQuery(const QSqlQuery &query) { CloudConnection cloudConnection; cloudConnection.fillFromQuery(query); return cloudConnection; @@ -192,16 +173,14 @@ bool CloudConnection::fillFromQuery(const QSqlQuery &query) { query.value(QStringLiteral("password")).toString()); this->priority = query.value(QStringLiteral("priority")).toInt(); - const int databaseVersion = DatabaseService::getAppData( - QStringLiteral("database_version")).toInt(); + const int databaseVersion = + DatabaseService::getAppData(QStringLiteral("database_version")).toInt(); - this->accountId = databaseVersion >= 41 ? - query.value(QStringLiteral("account_id")).toString() : - QStringLiteral(""); + this->accountId = databaseVersion >= 41 ? query.value(QStringLiteral("account_id")).toString() + : QStringLiteral(""); - this->appQOwnNotesAPIEnabled = databaseVersion >= 34 ? - query.value(QStringLiteral("qownnotesapi_enabled")).toBool() : - true; + this->appQOwnNotesAPIEnabled = + databaseVersion >= 34 ? query.value(QStringLiteral("qownnotesapi_enabled")).toBool() : true; return true; } @@ -212,8 +191,7 @@ QList<CloudConnection> CloudConnection::fetchAll() { QList<CloudConnection> cloudConnectionList; - query.prepare(QStringLiteral( - "SELECT * FROM cloudConnection ORDER BY priority ASC, id ASC")); + query.prepare(QStringLiteral("SELECT * FROM cloudConnection ORDER BY priority ASC, id ASC")); if (!query.exec()) { qWarning() << __func__ << ": " << query.lastError(); } else { @@ -255,8 +233,7 @@ bool CloudConnection::store() { query.bindValue(QStringLiteral(":password"), CryptoService::instance()->encryptToString(this->password)); query.bindValue(QStringLiteral(":priority"), this->priority); - query.bindValue(QStringLiteral(":qownnotesapi_enabled"), - this->appQOwnNotesAPIEnabled); + query.bindValue(QStringLiteral(":qownnotesapi_enabled"), this->appQOwnNotesAPIEnabled); if (!query.exec()) { // on error @@ -324,9 +301,7 @@ bool CloudConnection::isFetched() { return (this->id > 0); } /** * Checks if this note folder is the current one */ -bool CloudConnection::isCurrent() { - return currentCloudConnection().getId() == id; -} +bool CloudConnection::isCurrent() { return currentCloudConnection().getId() == id; } /** * Migrate the connections settings to a CloudConnection object @@ -337,10 +312,8 @@ bool CloudConnection::migrateToCloudConnections() { } QSettings settings; - const QString serverUrl = - settings.value(QStringLiteral("ownCloud/serverUrl")).toString(); - const QString username = - settings.value(QStringLiteral("ownCloud/userName")).toString(); + const QString serverUrl = settings.value(QStringLiteral("ownCloud/serverUrl")).toString(); + const QString username = settings.value(QStringLiteral("ownCloud/userName")).toString(); const QString password = CryptoService::instance()->decryptToString( settings.value(QStringLiteral("ownCloud/password")).toString()); @@ -381,10 +354,8 @@ QList<int> CloudConnection::fetchUsedCloudConnectionsIds() { QDebug operator<<(QDebug dbg, const CloudConnection &cloudConnection) { dbg.nospace() << "CloudConnection: <id>" << cloudConnection.id << " <name>" - << cloudConnection.name << " <serverUrl>" - << cloudConnection.serverUrl << " <username>" - << cloudConnection.username << " <accountId>" - << cloudConnection.accountId << " <priority>" - << cloudConnection.priority; + << cloudConnection.name << " <serverUrl>" << cloudConnection.serverUrl + << " <username>" << cloudConnection.username << " <accountId>" + << cloudConnection.accountId << " <priority>" << cloudConnection.priority; return dbg.space(); } diff --git a/src/entities/cloudconnection.h b/src/entities/cloudconnection.h index db12e59fc..d78b88102 100644 --- a/src/entities/cloudconnection.h +++ b/src/entities/cloudconnection.h @@ -7,14 +7,13 @@ class CloudConnection { explicit CloudConnection(); int getId(); - static bool create(const QString &name, const QString &serverUrl, - const QString &username, const QString &password); + static bool create(const QString &name, const QString &serverUrl, const QString &username, + const QString &password); static CloudConnection fetch(int id, bool ignoreTableWarning = false); static CloudConnection cloudConnectionFromQuery(const QSqlQuery &query); bool store(); bool storeMigratedCloudConnection(); - friend QDebug operator<<(QDebug dbg, - const CloudConnection &CloudConnection); + friend QDebug operator<<(QDebug dbg, const CloudConnection &CloudConnection); bool exists(); bool fillFromQuery(const QSqlQuery &query); bool remove(); @@ -37,8 +36,7 @@ class CloudConnection { static int countAll(); static bool migrateToCloudConnections(); bool isCurrent(); - static CloudConnection currentCloudConnection( - bool ignoreTableWarning = false); + static CloudConnection currentCloudConnection(bool ignoreTableWarning = false); static CloudConnection firstCloudConnection(); static CloudConnection currentTodoCalendarCloudConnection(); QString getServerUrlPath(); diff --git a/src/entities/commandsnippet.cpp b/src/entities/commandsnippet.cpp index c124a779c..51c0606bd 100644 --- a/src/entities/commandsnippet.cpp +++ b/src/entities/commandsnippet.cpp @@ -26,16 +26,14 @@ CommandSnippet::CommandSnippet(QString command, QString description, QStringList QJsonObject CommandSnippet::jsonObject() const { QJsonObject commandSnippetObject; commandSnippetObject.insert(QStringLiteral("command"), QJsonValue::fromVariant(command)); - commandSnippetObject.insert(QStringLiteral("tags"), - QJsonValue::fromVariant(tags)); + commandSnippetObject.insert(QStringLiteral("tags"), QJsonValue::fromVariant(tags)); commandSnippetObject.insert(QStringLiteral("description"), - QJsonValue::fromVariant(description)); + QJsonValue::fromVariant(description)); return commandSnippetObject; } QDebug operator<<(QDebug dbg, const CommandSnippet &commandSnippet) { - dbg.nospace() << " <command>" << commandSnippet.command - << " <tags>" << commandSnippet.tags + dbg.nospace() << " <command>" << commandSnippet.command << " <tags>" << commandSnippet.tags << " <description>" << commandSnippet.description; return dbg.space(); } @@ -51,13 +49,12 @@ bool CommandSnippet::operator==(const CommandSnippet &commandSnippet) const { * @return */ QVector<CommandSnippet> CommandSnippet::parseCommandSnippets(const QString &text, - bool withPrefixOnly) { + bool withPrefixOnly) { QRegularExpressionMatchIterator i; QVector<CommandSnippet> commandSnippets; - auto regex = QRegularExpression( - withPrefixOnly ? QStringLiteral(R"([-*]\s+cmd:\s+`(.+?)`(.*)$)") : - QStringLiteral(R"([-*]\s+`(.+?)`(.*)$)"), - QRegularExpression::MultilineOption); + auto regex = QRegularExpression(withPrefixOnly ? QStringLiteral(R"([-*]\s+cmd:\s+`(.+?)`(.*)$)") + : QStringLiteral(R"([-*]\s+`(.+?)`(.*)$)"), + QRegularExpression::MultilineOption); // parse command snippets like "- `my-command` #tag1 #tag2 description text" // with optional tags and description @@ -72,16 +69,15 @@ QVector<CommandSnippet> CommandSnippet::parseCommandSnippets(const QString &text if (!additionalText.isEmpty()) { QRegularExpressionMatchIterator addIterator = - QRegularExpression(QStringLiteral(R"(#([^\s#]+))")) - .globalMatch(additionalText); + QRegularExpression(QStringLiteral(R"(#([^\s#]+))")).globalMatch(additionalText); while (addIterator.hasNext()) { QRegularExpressionMatch addMatch = addIterator.next(); QString tag = addMatch.captured(1).trimmed(); if (!tags.contains(tag)) { tags << tag; - additionalText.remove(QRegularExpression( - "#" + QRegularExpression::escape(tag) + "\\b")); + additionalText.remove( + QRegularExpression("#" + QRegularExpression::escape(tag) + "\\b")); } } @@ -113,8 +109,7 @@ QVector<CommandSnippet> CommandSnippet::parseCommandSnippets(const QString &text if (!additionalText.isEmpty()) { QRegularExpressionMatchIterator addIterator = - QRegularExpression(QStringLiteral(R"(#([^\s#]+))")) - .globalMatch(additionalText); + QRegularExpression(QStringLiteral(R"(#([^\s#]+))")).globalMatch(additionalText); while (addIterator.hasNext()) { QRegularExpressionMatch addMatch = addIterator.next(); QString tag = addMatch.captured(1).trimmed(); @@ -147,7 +142,7 @@ QString CommandSnippet::commandSnippetsWebServiceJsonText( QJsonObject commandSnippetResultObject; commandSnippetResultObject.insert(QStringLiteral("type"), - QJsonValue::fromVariant("commandSnippets")); + QJsonValue::fromVariant("commandSnippets")); commandSnippetResultObject.insert(QStringLiteral("data"), commandSnippetObjectList); QJsonDocument doc(commandSnippetResultObject); @@ -161,7 +156,7 @@ QString CommandSnippet::commandSnippetsWebServiceJsonText( * @return */ QString CommandSnippet::parsedCommandSnippetsWebServiceJsonText(const QString &text, - bool withPrefixOnly) { + bool withPrefixOnly) { return commandSnippetsWebServiceJsonText(parseCommandSnippets(text, withPrefixOnly)); } @@ -185,7 +180,8 @@ void CommandSnippet::mergeInList(QVector<CommandSnippet> &commandSnippets) { /** * Merges a commandSnippet into a list of commandSnippets */ -void CommandSnippet::mergeInList(QVector<CommandSnippet> &commandSnippets, CommandSnippet &commandSnippet) { +void CommandSnippet::mergeInList(QVector<CommandSnippet> &commandSnippets, + CommandSnippet &commandSnippet) { commandSnippet.mergeInList(commandSnippets); } @@ -210,7 +206,7 @@ void CommandSnippet::merge(CommandSnippet &commandSnippet) { * Merges a list of commandSnippets into another */ void CommandSnippet::mergeListInList(const QVector<CommandSnippet> &sourceCommandSnippets, - QVector<CommandSnippet> &destinationCommandSnippets) { + QVector<CommandSnippet> &destinationCommandSnippets) { for (CommandSnippet commandSnippet : sourceCommandSnippets) { commandSnippet.mergeInList(destinationCommandSnippets); } diff --git a/src/entities/commandsnippet.h b/src/entities/commandsnippet.h index 1892c6cf3..3b01b2db6 100644 --- a/src/entities/commandsnippet.h +++ b/src/entities/commandsnippet.h @@ -13,17 +13,18 @@ class CommandSnippet { public: CommandSnippet(); explicit CommandSnippet(QString command, QString description = QString(), - QStringList tagList = QStringList()); + QStringList tagList = QStringList()); friend QDebug operator<<(QDebug dbg, const CommandSnippet &commandSnippet); QJsonObject jsonObject() const; static QVector<CommandSnippet> parseCommandSnippets(const QString &text, - bool withPrefixOnly = false); + bool withPrefixOnly = false); static QString commandSnippetsWebServiceJsonText( const QVector<CommandSnippet> &commandSnippets); - static QString parsedCommandSnippetsWebServiceJsonText( - const QString &text, bool withPrefixOnly = false); + static QString parsedCommandSnippetsWebServiceJsonText(const QString &text, + bool withPrefixOnly = false); bool operator==(const CommandSnippet &commandSnippet) const; - static void mergeInList(QVector<CommandSnippet> &commandSnippets, CommandSnippet &commandSnippet); + static void mergeInList(QVector<CommandSnippet> &commandSnippets, + CommandSnippet &commandSnippet); static void mergeListInList(const QVector<CommandSnippet> &sourceCommandSnippets, QVector<CommandSnippet> &destinationCommandSnippets); void mergeInList(QVector<CommandSnippet> &commandSnippets); diff --git a/src/entities/note.cpp b/src/entities/note.cpp index 8654a7383..c4b7818cb 100644 --- a/src/entities/note.cpp +++ b/src/entities/note.cpp @@ -1,5 +1,6 @@ #include "entities/note.h" +#include <botanwrapper.h> #include <services/owncloudservice.h> #include <services/scriptingservice.h> #include <utils/gui.h> @@ -26,9 +27,6 @@ #include "entities/bookmark.h" #include "entities/commandsnippet.h" #include "helpers/codetohtmlconverter.h" - -#include <botanwrapper.h> - #include "libraries/md4c/src/md4c-html.h" #include "libraries/md4c/src/md4c.h" #include "libraries/simplecrypt/simplecrypt.h" @@ -43,7 +41,7 @@ #endif Note::Note() - : _id{0}, + : _id{0}, _noteSubFolderId{0}, _cryptoKey{0}, _fileSize{0}, @@ -69,9 +67,7 @@ QString Note::getShareUrl() const { return this->_shareUrl; } int Note::getShareId() const { return this->_shareId; } -unsigned int Note::getSharePermissions() const { - return this->_sharePermissions; -} +unsigned int Note::getSharePermissions() const { return this->_sharePermissions; } /** * Check 2nd bit for edit permissions @@ -111,9 +107,7 @@ void Note::setNoteSubFolderId(int id) { this->_noteSubFolderId = id; } QString Note::getNoteText() const { return this->_noteText; } -void Note::setHasDirtyData(const bool hasDirtyData) { - this->_hasDirtyData = hasDirtyData; -} +void Note::setHasDirtyData(const bool hasDirtyData) { this->_hasDirtyData = hasDirtyData; } bool Note::getHasDirtyData() const { return this->_hasDirtyData; } @@ -123,22 +117,15 @@ void Note::setShareUrl(QString url) { this->_shareUrl = std::move(url); } void Note::setShareId(int id) { this->_shareId = id; } -void Note::setSharePermissions(unsigned int permissions) { - this->_sharePermissions = permissions; -} +void Note::setSharePermissions(unsigned int permissions) { this->_sharePermissions = permissions; } -void Note::setCryptoKey(const qint64 cryptoKey) { - this->_cryptoKey = cryptoKey; -} +void Note::setCryptoKey(const qint64 cryptoKey) { this->_cryptoKey = cryptoKey; } void Note::setNoteText(QString text) { this->_noteText = std::move(text); } -void Note::setDecryptedNoteText(QString text) { - this->_decryptedNoteText = std::move(text); -} +void Note::setDecryptedNoteText(QString text) { this->_decryptedNoteText = std::move(text); } -bool Note::addNote(const QString &name, const QString &fileName, - const QString &text) { +bool Note::addNote(const QString &name, const QString &fileName, const QString &text) { const QSqlDatabase db = QSqlDatabase::database(QStringLiteral("memory")); QSqlQuery query(db); @@ -178,8 +165,7 @@ Note Note::fetch(int id) { */ Note Note::fetchByName(const QRegularExpression ®Exp, int noteSubFolderId) { const QVector<Note> noteList = - noteSubFolderId == -1 ? fetchAll() - : fetchAllByNoteSubFolderId(noteSubFolderId); + noteSubFolderId == -1 ? fetchAll() : fetchAllByNoteSubFolderId(noteSubFolderId); // since there is no regular expression search in Qt's sqlite // implementation we have to iterate @@ -204,10 +190,8 @@ Note Note::fetchByFileName(const QString &fileName, int noteSubFolderId) { return note; } -Note Note::fetchByFileName(const QString &fileName, - const QString ¬eSubFolderPathData) { - auto noteSubFolder = NoteSubFolder::fetchByPathData(noteSubFolderPathData, - QStringLiteral("/")); +Note Note::fetchByFileName(const QString &fileName, const QString ¬eSubFolderPathData) { + auto noteSubFolder = NoteSubFolder::fetchByPathData(noteSubFolderPathData, QStringLiteral("/")); return fetchByFileName(fileName, noteSubFolder.getId()); } @@ -251,8 +235,7 @@ Note Note::fetchByRelativeFilePath(const QString &relativePath) { // load note subfolder and note from the relative path // be aware that there must not be a ".." in the path, a canonical path must // be presented! - const auto noteSubFolder = - NoteSubFolder::fetchByPathData(fileInfo.path(), QStringLiteral("/")); + const auto noteSubFolder = NoteSubFolder::fetchByPathData(fileInfo.path(), QStringLiteral("/")); if ((fileInfo.path() != ".") && !noteSubFolder.isFetched()) { return Note(); @@ -269,8 +252,7 @@ Note Note::fetchByRelativeFilePath(const QString &relativePath) { * @return */ Note Note::fetchByFileUrl(const QUrl &url) { - const QString &relativePath = - Note::fileUrlInCurrentNoteFolderToRelativePath(url); + const QString &relativePath = Note::fileUrlInCurrentNoteFolderToRelativePath(url); const Note note = Note::fetchByRelativeFilePath(relativePath); return note; @@ -308,19 +290,17 @@ bool Note::copyToPath(const QString &destinationPath, QString noteFolderPath) { QDir d; if (this->fileExists() && (d.exists(destinationPath))) { QFile file(fullNoteFilePath()); - QString destinationFileName = - destinationPath + QDir::separator() + this->_fileName; + QString destinationFileName = destinationPath + QDir::separator() + this->_fileName; if (d.exists(destinationFileName)) { qDebug() << destinationFileName << "already exists!"; // find a new filename for the note const QDateTime currentDateTime = QDateTime::currentDateTime(); - destinationFileName = destinationPath + QDir::separator() + - this->_name + QChar(' ') + - currentDateTime.toString(Qt::ISODate) - .replace(QChar(':'), QChar('_')) + - QChar('.') + defaultNoteFileExtension(); + destinationFileName = + destinationPath + QDir::separator() + this->_name + QChar(' ') + + currentDateTime.toString(Qt::ISODate).replace(QChar(':'), QChar('_')) + QChar('.') + + defaultNoteFileExtension(); qDebug() << "New file name:" << destinationFileName; } @@ -345,8 +325,7 @@ bool Note::copyToPath(const QString &destinationPath, QString noteFolderPath) { return true; } - const QDir mediaDir(noteFolderPath + QDir::separator() + - QStringLiteral("media")); + const QDir mediaDir(noteFolderPath + QDir::separator() + QStringLiteral("media")); // created the media folder if it doesn't exist if (!mediaDir.exists()) { @@ -358,8 +337,7 @@ bool Note::copyToPath(const QString &destinationPath, QString noteFolderPath) { // copy all images to the media folder inside // destinationPath for (const QString &fileName : mediaFileList) { - QFile mediaFile(NoteFolder::currentMediaPath() + QDir::separator() + - fileName); + QFile mediaFile(NoteFolder::currentMediaPath() + QDir::separator() + fileName); if (mediaFile.exists()) { mediaFile.copy(mediaDir.path() + QDir::separator() + fileName); @@ -392,8 +370,7 @@ bool Note::exportToPath(const QString &destinationPath, bool withAttachedFiles) // copy all images to the destination folder for (const QString &fileName : mediaFileList) { - QFile mediaFile(NoteFolder::currentMediaPath() + QDir::separator() + - fileName); + QFile mediaFile(NoteFolder::currentMediaPath() + QDir::separator() + fileName); if (mediaFile.exists()) { mediaFile.copy(absolutePath + QDir::separator() + fileName); @@ -411,7 +388,7 @@ bool Note::exportToPath(const QString &destinationPath, bool withAttachedFiles) const QString fileName = match.captured(2); noteText.replace(wholeLinkText, - titlePart + QStringLiteral("(./") + fileName + QChar(')')); + titlePart + QStringLiteral("(./") + fileName + QChar(')')); } } @@ -424,14 +401,15 @@ bool Note::exportToPath(const QString &destinationPath, bool withAttachedFiles) // copy all attachment to the destination folder for (const QString &fileName : attachmentFileList) { QFile attachmentFile(NoteFolder::currentAttachmentsPath() + QDir::separator() + - fileName); + fileName); if (attachmentFile.exists()) { attachmentFile.copy(absolutePath + QDir::separator() + fileName); } } - static const QRegularExpression re(QStringLiteral(R"((\[.*?\])\(.*attachments/(.+?)\))")); + static const QRegularExpression re( + QStringLiteral(R"((\[.*?\])\(.*attachments/(.+?)\))")); QRegularExpressionMatchIterator i = re.globalMatch(noteText); // remove the "attachments/" part from the file names in the note text @@ -442,7 +420,7 @@ bool Note::exportToPath(const QString &destinationPath, bool withAttachedFiles) const QString fileName = match.captured(2); noteText.replace(wholeLinkText, - titlePart + QStringLiteral("(./") + fileName + QChar(')')); + titlePart + QStringLiteral("(./") + fileName + QChar(')')); } } } @@ -474,8 +452,7 @@ bool Note::exportToPath(const QString &destinationPath, bool withAttachedFiles) * @param destinationPath * @return bool */ -bool Note::moveToPath(const QString &destinationPath, - const QString ¬eFolderPath) { +bool Note::moveToPath(const QString &destinationPath, const QString ¬eFolderPath) { const bool result = copyToPath(destinationPath, noteFolderPath); if (result) { return remove(true); @@ -506,9 +483,7 @@ QStringList Note::getMediaFileList() { return fileList; } -bool Note::hasMediaFiles() { - return !getMediaFileList().empty(); -} +bool Note::hasMediaFiles() { return !getMediaFileList().empty(); } bool Note::updateRelativeMediaFileLinks() { static const QRegularExpression re(QStringLiteral(R"((!\[.*?\])\((.*media/(.+?))\))")); @@ -529,8 +504,7 @@ bool Note::updateRelativeMediaFileLinks() { const QString fileName = match.captured(3); filePath = mediaUrlStringForFileName(fileName); - newText.replace(wholeLinkText, - titlePart + QChar('(') + filePath + QChar(')')); + newText.replace(wholeLinkText, titlePart + QChar('(') + filePath + QChar(')')); textWasUpdated = true; } @@ -551,8 +525,7 @@ QStringList Note::getAttachmentsFileList() const { // match attachment links like [956321614](file://attachments/956321614.pdf) // or [956321614](attachments/956321614.pdf) - static const QRegularExpression re( - QStringLiteral(R"(\[.*?\]\(.*attachments/(.+?)\))")); + static const QRegularExpression re(QStringLiteral(R"(\[.*?\]\(.*attachments/(.+?)\))")); QRegularExpressionMatchIterator i = re.globalMatch(text); while (i.hasNext()) { @@ -564,13 +537,10 @@ QStringList Note::getAttachmentsFileList() const { return fileList; } -bool Note::hasAttachments() { - return !getAttachmentsFileList().empty(); -} +bool Note::hasAttachments() { return !getAttachmentsFileList().empty(); } bool Note::updateRelativeAttachmentFileLinks() { - static const QRegularExpression re( - QStringLiteral(R"((\[.*?\])\((.*attachments/(.+?))\))")); + static const QRegularExpression re(QStringLiteral(R"((\[.*?\])\((.*attachments/(.+?))\))")); QRegularExpressionMatchIterator i = re.globalMatch(_noteText); bool textWasUpdated = false; QString newText = getNoteText(); @@ -588,8 +558,7 @@ bool Note::updateRelativeAttachmentFileLinks() { const QString fileName = match.captured(3); filePath = attachmentUrlStringForFileName(fileName); - newText.replace(wholeLinkText, - titlePart + QChar('(') + filePath + QChar(')')); + newText.replace(wholeLinkText, titlePart + QChar('(') + filePath + QChar(')')); textWasUpdated = true; } @@ -610,8 +579,7 @@ Note Note::fetchByShareId(int shareId) { const QSqlDatabase db = QSqlDatabase::database(QStringLiteral("memory")); QSqlQuery query(db); - query.prepare( - QStringLiteral("SELECT * FROM note WHERE share_id = :share_id")); + query.prepare(QStringLiteral("SELECT * FROM note WHERE share_id = :share_id")); query.bindValue(QStringLiteral(":share_id"), shareId); if (!query.exec()) { @@ -625,18 +593,15 @@ Note Note::fetchByShareId(int shareId) { return Note(); } -Note Note::fetchByName(const QString &name, - const QString ¬eSubFolderPathData, +Note Note::fetchByName(const QString &name, const QString ¬eSubFolderPathData, const QString &pathDataSeparator) { int noteSubFolderId = - NoteSubFolder::fetchByPathData(noteSubFolderPathData, pathDataSeparator) - .getId(); + NoteSubFolder::fetchByPathData(noteSubFolderPathData, pathDataSeparator).getId(); return fetchByName(name, noteSubFolderId); } -int Note::fetchNoteIdByName(const QString &name, int noteSubFolderId) -{ +int Note::fetchNoteIdByName(const QString &name, int noteSubFolderId) { const QSqlDatabase db = QSqlDatabase::database(QStringLiteral("memory")); QSqlQuery query(db); @@ -686,9 +651,7 @@ Note Note::fetchByName(const QString &name, int noteSubFolderId) { return Note(); } -Note Note::noteFromQuery(const QSqlQuery &query) { - return Note().fillFromQuery(query); -} +Note Note::noteFromQuery(const QSqlQuery &query) { return Note().fillFromQuery(query); } Note Note::fillFromQuery(const QSqlQuery &query) { _id = query.value(QStringLiteral("id")).toInt(); @@ -696,20 +659,16 @@ Note Note::fillFromQuery(const QSqlQuery &query) { _fileName = query.value(QStringLiteral("file_name")).toString(); _shareUrl = query.value(QStringLiteral("share_url")).toString(); _shareId = query.value(QStringLiteral("share_id")).toInt(); - _sharePermissions = - query.value(QStringLiteral("share_permissions")).toInt(); - _noteSubFolderId = - query.value(QStringLiteral("note_sub_folder_id")).toInt(); + _sharePermissions = query.value(QStringLiteral("share_permissions")).toInt(); + _noteSubFolderId = query.value(QStringLiteral("note_sub_folder_id")).toInt(); _noteText = query.value(QStringLiteral("note_text")).toString(); - _decryptedNoteText = - query.value(QStringLiteral("decrypted_note_text")).toString(); + _decryptedNoteText = query.value(QStringLiteral("decrypted_note_text")).toString(); _cryptoKey = query.value(QStringLiteral("crypto_key")).toLongLong(); _fileSize = query.value(QStringLiteral("file_size")).toLongLong(); _cryptoPassword = query.value(QStringLiteral("crypto_password")).toString(); _hasDirtyData = query.value(QStringLiteral("has_dirty_data")).toInt() == 1; _fileCreated = query.value(QStringLiteral("file_created")).toDateTime(); - _fileLastModified = - query.value(QStringLiteral("file_last_modified")).toDateTime(); + _fileLastModified = query.value(QStringLiteral("file_last_modified")).toDateTime(); _created = query.value(QStringLiteral("created")).toDateTime(); _modified = query.value(QStringLiteral("modified")).toDateTime(); return *this; @@ -721,12 +680,11 @@ QVector<Note> Note::fetchAll(int limit) { QVector<Note> noteList; - const QString sql = - limit >= 0 ? QStringLiteral( - "SELECT * FROM note ORDER BY file_last_modified DESC " - "LIMIT :limit") - : QStringLiteral( - "SELECT * FROM note ORDER BY file_last_modified DESC"); + const QString sql = limit >= 0 + ? QStringLiteral( + "SELECT * FROM note ORDER BY file_last_modified DESC " + "LIMIT :limit") + : QStringLiteral("SELECT * FROM note ORDER BY file_last_modified DESC"); query.prepare(sql); @@ -812,8 +770,7 @@ QVector<Note> Note::fetchAllByNoteSubFolderId(int noteSubFolderId) { return noteList; } -QVector<int> Note::fetchAllIdsByNoteSubFolderId(int noteSubFolderId) -{ +QVector<int> Note::fetchAllIdsByNoteSubFolderId(int noteSubFolderId) { const QSqlDatabase db = QSqlDatabase::database(QStringLiteral("memory")); QSqlQuery query(db); @@ -901,8 +858,7 @@ QVector<Note> Note::search(const QString &text) { query.prepare( QStringLiteral("SELECT * FROM note WHERE note_text LIKE :text " "ORDER BY file_last_modified DESC")); - query.bindValue(QStringLiteral(":text"), - QStringLiteral("%") + text + QStringLiteral("%")); + query.bindValue(QStringLiteral(":text"), QStringLiteral("%") + text + QStringLiteral("%")); if (!query.exec()) { qWarning() << __func__ << ": " << query.lastError(); @@ -915,24 +871,20 @@ QVector<Note> Note::search(const QString &text) { return noteList; } -QVector<QString> Note::searchAsNameListInCurrentNoteSubFolder( - const QString &text, bool searchInNameOnly) { +QVector<QString> Note::searchAsNameListInCurrentNoteSubFolder(const QString &text, + bool searchInNameOnly) { const QSqlDatabase db = QSqlDatabase::database(QStringLiteral("memory")); QSqlQuery query(db); QVector<QString> nameList; const QString textSearchSql = - !searchInNameOnly ? QStringLiteral("OR note_text LIKE :text ") - : QLatin1String(""); + !searchInNameOnly ? QStringLiteral("OR note_text LIKE :text ") : QLatin1String(""); const int noteSubFolderId = NoteSubFolder::activeNoteSubFolderId(); - query.prepare( - QStringLiteral("SELECT name FROM note WHERE (name LIKE :text ") + - textSearchSql + - QStringLiteral(") AND note_sub_folder_id = :note_sub_folder_id " - "ORDER BY file_last_modified DESC")); - query.bindValue(QStringLiteral(":text"), - QStringLiteral("%") + text + QStringLiteral("%")); + query.prepare(QStringLiteral("SELECT name FROM note WHERE (name LIKE :text ") + textSearchSql + + QStringLiteral(") AND note_sub_folder_id = :note_sub_folder_id " + "ORDER BY file_last_modified DESC")); + query.bindValue(QStringLiteral(":text"), QStringLiteral("%") + text + QStringLiteral("%")); query.bindValue(QStringLiteral(":note_sub_folder_id"), noteSubFolderId); if (!query.exec()) { @@ -946,21 +898,17 @@ QVector<QString> Note::searchAsNameListInCurrentNoteSubFolder( return nameList; } -QVector<QString> Note::searchAsNameList(const QString &text, - bool searchInNameOnly) { +QVector<QString> Note::searchAsNameList(const QString &text, bool searchInNameOnly) { const QSqlDatabase db = QSqlDatabase::database(QStringLiteral("memory")); QSqlQuery query(db); QVector<QString> nameList; const QString textSearchSql = - !searchInNameOnly ? QStringLiteral("OR note_text LIKE :text ") - : QLatin1String(""); + !searchInNameOnly ? QStringLiteral("OR note_text LIKE :text ") : QLatin1String(""); - query.prepare( - QStringLiteral("SELECT name FROM note WHERE (name LIKE :text ") + - textSearchSql + QStringLiteral(") ORDER BY file_last_modified DESC")); - query.bindValue(QStringLiteral(":text"), - QStringLiteral("%") + text + QStringLiteral("%")); + query.prepare(QStringLiteral("SELECT name FROM note WHERE (name LIKE :text ") + textSearchSql + + QStringLiteral(") ORDER BY file_last_modified DESC")); + query.bindValue(QStringLiteral(":text"), QStringLiteral("%") + text + QStringLiteral("%")); if (!query.exec()) { qWarning() << __func__ << ": " << query.lastError(); @@ -992,8 +940,7 @@ QString Note::removeNameSearchPrefix(QString searchTerm) { * You can search for longer texts by using quotes, `"this word1" word2` * will find all notes that are containing `this word1` and `word2` */ -QVector<int> Note::searchInNotes(QString search, bool ignoreNoteSubFolder, - int noteSubFolderId) { +QVector<int> Note::searchInNotes(QString search, bool ignoreNoteSubFolder, int noteSubFolderId) { const QSqlDatabase db = QSqlDatabase::database(QStringLiteral("memory")); QSqlQuery query(db); auto noteIdList = QVector<int>(); @@ -1015,18 +962,19 @@ QVector<int> Note::searchInNotes(QString search, bool ignoreNoteSubFolder, // if we just want to search in the name we use different columns // skip encrypted notes if search term is not found in (file) name of note - sqlList.append(isNameSearch(queryString) ? - QStringLiteral("(name LIKE ? OR file_name LIKE ?)") : - QStringLiteral("((note_text LIKE ? AND note_text NOT LIKE '%\n%1\n%') OR name LIKE ?)") - .arg(NOTE_TEXT_ENCRYPTION_PRE_STRING)); + sqlList.append( + isNameSearch(queryString) + ? QStringLiteral("(name LIKE ? OR file_name LIKE ?)") + : QStringLiteral( + "((note_text LIKE ? AND note_text NOT LIKE '%\n%1\n%') OR name LIKE ?)") + .arg(NOTE_TEXT_ENCRYPTION_PRE_STRING)); } QString sql; // build the query if (ignoreNoteSubFolder) { - sql = QStringLiteral("SELECT id FROM note WHERE ") + - sqlList.join(QStringLiteral(" AND ")); + sql = QStringLiteral("SELECT id FROM note WHERE ") + sqlList.join(QStringLiteral(" AND ")); query.prepare(sql); } else { sql = QStringLiteral( @@ -1050,10 +998,8 @@ QVector<int> Note::searchInNotes(QString search, bool ignoreNoteSubFolder, pos = ignoreNoteSubFolder ? pos : pos + 1; // bind the values for the note text (or name) and the filename - query.bindValue( - pos, QStringLiteral("%") + queryString + QStringLiteral("%")); - query.bindValue(pos + 1, QStringLiteral("%") + queryString + - QStringLiteral("%")); + query.bindValue(pos, QStringLiteral("%") + queryString + QStringLiteral("%")); + query.bindValue(pos + 1, QStringLiteral("%") + queryString + QStringLiteral("%")); } if (!query.exec()) { @@ -1074,8 +1020,7 @@ int Note::countSearchTextInNote(const QString &search) const { /** * Builds a string list of a search string */ -QStringList Note::buildQueryStringList(QString searchString, - bool escapeForRegularExpression, +QStringList Note::buildQueryStringList(QString searchString, bool escapeForRegularExpression, bool removeSearchPrefix) { auto queryStrings = QStringList(); @@ -1111,9 +1056,7 @@ QStringList Note::buildQueryStringList(QString searchString, // escape the text so strings like `^ ` don't cause an // infinite loop - queryStrings.append(escapeForRegularExpression - ? QRegularExpression::escape(text) - : text); + queryStrings.append(escapeForRegularExpression ? QRegularExpression::escape(text) : text); } // remove empty items, so the search will not run amok @@ -1182,8 +1125,7 @@ QStringList Note::fetchNoteFileNames() { QStringList list; - query.prepare(QStringLiteral( - "SELECT file_name FROM note ORDER BY file_last_modified DESC")); + query.prepare(QStringLiteral("SELECT file_name FROM note ORDER BY file_last_modified DESC")); if (!query.exec()) { qWarning() << __func__ << ": " << query.lastError(); } else { @@ -1204,8 +1146,7 @@ QVector<int> Note::fetchAllIdsByNoteTextPart(const QString &textPart) { query.prepare( QStringLiteral("SELECT id FROM note WHERE note_text LIKE :text " "ORDER BY file_last_modified DESC")); - query.bindValue(QStringLiteral(":text"), - QStringLiteral("%") + textPart + QStringLiteral("%")); + query.bindValue(QStringLiteral(":text"), QStringLiteral("%") + textPart + QStringLiteral("%")); if (!query.exec()) { qWarning() << __func__ << ": " << query.lastError(); @@ -1229,9 +1170,7 @@ bool Note::storeNewText(QString text) { return this->store(); } -void Note::setDecryptedText(QString text) { - this->_decryptedNoteText = std::move(text); -} +void Note::setDecryptedText(QString text) { this->_decryptedNoteText = std::move(text); } bool Note::storeNewDecryptedText(QString text) { if (text == this->_decryptedNoteText) { @@ -1258,9 +1197,7 @@ QString Note::defaultNoteFileExtension() { */ QStringList Note::noteFileExtensionList(const QString &prefix) { const QSettings settings; - QStringList list = - settings.value(QStringLiteral("noteFileExtensionList")) - .toStringList(); + QStringList list = settings.value(QStringLiteral("noteFileExtensionList")).toStringList(); list.removeDuplicates(); if (list.isEmpty()) { @@ -1320,19 +1257,19 @@ bool Note::store() { "WHERE id = :id")); query.bindValue(QStringLiteral(":id"), _id); } else { - query.prepare(QStringLiteral( - "INSERT INTO note" - "(name, share_url, share_id, share_permissions, file_name, " - "file_size, note_text, has_dirty_data, " - "file_last_modified, file_created, crypto_key," - "modified, crypto_password, decrypted_note_text, " - "note_sub_folder_id) " - "VALUES (:name, :share_url, :share_id, :share_permissions, " - ":file_name, :file_size, :note_text," - ":has_dirty_data, :file_last_modified," - ":file_created, :crypto_key, :modified," - ":crypto_password, :decrypted_note_text," - ":note_sub_folder_id)")); + query.prepare( + QStringLiteral("INSERT INTO note" + "(name, share_url, share_id, share_permissions, file_name, " + "file_size, note_text, has_dirty_data, " + "file_last_modified, file_created, crypto_key," + "modified, crypto_password, decrypted_note_text, " + "note_sub_folder_id) " + "VALUES (:name, :share_url, :share_id, :share_permissions, " + ":file_name, :file_size, :note_text," + ":has_dirty_data, :file_last_modified," + ":file_created, :crypto_key, :modified," + ":crypto_password, :decrypted_note_text," + ":note_sub_folder_id)")); } const QDateTime modified = QDateTime::currentDateTime(); @@ -1416,8 +1353,7 @@ bool Note::storeNoteTextFileToDisk(bool ¤tNoteTextChanged) { // rename the note file if (oldFile.exists()) { noteFileWasRenamed = oldFile.rename(fullNoteFilePath()); - qDebug() << __func__ - << " - 'noteFileWasRenamed': " << noteFileWasRenamed; + qDebug() << __func__ << " - 'noteFileWasRenamed': " << noteFileWasRenamed; // Restore the created date of the current note under Windows, // because it gets set to the current date when note is renamed @@ -1428,8 +1364,7 @@ bool Note::storeNoteTextFileToDisk(bool ¤tNoteTextChanged) { QFile file(fullNoteFilePath()); QFile::OpenMode flags = QIODevice::WriteOnly; const QSettings settings; - const bool useUNIXNewline = - settings.value(QStringLiteral("useUNIXNewline")).toBool(); + const bool useUNIXNewline = settings.value(QStringLiteral("useUNIXNewline")).toBool(); if (!useUNIXNewline) { flags |= QIODevice::Text; @@ -1457,8 +1392,7 @@ bool Note::storeNoteTextFileToDisk(bool ¤tNoteTextChanged) { } // rename the note file names of note tag links - Tag::renameNoteFileNamesOfLinks(oldName, newName, - this->getNoteSubFolder()); + Tag::renameNoteFileNamesOfLinks(oldName, newName, this->getNoteSubFolder()); // handle the replacing of all note urls if a note was renamed // (we couldn't make currentNoteTextChanged a pointer or the app would crash) @@ -1514,20 +1448,17 @@ bool Note::storeNoteTextFileToDisk(bool ¤tNoteTextChanged) { // filename has changed // #1190: we also need to check if the files are the same even if the // name is not the same for NTFS - if ((fullNoteFilePath() != oldNoteFilePath) && - (oldFileInfo != newFileInfo)) { + if ((fullNoteFilePath() != oldNoteFilePath) && (oldFileInfo != newFileInfo)) { // remove the old note file - if (oldFile.exists() && oldFileInfo.isFile() && - oldFileInfo.isReadable() && oldFile.remove()) { - qInfo() << QObject::tr("Renamed note-file was removed: %1") - .arg(oldFile.fileName()); + if (oldFile.exists() && oldFileInfo.isFile() && oldFileInfo.isReadable() && + oldFile.remove()) { + qInfo() << QObject::tr("Renamed note-file was removed: %1").arg(oldFile.fileName()); } else { qWarning() << QObject::tr( "Could not remove renamed note-file: %1" " - Error message: %2") - .arg(oldFile.fileName(), - oldFile.errorString()); + .arg(oldFile.fileName(), oldFile.errorString()); } } } @@ -1551,17 +1482,15 @@ void Note::restoreCreatedDate() { fileTime.dwLowDateTime = _100nanosecs; fileTime.dwHighDateTime = (_100nanosecs >> 32); - LPCWSTR filePath = - (const wchar_t *)QDir::toNativeSeparators(fullNoteFilePath()).utf16(); - HANDLE fileHandle = CreateFile( - filePath, FILE_WRITE_ATTRIBUTES, FILE_SHARE_READ | FILE_SHARE_WRITE, - nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); + LPCWSTR filePath = (const wchar_t *)QDir::toNativeSeparators(fullNoteFilePath()).utf16(); + HANDLE fileHandle = + CreateFile(filePath, FILE_WRITE_ATTRIBUTES, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, + OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); // set the created date to the old created date before the rename // see: // https://stackoverflow.com/questions/10041651/changing-the-file-creation-date-in-c-using-windows-h-in-windows-7 - SetFileTime(fileHandle, &fileTime, (LPFILETIME) nullptr, - (LPFILETIME) nullptr); + SetFileTime(fileHandle, &fileTime, (LPFILETIME) nullptr, (LPFILETIME) nullptr); CloseHandle(fileHandle); #endif } @@ -1603,8 +1532,7 @@ QString Note::extendedCleanupFileName(QString name) { */ bool Note::modifyNoteTextFileNameFromQMLHook() { // check if a QML function wants to set another note name - const QString newName = - ScriptingService::instance()->callHandleNoteTextFileNameHook(this); + const QString newName = ScriptingService::instance()->callHandleNoteTextFileNameHook(this); // set the file name from the QML hook if (!newName.isEmpty() && (newName != _name)) { @@ -1631,8 +1559,10 @@ bool Note::handleNoteTextFileName() { // remove frontmatter from start of markdown text if (noteText.startsWith(QLatin1String("---"))) { - static const QRegularExpression re(QStringLiteral(R"(^---((\r\n)|(\n\r)|\r|\n).+?((\r\n)|(\n\r)|\r|\n)---((\r\n)|(\n\r)|\r|\n))"), - QRegularExpression::DotMatchesEverythingOption); + static const QRegularExpression re( + QStringLiteral( + R"(^---((\r\n)|(\n\r)|\r|\n).+?((\r\n)|(\n\r)|\r|\n)---((\r\n)|(\n\r)|\r|\n))"), + QRegularExpression::DotMatchesEverythingOption); noteText.remove(re); } @@ -1684,8 +1614,7 @@ bool Note::handleNoteTextFileName() { // check if note with this filename already exists while (Note::fetchByFileName(fileName).isFetched()) { // find new filename for the note - name = nameBase + QStringLiteral(" ") + - QString::number(++nameCount); + name = nameBase + QStringLiteral(" ") + QString::number(++nameCount); fileName = generateNoteFileNameFromName(name); qDebug() << __func__ << " - 'override fileName': " << fileName; @@ -1709,8 +1638,8 @@ bool Note::handleNoteTextFileName() { // let's check if we would be able to write to the file if (!canWriteToNoteFile()) { - qDebug() << __func__ << " - cannot write to file " - << this->_fileName << " - we will try another filename"; + qDebug() << __func__ << " - cannot write to file " << this->_fileName + << " - we will try another filename"; // we try to replace some more characters (mostly for Windows // filesystems) @@ -1739,9 +1668,7 @@ QString Note::generateNoteFileNameFromName(const QString &name) { /** * Generates filename of the note from it's name */ -void Note::generateFileNameFromName() { - _fileName = generateNoteFileNameFromName(_name); -} +void Note::generateFileNameFromName() { _fileName = generateNoteFileNameFromName(_name); } /** * Checks if we can write to the note file @@ -1802,8 +1729,7 @@ QString Note::getFullFilePathForFile(const QString &fileName) { const QString notesPath = Utils::Misc::prependPortableDataPathIfNeeded( settings.value(QStringLiteral("notesPath")).toString()); - const QString path = Utils::Misc::removeIfEndsWith(std::move(notesPath), - QStringLiteral("/")) + + const QString path = Utils::Misc::removeIfEndsWith(std::move(notesPath), QStringLiteral("/")) + Utils::Misc::dirSeparator() + fileName; const QFileInfo fileInfo(path); @@ -1848,10 +1774,8 @@ QString Note::getNoteUrlForLinkingTo(const Note ¬e, bool forceLegacy) const { const QSettings settings; QString noteUrl; - if (forceLegacy || - settings.value(QStringLiteral("legacyLinking")).toBool()) { - const QString noteNameForLink = - Note::generateTextForLink(note.getName()); + if (forceLegacy || settings.value(QStringLiteral("legacyLinking")).toBool()) { + const QString noteNameForLink = Note::generateTextForLink(note.getName()); noteUrl = QStringLiteral("note://") + noteNameForLink; } else { noteUrl = urlEncodeNoteUrl(getFilePathRelativeToNote(note)); @@ -1874,9 +1798,7 @@ QString Note::getNoteUrlForLinkingTo(const Note ¬e, bool forceLegacy) const { * Example: * "Note with one bracket].md" will get "Note%20with%20one%20bracket%5D.md" */ -QString Note::urlEncodeNoteUrl(const QString &url) { - return QUrl::toPercentEncoding(url); -} +QString Note::urlEncodeNoteUrl(const QString &url) { return QUrl::toPercentEncoding(url); } /** * Returns the url decoded representation of a string to e.g. fetch a note from @@ -1894,9 +1816,7 @@ QString Note::urlDecodeNoteUrl(QString url) { /** * Returns the full path of the note file */ -QString Note::fullNoteFilePath() const { - return getFullFilePathForFile(relativeNoteFilePath()); -} +QString Note::fullNoteFilePath() const { return getFullFilePathForFile(relativeNoteFilePath()); } /** * Returns the full path of directory of the note file @@ -1970,9 +1890,8 @@ QUrl Note::fullNoteFileUrl() const { windowsSlash = QStringLiteral("/"); #endif - return QUrl( - QStringLiteral("file://") + windowsSlash + - QUrl::toPercentEncoding(fullNoteFilePath(), QByteArrayLiteral(":/"))); + return QUrl(QStringLiteral("file://") + windowsSlash + + QUrl::toPercentEncoding(fullNoteFilePath(), QByteArrayLiteral(":/"))); } /** @@ -1985,16 +1904,14 @@ QUrl Note::fullNoteFileUrl() const { * @param currentNoteTextChanged true if the current note text was changed during a rename * @return amount of notes that were saved */ -int Note::storeDirtyNotesToDisk(Note ¤tNote, bool *currentNoteChanged, - bool *noteWasRenamed, +int Note::storeDirtyNotesToDisk(Note ¤tNote, bool *currentNoteChanged, bool *noteWasRenamed, bool *currentNoteTextChanged) { const QSqlDatabase db = QSqlDatabase::database(QStringLiteral("memory")); QSqlQuery query(db); ScriptingService *scriptingService = ScriptingService::instance(); // qDebug() << "storeDirtyNotesToDisk"; - query.prepare( - QStringLiteral("SELECT * FROM note WHERE has_dirty_data = 1")); + query.prepare(QStringLiteral("SELECT * FROM note WHERE has_dirty_data = 1")); if (!query.exec()) { qWarning() << __func__ << ": " << query.lastError(); return 0; @@ -2003,8 +1920,7 @@ int Note::storeDirtyNotesToDisk(Note ¤tNote, bool *currentNoteChanged, for (int r = 0; query.next(); r++) { Note note = noteFromQuery(query); const QString &oldName = note.getName(); - const bool noteWasStored = note.storeNoteTextFileToDisk( - *currentNoteTextChanged); + const bool noteWasStored = note.storeNoteTextFileToDisk(*currentNoteTextChanged); // continue if note couldn't be stored if (!noteWasStored) { @@ -2016,8 +1932,7 @@ int Note::storeDirtyNotesToDisk(Note ¤tNote, bool *currentNoteChanged, // check if the file name has changed if (oldName != newName) { // rename the note file names of note tag links - Tag::renameNoteFileNamesOfLinks(oldName, newName, - note.getNoteSubFolder()); + Tag::renameNoteFileNamesOfLinks(oldName, newName, note.getNoteSubFolder()); *noteWasRenamed = true; // override the current note because the file name has changed @@ -2032,8 +1947,8 @@ int Note::storeDirtyNotesToDisk(Note ¤tNote, bool *currentNoteChanged, } // emit the signal for the QML that the note was stored - emit scriptingService->noteStored(QVariant::fromValue( - static_cast<QObject *>(NoteApi::fromNote(note)))); + emit scriptingService->noteStored( + QVariant::fromValue(static_cast<QObject *>(NoteApi::fromNote(note)))); // reassign currentNote if filename of currentNote has changed if (note.isSameFile(currentNote)) { @@ -2065,8 +1980,7 @@ bool Note::stripTrailingSpaces(int skipLine) { const auto lineText = noteTextLines.at(l); if (lineText.endsWith(QChar(' '))) { - noteTextLines[l] = - Utils::Misc::rstrip(Utils::Misc::rstrip(lineText)); + noteTextLines[l] = Utils::Misc::rstrip(Utils::Misc::rstrip(lineText)); wasStripped = true; } } @@ -2091,8 +2005,7 @@ QString Note::detectNewlineCharacters() { return QStringLiteral("\n"); } -void Note::createFromFile(QFile &file, int noteSubFolderId, - bool withNoteNameHook) { +void Note::createFromFile(QFile &file, int noteSubFolderId, bool withNoteNameHook) { if (file.open(QIODevice::ReadOnly)) { QTextStream in(&file); #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) @@ -2129,8 +2042,7 @@ void Note::createFromFile(QFile &file, int noteSubFolderId, if (withNoteNameHook) { // check if a name was set in a script - const QString hookName = - ScriptingService::instance()->callHandleNoteNameHook(this); + const QString hookName = ScriptingService::instance()->callHandleNoteNameHook(this); if (!hookName.isEmpty()) { this->_name = std::move(hookName); @@ -2147,8 +2059,7 @@ void Note::createFromFile(QFile &file, int noteSubFolderId, * @param noteSubFolder * @return */ -Note Note::updateOrCreateFromFile(QFile &file, - const NoteSubFolder ¬eSubFolder, +Note Note::updateOrCreateFromFile(QFile &file, const NoteSubFolder ¬eSubFolder, bool withNoteNameHook) { const QFileInfo fileInfo(file); Note note = fetchByFileName(fileInfo.fileName(), noteSubFolder.getId()); @@ -2156,8 +2067,7 @@ Note Note::updateOrCreateFromFile(QFile &file, // regardless if the file was found or not, if the size differs or the // file was modified after the internal note was modified we want to load // the note content again - if ((fileInfo.size() != note.getFileSize()) || - (fileInfo.lastModified() > note.getModified())) { + if ((fileInfo.size() != note.getFileSize()) || (fileInfo.lastModified() > note.getModified())) { // load file data and store note note.createFromFile(file, noteSubFolder.getId(), withNoteNameHook); @@ -2190,9 +2100,7 @@ bool Note::deleteAll() { * * @return bool */ -bool Note::fileExists() const { - return Utils::Misc::fileExists(fullNoteFilePath()); -} +bool Note::fileExists() const { return Utils::Misc::fileExists(fullNoteFilePath()); } /** * Checks if file of note exists in the filesystem and is writeable @@ -2215,16 +2123,12 @@ bool Note::noteIdExists(int id) { return fetch(id)._id > 0; } // // reloads the current Note (by fileName) // -bool Note::refetch() { - return this->fillByFileName(_fileName, _noteSubFolderId); -} +bool Note::refetch() { return this->fillByFileName(_fileName, _noteSubFolderId); } /** * Returns the suffix of the note file name */ -QString Note::fileNameSuffix() const { - return QFileInfo(_fileName).suffix(); -} +QString Note::fileNameSuffix() const { return QFileInfo(_fileName).suffix(); } /** * Returns the base name of the note file name @@ -2312,27 +2216,25 @@ bool Note::removeNoteFile() { * @param forExport defines whether the export or preview stylesheet * @return */ -QString Note::toMarkdownHtml(const QString ¬esPath, int maxImageWidth, - bool forExport, bool decrypt, bool base64Images) { +QString Note::toMarkdownHtml(const QString ¬esPath, int maxImageWidth, bool forExport, + bool decrypt, bool base64Images) { // get the decrypted note text (or the normal note text if there isn't any) const QString str = decrypt ? fetchDecryptedNoteText() : getNoteText(); // create a hash of the note text and the parameters - const QString toHash = str + QString::number(maxImageWidth) + - (forExport ? QChar('1') : QChar('0')) + - (decrypt ? QChar('1') : QChar('0')) + - (base64Images ? QChar('1') : QChar('0')); - const QString hash = QString( - QCryptographicHash::hash(toHash.toLocal8Bit(), QCryptographicHash::Sha1) - .toHex()); + const QString toHash = + str + QString::number(maxImageWidth) + (forExport ? QChar('1') : QChar('0')) + + (decrypt ? QChar('1') : QChar('0')) + (base64Images ? QChar('1') : QChar('0')); + const QString hash = + QString(QCryptographicHash::hash(toHash.toLocal8Bit(), QCryptographicHash::Sha1).toHex()); // check if the hash changed, if not return the old note text html if (hash == _noteTextHtmlConversionHash) { return _noteTextHtml; } - const QString result = textToMarkdownHtml( - std::move(str), notesPath, maxImageWidth, forExport, base64Images); + const QString result = + textToMarkdownHtml(std::move(str), notesPath, maxImageWidth, forExport, base64Images); // cache the html output and conversion hash _noteTextHtmlConversionHash = std::move(hash); @@ -2341,8 +2243,7 @@ QString Note::toMarkdownHtml(const QString ¬esPath, int maxImageWidth, return _noteTextHtml; } -static void captureHtmlFragment(const MD_CHAR *data, MD_SIZE data_size, - void *userData) { +static void captureHtmlFragment(const MD_CHAR *data, MD_SIZE data_size, void *userData) { QByteArray *array = static_cast<QByteArray *>(userData); if (data_size > 0) { @@ -2366,16 +2267,15 @@ static void highlightCode(QString &str, const QString &type, int cbCount) { } if (currentCbPos >= 4) { - bool fourSpaces = std::all_of(str.cbegin() + (currentCbPos - 4), str.cbegin() + currentCbPos, [](QChar c) { - return c.isSpace(); - }); + bool fourSpaces = + std::all_of(str.cbegin() + (currentCbPos - 4), str.cbegin() + currentCbPos, + [](QChar c) { return c.isSpace(); }); if (fourSpaces) { continue; } } - const QString lang = - str.mid(currentCbPos + 3, endline - (currentCbPos + 3)); + const QString lang = str.mid(currentCbPos + 3, endline - (currentCbPos + 3)); // we skip it because it is inline code and not codeBlock if (lang.contains(type)) { int nextEnd = str.indexOf(type, currentCbPos + 3); @@ -2392,8 +2292,7 @@ static void highlightCode(QString &str, const QString &type, int cbCount) { } // extract the codeBlock #if QT_VERSION < QT_VERSION_CHECK(5, 15, 2) - const QStringRef codeBlock = - str.midRef(currentCbPos, next - currentCbPos); + const QStringRef codeBlock = str.midRef(currentCbPos, next - currentCbPos); #else QStringView str_view = str; QStringView codeBlock = str_view.mid(currentCbPos, next - currentCbPos); @@ -2403,10 +2302,8 @@ static void highlightCode(QString &str, const QString &type, int cbCount) { const CodeToHtmlConverter c(lang); highlightedCodeBlock = c.process(codeBlock); // take care of the null char - highlightedCodeBlock.replace(QChar('\u0000'), - QLatin1String("")); - str.replace(currentCbPos, next - currentCbPos, - highlightedCodeBlock); + highlightedCodeBlock.replace(QChar('\u0000'), QLatin1String("")); + str.replace(currentCbPos, next - currentCbPos, highlightedCodeBlock); // recalculate next because string has now changed next = str.indexOf(type, currentCbPos); } @@ -2434,11 +2331,9 @@ struct ImageSize { QString fileName; int size; }; -static std::vector<ImageSize> *getImageSizeCache() -{ +static std::vector<ImageSize> *getImageSizeCache() { static std::vector<ImageSize> _imageSizesCache; - if (_imageSizesCache.size() > 100) - _imageSizesCache.erase(_imageSizesCache.begin()); + if (_imageSizesCache.size() > 100) _imageSizesCache.erase(_imageSizesCache.begin()); return &_imageSizesCache; } @@ -2452,12 +2347,11 @@ static std::vector<ImageSize> *getImageSizeCache() * @param base64Images * @return */ -QString Note::textToMarkdownHtml(QString str, const QString ¬esPath, - int maxImageWidth, bool forExport, - bool base64Images) { +QString Note::textToMarkdownHtml(QString str, const QString ¬esPath, int maxImageWidth, + bool forExport, bool base64Images) { // MD4C flags - unsigned flags = MD_DIALECT_GITHUB | MD_FLAG_WIKILINKS | - MD_FLAG_LATEXMATHSPANS | MD_FLAG_UNDERLINE; + unsigned flags = + MD_DIALECT_GITHUB | MD_FLAG_WIKILINKS | MD_FLAG_LATEXMATHSPANS | MD_FLAG_UNDERLINE; // we parse the task lists ourselves // we render checkboxes when using qlitehtml @@ -2466,9 +2360,7 @@ QString Note::textToMarkdownHtml(QString str, const QString ¬esPath, #endif const QSettings settings; - if (!settings - .value(QStringLiteral("MainWindow/noteTextView.underline"), true) - .toBool()) { + if (!settings.value(QStringLiteral("MainWindow/noteTextView.underline"), true).toBool()) { flags &= ~MD_FLAG_UNDERLINE; } @@ -2481,18 +2373,18 @@ QString Note::textToMarkdownHtml(QString str, const QString ¬esPath, // remove frontmatter from markdown text if (str.startsWith(QLatin1String("---"))) { - static const QRegularExpression re(QStringLiteral(R"(^---((\r\n)|(\n\r)|\r|\n).+?((\r\n)|(\n\r)|\r|\n)---((\r\n)|(\n\r)|\r|\n))"), - QRegularExpression::DotMatchesEverythingOption); + static const QRegularExpression re( + QStringLiteral( + R"(^---((\r\n)|(\n\r)|\r|\n).+?((\r\n)|(\n\r)|\r|\n)---((\r\n)|(\n\r)|\r|\n))"), + QRegularExpression::DotMatchesEverythingOption); str.remove(re); } // parse for relative file urls and make them absolute // (for example to show images under the note path) static const QRegularExpression re(QStringLiteral(R"(([\(<])file:\/\/([^\/].+?)([\)>]))")); - str.replace(re, - QStringLiteral("\\1file://") + windowsSlash + - QRegularExpression::escape(notesPath) + - QStringLiteral("/\\2\\3")); + str.replace(re, QStringLiteral("\\1file://") + windowsSlash + + QRegularExpression::escape(notesPath) + QStringLiteral("/\\2\\3")); // transform images without "file://" urls to file-urls (but we better do // that in the html, not the markdown!) @@ -2512,7 +2404,8 @@ QString Note::textToMarkdownHtml(QString str, const QString ¬esPath, // comment block? Important: The `\n` is needed to not crash under Windows // if there is just // an opening `<` and a lot of other text after it - static const QRegularExpression linkRE(QStringLiteral("<(((?!\\w+:\\/\\/)[^\\*<>\n])+\\.[\\w\\d]+)>")); + static const QRegularExpression linkRE( + QStringLiteral("<(((?!\\w+:\\/\\/)[^\\*<>\n])+\\.[\\w\\d]+)>")); i = linkRE.globalMatch(str); while (i.hasNext()) { @@ -2520,8 +2413,7 @@ QString Note::textToMarkdownHtml(QString str, const QString ¬esPath, const QString fileLink = match.captured(1); const QString url = Note::getFileURLFromFileName(fileLink, true, true); - str.replace(match.captured(0), QStringLiteral("[") + fileLink + - QStringLiteral("](") + url + + str.replace(match.captured(0), QStringLiteral("[") + fileLink + QStringLiteral("](") + url + QStringLiteral(")")); } @@ -2531,8 +2423,7 @@ QString Note::textToMarkdownHtml(QString str, const QString ¬esPath, // were crashes with regular expressions running wild // TODO: In theory we could convert relative note links in the html (and not // in the markdown) to prevent troubles with code blocks - i = QRegularExpression( - QStringLiteral(R"(\[(.*?)\]\((((?!\w+:\/\/)[^<>]){1,500}?)\))")) + i = QRegularExpression(QStringLiteral(R"(\[(.*?)\]\((((?!\w+:\/\/)[^<>]){1,500}?)\))")) .globalMatch(str); while (i.hasNext()) { @@ -2547,15 +2438,13 @@ QString Note::textToMarkdownHtml(QString str, const QString ¬esPath, const QString url = Note::getFileURLFromFileName(fileLink, true, true); - str.replace(match.captured(0), QStringLiteral("[") + fileText + - QStringLiteral("](") + url + + str.replace(match.captured(0), QStringLiteral("[") + fileText + QStringLiteral("](") + url + QStringLiteral(")")); } // check if there is a script that wants to modify the markdown const QString preScriptResult = - ScriptingService::instance()->callPreNoteToMarkdownHtmlHook(this, str, - forExport); + ScriptingService::instance()->callPreNoteToMarkdownHtmlHook(this, str, forExport); if (!preScriptResult.isEmpty()) { str = std::move(preScriptResult); @@ -2583,8 +2472,7 @@ QString Note::textToMarkdownHtml(QString str, const QString ¬esPath, QByteArray array; const int renderResult = - md_html(data.data(), MD_SIZE(data.size()), &captureHtmlFragment, - &array, flags, 0); + md_html(data.data(), MD_SIZE(data.size()), &captureHtmlFragment, &array, flags, 0); QString result; if (renderResult == 0) { @@ -2595,13 +2483,11 @@ QString Note::textToMarkdownHtml(QString str, const QString ¬esPath, } // transform remote preview image tags - Utils::Misc::transformRemotePreviewImages(result, maxImageWidth, - externalImageHash()); + Utils::Misc::transformRemotePreviewImages(result, maxImageWidth, externalImageHash()); if (OwnCloudService::isOwnCloudSupportEnabled()) { // transform Nextcloud preview image tags - Utils::Misc::transformNextcloudPreviewImages(result, maxImageWidth, - externalImageHash()); + Utils::Misc::transformNextcloudPreviewImages(result, maxImageWidth, externalImageHash()); } // transform images without "file://" urls to file-urls @@ -2627,17 +2513,13 @@ QString Note::textToMarkdownHtml(QString str, const QString ¬esPath, font.fromString(fontString); // add the font for the code block - codeStyleSheet = QStringLiteral("pre, code { %1; }") - .arg(Utils::Schema::encodeCssFont(font)); + codeStyleSheet = + QStringLiteral("pre, code { %1; }").arg(Utils::Schema::encodeCssFont(font)); // ignore code font size to allow zooming (#1202) - if (settings - .value(QStringLiteral( - "MainWindow/noteTextView.ignoreCodeFontSize"), - true) + if (settings.value(QStringLiteral("MainWindow/noteTextView.ignoreCodeFontSize"), true) .toBool()) { - codeStyleSheet.remove( - QRegularExpression(QStringLiteral(R"(font-size: \d+\w+;)"))); + codeStyleSheet.remove(QRegularExpression(QStringLiteral(R"(font-size: \d+\w+;)"))); } } @@ -2660,8 +2542,7 @@ QString Note::textToMarkdownHtml(QString str, const QString ¬esPath, .arg(codeBackgroundColor, codeForegroundColor); // TODO: We should probably make a stylesheet for this - codeStyleSheet += - QStringLiteral(" .code-comment { color: #75715E; font-style: italic;}"); + codeStyleSheet += QStringLiteral(" .code-comment { color: #75715E; font-style: italic;}"); codeStyleSheet += QStringLiteral(" .code-string { color: #E6DB74;}"); codeStyleSheet += QStringLiteral(" .code-literal { color: #AE81FF;}"); codeStyleSheet += QStringLiteral(" .code-type { color: #66D9EF;}"); @@ -2672,11 +2553,9 @@ QString Note::textToMarkdownHtml(QString str, const QString ¬esPath, // correct the strikeout tag result.replace(QRegularExpression(QStringLiteral("<del>([^<]+)<\\/del>")), QStringLiteral("<s>\\1</s>")); - const bool rtl = - settings.value(QStringLiteral("MainWindow/noteTextView.rtl")).toBool(); + const bool rtl = settings.value(QStringLiteral("MainWindow/noteTextView.rtl")).toBool(); const QString rtlStyle = - rtl ? QStringLiteral("body {text-align: right; direction: rtl;}") - : QLatin1String(""); + rtl ? QStringLiteral("body {text-align: right; direction: rtl;}") : QLatin1String(""); if (forExport) { // get defined body font from settings @@ -2688,8 +2567,8 @@ QString Note::textToMarkdownHtml(QString str, const QString ¬esPath, QFont bodyFont; bodyFont.fromString(bodyFontString); - exportStyleSheet = QStringLiteral("body { %1; }") - .arg(Utils::Schema::encodeCssFont(bodyFont)); + exportStyleSheet = + QStringLiteral("body { %1; }").arg(Utils::Schema::encodeCssFont(bodyFont)); } result = QString( @@ -2706,8 +2585,7 @@ QString Note::textToMarkdownHtml(QString str, const QString ¬esPath, "th, td {padding: 2px 5px;}" "a { color: #FF9137; text-decoration: none; } %1 %2 %4" "</style></head><body class=\"export\">%3</body></html>") - .arg(codeStyleSheet, exportStyleSheet, result, rtlStyle, - codeBackgroundColor); + .arg(codeStyleSheet, exportStyleSheet, result, rtlStyle, codeBackgroundColor); // remove trailing newline in code blocks result.replace(QStringLiteral("\n</code>"), QStringLiteral("</code>")); @@ -2717,17 +2595,16 @@ QString Note::textToMarkdownHtml(QString str, const QString ¬esPath, : QLatin1String(""); // for preview - result = - QStringLiteral( - "<html><head><style>" - "h1 { margin: 5px 0 20px 0; }" - "h2, h3 { margin: 10px 0 15px 0; }" - "table {border-spacing: 0; border-style: solid; border-width: " - "1px; border-collapse: collapse; margin-top: 0.5em;}" - "th, td {padding: 2px 5px;}" - "a { color: #FF9137; text-decoration: none; } %1 %3 %4" - "</style></head><body class=\"preview\">%2</body></html>") - .arg(codeStyleSheet, result, rtlStyle, schemaStyles); + result = QStringLiteral( + "<html><head><style>" + "h1 { margin: 5px 0 20px 0; }" + "h2, h3 { margin: 10px 0 15px 0; }" + "table {border-spacing: 0; border-style: solid; border-width: " + "1px; border-collapse: collapse; margin-top: 0.5em;}" + "th, td {padding: 2px 5px;}" + "a { color: #FF9137; text-decoration: none; } %1 %3 %4" + "</style></head><body class=\"preview\">%2</body></html>") + .arg(codeStyleSheet, result, rtlStyle, schemaStyles); // remove trailing newline in code blocks result.replace(QStringLiteral("\n</code>"), QStringLiteral("</code>")); } @@ -2736,11 +2613,10 @@ QString Note::textToMarkdownHtml(QString str, const QString ¬esPath, static const QRegularExpression imgRE(QStringLiteral("<img src=\"(file:\\/\\/[^\"]+)\"")); i = imgRE.globalMatch(result); - auto getImageSizeFromCache = [](const QString& image) { + auto getImageSizeFromCache = [](const QString &image) { auto cache = getImageSizeCache(); - auto it = std::find_if(cache->begin(), cache->end(), [image](const ImageSize& i){ - return i.fileName == image; - }); + auto it = std::find_if(cache->begin(), cache->end(), + [image](const ImageSize &i) { return i.fileName == image; }); return it == cache->end() ? -1 : it->size; }; @@ -2773,27 +2649,23 @@ QString Note::textToMarkdownHtml(QString str, const QString ¬esPath, fileNameWithPercentSpaces.replace(QChar(' '), QStringLiteral("%20")); if (forExport) { - result.replace( - QRegularExpression( - QStringLiteral(R"(<img src="file:\/\/)") + - QRegularExpression::escape(windowsSlash + fileNameWithPercentSpaces) + - QStringLiteral("\"")), - QStringLiteral("<img src=\"file://%2\"") - .arg(windowsSlash + fileName)); + result.replace(QRegularExpression(QStringLiteral(R"(<img src="file:\/\/)") + + QRegularExpression::escape( + windowsSlash + fileNameWithPercentSpaces) + + QStringLiteral("\"")), + QStringLiteral("<img src=\"file://%2\"").arg(windowsSlash + fileName)); } else { // for preview // cap the image width at maxImageWidth (note text view width) const int originalWidth = imageWidth; const int displayWidth = (originalWidth > maxImageWidth) ? maxImageWidth : originalWidth; - const QString filePattern = QStringLiteral(R"(<img src="file://)") + - windowsSlash + fileNameWithPercentSpaces + QChar('"'); + const QString filePattern = QStringLiteral(R"(<img src="file://)") + windowsSlash + + fileNameWithPercentSpaces + QChar('"'); - result.replace( - filePattern, - QStringLiteral(R"(<img width="%1" src="file://%2")") - .arg(QString::number(displayWidth), - windowsSlash + fileName)); + result.replace(filePattern, + QStringLiteral(R"(<img width="%1" src="file://%2")") + .arg(QString::number(displayWidth), windowsSlash + fileName)); } // encode the image base64 @@ -2801,8 +2673,7 @@ QString Note::textToMarkdownHtml(QString str, const QString ¬esPath, QFile file(fileName); if (!file.open(QIODevice::ReadOnly)) { - qWarning() << QObject::tr("Could not read image file: %1") - .arg(fileName); + qWarning() << QObject::tr("Could not read image file: %1").arg(fileName); continue; } @@ -2811,19 +2682,16 @@ QString Note::textToMarkdownHtml(QString str, const QString ¬esPath, const QMimeType type = db.mimeTypeForFile(file.fileName()); const QByteArray ba = file.readAll(); - result.replace( - QRegularExpression(QStringLiteral("<img(.+?)src=\"") + - QRegularExpression::escape(fileUrl) + - QChar('"')), - QStringLiteral(R"(<img\1src="data:%1;base64,%2")") - .arg(type.name(), QString(ba.toBase64()))); + result.replace(QRegularExpression(QStringLiteral("<img(.+?)src=\"") + + QRegularExpression::escape(fileUrl) + QChar('"')), + QStringLiteral(R"(<img\1src="data:%1;base64,%2")") + .arg(type.name(), QString(ba.toBase64()))); } } // check if there is a script that wants to modify the content const QString scriptResult = - ScriptingService::instance()->callNoteToMarkdownHtmlHook(this, result, - forExport); + ScriptingService::instance()->callNoteToMarkdownHtmlHook(this, result, forExport); if (!scriptResult.isEmpty()) { result = scriptResult; @@ -2837,15 +2705,13 @@ QString Note::textToMarkdownHtml(QString str, const QString ¬esPath, * Returns the global external image hash instance */ Utils::Misc::ExternalImageHash *Note::externalImageHash() { - auto *instance = qApp->property("externalImageHash") - .value<Utils::Misc::ExternalImageHash *>(); + auto *instance = qApp->property("externalImageHash").value<Utils::Misc::ExternalImageHash *>(); if (instance == nullptr) { instance = new Utils::Misc::ExternalImageHash; - qApp->setProperty( - "externalImageHash", - QVariant::fromValue<Utils::Misc::ExternalImageHash *>(instance)); + qApp->setProperty("externalImageHash", + QVariant::fromValue<Utils::Misc::ExternalImageHash *>(instance)); } return instance; @@ -2862,7 +2728,8 @@ QString Note::generateTextForLink(QString text) { // replace everything but characters and numbers with "_" // we want to treat unicode characters as normal characters // to support links to notes with unicode characters in their names - static const QRegularExpression re(QStringLiteral("[^\\d\\w]"), + static const QRegularExpression re( + QStringLiteral("[^\\d\\w]"), QRegularExpression::CaseInsensitiveOption | QRegularExpression::UseUnicodePropertiesOption); text.replace(re, QStringLiteral("_")); @@ -2876,8 +2743,7 @@ QString Note::generateTextForLink(QString text) { // add a "@" if the text contains numbers and utf8 characters // because the url will be invalid then static const QRegularExpression re(QStringLiteral("\\d")); - addAtSign = text.contains(re) && - text.toLocal8Bit().size() != text.length(); + addAtSign = text.contains(re) && text.toLocal8Bit().size() != text.length(); } // if the hostname of the url will get to long QUrl will not @@ -2896,8 +2762,7 @@ QString Note::generateTextForLink(QString text) { * Generates a qint64 hash from a QString */ qint64 Note::qint64Hash(const QString &str) { - const QByteArray hash = - QCryptographicHash::hash(str.toUtf8(), QCryptographicHash::Md5); + const QByteArray hash = QCryptographicHash::hash(str.toUtf8(), QCryptographicHash::Md5); Q_ASSERT(hash.size() == 16); QDataStream stream(hash); qint64 a, b; @@ -2924,9 +2789,8 @@ QString Note::encryptNoteText() { _noteText += noteTextLines.at(1) + QStringLiteral("\n"); } - _noteText += QStringLiteral("\n") + - QStringLiteral(NOTE_TEXT_ENCRYPTION_PRE_STRING) + - QStringLiteral("\n"); + _noteText += QStringLiteral("\n") + QStringLiteral(NOTE_TEXT_ENCRYPTION_PRE_STRING) + + QStringLiteral("\n"); // remove the first two lines for encryption noteTextLines.removeFirst(); @@ -2950,8 +2814,8 @@ QString Note::encryptNoteText() { } // check if we have an external encryption method - QString encryptedText = ScriptingService::instance()->callEncryptionHook( - text, _cryptoPassword, false); + QString encryptedText = + ScriptingService::instance()->callEncryptionHook(text, _cryptoPassword, false); // check if a hook changed the text if (encryptedText.isEmpty()) { @@ -2968,8 +2832,8 @@ QString Note::encryptNoteText() { } // add the encrypted text to the new note text - _noteText += encryptedText + QStringLiteral("\n") + - QStringLiteral(NOTE_TEXT_ENCRYPTION_POST_STRING); + _noteText += + encryptedText + QStringLiteral("\n") + QStringLiteral(NOTE_TEXT_ENCRYPTION_POST_STRING); // store note store(); @@ -2992,11 +2856,10 @@ QStringList Note::getNoteTextLines() const { */ QRegularExpression Note::getEncryptedNoteTextRegularExpression() { // match the encrypted string - QRegularExpression re(QRegularExpression::escape( - QStringLiteral(NOTE_TEXT_ENCRYPTION_PRE_STRING)) + - QStringLiteral("\\s+(.+)\\s+") + - QRegularExpression::escape(QStringLiteral( - NOTE_TEXT_ENCRYPTION_POST_STRING))); + QRegularExpression re( + QRegularExpression::escape(QStringLiteral(NOTE_TEXT_ENCRYPTION_PRE_STRING)) + + QStringLiteral("\\s+(.+)\\s+") + + QRegularExpression::escape(QStringLiteral(NOTE_TEXT_ENCRYPTION_POST_STRING))); re.setPatternOptions(QRegularExpression::MultilineOption | QRegularExpression::DotMatchesEverythingOption); @@ -3021,9 +2884,7 @@ QString Note::getEncryptedNoteText() const { /** * Returns encrypted note text if it is encrypted */ -bool Note::hasEncryptedNoteText() const { - return !getEncryptedNoteText().isEmpty(); -} +bool Note::hasEncryptedNoteText() const { return !getEncryptedNoteText().isEmpty(); } /** * Checks if note text can be decrypted @@ -3037,8 +2898,7 @@ bool Note::canDecryptNoteText() const { // check if we have an external decryption method QString decryptedNoteText = - ScriptingService::instance()->callEncryptionHook(encryptedNoteText, - _cryptoPassword, true); + ScriptingService::instance()->callEncryptionHook(encryptedNoteText, _cryptoPassword, true); // check if a hook changed the text if (decryptedNoteText.isEmpty()) { @@ -3070,9 +2930,7 @@ void Note::setCryptoPassword(const QString &password) { /** * Returns the decrypted note text */ -QString Note::getDecryptedNoteText() const { - return _decryptedNoteText; -} +QString Note::getDecryptedNoteText() const { return _decryptedNoteText; } /** * Fetches the decrypted note text if it is encrypted @@ -3096,8 +2954,7 @@ QString Note::fetchDecryptedNoteText() const { // check if we have an external decryption method QString decryptedNoteText = - ScriptingService::instance()->callEncryptionHook(encryptedNoteText, - _cryptoPassword, true); + ScriptingService::instance()->callEncryptionHook(encryptedNoteText, _cryptoPassword, true); // check if a hook changed the text if (decryptedNoteText.isEmpty()) { @@ -3139,9 +2996,9 @@ bool Note::expireCryptoKeys() { expiryDate = expiryDate.addSecs(-600); // reset expired crypto keys - query.prepare(QStringLiteral( - "UPDATE note SET crypto_key = 0, crypto_password = '' WHERE " - "modified < :expiryDate AND crypto_key != 0")); + query.prepare( + QStringLiteral("UPDATE note SET crypto_key = 0, crypto_password = '' WHERE " + "modified < :expiryDate AND crypto_key != 0")); query.bindValue(QStringLiteral(":expiryDate"), expiryDate); // on error @@ -3180,8 +3037,7 @@ int Note::countByNoteSubFolderId(int noteSubFolderId, bool recursive) { QVector<int> noteSubFolderIdList; if (recursive) { - noteSubFolderIdList = - NoteSubFolder::fetchIdsRecursivelyByParentId(noteSubFolderId); + noteSubFolderIdList = NoteSubFolder::fetchIdsRecursivelyByParentId(noteSubFolderId); } else { noteSubFolderIdList << noteSubFolderId; } @@ -3192,11 +3048,9 @@ int Note::countByNoteSubFolderId(int noteSubFolderId, bool recursive) { idStringList << QString::number(id); } - query.prepare( - QStringLiteral( - "SELECT COUNT(*) AS cnt FROM note WHERE note_sub_folder_id " - "IN (") + - idStringList.join(QChar(',')) + QChar(')')); + query.prepare(QStringLiteral("SELECT COUNT(*) AS cnt FROM note WHERE note_sub_folder_id " + "IN (") + + idStringList.join(QChar(',')) + QChar(')')); if (!query.exec()) { qWarning() << __func__ << ": " << query.lastError(); @@ -3214,8 +3068,7 @@ int Note::countByNoteSubFolderId(int noteSubFolderId, bool recursive) { * @return */ bool Note::isSameFile(const Note ¬e) const { - return (_id == note.getId()) && - (_noteSubFolderId == note.getNoteSubFolderId()); + return (_id == note.getId()) && (_noteSubFolderId == note.getNoteSubFolderId()); } /** @@ -3231,17 +3084,13 @@ QVector<int> Note::findLinkedNoteIds() const { // search for legacy links const QString linkText = getNoteURL(_name); noteIdList << searchInNotes(QChar('<') + linkText + QChar('>'), true); - noteIdList << searchInNotes( - QStringLiteral("](") + linkText + QStringLiteral(")"), true); + noteIdList << searchInNotes(QStringLiteral("](") + linkText + QStringLiteral(")"), true); // search vor legacy links ending with "@" - const QString altLinkText = - Utils::Misc::appendIfDoesNotEndWith(linkText, QStringLiteral("@")); + const QString altLinkText = Utils::Misc::appendIfDoesNotEndWith(linkText, QStringLiteral("@")); if (altLinkText != linkText) { - noteIdList << searchInNotes(QChar('<') + altLinkText + QChar('>'), - true); - noteIdList << searchInNotes( - QStringLiteral("](") + altLinkText + QChar(')'), true); + noteIdList << searchInNotes(QChar('<') + altLinkText + QChar('>'), true); + noteIdList << searchInNotes(QStringLiteral("](") + altLinkText + QChar(')'), true); } const auto noteList = Note::fetchAll(); @@ -3262,12 +3111,9 @@ QVector<int> Note::findLinkedNoteIds() const { // search for links to the relative file path in note // the "#" is for notes with a fragment (link to heading in note) - if (noteText.contains(QStringLiteral("<") + relativeFilePath + - QStringLiteral(">")) || - noteText.contains(QStringLiteral("](") + relativeFilePath + - QStringLiteral(")")) || - noteText.contains(QStringLiteral("](") + relativeFilePath + - QStringLiteral("#"))) { + if (noteText.contains(QStringLiteral("<") + relativeFilePath + QStringLiteral(">")) || + noteText.contains(QStringLiteral("](") + relativeFilePath + QStringLiteral(")")) || + noteText.contains(QStringLiteral("](") + relativeFilePath + QStringLiteral("#"))) { noteIdList.append(note.getId()); } } @@ -3276,8 +3122,7 @@ QVector<int> Note::findLinkedNoteIds() const { // return noteIdList.toSet().toList(); // QSet<int>(noteIdList.constBegin(), noteIdList.constEnd()); std::sort(noteIdList.begin(), noteIdList.end()); - noteIdList.erase(std::unique(noteIdList.begin(), noteIdList.end()), - noteIdList.end()); + noteIdList.erase(std::unique(noteIdList.begin(), noteIdList.end()), noteIdList.end()); return noteIdList; } @@ -3319,8 +3164,7 @@ const QString Note::getNoteURLFromFileName(const QString &fileName) { * @param fileName * @return */ -QString Note::getFileURLFromFileName(QString fileName, - bool urlDecodeFileName, +QString Note::getFileURLFromFileName(QString fileName, bool urlDecodeFileName, bool withFragment) const { // Remove the url fragment from the filename const auto splitList = fileName.split(QChar('#')); @@ -3334,8 +3178,7 @@ QString Note::getFileURLFromFileName(QString fileName, if (_noteSubFolderId > 0) { const NoteSubFolder noteSubFolder = getNoteSubFolder(); if (noteSubFolder.isFetched()) { - fileName.prepend(noteSubFolder.relativePath() + - QStringLiteral("/")); + fileName.prepend(noteSubFolder.relativePath() + QStringLiteral("/")); } } @@ -3349,7 +3192,7 @@ QString Note::getFileURLFromFileName(QString fileName, return url; } -QString Note::getURLFragmentFromFileName(const QString& fileName) { +QString Note::getURLFragmentFromFileName(const QString &fileName) { const auto splitList = fileName.split(QChar('#')); const QString fragment = splitList.count() > 1 ? splitList.at(1) : ""; @@ -3423,8 +3266,8 @@ QString Note::fileUrlInCurrentNoteFolderToRelativePath(const QUrl &url) { qDebug() << __func__ << " - 'canonicalFilePath': " << path; - return path.remove(Utils::Misc::appendIfDoesNotEndWith( - NoteFolder::currentLocalPath(), QStringLiteral("/"))); + return path.remove( + Utils::Misc::appendIfDoesNotEndWith(NoteFolder::currentLocalPath(), QStringLiteral("/"))); } /** @@ -3489,51 +3332,36 @@ bool Note::handleNoteMoving(const Note &oldNote) { // replace legacy links with note:// and ending @ // if (!oldUrl.contains(QLatin1String("@"))) { - text.replace( - QStringLiteral("<") + oldUrl + QStringLiteral("@>"), - QStringLiteral("<") + newUrl + QStringLiteral(">")); - text.replace( - QStringLiteral("](") + oldUrl + QStringLiteral("@)"), - QStringLiteral("](") + newUrl + QStringLiteral(")")); + text.replace(QStringLiteral("<") + oldUrl + QStringLiteral("@>"), + QStringLiteral("<") + newUrl + QStringLiteral(">")); + text.replace(QStringLiteral("](") + oldUrl + QStringLiteral("@)"), + QStringLiteral("](") + newUrl + QStringLiteral(")")); } - QString oldNoteRelativeFilePath = - note.getFilePathRelativeToNote(oldNote); + QString oldNoteRelativeFilePath = note.getFilePathRelativeToNote(oldNote); const QString relativeFilePath = urlEncodeNoteUrl(note.getFilePathRelativeToNote(*this)); // // replace non-urlencoded relative file links to the note // - text.replace( - QStringLiteral("<") + oldNoteRelativeFilePath + - QStringLiteral(">"), - QStringLiteral("<") + relativeFilePath + QStringLiteral(">")); - text.replace( - QStringLiteral("](") + oldNoteRelativeFilePath + - QStringLiteral(")"), - QStringLiteral("](") + relativeFilePath + QStringLiteral(")")); - text.replace( - QStringLiteral("](") + oldNoteRelativeFilePath + - QStringLiteral("#"), - QStringLiteral("](") + relativeFilePath + QStringLiteral("#")); + text.replace(QStringLiteral("<") + oldNoteRelativeFilePath + QStringLiteral(">"), + QStringLiteral("<") + relativeFilePath + QStringLiteral(">")); + text.replace(QStringLiteral("](") + oldNoteRelativeFilePath + QStringLiteral(")"), + QStringLiteral("](") + relativeFilePath + QStringLiteral(")")); + text.replace(QStringLiteral("](") + oldNoteRelativeFilePath + QStringLiteral("#"), + QStringLiteral("](") + relativeFilePath + QStringLiteral("#")); // // replace url encoded relative file links to the note // oldNoteRelativeFilePath = urlEncodeNoteUrl(oldNoteRelativeFilePath); - text.replace( - QStringLiteral("<") + oldNoteRelativeFilePath + - QStringLiteral(">"), - QStringLiteral("<") + relativeFilePath + QStringLiteral(">")); - text.replace( - QStringLiteral("](") + oldNoteRelativeFilePath + - QStringLiteral(")"), - QStringLiteral("](") + relativeFilePath + QStringLiteral(")")); - text.replace( - QStringLiteral("](") + oldNoteRelativeFilePath + - QStringLiteral("#"), - QStringLiteral("](") + relativeFilePath + QStringLiteral("#")); + text.replace(QStringLiteral("<") + oldNoteRelativeFilePath + QStringLiteral(">"), + QStringLiteral("<") + relativeFilePath + QStringLiteral(">")); + text.replace(QStringLiteral("](") + oldNoteRelativeFilePath + QStringLiteral(")"), + QStringLiteral("](") + relativeFilePath + QStringLiteral(")")); + text.replace(QStringLiteral("](") + oldNoteRelativeFilePath + QStringLiteral("#"), + QStringLiteral("](") + relativeFilePath + QStringLiteral("#")); // if the current note was changed we need to make sure the // _noteText is updated @@ -3567,8 +3395,8 @@ QString Note::createNoteHeader(const QString &name) { /** * Returns the markdown of the inserted media file into a note */ -QString Note::getInsertMediaMarkdown(QFile *file, bool addNewLine, - bool returnUrlOnly, QString title) const { +QString Note::getInsertMediaMarkdown(QFile *file, bool addNewLine, bool returnUrlOnly, + QString title) const { // file->exists() is false on Arch Linux for QTemporaryFile! if (file->size() == 0) { return QLatin1String(""); @@ -3600,28 +3428,25 @@ QString Note::getInsertMediaMarkdown(QFile *file, bool addNewLine, // file->fileName() wields a path! auto fileHash = Utils::Misc::generateFileSha1Signature(file->fileName()); auto newFileHash = Utils::Misc::generateFileSha1Signature( - mediaDir.path() + QDir::separator() + - Utils::Misc::fileNameForPath(file->fileName())); + mediaDir.path() + QDir::separator() + Utils::Misc::fileNameForPath(file->fileName())); // check if files are binary identical and ask if we want to use the existing file - if (fileHash == newFileHash && Utils::Gui::question(nullptr, - QObject::tr("Image file exists"), - QObject::tr("Image file already exists in the media folder, " - "do you want to use the existing one instead of creating a new file?"), - QStringLiteral("insert-media-use-existing-image")) == - QMessageBox::Yes) { + if (fileHash == newFileHash && + Utils::Gui::question( + nullptr, QObject::tr("Image file exists"), + QObject::tr("Image file already exists in the media folder, " + "do you want to use the existing one instead of creating a new file?"), + QStringLiteral("insert-media-use-existing-image")) == QMessageBox::Yes) { useExistingFile = true; } } // find a name for the new file - const QString newFileName = useExistingFile ? - Utils::Misc::fileNameForPath(file->fileName()) : - Utils::Misc::findAvailableFileName(file->fileName(), - mediaDir.path(), suffix); + const QString newFileName = useExistingFile ? Utils::Misc::fileNameForPath(file->fileName()) + : Utils::Misc::findAvailableFileName( + file->fileName(), mediaDir.path(), suffix); - const QString newFilePath = - mediaDir.path() + QDir::separator() + newFileName; + const QString newFilePath = mediaDir.path() + QDir::separator() + newFileName; if (!useExistingFile) { // copy the file to the media folder @@ -3644,9 +3469,8 @@ QString Note::getInsertMediaMarkdown(QFile *file, bool addNewLine, // return the image link // we add a "\n" in the end so that hoedown recognizes multiple images - return QStringLiteral("![") + title + QStringLiteral("](") + - mediaUrlString + QStringLiteral(")") + - (addNewLine ? QStringLiteral("\n") : QLatin1String("")); + return QStringLiteral("![") + title + QStringLiteral("](") + mediaUrlString + + QStringLiteral(")") + (addNewLine ? QStringLiteral("\n") : QLatin1String("")); } QString Note::mediaUrlStringForFileName(const QString &fileName) const { @@ -3690,8 +3514,7 @@ QString Note::attachmentUrlStringForFileName(const QString &fileName) const { /** * Returns the markdown of the inserted attachment file into a note */ -QString Note::getInsertAttachmentMarkdown(QFile *file, QString title, - bool returnUrlOnly, +QString Note::getInsertAttachmentMarkdown(QFile *file, QString title, bool returnUrlOnly, QString fileBaseName) const { // file->exists() was false for QTemporaryFile, so we are using file->size() only if (file->size() > 0) { @@ -3713,14 +3536,12 @@ QString Note::getInsertAttachmentMarkdown(QFile *file, QString title, const QString newFileName = Utils::Misc::findAvailableFileName(fileBaseName, dir.path(), suffix); - const QString newFilePath = - dir.path() + QDir::separator() + newFileName; + const QString newFilePath = dir.path() + QDir::separator() + newFileName; // copy the file to the attachments folder file->copy(newFilePath); - const QString attachmentUrlString = - attachmentUrlStringForFileName(newFileName); + const QString attachmentUrlString = attachmentUrlStringForFileName(newFileName); // check if we only want to return the attachment url string if (returnUrlOnly) { @@ -3732,8 +3553,8 @@ QString Note::getInsertAttachmentMarkdown(QFile *file, QString title, } // return the attachment link - return QStringLiteral("[") + title + QStringLiteral("](") + - attachmentUrlString + QStringLiteral(")"); + return QStringLiteral("[") + title + QStringLiteral("](") + attachmentUrlString + + QStringLiteral(")"); } return QLatin1String(""); @@ -3767,9 +3588,8 @@ QString Note::downloadUrlToMedia(const QUrl &url, bool returnUrlOnly) { suffix.remove(re).remove(re1); QString text; - QTemporaryFile *tempFile = - new QTemporaryFile(QDir::tempPath() + QDir::separator() + - QStringLiteral("media-XXXXXX.") + suffix); + QTemporaryFile *tempFile = new QTemporaryFile(QDir::tempPath() + QDir::separator() + + QStringLiteral("media-XXXXXX.") + suffix); if (tempFile->open()) { // download the image to the temporary file @@ -3799,9 +3619,8 @@ QString Note::importMediaFromBase64(QString &data, const QString &imageSuffix) { } // create a temporary file for the image - auto *tempFile = - new QTemporaryFile(QDir::tempPath() + QDir::separator() + - QStringLiteral("media-XXXXXX.") + imageSuffix); + auto *tempFile = new QTemporaryFile(QDir::tempPath() + QDir::separator() + + QStringLiteral("media-XXXXXX.") + imageSuffix); if (!tempFile->open()) { delete tempFile; @@ -3825,8 +3644,7 @@ QString Note::importMediaFromBase64(QString &data, const QString &imageSuffix) { * markdown image tag */ QString Note::importMediaFromDataUrl(const QString &dataUrl) { - if (dataUrl.contains(QLatin1String("data:image/"), - Qt::CaseInsensitive)) { + if (dataUrl.contains(QLatin1String("data:image/"), Qt::CaseInsensitive)) { QStringList parts = dataUrl.split(QLatin1String("data:image/")); if (parts.count() != 2) { @@ -3835,8 +3653,7 @@ QString Note::importMediaFromDataUrl(const QString &dataUrl) { parts = parts[1].split(QStringLiteral(";base64,")); if (parts.count() == 2) { - QString fileExtension = Utils::Misc::fileExtensionForMimeType( - parts[0].mid(5)); + QString fileExtension = Utils::Misc::fileExtensionForMimeType(parts[0].mid(5)); return importMediaFromBase64(parts[1], fileExtension); } } @@ -3855,8 +3672,7 @@ bool Note::scaleDownImageFileIfNeeded(QFile &file) { const QSettings settings; // load image scaling settings - const bool scaleImageDown = - settings.value(QStringLiteral("imageScaleDown"), false).toBool(); + const bool scaleImageDown = settings.value(QStringLiteral("imageScaleDown"), false).toBool(); if (!scaleImageDown) { return true; @@ -3876,21 +3692,16 @@ bool Note::scaleDownImageFileIfNeeded(QFile &file) { return false; } - const int width = - settings.value(QStringLiteral("imageScaleDownMaximumWidth"), 1024) - .toInt(); - const int height = - settings.value(QStringLiteral("imageScaleDownMaximumHeight"), 1024) - .toInt(); + const int width = settings.value(QStringLiteral("imageScaleDownMaximumWidth"), 1024).toInt(); + const int height = settings.value(QStringLiteral("imageScaleDownMaximumHeight"), 1024).toInt(); // don't scale if image is already small enough if (image.width() <= width && image.height() <= height) { return true; } - - const QPixmap &pixmap = QPixmap::fromImage(image.scaled( - width, height, Qt::KeepAspectRatio, Qt::SmoothTransformation)); + const QPixmap &pixmap = QPixmap::fromImage( + image.scaled(width, height, Qt::KeepAspectRatio, Qt::SmoothTransformation)); file.open(QIODevice::WriteOnly); pixmap.save(&file); @@ -3911,8 +3722,7 @@ Note Note::fetchByUrlString(const QString &urlString) { // if the name of the linked note only consists of numbers we cannot use // host() to get the filename, it would get converted to an ip-address const QRegularExpressionMatch match = - QRegularExpression(QStringLiteral(R"(^\w+:\/\/(\d+)$)")) - .match(urlString); + QRegularExpression(QStringLiteral(R"(^\w+:\/\/(\d+)$)")).match(urlString); QString fileName = match.hasMatch() ? match.captured(1) : url.host(); // we are using the user name as fallback if the hostname was too long @@ -3929,8 +3739,8 @@ Note Note::fetchByUrlString(const QString &urlString) { // convert the ACE to IDN (internationalized domain names) to support // links to notes with unicode characters in their names // then remove the ".com" again - fileName = Utils::Misc::removeIfEndsWith( - QUrl::fromAce(fileName.toLatin1()), QStringLiteral(".com")); + fileName = Utils::Misc::removeIfEndsWith(QUrl::fromAce(fileName.toLatin1()), + QStringLiteral(".com")); // if it seem we have unicode characters in our filename let us use // wildcards for each number, because full width numbers get somehow @@ -3957,9 +3767,9 @@ Note Note::fetchByUrlString(const QString &urlString) { // create a regular expression to search in sqlite note table QString escapedFileName = QRegularExpression::escape(fileName); escapedFileName.replace(QStringLiteral("\\?"), QStringLiteral(".")); - const QRegularExpression regExp = QRegularExpression( - QLatin1Char('^') + escapedFileName + QLatin1Char('$'), - QRegularExpression::CaseInsensitiveOption); + const QRegularExpression regExp = + QRegularExpression(QLatin1Char('^') + escapedFileName + QLatin1Char('$'), + QRegularExpression::CaseInsensitiveOption); qDebug() << __func__ << " - 'regExp': " << regExp; @@ -4045,8 +3855,7 @@ QString Note::getNotePreviewText(bool asHtml, int lines) const { */ QString Note::generateMultipleNotesPreviewText(const QVector<Note> ¬es) { const QSettings settings; - const bool darkModeColors = - settings.value(QStringLiteral("darkModeColors")).toBool(); + const bool darkModeColors = settings.value(QStringLiteral("darkModeColors")).toBool(); const QString oddBackgroundColor = darkModeColors ? QStringLiteral("#444444") : QStringLiteral("#f1f1f1"); const QString linkColor = @@ -4077,8 +3886,7 @@ QString Note::generateMultipleNotesPreviewText(const QVector<Note> ¬es) { bool isOdd = false; for (int i = 0; i < displayedNotesCount; i++) { const Note ¬e = notes.at(i); - const QString oddStyle = - isOdd ? QStringLiteral(" class='odd'") : QLatin1String(""); + const QString oddStyle = isOdd ? QStringLiteral(" class='odd'") : QLatin1String(""); const QDateTime modified = note.getFileLastModified(); const QString noteText = note.getNotePreviewText(true, 5); const QString noteLink = note.getNoteIdURL(); @@ -4104,8 +3912,7 @@ QString Note::generateMultipleNotesPreviewText(const QVector<Note> ¬es) { if (displayedNotesCount < notesCount) { previewHtml += QStringLiteral("<tr><td>") + - QObject::tr("…and %n more note(s)", "", - notesCount - displayedNotesCount) + + QObject::tr("…and %n more note(s)", "", notesCount - displayedNotesCount) + QStringLiteral("</td></tr>"); } @@ -4132,8 +3939,7 @@ QString Note::getParsedBookmarksWebServiceJsonText() const { * @return */ QVector<Bookmark> Note::getParsedBookmarks() const { - const QString text = - _decryptedNoteText.isEmpty() ? _noteText : _decryptedNoteText; + const QString text = _decryptedNoteText.isEmpty() ? _noteText : _decryptedNoteText; return Bookmark::parseBookmarks(text); } @@ -4143,14 +3949,11 @@ QVector<Bookmark> Note::getParsedBookmarks() const { * @return */ QVector<CommandSnippet> Note::getParsedCommandSnippets() const { - const QString text = - _decryptedNoteText.isEmpty() ? _noteText : _decryptedNoteText; + const QString text = _decryptedNoteText.isEmpty() ? _noteText : _decryptedNoteText; return CommandSnippet::parseCommandSnippets(text); } -void Note::resetNoteTextHtmlConversionHash() { - _noteTextHtmlConversionHash = QLatin1String(""); -} +void Note::resetNoteTextHtmlConversionHash() { _noteTextHtmlConversionHash = QLatin1String(""); } /** * Get a list of all headings in a note starting with ## @@ -4172,11 +3975,10 @@ QStringList Note::getHeadingList() { return headingList; } -bool Note::applyIgnoredNotesSetting(QStringList& fileNames) { +bool Note::applyIgnoredNotesSetting(QStringList &fileNames) { const QSettings settings; const QStringList ignoredFileRegExpList = - settings.value(QStringLiteral("ignoredNoteFiles")).toString() - .split(QLatin1Char(';')); + settings.value(QStringLiteral("ignoredNoteFiles")).toString().split(QLatin1Char(';')); if (ignoredFileRegExpList.isEmpty()) { return false; @@ -4185,8 +3987,7 @@ bool Note::applyIgnoredNotesSetting(QStringList& fileNames) { auto newFileNames = QStringList(); for (const QString &fileName : fileNames) { - if (!Utils::Misc::regExpInListMatches(fileName, - ignoredFileRegExpList)) { + if (!Utils::Misc::regExpInListMatches(fileName, ignoredFileRegExpList)) { newFileNames.append(fileName); } } @@ -4204,12 +4005,10 @@ bool Note::applyIgnoredNotesSetting(QStringList& fileNames) { //} QDebug operator<<(QDebug dbg, const Note ¬e) { - const NoteSubFolder noteSubFolder = - NoteSubFolder::fetch(note._noteSubFolderId); - dbg.nospace() << "Note: <id>" << note._id << " <name>" << note._name - << " <fileName>" << note._fileName << " <noteSubFolderId>" - << note._noteSubFolderId << " <relativePath>" - << noteSubFolder.relativePath() << " <hasDirtyData>" + const NoteSubFolder noteSubFolder = NoteSubFolder::fetch(note._noteSubFolderId); + dbg.nospace() << "Note: <id>" << note._id << " <name>" << note._name << " <fileName>" + << note._fileName << " <noteSubFolderId>" << note._noteSubFolderId + << " <relativePath>" << noteSubFolder.relativePath() << " <hasDirtyData>" << note._hasDirtyData; return dbg.space(); } diff --git a/src/entities/note.h b/src/entities/note.h index f45bd32b0..544339956 100644 --- a/src/entities/note.h +++ b/src/entities/note.h @@ -43,25 +43,20 @@ class Note { void setCryptoKey(const qint64 cryptoKey); - static bool addNote(const QString &name, const QString &fileName, - const QString &text); + static bool addNote(const QString &name, const QString &fileName, const QString &text); static Note fetch(int id); - static Note fetchByName(const QRegularExpression ®Exp, - int noteSubFolderId = -1); + static Note fetchByName(const QRegularExpression ®Exp, int noteSubFolderId = -1); - static Note fetchByFileName(const QString &fileName, - int noteSubFolderId = -1); + static Note fetchByFileName(const QString &fileName, int noteSubFolderId = -1); - static Note fetchByFileName(const QString &fileName, - const QString ¬eSubFolderPathData); + static Note fetchByFileName(const QString &fileName, const QString ¬eSubFolderPathData); static Note fetchByName(const QString &name, int noteSubFolderId = -1); - static Note fetchByName(const QString &name, - const QString ¬eSubFolderPathData, - const QString& pathDataSeparator = QStringLiteral("\n")); + static Note fetchByName(const QString &name, const QString ¬eSubFolderPathData, + const QString &pathDataSeparator = QStringLiteral("\n")); static int fetchNoteIdByName(const QString &name, int noteSubFolderId = -1); @@ -73,11 +68,10 @@ class Note { static QVector<Note> search(const QString &text); - static QVector<QString> searchAsNameListInCurrentNoteSubFolder( - const QString &text, bool searchInNameOnly = false); + static QVector<QString> searchAsNameListInCurrentNoteSubFolder(const QString &text, + bool searchInNameOnly = false); - static QVector<QString> searchAsNameList(const QString &text, - bool searchInNameOnly = false); + static QVector<QString> searchAsNameList(const QString &text, bool searchInNameOnly = false); static QStringList fetchNoteNamesInCurrentNoteSubFolder(); @@ -96,15 +90,13 @@ class Note { static QString defaultNoteFileExtension(); - static QStringList noteFileExtensionList( - const QString &prefix = QString()); + static QStringList noteFileExtensionList(const QString &prefix = QString()); static QString getFullFilePathForFile(const QString &fileName); QString getFilePathRelativeToNote(const Note ¬e) const; - static int storeDirtyNotesToDisk(Note ¤tNote, - bool *currentNoteChanged = nullptr, + static int storeDirtyNotesToDisk(Note ¤tNote, bool *currentNoteChanged = nullptr, bool *noteWasRenamed = nullptr, bool *currentNoteTextChanged = nullptr); @@ -114,8 +106,7 @@ class Note { bool operator==(const Note ¬e) const; - void createFromFile(QFile &file, int noteSubFolderId = 0, - bool withNoteNameHook = false); + void createFromFile(QFile &file, int noteSubFolderId = 0, bool withNoteNameHook = false); static bool deleteAll(); @@ -138,18 +129,15 @@ class Note { bool remove(bool withFile = false); QString toMarkdownHtml(const QString ¬esPath, int maxImageWidth = 980, - bool forExport = false, bool decrypt = true, - bool base64Images = false); + bool forExport = false, bool decrypt = true, bool base64Images = false); bool isFetched() const; - bool copyToPath(const QString &destinationPath, - QString noteFolderPath = QString()); + bool copyToPath(const QString &destinationPath, QString noteFolderPath = QString()); bool exportToPath(const QString &destinationPath, bool withAttachedFiles = false); - bool moveToPath(const QString &destinationPath, - const QString ¬eFolderPath = QString()); + bool moveToPath(const QString &destinationPath, const QString ¬eFolderPath = QString()); static QString generateTextForLink(QString text); @@ -199,15 +187,14 @@ class Note { bool modifyNoteTextFileNameFromQMLHook(); - static QVector<int> searchInNotes(QString query, - bool ignoreNoteSubFolder = false, + static QVector<int> searchInNotes(QString query, bool ignoreNoteSubFolder = false, int noteSubFolderId = -1); int countSearchTextInNote(const QString &search) const; - static QStringList buildQueryStringList( - QString searchString, bool escapeForRegularExpression = false, - bool removeSearchPrefix = false); + static QStringList buildQueryStringList(QString searchString, + bool escapeForRegularExpression = false, + bool removeSearchPrefix = false); QString fileBaseName(bool withFullName = false); @@ -223,8 +210,7 @@ class Note { static QVector<int> noteIdListFromNoteList(const QVector<Note> ¬eList); - static int countByNoteSubFolderId(int noteSubFolderId = 0, - bool recursive = false); + static int countByNoteSubFolderId(int noteSubFolderId = 0, bool recursive = false); int getNoteSubFolderId() const; @@ -258,8 +244,7 @@ class Note { int getFileSize() const; - static Note updateOrCreateFromFile(QFile &file, - const NoteSubFolder ¬eSubFolder, + static Note updateOrCreateFromFile(QFile &file, const NoteSubFolder ¬eSubFolder, bool withNoteNameHook = false); static QVector<int> fetchAllIds(int limit = -1, int offset = -1); @@ -270,12 +255,10 @@ class Note { static QString createNoteHeader(const QString &name); - QString getInsertMediaMarkdown(QFile *file, bool addNewLine = true, - bool returnUrlOnly = false, + QString getInsertMediaMarkdown(QFile *file, bool addNewLine = true, bool returnUrlOnly = false, QString title = QString()) const; - QString getInsertAttachmentMarkdown(QFile *file, - QString title = QString(), + QString getInsertAttachmentMarkdown(QFile *file, QString title = QString(), bool returnUrlOnly = false, QString fileBaseName = QString()) const; @@ -283,8 +266,8 @@ class Note { QString downloadUrlToMedia(const QUrl &url, bool returnUrlOnly = false); - QString importMediaFromBase64( - QString &data, const QString &imageSuffix = QStringLiteral("dat")); + QString importMediaFromBase64(QString &data, + const QString &imageSuffix = QStringLiteral("dat")); QString importMediaFromDataUrl(const QString &dataUrl); @@ -294,9 +277,8 @@ class Note { void generateFileNameFromName(); - QString textToMarkdownHtml(QString str, const QString ¬esPath, - int maxImageWidth = 980, bool forExport = false, - bool base64Images = false); + QString textToMarkdownHtml(QString str, const QString ¬esPath, int maxImageWidth = 980, + bool forExport = false, bool base64Images = false); QStringList getMediaFileList(); @@ -330,11 +312,10 @@ class Note { void resetNoteTextHtmlConversionHash(); - QString getFileURLFromFileName(QString fileName, - bool urlDecodeFileName = false, + QString getFileURLFromFileName(QString fileName, bool urlDecodeFileName = false, bool withFragment = false) const; - static QString getURLFragmentFromFileName(const QString& fileName); + static QString getURLFragmentFromFileName(const QString &fileName); static bool fileUrlIsNoteInCurrentNoteFolder(const QUrl &url); @@ -348,8 +329,7 @@ class Note { static Note fetchByRelativeFilePath(const QString &relativePath); - QString getNoteUrlForLinkingTo(const Note ¬e, - bool forceLegacy = false) const; + QString getNoteUrlForLinkingTo(const Note ¬e, bool forceLegacy = false) const; QString mediaUrlStringForFileName(const QString &fileName) const; @@ -379,7 +359,7 @@ class Note { QStringList getHeadingList(); - static bool applyIgnoredNotesSetting(QStringList& fileNames); + static bool applyIgnoredNotesSetting(QStringList &fileNames); protected: int _id; @@ -402,7 +382,7 @@ class Note { unsigned int _sharePermissions; bool _hasDirtyData; - static QRegularExpression getEncryptedNoteTextRegularExpression() ; + static QRegularExpression getEncryptedNoteTextRegularExpression(); QString getEncryptedNoteText() const; static const QString getNoteURL(const QString &baseName); diff --git a/src/entities/notefolder.cpp b/src/entities/notefolder.cpp index 81d4cdf21..4532be064 100644 --- a/src/entities/notefolder.cpp +++ b/src/entities/notefolder.cpp @@ -17,9 +17,7 @@ #include "notesubfolder.h" NoteFolder::NoteFolder() - : name(QLatin1String("")), - localPath(QLatin1String("")), - remotePath(QLatin1String("")) { + : name(QLatin1String("")), localPath(QLatin1String("")), remotePath(QLatin1String("")) { id = 0; cloudConnectionId = 1; priority = 0; @@ -70,12 +68,10 @@ void NoteFolder::setActiveNoteSubFolder(const NoteSubFolder ¬eSubFolder) { this->activeNoteSubFolderData = noteSubFolder.pathData(); } -void NoteFolder::resetActiveNoteSubFolder() { - this->activeNoteSubFolderData.clear(); -} +void NoteFolder::resetActiveNoteSubFolder() { this->activeNoteSubFolderData.clear(); } -bool NoteFolder::create(const QString &name, const QString &localPath, - int cloudConnectionId, const QString &remotePath) { +bool NoteFolder::create(const QString &name, const QString &localPath, int cloudConnectionId, + const QString &remotePath) { const QSqlDatabase db = QSqlDatabase::database(QStringLiteral("disk")); QSqlQuery query(db); @@ -142,12 +138,9 @@ bool NoteFolder::remove() { } else { // remove the settings of the note folder QSettings settings; - settings.remove(QStringLiteral("NoteHistory-") + - QString::number(this->id)); - settings.remove(QStringLiteral("NoteHistoryCurrentIndex-") + - QString::number(this->id)); - settings.remove(QStringLiteral("NoteFolder-") + - QString::number(this->id)); + settings.remove(QStringLiteral("NoteHistory-") + QString::number(this->id)); + settings.remove(QStringLiteral("NoteHistoryCurrentIndex-") + QString::number(this->id)); + settings.remove(QStringLiteral("NoteFolder-") + QString::number(this->id)); return true; } } @@ -161,12 +154,10 @@ NoteFolder NoteFolder::noteFolderFromQuery(const QSqlQuery &query) { bool NoteFolder::fillFromQuery(const QSqlQuery &query) { this->id = query.value(QStringLiteral("id")).toInt(); this->name = query.value(QStringLiteral("name")).toString(); - this->cloudConnectionId = - query.value(QStringLiteral("cloud_connection_id")).toInt(); + this->cloudConnectionId = query.value(QStringLiteral("cloud_connection_id")).toInt(); this->remotePath = query.value(QStringLiteral("remote_path")).toString(); this->priority = query.value(QStringLiteral("priority")).toInt(); - this->showSubfolders = - query.value(QStringLiteral("show_subfolders")).toBool(); + this->showSubfolders = query.value(QStringLiteral("show_subfolders")).toBool(); this->useGit = query.value(QStringLiteral("use_git")).toBool(); this->activeTagId = query.value(QStringLiteral("active_tag_id")).toInt(); this->activeNoteSubFolderData = @@ -185,8 +176,7 @@ QList<NoteFolder> NoteFolder::fetchAll() { QList<NoteFolder> noteFolderList; - query.prepare(QStringLiteral( - "SELECT * FROM noteFolder ORDER BY priority ASC, id ASC")); + query.prepare(QStringLiteral("SELECT * FROM noteFolder ORDER BY priority ASC, id ASC")); if (!query.exec()) { qWarning() << __func__ << ": " << query.lastError(); } else { @@ -206,41 +196,38 @@ bool NoteFolder::store() { QSqlQuery query(db); if (this->id > 0) { - query.prepare(QStringLiteral( - "UPDATE noteFolder SET name = :name, local_path = :localPath, " - "cloud_connection_id = :cloudConnectionId, " - "remote_path = :remotePath, priority = :priority, " - "active_tag_id = :activeTagId, show_subfolders = " - ":showSubfolders, active_note_sub_folder_data = " - ":activeNoteSubFolderData, use_git = :useGit WHERE " - "id = :id")); + query.prepare( + QStringLiteral("UPDATE noteFolder SET name = :name, local_path = :localPath, " + "cloud_connection_id = :cloudConnectionId, " + "remote_path = :remotePath, priority = :priority, " + "active_tag_id = :activeTagId, show_subfolders = " + ":showSubfolders, active_note_sub_folder_data = " + ":activeNoteSubFolderData, use_git = :useGit WHERE " + "id = :id")); query.bindValue(QStringLiteral(":id"), this->id); } else { - query.prepare(QStringLiteral( - "INSERT INTO noteFolder (name, local_path, cloud_connection_id, " - "remote_path, priority, active_tag_id, " - "show_subfolders, active_note_sub_folder_data, use_git)" - " VALUES (:name, :localPath, :cloudConnectionId, " - ":remotePath, :priority, :activeTagId, " - ":showSubfolders, :activeNoteSubFolderData, :useGit)")); + query.prepare( + QStringLiteral("INSERT INTO noteFolder (name, local_path, cloud_connection_id, " + "remote_path, priority, active_tag_id, " + "show_subfolders, active_note_sub_folder_data, use_git)" + " VALUES (:name, :localPath, :cloudConnectionId, " + ":remotePath, :priority, :activeTagId, " + ":showSubfolders, :activeNoteSubFolderData, :useGit)")); } query.bindValue(QStringLiteral(":name"), this->name); - query.bindValue(QStringLiteral(":cloudConnectionId"), - this->cloudConnectionId); + query.bindValue(QStringLiteral(":cloudConnectionId"), this->cloudConnectionId); query.bindValue(QStringLiteral(":remotePath"), this->remotePath); query.bindValue(QStringLiteral(":priority"), this->priority); query.bindValue(QStringLiteral(":activeTagId"), this->activeTagId); query.bindValue(QStringLiteral(":showSubfolders"), this->showSubfolders); query.bindValue(QStringLiteral(":useGit"), this->useGit); - query.bindValue(QStringLiteral(":activeNoteSubFolderData"), - this->activeNoteSubFolderData); + query.bindValue(QStringLiteral(":activeNoteSubFolderData"), this->activeNoteSubFolderData); // make the path relative to the portable data path if we are in // portable mode query.bindValue(QStringLiteral(":localPath"), - Utils::Misc::makePathRelativeToPortableDataPathIfNeeded( - this->localPath)); + Utils::Misc::makePathRelativeToPortableDataPathIfNeeded(this->localPath)); if (!query.exec()) { // on error @@ -267,9 +254,8 @@ void NoteFolder::setAsCurrent() const { // make the path relative to the portable data path if we are in // portable mode - settings.setValue( - QStringLiteral("notesPath"), - Utils::Misc::makePathRelativeToPortableDataPathIfNeeded(localPath)); + settings.setValue(QStringLiteral("notesPath"), + Utils::Misc::makePathRelativeToPortableDataPathIfNeeded(localPath)); // we need to reset the instance OwnCloudService::instance(true); @@ -291,9 +277,7 @@ int NoteFolder::currentNoteFolderId() { /** * Returns the current note folder */ -NoteFolder NoteFolder::currentNoteFolder() { - return NoteFolder::fetch(currentNoteFolderId()); -} +NoteFolder NoteFolder::currentNoteFolder() { return NoteFolder::fetch(currentNoteFolderId()); } /** * Fetches the current remote path for the ownCloud service @@ -307,17 +291,15 @@ QString NoteFolder::currentRemotePath(bool addTrailingSlash) { } // add a leading "/" - remotePath = Utils::Misc::prependIfDoesNotStartWith(std::move(remotePath), - QStringLiteral("/")); + remotePath = Utils::Misc::prependIfDoesNotStartWith(std::move(remotePath), QStringLiteral("/")); if (addTrailingSlash) { // add a trailing "/" - remotePath = Utils::Misc::appendIfDoesNotEndWith(std::move(remotePath), - QStringLiteral("/")); + remotePath = + Utils::Misc::appendIfDoesNotEndWith(std::move(remotePath), QStringLiteral("/")); } else { // remove a trailing "/" - remotePath = Utils::Misc::removeIfEndsWith(std::move(remotePath), - QStringLiteral("/")); + remotePath = Utils::Misc::removeIfEndsWith(std::move(remotePath), QStringLiteral("/")); } return remotePath; @@ -353,8 +335,7 @@ QString NoteFolder::currentLocalPath() { } path = Utils::Misc::removeIfEndsWith(std::move(path), QDir::separator()); - path = Utils::Misc::removeIfEndsWith(std::move(path), - QString{Utils::Misc::dirSeparator()}); + path = Utils::Misc::removeIfEndsWith(std::move(path), QString{Utils::Misc::dirSeparator()}); return path; } @@ -365,33 +346,28 @@ QString NoteFolder::currentLocalPath() { */ QString NoteFolder::currentRootFolderName(bool fullPath) { QString path = currentLocalPath(); - return fullPath ? path - : path.remove( - 0, path.lastIndexOf(Utils::Misc::dirSeparator()) + 1); + return fullPath ? path : path.remove(0, path.lastIndexOf(Utils::Misc::dirSeparator()) + 1); } /** * Fetches the current trash path */ QString NoteFolder::currentTrashPath() { - return NoteFolder::currentLocalPath() + QDir::separator() + - QStringLiteral("trash"); + return NoteFolder::currentLocalPath() + QDir::separator() + QStringLiteral("trash"); } /** * Fetches the current media path */ QString NoteFolder::currentMediaPath() { - return NoteFolder::currentLocalPath() + QDir::separator() + - QStringLiteral("media"); + return NoteFolder::currentLocalPath() + QDir::separator() + QStringLiteral("media"); } /** * Fetches the current attachments path */ QString NoteFolder::currentAttachmentsPath() { - return NoteFolder::currentLocalPath() + QDir::separator() + - QStringLiteral("attachments"); + return NoteFolder::currentLocalPath() + QDir::separator() + QStringLiteral("attachments"); } /** @@ -441,10 +417,8 @@ QString NoteFolder::suggestRemotePath() { * Removes a leading or trailing slash from the remote path */ QString NoteFolder::fixRemotePath() { - remotePath = Utils::Misc::removeIfStartsWith(std::move(remotePath), - QStringLiteral("/")); - remotePath = Utils::Misc::removeIfEndsWith(std::move(remotePath), - QStringLiteral("/")); + remotePath = Utils::Misc::removeIfStartsWith(std::move(remotePath), QStringLiteral("/")); + remotePath = Utils::Misc::removeIfEndsWith(std::move(remotePath), QStringLiteral("/")); return remotePath; } @@ -472,8 +446,7 @@ bool NoteFolder::migrateToNoteFolders() { noteFolder.setCloudConnectionId(1); noteFolder.suggestRemotePath(); noteFolder.setPriority(priority++); - noteFolder.setShowSubfolders( - settings.value(QStringLiteral("showNoteSubFolders")).toBool()); + noteFolder.setShowSubfolders(settings.value(QStringLiteral("showNoteSubFolders")).toBool()); noteFolder.store(); settings.remove(QStringLiteral("showNoteSubFolders")); @@ -558,16 +531,14 @@ void NoteFolder::setSettingsValue(const QString &key, const QVariant &value) { settings.setValue(QString("NoteFolder-%1/%2").arg(QString::number(id), key), value); } -QVariant NoteFolder::settingsValue(const QString &key, - const QVariant &defaultValue) const { +QVariant NoteFolder::settingsValue(const QString &key, const QVariant &defaultValue) const { const QSettings settings; return settings.value(QString("NoteFolder-%1/%2").arg(QString::number(id), key), defaultValue); } QDebug operator<<(QDebug dbg, const NoteFolder ¬eFolder) { - dbg.nospace() << "NoteFolder: <id>" << noteFolder.id << " <name>" - << noteFolder.name << " <localPath>" << noteFolder.localPath - << " <remotePath>" << noteFolder.remotePath << " <priority>" - << noteFolder.priority; + dbg.nospace() << "NoteFolder: <id>" << noteFolder.id << " <name>" << noteFolder.name + << " <localPath>" << noteFolder.localPath << " <remotePath>" + << noteFolder.remotePath << " <priority>" << noteFolder.priority; return dbg.space(); } diff --git a/src/entities/notefolder.h b/src/entities/notefolder.h index 6e79afcf0..713561c5a 100644 --- a/src/entities/notefolder.h +++ b/src/entities/notefolder.h @@ -44,8 +44,8 @@ class NoteFolder { void setUseGit(bool value); QJsonObject jsonObject() const; - static bool create(const QString &name, const QString &localPath, - int cloudConnectionId, const QString &remotePath); + static bool create(const QString &name, const QString &localPath, int cloudConnectionId, + const QString &remotePath); static NoteFolder fetch(int id); static NoteFolder noteFolderFromQuery(const QSqlQuery &query); static QList<NoteFolder> fetchAll(); @@ -67,7 +67,7 @@ class NoteFolder { void setSettingsValue(const QString &key, const QVariant &value); QVariant settingsValue(const QString &key, const QVariant &defaultValue = QVariant()) const; -private: + private: QString name; QString localPath; QString remotePath; diff --git a/src/entities/notehistory.cpp b/src/entities/notehistory.cpp index e999c53f5..3c9ec74b7 100644 --- a/src/entities/notehistory.cpp +++ b/src/entities/notehistory.cpp @@ -27,15 +27,12 @@ NoteHistoryItem::NoteHistoryItem(Note *note, QPlainTextEdit *textEdit) if (textEdit != nullptr) { _cursorPosition = textEdit->textCursor().position(); - _relativeScrollBarPosition = - getTextEditScrollBarRelativePosition(textEdit); + _relativeScrollBarPosition = getTextEditScrollBarRelativePosition(textEdit); } } -NoteHistoryItem::NoteHistoryItem(QString noteName, - QString noteSubFolderPathData, - int cursorPosition, - float relativeScrollBarPosition) { +NoteHistoryItem::NoteHistoryItem(QString noteName, QString noteSubFolderPathData, + int cursorPosition, float relativeScrollBarPosition) { _noteName = std::move(noteName); _noteSubFolderPathData = std::move(noteSubFolderPathData); _cursorPosition = cursorPosition; @@ -45,8 +42,7 @@ NoteHistoryItem::NoteHistoryItem(QString noteName, /** * Returns the relative note text edit scrollbar position (0..1) */ -float NoteHistoryItem::getTextEditScrollBarRelativePosition( - QPlainTextEdit *textEdit) { +float NoteHistoryItem::getTextEditScrollBarRelativePosition(QPlainTextEdit *textEdit) { QScrollBar *scrollBar = textEdit->verticalScrollBar(); int max = scrollBar->maximum(); @@ -55,21 +51,16 @@ float NoteHistoryItem::getTextEditScrollBarRelativePosition( QString NoteHistoryItem::getNoteName() const { return _noteName; } -QString NoteHistoryItem::getNoteSubFolderPathData() const { - return _noteSubFolderPathData; -} +QString NoteHistoryItem::getNoteSubFolderPathData() const { return _noteSubFolderPathData; } Note NoteHistoryItem::getNote() const { - NoteSubFolder noteSubFolder = - NoteSubFolder::fetchByPathData(_noteSubFolderPathData); + NoteSubFolder noteSubFolder = NoteSubFolder::fetchByPathData(_noteSubFolderPathData); return Note::fetchByName(_noteName, noteSubFolder.getId()); } int NoteHistoryItem::getCursorPosition() const { return _cursorPosition; } -float NoteHistoryItem::getRelativeScrollBarPosition() const { - return _relativeScrollBarPosition; -} +float NoteHistoryItem::getRelativeScrollBarPosition() const { return _relativeScrollBarPosition; } /** * Restores the position in a text edit @@ -93,9 +84,7 @@ void NoteHistoryItem::restoreTextEditPosition(QPlainTextEdit *textEdit) const { static_cast<int>(scrollBar->maximum() * _relativeScrollBarPosition)); } -bool NoteHistoryItem::isValid() const { - return _noteName.isEmpty(); -} +bool NoteHistoryItem::isValid() const { return _noteName.isEmpty(); } bool NoteHistoryItem::isNoteValid() const { Note note = getNote(); @@ -108,11 +97,9 @@ bool NoteHistoryItem::operator==(const NoteHistoryItem &item) const { } QDebug operator<<(QDebug dbg, const NoteHistoryItem &item) { - dbg.nospace() << "NoteHistoryItem: <noteName>" << item._noteName - << " <noteSubFolderPathData>" << item._noteSubFolderPathData - << " <cursorPosition>" << item._cursorPosition - << " <relativeScrollBarPosition>" - << item._relativeScrollBarPosition; + dbg.nospace() << "NoteHistoryItem: <noteName>" << item._noteName << " <noteSubFolderPathData>" + << item._noteSubFolderPathData << " <cursorPosition>" << item._cursorPosition + << " <relativeScrollBarPosition>" << item._relativeScrollBarPosition; return dbg.space(); } @@ -124,8 +111,8 @@ QDebug operator<<(QDebug dbg, const NoteHistoryItem &item) { * @return */ QDataStream &operator<<(QDataStream &out, const NoteHistoryItem &item) { - out << item.getNoteName() << item.getNoteSubFolderPathData() - << item.getCursorPosition() << item.getRelativeScrollBarPosition(); + out << item.getNoteName() << item.getNoteSubFolderPathData() << item.getCursorPosition() + << item.getRelativeScrollBarPosition(); return out; } @@ -143,10 +130,9 @@ QDataStream &operator>>(QDataStream &in, NoteHistoryItem &item) { int cursorPosition; float relativeScrollBarPosition; - in >> noteName >> noteSubFolderPathData >> cursorPosition >> - relativeScrollBarPosition; - item = NoteHistoryItem(noteName, noteSubFolderPathData, cursorPosition, - relativeScrollBarPosition); + in >> noteName >> noteSubFolderPathData >> cursorPosition >> relativeScrollBarPosition; + item = + NoteHistoryItem(noteName, noteSubFolderPathData, cursorPosition, relativeScrollBarPosition); return in; } @@ -231,8 +217,7 @@ void NoteHistory::add(Note note, QPlainTextEdit *textEdit) { qDebug() << " added to history: " << item; } -void NoteHistory::updateCursorPositionOfNote(Note note, - QPlainTextEdit *textEdit) { +void NoteHistory::updateCursorPositionOfNote(Note note, QPlainTextEdit *textEdit) { if (isEmpty()) { return; } @@ -314,9 +299,7 @@ bool NoteHistory::forward() { int NoteHistory::lastIndex() const { return noteHistory->size() - 1; } -NoteHistoryItem NoteHistory::getCurrentHistoryItem() const { - return currentHistoryItem; -} +NoteHistoryItem NoteHistory::getCurrentHistoryItem() const { return currentHistoryItem; } bool NoteHistory::isEmpty() const { return noteHistory->empty(); } @@ -348,10 +331,8 @@ void NoteHistory::storeForCurrentNoteFolder() { int count = 0; // store the last - for (int i = noteHistoryItemCount - maxCount; i < noteHistoryItemCount; - i++) { - noteHistoryVariantItems.append( - QVariant::fromValue(noteHistoryItems.at(i))); + for (int i = noteHistoryItemCount - maxCount; i < noteHistoryItemCount; i++) { + noteHistoryVariantItems.append(QVariant::fromValue(noteHistoryItems.at(i))); if (i == currentIndex) { newCurrentIndex = count; @@ -361,13 +342,12 @@ void NoteHistory::storeForCurrentNoteFolder() { } // store the note history settings of the old note folder - settings.setValue( - QStringLiteral("NoteHistory-") + QString::number(currentNoteFolderId), - noteHistoryVariantItems); + settings.setValue(QStringLiteral("NoteHistory-") + QString::number(currentNoteFolderId), + noteHistoryVariantItems); - settings.setValue(QStringLiteral("NoteHistoryCurrentIndex-") + - QString::number(currentNoteFolderId), - newCurrentIndex); + settings.setValue( + QStringLiteral("NoteHistoryCurrentIndex-") + QString::number(currentNoteFolderId), + newCurrentIndex); } /** @@ -380,9 +360,7 @@ void NoteHistory::restoreForCurrentNoteFolder() { // restore the note history of the new note folder const QVariantList noteHistoryVariantItems = - settings - .value(QStringLiteral("NoteHistory-") + - QString::number(currentNoteFolderId)) + settings.value(QStringLiteral("NoteHistory-") + QString::number(currentNoteFolderId)) .toList(); if (noteHistoryVariantItems.count() == 0) { @@ -399,10 +377,8 @@ void NoteHistory::restoreForCurrentNoteFolder() { } } - int newCurrentIndex = settings - .value("NoteHistoryCurrentIndex-" + - QString::number(currentNoteFolderId)) - .toInt(); + int newCurrentIndex = + settings.value("NoteHistoryCurrentIndex-" + QString::number(currentNoteFolderId)).toInt(); if (newCurrentIndex > 0 && newCurrentIndex <= maxIndex) { currentIndex = newCurrentIndex; @@ -414,8 +390,8 @@ void NoteHistory::restoreForCurrentNoteFolder() { } QDebug operator<<(QDebug dbg, const NoteHistory &history) { - dbg.nospace() << "NoteHistory: <index>" << history.currentIndex - << " <noteHistorySize>" << history.noteHistory->size(); + dbg.nospace() << "NoteHistory: <index>" << history.currentIndex << " <noteHistorySize>" + << history.noteHistory->size(); return dbg.space(); } @@ -442,9 +418,7 @@ QList<NoteHistoryItem> NoteHistory::getNoteHistoryItems() const { * * @param item */ -void NoteHistory::addNoteHistoryItem(const NoteHistoryItem &item) { - noteHistory->append(item); -} +void NoteHistory::addNoteHistoryItem(const NoteHistoryItem &item) { noteHistory->append(item); } /** * Stream operator for storing the class to QSettings diff --git a/src/entities/notehistory.h b/src/entities/notehistory.h index 8ee1214dc..1544bde97 100644 --- a/src/entities/notehistory.h +++ b/src/entities/notehistory.h @@ -2,18 +2,16 @@ #define NOTEHISTORY_H #include <QDataStream> -#include <QString> #include <QMetaType> +#include <QString> class Note; class QPlainTextEdit; class NoteHistoryItem { public: - explicit NoteHistoryItem(Note *note = nullptr, - QPlainTextEdit *textEdit = nullptr); - explicit NoteHistoryItem(QString noteName, QString noteSubFolderPathData, - int cursorPosition, + explicit NoteHistoryItem(Note *note = nullptr, QPlainTextEdit *textEdit = nullptr); + explicit NoteHistoryItem(QString noteName, QString noteSubFolderPathData, int cursorPosition, float relativeScrollBarPosition); friend QDebug operator<<(QDebug dbg, const NoteHistoryItem &item); QString getNoteName() const; diff --git a/src/entities/notesubfolder.cpp b/src/entities/notesubfolder.cpp index efcece708..60d803bb7 100644 --- a/src/entities/notesubfolder.cpp +++ b/src/entities/notesubfolder.cpp @@ -17,22 +17,17 @@ #include "notefolder.h" #include "tag.h" -NoteSubFolder::NoteSubFolder() - : _id{0}, _parentId{0}, _name{QLatin1String("")} {} +NoteSubFolder::NoteSubFolder() : _id{0}, _parentId{0}, _name{QLatin1String("")} {} int NoteSubFolder::getId() const { return _id; } int NoteSubFolder::getParentId() const { return _parentId; } -NoteSubFolder NoteSubFolder::getParent() const { - return NoteSubFolder::fetch(_parentId); -} +NoteSubFolder NoteSubFolder::getParent() const { return NoteSubFolder::fetch(_parentId); } QString NoteSubFolder::getName() const { return _name; } -QDateTime NoteSubFolder::getFileLastModified() const { - return _fileLastModified; -} +QDateTime NoteSubFolder::getFileLastModified() const { return _fileLastModified; } QDateTime NoteSubFolder::getModified() const { return _modified; } @@ -60,8 +55,7 @@ NoteSubFolder NoteSubFolder::fetch(int id) { return NoteSubFolder(); } -NoteSubFolder NoteSubFolder::fetchByNameAndParentId(const QString& name, - int parentId) { +NoteSubFolder NoteSubFolder::fetchByNameAndParentId(const QString& name, int parentId) { const QSqlDatabase db = QSqlDatabase::database(QStringLiteral("memory")); QSqlQuery query(db); @@ -86,17 +80,15 @@ NoteSubFolder NoteSubFolder::fetchByNameAndParentId(const QString& name, * Gets the relative path name of the note sub folder */ QString NoteSubFolder::relativePath(char separator) const { - return _parentId == 0 - ? _name - : getParent().relativePath(separator) + separator + _name; + return _parentId == 0 ? _name : getParent().relativePath(separator) + separator + _name; } /** * Gets the full path of the note sub folder */ QString NoteSubFolder::fullPath() const { - return Utils::Misc::removeIfEndsWith( - Note::getFullFilePathForFile(relativePath()), QStringLiteral("/")); + return Utils::Misc::removeIfEndsWith(Note::getFullFilePathForFile(relativePath()), + QStringLiteral("/")); } /** @@ -108,15 +100,13 @@ QDir NoteSubFolder::dir() const { return QDir(fullPath()); } * Gets the path data of the note sub folder */ QString NoteSubFolder::pathData() const { - return _parentId == 0 ? _name - : getParent().pathData() + QChar('\n') + _name; + return _parentId == 0 ? _name : getParent().pathData() + QChar('\n') + _name; } /** * Fetches a note sub folder by its path data */ -NoteSubFolder NoteSubFolder::fetchByPathData(QString pathData, - const QString& separator) { +NoteSubFolder NoteSubFolder::fetchByPathData(QString pathData, const QString& separator) { if (pathData.isEmpty()) return NoteSubFolder(); pathData = Utils::Misc::removeIfStartsWith(std::move(pathData), separator); @@ -124,8 +114,7 @@ NoteSubFolder NoteSubFolder::fetchByPathData(QString pathData, NoteSubFolder noteSubFolder; // loop through all names to fetch the deepest note sub folder for (const auto& name : pathList) { - noteSubFolder = - NoteSubFolder::fetchByNameAndParentId(name, noteSubFolder.getId()); + noteSubFolder = NoteSubFolder::fetchByNameAndParentId(name, noteSubFolder.getId()); if (!noteSubFolder.isFetched()) return NoteSubFolder(); } return noteSubFolder; @@ -181,8 +170,7 @@ bool NoteSubFolder::rename(const QString& newName) { const bool ret = QDir().rename(oldPath, newPath); if (!ret) { - qCritical() << "Renaming " << oldPath << " to " << newPath - << " failed"; + qCritical() << "Renaming " << oldPath << " to " << newPath << " failed"; } return ret; @@ -199,8 +187,7 @@ NoteSubFolder NoteSubFolder::fillFromQuery(const QSqlQuery& query) { _id = query.value(QStringLiteral("id")).toInt(); _parentId = query.value(QStringLiteral("parent_id")).toInt(); _name = query.value(QStringLiteral("name")).toString(); - _fileLastModified = - query.value(QStringLiteral("file_last_modified")).toDateTime(); + _fileLastModified = query.value(QStringLiteral("file_last_modified")).toDateTime(); _created = query.value(QStringLiteral("created")).toDateTime(); _modified = query.value(QStringLiteral("modified")).toDateTime(); @@ -259,8 +246,7 @@ QVector<int> NoteSubFolder::fetchAllIds() { return idList; } -QVector<NoteSubFolder> NoteSubFolder::fetchAllByParentId( - int parentId, const QString& sortBy) { +QVector<NoteSubFolder> NoteSubFolder::fetchAllByParentId(int parentId, const QString& sortBy) { const QSqlDatabase db = QSqlDatabase::database(QStringLiteral("memory")); QSqlQuery query(db); @@ -451,9 +437,7 @@ bool NoteSubFolder::isActive() const { return activeNoteSubFolderId() == _id; } /** * Returns the id of the current note sub folder of the current note folder */ -int NoteSubFolder::activeNoteSubFolderId() { - return activeNoteSubFolder().getId(); -} +int NoteSubFolder::activeNoteSubFolderId() { return activeNoteSubFolder().getId(); } /** * Returns the current note sub folder of the current note folder @@ -505,9 +489,7 @@ bool NoteSubFolder::treeWidgetExpandState() const { * Checks if noteSubfoldersPanelShowNotesRecursively is set */ bool NoteSubFolder::isNoteSubfoldersPanelShowNotesRecursively() { - return QSettings() - .value(QStringLiteral("noteSubfoldersPanelShowNotesRecursively")) - .toBool(); + return QSettings().value(QStringLiteral("noteSubfoldersPanelShowNotesRecursively")).toBool(); } /** @@ -537,22 +519,19 @@ int NoteSubFolder::depth() const { return relativePath.split(QChar('\n')).count(); } -bool NoteSubFolder::willFolderBeIgnored(const QString& folderName, - bool showWarning) { +bool NoteSubFolder::willFolderBeIgnored(const QString& folderName, bool showWarning) { // ignore some folders - const QStringList ignoreFolderList{".", "..", "media", "attachments", - "trash"}; + const QStringList ignoreFolderList{".", "..", "media", "attachments", "trash"}; if (ignoreFolderList.contains(folderName)) { #ifndef INTEGRATION_TESTS if (showWarning) { - Utils::Gui::warning( - nullptr, QObject::tr("Folder will be hidden!"), - QObject::tr("Folder with name <b>%1</b> can't be created, " - "because it's internally used by the " - "application!") - .arg(folderName), - "note-subfolder-hidden-internal"); + Utils::Gui::warning(nullptr, QObject::tr("Folder will be hidden!"), + QObject::tr("Folder with name <b>%1</b> can't be created, " + "because it's internally used by the " + "application!") + .arg(folderName), + "note-subfolder-hidden-internal"); } #else Q_UNUSED(showWarning) @@ -563,9 +542,7 @@ bool NoteSubFolder::willFolderBeIgnored(const QString& folderName, const QSettings settings; const QStringList ignoredFolderRegExpList = - settings - .value(QStringLiteral("ignoreNoteSubFolders"), - IGNORED_NOTE_SUBFOLDERS_DEFAULT) + settings.value(QStringLiteral("ignoreNoteSubFolders"), IGNORED_NOTE_SUBFOLDERS_DEFAULT) .toString() .split(QLatin1Char(';')); @@ -573,14 +550,12 @@ bool NoteSubFolder::willFolderBeIgnored(const QString& folderName, if (Utils::Misc::regExpInListMatches(folderName, ignoredFolderRegExpList)) { #ifndef INTEGRATION_TESTS if (showWarning) { - Utils::Gui::warning( - nullptr, QObject::tr("Folder will be hidden!"), - QObject::tr( - "Folder with name <b>%1</b> can't be created, " - "because it's on the list of ignored subfolders! " - "You can change that in the <i>Panels settings</i>.") - .arg(folderName), - "note-subfolder-hidden-settings"); + Utils::Gui::warning(nullptr, QObject::tr("Folder will be hidden!"), + QObject::tr("Folder with name <b>%1</b> can't be created, " + "because it's on the list of ignored subfolders! " + "You can change that in the <i>Panels settings</i>.") + .arg(folderName), + "note-subfolder-hidden-settings"); } #endif @@ -591,8 +566,7 @@ bool NoteSubFolder::willFolderBeIgnored(const QString& folderName, } QDebug operator<<(QDebug dbg, const NoteSubFolder& noteSubFolder) { - dbg.nospace() << "NoteSubFolder: <id>" << noteSubFolder._id << " <name>" - << noteSubFolder._name << " <parentId>" - << noteSubFolder._parentId; + dbg.nospace() << "NoteSubFolder: <id>" << noteSubFolder._id << " <name>" << noteSubFolder._name + << " <parentId>" << noteSubFolder._parentId; return dbg.space(); } diff --git a/src/entities/notesubfolder.h b/src/entities/notesubfolder.h index b98d760a2..5de499c80 100644 --- a/src/entities/notesubfolder.h +++ b/src/entities/notesubfolder.h @@ -56,8 +56,7 @@ class NoteSubFolder { NoteSubFolder getParent() const; static QVector<NoteSubFolder> fetchAllByParentId( - int parentId, - const QString& sortBy = QStringLiteral("file_last_modified DESC")); + int parentId, const QString& sortBy = QStringLiteral("file_last_modified DESC")); static QVector<int> fetchIdsRecursivelyByParentId(int parentId); @@ -73,11 +72,10 @@ class NoteSubFolder { QString pathData() const; - static NoteSubFolder fetchByPathData( - QString pathData, const QString& separator = QStringLiteral("\n")); + static NoteSubFolder fetchByPathData(QString pathData, + const QString& separator = QStringLiteral("\n")); - static NoteSubFolder fetchByNameAndParentId(const QString& name, - int parentId); + static NoteSubFolder fetchByNameAndParentId(const QString& name, int parentId); void saveTreeWidgetExpandState(bool expanded) const; @@ -99,8 +97,7 @@ class NoteSubFolder { int depth() const; - static bool willFolderBeIgnored(const QString& folderName, - bool showWarning = false); + static bool willFolderBeIgnored(const QString& folderName, bool showWarning = false); protected: int _id; diff --git a/src/entities/script.cpp b/src/entities/script.cpp index 03b268cf9..1ad19d0a9 100644 --- a/src/entities/script.cpp +++ b/src/entities/script.cpp @@ -29,15 +29,11 @@ #include <QSqlRecord> #include <QtCore/QJsonArray> -const QString Script::ScriptRepositoryRawContentUrlPrefix = QStringLiteral( - "https://raw.githubusercontent.com/qownnotes/scripts/master/"); +const QString Script::ScriptRepositoryRawContentUrlPrefix = + QStringLiteral("https://raw.githubusercontent.com/qownnotes/scripts/master/"); Script::Script() - : id{0}, - name(QLatin1String("")), - scriptPath(QLatin1String("")), - priority{0}, - enabled{true} {} + : id{0}, name(QLatin1String("")), scriptPath(QLatin1String("")), priority{0}, enabled{true} {} int Script::getId() const { return this->id; } @@ -72,13 +68,9 @@ bool Script::isEnabled() const { return getEnabled(); } void Script::setName(const QString &text) { this->name = text; } -void Script::setIdentifier(QString identifier) { - this->identifier = std::move(identifier); -} +void Script::setIdentifier(QString identifier) { this->identifier = std::move(identifier); } -void Script::setInfoJson(QString infoJson) { - this->infoJson = std::move(infoJson); -} +void Script::setInfoJson(QString infoJson) { this->infoJson = std::move(infoJson); } void Script::setSettingsVariablesJson(QString json) { this->settingsVariablesJson = std::move(json); @@ -107,8 +99,7 @@ bool Script::create(const QString &name, QString scriptPath) { // make the path relative to the portable data path if we are in // portable mode query.bindValue(QStringLiteral(":scriptPath"), - Utils::Misc::makePathRelativeToPortableDataPathIfNeeded( - std::move(scriptPath))); + Utils::Misc::makePathRelativeToPortableDataPathIfNeeded(std::move(scriptPath))); return query.exec(); } @@ -157,8 +148,7 @@ int Script::countEnabled() { QSqlDatabase db = QSqlDatabase::database(QStringLiteral("disk")); QSqlQuery query(db); - query.prepare( - QStringLiteral("SELECT COUNT(*) AS cnt FROM script WHERE enabled = 1")); + query.prepare(QStringLiteral("SELECT COUNT(*) AS cnt FROM script WHERE enabled = 1")); if (!query.exec()) { qWarning() << __func__ << ": " << query.lastError(); @@ -192,8 +182,7 @@ Script Script::fetchByIdentifier(const QString &identifier) { Script script; - query.prepare( - QStringLiteral("SELECT * FROM script WHERE identifier = :identifier")); + query.prepare(QStringLiteral("SELECT * FROM script WHERE identifier = :identifier")); query.bindValue(QStringLiteral(":identifier"), identifier); if (!query.exec()) { @@ -266,8 +255,7 @@ bool Script::fillFromQuery(const QSqlQuery &query) { this->name = query.value(QStringLiteral("name")).toString(); this->identifier = query.value(QStringLiteral("identifier")).toString(); this->infoJson = query.value(QStringLiteral("info_json")).toString(); - this->settingsVariablesJson = - query.value(QStringLiteral("settings_variables_json")).toString(); + this->settingsVariablesJson = query.value(QStringLiteral("settings_variables_json")).toString(); this->priority = query.value(QStringLiteral("priority")).toInt(); this->enabled = query.value(QStringLiteral("enabled")).toBool(); @@ -283,10 +271,8 @@ QList<Script> Script::fetchAll(bool enabledOnly) { QSqlQuery query(db); QList<Script> scriptList; - query.prepare( - QStringLiteral("SELECT * FROM script %1 ORDER BY priority ASC, id ASC") - .arg(enabledOnly ? QStringLiteral("WHERE enabled = 1") - : QLatin1String(""))); + query.prepare(QStringLiteral("SELECT * FROM script %1 ORDER BY priority ASC, id ASC") + .arg(enabledOnly ? QStringLiteral("WHERE enabled = 1") : QLatin1String(""))); if (!query.exec()) { qWarning() << __func__ << ": " << query.lastError(); @@ -308,20 +294,20 @@ bool Script::store() { QSqlQuery query(db); if (this->id > 0) { - query.prepare(QStringLiteral( - "UPDATE script SET name = :name, script_path = :scriptPath, " - "priority = :priority, enabled = :enabled, " - "identifier = :identifier, info_json = :info_json, " - "settings_variables_json = :settings_variables_json " - "WHERE id = :id")); + query.prepare( + QStringLiteral("UPDATE script SET name = :name, script_path = :scriptPath, " + "priority = :priority, enabled = :enabled, " + "identifier = :identifier, info_json = :info_json, " + "settings_variables_json = :settings_variables_json " + "WHERE id = :id")); query.bindValue(QStringLiteral(":id"), this->id); } else { - query.prepare(QStringLiteral( - "INSERT INTO script (name, script_path, " - "priority, enabled, identifier, info_json," - "settings_variables_json) VALUES " - "(:name, :scriptPath, :priority, :enabled, " - ":identifier, :info_json, :settings_variables_json)")); + query.prepare( + QStringLiteral("INSERT INTO script (name, script_path, " + "priority, enabled, identifier, info_json," + "settings_variables_json) VALUES " + "(:name, :scriptPath, :priority, :enabled, " + ":identifier, :info_json, :settings_variables_json)")); } query.bindValue(QStringLiteral(":name"), this->name); @@ -329,14 +315,12 @@ bool Script::store() { query.bindValue(QStringLiteral(":enabled"), this->enabled); query.bindValue(QStringLiteral(":identifier"), this->identifier); query.bindValue(QStringLiteral(":info_json"), this->infoJson); - query.bindValue(QStringLiteral(":settings_variables_json"), - this->settingsVariablesJson); + query.bindValue(QStringLiteral(":settings_variables_json"), this->settingsVariablesJson); // make the path relative to the portable data path if we are in // portable mode query.bindValue(QStringLiteral(":scriptPath"), - Utils::Misc::makePathRelativeToPortableDataPathIfNeeded( - this->scriptPath)); + Utils::Misc::makePathRelativeToPortableDataPathIfNeeded(this->scriptPath)); if (!query.exec()) { // on error @@ -375,9 +359,7 @@ QJsonObject Script::getInfoJsonObject() const { * * @return */ -ScriptInfoJson Script::getScriptInfoJson() const { - return ScriptInfoJson(getInfoJsonObject()); -} +ScriptInfoJson Script::getScriptInfoJson() const { return ScriptInfoJson(getInfoJsonObject()); } /** * Returns the json object of the settingsVariablesJson field @@ -385,8 +367,7 @@ ScriptInfoJson Script::getScriptInfoJson() const { * @return */ QJsonObject Script::getSettingsVariablesJsonObject() const { - QJsonDocument jsonResponse = - QJsonDocument::fromJson(settingsVariablesJson.toUtf8()); + QJsonDocument jsonResponse = QJsonDocument::fromJson(settingsVariablesJson.toUtf8()); return jsonResponse.object(); } @@ -395,9 +376,7 @@ QJsonObject Script::getSettingsVariablesJsonObject() const { * * @return */ -QString Script::getSettingsVariablesJson() const { - return settingsVariablesJson; -} +QString Script::getSettingsVariablesJson() const { return settingsVariablesJson; } /** * Returns the path where the script repositories will be stored locally @@ -424,8 +403,7 @@ QString Script::scriptRepositoryPath(bool removeRecursively) const { return QString(); } - QString path = - globalScriptRepositoryPath() + QStringLiteral("/") + identifier; + QString path = globalScriptRepositoryPath() + QStringLiteral("/") + identifier; QDir dir(path); // remove the old files in the script path @@ -443,9 +421,7 @@ QString Script::scriptRepositoryPath(bool removeRecursively) const { * * @return */ -bool Script::isScriptFromRepository() const { - return !identifier.isEmpty() || !infoJson.isEmpty(); -} +bool Script::isScriptFromRepository() const { return !identifier.isEmpty() || !infoJson.isEmpty(); } /** * Returns the url of the script in the remote script repository @@ -473,10 +449,8 @@ QUrl Script::remoteFileUrl(const QString &fileName) const { return QUrl(); } - return QUrl( - QStringLiteral( - "https://raw.githubusercontent.com/qownnotes/scripts/master/") + - identifier + QStringLiteral("/") + fileName); + return QUrl(QStringLiteral("https://raw.githubusercontent.com/qownnotes/scripts/master/") + + identifier + QStringLiteral("/") + fileName); } /** @@ -505,9 +479,9 @@ QList<QUrl> Script::remoteFileUrls() const { } QDebug operator<<(QDebug dbg, const Script &script) { - dbg.nospace() << "Script: <id>" << script.id << " <name>" << script.name - << " <scriptPath>" << script.scriptPath << " <enabled>" - << script.enabled << " <priority>" << script.priority; + dbg.nospace() << "Script: <id>" << script.id << " <name>" << script.name << " <scriptPath>" + << script.scriptPath << " <enabled>" << script.enabled << " <priority>" + << script.priority; return dbg.space(); } @@ -524,16 +498,12 @@ ScriptInfoJson::ScriptInfoJson(const QJsonObject &jsonObject) { name = jsonObject.value(QStringLiteral("name")).toString(); identifier = jsonObject.value(QStringLiteral("identifier")).toString(); version = jsonObject.value(QStringLiteral("version")).toString(); - minAppVersion = - jsonObject.value(QStringLiteral("minAppVersion")).toString(); + minAppVersion = jsonObject.value(QStringLiteral("minAppVersion")).toString(); description = jsonObject.value(QStringLiteral("description")).toString(); - description = - description.replace(QStringLiteral("\n"), QStringLiteral("<br>")); + description = description.replace(QStringLiteral("\n"), QStringLiteral("<br>")); script = jsonObject.value(QStringLiteral("script")).toString(); - const QJsonArray authors = - jsonObject.value(QStringLiteral("authors")).toArray(); - const QJsonArray platforms = - jsonObject.value(QStringLiteral("platforms")).toArray(); + const QJsonArray authors = jsonObject.value(QStringLiteral("authors")).toArray(); + const QJsonArray platforms = jsonObject.value(QStringLiteral("platforms")).toArray(); // generate the author list richAuthorList.clear(); @@ -579,8 +549,7 @@ ScriptInfoJson::ScriptInfoJson(const QJsonObject &jsonObject) { richPlatformText = richPlatformList.join(QStringLiteral(", ")); // get the resources file names - const QJsonArray resourcesArray = - jsonObject.value(QStringLiteral("resources")).toArray(); + const QJsonArray resourcesArray = jsonObject.value(QStringLiteral("resources")).toArray(); resources.clear(); for (const QJsonValue &value : resourcesArray) { const QString fileName = value.toString().trimmed(); @@ -591,8 +560,7 @@ ScriptInfoJson::ScriptInfoJson(const QJsonObject &jsonObject) { } // check if app version is supported - appVersionSupported = - VersionNumber(VERSION) >= VersionNumber(minAppVersion); + appVersionSupported = VersionNumber(VERSION) >= VersionNumber(minAppVersion); } /** @@ -601,6 +569,5 @@ ScriptInfoJson::ScriptInfoJson(const QJsonObject &jsonObject) { * @return */ QUrl Script::repositoryInfoJsonUrl() const { - return ScriptRepositoryRawContentUrlPrefix + getIdentifier() + - QStringLiteral("/info.json"); + return ScriptRepositoryRawContentUrlPrefix + getIdentifier() + QStringLiteral("/info.json"); } diff --git a/src/entities/tag.cpp b/src/entities/tag.cpp index e2fb5897e..3eb1d23e3 100644 --- a/src/entities/tag.cpp +++ b/src/entities/tag.cpp @@ -16,8 +16,7 @@ #include "notefolder.h" #include "notesubfolder.h" -Tag::Tag() noexcept - : _parentId(0), _priority(0) {} +Tag::Tag() noexcept : _parentId(0), _priority(0) {} int Tag::getParentId() const { return _parentId; } @@ -62,10 +61,9 @@ Tag Tag::fetchByName(QString name, const bool startsWith) { QSqlDatabase db = DatabaseService::getNoteFolderDatabase(); QSqlQuery query(db); Tag tag; - const QString sql = - QStringLiteral("SELECT * FROM tag WHERE name ") % - QString(startsWith ? QStringLiteral("LIKE") : QStringLiteral("=")) % - QStringLiteral(" :name ORDER BY name"); + const QString sql = QStringLiteral("SELECT * FROM tag WHERE name ") % + QString(startsWith ? QStringLiteral("LIKE") : QStringLiteral("=")) % + QStringLiteral(" :name ORDER BY name"); query.prepare(sql); if (startsWith) { @@ -153,8 +151,7 @@ bool Tag::remove() const { QSqlQuery query2(db2); // remove the note tag links - query2.prepare( - QStringLiteral("DELETE FROM noteTagLink WHERE tag_id = :id")); + query2.prepare(QStringLiteral("DELETE FROM noteTagLink WHERE tag_id = :id")); query2.bindValue(QStringLiteral(":id"), _id); if (!query2.exec()) { @@ -169,9 +166,7 @@ bool Tag::remove() const { } } -Tag Tag::tagFromQuery(const QSqlQuery &query) { - return Tag().fillFromQuery(query); -} +Tag Tag::tagFromQuery(const QSqlQuery &query) { return Tag().fillFromQuery(query); } Tag Tag::fillFromQuery(const QSqlQuery &query) { _id = query.value(QStringLiteral("id")).toInt(); @@ -207,17 +202,17 @@ QVector<Tag> Tag::fetchAll() { * to sort the result by. * */ - query.prepare(QStringLiteral( - "SELECT t.id as id, t.name as name, t.priority as priority, max( " - "CASE " - "WHEN l.created > t.updated THEN l.created " - "ELSE t.updated " - "END " - ") AS created, t.parent_id as parent_id, " - "t.color as color, t.dark_color as dark_color " - "FROM tag t LEFT JOIN noteTagLink l ON t.id = l.tag_id " - "GROUP BY t.name " - "ORDER BY created DESC")); + query.prepare( + QStringLiteral("SELECT t.id as id, t.name as name, t.priority as priority, max( " + "CASE " + "WHEN l.created > t.updated THEN l.created " + "ELSE t.updated " + "END " + ") AS created, t.parent_id as parent_id, " + "t.color as color, t.dark_color as dark_color " + "FROM tag t LEFT JOIN noteTagLink l ON t.id = l.tag_id " + "GROUP BY t.name " + "ORDER BY created DESC")); if (!query.exec()) { qWarning() << __func__ << ": " << query.lastError(); } else { @@ -237,11 +232,10 @@ QVector<TagHeader> Tag::fetchAllTagHeadersByParentId(const int parentId) { QVector<TagHeader> tagList; query.prepare( - QStringLiteral( - "SELECT t.id as id, t.name as name " - "FROM tag t LEFT JOIN noteTagLink l ON t.id = l.tag_id " - "WHERE parent_id = :parentId " - "GROUP BY t.name")); + QStringLiteral("SELECT t.id as id, t.name as name " + "FROM tag t LEFT JOIN noteTagLink l ON t.id = l.tag_id " + "WHERE parent_id = :parentId " + "GROUP BY t.name")); query.bindValue(QStringLiteral(":parentId"), parentId); if (!query.exec()) { @@ -271,18 +265,17 @@ QVector<Tag> Tag::fetchAllByParentId(const int parentId, const QString &sortBy) * parent_id. */ query.prepare( - QStringLiteral( - "SELECT t.id as id, t.name as name, t.priority as priority, max( " - "CASE " - "WHEN l.created > t.updated THEN l.created " - "ELSE t.updated " - "END " - ") AS created, t.parent_id as parent_id, " - "t.color as color, t.dark_color as dark_color " - "FROM tag t LEFT JOIN noteTagLink l ON t.id = l.tag_id " - "WHERE parent_id = :parentId " - "GROUP BY t.name " - "ORDER BY :sortBy")); + QStringLiteral("SELECT t.id as id, t.name as name, t.priority as priority, max( " + "CASE " + "WHEN l.created > t.updated THEN l.created " + "ELSE t.updated " + "END " + ") AS created, t.parent_id as parent_id, " + "t.color as color, t.dark_color as dark_color " + "FROM tag t LEFT JOIN noteTagLink l ON t.id = l.tag_id " + "WHERE parent_id = :parentId " + "GROUP BY t.name " + "ORDER BY :sortBy")); query.bindValue(QStringLiteral(":parentId"), parentId); query.bindValue(QStringLiteral(":sortBy"), sortBy); @@ -299,16 +292,14 @@ QVector<Tag> Tag::fetchAllByParentId(const int parentId, const QString &sortBy) return tagList; } -QVector<int> Tag::fetchAllIdsByParentId(const int parentId) -{ +QVector<int> Tag::fetchAllIdsByParentId(const int parentId) { QSqlDatabase db = DatabaseService::getNoteFolderDatabase(); QSqlQuery query(db); query.prepare( - QStringLiteral( - "SELECT t.id as id " - "FROM tag t LEFT JOIN noteTagLink l ON t.id = l.tag_id " - "WHERE parent_id = :parentId")); + QStringLiteral("SELECT t.id as id " + "FROM tag t LEFT JOIN noteTagLink l ON t.id = l.tag_id " + "WHERE parent_id = :parentId")); query.bindValue(QStringLiteral(":parentId"), parentId); @@ -344,9 +335,8 @@ QVector<Tag> Tag::fetchRecursivelyByParentId(const int parentId) { return tagList; } -QVector<int> Tag::fetchTagIdsRecursivelyByParentId(const int parentId) -{ - QVector<int> tagIdList {parentId}; +QVector<int> Tag::fetchTagIdsRecursivelyByParentId(const int parentId) { + QVector<int> tagIdList{parentId}; const auto tagIds = fetchAllIdsByParentId(parentId); tagIdList.reserve(tagIds.size()); @@ -380,9 +370,7 @@ QStringList Tag::getParentTagNames() { * Checks if taggingShowNotesRecursively is set */ bool Tag::isTaggingShowNotesRecursively() { - return QSettings() - .value(QStringLiteral("taggingShowNotesRecursively")) - .toBool(); + return QSettings().value(QStringLiteral("taggingShowNotesRecursively")).toBool(); } int Tag::countAllParentId(const int parentId) { @@ -439,14 +427,13 @@ QVector<Tag> Tag::fetchAllOfNote(const Note ¬e) { "l.note_sub_folder_path = :noteSubFolderPath " "ORDER BY t.priority ASC, t.name ASC")); query.bindValue(QStringLiteral(":fileName"), note.getName()); - query.bindValue(QStringLiteral(":noteSubFolderPath"), - note.getNoteSubFolder().relativePath()); + query.bindValue(QStringLiteral(":noteSubFolderPath"), note.getNoteSubFolder().relativePath()); if (!query.exec()) { qWarning() << __func__ << ": " << query.lastError(); } else { for (int r = 0; query.next(); r++) { - tagList.append(tagFromQuery(query)); + tagList.append(tagFromQuery(query)); } } @@ -461,15 +448,14 @@ QVector<Tag> Tag::fetchAllOfNote(const Note ¬e) { QVector<Tag> Tag::fetchAllOfNotes(const QVector<Note> ¬es) { QVector<Tag> notesTagList; - //get all tags for the notes list + // get all tags for the notes list for (const Note ¬e : notes) { notesTagList.append(Tag::fetchAllOfNote(note)); } - //sort - std::sort (notesTagList.begin(), notesTagList.end()); - //remove duplicates - notesTagList.erase(std::unique(notesTagList.begin(), notesTagList.end()), - notesTagList.end()); + // sort + std::sort(notesTagList.begin(), notesTagList.end()); + // remove duplicates + notesTagList.erase(std::unique(notesTagList.begin(), notesTagList.end()), notesTagList.end()); return notesTagList; } @@ -489,8 +475,7 @@ QStringList Tag::fetchAllNamesOfNote(const Note ¬e) { "l.note_sub_folder_path = :noteSubFolderPath " "ORDER BY t.priority ASC, t.name ASC")); query.bindValue(QStringLiteral(":fileName"), note.getName()); - query.bindValue(QStringLiteral(":noteSubFolderPath"), - note.getNoteSubFolder().relativePath()); + query.bindValue(QStringLiteral(":noteSubFolderPath"), note.getNoteSubFolder().relativePath()); if (!query.exec()) { qWarning() << __func__ << ": " << query.lastError(); @@ -518,8 +503,7 @@ QSet<int> Tag::fetchAllIdsByNote(const Note ¬e) { "WHERE note_file_name = :fileName AND " "note_sub_folder_path = :noteSubFolderPath")); query.bindValue(QStringLiteral(":fileName"), note.getName()); - query.bindValue(QStringLiteral(":noteSubFolderPath"), - note.getNoteSubFolder().relativePath()); + query.bindValue(QStringLiteral(":noteSubFolderPath"), note.getNoteSubFolder().relativePath()); if (!query.exec()) { qWarning() << __func__ << ": " << query.lastError(); @@ -578,15 +562,15 @@ Tag Tag::fetchOneOfNoteWithColor(const Note ¬e) { /** * Checks if a note has tags */ -bool Tag::noteHasTags(const Note ¬e, const QString& path) { +bool Tag::noteHasTags(const Note ¬e, const QString &path) { QSqlDatabase db = DatabaseService::getNoteFolderDatabase(); QSqlQuery query(db); query.prepare( - QStringLiteral("SELECT " - "EXISTS (SELECT tag_id FROM noteTagLink " - "WHERE note_file_name=:fileName AND " - "note_sub_folder_path=:noteSubFolderPath) AS cnt")); + QStringLiteral("SELECT " + "EXISTS (SELECT tag_id FROM noteTagLink " + "WHERE note_file_name=:fileName AND " + "note_sub_folder_path=:noteSubFolderPath) AS cnt")); query.bindValue(QStringLiteral(":fileName"), note.getName()); query.bindValue(QStringLiteral(":noteSubFolderPath"), path.isEmpty() ? note.getNoteSubFolder().relativePath() : path); @@ -618,8 +602,7 @@ bool Tag::isLinkedToNote(const Note ¬e) const { "note_sub_folder_path = :noteSubFolderPath " "AND tag_id = :tagId")); query.bindValue(QStringLiteral(":fileName"), note.getName()); - query.bindValue(QStringLiteral(":noteSubFolderPath"), - note.getNoteSubFolder().relativePath()); + query.bindValue(QStringLiteral(":noteSubFolderPath"), note.getNoteSubFolder().relativePath()); query.bindValue(QStringLiteral(":tagId"), _id); if (!query.exec()) { @@ -689,9 +672,8 @@ QVector<int> Tag::fetchAllLinkedNoteIds(int tagId, const bool fromAllSubfolders, QStringLiteral("SELECT note_file_name, note_sub_folder_path " "FROM noteTagLink WHERE tag_id = :id " "AND note_sub_folder_path LIKE :noteSubFolderPath")); - query.bindValue( - QStringLiteral(":noteSubFolderPath"), - NoteSubFolder::activeNoteSubFolder().relativePath() + "%"); + query.bindValue(QStringLiteral(":noteSubFolderPath"), + NoteSubFolder::activeNoteSubFolder().relativePath() + "%"); } else { query.prepare( QStringLiteral("SELECT note_file_name, note_sub_folder_path " @@ -709,13 +691,11 @@ QVector<int> Tag::fetchAllLinkedNoteIds(int tagId, const bool fromAllSubfolders, for (int r = 0; query.next(); r++) { // always keep in mind that note_file_name is no file name, // but the base name (so "my-note", instead of "my-note.md") - const QString name = - query.value(QStringLiteral("note_file_name")).toString(); + const QString name = query.value(QStringLiteral("note_file_name")).toString(); const QString noteSubFolderPathData = query.value(QStringLiteral("note_sub_folder_path")).toString(); int noteSubFolderId = - NoteSubFolder::fetchByPathData(noteSubFolderPathData, QStringLiteral("/")) - .getId(); + NoteSubFolder::fetchByPathData(noteSubFolderPathData, QStringLiteral("/")).getId(); int noteId = Note::fetchNoteIdByName(name, noteSubFolderId); noteIdList.append(noteId); } @@ -729,10 +709,8 @@ QVector<int> Tag::fetchAllLinkedNoteIds(int tagId, const bool fromAllSubfolders, /** * Fetches all linked note ids for a given subfolder */ -QVector<int> Tag::fetchAllLinkedNoteIdsForFolder(int tagId, - const NoteSubFolder ¬eSubFolder, - bool fromAllSubfolders, - const bool recursive) { +QVector<int> Tag::fetchAllLinkedNoteIdsForFolder(int tagId, const NoteSubFolder ¬eSubFolder, + bool fromAllSubfolders, const bool recursive) { QSqlDatabase db = DatabaseService::getNoteFolderDatabase(); QSqlQuery query(db); QVector<int> noteIdList; @@ -747,15 +725,13 @@ QVector<int> Tag::fetchAllLinkedNoteIdsForFolder(int tagId, QStringLiteral("SELECT note_file_name, note_sub_folder_path " "FROM noteTagLink WHERE tag_id = :id " "AND note_sub_folder_path LIKE :noteSubFolderPath")); - query.bindValue(QStringLiteral(":noteSubFolderPath"), - noteSubFolder.relativePath() + "%"); + query.bindValue(QStringLiteral(":noteSubFolderPath"), noteSubFolder.relativePath() + "%"); } else { query.prepare( QStringLiteral("SELECT note_file_name, note_sub_folder_path " "FROM noteTagLink WHERE tag_id = :id " "AND note_sub_folder_path = :noteSubFolderPath")); - query.bindValue(QStringLiteral(":noteSubFolderPath"), - noteSubFolder.relativePath()); + query.bindValue(QStringLiteral(":noteSubFolderPath"), noteSubFolder.relativePath()); } query.bindValue(QStringLiteral(":id"), tagId); @@ -766,13 +742,11 @@ QVector<int> Tag::fetchAllLinkedNoteIdsForFolder(int tagId, for (int r = 0; query.next(); r++) { // always keep in mind that note_file_name is no file name, // but the base name (so "my-note", instead of "my-note.md") - const QString name = - query.value(QStringLiteral("note_file_name")).toString(); + const QString name = query.value(QStringLiteral("note_file_name")).toString(); const QString noteSubFolderPathData = query.value(QStringLiteral("note_sub_folder_path")).toString(); int noteSubFolderId = - NoteSubFolder::fetchByPathData(noteSubFolderPathData, QStringLiteral("/")) - .getId(); + NoteSubFolder::fetchByPathData(noteSubFolderPathData, QStringLiteral("/")).getId(); int noteId = Note::fetchNoteIdByName(name, noteSubFolderId); noteIdList.append(noteId); } @@ -800,14 +774,12 @@ QVector<Note> Tag::fetchAllLinkedNotes() const { qWarning() << __func__ << ": " << query.lastError(); } else { for (int r = 0; query.next(); r++) { - const QString fileName = - query.value(QStringLiteral("note_file_name")).toString(); + const QString fileName = query.value(QStringLiteral("note_file_name")).toString(); const QString noteSubFolderPath = query.value(QStringLiteral("note_sub_folder_path")).toString(); - const auto noteSubFolder = NoteSubFolder::fetchByPathData( - std::move(noteSubFolderPath), QStringLiteral("/")); - const auto note = - Note::fetchByName(fileName, noteSubFolder.getId()); + const auto noteSubFolder = + NoteSubFolder::fetchByPathData(std::move(noteSubFolderPath), QStringLiteral("/")); + const auto note = Note::fetchByName(fileName, noteSubFolder.getId()); noteList << note; } @@ -864,28 +836,27 @@ QStringList Tag::fetchAllNames() { /** * Count the linked note file names for a note sub folder */ -int Tag::countLinkedNoteFileNamesForNoteSubFolder( - int tagId, const NoteSubFolder ¬eSubFolder, - bool fromAllSubfolders, const bool recursive) { +int Tag::countLinkedNoteFileNamesForNoteSubFolder(int tagId, const NoteSubFolder ¬eSubFolder, + bool fromAllSubfolders, const bool recursive) { QSqlDatabase db = DatabaseService::getNoteFolderDatabase(); QSqlQuery query(db); if (fromAllSubfolders) { - query.prepare(QStringLiteral( - "SELECT COUNT(note_file_name) AS cnt FROM noteTagLink " - "WHERE tag_id = :id")); + query.prepare( + QStringLiteral("SELECT COUNT(note_file_name) AS cnt FROM noteTagLink " + "WHERE tag_id = :id")); } else if (recursive) { - query.prepare(QStringLiteral( - "SELECT COUNT(note_file_name) AS cnt FROM noteTagLink " - "WHERE tag_id = :id AND " - "note_sub_folder_path LIKE :noteSubFolderPath")); + query.prepare( + QStringLiteral("SELECT COUNT(note_file_name) AS cnt FROM noteTagLink " + "WHERE tag_id = :id AND " + "note_sub_folder_path LIKE :noteSubFolderPath")); query.bindValue(QStringLiteral(":noteSubFolderPath"), noteSubFolder.relativePath() + QLatin1Char('%')); } else { - query.prepare(QStringLiteral( - "SELECT COUNT(note_file_name) AS cnt FROM noteTagLink " - "WHERE tag_id = :id AND " - "note_sub_folder_path = :noteSubFolderPath")); + query.prepare( + QStringLiteral("SELECT COUNT(note_file_name) AS cnt FROM noteTagLink " + "WHERE tag_id = :id AND " + "note_sub_folder_path = :noteSubFolderPath")); query.bindValue(QStringLiteral(":noteSubFolderPath"), noteSubFolder.relativePath() + QLatin1Char('%')); } @@ -908,28 +879,26 @@ int Tag::countLinkedNoteFileNamesForNoteSubFolder( /** * Count the linked note file names */ -int Tag::countLinkedNoteFileNames(int tagId, bool fromAllSubfolders, - bool recursive) { +int Tag::countLinkedNoteFileNames(int tagId, bool fromAllSubfolders, bool recursive) { QSqlDatabase db = DatabaseService::getNoteFolderDatabase(); QSqlQuery query(db); if (fromAllSubfolders) { - query.prepare(QStringLiteral( - "SELECT COUNT(note_file_name) AS cnt FROM noteTagLink " - "WHERE tag_id = :id")); + query.prepare( + QStringLiteral("SELECT COUNT(note_file_name) AS cnt FROM noteTagLink " + "WHERE tag_id = :id")); } else if (recursive) { - query.prepare(QStringLiteral( - "SELECT COUNT(note_file_name) AS cnt FROM noteTagLink " - "WHERE tag_id = :id AND " - "note_sub_folder_path LIKE :noteSubFolderPath")); - query.bindValue( - QStringLiteral(":noteSubFolderPath"), - NoteSubFolder::activeNoteSubFolder().relativePath() + "%"); + query.prepare( + QStringLiteral("SELECT COUNT(note_file_name) AS cnt FROM noteTagLink " + "WHERE tag_id = :id AND " + "note_sub_folder_path LIKE :noteSubFolderPath")); + query.bindValue(QStringLiteral(":noteSubFolderPath"), + NoteSubFolder::activeNoteSubFolder().relativePath() + "%"); } else { - query.prepare(QStringLiteral( - "SELECT COUNT(note_file_name) AS cnt FROM noteTagLink " - "WHERE tag_id = :id AND " - "note_sub_folder_path = :noteSubFolderPath")); + query.prepare( + QStringLiteral("SELECT COUNT(note_file_name) AS cnt FROM noteTagLink " + "WHERE tag_id = :id AND " + "note_sub_folder_path = :noteSubFolderPath")); query.bindValue(QStringLiteral(":noteSubFolderPath"), NoteSubFolder::activeNoteSubFolder().relativePath()); } @@ -959,19 +928,16 @@ bool Tag::store() { const int id = _id; if (id > 0) { - query.prepare( - QStringLiteral("UPDATE tag SET name = :name, priority = :priority, " - "parent_id = :parentId, ") % - colorField % - QStringLiteral(" = :color, " - "updated = datetime('now') " - "WHERE id = :id")); + query.prepare(QStringLiteral("UPDATE tag SET name = :name, priority = :priority, " + "parent_id = :parentId, ") % + colorField % + QStringLiteral(" = :color, " + "updated = datetime('now') " + "WHERE id = :id")); query.bindValue(QStringLiteral(":id"), id); } else { - query.prepare( - QStringLiteral("INSERT INTO tag (name, priority, parent_id, ") % - colorField % - QStringLiteral(") VALUES (:name, :priority, :parentId, :color)")); + query.prepare(QStringLiteral("INSERT INTO tag (name, priority, parent_id, ") % colorField % + QStringLiteral(") VALUES (:name, :priority, :parentId, :color)")); } const int parentId = _parentId; @@ -979,8 +945,7 @@ bool Tag::store() { query.bindValue(QStringLiteral(":name"), _name); query.bindValue(QStringLiteral(":priority"), _priority); query.bindValue(QStringLiteral(":parentId"), parentId); - query.bindValue(QStringLiteral(":color"), - _color.isValid() ? _color.name() : QLatin1String("")); + query.bindValue(QStringLiteral(":color"), _color.isValid() ? _color.name() : QLatin1String("")); if (!query.exec()) { // on error @@ -996,8 +961,7 @@ bool Tag::store() { // update the parent tag for correct sorting by last use if (parentId > 0) { QSqlQuery parentQuery(db); - parentQuery.prepare( - QStringLiteral("SELECT * FROM tag WHERE id = :parentId")); + parentQuery.prepare(QStringLiteral("SELECT * FROM tag WHERE id = :parentId")); parentQuery.bindValue(QStringLiteral(":parentId"), parentId); if (!parentQuery.exec()) { @@ -1022,9 +986,8 @@ bool Tag::store() { * @return */ QString Tag::colorFieldName() const { - return QSettings().value(QStringLiteral("darkMode")).toBool() - ? QStringLiteral("dark_color") - : QStringLiteral("color"); + return QSettings().value(QStringLiteral("darkMode")).toBool() ? QStringLiteral("dark_color") + : QStringLiteral("color"); } /** @@ -1045,8 +1008,7 @@ bool Tag::linkToNote(const Note ¬e) const { query.bindValue(QStringLiteral(":tagId"), _id); query.bindValue(QStringLiteral(":noteFileName"), note.getName()); - query.bindValue(QStringLiteral(":noteSubFolderPath"), - note.getNoteSubFolder().relativePath()); + query.bindValue(QStringLiteral(":noteSubFolderPath"), note.getNoteSubFolder().relativePath()); if (!query.exec()) { // we should not show this warning, because we don't check if a @@ -1061,8 +1023,7 @@ bool Tag::linkToNote(const Note ¬e) const { // update the parent tag for correct sorting by last use if (_parentId > 0) { QSqlQuery parentQuery(db); - parentQuery.prepare( - QStringLiteral("SELECT * FROM tag WHERE id = :parentId")); + parentQuery.prepare(QStringLiteral("SELECT * FROM tag WHERE id = :parentId")); parentQuery.bindValue(QStringLiteral(":parentId"), _parentId); if (!parentQuery.exec()) { @@ -1097,8 +1058,7 @@ bool Tag::removeLinkToNote(const Note ¬e) const { query.bindValue(QStringLiteral(":tagId"), _id); query.bindValue(QStringLiteral(":noteFileName"), note.getName()); - query.bindValue(QStringLiteral(":noteSubFolderPath"), - note.getNoteSubFolder().relativePath()); + query.bindValue(QStringLiteral(":noteSubFolderPath"), note.getNoteSubFolder().relativePath()); if (!query.exec()) { // on error @@ -1126,8 +1086,7 @@ bool Tag::removeAllLinksToNote(const Note ¬e) { "note_sub_folder_path = :noteSubFolderPath")); query.bindValue(QStringLiteral(":noteFileName"), note.getName()); - query.bindValue(QStringLiteral(":noteSubFolderPath"), - note.getNoteSubFolder().relativePath()); + query.bindValue(QStringLiteral(":noteSubFolderPath"), note.getNoteSubFolder().relativePath()); if (!query.exec()) { // on error @@ -1190,13 +1149,12 @@ void Tag::removeBrokenLinks() { } Note Tag::getNoteFromNoteTagLinkQuery(const QSqlQuery &query) { - const QString noteFileName = - query.value(QStringLiteral("note_file_name")).toString(); + const QString noteFileName = query.value(QStringLiteral("note_file_name")).toString(); const QString noteSubFolderPath = query.value(QStringLiteral("note_sub_folder_path")).toString(); - const NoteSubFolder noteSubFolder = NoteSubFolder::fetchByPathData( - noteSubFolderPath, QStringLiteral("/")); + const NoteSubFolder noteSubFolder = + NoteSubFolder::fetchByPathData(noteSubFolderPath, QStringLiteral("/")); return Note::fetchByName(noteFileName, noteSubFolder.getId()); } @@ -1234,7 +1192,8 @@ bool Tag::removeNoteLinkById(int id) { bool Tag::setNoteLinkByIdStale(int id) { QSqlDatabase db = DatabaseService::getNoteFolderDatabase(); QSqlQuery query(db); - query.prepare(QStringLiteral("UPDATE noteTagLink SET stale_date = :date WHERE id = :id AND stale_date IS NULL")); + query.prepare(QStringLiteral( + "UPDATE noteTagLink SET stale_date = :date WHERE id = :id AND stale_date IS NULL")); query.bindValue(QStringLiteral(":id"), id); query.bindValue(QStringLiteral(":date"), QDateTime::currentDateTime()); @@ -1300,20 +1259,18 @@ bool Tag::removeExpiredStaleNoteLinkBy() { /** * Renames the note file name of note links */ -bool Tag::renameNoteFileNamesOfLinks(const QString &oldFileName, - const QString &newFileName, +bool Tag::renameNoteFileNamesOfLinks(const QString &oldFileName, const QString &newFileName, const NoteSubFolder ¬eSubFolder) { QSqlDatabase db = DatabaseService::getNoteFolderDatabase(); QSqlQuery query(db); - query.prepare(QStringLiteral( - "UPDATE noteTagLink SET note_file_name = :newFileName WHERE " - "note_file_name = :oldFileName AND " - "note_sub_folder_path = :noteSubFolderPath")); + query.prepare( + QStringLiteral("UPDATE noteTagLink SET note_file_name = :newFileName WHERE " + "note_file_name = :oldFileName AND " + "note_sub_folder_path = :noteSubFolderPath")); query.bindValue(QStringLiteral(":oldFileName"), oldFileName); query.bindValue(QStringLiteral(":newFileName"), newFileName); - query.bindValue(QStringLiteral(":noteSubFolderPath"), - noteSubFolder.relativePath()); + query.bindValue(QStringLiteral(":noteSubFolderPath"), noteSubFolder.relativePath()); if (!query.exec()) { // on error @@ -1331,14 +1288,13 @@ bool Tag::renameNoteFileNamesOfLinks(const QString &oldFileName, /** * Renames the note sub folder paths of note links */ -bool Tag::renameNoteSubFolderPathsOfLinks(const QString &oldPath, - const QString &newPath) { +bool Tag::renameNoteSubFolderPathsOfLinks(const QString &oldPath, const QString &newPath) { QSqlDatabase db = DatabaseService::getNoteFolderDatabase(); QSqlQuery query(db); - query.prepare(QStringLiteral( - "UPDATE noteTagLink SET note_sub_folder_path = " - "replace(note_sub_folder_path, :oldPath, :newPath) WHERE " - "note_sub_folder_path LIKE :oldPathLike")); + query.prepare( + QStringLiteral("UPDATE noteTagLink SET note_sub_folder_path = " + "replace(note_sub_folder_path, :oldPath, :newPath) WHERE " + "note_sub_folder_path LIKE :oldPathLike")); query.bindValue(QStringLiteral(":oldPath"), oldPath); query.bindValue(QStringLiteral(":oldPathLike"), oldPath + "%"); @@ -1426,14 +1382,11 @@ bool Tag::mergeFromDatabase(QSqlDatabase &db) { const bool isSameTagTable = DatabaseService::generateDatabaseTableSha1Signature(db, "tag") == - DatabaseService::generateDatabaseTableSha1Signature(noteFolderDB, - "tag"); + DatabaseService::generateDatabaseTableSha1Signature(noteFolderDB, "tag"); const bool isSameNoteTagLinkTable = - DatabaseService::generateDatabaseTableSha1Signature(db, - "noteTagLink") == - DatabaseService::generateDatabaseTableSha1Signature(noteFolderDB, - "noteTagLink"); + DatabaseService::generateDatabaseTableSha1Signature(db, "noteTagLink") == + DatabaseService::generateDatabaseTableSha1Signature(noteFolderDB, "noteTagLink"); // if those tables are the same everything is ok if (isSameTagTable && isSameNoteTagLinkTable) { @@ -1457,8 +1410,7 @@ bool Tag::mergeFromDatabase(QSqlDatabase &db) { * created * @return Tag object of deepest tag of the name breadcrumb list */ -Tag Tag::getTagByNameBreadcrumbList(const QStringList &nameList, - bool createMissing) { +Tag Tag::getTagByNameBreadcrumbList(const QStringList &nameList, bool createMissing) { int parentId = 0; Tag tag; @@ -1488,7 +1440,7 @@ bool Tag::operator==(const Tag &tag) const { return _id == tag._id; } bool Tag::operator<(const Tag &tag) const { return _name < tag._name; } QDebug operator<<(QDebug dbg, const Tag &tag) { - dbg.nospace() << "Tag: <id>" << tag._id << " <name>" << tag._name - << " <parentId>" << tag._parentId; + dbg.nospace() << "Tag: <id>" << tag._id << " <name>" << tag._name << " <parentId>" + << tag._parentId; return dbg.space(); } diff --git a/src/entities/tag.h b/src/entities/tag.h index d32835731..ba1e1bea9 100644 --- a/src/entities/tag.h +++ b/src/entities/tag.h @@ -10,7 +10,7 @@ class NoteSubFolder; struct TagHeader { TagHeader() = default; - TagHeader(int id, QString name) : _id {id}, _name{std::move(name)} {} + TagHeader(int id, QString name) : _id{id}, _name{std::move(name)} {} int _id = 0; QString _name{QLatin1String("")}; @@ -36,7 +36,7 @@ class Tag : protected TagHeader { inline int getId() const { return _id; } - inline const QString& getName() const { return _name; } + inline const QString &getName() const { return _name; } inline void setName(QString text) { _name = text; } @@ -50,7 +50,6 @@ class Tag : protected TagHeader { bool isFetched() const; - int getPriority() const; void setPriority(const int value); @@ -63,25 +62,23 @@ class Tag : protected TagHeader { bool removeLinkToNote(const Note ¬e) const; - static QVector<int> fetchAllLinkedNoteIds(int tagId, - const bool fromAllSubfolders, - const bool recursive = true); + static QVector<int> fetchAllLinkedNoteIds(int tagId, const bool fromAllSubfolders, + const bool recursive = true); - static QVector<int> fetchAllLinkedNoteIdsForFolder( - int tagId, - const NoteSubFolder ¬eSubFolder, bool fromAllSubfolders, - const bool recursive = true); + static QVector<int> fetchAllLinkedNoteIdsForFolder(int tagId, + const NoteSubFolder ¬eSubFolder, + bool fromAllSubfolders, + const bool recursive = true); QVector<Note> fetchAllLinkedNotes() const; bool isLinkedToNote(const Note ¬e) const; - static int countLinkedNoteFileNames(int tagId, bool fromAllSubfolders, - bool recursive); + static int countLinkedNoteFileNames(int tagId, bool fromAllSubfolders, bool recursive); - static int countLinkedNoteFileNamesForNoteSubFolder( - int tagId, const NoteSubFolder ¬eSubFolder, - bool fromAllSubfolders, bool recursive); + static int countLinkedNoteFileNamesForNoteSubFolder(int tagId, + const NoteSubFolder ¬eSubFolder, + bool fromAllSubfolders, bool recursive); int getParentId() const; @@ -116,31 +113,27 @@ class Tag : protected TagHeader { static bool removeAllLinksToNote(const Note ¬e); - static bool renameNoteFileNamesOfLinks(const QString &oldFileName, - const QString &newFileName, + static bool renameNoteFileNamesOfLinks(const QString &oldFileName, const QString &newFileName, const NoteSubFolder ¬eSubFolder); - static bool renameNoteSubFolderPathsOfLinks(const QString &oldPath, - const QString &newPath); + static bool renameNoteSubFolderPathsOfLinks(const QString &oldPath, const QString &newPath); static Tag fetch(const int id); static Tag tagFromQuery(const QSqlQuery &query); - static QVector<Tag> fetchAllWithLinkToNoteNames( - const QStringList ¬eNameList); + static QVector<Tag> fetchAllWithLinkToNoteNames(const QStringList ¬eNameList); static QVector<TagHeader> fetchAllTagHeadersByParentId(const int parentId); - static QVector<Tag> fetchAllByParentId( - const int parentId, - const QString &sortBy = QStringLiteral("created DESC")); + static QVector<Tag> fetchAllByParentId(const int parentId, + const QString &sortBy = QStringLiteral("created DESC")); static QVector<int> fetchAllIdsByParentId(const int parentId); static int countAllParentId(const int parentId); - static bool noteHasTags(const Note ¬e, const QString& path); + static bool noteHasTags(const Note ¬e, const QString &path); static void setAsActive(const int tagId); @@ -170,10 +163,9 @@ class Tag : protected TagHeader { static bool mergeFromDatabase(QSqlDatabase &db); - static Tag getTagByNameBreadcrumbList(const QStringList &nameList, - bool createMissing); + static Tag getTagByNameBreadcrumbList(const QStringList &nameList, bool createMissing); -protected: + protected: int _parentId; int _priority; QColor _color; diff --git a/src/entities/trashitem.cpp b/src/entities/trashitem.cpp index 71f0e8685..4fad73430 100644 --- a/src/entities/trashitem.cpp +++ b/src/entities/trashitem.cpp @@ -30,9 +30,7 @@ qint64 TrashItem::getFileSize() { return this->fileSize; } QString TrashItem::getFileName() { return this->fileName; } -NoteSubFolder TrashItem::getNoteSubFolder() { - return NoteSubFolder::fetch(this->noteSubFolderId); -} +NoteSubFolder TrashItem::getNoteSubFolder() { return NoteSubFolder::fetch(this->noteSubFolderId); } void TrashItem::setNoteSubFolder(const NoteSubFolder ¬eSubFolder) { this->noteSubFolderPathData = noteSubFolder.pathData(); @@ -84,8 +82,7 @@ bool TrashItem::remove(bool withFile) { * Returns the full path of the trashed file */ QString TrashItem::fullFilePath() { - return NoteFolder::currentTrashPath() + QDir::separator() + - QString::number(getId()); + return NoteFolder::currentTrashPath() + QDir::separator() + QString::number(getId()); } /** @@ -158,8 +155,7 @@ bool TrashItem::doTrashing() { QDir destinationDir(destinationPath); // created the trash folder if it doesn't exist - if (!destinationDir.exists() && - !destinationDir.mkpath(destinationDir.path())) { + if (!destinationDir.exists() && !destinationDir.mkpath(destinationDir.path())) { return false; } @@ -211,8 +207,7 @@ QString TrashItem::restorationFilePath() { // prepend the current timestamp if the file already exists if (file.exists()) { filePath = folderPath + QDir::separator() + - QString::number(QDateTime::currentMSecsSinceEpoch() / 1000) + - "_" + fileName; + QString::number(QDateTime::currentMSecsSinceEpoch() / 1000) + "_" + fileName; } file.setFileName(filePath); @@ -224,8 +219,7 @@ QString TrashItem::restorationFilePath() { const quint32 number = QRandomGenerator::global()->generate(); #endif - filePath = folderPath + QDir::separator() + QString::number(number) + - "_" + fileName; + filePath = folderPath + QDir::separator() + QString::number(number) + "_" + fileName; } file.setFileName(filePath); @@ -255,8 +249,7 @@ TrashItem TrashItem::trashItemFromQuery(const QSqlQuery &query) { bool TrashItem::fillFromQuery(const QSqlQuery &query) { id = query.value(QStringLiteral("id")).toInt(); fileName = query.value(QStringLiteral("file_name")).toString(); - noteSubFolderPathData = - query.value(QStringLiteral("note_sub_folder_path_data")).toString(); + noteSubFolderPathData = query.value(QStringLiteral("note_sub_folder_path_data")).toString(); fileSize = query.value(QStringLiteral("file_size")).toLongLong(); created = query.value(QStringLiteral("created")).toDateTime(); @@ -273,8 +266,7 @@ QList<TrashItem> TrashItem::fetchAll(int limit) { QSqlQuery query(db); QList<TrashItem> trashItemList; - QString sql = - QStringLiteral("SELECT * FROM trashItem ORDER BY created DESC"); + QString sql = QStringLiteral("SELECT * FROM trashItem ORDER BY created DESC"); if (limit >= 0) { sql += QLatin1String(" LIMIT :limit"); @@ -309,8 +301,7 @@ QList<TrashItem> TrashItem::fetchAllExpired() { QSqlQuery query(db); QSettings settings; QList<TrashItem> trashItemList; - int days = settings.value(QStringLiteral("localTrash/autoCleanupDays"), 30) - .toInt(); + int days = settings.value(QStringLiteral("localTrash/autoCleanupDays"), 30).toInt(); QDateTime dateTime = QDateTime::currentDateTime().addDays(-1 * days); QString sql = "SELECT * FROM trashItem WHERE created < :created " @@ -363,8 +354,7 @@ bool TrashItem::store() { query.bindValue(QStringLiteral(":file_name"), fileName); query.bindValue(QStringLiteral(":file_size"), fileSize); - query.bindValue(QStringLiteral(":note_sub_folder_path_data"), - noteSubFolderPathData); + query.bindValue(QStringLiteral(":note_sub_folder_path_data"), noteSubFolderPathData); // on error if (!query.exec()) { @@ -524,8 +514,7 @@ int TrashItem::countAll() { bool TrashItem::isLocalTrashEnabled() { QSettings settings; - return settings.value(QStringLiteral("localTrash/supportEnabled"), true) - .toBool(); + return settings.value(QStringLiteral("localTrash/supportEnabled"), true).toBool(); } /** @@ -537,8 +526,7 @@ bool TrashItem::expireItems() { QSettings settings; if (!TrashItem::isLocalTrashEnabled() || - !settings.value(QStringLiteral("localTrash/autoCleanupEnabled"), true) - .toBool()) { + !settings.value(QStringLiteral("localTrash/autoCleanupEnabled"), true).toBool()) { return false; } @@ -555,11 +543,9 @@ bool TrashItem::expireItems() { } QDebug operator<<(QDebug dbg, const TrashItem &trashItem) { - NoteSubFolder noteSubFolder = - NoteSubFolder::fetchByPathData(trashItem.noteSubFolderPathData); - dbg.nospace() << "TrashItem: <id>" << trashItem.id << " <fileName>" - << trashItem.fileName << " <noteSubFolderId>" - << trashItem.noteSubFolderId << " <_fullNoteFilePath>" + NoteSubFolder noteSubFolder = NoteSubFolder::fetchByPathData(trashItem.noteSubFolderPathData); + dbg.nospace() << "TrashItem: <id>" << trashItem.id << " <fileName>" << trashItem.fileName + << " <noteSubFolderId>" << trashItem.noteSubFolderId << " <_fullNoteFilePath>" << trashItem._fullNoteFilePath << " <relativePath>" << noteSubFolder.relativePath(); return dbg.space(); diff --git a/src/helpers/LanguageCache.h b/src/helpers/LanguageCache.h index 039c13b4f..8d6bf60dc 100644 --- a/src/helpers/LanguageCache.h +++ b/src/helpers/LanguageCache.h @@ -31,8 +31,7 @@ class LanguageCache : public QTextBlockUserData { QMapIterator<QPair<int, int>, QString> it(languages); while (it.hasNext()) { it.next(); - if (it.key().first <= pos && - it.key().first + it.key().second >= pos) { + if (it.key().first <= pos && it.key().first + it.key().second >= pos) { return it.value(); } } diff --git a/src/helpers/clientproxy.cpp b/src/helpers/clientproxy.cpp index 6b47b58b8..621ba620e 100644 --- a/src/helpers/clientproxy.cpp +++ b/src/helpers/clientproxy.cpp @@ -12,30 +12,24 @@ ClientProxy::ClientProxy(QObject *parent) : QObject(parent) {} QNetworkProxy ClientProxy::proxyFromSettings() { QNetworkProxy proxy; QSettings settings; - QString proxyHostName = - settings.value(QStringLiteral("networking/proxyHostName")).toString(); + QString proxyHostName = settings.value(QStringLiteral("networking/proxyHostName")).toString(); if (proxyHostName.isEmpty()) { return QNetworkProxy(); } - int proxyPort = - settings.value(QStringLiteral("networking/proxyPort")).toInt(); - int proxyNeedsAuth = - settings.value(QStringLiteral("networking/proxyNeedsAuth")).toBool(); + int proxyPort = settings.value(QStringLiteral("networking/proxyPort")).toInt(); + int proxyNeedsAuth = settings.value(QStringLiteral("networking/proxyNeedsAuth")).toBool(); proxy.setHostName(proxyHostName); proxy.setPort(proxyPort); if (proxyNeedsAuth) { - QString proxyUser = - settings.value(QStringLiteral("networking/proxyUser")).toString(); + QString proxyUser = settings.value(QStringLiteral("networking/proxyUser")).toString(); QString proxyPassword = - settings.value(QStringLiteral("networking/proxyPassword")) - .toString(); + settings.value(QStringLiteral("networking/proxyPassword")).toString(); proxy.setUser(proxyUser); - proxy.setPassword( - CryptoService::instance()->decryptToString(proxyPassword)); + proxy.setPassword(CryptoService::instance()->decryptToString(proxyPassword)); } return proxy; @@ -43,26 +37,19 @@ QNetworkProxy ClientProxy::proxyFromSettings() { bool ClientProxy::isUsingSystemDefault() { QSettings settings; - int proxyType = settings - .value(QStringLiteral("networking/proxyType"), - QNetworkProxy::NoProxy) - .toInt(); + int proxyType = + settings.value(QStringLiteral("networking/proxyType"), QNetworkProxy::NoProxy).toInt(); return proxyType == QNetworkProxy::DefaultProxy; } QString printQNetworkProxy(const QNetworkProxy &proxy) { - return QStringLiteral("%1://%2:%3") - .arg(proxy.type()) - .arg(proxy.hostName()) - .arg(proxy.port()); + return QStringLiteral("%1://%2:%3").arg(proxy.type()).arg(proxy.hostName()).arg(proxy.port()); } void ClientProxy::setupQtProxyFromSettings() { QSettings settings; - int proxyType = settings - .value(QStringLiteral("networking/proxyType"), - QNetworkProxy::NoProxy) - .toInt(); + int proxyType = + settings.value(QStringLiteral("networking/proxyType"), QNetworkProxy::NoProxy).toInt(); QNetworkProxy proxy = proxyFromSettings(); switch (proxyType) { @@ -77,15 +64,13 @@ void ClientProxy::setupQtProxyFromSettings() { break; case QNetworkProxy::Socks5Proxy: proxy.setType(QNetworkProxy::Socks5Proxy); - qDebug() << "Set proxy configuration to SOCKS5" - << printQNetworkProxy(proxy); + qDebug() << "Set proxy configuration to SOCKS5" << printQNetworkProxy(proxy); QNetworkProxyFactory::setUseSystemConfiguration(false); QNetworkProxy::setApplicationProxy(proxy); break; case QNetworkProxy::HttpProxy: proxy.setType(QNetworkProxy::HttpProxy); - qDebug() << "Set proxy configuration to HTTP" - << printQNetworkProxy(proxy); + qDebug() << "Set proxy configuration to HTTP" << printQNetworkProxy(proxy); QNetworkProxyFactory::setUseSystemConfiguration(false); QNetworkProxy::setApplicationProxy(proxy); break; @@ -114,18 +99,15 @@ const char *ClientProxy::proxyTypeToCStr(QNetworkProxy::ProxyType type) { } } -void ClientProxy::lookupSystemProxyAsync(const QUrl &url, QObject *dst, - const char *slot) { +void ClientProxy::lookupSystemProxyAsync(const QUrl &url, QObject *dst, const char *slot) { auto *runnable = new SystemProxyRunnable(url); - QObject::connect(runnable, SIGNAL(systemProxyLookedUp(QNetworkProxy)), dst, - slot); + QObject::connect(runnable, SIGNAL(systemProxyLookedUp(QNetworkProxy)), dst, slot); // takes ownership and deletes QThreadPool::globalInstance()->start(runnable); } -SystemProxyRunnable::SystemProxyRunnable(QUrl url) - : QObject(), QRunnable(), _url(std::move(url)) {} +SystemProxyRunnable::SystemProxyRunnable(QUrl url) : QObject(), QRunnable(), _url(std::move(url)) {} void SystemProxyRunnable::run() { qDebug() << Q_FUNC_INFO << "Starting system proxy lookup"; diff --git a/src/helpers/clientproxy.h b/src/helpers/clientproxy.h index 20de45089..776a9a92c 100644 --- a/src/helpers/clientproxy.h +++ b/src/helpers/clientproxy.h @@ -14,8 +14,7 @@ class ClientProxy : public QObject { explicit ClientProxy(QObject *parent = 0); static bool isUsingSystemDefault(); - static void lookupSystemProxyAsync(const QUrl &url, QObject *dst, - const char *slot); + static void lookupSystemProxyAsync(const QUrl &url, QObject *dst, const char *slot); static QNetworkProxy proxyFromSettings(); public slots: diff --git a/src/helpers/codetohtmlconverter.cpp b/src/helpers/codetohtmlconverter.cpp index 29415da01..63ae43fca 100644 --- a/src/helpers/codetohtmlconverter.cpp +++ b/src/helpers/codetohtmlconverter.cpp @@ -1,13 +1,12 @@ #include "codetohtmlconverter.h" +#include <QDebug> #include <QStringBuilder> #include <QtCore/QRegularExpression> -#include <QDebug> #include "libraries/qmarkdowntextedit/qownlanguagedata.h" -QHash<QString, CodeToHtmlConverter::Lang> - CodeToHtmlConverter::_langStringToEnum; +QHash<QString, CodeToHtmlConverter::Lang> CodeToHtmlConverter::_langStringToEnum; CodeToHtmlConverter::CodeToHtmlConverter(const QString &lang) Q_DECL_NOTHROW { if (_langStringToEnum.isEmpty()) initCodeLangs(); @@ -54,10 +53,12 @@ void CodeToHtmlConverter::initCodeLangs() Q_DECL_NOTHROW { QString CodeToHtmlConverter::process(const QString &input) const { #if QT_VERSION >= QT_VERSION_CHECK(5, 15, 0) - qDebug() << "Going to highlight input:" << StringView(input).mid(0, 12) << ", with lang:" << _currentLang; + qDebug() << "Going to highlight input:" << StringView(input).mid(0, 12) + << ", with lang:" << _currentLang; return process(StringView(input)); #else - qDebug() << "Going to highlight input:" << StringView(&input).mid(0, 12) << ", with lang:" << _currentLang; + qDebug() << "Going to highlight input:" << StringView(&input).mid(0, 12) + << ", with lang:" << _currentLang; return process(StringView(&input)); #endif } @@ -157,14 +158,12 @@ QString CodeToHtmlConverter::process(StringView input) const { for (int i = 0; i < textLen; ++i) { if (input.at(i) == QLatin1Char(' ')) { output += (QLatin1Char(' ')); - } else if (input.at(i) == QLatin1Char('\'') || - input.at(i) == QLatin1Char('"')) { + } else if (input.at(i) == QLatin1Char('\'') || input.at(i) == QLatin1Char('"')) { i = highlightStringLiterals(input, input.at(i), output, i); } else if (input.at(i).isDigit()) { i = highlightNumericLit(input, output, i); } else if (comment.isNull() && input.at(i) == QLatin1Char('/')) { - if (input.at(i + 1) == QLatin1Char('/')) - i = highlightComment(input, output, i); + if (input.at(i + 1) == QLatin1Char('/')) i = highlightComment(input, output, i); // Multiline comment i.e /* */ else if (input.at(i + 1) == QLatin1Char('*')) i = highlightComment(input, output, i, false); @@ -172,8 +171,7 @@ QString CodeToHtmlConverter::process(StringView input) const { output += escape(input.at(i)); } else if (input.at(i) == comment) { i = highlightComment(input, output, i); - } else if (input.at(i) == QLatin1Char('<') || - input.at(i) == QLatin1Char('>') || + } else if (input.at(i) == QLatin1Char('<') || input.at(i) == QLatin1Char('>') || input.at(i) == QLatin1Char('&')) { output += escape(input.at(i)); } else if (input.at(i).isLetter()) { @@ -227,8 +225,7 @@ QString CodeToHtmlConverter::process(StringView input) const { return output; } -int CodeToHtmlConverter::highlightNumericLit(StringView input, QString &output, - int i) const { +int CodeToHtmlConverter::highlightNumericLit(StringView input, QString &output, int i) const { bool isPreAllowed = false; if (i == 0) isPreAllowed = true; @@ -274,8 +271,7 @@ int CodeToHtmlConverter::highlightNumericLit(StringView input, QString &output, ++i; // hex numbers highlighting (only if there's a preceding zero) - if (input.at(i) == QLatin1Char('x') && input.at(i - 1) == QLatin1Char('0')) - ++i; + if (input.at(i) == QLatin1Char('x') && input.at(i - 1) == QLatin1Char('0')) ++i; // unroll till we find a non number while (i < input.length()) { @@ -310,19 +306,15 @@ int CodeToHtmlConverter::highlightNumericLit(StringView input, QString &output, isPostAllowed = true; break; case 'p': - if (_currentLang == CodeCSS && - input.at(i + 2) == QLatin1Char('x')) - if ((i + 3 < input.length()) && - (input.at(i + 3) == QLatin1Char(';') || - input.at(i + 3) == QLatin1Char('\n'))) + if (_currentLang == CodeCSS && input.at(i + 2) == QLatin1Char('x')) + if ((i + 3 < input.length()) && (input.at(i + 3) == QLatin1Char(';') || + input.at(i + 3) == QLatin1Char('\n'))) isPostAllowed = true; break; case 'e': - if (_currentLang == CodeCSS && - input.at(i + 2) == QLatin1Char('m')) - if ((i + 3 < input.length()) && - (input.at(i + 3) == QLatin1Char(';') || - input.at(i + 3) == QLatin1Char('\n'))) + if (_currentLang == CodeCSS && input.at(i + 2) == QLatin1Char('m')) + if ((i + 3 < input.length()) && (input.at(i + 3) == QLatin1Char(';') || + input.at(i + 3) == QLatin1Char('\n'))) isPostAllowed = true; break; // for 100u, 1.0F @@ -357,8 +349,7 @@ int CodeToHtmlConverter::highlightNumericLit(StringView input, QString &output, } } -int CodeToHtmlConverter::highlightStringLiterals(StringView input, - QChar strType, QString &output, +int CodeToHtmlConverter::highlightStringLiterals(StringView input, QChar strType, QString &output, int i) { int start = i; ++i; @@ -400,11 +391,10 @@ int CodeToHtmlConverter::highlightStringLiterals(StringView input, case '6': case '7': { if (i + 4 <= input.length()) { - const bool isCurrentOctal = - (isOctal(input.at(i + 2).toLatin1()) && - isOctal(input.at(i + 3).toLatin1())) - ? true - : false; + const bool isCurrentOctal = (isOctal(input.at(i + 2).toLatin1()) && + isOctal(input.at(i + 3).toLatin1())) + ? true + : false; if (!isCurrentOctal) break; len = isCurrentOctal ? 4 : 0; } @@ -414,8 +404,7 @@ int CodeToHtmlConverter::highlightStringLiterals(StringView input, case 'x': { if (i + 3 <= input.length()) { const bool isCurrentHex = - (isHex(input.at(i + 2).toLatin1()) && - isHex(input.at(i + 3).toLatin1())) + (isHex(input.at(i + 2).toLatin1()) && isHex(input.at(i + 3).toLatin1())) ? true : false; if (!isCurrentHex) break; @@ -447,7 +436,8 @@ int CodeToHtmlConverter::highlightStringLiterals(StringView input, ++i; } - if (!input.isEmpty() && i >= input.length() && input.at(input.length() - 1) == QLatin1Char('\n')) { + if (!input.isEmpty() && i >= input.length() && + input.at(input.length() - 1) == QLatin1Char('\n')) { // move one position backwards, we want to insert </span> so // that it's like </span>\n and not \n</span> i.e., new line // should be after @@ -457,14 +447,15 @@ int CodeToHtmlConverter::highlightStringLiterals(StringView input, // decrement i, this ensures that // - if current pos wasn't a string we are back to the string start char - // - if it was a string, we will be at string end char thus not skipping the next character in the next loop iteration + // - if it was a string, we will be at string end char thus not skipping the next character in + // the next loop iteration --i; return i; } -int CodeToHtmlConverter::highlightComment(StringView input, QString &output, - int i, bool isSingleLine) { +int CodeToHtmlConverter::highlightComment(StringView input, QString &output, int i, + bool isSingleLine) { int endPos = -1; if (isSingleLine) { endPos = input.indexOf(QLatin1Char('\n'), i); @@ -485,14 +476,12 @@ int CodeToHtmlConverter::highlightComment(StringView input, QString &output, return i; } -int CodeToHtmlConverter::highlightWord(int i, const LangData &data, - StringView input, QString &output, - CodeToHtmlConverter::Format f) { +int CodeToHtmlConverter::highlightWord(int i, const LangData &data, StringView input, + QString &output, CodeToHtmlConverter::Format f) { if (data.isEmpty()) return i; // check if we are at the beginning OR if this is the start of a word // AND the current char is present in the data structure - if (i == 0 || (!input.at(i - 1).isLetterOrNumber() && - input.at(i - 1) != QLatin1Char('_'))) { + if (i == 0 || (!input.at(i - 1).isLetterOrNumber() && input.at(i - 1) != QLatin1Char('_'))) { const auto wordList = data.values(input.at(i).toLatin1()); for (const auto &word : wordList) { if (word == input.mid(i, word.size())) { @@ -515,8 +504,7 @@ QString CodeToHtmlConverter::xmlHighlighter(StringView input) const { QString output = QLatin1String(""); for (int i = 0; i < textLen; ++i) { - if (input.at(i) == QLatin1Char('<') && - input.at(i + 1) != QLatin1Char('!')) { + if (input.at(i) == QLatin1Char('<') && input.at(i + 1) != QLatin1Char('!')) { const int found = input.indexOf(QLatin1Char('>'), i); if (found > 0) { output += escape(input.at(i)); @@ -539,10 +527,9 @@ QString CodeToHtmlConverter::xmlHighlighter(StringView input) const { output += setFormat(captured, Format::Builtin); } else { int eqPos = captured.indexOf(QLatin1Char('=')); - output += - setFormat(captured.left(eqPos), Format::Builtin) + "=" + - setFormat(captured.mid(eqPos + 1, captured.length() - eqPos - 1), - Format::String); + output += setFormat(captured.left(eqPos), Format::Builtin) + "=" + + setFormat(captured.mid(eqPos + 1, captured.length() - eqPos - 1), + Format::String); } if (matchIt.hasNext()) { @@ -556,8 +543,7 @@ QString CodeToHtmlConverter::xmlHighlighter(StringView input) const { } } - else if (input.at(i) == QLatin1Char('\"') || - input.at(i) == QLatin1Char('\'')) { + else if (input.at(i) == QLatin1Char('\"') || input.at(i) == QLatin1Char('\'')) { // find the next end of string int next = input.indexOf(input.at(i), i + 1); bool isEndline = false; @@ -584,8 +570,7 @@ QString CodeToHtmlConverter::xmlHighlighter(StringView input) const { * @brief CSS highlighter * @return */ -QString CodeToHtmlConverter::cssHighlighter(StringView input, - const LangData &types, +QString CodeToHtmlConverter::cssHighlighter(StringView input, const LangData &types, const LangData &keywords) const { if (input.isEmpty()) return QLatin1String(""); const auto textLen = input.length(); @@ -596,8 +581,7 @@ QString CodeToHtmlConverter::cssHighlighter(StringView input, for (int i = 0; i < textLen; ++i) { if (input.at(i) == QLatin1Char(' ')) { output += (QLatin1Char(' ')); - } else if (input.at(i) == QLatin1Char('.') || - input.at(i) == QLatin1Char('#')) { + } else if (input.at(i) == QLatin1Char('.') || input.at(i) == QLatin1Char('#')) { if (input.at(i + 1).isSpace() || input.at(i + 1).isNumber()) { output += input.at(i); continue; @@ -609,8 +593,7 @@ QString CodeToHtmlConverter::cssHighlighter(StringView input, output += setFormat(input.mid(i, bracketOpen - i), Format::Keyword); i = bracketOpen; output += input.at(i); - } else if (input.at(i) == QLatin1Char('\'') || - input.at(i) == QLatin1Char('"')) { + } else if (input.at(i) == QLatin1Char('\'') || input.at(i) == QLatin1Char('"')) { i = highlightStringLiterals(input, input.at(i), output, i); // escape text at i, otherwise it gets skipped and won't be present // in output @@ -624,8 +607,7 @@ QString CodeToHtmlConverter::cssHighlighter(StringView input, i = highlightComment(input, output, i, false); else output += escape(input.at(i)); - } else if (input.at(i) == QLatin1Char('<') || - input.at(i) == QLatin1Char('>') || + } else if (input.at(i) == QLatin1Char('<') || input.at(i) == QLatin1Char('>') || input.at(i) == QLatin1Char('&')) { output += escape(input.at(i)); } else if (input.at(i).isLetter()) { @@ -674,8 +656,7 @@ QString CodeToHtmlConverter::ymlHighlighter(StringView input) const { for (int i = 0; i < textLen; ++i) { // we found a string literal - if (input.at(i) == QLatin1Char('"') || - input.at(i) == QLatin1Char('\'')) { + if (input.at(i) == QLatin1Char('"') || input.at(i) == QLatin1Char('\'')) { i = highlightStringLiterals(input, input.at(i), output, i); } else if (input.at(i) == QLatin1Char('#')) { i = highlightComment(input, output, i); @@ -684,8 +665,7 @@ QString CodeToHtmlConverter::ymlHighlighter(StringView input) const { if (colon > 0) { // move i to the beginning of the word int cursor = i; - while (cursor < textLen && !input.at(cursor).isLetter()) - ++cursor; + while (cursor < textLen && !input.at(cursor).isLetter()) ++cursor; // add this to output output += escapeString(input.mid(i, cursor - i)); i = cursor; @@ -702,13 +682,11 @@ QString CodeToHtmlConverter::ymlHighlighter(StringView input) const { // advance i i = hashPos; // then add the comment - output += setFormat(input.mid(i, endLine - i), - Format::Comment); + output += setFormat(input.mid(i, endLine - i), Format::Comment); i = endLine; } - if (i != endLine) - output += escapeString(input.mid(i, endLine - i)); + if (i != endLine) output += escapeString(input.mid(i, endLine - i)); i = endLine; } } @@ -749,11 +727,10 @@ QString CodeToHtmlConverter::iniHighlighter(StringView input) const { } // key-val - else if (i == 0 || (input.at(i) == QLatin1Char('\n') && - i + 1 < textLen && input.at(i + 1).isLetter())) { + else if (i == 0 || (input.at(i) == QLatin1Char('\n') && i + 1 < textLen && + input.at(i + 1).isLetter())) { int equalsPos = input.indexOf(QLatin1Char('='), i); - if (equalsPos == -1) - equalsPos = input.indexOf(QLatin1Char('\n'), i); + if (equalsPos == -1) equalsPos = input.indexOf(QLatin1Char('\n'), i); output += setFormat(input.mid(i, equalsPos - i), Format::Keyword); i = equalsPos; output += escape(input.at(i)); @@ -801,37 +778,35 @@ QString CodeToHtmlConverter::escapeString(StringView s) { return ret; } -QString CodeToHtmlConverter::setFormat(StringView str, - CodeToHtmlConverter::Format format) { +QString CodeToHtmlConverter::setFormat(StringView str, CodeToHtmlConverter::Format format) { switch (format) { case Type: - return QStringLiteral("<span class=\"code-type\">") % - escapeString(str) % QStringLiteral("</span>"); + return QStringLiteral("<span class=\"code-type\">") % escapeString(str) % + QStringLiteral("</span>"); case Keyword: - return QStringLiteral("<span class=\"code-keyword\">") % - escapeString(str) % QStringLiteral("</span>"); + return QStringLiteral("<span class=\"code-keyword\">") % escapeString(str) % + QStringLiteral("</span>"); case Literal: - return QStringLiteral("<span class=\"code-literal\">") % - escapeString(str) % QStringLiteral("</span>"); + return QStringLiteral("<span class=\"code-literal\">") % escapeString(str) % + QStringLiteral("</span>"); case String: - return QStringLiteral("<span class=\"code-string\">") % - escapeString(str) % QStringLiteral("</span>"); + return QStringLiteral("<span class=\"code-string\">") % escapeString(str) % + QStringLiteral("</span>"); case Builtin: - return QStringLiteral("<span class=\"code-builtin\">") % - escapeString(str) % QStringLiteral("</span>"); + return QStringLiteral("<span class=\"code-builtin\">") % escapeString(str) % + QStringLiteral("</span>"); case Other: - return QStringLiteral("<span class=\"code-other\">") % - escapeString(str) % QStringLiteral("</span>"); + return QStringLiteral("<span class=\"code-other\">") % escapeString(str) % + QStringLiteral("</span>"); case Comment: - return QStringLiteral("<span class=\"code-comment\">") % - escapeString(str) % QStringLiteral("</span>"); + return QStringLiteral("<span class=\"code-comment\">") % escapeString(str) % + QStringLiteral("</span>"); } return str.toString(); } -QString CodeToHtmlConverter::setFormat(const QString &str, CodeToHtmlConverter::Format format) -{ +QString CodeToHtmlConverter::setFormat(const QString &str, CodeToHtmlConverter::Format format) { #if QT_VERSION >= QT_VERSION_CHECK(5, 15, 0) return setFormat(StringView(str), format); #else diff --git a/src/helpers/codetohtmlconverter.h b/src/helpers/codetohtmlconverter.h index cc88969dc..4d7c9fce0 100644 --- a/src/helpers/codetohtmlconverter.h +++ b/src/helpers/codetohtmlconverter.h @@ -13,7 +13,7 @@ using LangData = QMultiHash<char, QLatin1String>; #if QT_VERSION >= QT_VERSION_CHECK(5, 15, 2) using StringView = QStringView; #else -using StringView = const QStringRef&; +using StringView = const QStringRef &; #endif #if QT_VERSION < QT_VERSION_CHECK(5, 5, 0) @@ -64,19 +64,15 @@ class CodeToHtmlConverter { Q_REQUIRED_RESULT static QString setFormat(const QString &str, Format format); static void initCodeLangs() Q_DECL_NOTHROW; - Q_REQUIRED_RESULT int highlightNumericLit(StringView input, - QString &output, int i) const; - Q_REQUIRED_RESULT static int highlightStringLiterals( - StringView input, QChar strType, QString &output, int i); - Q_REQUIRED_RESULT static int highlightComment(StringView input, - QString &output, int i, + Q_REQUIRED_RESULT int highlightNumericLit(StringView input, QString &output, int i) const; + Q_REQUIRED_RESULT static int highlightStringLiterals(StringView input, QChar strType, + QString &output, int i); + Q_REQUIRED_RESULT static int highlightComment(StringView input, QString &output, int i, bool isSingleLine = true); - Q_REQUIRED_RESULT static int highlightWord(int i, const LangData &data, - StringView input, + Q_REQUIRED_RESULT static int highlightWord(int i, const LangData &data, StringView input, QString &output, Format f); Q_REQUIRED_RESULT QString xmlHighlighter(StringView input) const; - Q_REQUIRED_RESULT QString cssHighlighter(StringView input, - const LangData &types, + Q_REQUIRED_RESULT QString cssHighlighter(StringView input, const LangData &types, const LangData &keywords) const; Q_REQUIRED_RESULT QString ymlHighlighter(StringView input) const; Q_REQUIRED_RESULT QString iniHighlighter(StringView input) const; @@ -84,22 +80,19 @@ class CodeToHtmlConverter { /** * @brief returns true if c is octal */ - Q_REQUIRED_RESULT static inline bool isOctal(const char c) { - return (c >= '0' && c <= '7'); - } + Q_REQUIRED_RESULT static inline bool isOctal(const char c) { return (c >= '0' && c <= '7'); } /** * @brief returns true if c is hex */ Q_REQUIRED_RESULT static inline bool isHex(const char c) { - return ((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || - (c >= 'A' && c <= 'F')); + return ((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F')); } static QHash<QString, Lang> _langStringToEnum; /** For Test Cases Only **/ - Q_REQUIRED_RESULT QString process(const QString& input) const; + Q_REQUIRED_RESULT QString process(const QString &input) const; friend class TestNotes; }; diff --git a/src/helpers/fakevimproxy.cpp b/src/helpers/fakevimproxy.cpp index 1a0dc61d5..044dcb7d5 100644 --- a/src/helpers/fakevimproxy.cpp +++ b/src/helpers/fakevimproxy.cpp @@ -3,6 +3,10 @@ #include <libraries/fakevim/fakevim/fakevimhandler.h> #include <mainwindow.h> +#include <QDir> +#include <QRegularExpression> +#include <QSettings> +#include <QStandardPaths> #include <QtCore/QTemporaryFile> #include <QtCore/QTextStream> #include <QtGui/QTextBlock> @@ -11,18 +15,11 @@ #include <QtWidgets/QMessageBox> #include <QtWidgets/QPlainTextEdit> #include <QtWidgets/QStatusBar> -#include <QSettings> -#include <QStandardPaths> -#include <QDir> - #include<QRegularExpression> - -FakeVimProxy::FakeVimProxy(QWidget *widget, QObject *parent) - : QObject(parent), m_widget(widget) -{ +FakeVimProxy::FakeVimProxy(QWidget *widget, QObject *parent) : QObject(parent), m_widget(widget) { using namespace FakeVim::Internal; - auto *handler = static_cast<FakeVim::Internal::FakeVimHandler*>(parent); + auto *handler = static_cast<FakeVim::Internal::FakeVimHandler *>(parent); handler->installEventFilter(); handler->setupWidget(); @@ -46,7 +43,6 @@ FakeVimProxy::FakeVimProxy(QWidget *widget, QObject *parent) fakeVimSettings()->item("ts")->setValue(Utils::Misc::indentSize()); fakeVimSettings()->item("sw")->setValue(Utils::Misc::indentSize()); - { auto h = [this](const QString &contents, int cursorPos, int anchorPos, int msgLvl) { changeStatusMessage(contents, cursorPos, anchorPos, msgLvl); @@ -85,7 +81,6 @@ FakeVimProxy::FakeVimProxy(QWidget *widget, QObject *parent) } { - auto h = [this](bool *on) { requestHasBlockSelection(on); }; handler->requestHasBlockSelection.connect(h); } @@ -98,14 +93,13 @@ FakeVimProxy::FakeVimProxy(QWidget *widget, QObject *parent) } { - auto h = [this](bool *result, QChar c) { - checkForElectricCharacter(result, c); - }; + auto h = [this](bool *result, QChar c) { checkForElectricCharacter(result, c); }; handler->checkForElectricCharacter.connect(h); } // regular signal - connect(this, &FakeVimProxy::handleInput, handler, [handler](const QString &text) { handler->handleInput(text); }); + connect(this, &FakeVimProxy::handleInput, handler, + [handler](const QString &text) { handler->handleInput(text); }); } void FakeVimProxy::changeStatusData(const QString &info) { @@ -156,23 +150,21 @@ void FakeVimProxy::highlightMatches(const QString &pattern) { updateExtraSelections(); } -void FakeVimProxy::changeStatusMessage(const QString &contents, int cursorPos, int /*anchorPos*/, int /*messageLevel*/) { - m_statusMessage = - cursorPos == -1 - ? contents - : contents.left(cursorPos) + QChar(10073) + contents.mid(cursorPos); +void FakeVimProxy::changeStatusMessage(const QString &contents, int cursorPos, int /*anchorPos*/, + int /*messageLevel*/) { + m_statusMessage = cursorPos == -1 + ? contents + : contents.left(cursorPos) + QChar(10073) + contents.mid(cursorPos); updateStatusBar(); } void FakeVimProxy::updateStatusBar() { int slack = 80 - m_statusMessage.size() - m_statusData.size(); - QString msg = - m_statusMessage + QString(slack, QLatin1Char(' ')) + m_statusData; + QString msg = m_statusMessage + QString(slack, QLatin1Char(' ')) + m_statusData; MainWindow::instance()->statusBar()->showMessage(msg); } -void FakeVimProxy::handleExCommand(bool *handled, - const FakeVim::Internal::ExCommand &cmd) { +void FakeVimProxy::handleExCommand(bool *handled, const FakeVim::Internal::ExCommand &cmd) { if (wantSaveAndQuit(cmd)) { // :wq if (save()) cancel(); @@ -195,8 +187,8 @@ void FakeVimProxy::requestSetBlockSelection(const QTextCursor &tc) { auto *ed = qobject_cast<QPlainTextEdit *>(m_widget); if (!ed) return; - QPalette pal = ed->parentWidget() != nullptr ? ed->parentWidget()->palette() - : QApplication::palette(); + QPalette pal = + ed->parentWidget() != nullptr ? ed->parentWidget()->palette() : QApplication::palette(); m_blockSelection.clear(); m_clearSelection.clear(); @@ -219,17 +211,14 @@ void FakeVimProxy::requestSetBlockSelection(const QTextCursor &tc) { for (QTextBlock block = cur.document()->findBlock(min); block.isValid() && block.position() < max; block = block.next()) { cur.setPosition(block.position() + qMin<int>(from, block.length())); - cur.setPosition(block.position() + qMin<int>(to, block.length()), - QTextCursor::KeepAnchor); + cur.setPosition(block.position() + qMin<int>(to, block.length()), QTextCursor::KeepAnchor); selection.cursor = cur; m_blockSelection.append(selection); } - disconnect(ed, &QPlainTextEdit::selectionChanged, this, - &FakeVimProxy::updateBlockSelection); + disconnect(ed, &QPlainTextEdit::selectionChanged, this, &FakeVimProxy::updateBlockSelection); ed->setTextCursor(tc); - connect(ed, &QPlainTextEdit::selectionChanged, this, - &FakeVimProxy::updateBlockSelection); + connect(ed, &QPlainTextEdit::selectionChanged, this, &FakeVimProxy::updateBlockSelection); QPalette pal2 = ed->palette(); pal2.setColor(QPalette::Highlight, Qt::transparent); @@ -243,16 +232,15 @@ void FakeVimProxy::requestDisableBlockSelection() { auto *ed = qobject_cast<QPlainTextEdit *>(m_widget); if (!ed) return; - QPalette pal = ed->parentWidget() != nullptr ? ed->parentWidget()->palette() - : QApplication::palette(); + QPalette pal = + ed->parentWidget() != nullptr ? ed->parentWidget()->palette() : QApplication::palette(); m_blockSelection.clear(); m_clearSelection.clear(); ed->setPalette(pal); - disconnect(ed, &QPlainTextEdit::selectionChanged, this, - &FakeVimProxy::updateBlockSelection); + disconnect(ed, &QPlainTextEdit::selectionChanged, this, &FakeVimProxy::updateBlockSelection); updateExtraSelections(); } @@ -264,9 +252,7 @@ void FakeVimProxy::updateBlockSelection() { requestSetBlockSelection(ed->textCursor()); } -void FakeVimProxy::requestHasBlockSelection(bool *on) { - *on = !m_blockSelection.isEmpty(); -} +void FakeVimProxy::requestHasBlockSelection(bool *on) { *on = !m_blockSelection.isEmpty(); } void FakeVimProxy::indentRegion(int beginBlock, int endBlock, QChar typedChar) { auto *ed = qobject_cast<QPlainTextEdit *>(m_widget); @@ -290,8 +276,7 @@ void FakeVimProxy::indentRegion(int beginBlock, int endBlock, QChar typedChar) { while (!cursor.atBlockEnd()) cursor.deleteChar(); } else { const auto previousBlock = block.previous(); - const auto previousLine = - previousBlock.isValid() ? previousBlock.text() : QString(); + const auto previousLine = previousBlock.isValid() ? previousBlock.text() : QString(); qint64 indent = firstNonSpace(previousLine); if (typedChar == '}') @@ -303,8 +288,8 @@ void FakeVimProxy::indentRegion(int beginBlock, int endBlock, QChar typedChar) { QTextCursor cursor(block); cursor.beginEditBlock(); cursor.movePosition(QTextCursor::StartOfBlock); - cursor.movePosition(QTextCursor::NextCharacter, - QTextCursor::KeepAnchor, firstNonSpace(line)); + cursor.movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor, + firstNonSpace(line)); cursor.removeSelectedText(); cursor.insertText(indentString); cursor.endEditBlock(); @@ -325,9 +310,7 @@ int FakeVimProxy::firstNonSpace(const QString &text) { void FakeVimProxy::updateExtraSelections() { auto *ed = qobject_cast<QPlainTextEdit *>(m_widget); - if (ed) - ed->setExtraSelections(m_clearSelection + m_searchSelection + - m_blockSelection); + if (ed) ed->setExtraSelections(m_clearSelection + m_searchSelection + m_blockSelection); } bool FakeVimProxy::wantSaveAndQuit(const FakeVim::Internal::ExCommand &cmd) { diff --git a/src/helpers/fakevimproxy.h b/src/helpers/fakevimproxy.h index 2f75a0d71..f78013ebc 100644 --- a/src/helpers/fakevimproxy.h +++ b/src/helpers/fakevimproxy.h @@ -26,14 +26,14 @@ class FakeVimProxy : public QObject { void highlightMatches(const QString &pattern); - void changeStatusMessage(const QString &contents, int cursorPos, int anchorPos, int messageLevel); + void changeStatusMessage(const QString &contents, int cursorPos, int anchorPos, + int messageLevel); void changeExtraInformation(const QString &info); void updateStatusBar(); - void handleExCommand(bool *handled, - const FakeVim::Internal::ExCommand &cmd); + void handleExCommand(bool *handled, const FakeVim::Internal::ExCommand &cmd); void requestSetBlockSelection(const QTextCursor &tc); diff --git a/src/helpers/flowlayout.cpp b/src/helpers/flowlayout.cpp index 48c50ab4a..d01140074 100644 --- a/src/helpers/flowlayout.cpp +++ b/src/helpers/flowlayout.cpp @@ -48,42 +48,34 @@ ** ****************************************************************************/ -#include <QtWidgets> - #include "flowlayout.h" + +#include <QtWidgets> //! [1] FlowLayout::FlowLayout(QWidget *parent, int margin, int hSpacing, int vSpacing) - : QLayout(parent), m_hSpace(hSpacing), m_vSpace(vSpacing) -{ + : QLayout(parent), m_hSpace(hSpacing), m_vSpace(vSpacing) { setContentsMargins(margin, margin, margin, margin); } FlowLayout::FlowLayout(int margin, int hSpacing, int vSpacing) - : m_hSpace(hSpacing), m_vSpace(vSpacing) -{ + : m_hSpace(hSpacing), m_vSpace(vSpacing) { setContentsMargins(margin, margin, margin, margin); } //! [1] //! [2] -FlowLayout::~FlowLayout() -{ +FlowLayout::~FlowLayout() { QLayoutItem *item; - while ((item = takeAt(0))) - delete item; + while ((item = takeAt(0))) delete item; } //! [2] //! [3] -void FlowLayout::addItem(QLayoutItem *item) -{ - itemList.append(item); -} +void FlowLayout::addItem(QLayoutItem *item) { itemList.append(item); } //! [3] //! [4] -int FlowLayout::horizontalSpacing() const -{ +int FlowLayout::horizontalSpacing() const { if (m_hSpace >= 0) { return m_hSpace; } else { @@ -91,8 +83,7 @@ int FlowLayout::horizontalSpacing() const } } -int FlowLayout::verticalSpacing() const -{ +int FlowLayout::verticalSpacing() const { if (m_vSpace >= 0) { return m_vSpace; } else { @@ -102,58 +93,38 @@ int FlowLayout::verticalSpacing() const //! [4] //! [5] -int FlowLayout::count() const -{ - return itemList.size(); -} +int FlowLayout::count() const { return itemList.size(); } -QLayoutItem *FlowLayout::itemAt(int index) const -{ - return itemList.value(index); -} +QLayoutItem *FlowLayout::itemAt(int index) const { return itemList.value(index); } -QLayoutItem *FlowLayout::takeAt(int index) -{ - if (index >= 0 && index < itemList.size()) - return itemList.takeAt(index); +QLayoutItem *FlowLayout::takeAt(int index) { + if (index >= 0 && index < itemList.size()) return itemList.takeAt(index); return nullptr; } //! [5] //! [6] -Qt::Orientations FlowLayout::expandingDirections() const -{ - return {}; -} +Qt::Orientations FlowLayout::expandingDirections() const { return {}; } //! [6] //! [7] -bool FlowLayout::hasHeightForWidth() const -{ - return true; -} +bool FlowLayout::hasHeightForWidth() const { return true; } -int FlowLayout::heightForWidth(int width) const -{ +int FlowLayout::heightForWidth(int width) const { int height = doLayout(QRect(0, 0, width, 0), true); return height; } //! [7] //! [8] -void FlowLayout::setGeometry(const QRect &rect) -{ +void FlowLayout::setGeometry(const QRect &rect) { QLayout::setGeometry(rect); doLayout(rect, false); } -QSize FlowLayout::sizeHint() const -{ - return minimumSize(); -} +QSize FlowLayout::sizeHint() const { return minimumSize(); } -QSize FlowLayout::minimumSize() const -{ +QSize FlowLayout::minimumSize() const { QSize size; #if QT_VERSION >= 0x050700 for (const QLayoutItem *item : qAsConst(itemList)) @@ -169,8 +140,7 @@ QSize FlowLayout::minimumSize() const //! [8] //! [9] -int FlowLayout::doLayout(const QRect &rect, bool testOnly) const -{ +int FlowLayout::doLayout(const QRect &rect, bool testOnly) const { int left, top, right, bottom; getContentsMargins(&left, &top, &right, &bottom); QRect effectiveRect = rect.adjusted(+left, +top, -right, -bottom); @@ -188,14 +158,14 @@ int FlowLayout::doLayout(const QRect &rect, bool testOnly) const const QWidget *wid = item->widget(); int spaceX = horizontalSpacing(); if (spaceX == -1) - spaceX = wid->style()->layoutSpacing( - QSizePolicy::PushButton, QSizePolicy::PushButton, Qt::Horizontal); + spaceX = wid->style()->layoutSpacing(QSizePolicy::PushButton, QSizePolicy::PushButton, + Qt::Horizontal); int spaceY = verticalSpacing(); if (spaceY == -1) - spaceY = wid->style()->layoutSpacing( - QSizePolicy::PushButton, QSizePolicy::PushButton, Qt::Vertical); -//! [10] -//! [11] + spaceY = wid->style()->layoutSpacing(QSizePolicy::PushButton, QSizePolicy::PushButton, + Qt::Vertical); + //! [10] + //! [11] int nextX = x + item->sizeHint().width() + spaceX; if (nextX - spaceX > effectiveRect.right() && lineHeight > 0) { x = effectiveRect.x(); @@ -204,8 +174,7 @@ int FlowLayout::doLayout(const QRect &rect, bool testOnly) const lineHeight = 0; } - if (!testOnly) - item->setGeometry(QRect(QPoint(x, y), item->sizeHint())); + if (!testOnly) item->setGeometry(QRect(QPoint(x, y), item->sizeHint())); x = nextX; lineHeight = qMax<int>(lineHeight, item->sizeHint().height()); @@ -214,8 +183,7 @@ int FlowLayout::doLayout(const QRect &rect, bool testOnly) const } //! [11] //! [12] -int FlowLayout::smartSpacing(QStyle::PixelMetric pm) const -{ +int FlowLayout::smartSpacing(QStyle::PixelMetric pm) const { QObject *parent = this->parent(); if (!parent) { return -1; diff --git a/src/helpers/flowlayout.h b/src/helpers/flowlayout.h index 3155d5d34..0f173cd34 100644 --- a/src/helpers/flowlayout.h +++ b/src/helpers/flowlayout.h @@ -55,9 +55,8 @@ #include <QRect> #include <QStyle> //! [0] -class FlowLayout : public QLayout -{ -public: +class FlowLayout : public QLayout { + public: explicit FlowLayout(QWidget *parent, int margin = -1, int hSpacing = -1, int vSpacing = -1); explicit FlowLayout(int margin = -1, int hSpacing = -1, int vSpacing = -1); ~FlowLayout(); @@ -75,7 +74,7 @@ public: QSize sizeHint() const override; QLayoutItem *takeAt(int index) override; -private: + private: int doLayout(const QRect &rect, bool testOnly) const; int smartSpacing(QStyle::PixelMetric pm) const; @@ -85,4 +84,4 @@ private: }; //! [0] -#endif // FLOWLAYOUT_H +#endif // FLOWLAYOUT_H diff --git a/src/helpers/qownnotesmarkdownhighlighter.cpp b/src/helpers/qownnotesmarkdownhighlighter.cpp index a36dc62b4..f31d3382d 100644 --- a/src/helpers/qownnotesmarkdownhighlighter.cpp +++ b/src/helpers/qownnotesmarkdownhighlighter.cpp @@ -14,8 +14,7 @@ */ #include "qownnotesmarkdownhighlighter.h" -#include "mainwindow.h" -#include "qownspellchecker.h" + #include <entities/note.h> #include <services/scriptingservice.h> @@ -25,13 +24,14 @@ #include <QRegularExpression> #include <QRegularExpressionMatch> +#include "mainwindow.h" +#include "qownspellchecker.h" -QOwnNotesMarkdownHighlighter::QOwnNotesMarkdownHighlighter( - QTextDocument *parent, HighlightingOptions highlightingOptions) - : MarkdownHighlighter(parent, highlightingOptions) -{ +QOwnNotesMarkdownHighlighter::QOwnNotesMarkdownHighlighter(QTextDocument *parent, + HighlightingOptions highlightingOptions) + : MarkdownHighlighter(parent, highlightingOptions) { _defaultNoteFileExt = Note::defaultNoteFileExtension(); - connect(MainWindow::instance(), &MainWindow::settingsChanged, this, [this](){ + connect(MainWindow::instance(), &MainWindow::settingsChanged, this, [this]() { _defaultNoteFileExt = Note::defaultNoteFileExtension(); updateCachedRegexes(_defaultNoteFileExt); }); @@ -60,7 +60,8 @@ void QOwnNotesMarkdownHighlighter::highlightBlock(const QString &text) { // do the markdown highlighting before the spellcheck highlighting // if we do it afterwards, it overwrites the spellcheck highlighting MarkdownHighlighter::highlightMarkdown(text); - if (text.contains(QLatin1String("note://")) || text.contains(QChar('.') + _defaultNoteFileExt)) { + if (text.contains(QLatin1String("note://")) || + text.contains(QChar('.') + _defaultNoteFileExt)) { highlightBrokenNotesLink(text); } @@ -104,26 +105,23 @@ void QOwnNotesMarkdownHighlighter::highlightScriptingRules( QTextCharFormat currentMaskedFormat = maskedFormat; // set the font size from the current rule's font format if (format.fontPointSize() > 0) { - currentMaskedFormat.setFontPointSize( - format.fontPointSize()); + currentMaskedFormat.setFontPointSize(format.fontPointSize()); } - setFormat(match.capturedStart(maskedGroup), - match.capturedLength(maskedGroup), + setFormat(match.capturedStart(maskedGroup), match.capturedLength(maskedGroup), currentMaskedFormat); } - setFormat(match.capturedStart(capturingGroup), - match.capturedLength(capturingGroup), format); + setFormat(match.capturedStart(capturingGroup), match.capturedLength(capturingGroup), + format); } } } - -void QOwnNotesMarkdownHighlighter::updateCachedRegexes(const QString& newExt) -{ +void QOwnNotesMarkdownHighlighter::updateCachedRegexes(const QString &newExt) { _regexTagStyleLink = QRegularExpression(R"(<([^\s`][^`]*?\.)" + newExt + R"()>)"); - _regexBracketLink = QRegularExpression(R"(\[[^\[\]]+\]\((\S+\.)" + newExt + R"(|.+?\.)" + newExt + R"()(#[^\)]+)?\)\B)"); + _regexBracketLink = QRegularExpression(R"(\[[^\[\]]+\]\((\S+\.)" + newExt + R"(|.+?\.)" + + newExt + R"()(#[^\)]+)?\)\B)"); } /** @@ -131,8 +129,7 @@ void QOwnNotesMarkdownHighlighter::updateCachedRegexes(const QString& newExt) * * @param text */ -void QOwnNotesMarkdownHighlighter::highlightBrokenNotesLink( - const QString &text) { +void QOwnNotesMarkdownHighlighter::highlightBrokenNotesLink(const QString &text) { static const QRegularExpression regex(QStringLiteral(R"(note:\/\/[^\s\)>]+)")); QRegularExpressionMatch match = regex.match(text); @@ -164,8 +161,7 @@ void QOwnNotesMarkdownHighlighter::highlightBrokenNotesLink( return; } - const Note note = - _currentNote->fetchByRelativeFileName(fileName); + const Note note = _currentNote->fetchByRelativeFileName(fileName); // if the note exists we don't need to do anything if (note.isFetched()) { @@ -176,16 +172,14 @@ void QOwnNotesMarkdownHighlighter::highlightBrokenNotesLink( match = _regexBracketLink.match(text); if (match.hasMatch()) { - const QString fileName = - Note::urlDecodeNoteUrl(match.captured(1)); + const QString fileName = Note::urlDecodeNoteUrl(match.captured(1)); // skip urls if (fileName.contains(QStringLiteral("://"))) { return; } - const Note note = - _currentNote->fetchByRelativeFileName(fileName); + const Note note = _currentNote->fetchByRelativeFileName(fileName); // if the note exists we don't need to do anything if (note.isFetched()) { @@ -201,10 +195,8 @@ void QOwnNotesMarkdownHighlighter::highlightBrokenNotesLink( setFormat(match.capturedStart(0), match.capturedLength(0), _formats[state]); } -void QOwnNotesMarkdownHighlighter::setMisspelled(const int start, - const int count) { - if (MarkdownHighlighter::isPosInACodeSpan(currentBlock().blockNumber(), start)) - return; +void QOwnNotesMarkdownHighlighter::setMisspelled(const int start, const int count) { + if (MarkdownHighlighter::isPosInACodeSpan(currentBlock().blockNumber(), start)) return; // append to the already existing text format. // creating a new format will destroy pre-existing format @@ -230,14 +222,12 @@ void QOwnNotesMarkdownHighlighter::highlightSpellChecking(const QString &text) { return; } int state = currentBlockState(); - if (state == HighlighterState::HeadlineEnd || - state == HighlighterState::CodeBlock || + if (state == HighlighterState::HeadlineEnd || state == HighlighterState::CodeBlock || state >= HighlighterState::CodeCpp) return; // use our own settings, as KDE users might face issues with Autodetection - const bool autodetectLanguage = - QOwnSpellChecker::instance()->isAutoDetectOn(); + const bool autodetectLanguage = QOwnSpellChecker::instance()->isAutoDetectOn(); LanguageCache *languageCache = nullptr; if (autodetectLanguage) { languageCache = dynamic_cast<LanguageCache *>(currentBlockUserData()); @@ -252,8 +242,7 @@ void QOwnNotesMarkdownHighlighter::highlightSpellChecking(const QString &text) { const Sonnet::Token sentence = languageFilter->next(); if (autodetectLanguage) { QString lang; - const QPair<int, int> spos = - QPair<int, int>(sentence.position(), sentence.length()); + const QPair<int, int> spos = QPair<int, int>(sentence.position(), sentence.length()); // try cache first if (languageCache->languages.contains(spos)) { lang = languageCache->languages.value(spos); @@ -270,8 +259,7 @@ void QOwnNotesMarkdownHighlighter::highlightSpellChecking(const QString &text) { QOwnSpellChecker::instance()->setCurrentLanguage(lang); } - const auto wordTokenizer = - QOwnSpellChecker::instance()->wordTokenizer(); + const auto wordTokenizer = QOwnSpellChecker::instance()->wordTokenizer(); wordTokenizer->setBuffer(sentence.toString()); const int offset = sentence.position(); while (wordTokenizer->hasNext()) { diff --git a/src/helpers/qownnotesmarkdownhighlighter.h b/src/helpers/qownnotesmarkdownhighlighter.h index c70ae6aa4..422489918 100644 --- a/src/helpers/qownnotesmarkdownhighlighter.h +++ b/src/helpers/qownnotesmarkdownhighlighter.h @@ -40,8 +40,7 @@ class QOwnNotesMarkdownHighlighter : public MarkdownHighlighter { void updateCurrentNote(Note *note); struct ScriptingHighlightingRule { - explicit ScriptingHighlightingRule(const HighlighterState state_) - : state(state_) {} + explicit ScriptingHighlightingRule(const HighlighterState state_) : state(state_) {} ScriptingHighlightingRule() = default; QRegularExpression pattern; @@ -61,7 +60,7 @@ class QOwnNotesMarkdownHighlighter : public MarkdownHighlighter { void setMisspelled(const int start, const int count); void highlightSpellChecking(const QString &text); - void updateCachedRegexes(const QString& newExt); + void updateCachedRegexes(const QString &newExt); private: Note *_currentNote = nullptr; diff --git a/src/helpers/qownspellchecker.cpp b/src/helpers/qownspellchecker.cpp index 55a0c958c..d90d25956 100644 --- a/src/helpers/qownspellchecker.cpp +++ b/src/helpers/qownspellchecker.cpp @@ -19,8 +19,7 @@ #include <QSettings> QOwnSpellChecker::QOwnSpellChecker() : _spellchecker{new Sonnet::Speller()} { - _languageFilter = - new Sonnet::LanguageFilter(new Sonnet::SentenceTokenizer()); + _languageFilter = new Sonnet::LanguageFilter(new Sonnet::SentenceTokenizer()); _wordTokenizer = new Sonnet::WordTokenizer(); #ifdef Q_OS_MACOS QStringList s = _spellchecker->availableLanguages(); @@ -30,13 +29,9 @@ QOwnSpellChecker::QOwnSpellChecker() : _spellchecker{new Sonnet::Speller()} { #endif } -Sonnet::WordTokenizer *QOwnSpellChecker::wordTokenizer() const { - return _wordTokenizer; -} +Sonnet::WordTokenizer *QOwnSpellChecker::wordTokenizer() const { return _wordTokenizer; } -Sonnet::LanguageFilter *QOwnSpellChecker::languageFilter() const { - return _languageFilter; -} +Sonnet::LanguageFilter *QOwnSpellChecker::languageFilter() const { return _languageFilter; } QOwnSpellChecker::~QOwnSpellChecker() { delete _languageFilter; @@ -49,13 +44,9 @@ QOwnSpellChecker *QOwnSpellChecker::instance() { return &qonSpellchecker; } -QString QOwnSpellChecker::currentLanguage() const { - return _spellchecker->language(); -} +QString QOwnSpellChecker::currentLanguage() const { return _spellchecker->language(); } -void QOwnSpellChecker::setCurrentLanguage(const QString &lang) { - _spellchecker->setLanguage(lang); -} +void QOwnSpellChecker::setCurrentLanguage(const QString &lang) { _spellchecker->setLanguage(lang); } void QOwnSpellChecker::setActive(bool active) { _active = active; } @@ -65,9 +56,7 @@ void QOwnSpellChecker::addWordToDictionary(const QString &word) { _spellchecker->addToPersonal(word); } -void QOwnSpellChecker::ignoreWord(const QString &word) { - _spellchecker->addToSession(word); -} +void QOwnSpellChecker::ignoreWord(const QString &word) { _spellchecker->addToSession(word); } bool QOwnSpellChecker::isValid() { return _spellchecker->isValid(); } @@ -75,9 +64,7 @@ bool QOwnSpellChecker::testAttribute(Sonnet::Speller::Attribute attr) const { return _spellchecker->testAttribute(attr); } -void QOwnSpellChecker::setAutoDetect(bool autoDetect) { - _autoDetect = autoDetect; -} +void QOwnSpellChecker::setAutoDetect(bool autoDetect) { _autoDetect = autoDetect; } bool QOwnSpellChecker::isAutoDetectOn() const { return _autoDetect; } @@ -89,16 +76,13 @@ QStringList QOwnSpellChecker::suggestionsForWord(const QString &word, int max) { return suggestions; } -QStringList QOwnSpellChecker::suggestionsForWord(const QString &word, - const QTextCursor &cursor, +QStringList QOwnSpellChecker::suggestionsForWord(const QString &word, const QTextCursor &cursor, int max) { // detect the lang if (_autoDetect) { - LanguageCache *cache = - dynamic_cast<LanguageCache *>(cursor.block().userData()); + LanguageCache *cache = dynamic_cast<LanguageCache *>(cursor.block().userData()); if (cache) { - const QString cachedLanguage = - cache->languageAtPos(cursor.positionInBlock()); + const QString cachedLanguage = cache->languageAtPos(cursor.positionInBlock()); if (!cachedLanguage.isEmpty()) { _spellchecker->setLanguage(cachedLanguage); } diff --git a/src/helpers/qownspellchecker.h b/src/helpers/qownspellchecker.h index 4dc964c47..39d177cd9 100644 --- a/src/helpers/qownspellchecker.h +++ b/src/helpers/qownspellchecker.h @@ -17,9 +17,9 @@ #define QOWNSPELLCHECKER_H #include <libraries/sonnet/src/core/speller.h> -#include "libraries/sonnet/src/core/languagefilter_p.h" #include "LanguageCache.h" +#include "libraries/sonnet/src/core/languagefilter_p.h" class QOwnSpellChecker { public: @@ -47,9 +47,7 @@ class QOwnSpellChecker { * @param word the word to be checked * @return true if the given word is misspelled. */ - inline bool isWordMisspelled(const QString &word) { - return _spellchecker->isMisspelled(word); - } + inline bool isWordMisspelled(const QString &word) { return _spellchecker->isMisspelled(word); } /** * Returns a list of suggested replacements for the given misspelled word. @@ -76,8 +74,7 @@ class QOwnSpellChecker { * be returned. * @return a list of suggested replacements for the word */ - QStringList suggestionsForWord(const QString &word, - const QTextCursor &cursor, int max); + QStringList suggestionsForWord(const QString &word, const QTextCursor &cursor, int max); /** * @short Enable/Disable spell checking. diff --git a/src/helpers/toolbarcontainer.cpp b/src/helpers/toolbarcontainer.cpp index 28de13526..2aa16d59b 100644 --- a/src/helpers/toolbarcontainer.cpp +++ b/src/helpers/toolbarcontainer.cpp @@ -12,8 +12,7 @@ ToolbarContainer::ToolbarContainer(QToolBar *toolbar) : name(toolbar->objectName()), title(toolbar->windowTitle()) { - foreach (QAction *a, toolbar->actions()) - actions.push_back(a->objectName()); + foreach (QAction *a, toolbar->actions()) actions.push_back(a->objectName()); } QToolBar *ToolbarContainer::create(QMainWindow *w) const { @@ -78,25 +77,21 @@ void ToolbarContainer::updateToolbar() { // TODO(pbek): we will enable that again later if (false) { // if (item == "actionWorkspaceComboBox") { - qDebug() << __func__ - << " - 'actionWorkspaceComboBox': " << item; + qDebug() << __func__ << " - 'actionWorkspaceComboBox': " << item; // TODO(pbek): for some reason we can't find the combobox - auto *workspaceComboBox = mainWindow->findChild<QComboBox *>( - QStringLiteral("workspaceComboBox")); + auto *workspaceComboBox = + mainWindow->findChild<QComboBox *>(QStringLiteral("workspaceComboBox")); - qDebug() << __func__ - << " - 'workspaceComboBox': " << workspaceComboBox; + qDebug() << __func__ << " - 'workspaceComboBox': " << workspaceComboBox; - auto *widgetAction = - mainWindow->findChild<QWidgetAction *>(item); + auto *widgetAction = mainWindow->findChild<QWidgetAction *>(item); qDebug() << __func__ << " - 'widgetAction': " << widgetAction; if (widgetAction == nullptr) { widgetAction = new QWidgetAction(mainWindow); - widgetAction->setObjectName( - QStringLiteral("actionWorkspaceComboBox")); + widgetAction->setObjectName(QStringLiteral("actionWorkspaceComboBox")); widgetAction->setText(QObject::tr("Workspace selector")); } @@ -131,9 +126,7 @@ void ToolbarContainer::updateToolbar() { */ void ToolbarContainer::updateIconSize(QToolBar *toolbar) { QSettings settings; - int toolBarIconSize = - settings.value(QStringLiteral("MainWindow/mainToolBar.iconSize")) - .toInt(); + int toolBarIconSize = settings.value(QStringLiteral("MainWindow/mainToolBar.iconSize")).toInt(); QSize size(toolBarIconSize, toolBarIconSize); toolbar->setIconSize(size); } diff --git a/src/helpers/toolbarcontainer.h b/src/helpers/toolbarcontainer.h index d45fe768e..38ec8b16b 100644 --- a/src/helpers/toolbarcontainer.h +++ b/src/helpers/toolbarcontainer.h @@ -16,8 +16,7 @@ struct ToolbarContainer { QStringList actions; ToolbarContainer() {} - ToolbarContainer(const QString &name, const QString &title, - const QStringList &actions) + ToolbarContainer(const QString &name, const QString &title, const QStringList &actions) : name(name), title(title), actions(actions) {} ToolbarContainer(QToolBar *toolbar); QToolBar *create(QMainWindow *w) const; diff --git a/src/main.cpp b/src/main.cpp index 5bee7264c..e9c78f5df 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -30,18 +30,18 @@ void loadTranslation(QTranslator &translator, const QString &fileName, bool isLoaded = translator.load(fileName, directory); bool isInstalled = QCoreApplication::installTranslator(&translator); - qDebug() << "Translation " << fileName << "in" << directory << "isLoaded:" - << isLoaded << ", isInstalled:" << isInstalled; + qDebug() << "Translation " << fileName << "in" << directory << "isLoaded:" << isLoaded + << ", isInstalled:" << isInstalled; } /** * Function for loading the translations */ void loadTranslations(QTranslator *translator, const QString &locale) { -// loadTranslation(translator[0], "qt_" + QLocale::system().name(), -// QLibraryInfo::location(QLibraryInfo::TranslationsPath)); + // loadTranslation(translator[0], "qt_" + QLocale::system().name(), + // QLibraryInfo::location(QLibraryInfo::TranslationsPath)); loadTranslation(translator[1], "qt_" + locale, - QLibraryInfo::location(QLibraryInfo::TranslationsPath)); + QLibraryInfo::location(QLibraryInfo::TranslationsPath)); QString appPath = QCoreApplication::applicationDirPath(); loadTranslation(translator[2], "qt_" + locale, appPath + "/translations"); loadTranslation(translator[3], appPath + "/../src/languages/QOwnNotes_" + locale); @@ -50,31 +50,26 @@ void loadTranslations(QTranslator *translator, const QString &locale) { loadTranslation(translator[6], appPath + "/QOwnNotes_" + locale); loadTranslation(translator[7], "../src/languages/QOwnNotes_" + locale); loadTranslation(translator[8], "../share/qt5/translations/QOwnNotes_" + locale); - loadTranslation(translator[9], appPath + "/../share/qt5/translations/QOwnNotes_" + - locale); + loadTranslation(translator[9], appPath + "/../share/qt5/translations/QOwnNotes_" + locale); loadTranslation(translator[10], "QOwnNotes_" + locale); } /** * Function for loading the release translations */ -inline void loadReleaseTranslations(QTranslator &translatorRelease, - const QString &locale) { +inline void loadReleaseTranslations(QTranslator &translatorRelease, const QString &locale) { loadTranslation(translatorRelease, - "/usr/share/qt5/translations/" - "QOwnNotes_" + - locale); + "/usr/share/qt5/translations/" + "QOwnNotes_" + + locale); } /** * Function for loading the translations on OS X */ -inline void loadMacTranslations(QTranslator &translatorOSX, - QTranslator &translatorOSX2, - QTranslator &translatorOSX3, - QTranslator &translatorOSX4, - const QString &appPath, - const QString &locale) { +inline void loadMacTranslations(QTranslator &translatorOSX, QTranslator &translatorOSX2, + QTranslator &translatorOSX3, QTranslator &translatorOSX4, + const QString &appPath, const QString &locale) { loadTranslation(translatorOSX, appPath + "/../Resources/QOwnNotes_" + locale); loadTranslation(translatorOSX2, "../Resources/QOwnNotes_" + locale); loadTranslation(translatorOSX3, appPath + "/../Resources/qtbase_" + locale); @@ -90,31 +85,27 @@ bool mainStartupMisc(const QStringList &arguments) { parser.setApplicationDescription("QOwnNotes " + QString(VERSION)); const QCommandLineOption helpOption = parser.addHelpOption(); const QCommandLineOption portableOption( - QStringLiteral("portable"), - QCoreApplication::translate("main", - "Runs the " - "application in portable mode.")); + QStringLiteral("portable"), QCoreApplication::translate("main", + "Runs the " + "application in portable mode.")); parser.addOption(portableOption); const QCommandLineOption dumpSettingsOption( QStringLiteral("dump-settings"), - QCoreApplication::translate( - "main", - "Prints out " - "a dump of the settings and other information about the " - "application and environment in GitHub Markdown and exits " - "the application.")); + QCoreApplication::translate("main", + "Prints out " + "a dump of the settings and other information about the " + "application and environment in GitHub Markdown and exits " + "the application.")); parser.addOption(dumpSettingsOption); const QCommandLineOption versionOption( QStringLiteral("version"), - QCoreApplication::translate( - "main", "Prints out the version number.")); + QCoreApplication::translate("main", "Prints out the version number.")); parser.addOption(versionOption); const QCommandLineOption allowMultipleInstancesOption( QStringLiteral("allow-multiple-instances"), - QCoreApplication::translate( - "main", - "Allows multiple instances of QOwnNotes to be started " - "even if disallowed in the settings.")); + QCoreApplication::translate("main", + "Allows multiple instances of QOwnNotes to be started " + "even if disallowed in the settings.")); parser.addOption(allowMultipleInstancesOption); const QCommandLineOption clearSettingsOption( QStringLiteral("clear-settings"), @@ -124,18 +115,16 @@ bool mainStartupMisc(const QStringList &arguments) { parser.addOption(clearSettingsOption); const QCommandLineOption sessionOption( QStringLiteral("session"), - QCoreApplication::translate( - "main", - "Runs the " - "application in a different context for settings and " - "internal files."), + QCoreApplication::translate("main", + "Runs the " + "application in a different context for settings and " + "internal files."), "name"); parser.addOption(sessionOption); const QCommandLineOption actionOption( QStringLiteral("action"), - QCoreApplication::translate( - "main", - "Triggers a menu action after the application was started."), + QCoreApplication::translate("main", + "Triggers a menu action after the application was started."), "name"); parser.addOption(actionOption); @@ -148,8 +137,7 @@ bool mainStartupMisc(const QStringList &arguments) { } QSettings settings; - QString interfaceStyle = - settings.value(QStringLiteral("interfaceStyle")).toString(); + QString interfaceStyle = settings.value(QStringLiteral("interfaceStyle")).toString(); // restore the interface style if (!interfaceStyle.isEmpty()) { @@ -164,12 +152,10 @@ bool mainStartupMisc(const QStringList &arguments) { Utils::Gui::doLinuxDarkModeCheck(); #endif - bool systemIconTheme = - settings.value(QStringLiteral("systemIconTheme")).toBool(); + bool systemIconTheme = settings.value(QStringLiteral("systemIconTheme")).toBool(); if (!systemIconTheme) { - bool internalIconTheme = - settings.value(QStringLiteral("internalIconTheme")).toBool(); + bool internalIconTheme = settings.value(QStringLiteral("internalIconTheme")).toBool(); #if (QT_VERSION >= QT_VERSION_CHECK(5, 12, 0)) if (!internalIconTheme && QIcon::themeName().isEmpty()) { @@ -187,30 +173,26 @@ bool mainStartupMisc(const QStringList &arguments) { } MetricsService *metricsService = MetricsService::createInstance(); - metricsService->sendVisitIfEnabled(QStringLiteral("app/start"), - QStringLiteral("App Start")); + metricsService->sendVisitIfEnabled(QStringLiteral("app/start"), QStringLiteral("App Start")); + metricsService->sendEventIfEnabled(QStringLiteral("app/qt-version-build"), + QStringLiteral("app"), QStringLiteral("qt version build"), + QStringLiteral(QT_VERSION_STR)); + metricsService->sendEventIfEnabled(QStringLiteral("app/qt-version-runtime"), + QStringLiteral("app"), QStringLiteral("qt version runtime"), + qVersion()); + metricsService->sendEventIfEnabled(QStringLiteral("app/theme"), QStringLiteral("app"), + QStringLiteral("theme"), QIcon::themeName()); + metricsService->sendEventIfEnabled(QStringLiteral("app/release"), QStringLiteral("app"), + QStringLiteral("release"), + qApp->property("release").toString()); metricsService->sendEventIfEnabled( - QStringLiteral("app/qt-version-build"), QStringLiteral("app"), - QStringLiteral("qt version build"), QStringLiteral(QT_VERSION_STR)); - metricsService->sendEventIfEnabled( - QStringLiteral("app/qt-version-runtime"), QStringLiteral("app"), - QStringLiteral("qt version runtime"), qVersion()); - metricsService->sendEventIfEnabled( - QStringLiteral("app/theme"), QStringLiteral("app"), - QStringLiteral("theme"), QIcon::themeName()); - metricsService->sendEventIfEnabled( - QStringLiteral("app/release"), QStringLiteral("app"), - QStringLiteral("release"), qApp->property("release").toString()); - metricsService->sendEventIfEnabled( - QStringLiteral("app/portable"), QStringLiteral("app"), - QStringLiteral("portable"), - Utils::Misc::isInPortableMode() ? QStringLiteral("yes") - : QStringLiteral("no")); + QStringLiteral("app/portable"), QStringLiteral("app"), QStringLiteral("portable"), + Utils::Misc::isInPortableMode() ? QStringLiteral("yes") : QStringLiteral("no")); if (qApp->property("snap").toBool()) { - metricsService->sendEventIfEnabled( - QStringLiteral("app/styles"), QStringLiteral("app"), - QStringLiteral("styles"), QStyleFactory::keys().join(QChar(' '))); + metricsService->sendEventIfEnabled(QStringLiteral("app/styles"), QStringLiteral("app"), + QStringLiteral("styles"), + QStyleFactory::keys().join(QChar(' '))); } QString productType; @@ -221,9 +203,8 @@ bool mainStartupMisc(const QStringList &arguments) { productType += " Qt " + QString(QT_VERSION_STR); #endif - metricsService->sendEventIfEnabled( - QStringLiteral("app/product-type"), QStringLiteral("app"), - QStringLiteral("product-type"), productType); + metricsService->sendEventIfEnabled(QStringLiteral("app/product-type"), QStringLiteral("app"), + QStringLiteral("product-type"), productType); QString platform = QStringLiteral("other"); #ifdef Q_OS_LINUX @@ -240,16 +221,14 @@ bool mainStartupMisc(const QStringList &arguments) { // self-builds if nothing is already set Utils::Misc::presetDisableAutomaticUpdateDialog(); - metricsService->sendEventIfEnabled(QStringLiteral("app/platform"), - QStringLiteral("app"), + metricsService->sendEventIfEnabled(QStringLiteral("app/platform"), QStringLiteral("app"), QStringLiteral("platform"), platform); // sends locale information metricsService->sendLocaleEvent(); // check legacy setting - QString notesPath = - settings.value(QStringLiteral("General/notesPath")).toString(); + QString notesPath = settings.value(QStringLiteral("General/notesPath")).toString(); // migration: remove old setting if we found one and store new one if (!notesPath.isEmpty()) { @@ -270,17 +249,14 @@ bool mainStartupMisc(const QStringList &arguments) { // if this isn't the first run but the note folder doesn't exist any more // let the user select another one if (!notesPath.isEmpty() && !dir.exists()) { - if (QMessageBox::question( - nullptr, QObject::tr("Note folder not found!"), - QObject::tr("Your note folder was not found any more! Do you " - "want to select a new one?")) != QMessageBox::Yes) { + if (QMessageBox::question(nullptr, QObject::tr("Note folder not found!"), + QObject::tr("Your note folder was not found any more! Do you " + "want to select a new one?")) != QMessageBox::Yes) { return false; } notesPath = QFileDialog::getExistingDirectory( - nullptr, - QObject::tr( - "Please select the folder where your notes will get stored to"), + nullptr, QObject::tr("Please select the folder where your notes will get stored to"), notesPath, QFileDialog::ShowDirsOnly); dir = QDir(notesPath); @@ -315,9 +291,7 @@ bool mainStartupMisc(const QStringList &arguments) { NoteFolder::migrateToNoteFolders(); if (parser.isSet(dumpSettingsOption)) { - fprintf( - stdout, "%s\n", - Utils::Misc::generateDebugInformation().toLocal8Bit().constData()); + fprintf(stdout, "%s\n", Utils::Misc::generateDebugInformation().toLocal8Bit().constData()); exit(0); } @@ -342,12 +316,11 @@ bool mainStartupMisc(const QStringList &arguments) { /** * Temporary log output until LogWidget::logMessageOutput takes over */ -void tempLogMessageOutput(QtMsgType type, const QMessageLogContext &context, - const QString &msg) { +void tempLogMessageOutput(QtMsgType type, const QMessageLogContext &context, const QString &msg) { QByteArray localMsg = msg.toLocal8Bit(); auto typeText = Utils::Misc::logMsgTypeText(type); - auto message = QStringLiteral("%1 (%2:%3, %4)").arg( - msg, context.file, QString::number(context.line), context.function); + auto message = QStringLiteral("%1 (%2:%3, %4)") + .arg(msg, context.file, QString::number(context.line), context.function); auto messageWithType = QStringLiteral("%1: %2\n").arg(typeText, message); switch (type) { @@ -370,8 +343,8 @@ void tempLogMessageOutput(QtMsgType type, const QMessageLogContext &context, } inline void setAppProperties(QCoreApplication &app, const QString &release, - const QStringList &arguments, bool singleApp, - bool snap, bool portable, const QString &action) { + const QStringList &arguments, bool singleApp, bool snap, bool portable, + const QString &action) { app.setProperty("release", release); app.setProperty("portable", portable); if (singleApp) app.setProperty("singleApplication", true); @@ -424,8 +397,7 @@ int main(int argc, char *argv[]) { portable = true; } else if (arg == QStringLiteral("--clear-settings")) { clearSettings = true; - } else if (arg == QStringLiteral("--help") || - arg == QStringLiteral("--dump-settings") || + } else if (arg == QStringLiteral("--help") || arg == QStringLiteral("--dump-settings") || arg == QStringLiteral("-h") || arg == QStringLiteral("--allow-multiple-instances")) { allowOnlyOneAppInstance = false; @@ -481,8 +453,7 @@ int main(int argc, char *argv[]) { QCoreApplication::setOrganizationDomain(QStringLiteral("PBE")); QCoreApplication::setOrganizationName(QStringLiteral("PBE")); - QCoreApplication::setApplicationName(QStringLiteral("QOwnNotes") + - appNameAdd); + QCoreApplication::setApplicationName(QStringLiteral("QOwnNotes") + appNameAdd); QString appVersion = QStringLiteral(VERSION); @@ -527,8 +498,7 @@ int main(int argc, char *argv[]) { } QSettings settings; - QString locale = - settings.value(QStringLiteral("interfaceLanguage")).toString(); + QString locale = settings.value(QStringLiteral("interfaceLanguage")).toString(); if (locale.isEmpty()) { locale = QLocale::system().name().section('_', 0, 0); @@ -554,8 +524,7 @@ int main(int argc, char *argv[]) { // settings if (allowOnlyOneAppInstance) { allowOnlyOneAppInstance = - settings.value(QStringLiteral("allowOnlyOneAppInstance"), true) - .toBool(); + settings.value(QStringLiteral("allowOnlyOneAppInstance"), true).toBool(); } #endif @@ -571,9 +540,9 @@ int main(int argc, char *argv[]) { // if only one app instance is allowed use SingleApplication if (allowOnlyOneAppInstance) { - SingleApplication app(argc, argv, true, - SingleApplication::Mode::User | - SingleApplication::Mode::SecondaryNotification); + SingleApplication app( + argc, argv, true, + SingleApplication::Mode::User | SingleApplication::Mode::SecondaryNotification); // quit app if it was already started if (app.isSecondary()) { @@ -613,17 +582,18 @@ int main(int argc, char *argv[]) { w.show(); // receive messages from the primary app - QObject::connect(&app, &SingleApplication::receivedMessage, [&](quint32 instanceId, QByteArray message) { - Q_UNUSED(instanceId) - qDebug() << __func__ << " - 'message': " << message; + QObject::connect(&app, &SingleApplication::receivedMessage, + [&](quint32 instanceId, QByteArray message) { + Q_UNUSED(instanceId) + qDebug() << __func__ << " - 'message': " << message; - // trigger the startup menu action - if (message.startsWith("startupAction:")) { - message.remove(0, 14); - app.setProperty("startupAction", message); - w.triggerStartupMenuAction(); - } - }); + // trigger the startup menu action + if (message.startsWith("startupAction:")) { + message.remove(0, 14); + app.setProperty("startupAction", message); + w.triggerStartupMenuAction(); + } + }); // raise the main window if app was started a 2nd time in single // application mode diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp index f26efc1d4..7e9e02de7 100644 --- a/src/mainwindow.cpp +++ b/src/mainwindow.cpp @@ -13,14 +13,14 @@ */ #include "mainwindow.h" -#include <memory> + #include <dialogs/actiondialog.h> #include <dialogs/attachmentdialog.h> #include <dialogs/dictionarymanagerdialog.h> #include <dialogs/evernoteimportdialog.h> -#include <dialogs/joplinimportdialog.h> #include <dialogs/filedialog.h> #include <dialogs/imagedialog.h> +#include <dialogs/joplinimportdialog.h> #include <dialogs/localtrashdialog.h> #include <dialogs/notedialog.h> #include <dialogs/scriptrepositorydialog.h> @@ -43,8 +43,8 @@ #include <utils/misc.h> #include <utils/schema.h> #include <widgets/logwidget.h> -#include <widgets/notetreewidgetitem.h> #include <widgets/notesubfoldertree.h> +#include <widgets/notetreewidgetitem.h> #include <QAbstractEventDispatcher> #include <QActionGroup> @@ -90,6 +90,7 @@ #include <QUuid> #include <QWidgetAction> #include <libraries/qttoolbareditor/src/toolbar_editor.hpp> +#include <memory> #include <utility> #include "build_number.h" @@ -113,36 +114,32 @@ #include "services/metricsservice.h" #include "services/owncloudservice.h" #include "services/updateservice.h" -#include "services/websocketserverservice.h" #include "services/webappclientservice.h" +#include "services/websocketserverservice.h" #include "ui_mainwindow.h" -#include "version.h" -#include "widgets/qownnotesmarkdowntextedit.h" -#include "widgets/htmlpreviewwidget.h" #include "utils/urlhandler.h" +#include "version.h" +#include "widgets/htmlpreviewwidget.h" +#include "widgets/qownnotesmarkdowntextedit.h" -static MainWindow* s_self = nullptr; +static MainWindow *s_self = nullptr; struct FileWatchDisabler { - FileWatchDisabler(MainWindow *mw) - : _mainWindow(mw) - { + FileWatchDisabler(MainWindow *mw) : _mainWindow(mw) { Q_ASSERT(mw); QObject::disconnect(&mw->noteDirectoryWatcher, nullptr, nullptr, nullptr); } - ~FileWatchDisabler() - { + ~FileWatchDisabler() { Q_ASSERT(_mainWindow); _mainWindow->connectFileWatcher(/*delayed = */ true); } -private: + + private: MainWindow *const _mainWindow = nullptr; }; -MainWindow::MainWindow(QWidget *parent) - : QMainWindow(parent) { - +MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) { // static reference to us s_self = this; ui = new Ui::MainWindow; @@ -162,15 +159,14 @@ MainWindow::MainWindow(QWidget *parent) QSettings settings; _noteEditIsCentralWidget = - settings.value(QStringLiteral("noteEditIsCentralWidget"), true) - .toBool(); + settings.value(QStringLiteral("noteEditIsCentralWidget"), true).toBool(); #if QT_VERSION >= QT_VERSION_CHECK(5, 4, 0) ui->noteEditTabWidget->setTabBarAutoHide(true); #endif ui->noteEditTabWidget->tabBar()->setContextMenuPolicy(Qt::CustomContextMenu); - connect(ui->noteEditTabWidget->tabBar(), &QWidget::customContextMenuRequested, - this, &MainWindow::showNoteEditTabWidgetContextMenu); + connect(ui->noteEditTabWidget->tabBar(), &QWidget::customContextMenuRequested, this, + &MainWindow::showNoteEditTabWidgetContextMenu); initTreeWidgets(); @@ -187,14 +183,11 @@ MainWindow::MainWindow(QWidget *parent) ui->actionShare_note->setIconVisibleInMenu(false); // set another shortcut for delete line under macOS - ui->actionDelete_line->setShortcut( - QKeySequence(QStringLiteral("Ctrl+Backspace"))); - ui->actionDelete_word->setShortcut( - QKeySequence(QStringLiteral("Alt+Backspace"))); + ui->actionDelete_line->setShortcut(QKeySequence(QStringLiteral("Ctrl+Backspace"))); + ui->actionDelete_word->setShortcut(QKeySequence(QStringLiteral("Alt+Backspace"))); // set another shortcut for the full-screen mode - ui->actionToggle_fullscreen->setShortcut( - QKeySequence(QStringLiteral("Ctrl+F11"))); + ui->actionToggle_fullscreen->setShortcut(QKeySequence(QStringLiteral("Ctrl+F11"))); #endif _noteViewIsRegenerated = false; @@ -213,9 +206,8 @@ MainWindow::MainWindow(QWidget *parent) _leaveFullScreenModeButton = nullptr; _useNoteFolderButtons = settings.value("useNoteFolderButtons").toBool(); - this->setWindowTitle(QStringLiteral("QOwnNotes - version ") + - QStringLiteral(VERSION) + QStringLiteral(" - build ") + - QString::number(BUILD)); + this->setWindowTitle(QStringLiteral("QOwnNotes - version ") + QStringLiteral(VERSION) + + QStringLiteral(" - build ") + QString::number(BUILD)); ClientProxy proxy; // refresh the Qt proxy settings @@ -248,10 +240,8 @@ MainWindow::MainWindow(QWidget *parent) #ifdef Q_OS_MAC // add some different shortcuts for the note history on the mac - ui->action_Back_in_note_history->setShortcut(Qt::CTRL | Qt::ALT | - Qt::Key_Left); - ui->action_Forward_in_note_history->setShortcut(Qt::CTRL | Qt::ALT | - Qt::Key_Right); + ui->action_Back_in_note_history->setShortcut(Qt::CTRL | Qt::ALT | Qt::Key_Left); + ui->action_Forward_in_note_history->setShortcut(Qt::CTRL | Qt::ALT | Qt::Key_Right); // add another shortcut for the auto-completer ui->actionAutocomplete->setShortcut(Qt::META | Qt::Key_Space); @@ -261,14 +251,11 @@ MainWindow::MainWindow(QWidget *parent) #endif // adding some alternate shortcuts for changing the current note - auto *shortcut = - new QShortcut(QKeySequence(QStringLiteral("Ctrl+PgDown")), this); - connect(shortcut, &QShortcut::activated, this, - &MainWindow::on_actionNext_note_triggered); + auto *shortcut = new QShortcut(QKeySequence(QStringLiteral("Ctrl+PgDown")), this); + connect(shortcut, &QShortcut::activated, this, &MainWindow::on_actionNext_note_triggered); shortcut = new QShortcut(QKeySequence(QStringLiteral("Ctrl+PgUp")), this); - connect(shortcut, &QShortcut::activated, this, - &MainWindow::on_actionPrevious_Note_triggered); + connect(shortcut, &QShortcut::activated, this, &MainWindow::on_actionPrevious_Note_triggered); // read the settings (shortcuts have to be defined before that) readSettings(); @@ -312,24 +299,21 @@ MainWindow::MainWindow(QWidget *parent) // look if we need to save something every 10 sec (default) this->noteSaveTimer = new QTimer(this); - connect(this->noteSaveTimer, &QTimer::timeout, this, - &MainWindow::storeUpdatedNotesToDisk); + connect(this->noteSaveTimer, &QTimer::timeout, this, &MainWindow::storeUpdatedNotesToDisk); this->noteSaveTimer->start(this->noteSaveIntervalTime * 1000); // look if we need update the note view every two seconds _noteViewUpdateTimer = new QTimer(this); _noteViewUpdateTimer->setSingleShot(true); - connect(_noteViewUpdateTimer, &QTimer::timeout, this, - &MainWindow::noteViewUpdateTimerSlot); + connect(_noteViewUpdateTimer, &QTimer::timeout, this, &MainWindow::noteViewUpdateTimerSlot); _noteViewUpdateTimer->start(2000); // commit changes from the current note folder to git every 30 sec gitCommitCurrentNoteFolder(); _gitCommitTimer = new QTimer(this); - connect(_gitCommitTimer, &QTimer::timeout, this, - &MainWindow::gitCommitCurrentNoteFolder); + connect(_gitCommitTimer, &QTimer::timeout, this, &MainWindow::gitCommitCurrentNoteFolder); _gitCommitTimer->start(_gitCommitInterval * 1000); // set last heartbeat in the past, so it gets called the first time @@ -410,8 +394,7 @@ MainWindow::MainWindow(QWidget *parent) const auto toolbars = findChildren<QToolBar *>(); for (QToolBar *toolbar : toolbars) { - connect(toolbar, &QToolBar::visibilityChanged, this, - &MainWindow::toolbarVisibilityChanged); + connect(toolbar, &QToolBar::visibilityChanged, this, &MainWindow::toolbarVisibilityChanged); } // set the action group for the width selector of the distraction free mode @@ -437,16 +420,14 @@ MainWindow::MainWindow(QWidget *parent) // create a timer to load all tasks every 10min _todoListTimer = new QTimer(this); - connect(_todoListTimer, &QTimer::timeout, this, - &MainWindow::reloadTodoLists); + connect(_todoListTimer, &QTimer::timeout, this, &MainWindow::reloadTodoLists); _todoListTimer->start(600000); // set up the soft-wrap checkbox const QSignalBlocker blocker2(ui->actionUse_softwrap_in_note_editor); Q_UNUSED(blocker2) ui->actionUse_softwrap_in_note_editor->setChecked( - settings.value(QStringLiteral("useSoftWrapInNoteEditor"), true) - .toBool()); + settings.value(QStringLiteral("useSoftWrapInNoteEditor"), true).toBool()); // initialize the editor soft wrapping initEditorSoftWrap(); @@ -455,17 +436,14 @@ MainWindow::MainWindow(QWidget *parent) MetricsService::instance()->sendEventIfEnabled( QStringLiteral("app/has-owncloud-settings"), QStringLiteral("app"), QStringLiteral("has owncloud settings"), - OwnCloudService::hasOwnCloudSettings() ? QStringLiteral("yes") - : QStringLiteral("no")); + OwnCloudService::hasOwnCloudSettings() ? QStringLiteral("yes") : QStringLiteral("no")); // send an event for counting the editor color schemes const int schemaCount = - settings.value(QStringLiteral("Editor/ColorSchemes")) - .toStringList() - .count(); + settings.value(QStringLiteral("Editor/ColorSchemes")).toStringList().count(); MetricsService::instance()->sendEventIfEnabled( - QStringLiteral("app/editor-color-schema-count"), - QStringLiteral("editor"), QStringLiteral("editor color schema count"), + QStringLiteral("app/editor-color-schema-count"), QStringLiteral("editor"), + QStringLiteral("editor color schema count"), QString::number(schemaCount) + QStringLiteral(" schemas"), schemaCount); _actionDialog = nullptr; @@ -475,8 +453,7 @@ MainWindow::MainWindow(QWidget *parent) _issueAssistantDialog = nullptr; // restore the note tabs - Utils::Gui::restoreNoteTabs(ui->noteEditTabWidget, - ui->noteEditTabWidgetLayout); + Utils::Gui::restoreNoteTabs(ui->noteEditTabWidget, ui->noteEditTabWidgetLayout); if (isInDistractionFreeMode()) { ui->noteEditTabWidget->tabBar()->hide(); @@ -485,8 +462,7 @@ MainWindow::MainWindow(QWidget *parent) // restore the note history of the current note folder noteHistory.restoreForCurrentNoteFolder(); - if (settings.value(QStringLiteral("restoreLastNoteAtStartup"), true) - .toBool()) { + if (settings.value(QStringLiteral("restoreLastNoteAtStartup"), true).toBool()) { // try to restore the last note before the app was quit // if that fails jump to the first note // we do that with a timer, because otherwise the scrollbar will not be @@ -503,8 +479,7 @@ MainWindow::MainWindow(QWidget *parent) startAppVersionTest(); // attempt to quit the application when a logout is initiated - connect(qApp, &QApplication::commitDataRequest, this, - &MainWindow::on_action_Quit_triggered); + connect(qApp, &QApplication::commitDataRequest, this, &MainWindow::on_action_Quit_triggered); automaticScriptUpdateCheck(); @@ -514,21 +489,20 @@ MainWindow::MainWindow(QWidget *parent) resizeTagTreeWidgetColumnToContents(); } -void MainWindow::initTreeWidgets() -{ - connect(ui->noteSubFolderTreeWidget, &NoteSubFolderTree::multipleSubfoldersSelected, this, &MainWindow::onMultipleSubfoldersSelected); - connect(ui->noteSubFolderTreeWidget, &NoteSubFolderTree::currentSubFolderChanged, this, &MainWindow::onCurrentSubFolderChanged); +void MainWindow::initTreeWidgets() { + connect(ui->noteSubFolderTreeWidget, &NoteSubFolderTree::multipleSubfoldersSelected, this, + &MainWindow::onMultipleSubfoldersSelected); + connect(ui->noteSubFolderTreeWidget, &NoteSubFolderTree::currentSubFolderChanged, this, + &MainWindow::onCurrentSubFolderChanged); } -void MainWindow::initNotePreviewAndTextEdits() -{ +void MainWindow::initNotePreviewAndTextEdits() { QSettings settings; // set the search frames for the note text edits const bool darkMode = settings.value(QStringLiteral("darkMode")).toBool(); ui->noteTextEdit->initSearchFrame(ui->noteTextEditSearchFrame, darkMode); - ui->encryptedNoteTextEdit->initSearchFrame(ui->noteTextEditSearchFrame, - darkMode); + ui->encryptedNoteTextEdit->initSearchFrame(ui->noteTextEditSearchFrame, darkMode); // setup vim mode if (settings.value(QStringLiteral("Editor/vimMode")).toBool()) { @@ -537,21 +511,19 @@ void MainWindow::initNotePreviewAndTextEdits() } // do the navigation parsing after the highlighter was finished - connect(ui->noteTextEdit->highlighter(), - &QOwnNotesMarkdownHighlighter::highlightingFinished, this, - &MainWindow::startNavigationParser); + connect(ui->noteTextEdit->highlighter(), &QOwnNotesMarkdownHighlighter::highlightingFinished, + this, &MainWindow::startNavigationParser); connect(ui->encryptedNoteTextEdit->highlighter(), &QOwnNotesMarkdownHighlighter::highlightingFinished, this, &MainWindow::startNavigationParser); // track cursor position changes for the line number label - connect(ui->noteTextEdit, &QOwnNotesMarkdownTextEdit::cursorPositionChanged, - this, &MainWindow::noteEditCursorPositionChanged); + connect(ui->noteTextEdit, &QOwnNotesMarkdownTextEdit::cursorPositionChanged, this, + &MainWindow::noteEditCursorPositionChanged); // track cursor position changes for the line number label - connect(ui->encryptedNoteTextEdit, - &QOwnNotesMarkdownTextEdit::cursorPositionChanged, this, + connect(ui->encryptedNoteTextEdit, &QOwnNotesMarkdownTextEdit::cursorPositionChanged, this, &MainWindow::noteEditCursorPositionChanged); // TODO: Remove and handle this in widgets directly @@ -562,8 +534,7 @@ void MainWindow::initNotePreviewAndTextEdits() #ifdef USE_QLITEHTML _notePreviewWidget = new HtmlPreviewWidget(this); - if (!ui->noteViewFrame->layout()) - ui->noteViewFrame->setLayout(new QVBoxLayout); + if (!ui->noteViewFrame->layout()) ui->noteViewFrame->setLayout(new QVBoxLayout); ui->noteViewFrame->layout()->addWidget(_notePreviewWidget); // QTextBrowser previewer is hidden when we use qlitehtml @@ -573,33 +544,37 @@ void MainWindow::initNotePreviewAndTextEdits() _notePreviewWidget->installEventFilter(this); _notePreviewWidget->viewport()->installEventFilter(this); - connect(_notePreviewWidget, &HtmlPreviewWidget::anchorClicked, this, &MainWindow::onNotePreviewAnchorClicked); + connect(_notePreviewWidget, &HtmlPreviewWidget::anchorClicked, this, + &MainWindow::onNotePreviewAnchorClicked); #else ui->noteTextView->installEventFilter(this); ui->noteTextView->viewport()->installEventFilter(this); - connect(ui->noteTextView, &NotePreviewWidget::resize, this, - &MainWindow::onNoteTextViewResize); + connect(ui->noteTextView, &NotePreviewWidget::resize, this, &MainWindow::onNoteTextViewResize); - // TODO centralize dark mode handling - ui->noteTextView->initSearchFrame(ui->noteTextViewSearchFrame, darkMode); + // TODO centralize dark mode handling + ui->noteTextView->initSearchFrame(ui->noteTextViewSearchFrame, darkMode); - connect(ui->noteTextView, &QTextBrowser::anchorClicked, this, &MainWindow::onNotePreviewAnchorClicked); + connect(ui->noteTextView, &QTextBrowser::anchorClicked, this, + &MainWindow::onNotePreviewAnchorClicked); #endif } -void MainWindow::connectFileWatcher(bool delayed) -{ +void MainWindow::connectFileWatcher(bool delayed) { if (!delayed) { - connect(¬eDirectoryWatcher, &QFileSystemWatcher::directoryChanged, this, &MainWindow::notesDirectoryWasModified, Qt::UniqueConnection); - connect(¬eDirectoryWatcher, &QFileSystemWatcher::fileChanged, this, &MainWindow::notesWereModified, Qt::UniqueConnection); + connect(¬eDirectoryWatcher, &QFileSystemWatcher::directoryChanged, this, + &MainWindow::notesDirectoryWasModified, Qt::UniqueConnection); + connect(¬eDirectoryWatcher, &QFileSystemWatcher::fileChanged, this, + &MainWindow::notesWereModified, Qt::UniqueConnection); } else { // In some cases, there are delayed signals coming in which we don't want to handle // so reconnect with delay - QTimer::singleShot(300, this, [this]{ - connect(¬eDirectoryWatcher, &QFileSystemWatcher::directoryChanged, this, &MainWindow::notesDirectoryWasModified, Qt::UniqueConnection); - connect(¬eDirectoryWatcher, &QFileSystemWatcher::fileChanged, this, &MainWindow::notesWereModified, Qt::UniqueConnection); + QTimer::singleShot(300, this, [this] { + connect(¬eDirectoryWatcher, &QFileSystemWatcher::directoryChanged, this, + &MainWindow::notesDirectoryWasModified, Qt::UniqueConnection); + connect(¬eDirectoryWatcher, &QFileSystemWatcher::fileChanged, this, + &MainWindow::notesWereModified, Qt::UniqueConnection); }); } } @@ -622,11 +597,11 @@ void MainWindow::triggerStartupMenuAction() { qDebug() << "Running menu action: " << actionName; action->trigger(); } else { - Utils::Gui::warning( - this, tr("Action not found!"), - tr("Could not find menu action <code>%1</code>! " - "Did you spell it correctly?").arg(actionName), - "menu-action-not-found"); + Utils::Gui::warning(this, tr("Action not found!"), + tr("Could not find menu action <code>%1</code>! " + "Did you spell it correctly?") + .arg(actionName), + "menu-action-not-found"); } }); } @@ -636,7 +611,7 @@ void MainWindow::triggerStartupMenuAction() { */ void MainWindow::initGlobalKeyboardShortcuts() { // deleting old global shortcut assignments - foreach(QHotkey *hotKey, _globalShortcuts) { + foreach (QHotkey *hotKey, _globalShortcuts) { delete hotKey; } @@ -644,7 +619,7 @@ void MainWindow::initGlobalKeyboardShortcuts() { QSettings settings; settings.beginGroup(QStringLiteral("GlobalShortcuts")); - foreach(const QString &key, settings.allKeys()) { + foreach (const QString &key, settings.allKeys()) { if (!key.contains(QStringLiteral("MainWindow"))) { continue; } @@ -681,9 +656,7 @@ void MainWindow::initWebSocketServerService() { _webSocketServerService = new WebSocketServerService(); } -void MainWindow::initWebAppClientService() { - _webAppClientService = new WebAppClientService(); -} +void MainWindow::initWebAppClientService() { _webAppClientService = new WebAppClientService(); } void MainWindow::initFakeVim(QOwnNotesMarkdownTextEdit *noteTextEdit) { auto handler = new FakeVim::Internal::FakeVimHandler(noteTextEdit, this); @@ -770,10 +743,9 @@ MainWindow::~MainWindow() { */ void MainWindow::initWorkspaceComboBox() { _workspaceComboBox = new QComboBox(this); - connect( - _workspaceComboBox, - static_cast<void (QComboBox::*)(int)>(&QComboBox::currentIndexChanged), - this, &MainWindow::onWorkspaceComboBoxCurrentIndexChanged); + connect(_workspaceComboBox, + static_cast<void (QComboBox::*)(int)>(&QComboBox::currentIndexChanged), this, + &MainWindow::onWorkspaceComboBoxCurrentIndexChanged); _workspaceComboBox->setToolTip(tr("Workspaces")); _workspaceComboBox->setObjectName(QStringLiteral("workspaceComboBox")); } @@ -788,16 +760,13 @@ void MainWindow::initDockWidgets() { QSizePolicy sizePolicy; _noteSubFolderDockWidget = new QDockWidget(tr("Subfolders"), this); - _noteSubFolderDockWidget->setObjectName( - QStringLiteral("noteSubFolderDockWidget")); + _noteSubFolderDockWidget->setObjectName(QStringLiteral("noteSubFolderDockWidget")); _noteSubFolderDockWidget->setWidget(ui->noteSubFolderFrame); - _noteSubFolderDockTitleBarWidget = - _noteSubFolderDockWidget->titleBarWidget(); + _noteSubFolderDockTitleBarWidget = _noteSubFolderDockWidget->titleBarWidget(); sizePolicy = _noteSubFolderDockWidget->sizePolicy(); sizePolicy.setHorizontalStretch(2); _noteSubFolderDockWidget->setSizePolicy(sizePolicy); - addDockWidget(Qt::LeftDockWidgetArea, _noteSubFolderDockWidget, - Qt::Horizontal); + addDockWidget(Qt::LeftDockWidgetArea, _noteSubFolderDockWidget, Qt::Horizontal); _taggingDockWidget = new QDockWidget(tr("Tags"), this); _taggingDockWidget->setObjectName(QStringLiteral("taggingDockWidget")); @@ -809,8 +778,7 @@ void MainWindow::initDockWidgets() { addDockWidget(Qt::LeftDockWidgetArea, _taggingDockWidget, Qt::Vertical); _noteSearchDockWidget = new QDockWidget(tr("Note search"), this); - _noteSearchDockWidget->setObjectName( - QStringLiteral("noteSearchDockWidget")); + _noteSearchDockWidget->setObjectName(QStringLiteral("noteSearchDockWidget")); _noteSearchDockWidget->setWidget(ui->searchLineEdit); _noteSearchDockTitleBarWidget = _noteSearchDockWidget->titleBarWidget(); sizePolicy = _noteSearchDockWidget->sizePolicy(); @@ -819,8 +787,7 @@ void MainWindow::initDockWidgets() { addDockWidget(Qt::LeftDockWidgetArea, _noteSearchDockWidget, Qt::Vertical); _noteFolderDockWidget = new QDockWidget(tr("Note folder"), this); - _noteFolderDockWidget->setObjectName( - QStringLiteral("noteFolderDockWidget")); + _noteFolderDockWidget->setObjectName(QStringLiteral("noteFolderDockWidget")); if (_useNoteFolderButtons) { _noteFolderDockWidgetFrame = new QFrame(_noteFolderDockWidget); @@ -847,31 +814,25 @@ void MainWindow::initDockWidgets() { addDockWidget(Qt::LeftDockWidgetArea, _noteListDockWidget, Qt::Vertical); _noteNavigationDockWidget = new QDockWidget(tr("Navigation"), this); - _noteNavigationDockWidget->setObjectName( - QStringLiteral("noteNavigationDockWidget")); + _noteNavigationDockWidget->setObjectName(QStringLiteral("noteNavigationDockWidget")); _noteNavigationDockWidget->setWidget(ui->navigationFrame); - _noteNavigationDockTitleBarWidget = - _noteNavigationDockWidget->titleBarWidget(); + _noteNavigationDockTitleBarWidget = _noteNavigationDockWidget->titleBarWidget(); sizePolicy = _noteNavigationDockWidget->sizePolicy(); sizePolicy.setHorizontalStretch(2); _noteNavigationDockWidget->setSizePolicy(sizePolicy); - addDockWidget(Qt::LeftDockWidgetArea, _noteNavigationDockWidget, - Qt::Vertical); + addDockWidget(Qt::LeftDockWidgetArea, _noteNavigationDockWidget, Qt::Vertical); // we want the navigation under the note list - splitDockWidget(_noteListDockWidget, _noteNavigationDockWidget, - Qt::Vertical); + splitDockWidget(_noteListDockWidget, _noteNavigationDockWidget, Qt::Vertical); if (!_noteEditIsCentralWidget) { _noteEditDockWidget = new QDockWidget(tr("Note edit"), this); - _noteEditDockWidget->setObjectName( - QStringLiteral("noteEditDockWidget")); + _noteEditDockWidget->setObjectName(QStringLiteral("noteEditDockWidget")); _noteEditDockWidget->setWidget(ui->noteEditTabWidget); _noteEditDockTitleBarWidget = _noteEditDockWidget->titleBarWidget(); sizePolicy = _noteEditDockWidget->sizePolicy(); sizePolicy.setHorizontalStretch(5); _noteEditDockWidget->setSizePolicy(sizePolicy); - addDockWidget(Qt::RightDockWidgetArea, _noteEditDockWidget, - Qt::Horizontal); + addDockWidget(Qt::RightDockWidgetArea, _noteEditDockWidget, Qt::Horizontal); } _noteTagDockWidget = new QDockWidget(tr("Note tags"), this); @@ -881,17 +842,14 @@ void MainWindow::initDockWidgets() { sizePolicy = _noteTagDockWidget->sizePolicy(); sizePolicy.setHorizontalStretch(5); _noteTagDockWidget->setSizePolicy(sizePolicy); - addDockWidget(_noteEditIsCentralWidget ? Qt::LeftDockWidgetArea - : Qt::RightDockWidgetArea, + addDockWidget(_noteEditIsCentralWidget ? Qt::LeftDockWidgetArea : Qt::RightDockWidgetArea, _noteTagDockWidget, Qt::Vertical); _notePreviewDockWidget = new QDockWidget(tr("Note preview"), this); - _notePreviewDockWidget->setObjectName( - QStringLiteral("notePreviewDockWidget")); + _notePreviewDockWidget->setObjectName(QStringLiteral("notePreviewDockWidget")); _notePreviewDockWidget->setWidget(ui->noteViewFrame); _notePreviewDockTitleBarWidget = _notePreviewDockWidget->titleBarWidget(); - addDockWidget(Qt::RightDockWidgetArea, _notePreviewDockWidget, - Qt::Horizontal); + addDockWidget(Qt::RightDockWidgetArea, _notePreviewDockWidget, Qt::Horizontal); _logDockWidget = new QDockWidget(tr("Log"), this); _logDockWidget->setObjectName(QStringLiteral("logDockWidget")); @@ -973,8 +931,7 @@ void MainWindow::releaseDockWidgetSizes() { */ void MainWindow::initShowHidden() { QSettings settings; - const bool startHidden = - settings.value(QStringLiteral("StartHidden"), false).toBool(); + const bool startHidden = settings.value(QStringLiteral("StartHidden"), false).toBool(); if (startHidden) { QTimer::singleShot(250, this, SLOT(hide())); } @@ -990,8 +947,7 @@ void MainWindow::initShowHidden() { void MainWindow::initTagButtonScrollArea() { _noteTagButtonScrollArea = new QScrollArea(this); _noteTagButtonScrollArea->setWidgetResizable(true); - _noteTagButtonScrollArea->setSizePolicy(QSizePolicy::MinimumExpanding, - QSizePolicy::Ignored); + _noteTagButtonScrollArea->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Ignored); _noteTagButtonScrollArea->setAlignment(Qt::AlignLeft); _noteTagButtonScrollArea->setWidget(ui->noteTagButtonFrame); @@ -1018,9 +974,7 @@ void MainWindow::initTagButtonScrollArea() { /** * Returns all menus from the menu bar */ -QList<QMenu *> MainWindow::menuList() { - return ui->menuBar->findChildren<QMenu *>(); -} +QList<QMenu *> MainWindow::menuList() { return ui->menuBar->findChildren<QMenu *>(); } /** * Finds an action in all menus of the menu bar @@ -1050,8 +1004,7 @@ QAction *MainWindow::findAction(const QString &objectName) { * @param forceLoad * @param reloadTabs */ -void MainWindow::buildNotesIndexAndLoadNoteDirectoryList(bool forceBuild, - bool forceLoad, +void MainWindow::buildNotesIndexAndLoadNoteDirectoryList(bool forceBuild, bool forceLoad, bool reloadTabs) { const bool wasBuilt = buildNotesIndex(0, forceBuild); @@ -1068,9 +1021,7 @@ void MainWindow::buildNotesIndexAndLoadNoteDirectoryList(bool forceBuild, /** * Returns the global main window instance */ -MainWindow *MainWindow::instance() { - return s_self; -} +MainWindow *MainWindow::instance() { return s_self; } /** * Initializes the editor soft wrapping @@ -1078,14 +1029,12 @@ MainWindow *MainWindow::instance() { void MainWindow::initEditorSoftWrap() { QSettings settings; const bool useSoftWrapInNoteEditor = - settings.value(QStringLiteral("useSoftWrapInNoteEditor"), true) - .toBool(); + settings.value(QStringLiteral("useSoftWrapInNoteEditor"), true).toBool(); QTextEdit::LineWrapMode mode = useSoftWrapInNoteEditor ? QTextEdit::WidgetWidth : QTextEdit::NoWrap; - QPlainTextEdit::LineWrapMode pMode = useSoftWrapInNoteEditor - ? QPlainTextEdit::WidgetWidth - : QPlainTextEdit::NoWrap; + QPlainTextEdit::LineWrapMode pMode = + useSoftWrapInNoteEditor ? QPlainTextEdit::WidgetWidth : QPlainTextEdit::NoWrap; Q_UNUSED(mode) ui->noteTextEdit->setLineWrapMode(pMode); @@ -1106,10 +1055,8 @@ void MainWindow::reloadTodoLists() { QSettings settings; QStringList calendars = - settings.value(QStringLiteral("ownCloud/todoCalendarEnabledList")) - .toStringList(); - QString serverUrl = - CloudConnection::currentCloudConnection().getServerUrl(); + settings.value(QStringLiteral("ownCloud/todoCalendarEnabledList")).toStringList(); + QString serverUrl = CloudConnection::currentCloudConnection().getServerUrl(); if (calendars.count() > 0 && !serverUrl.isEmpty()) { OwnCloudService *ownCloud = OwnCloudService::instance(); @@ -1120,8 +1067,7 @@ void MainWindow::reloadTodoLists() { ownCloud->todoGetTodoList(calendar, nullptr); } - showStatusBarMessage(tr("Your tasks are being loaded from your server"), - 4000); + showStatusBarMessage(tr("Your tasks are being loaded from your server"), 4000); // generate the system tray context menu to show modified tasks // in 15 sec (because we don't know when all new tasks will be loaded) @@ -1140,8 +1086,7 @@ void MainWindow::initScriptingEngine() { QQmlEngine *engine = scriptingService->engine(); // engine->setObjectOwnership(ui->noteTextEdit, // QQmlEngine::CppOwnership); - engine->rootContext()->setContextProperty(QStringLiteral("noteTextEdit"), - ui->noteTextEdit); + engine->rootContext()->setContextProperty(QStringLiteral("noteTextEdit"), ui->noteTextEdit); scriptingService->initComponents(); } @@ -1260,10 +1205,9 @@ void MainWindow::updateWorkspaceLists(bool rebuild) { continue; } - const QString name = settings - .value(QStringLiteral("workspace-") + uuid + - QStringLiteral("/name")) - .toString(); + const QString name = + settings.value(QStringLiteral("workspace-") + uuid + QStringLiteral("/name")) + .toString(); const QString objectName = QStringLiteral("restoreWorkspace-") + uuid; _workspaceNameUuidMap.insert(name, uuid); @@ -1271,16 +1215,14 @@ void MainWindow::updateWorkspaceLists(bool rebuild) { _workspaceComboBox->addItem(name, uuid); auto *action = new QAction(name, ui->menuWorkspaces); - connect(action, &QAction::triggered, this, - [this, uuid]() { setCurrentWorkspace(uuid); }); + connect(action, &QAction::triggered, this, [this, uuid]() { setCurrentWorkspace(uuid); }); // set an object name for creating shortcuts action->setObjectName(objectName); // try to load a key sequence from the settings QKeySequence shortcut = QKeySequence( - settings.value(QStringLiteral("Shortcuts/MainWindow-") + objectName) - .toString()); + settings.value(QStringLiteral("Shortcuts/MainWindow-") + objectName).toString()); action->setShortcut(shortcut); // if (uuid == currentUuid) { @@ -1357,8 +1299,7 @@ void MainWindow::updatePanelMenu() { const auto dockWidgets = findChildren<QDockWidget *>(); for (QDockWidget *dockWidget : dockWidgets) { auto *action = new QAction(this); - const QString objectName = - QStringLiteral("togglePanel-") + dockWidget->objectName(); + const QString objectName = QStringLiteral("togglePanel-") + dockWidget->objectName(); action->setText(tr("Show %1 panel").arg(dockWidget->windowTitle())); action->setObjectName(objectName); @@ -1367,16 +1308,14 @@ void MainWindow::updatePanelMenu() { // disable the noteSubFolderDockWidget menu entry if subfolders are // not enabled - if (dockWidget->objectName() == - QStringLiteral("noteSubFolderDockWidget") && + if (dockWidget->objectName() == QStringLiteral("noteSubFolderDockWidget") && !NoteFolder::isCurrentShowSubfolders()) { action->setEnabled(false); } // try to load a key sequence from the settings QKeySequence shortcut = QKeySequence( - settings.value(QStringLiteral("Shortcuts/MainWindow-") + objectName) - .toString()); + settings.value(QStringLiteral("Shortcuts/MainWindow-") + objectName).toString()); action->setShortcut(shortcut); // toggle the panel if the checkbox was triggered @@ -1406,15 +1345,13 @@ void MainWindow::updateToolbarMenu() { for (QToolBar *toolbar : toolbars) { auto *action = new QAction(this); action->setText(tr("Show %1").arg(toolbar->windowTitle())); - action->setObjectName(QStringLiteral("toggleToolBar-") + - toolbar->objectName()); + action->setObjectName(QStringLiteral("toggleToolBar-") + toolbar->objectName()); action->setCheckable(true); action->setChecked(!toolbar->isHidden()); // toggle the panel if the checkbox was triggered - connect(action, &QAction::triggered, this, [this, toolbar]() { - toggleToolbarVisibility(toolbar->objectName()); - }); + connect(action, &QAction::triggered, this, + [this, toolbar]() { toggleToolbarVisibility(toolbar->objectName()); }); ui->menuToolbars->addAction(action); } @@ -1446,7 +1383,8 @@ void MainWindow::togglePanelVisibility(const QString &objectName) { // don't allow the note subfolder dock widget to be visible if the // note folder has no subfolders activated or if the note tree feature is enabled if (newVisibility) { - newVisibility = NoteFolder::isCurrentShowSubfolders() && !Utils::Misc::isEnableNoteTree(); + newVisibility = + NoteFolder::isCurrentShowSubfolders() && !Utils::Misc::isEnableNoteTree(); } } @@ -1496,8 +1434,7 @@ void MainWindow::restoreDistractionFreeMode() { */ bool MainWindow::isInDistractionFreeMode() { QSettings settings; - return settings.value(QStringLiteral("DistractionFreeMode/isEnabled")) - .toBool(); + return settings.value(QStringLiteral("DistractionFreeMode/isEnabled")).toBool(); } /** @@ -1512,8 +1449,7 @@ void MainWindow::toggleDistractionFreeMode() { QSettings settings; bool isInDistractionFreeMode = this->isInDistractionFreeMode(); - qDebug() << __func__ - << " - 'isInDistractionFreeMode': " << isInDistractionFreeMode; + qDebug() << __func__ << " - 'isInDistractionFreeMode': " << isInDistractionFreeMode; // store the window settings before we go into distraction free mode if (!isInDistractionFreeMode) { @@ -1523,8 +1459,7 @@ void MainWindow::toggleDistractionFreeMode() { isInDistractionFreeMode = !isInDistractionFreeMode; // remember that we were using the distraction free mode - settings.setValue(QStringLiteral("DistractionFreeMode/isEnabled"), - isInDistractionFreeMode); + settings.setValue(QStringLiteral("DistractionFreeMode/isEnabled"), isInDistractionFreeMode); setDistractionFreeMode(isInDistractionFreeMode); } @@ -1569,9 +1504,8 @@ void MainWindow::initStyling() { .name(); // set the foreground and background color for the note text edits - appStyleSheet += - QStringLiteral("QMarkdownTextEdit{color:%1;background-color:%2;}") - .arg(fgColorName, bgColorName); + appStyleSheet += QStringLiteral("QMarkdownTextEdit{color:%1;background-color:%2;}") + .arg(fgColorName, bgColorName); // set the background color for the note tag frame and its children QFrames appStyleSheet += QStringLiteral( @@ -1582,7 +1516,7 @@ void MainWindow::initStyling() { qApp->setStyleSheet(appStyleSheet); #if (QT_VERSION >= QT_VERSION_CHECK(5, 4, 0)) - QTimer::singleShot(1, this, []{ + QTimer::singleShot(1, this, [] { #endif Utils::Gui::updateInterfaceFontSize(); #if (QT_VERSION >= QT_VERSION_CHECK(5, 4, 0)) @@ -1608,24 +1542,22 @@ void MainWindow::initStyling() { // add a padding for the note tag frame so the `add tag` button doesn't // stick to the right corner - ui->noteTagFrame->setStyleSheet( - "QFrame {border: none; padding-right: 5px;}"); + ui->noteTagFrame->setStyleSheet("QFrame {border: none; padding-right: 5px;}"); #endif // move the note view scrollbar when the note edit scrollbar was moved - connect(ui->noteTextEdit->verticalScrollBar(), SIGNAL(valueChanged(int)), - this, SLOT(noteTextSliderValueChanged(int))); - connect(ui->encryptedNoteTextEdit->verticalScrollBar(), - SIGNAL(valueChanged(int)), this, + connect(ui->noteTextEdit->verticalScrollBar(), SIGNAL(valueChanged(int)), this, + SLOT(noteTextSliderValueChanged(int))); + connect(ui->encryptedNoteTextEdit->verticalScrollBar(), SIGNAL(valueChanged(int)), this, SLOT(noteTextSliderValueChanged(int))); // move the note edit scrollbar when the note view scrollbar was moved #ifdef USE_QLITEHTML - connect(_notePreviewWidget->verticalScrollBar(), SIGNAL(valueChanged(int)), - this, SLOT(noteViewSliderValueChanged(int))); + connect(_notePreviewWidget->verticalScrollBar(), SIGNAL(valueChanged(int)), this, + SLOT(noteViewSliderValueChanged(int))); #else - connect(ui->noteTextView->verticalScrollBar(), SIGNAL(valueChanged(int)), - this, SLOT(noteViewSliderValueChanged(int))); + connect(ui->noteTextView->verticalScrollBar(), SIGNAL(valueChanged(int)), this, + SLOT(noteViewSliderValueChanged(int))); #endif // hide the combo box if it looses focus if it should not be viewed @@ -1649,10 +1581,8 @@ void MainWindow::noteTextSliderValueChanged(int value, bool force) { QScrollBar *viewScrollBar = ui->noteTextView->verticalScrollBar(); #endif - const float editScrollFactor = - static_cast<float>(value) / editScrollBar->maximum(); - const int viewPosition = - static_cast<int>(viewScrollBar->maximum() * editScrollFactor); + const float editScrollFactor = static_cast<float>(value) / editScrollBar->maximum(); + const int viewPosition = static_cast<int>(viewScrollBar->maximum() * editScrollFactor); // set the scroll position in the note text view viewScrollBar->setSliderPosition(viewPosition); @@ -1679,11 +1609,9 @@ void MainWindow::noteViewSliderValueChanged(int value, bool force) { QScrollBar *viewScrollBar = ui->noteTextView->verticalScrollBar(); #endif - const float editScrollFactor = - static_cast<float>(value) / viewScrollBar->maximum(); + const float editScrollFactor = static_cast<float>(value) / viewScrollBar->maximum(); - const int editPosition = - static_cast<int>(editScrollBar->maximum() * editScrollFactor); + const int editPosition = static_cast<int>(editScrollBar->maximum() * editScrollFactor); // for some reason we get some int-min value here sometimes if (editPosition < 0) { @@ -1713,9 +1641,7 @@ void MainWindow::setDistractionFreeMode(const bool enabled) { storeCurrentWorkspace(); const bool menuBarWasVisible = - settings - .value(QStringLiteral("showMenuBar"), !ui->menuBar->isHidden()) - .toBool(); + settings.value(QStringLiteral("showMenuBar"), !ui->menuBar->isHidden()).toBool(); // set the menu bar visible so we get the correct height if (!menuBarWasVisible) { @@ -1723,14 +1649,12 @@ void MainWindow::setDistractionFreeMode(const bool enabled) { } // remember states, geometry and sizes - settings.setValue(QStringLiteral("DistractionFreeMode/windowState"), - saveState()); + settings.setValue(QStringLiteral("DistractionFreeMode/windowState"), saveState()); settings.setValue(QStringLiteral("DistractionFreeMode/menuBarGeometry"), ui->menuBar->saveGeometry()); settings.setValue(QStringLiteral("DistractionFreeMode/menuBarHeight"), ui->menuBar->height()); - settings.setValue(QStringLiteral("DistractionFreeMode/menuBarVisible"), - menuBarWasVisible); + settings.setValue(QStringLiteral("DistractionFreeMode/menuBarVisible"), menuBarWasVisible); // we must not hide the menu bar or else the shortcuts // will not work any more @@ -1750,8 +1674,7 @@ void MainWindow::setDistractionFreeMode(const bool enabled) { // hide all dock widgets but the note edit dock widget const QList<QDockWidget *> dockWidgets = findChildren<QDockWidget *>(); for (QDockWidget *dockWidget : dockWidgets) { - if (dockWidget->objectName() == - QStringLiteral("noteEditDockWidget")) { + if (dockWidget->objectName() == QStringLiteral("noteEditDockWidget")) { continue; } dockWidget->hide(); @@ -1762,15 +1685,13 @@ void MainWindow::setDistractionFreeMode(const bool enabled) { _leaveDistractionFreeModeButton = new QPushButton(tr("leave")); _leaveDistractionFreeModeButton->setFlat(true); - _leaveDistractionFreeModeButton->setToolTip( - tr("Leave distraction free mode")); + _leaveDistractionFreeModeButton->setToolTip(tr("Leave distraction free mode")); _leaveDistractionFreeModeButton->setStyleSheet( QStringLiteral("QPushButton {padding: 0 5px}")); _leaveDistractionFreeModeButton->setIcon(QIcon::fromTheme( QStringLiteral("zoom-original"), - QIcon(QStringLiteral( - ":icons/breeze-qownnotes/16x16/zoom-original.svg")))); + QIcon(QStringLiteral(":icons/breeze-qownnotes/16x16/zoom-original.svg")))); connect(_leaveDistractionFreeModeButton, &QPushButton::clicked, this, &MainWindow::toggleDistractionFreeMode); @@ -1784,29 +1705,24 @@ void MainWindow::setDistractionFreeMode(const bool enabled) { // statusBar()->removeWidget(_leaveDistractionFreeModeButton); - disconnect(_leaveDistractionFreeModeButton, nullptr, nullptr, - nullptr); + disconnect(_leaveDistractionFreeModeButton, nullptr, nullptr, nullptr); // restore states and sizes restoreState( - settings.value(QStringLiteral("DistractionFreeMode/windowState")) - .toByteArray()); + settings.value(QStringLiteral("DistractionFreeMode/windowState")).toByteArray()); ui->menuBar->setVisible( - settings.value(QStringLiteral("DistractionFreeMode/menuBarVisible")) - .toBool()); + settings.value(QStringLiteral("DistractionFreeMode/menuBarVisible")).toBool()); ui->menuBar->restoreGeometry( - settings - .value(QStringLiteral("DistractionFreeMode/menuBarGeometry")) - .toByteArray()); + settings.value(QStringLiteral("DistractionFreeMode/menuBarGeometry")).toByteArray()); ui->menuBar->setFixedHeight( - settings.value(QStringLiteral("DistractionFreeMode/menuBarHeight")) - .toInt()); + settings.value(QStringLiteral("DistractionFreeMode/menuBarHeight")).toInt()); if (ui->noteEditTabWidget->count() > 1) { ui->noteEditTabWidget->tabBar()->show(); } - bool showLineNumbersInEditor = settings.value(QStringLiteral("Editor/showLineNumbers")).toBool(); + bool showLineNumbersInEditor = + settings.value(QStringLiteral("Editor/showLineNumbers")).toBool(); // turn line numbers on again if they were enabled if (showLineNumbersInEditor) { @@ -1832,8 +1748,7 @@ void MainWindow::changeDistractionFreeMode(const bool enabled) { /** * Shows a status bar message if not in distraction free mode */ -void MainWindow::showStatusBarMessage(const QString &message, - const int timeout) { +void MainWindow::showStatusBarMessage(const QString &message, const int timeout) { if (!isInDistractionFreeMode()) { ui->statusBar->showMessage(message, timeout); } @@ -1848,18 +1763,15 @@ void MainWindow::showStatusBarMessage(const QString &message, void MainWindow::setupNoteBookmarkShortcuts() { for (int number = 1; number <= 9; number++) { // setup the store shortcut - auto *storeShortcut = - new QShortcut(QKeySequence(QStringLiteral("Ctrl+Shift+") + - QString::number(number)), - this); + auto *storeShortcut = new QShortcut( + QKeySequence(QStringLiteral("Ctrl+Shift+") + QString::number(number)), this); connect(storeShortcut, &QShortcut::activated, this, [this, number]() { storeNoteBookmark(number); }); // setup the goto shortcut - auto *gotoShortcut = new QShortcut( - QKeySequence(QStringLiteral("Ctrl+") + QString::number(number)), - this); + auto *gotoShortcut = + new QShortcut(QKeySequence(QStringLiteral("Ctrl+") + QString::number(number)), this); connect(gotoShortcut, &QShortcut::activated, this, [this, number]() { gotoNoteBookmark(number); }); @@ -1876,8 +1788,7 @@ void MainWindow::loadNoteFolderListMenu() { // ui->noteFoldersMenu->clear(); // find all actions of the recent note folders menu - const QList<QAction *> actions = - ui->noteFoldersMenu->findChildren<QAction *>(); + const QList<QAction *> actions = ui->noteFoldersMenu->findChildren<QAction *>(); // loop through all actions of the recent note folders menu and hide them // this is a workaround because the app might crash if trackAction() is @@ -1905,8 +1816,7 @@ void MainWindow::loadNoteFolderListMenu() { if (_useNoteFolderButtons) { QLayoutItem *child; - while ((child = _noteFolderDockWidgetFrame->layout()->takeAt(0)) != - nullptr) { + while ((child = _noteFolderDockWidgetFrame->layout()->takeAt(0)) != nullptr) { _noteFolderDockWidgetFrame->layout()->removeWidget(child->widget()); delete child->widget(); delete child; @@ -1935,8 +1845,7 @@ void MainWindow::loadNoteFolderListMenu() { action->setData(folderId); action->setToolTip(noteFolder.getLocalPath()); action->setStatusTip(noteFolder.getLocalPath()); - action->setObjectName(QStringLiteral("noteFolder-") + - QString::number(folderId)); + action->setObjectName(QStringLiteral("noteFolder-") + QString::number(folderId)); action->setIcon(Utils::Gui::folderIcon()); if (isCurrentNoteFolder) { @@ -1976,8 +1885,7 @@ void MainWindow::loadNoteFolderListMenu() { /* * Set a new note folder */ -bool MainWindow::changeNoteFolder(const int noteFolderId, - const bool forceChange) { +bool MainWindow::changeNoteFolder(const int noteFolderId, const bool forceChange) { const int currentNoteFolderId = NoteFolder::currentNoteFolderId(); // store the current position in the note of the current note folder @@ -2032,8 +1940,7 @@ bool MainWindow::changeNoteFolder(const int noteFolderId, // portable mode settings.setValue( QStringLiteral("notesPath"), - Utils::Misc::makePathRelativeToPortableDataPathIfNeeded( - std::move(folderName))); + Utils::Misc::makePathRelativeToPortableDataPathIfNeeded(std::move(folderName))); // we have to unset the current note otherwise it might show up after // switching to another note folder @@ -2045,20 +1952,17 @@ bool MainWindow::changeNoteFolder(const int noteFolderId, updateCurrentFolderTooltip(); // restore the note tabs - Utils::Gui::restoreNoteTabs(ui->noteEditTabWidget, - ui->noteEditTabWidgetLayout); + Utils::Gui::restoreNoteTabs(ui->noteEditTabWidget, ui->noteEditTabWidgetLayout); // restore the note history of the new note folder noteHistory.restoreForCurrentNoteFolder(); // check if there is a note name set and jump to it - QString noteName = _activeNoteFolderNotePositions[noteFolderId] - .getNoteName(); + QString noteName = _activeNoteFolderNotePositions[noteFolderId].getNoteName(); // if there was no NoteHistory found try the note history if (noteName.isEmpty()) { - _activeNoteFolderNotePositions[noteFolderId] = - noteHistory.getCurrentHistoryItem(); + _activeNoteFolderNotePositions[noteFolderId] = noteHistory.getCurrentHistoryItem(); noteName = _activeNoteFolderNotePositions[noteFolderId].getNoteName(); } @@ -2066,8 +1970,7 @@ bool MainWindow::changeNoteFolder(const int noteFolderId, jumpToNoteName(noteName); // restore the current position in the note - _activeNoteFolderNotePositions[noteFolderId] - .restoreTextEditPosition(ui->noteTextEdit); + _activeNoteFolderNotePositions[noteFolderId].restoreTextEditPosition(ui->noteTextEdit); } // commit the changes in the selected note folder to git @@ -2115,14 +2018,12 @@ int MainWindow::openNoteDiffDialog(Note changedNote) { QSettings settings; // check if we should ignore all changes - if (settings.value(QStringLiteral("ignoreAllExternalModifications")) - .toBool()) { + if (settings.value(QStringLiteral("ignoreAllExternalModifications")).toBool()) { return NoteDiffDialog::Ignore; } // check if we should accept all changes - if (settings.value(QStringLiteral("acceptAllExternalModifications")) - .toBool()) { + if (settings.value(QStringLiteral("acceptAllExternalModifications")).toBool()) { return NoteDiffDialog::Reload; } @@ -2150,8 +2051,7 @@ int MainWindow::openNoteDiffDialog(Note changedNote) { void MainWindow::createSystemTrayIcon() { trayIcon = new QSystemTrayIcon(this); - connect(trayIcon, &QSystemTrayIcon::activated, this, - &MainWindow::systemTrayIconClicked); + connect(trayIcon, &QSystemTrayIcon::activated, this, &MainWindow::systemTrayIconClicked); if (showSystemTray) { trayIcon->setIcon(getSystemTrayIcon()); @@ -2166,8 +2066,7 @@ void MainWindow::createSystemTrayIcon() { */ QIcon MainWindow::getSystemTrayIcon() { const QSettings settings; - const bool darkModeIcon = - settings.value(QStringLiteral("darkModeTrayIcon"), false).toBool(); + const bool darkModeIcon = settings.value(QStringLiteral("darkModeTrayIcon"), false).toBool(); const QString file = darkModeIcon ? QStringLiteral(":/images/icon-dark.png") : QStringLiteral(":/images/icon.png"); return QIcon(file); @@ -2186,8 +2085,7 @@ void MainWindow::loadNoteDirectoryList() { const QSignalBlocker blocker2(ui->noteTreeWidget); Q_UNUSED(blocker2) - const bool isCurrentNoteTreeEnabled = - NoteFolder::isCurrentNoteTreeEnabled(); + const bool isCurrentNoteTreeEnabled = NoteFolder::isCurrentNoteTreeEnabled(); ui->noteTreeWidget->clear(); // ui->noteTreeWidget->setRootIsDecorated(isCurrentNoteTreeEnabled); int itemCount; @@ -2217,13 +2115,13 @@ void MainWindow::loadNoteDirectoryList() { MetricsService::instance()->sendEventIfEnabled( QStringLiteral("note/list/loaded"), QStringLiteral("note"), - QStringLiteral("note list loaded"), - QString::number(itemCount) + QStringLiteral(" notes"), itemCount); + QStringLiteral("note list loaded"), QString::number(itemCount) + QStringLiteral(" notes"), + itemCount); // sort alphabetically again if necessary QSettings settings; - if (settings.value(QStringLiteral("notesPanelSort"), SORT_BY_LAST_CHANGE) - .toInt() == SORT_ALPHABETICAL) { + if (settings.value(QStringLiteral("notesPanelSort"), SORT_BY_LAST_CHANGE).toInt() == + SORT_ALPHABETICAL) { ui->noteTreeWidget->sortItems( 0, Utils::Gui::toQtOrder(settings.value(QStringLiteral("notesPanelOrder")).toInt())); } @@ -2255,8 +2153,7 @@ void MainWindow::loadNoteDirectoryList() { /** * Adds a note to the note tree widget */ -bool MainWindow::addNoteToNoteTreeWidget(const Note ¬e, - QTreeWidgetItem *parent) { +bool MainWindow::addNoteToNoteTreeWidget(const Note ¬e, QTreeWidgetItem *parent) { const QString name = note.getName(); // skip notes without name @@ -2310,8 +2207,7 @@ bool MainWindow::addNoteToNoteTreeWidget(const Note ¬e, return true; } -void MainWindow::updateNoteTreeWidgetItem(const Note ¬e, - QTreeWidgetItem *noteItem) { +void MainWindow::updateNoteTreeWidgetItem(const Note ¬e, QTreeWidgetItem *noteItem) { if (noteItem == nullptr) { noteItem = findNoteInNoteTreeWidget(note); } @@ -2347,8 +2243,7 @@ void MainWindow::makeCurrentNoteFirstInNoteList() { const QSignalBlocker blocker(ui->noteTreeWidget); Q_UNUSED(blocker) - ui->noteTreeWidget->takeTopLevelItem( - ui->noteTreeWidget->indexOfTopLevelItem(item)); + ui->noteTreeWidget->takeTopLevelItem(ui->noteTreeWidget->indexOfTopLevelItem(item)); ui->noteTreeWidget->insertTopLevelItem(0, item); // set the item as current item if it is visible @@ -2404,21 +2299,18 @@ void MainWindow::readSettings() { NoteFolder::migrateToNoteFolders(); QSettings settings; - showSystemTray = - settings.value(QStringLiteral("ShowSystemTray"), false).toBool(); + showSystemTray = settings.value(QStringLiteral("ShowSystemTray"), false).toBool(); #if (QT_VERSION >= QT_VERSION_CHECK(5, 4, 0)) - QTimer::singleShot(1, this, [this]{ + QTimer::singleShot(1, this, [this] { #endif - restoreGeometry( - QSettings().value(QStringLiteral("MainWindow/geometry")).toByteArray()); + restoreGeometry(QSettings().value(QStringLiteral("MainWindow/geometry")).toByteArray()); #if (QT_VERSION >= QT_VERSION_CHECK(5, 4, 0)) }); #endif ui->menuBar->restoreGeometry( - settings.value(QStringLiteral("MainWindow/menuBarGeometry")) - .toByteArray()); + settings.value(QStringLiteral("MainWindow/menuBarGeometry")).toByteArray()); // read all relevant settings, that can be set in the settings dialog readSettingsFromSettingsDialog(true); @@ -2429,9 +2321,7 @@ void MainWindow::readSettings() { settings.value(QStringLiteral("notesPath")).toString()); // migration: remove GAnalytics-cid - if (!settings.value(QStringLiteral("GAnalytics-cid")) - .toString() - .isEmpty()) { + if (!settings.value(QStringLiteral("GAnalytics-cid")).toString().isEmpty()) { settings.remove(QStringLiteral("GAnalytics-cid")); } @@ -2446,15 +2336,13 @@ void MainWindow::readSettings() { settings.value(QStringLiteral("recentNoteFolders")).toStringList(); if (recentNoteFolders.contains(this->notesPath)) { recentNoteFolders.removeAll(this->notesPath); - settings.setValue(QStringLiteral("recentNoteFolders"), - recentNoteFolders); + settings.setValue(QStringLiteral("recentNoteFolders"), recentNoteFolders); } } // set the editor width selector for the distraction free mode const int editorWidthMode = - settings.value(QStringLiteral("DistractionFreeMode/editorWidthMode")) - .toInt(); + settings.value(QStringLiteral("DistractionFreeMode/editorWidthMode")).toInt(); switch (editorWidthMode) { case QOwnNotesMarkdownTextEdit::Medium: @@ -2476,16 +2364,14 @@ void MainWindow::readSettings() { } // toggle the show status bar checkbox - const bool showStatusBar = - settings.value(QStringLiteral("showStatusBar"), true).toBool(); + const bool showStatusBar = settings.value(QStringLiteral("showStatusBar"), true).toBool(); on_actionShow_status_bar_triggered(showStatusBar); // toggle the show menu bar checkbox // use the current menu bar visibility as default (so it will not be // shown by default on Unity desktop) const bool showMenuBar = - settings.value(QStringLiteral("showMenuBar"), !ui->menuBar->isHidden()) - .toBool(); + settings.value(QStringLiteral("showMenuBar"), !ui->menuBar->isHidden()).toBool(); on_actionShow_menu_bar_triggered(showMenuBar); { @@ -2501,8 +2387,7 @@ void MainWindow::readSettings() { // we want to trigger the event afterwards so the settings of the note edits // are updated - const bool centerCursor = - settings.value(QStringLiteral("Editor/centerCursor")).toBool(); + const bool centerCursor = settings.value(QStringLiteral("Editor/centerCursor")).toBool(); ui->actionTypewriter_mode->setChecked(centerCursor); // restore old spell check settings @@ -2520,7 +2405,7 @@ void MainWindow::readSettings() { // load language dicts names into menu // Delay loading, loading dictionary names is slow #if (QT_VERSION >= QT_VERSION_CHECK(5, 4, 0)) - QTimer::singleShot(10, this, [this]{ + QTimer::singleShot(10, this, [this] { #endif _languageGroup = new QActionGroup(ui->menuLanguages); loadDictionaryNames(); @@ -2542,17 +2427,14 @@ void MainWindow::restoreToolbars() { ToolbarContainer toolbarContainer; - toolbarContainer.name = - settings.value(QStringLiteral("name")).toString(); + toolbarContainer.name = settings.value(QStringLiteral("name")).toString(); if (toolbarContainer.name.isEmpty()) { qWarning() << tr("Toolbar could not be loaded without name"); continue; } - toolbarContainer.title = - settings.value(QStringLiteral("title")).toString(); - toolbarContainer.actions = - settings.value(QStringLiteral("items")).toStringList(); + toolbarContainer.title = settings.value(QStringLiteral("title")).toString(); + toolbarContainer.actions = settings.value(QStringLiteral("items")).toStringList(); toolbarContainers.push_back(toolbarContainer); } @@ -2563,16 +2445,14 @@ void MainWindow::restoreToolbars() { // delete the custom toolbars const auto toolbars = findChildren<QToolBar *>(); for (QToolBar *toolbar : toolbars) { - if (!toolbar->objectName().startsWith( - Toolbar_Editor::customToolbarNamePrefix)) { + if (!toolbar->objectName().startsWith(Toolbar_Editor::customToolbarNamePrefix)) { continue; } delete toolbar; } - for (ToolbarContainer toolbarContainer : - Utils::asConst(toolbarContainers)) { + for (ToolbarContainer toolbarContainer : Utils::asConst(toolbarContainers)) { if (toolbarContainer.toolbarFound()) { toolbarContainer.updateToolbar(); } else { @@ -2598,21 +2478,17 @@ void MainWindow::readSettingsFromSettingsDialog(const bool isAppLaunch) { QSettings settings; this->notifyAllExternalModifications = - settings.value(QStringLiteral("notifyAllExternalModifications")) - .toBool(); - this->noteSaveIntervalTime = - settings.value(QStringLiteral("noteSaveIntervalTime"), 10).toInt(); + settings.value(QStringLiteral("notifyAllExternalModifications")).toBool(); + this->noteSaveIntervalTime = settings.value(QStringLiteral("noteSaveIntervalTime"), 10).toInt(); // default value is 10 seconds if (this->noteSaveIntervalTime == 0) { this->noteSaveIntervalTime = 10; - settings.setValue(QStringLiteral("noteSaveIntervalTime"), - this->noteSaveIntervalTime); + settings.setValue(QStringLiteral("noteSaveIntervalTime"), this->noteSaveIntervalTime); } // set the git commit interval time - _gitCommitInterval = - settings.value(QStringLiteral("gitCommitInterval"), 30).toInt(); + _gitCommitInterval = settings.value(QStringLiteral("gitCommitInterval"), 30).toInt(); // load note text view font QString fontString = Utils::Misc::previewFontString(); @@ -2624,8 +2500,7 @@ void MainWindow::readSettingsFromSettingsDialog(const bool isAppLaunch) { #else fontString = ui->noteTextView->font().toString(); #endif - settings.setValue(QStringLiteral("MainWindow/noteTextView.font"), - fontString); + settings.setValue(QStringLiteral("MainWindow/noteTextView.font"), fontString); } // set the note text view font @@ -2638,13 +2513,10 @@ void MainWindow::readSettingsFromSettingsDialog(const bool isAppLaunch) { #endif // set the main toolbar icon size - int toolBarIconSize = - settings.value(QStringLiteral("MainWindow/mainToolBar.iconSize")) - .toInt(); + int toolBarIconSize = settings.value(QStringLiteral("MainWindow/mainToolBar.iconSize")).toInt(); if (toolBarIconSize == 0) { toolBarIconSize = ui->mainToolBar->iconSize().height(); - settings.setValue(QStringLiteral("MainWindow/mainToolBar.iconSize"), - toolBarIconSize); + settings.setValue(QStringLiteral("MainWindow/mainToolBar.iconSize"), toolBarIconSize); } else { QSize size(toolBarIconSize, toolBarIconSize); ui->mainToolBar->setIconSize(size); @@ -2689,10 +2561,8 @@ void MainWindow::readSettingsFromSettingsDialog(const bool isAppLaunch) { // show or hide 'Find or create ...' search in Note Subfolders & Tags Panels ui->noteSubFolderLineEdit->setHidden( - settings.value(QStringLiteral("noteSubfoldersPanelHideSearch")) - .toBool()); - ui->tagLineEdit->setHidden( - settings.value(QStringLiteral("tagsPanelHideSearch")).toBool()); + settings.value(QStringLiteral("noteSubfoldersPanelHideSearch")).toBool()); + ui->tagLineEdit->setHidden(settings.value(QStringLiteral("tagsPanelHideSearch")).toBool()); ui->navigationLineEdit->setHidden( settings.value(QStringLiteral("navigationPanelHideSearch")).toBool()); @@ -2702,15 +2572,15 @@ void MainWindow::readSettingsFromSettingsDialog(const bool isAppLaunch) { ui->encryptedNoteTextEdit->setCursorWidth(cursorWidth); // turn line numbers on if enabled - bool showLineNumbersInEditor = settings.value( - QStringLiteral("Editor/showLineNumbers")).toBool(); + bool showLineNumbersInEditor = + settings.value(QStringLiteral("Editor/showLineNumbers")).toBool(); ui->noteTextEdit->setLineNumberEnabled(showLineNumbersInEditor); ui->encryptedNoteTextEdit->setLineNumberEnabled(showLineNumbersInEditor); if (showLineNumbersInEditor) { bool darkMode = settings.value(QStringLiteral("darkMode")).toBool(); - ui->noteTextEdit->setLineNumbersCurrentLineColor(QColor(darkMode ? - QStringLiteral("#eef067") : QStringLiteral("##141414"))); + ui->noteTextEdit->setLineNumbersCurrentLineColor( + QColor(darkMode ? QStringLiteral("#eef067") : QStringLiteral("##141414"))); } ui->noteTextEdit->setPaperMargins(); @@ -2719,16 +2589,14 @@ void MainWindow::readSettingsFromSettingsDialog(const bool isAppLaunch) { if (_webSocketServerService == nullptr) { QTimer::singleShot(250, this, SLOT(initWebSocketServerService())); } else if (Utils::Misc::isSocketServerEnabled()) { - if (_webSocketServerService->getPort() != - WebSocketServerService::getSettingsPort()) { + if (_webSocketServerService->getPort() != WebSocketServerService::getSettingsPort()) { _webSocketServerService->listen(); } } else { _webSocketServerService->close(); } - if (settings.value(QStringLiteral("Editor/disableCursorBlinking")) - .toBool()) { + if (settings.value(QStringLiteral("Editor/disableCursorBlinking")).toBool()) { qApp->setCursorFlashTime(0); } @@ -2772,19 +2640,16 @@ void MainWindow::initTreeWidgetItemHeight() { * @param treeWidget * @param height */ -void MainWindow::updateTreeWidgetItemHeight(QTreeWidget *treeWidget, - int height) { +void MainWindow::updateTreeWidgetItemHeight(QTreeWidget *treeWidget, int height) { QString styleText = treeWidget->styleSheet(); // remove the old height stylesheet - static const QRegularExpression re( - QStringLiteral("\nQTreeWidget::item \\{height: \\d+px\\}"), - QRegularExpression::CaseInsensitiveOption); + static const QRegularExpression re(QStringLiteral("\nQTreeWidget::item \\{height: \\d+px\\}"), + QRegularExpression::CaseInsensitiveOption); styleText.remove(re); // add the new height stylesheet - styleText += QStringLiteral("\nQTreeWidget::item {height: %1px}") - .arg(QString::number(height)); + styleText += QStringLiteral("\nQTreeWidget::item {height: %1px}").arg(QString::number(height)); treeWidget->setStyleSheet(styleText); } @@ -2811,8 +2676,7 @@ void MainWindow::notesWereModified(const QString &str) { } // if we should ignore all changes return here - if (QSettings().value(QStringLiteral("ignoreAllExternalNoteFolderChanges")) - .toBool()) { + if (QSettings().value(QStringLiteral("ignoreAllExternalNoteFolderChanges")).toBool()) { return; } @@ -2838,11 +2702,9 @@ void MainWindow::notesWereModified(const QString &str) { // fetch text of note from disk note.updateNoteTextFromDisk(); - const QString noteTextOnDisk = - Utils::Misc::transformLineFeeds(note.getNoteText()); + const QString noteTextOnDisk = Utils::Misc::transformLineFeeds(note.getNoteText()); const bool isCurrentNoteNotEditedForAWhile = - this->currentNoteLastEdited.addSecs(60) < - QDateTime::currentDateTime(); + this->currentNoteLastEdited.addSecs(60) < QDateTime::currentDateTime(); // If the current note wasn't edited for a while, we want that it is possible // to get updated even with small changes, so we are setting a threshold of 0 const int threshold = isCurrentNoteNotEditedForAWhile ? 0 : 8; @@ -2853,21 +2715,20 @@ void MainWindow::notesWereModified(const QString &str) { return; } - const QString noteTextOnDiskHash = - QString(QCryptographicHash::hash(noteTextOnDisk.toLocal8Bit(), - QCryptographicHash::Sha1) - .toHex()); + const QString noteTextOnDiskHash = QString( + QCryptographicHash::hash(noteTextOnDisk.toLocal8Bit(), QCryptographicHash::Sha1) + .toHex()); // skip dialog if text of note file on disk and current note are // equal if (noteTextOnDiskHash == _currentNoteTextHash) { - qDebug() << __func__ << " - Note text and _currentNoteTextHash are the same, ignoring"; + qDebug() << __func__ + << " - Note text and _currentNoteTextHash are the same, ignoring"; return; } // fetch current text - const QString noteTextEditText = - this->ui->noteTextEdit->toPlainText(); + const QString noteTextEditText = this->ui->noteTextEdit->toPlainText(); // skip dialog if text of note file on disk text from note text // edit are equal or similar @@ -2876,16 +2737,14 @@ void MainWindow::notesWereModified(const QString &str) { return; } - showStatusBarMessage(tr("Current note was modified externally"), - 5000); + showStatusBarMessage(tr("Current note was modified externally"), 5000); // if we don't want to get notifications at all // external modifications check if we really need one if (!this->notifyAllExternalModifications) { // reloading the current note text straight away // if we didn't change it for a minute - if (!this->currentNote.getHasDirtyData() && - isCurrentNoteNotEditedForAWhile) { + if (!this->currentNote.getHasDirtyData() && isCurrentNoteNotEditedForAWhile) { updateNoteTextFromDisk(std::move(note)); return; } @@ -2899,8 +2758,7 @@ void MainWindow::notesWereModified(const QString &str) { FileWatchDisabler disable(this); showStatusBarMessage( - tr("Overwriting external changes of: %1") - .arg(currentNote.getFileName()), + tr("Overwriting external changes of: %1").arg(currentNote.getFileName()), 3000); // the note text has to be stored newly because the @@ -2911,9 +2769,9 @@ void MainWindow::notesWereModified(const QString &str) { // reload note file from disk case NoteDiffDialog::Reload: - showStatusBarMessage(tr("Loading external changes from: %1") - .arg(currentNote.getFileName()), - 3000); + showStatusBarMessage( + tr("Loading external changes from: %1").arg(currentNote.getFileName()), + 3000); updateNoteTextFromDisk(note); break; @@ -2923,8 +2781,7 @@ void MainWindow::notesWereModified(const QString &str) { // do nothing break; } - } else if (_noteExternallyRemovedCheckEnabled && - (currentNote.getNoteSubFolderId() == 0)) { + } else if (_noteExternallyRemovedCheckEnabled && (currentNote.getNoteSubFolderId() == 0)) { // only allow the check if current note was removed externally in // the root note folder, because it gets triggered every time // a note gets renamed in subfolders @@ -2944,11 +2801,9 @@ void MainWindow::notesWereModified(const QString &str) { // store note to disk again const bool noteWasStored = note.storeNoteTextFileToDisk(); - showStatusBarMessage( - noteWasStored - ? tr("Stored current note to disk") - : tr("Current note could not be stored to disk"), - 3000); + showStatusBarMessage(noteWasStored ? tr("Stored current note to disk") + : tr("Current note could not be stored to disk"), + 3000); // rebuild and reload the notes directory list buildNotesIndexAndLoadNoteDirectoryList(); @@ -2969,8 +2824,7 @@ void MainWindow::notesWereModified(const QString &str) { } else { qDebug() << "other note was changed: " << str; - showStatusBarMessage(tr("Note was modified externally: %1").arg(str), - 5000); + showStatusBarMessage(tr("Note was modified externally: %1").arg(str), 5000); // rebuild and reload the notes directory list buildNotesIndexAndLoadNoteDirectoryList(); @@ -2985,8 +2839,7 @@ void MainWindow::notesDirectoryWasModified(const QString &str) { } // if we should ignore all changes return here - if (QSettings().value(QStringLiteral("ignoreAllExternalNoteFolderChanges")) - .toBool()) { + if (QSettings().value(QStringLiteral("ignoreAllExternalNoteFolderChanges")).toBool()) { return; } @@ -3041,16 +2894,16 @@ void MainWindow::storeUpdatedNotesToDisk() { bool currentNoteTextChanged = false; // currentNote will be set by this method if the filename has changed - const int count = Note::storeDirtyNotesToDisk( - currentNote, ¤tNoteChanged, ¬eWasRenamed, ¤tNoteTextChanged); + const int count = Note::storeDirtyNotesToDisk(currentNote, ¤tNoteChanged, ¬eWasRenamed, + ¤tNoteTextChanged); if (count > 0) { _noteViewNeedsUpdate = true; MetricsService::instance()->sendEventIfEnabled( QStringLiteral("note/notes/stored"), QStringLiteral("note"), - QStringLiteral("notes stored"), - QString::number(count) + QStringLiteral(" notes"), count); + QStringLiteral("notes stored"), QString::number(count) + QStringLiteral(" notes"), + count); qDebug() << __func__ << " - 'count': " << count; @@ -3058,19 +2911,18 @@ void MainWindow::storeUpdatedNotesToDisk() { if (currentNoteChanged) { // strip trailing spaces of the current note (if enabled) - if (QSettings().value(QStringLiteral("Editor/removeTrailingSpaces")) - .toBool()) { - const bool wasStripped = currentNote.stripTrailingSpaces( - activeNoteTextEdit()->textCursor().position()); + if (QSettings().value(QStringLiteral("Editor/removeTrailingSpaces")).toBool()) { + const bool wasStripped = + currentNote.stripTrailingSpaces(activeNoteTextEdit()->textCursor().position()); if (wasStripped) { qDebug() << __func__ << " - 'wasStripped'"; // updating the current note text is disabled because it // moves the cursor to the top -// const QSignalBlocker blocker2(activeNoteTextEdit()); -// Q_UNUSED(blocker2) -// setNoteTextFromNote(¤tNote); + // const QSignalBlocker blocker2(activeNoteTextEdit()); + // Q_UNUSED(blocker2) + // setNoteTextFromNote(¤tNote); } } @@ -3116,12 +2968,10 @@ void MainWindow::frequentPeriodicChecker() { } QSettings settings; - QDateTime lastUpdateCheck = - settings.value(QStringLiteral("LastUpdateCheck")).toDateTime(); + QDateTime lastUpdateCheck = settings.value(QStringLiteral("LastUpdateCheck")).toDateTime(); if (!lastUpdateCheck.isValid()) { // set the LastUpdateCheck if it wasn't set - settings.setValue(QStringLiteral("LastUpdateCheck"), - QDateTime::currentDateTime()); + settings.setValue(QStringLiteral("LastUpdateCheck"), QDateTime::currentDateTime()); } else if (lastUpdateCheck.addSecs(3600) <= QDateTime::currentDateTime()) { // check for updates every 1h updateService->checkForUpdates(UpdateService::Periodic); @@ -3142,13 +2992,11 @@ void MainWindow::setupStatusBarWidgets() { _readOnlyButton->setToolTip( tr("Note editing is disabled, click to " "enable")); - _readOnlyButton->setStyleSheet( - QStringLiteral("QPushButton {padding: 0 5px}")); + _readOnlyButton->setStyleSheet(QStringLiteral("QPushButton {padding: 0 5px}")); _readOnlyButton->setFlat(true); _readOnlyButton->setHidden(Utils::Misc::isNoteEditingAllowed()); - connect(_readOnlyButton, &QPushButton::pressed, this, - &MainWindow::allowNoteEditing); + connect(_readOnlyButton, &QPushButton::pressed, this, &MainWindow::allowNoteEditing); ui->statusBar->addPermanentWidget(_readOnlyButton); @@ -3170,8 +3018,7 @@ void MainWindow::setupStatusBarWidgets() { tr("Click here to see what has changed and to be able to " "update to the latest version")); _updateAvailableButton->hide(); - _updateAvailableButton->setStyleSheet( - QStringLiteral("QPushButton {padding: 0 5px}")); + _updateAvailableButton->setStyleSheet(QStringLiteral("QPushButton {padding: 0 5px}")); connect(_updateAvailableButton, &QPushButton::pressed, this, &MainWindow::on_actionCheck_for_updates_triggered); @@ -3180,8 +3027,7 @@ void MainWindow::setupStatusBarWidgets() { } void MainWindow::showUpdateAvailableButton(const QString &version) { - _updateAvailableButton->setText( - tr("new version %1 available").arg(version)); + _updateAvailableButton->setText(tr("new version %1 available").arg(version)); _updateAvailableButton->show(); } @@ -3191,8 +3037,7 @@ void MainWindow::hideUpdateAvailableButton() { _updateAvailableButton->hide(); } * Builds the index of notes and note sub folders */ bool MainWindow::buildNotesIndex(int noteSubFolderId, bool forceRebuild) { - QString notePath = - Utils::Misc::removeIfEndsWith(this->notesPath, QDir::separator()); + QString notePath = Utils::Misc::removeIfEndsWith(this->notesPath, QDir::separator()); NoteSubFolder noteSubFolder; bool hasNoteSubFolder = false; bool wasModified = false; @@ -3205,8 +3050,7 @@ bool MainWindow::buildNotesIndex(int noteSubFolderId, bool forceRebuild) { // init the lists to check for removed items _buildNotesIndexBeforeNoteIdList = Note::fetchAllIds(); - _buildNotesIndexBeforeNoteSubFolderIdList = - NoteSubFolder::fetchAllIds(); + _buildNotesIndexBeforeNoteSubFolderIdList = NoteSubFolder::fetchAllIds(); _buildNotesIndexAfterNoteIdList.clear(); _buildNotesIndexAfterNoteSubFolderIdList.clear(); } else { @@ -3237,8 +3081,7 @@ bool MainWindow::buildNotesIndex(int noteSubFolderId, bool forceRebuild) { if (createDemoNotes) { QSettings settings; // check if we already have created the demo notes once - createDemoNotes = - !settings.value(QStringLiteral("demoNotesCreated")).toBool(); + createDemoNotes = !settings.value(QStringLiteral("demoNotesCreated")).toBool(); if (createDemoNotes) { // we don't want to create the demo notes again @@ -3255,14 +3098,12 @@ bool MainWindow::buildNotesIndex(int noteSubFolderId, bool forceRebuild) { // copy note files to the notes path for (int i = 0; i < filenames.size(); ++i) { const QString &filename = filenames.at(i); - const QString destinationFile = - this->notesPath + QDir::separator() + filename; + const QString destinationFile = this->notesPath + QDir::separator() + filename; QFile sourceFile(QStringLiteral(":/demonotes/") + filename); sourceFile.copy(destinationFile); // set read/write permissions for the owner and user - QFile::setPermissions(destinationFile, - QFile::ReadOwner | QFile::WriteOwner | - QFile::ReadUser | QFile::WriteUser); + QFile::setPermissions(destinationFile, QFile::ReadOwner | QFile::WriteOwner | + QFile::ReadUser | QFile::WriteUser); } // copy the shortcuts file and handle its file permissions @@ -3292,11 +3133,9 @@ bool MainWindow::buildNotesIndex(int noteSubFolderId, bool forceRebuild) { NoteSubFolder::deleteAll(); } - const bool withNoteNameHook = - ScriptingService::instance()->handleNoteNameHookExists(); + const bool withNoteNameHook = ScriptingService::instance()->handleNoteNameHookExists(); const int numFiles = files.count(); - QProgressDialog progress(tr("Loading notes…"), tr("Abort"), 0, numFiles, - this); + QProgressDialog progress(tr("Loading notes…"), tr("Abort"), 0, numFiles, this); progress.setWindowModality(Qt::WindowModal); int currentCount = 0; @@ -3315,8 +3154,7 @@ bool MainWindow::buildNotesIndex(int noteSubFolderId, bool forceRebuild) { QFile file(Note::getFullFilePathForFile(fileName)); // update or create a note from the file - const Note note = - Note::updateOrCreateFromFile(file, noteSubFolder, withNoteNameHook); + const Note note = Note::updateOrCreateFromFile(file, noteSubFolder, withNoteNameHook); // add the note id to in the end check if notes need to be removed _buildNotesIndexAfterNoteIdList << note.getId(); @@ -3364,8 +3202,7 @@ bool MainWindow::buildNotesIndex(int noteSubFolderId, bool forceRebuild) { // build the note sub folders const bool showSubfolders = NoteFolder::isCurrentHasSubfolders(); if (showSubfolders) { - const QStringList folders = - notesDir.entryList(QDir::Dirs | QDir::Hidden, QDir::Time); + const QStringList folders = notesDir.entryList(QDir::Dirs | QDir::Hidden, QDir::Time); for (const QString &folder : folders) { if (NoteSubFolder::willFolderBeIgnored(folder)) { @@ -3386,12 +3223,10 @@ bool MainWindow::buildNotesIndex(int noteSubFolderId, bool forceRebuild) { if (parentNoteSubFolder.isFetched()) { // add the note id to in the end check if notes need to // be removed - _buildNotesIndexAfterNoteSubFolderIdList - << parentNoteSubFolder.getId(); + _buildNotesIndexAfterNoteSubFolderIdList << parentNoteSubFolder.getId(); // build the notes index for the note subfolder - const bool result = - buildNotesIndex(parentNoteSubFolder.getId()); + const bool result = buildNotesIndex(parentNoteSubFolder.getId()); if (result) { wasModified = true; } @@ -3425,11 +3260,10 @@ bool MainWindow::buildNotesIndex(int noteSubFolderId, bool forceRebuild) { _buildNotesIndexAfterNoteIdList.end())) .values(); #else - const QList<int> removedNoteIdList = - _buildNotesIndexBeforeNoteIdList.toList() - .toSet() - .subtract(_buildNotesIndexAfterNoteIdList.toSet()) - .toList(); + const QList<int> removedNoteIdList = _buildNotesIndexBeforeNoteIdList.toList() + .toSet() + .subtract(_buildNotesIndexAfterNoteIdList.toSet()) + .toList(); #endif // remove all missing notes @@ -3447,7 +3281,8 @@ bool MainWindow::buildNotesIndex(int noteSubFolderId, bool forceRebuild) { QSet<int>(_buildNotesIndexBeforeNoteSubFolderIdList.begin(), _buildNotesIndexBeforeNoteSubFolderIdList.end()) .subtract(QSet<int>(_buildNotesIndexAfterNoteSubFolderIdList.begin(), - _buildNotesIndexAfterNoteSubFolderIdList.end())).values(); + _buildNotesIndexAfterNoteSubFolderIdList.end())) + .values(); #else const QList<int> removedNoteSubFolderIdList = _buildNotesIndexBeforeNoteSubFolderIdList.toList() @@ -3458,8 +3293,7 @@ bool MainWindow::buildNotesIndex(int noteSubFolderId, bool forceRebuild) { // remove all missing note subfolders for (const int _noteSubFolderId : removedNoteSubFolderIdList) { - NoteSubFolder _noteSubFolder = - NoteSubFolder::fetch(_noteSubFolderId); + NoteSubFolder _noteSubFolder = NoteSubFolder::fetch(_noteSubFolderId); if (_noteSubFolder.isFetched()) { _noteSubFolder.remove(); wasModified = true; @@ -3504,20 +3338,17 @@ void MainWindow::removeConflictedNotesDatabaseCopies() { // check if conflicted database copy is the same as the current note // folder database - if (Utils::Misc::isSameFile( - file, DatabaseService::getNoteFolderDatabasePath())) { + if (Utils::Misc::isSameFile(file, DatabaseService::getNoteFolderDatabasePath())) { showStatusBarMessage( QFile::remove(file) ? tr("Removed duplicate conflicted database: %1").arg(file) - : tr("Could not remove duplicate conflicted database: %1") - .arg(file), + : tr("Could not remove duplicate conflicted database: %1").arg(file), 4000); } else if (DatabaseService::mergeNoteFolderDatabase(file)) { showStatusBarMessage( QFile::remove(file) ? tr("Removed merged conflicted database: %1").arg(file) - : tr("Could not remove merged conflicted database: %1") - .arg(file), + : tr("Could not remove merged conflicted database: %1").arg(file), 4000); } else { files << file; @@ -3537,10 +3368,8 @@ void MainWindow::removeConflictedNotesDatabaseCopies() { " conflicted database copies that may block your ownCloud" " sync process?", "", count)) + - QStringLiteral("<br /><br />") + - files.join(QStringLiteral("<br />")), - QStringLiteral("delete-conflicted-database-files")) != - QMessageBox::Yes) { + QStringLiteral("<br /><br />") + files.join(QStringLiteral("<br />")), + QStringLiteral("delete-conflicted-database-files")) != QMessageBox::Yes) { return; } @@ -3553,8 +3382,7 @@ void MainWindow::removeConflictedNotesDatabaseCopies() { } } - showStatusBarMessage( - tr("Removed %n conflicted database copies", "", count)); + showStatusBarMessage(tr("Removed %n conflicted database copies", "", count)); } /** @@ -3569,8 +3397,7 @@ void MainWindow::updateNoteDirectoryWatcher() { // return; // } - const QString notePath = - Utils::Misc::removeIfEndsWith(this->notesPath, QDir::separator()); + const QString notePath = Utils::Misc::removeIfEndsWith(this->notesPath, QDir::separator()); const QDir notesDir(notePath); @@ -3580,11 +3407,9 @@ void MainWindow::updateNoteDirectoryWatcher() { } if (hasSubfolders) { - const QVector<NoteSubFolder> noteSubFolderList = - NoteSubFolder::fetchAll(); + const QVector<NoteSubFolder> noteSubFolderList = NoteSubFolder::fetchAll(); for (const NoteSubFolder ¬eSubFolder : noteSubFolderList) { - const QString path = - notePath + QDir::separator() + noteSubFolder.relativePath(); + const QString path = notePath + QDir::separator() + noteSubFolder.relativePath(); QDir folderDir(path); @@ -3628,8 +3453,7 @@ void MainWindow::updateNoteDirectoryWatcher() { * Clears all paths from the directory watcher */ void MainWindow::clearNoteDirectoryWatcher() { - const QStringList fileList = - noteDirectoryWatcher.directories() + noteDirectoryWatcher.files(); + const QStringList fileList = noteDirectoryWatcher.directories() + noteDirectoryWatcher.files(); if (fileList.count() > 0) { noteDirectoryWatcher.removePaths(fileList); } @@ -3638,17 +3462,15 @@ void MainWindow::clearNoteDirectoryWatcher() { /** * Jumps to the welcome note in the note selector */ -void MainWindow::jumpToWelcomeNote() { - jumpToNoteName(QStringLiteral("Welcome to QOwnNotes")); -} +void MainWindow::jumpToWelcomeNote() { jumpToNoteName(QStringLiteral("Welcome to QOwnNotes")); } /** * Jumps to a note in the note selector */ bool MainWindow::jumpToNoteName(const QString &name) { // search for the note - QList<QTreeWidgetItem *> items = ui->noteTreeWidget->findItems( - name, Qt::MatchExactly | Qt::MatchRecursive, 0); + QList<QTreeWidgetItem *> items = + ui->noteTreeWidget->findItems(name, Qt::MatchExactly | Qt::MatchRecursive, 0); if (items.count() > 0) { ui->noteTreeWidget->setCurrentItem(items.at(0)); @@ -3665,14 +3487,12 @@ bool MainWindow::jumpToNoteHistoryItem(const NoteHistoryItem &historyItem) { // search for the note const QList<QTreeWidgetItem *> items = ui->noteTreeWidget->findItems( historyItem.getNoteName(), Qt::MatchExactly | Qt::MatchRecursive, 0); - const bool isCurrentNoteTreeEnabled = - NoteFolder::isCurrentNoteTreeEnabled(); + const bool isCurrentNoteTreeEnabled = NoteFolder::isCurrentNoteTreeEnabled(); for (QTreeWidgetItem *item : items) { if (isCurrentNoteTreeEnabled) { QString pathData = historyItem.getNoteSubFolderPathData(); - auto noteSubFolder = - NoteSubFolder::fetchByPathData(std::move(pathData)); + auto noteSubFolder = NoteSubFolder::fetchByPathData(std::move(pathData)); int parentId = item->parent()->data(0, Qt::UserRole).toInt(); if (parentId != noteSubFolder.getId()) { @@ -3694,8 +3514,8 @@ bool MainWindow::jumpToNoteHistoryItem(const NoteHistoryItem &historyItem) { * @return */ bool MainWindow::jumpToNoteSubFolder(int noteSubFolderId) { - QTreeWidgetItem *item = Utils::Gui::getTreeWidgetItemWithUserData( - ui->noteSubFolderTreeWidget, noteSubFolderId); + QTreeWidgetItem *item = + Utils::Gui::getTreeWidgetItemWithUserData(ui->noteSubFolderTreeWidget, noteSubFolderId); if (item != nullptr) { // If the selection isn't cleared then the old subfolder is still selected too @@ -3708,8 +3528,7 @@ bool MainWindow::jumpToNoteSubFolder(int noteSubFolderId) { return false; } -void MainWindow::selectNavigationItemAtPosition(int position) -{ +void MainWindow::selectNavigationItemAtPosition(int position) { if (ui->navigationWidget->isVisible()) { ui->navigationWidget->selectItemForCursorPosition(position); } @@ -3725,8 +3544,8 @@ QString MainWindow::selectOwnCloudNotesFolder() { // TODO(pbek): We sometimes seem to get a "QCoreApplication::postEvent: // Unexpected null receiver" here. QString dir = QFileDialog::getExistingDirectory( - this, tr("Please select the folder where your notes will get stored"), - path, QFileDialog::ShowDirsOnly); + this, tr("Please select the folder where your notes will get stored"), path, + QFileDialog::ShowDirsOnly); QDir d = QDir(dir); @@ -3741,10 +3560,8 @@ QString MainWindow::selectOwnCloudNotesFolder() { QSettings settings; // make the path relative to the portable data path if we are in // portable mode - settings.setValue( - QStringLiteral("notesPath"), - Utils::Misc::makePathRelativeToPortableDataPathIfNeeded( - std::move(dir))); + settings.setValue(QStringLiteral("notesPath"), + Utils::Misc::makePathRelativeToPortableDataPathIfNeeded(std::move(dir))); // update the current folder tooltip updateCurrentFolderTooltip(); @@ -3752,9 +3569,8 @@ QString MainWindow::selectOwnCloudNotesFolder() { if (this->notesPath.isEmpty()) { switch (QMessageBox::information( this, tr("No folder was selected"), - Utils::Misc::replaceOwnCloudText( - tr("You have to select your ownCloud notes " - "folder to make this software work!")), + Utils::Misc::replaceOwnCloudText(tr("You have to select your ownCloud notes " + "folder to make this software work!")), tr("&Retry"), tr("&Exit"), QString(), 0, 1)) { case 0: selectOwnCloudNotesFolder(); @@ -3805,15 +3621,12 @@ void MainWindow::reloadCurrentNoteByNoteId(bool updateNoteText) { activeNoteTextEdit()->setTextCursor(cursor); } -void MainWindow::setCurrentNote(Note note, bool updateNoteText, - bool updateSelectedNote, +void MainWindow::setCurrentNote(Note note, bool updateNoteText, bool updateSelectedNote, bool addNoteToHistory) { - qDebug() << __func__ << " - 'note': " << note - << " - 'updateNoteText': " << updateNoteText + qDebug() << __func__ << " - 'note': " << note << " - 'updateNoteText': " << updateNoteText << " - 'updateSelectedNote': " << updateSelectedNote; - MetricsService::instance()->sendVisitIfEnabled( - QStringLiteral("note/current-note/changed")); + MetricsService::instance()->sendVisitIfEnabled(QStringLiteral("note/current-note/changed")); // if note subfolder was different than the current we will // switch to that note subfolder @@ -3830,8 +3643,7 @@ void MainWindow::setCurrentNote(Note note, bool updateNoteText, // update cursor position of previous note const int noteId = note.getId(); if (currentNote.exists() && (currentNote.getId() != noteId)) { - this->noteHistory.updateCursorPositionOfNote(this->currentNote, - ui->noteTextEdit); + this->noteHistory.updateCursorPositionOfNote(this->currentNote, ui->noteTextEdit); } this->_lastNoteId = this->currentNote.getId(); @@ -3846,7 +3658,7 @@ void MainWindow::setCurrentNote(Note note, bool updateNoteText, // update current tab if (!jumpToTab(note) && Utils::Gui::isTabWidgetTabSticky( - ui->noteEditTabWidget, ui->noteEditTabWidget->currentIndex())) { + ui->noteEditTabWidget, ui->noteEditTabWidget->currentIndex())) { openCurrentNoteInTab(); } @@ -3854,8 +3666,7 @@ void MainWindow::setCurrentNote(Note note, bool updateNoteText, // find and set the current item if (updateSelectedNote) { - QList<QTreeWidgetItem *> items = - ui->noteTreeWidget->findItems(name, Qt::MatchExactly); + QList<QTreeWidgetItem *> items = ui->noteTreeWidget->findItems(name, Qt::MatchExactly); if (items.count() > 0) { const QSignalBlocker blocker(ui->noteTreeWidget); Q_UNUSED(blocker) @@ -3917,8 +3728,7 @@ void MainWindow::setCurrentNote(Note note, bool updateNoteText, } void MainWindow::updateCurrentTabData(const Note ¬e) const { - Utils::Gui::updateTabWidgetTabData(ui->noteEditTabWidget, - ui->noteEditTabWidget->currentIndex(), + Utils::Gui::updateTabWidgetTabData(ui->noteEditTabWidget, ui->noteEditTabWidget->currentIndex(), note); } @@ -3926,8 +3736,7 @@ void MainWindow::closeOrphanedTabs() const { const int maxIndex = ui->noteEditTabWidget->count() - 1; for (int i = maxIndex; i >= 0; i--) { - const int noteId = Utils::Gui::getTabWidgetNoteId( - ui->noteEditTabWidget, i); + const int noteId = Utils::Gui::getTabWidgetNoteId(ui->noteEditTabWidget, i); if (!Note::noteIdExists(noteId)) { removeNoteTab(i); @@ -3960,8 +3769,7 @@ bool MainWindow::jumpToTab(const Note ¬e) const { */ void MainWindow::updateCurrentNoteTextHash() { _currentNoteTextHash = QString( - QCryptographicHash::hash(currentNote.getNoteText().toLocal8Bit(), - QCryptographicHash::Sha1) + QCryptographicHash::hash(currentNote.getNoteText().toLocal8Bit(), QCryptographicHash::Sha1) .toHex()); } @@ -3970,17 +3778,15 @@ void MainWindow::updateCurrentNoteTextHash() { * note file is not writable or the note is encrypted */ void MainWindow::updateNoteTextEditReadOnly() { - setNoteTextEditReadOnly(!(currentNote.exists() && - currentNote.fileWriteable() && + setNoteTextEditReadOnly(!(currentNote.exists() && currentNote.fileWriteable() && Utils::Misc::isNoteEditingAllowed())); if (ui->noteTextEdit->isVisible() && currentNote.hasEncryptedNoteText()) { ui->noteTextEdit->setReadOnly(true); } - ui->noteTextEdit->setTextInteractionFlags( - ui->noteTextEdit->textInteractionFlags() | - Qt::TextSelectableByKeyboard); + ui->noteTextEdit->setTextInteractionFlags(ui->noteTextEdit->textInteractionFlags() | + Qt::TextSelectableByKeyboard); } /** @@ -3992,12 +3798,10 @@ void MainWindow::setNoteTextEditReadOnly(bool readonly) const { ui->noteTextEdit->setReadOnly(readonly); ui->encryptedNoteTextEdit->setReadOnly(readonly); - ui->noteTextEdit->setTextInteractionFlags( - ui->noteTextEdit->textInteractionFlags() | - Qt::TextSelectableByKeyboard); + ui->noteTextEdit->setTextInteractionFlags(ui->noteTextEdit->textInteractionFlags() | + Qt::TextSelectableByKeyboard); ui->encryptedNoteTextEdit->setTextInteractionFlags( - ui->encryptedNoteTextEdit->textInteractionFlags() | - Qt::TextSelectableByKeyboard); + ui->encryptedNoteTextEdit->textInteractionFlags() | Qt::TextSelectableByKeyboard); } /** @@ -4014,12 +3818,10 @@ void MainWindow::updateShareButton() { */ void MainWindow::updateWindowTitle() { const QString &session = qApp->property("session").toString(); - QString title = currentNote.exists() ? - currentNote.getName() : QStringLiteral("#"); + QString title = currentNote.exists() ? currentNote.getName() : QStringLiteral("#"); if (NoteFolder::countAll() > 0) { - title += QStringLiteral(" - %1").arg( - NoteFolder::currentNoteFolder().getName()); + title += QStringLiteral(" - %1").arg(NoteFolder::currentNoteFolder().getName()); } if (!session.isEmpty()) { @@ -4062,11 +3864,10 @@ void MainWindow::removeCurrentNote() { // store updated notes to disk storeUpdatedNotesToDisk(); - if (Utils::Gui::question(this, tr("Remove current note"), - tr("Remove current note: <strong>%1</strong>?") - .arg(this->currentNote.getName()), - QStringLiteral("remove-note")) == - QMessageBox::Yes) { + if (Utils::Gui::question( + this, tr("Remove current note"), + tr("Remove current note: <strong>%1</strong>?").arg(this->currentNote.getName()), + QStringLiteral("remove-note")) == QMessageBox::Yes) { const QSignalBlocker blocker2(ui->noteTextEdit); Q_UNUSED(blocker2) @@ -4114,11 +3915,10 @@ void MainWindow::removeCurrentNote() { * Searches and removes note from the note tree widget */ void MainWindow::removeNoteFromNoteTreeWidget(Note ¬e) const { - auto *item = Utils::Gui::getTreeWidgetItemWithUserData(ui->noteTreeWidget, - note.getId()); + auto *item = Utils::Gui::getTreeWidgetItemWithUserData(ui->noteTreeWidget, note.getId()); if (item != nullptr) { - delete(item); + delete (item); } } @@ -4127,8 +3927,7 @@ void MainWindow::removeNoteFromNoteTreeWidget(Note ¬e) const { */ void MainWindow::resetCurrentNote(bool goToTop) { auto *event = - new QKeyEvent(QEvent::KeyPress, goToTop ? Qt::Key_Home : Qt::Key_Down, - Qt::NoModifier); + new QKeyEvent(QEvent::KeyPress, goToTop ? Qt::Key_Home : Qt::Key_Down, Qt::NoModifier); QApplication::postEvent(ui->noteTreeWidget, event); } @@ -4140,8 +3939,7 @@ void MainWindow::storeSettings() { // don't store the window settings in distraction free mode if (!isInDistractionFreeMode()) { - settings.setValue(QStringLiteral("MainWindow/geometry"), - saveGeometry()); + settings.setValue(QStringLiteral("MainWindow/geometry"), saveGeometry()); settings.setValue(QStringLiteral("MainWindow/menuBarGeometry"), ui->menuBar->saveGeometry()); } @@ -4216,21 +4014,20 @@ bool MainWindow::eventFilter(QObject *obj, QEvent *event) { // the current text will be added if (keyEvent->key() == Qt::Key_Tab) { // fetch the tag that is starting with the current text - Tag tag = - Tag::fetchByName(ui->newNoteTagLineEdit->text(), true); + Tag tag = Tag::fetchByName(ui->newNoteTagLineEdit->text(), true); if (tag.isFetched()) { linkTagNameToCurrentNote(tag.getName(), true); on_newNoteTagLineEdit_editingFinished(); } - return QMainWindow::eventFilter(obj, event);; + return QMainWindow::eventFilter(obj, event); + ; } } else if (obj == ui->searchLineEdit) { bool downSelectNote = false; // fallback to the default completion - ui->searchLineEdit->completer()->setCompletionMode( - QCompleter::PopupCompletion); + ui->searchLineEdit->completer()->setCompletionMode(QCompleter::PopupCompletion); if (keyEvent->key() == Qt::Key_Down) { if (ui->searchLineEdit->completer()->completionCount() > 0) { @@ -4243,7 +4040,8 @@ bool MainWindow::eventFilter(QObject *obj, QEvent *event) { // open the completer ui->searchLineEdit->completer()->complete(); - return QMainWindow::eventFilter(obj, event);; + return QMainWindow::eventFilter(obj, event); + ; } else { // if nothing was found in the completer we want to jump // to the note list @@ -4253,16 +4051,15 @@ bool MainWindow::eventFilter(QObject *obj, QEvent *event) { // set focus to the notes list if Key_Right or Key_Tab were // pressed in the search line edit - if ((keyEvent->key() == Qt::Key_Right) || - (keyEvent->key() == Qt::Key_Tab) || downSelectNote) { + if ((keyEvent->key() == Qt::Key_Right) || (keyEvent->key() == Qt::Key_Tab) || + downSelectNote) { // add the current search text to the saved searches storeSavedSearch(); // choose another selected item if current item is invisible QTreeWidgetItem *item = ui->noteTreeWidget->currentItem(); if ((item != nullptr) && item->isHidden()) { - QTreeWidgetItem *firstVisibleItem = - firstVisibleNoteTreeWidgetItem(); + QTreeWidgetItem *firstVisibleItem = firstVisibleNoteTreeWidgetItem(); if (firstVisibleItem != nullptr) { ui->noteTreeWidget->setCurrentItem(firstVisibleItem); } @@ -4272,31 +4069,30 @@ bool MainWindow::eventFilter(QObject *obj, QEvent *event) { ui->noteTreeWidget->setFocus(); return true; } - return QMainWindow::eventFilter(obj, event);; + return QMainWindow::eventFilter(obj, event); + ; } else if (obj == activeNoteTextEdit()) { // check if we want to leave the distraction free mode and the // search widget is not visible (because we want to close that // first) - if ((keyEvent->key() == Qt::Key_Escape) && - isInDistractionFreeMode() && + if ((keyEvent->key() == Qt::Key_Escape) && isInDistractionFreeMode() && !activeNoteTextEdit()->searchWidget()->isVisible()) { toggleDistractionFreeMode(); return true; } - return QMainWindow::eventFilter(obj, event);; + return QMainWindow::eventFilter(obj, event); + ; } else if (obj == ui->noteTreeWidget) { // set focus to the note text edit if Key_Return or Key_Tab were // pressed in the notes list - if ((keyEvent->key() == Qt::Key_Return) || - (keyEvent->key() == Qt::Key_Tab)) { + if ((keyEvent->key() == Qt::Key_Return) || (keyEvent->key() == Qt::Key_Tab)) { // focusNoteTextEdit() might cause a crash in // on_noteTreeWidget_itemChanged if Note::allowDifferentFileName() // is true when Note::handleNoteRenaming is called, the // QTimer::singleShot helps with that - QTimer::singleShot(150, this, - SLOT(focusNoteTextEdit())); + QTimer::singleShot(150, this, SLOT(focusNoteTextEdit())); return true; } else if ((keyEvent->key() == Qt::Key_Delete) || @@ -4307,10 +4103,10 @@ bool MainWindow::eventFilter(QObject *obj, QEvent *event) { ui->searchLineEdit->clear(); return true; } - return QMainWindow::eventFilter(obj, event);; + return QMainWindow::eventFilter(obj, event); + ; } else if (obj == ui->tagTreeWidget) { - if ((keyEvent->key() == Qt::Key_Delete) || - (keyEvent->key() == Qt::Key_Backspace)) { + if ((keyEvent->key() == Qt::Key_Delete) || (keyEvent->key() == Qt::Key_Backspace)) { removeSelectedTags(); return true; } @@ -4322,7 +4118,7 @@ bool MainWindow::eventFilter(QObject *obj, QEvent *event) { if ((mouseEvent->button() == Qt::BackButton)) { // There was an issue with the back button triggering infinitely when // the selected notes were opened in a new tab, the singleShot helped - QTimer::singleShot(0, this, [this] () { + QTimer::singleShot(0, this, [this]() { // move back in the note history on_action_Back_in_note_history_triggered(); }); @@ -4330,8 +4126,7 @@ bool MainWindow::eventFilter(QObject *obj, QEvent *event) { // move forward in the note history on_action_Forward_in_note_history_triggered(); } - } else if (event->type() == QEvent::MouseButtonPress && - obj == ui->selectedTagsToolButton) { + } else if (event->type() == QEvent::MouseButtonPress && obj == ui->selectedTagsToolButton) { // we don't want to make the button clickable return true; } @@ -4343,8 +4138,7 @@ bool MainWindow::eventFilter(QObject *obj, QEvent *event) { * Finds the first visible tree widget item */ QTreeWidgetItem *MainWindow::firstVisibleNoteTreeWidgetItem() { - QTreeWidgetItemIterator it(ui->noteTreeWidget, - QTreeWidgetItemIterator::NotHidden); + QTreeWidgetItemIterator it(ui->noteTreeWidget, QTreeWidgetItemIterator::NotHidden); return *it; } @@ -4363,28 +4157,24 @@ void MainWindow::searchInNoteTextEdit(QString str) { doSearchInNote(str); ui->noteTextEdit->moveCursor(QTextCursor::Start); #ifndef USE_QLITEHTML - ui->noteTextView->moveCursor(QTextCursor::Start); + ui->noteTextView->moveCursor(QTextCursor::Start); #endif ui->encryptedNoteTextEdit->moveCursor(QTextCursor::Start); const QColor color = QColor(0, 180, 0, 100); // build the string list of the search string - const QString queryStr = - str.replace(QLatin1String("|"), QLatin1String("\\|")); - const QStringList queryStrings = - Note::buildQueryStringList(queryStr, true); + const QString queryStr = str.replace(QLatin1String("|"), QLatin1String("\\|")); + const QStringList queryStrings = Note::buildQueryStringList(queryStr, true); if (queryStrings.count() > 0) { #if (QT_VERSION >= QT_VERSION_CHECK(5, 13, 0)) const QRegularExpression regExp( - QLatin1Char('(') + queryStrings.join(QLatin1String("|")) + - QLatin1Char(')'), + QLatin1Char('(') + queryStrings.join(QLatin1String("|")) + QLatin1Char(')'), QRegularExpression::CaseInsensitiveOption); #else - const QRegExp regExp(QLatin1String("(") + - queryStrings.join(QLatin1String("|")) + - QLatin1String(")"), - Qt::CaseInsensitive); + const QRegExp regExp( + QLatin1String("(") + queryStrings.join(QLatin1String("|")) + QLatin1String(")"), + Qt::CaseInsensitive); #endif while (ui->noteTextEdit->find(regExp)) { QTextEdit::ExtraSelection extra = QTextEdit::ExtraSelection(); @@ -4396,15 +4186,15 @@ void MainWindow::searchInNoteTextEdit(QString str) { // TODO: #ifdef USE_QLITEHTML - _notePreviewWidget->findText(str, QTextDocument::FindFlag::FindWholeWords, true); + _notePreviewWidget->findText(str, QTextDocument::FindFlag::FindWholeWords, true); #else - while (ui->noteTextView->find(regExp)) { - QTextEdit::ExtraSelection extra = QTextEdit::ExtraSelection(); - extra.format.setBackground(color); + while (ui->noteTextView->find(regExp)) { + QTextEdit::ExtraSelection extra = QTextEdit::ExtraSelection(); + extra.format.setBackground(color); - extra.cursor = ui->noteTextView->textCursor(); - extraSelections2.append(extra); - } + extra.cursor = ui->noteTextView->textCursor(); + extraSelections2.append(extra); + } #endif while (ui->encryptedNoteTextEdit->find(regExp)) { QTextEdit::ExtraSelection extra = QTextEdit::ExtraSelection(); @@ -4418,7 +4208,7 @@ void MainWindow::searchInNoteTextEdit(QString str) { ui->noteTextEdit->setExtraSelections(extraSelections); #ifndef USE_QLITEHTML - ui->noteTextView->setExtraSelections(extraSelections2); + ui->noteTextView->setExtraSelections(extraSelections2); #endif ui->encryptedNoteTextEdit->setExtraSelections(extraSelections3); } @@ -4439,13 +4229,11 @@ void MainWindow::searchForSearchLineTextInNoteTextEdit() { /** * Asks for the password if the note is encrypted and can't be decrypted */ -void MainWindow::askForEncryptedNotePasswordIfNeeded( - const QString &additionalText) { +void MainWindow::askForEncryptedNotePasswordIfNeeded(const QString &additionalText) { currentNote.refetch(); // check if the note is encrypted and can't be decrypted - if (currentNote.hasEncryptedNoteText() && - !currentNote.canDecryptNoteText()) { + if (currentNote.hasEncryptedNoteText() && !currentNote.canDecryptNoteText()) { QString labelText = tr("Please enter the <strong>password</strong> " "of this encrypted note."); @@ -4469,9 +4257,8 @@ void MainWindow::askForEncryptedNotePasswordIfNeeded( // warn if password is incorrect if (!currentNote.canDecryptNoteText()) { - QMessageBox::warning( - this, tr("Note can't be decrypted!"), - tr("It seems that your password is not valid!")); + QMessageBox::warning(this, tr("Note can't be decrypted!"), + tr("It seems that your password is not valid!")); } } @@ -4504,7 +4291,8 @@ int MainWindow::getMaxImageWidth() const { * Sets the note text according to a note */ void MainWindow::setNoteTextFromNote(Note *note, bool updateNoteTextViewOnly, - bool ignorePreviewVisibility, bool allowRestoreCursorPosition) { + bool ignorePreviewVisibility, + bool allowRestoreCursorPosition) { if (note == nullptr) { return; } @@ -4512,10 +4300,9 @@ void MainWindow::setNoteTextFromNote(Note *note, bool updateNoteTextViewOnly, auto historyItem = noteHistory.getLastItemOfNote(currentNote); if (!updateNoteTextViewOnly) { - qobject_cast<QOwnNotesMarkdownHighlighter *>( - ui->noteTextEdit->highlighter()) - ->updateCurrentNote(note); - ui->noteTextEdit->setText(note->getNoteText()); + qobject_cast<QOwnNotesMarkdownHighlighter *>(ui->noteTextEdit->highlighter()) + ->updateCurrentNote(note); + ui->noteTextEdit->setText(note->getNoteText()); } if (allowRestoreCursorPosition && Utils::Misc::isRestoreCursorPosition()) { @@ -4527,14 +4314,12 @@ void MainWindow::setNoteTextFromNote(Note *note, bool updateNoteTextViewOnly, if (_notePreviewDockWidget->isVisible() || ignorePreviewVisibility) { const bool decrypt = ui->noteTextEdit->isHidden(); - const QString html = note->toMarkdownHtml( - NoteFolder::currentLocalPath(), getMaxImageWidth(), false, decrypt); + const QString html = note->toMarkdownHtml(NoteFolder::currentLocalPath(), + getMaxImageWidth(), false, decrypt); // create a hash of the html (because const QString hash = - QString(QCryptographicHash::hash(html.toLocal8Bit(), - QCryptographicHash::Sha1) - .toHex()); + QString(QCryptographicHash::hash(html.toLocal8Bit(), QCryptographicHash::Sha1).toHex()); // update the note preview if the text has changed // we use our hash because ui->noteTextView->toHtml() may return @@ -4550,8 +4335,7 @@ void MainWindow::setNoteTextFromNote(Note *note, bool updateNoteTextViewOnly, } // update the slider when editing notes - noteTextSliderValueChanged( - activeNoteTextEdit()->verticalScrollBar()->value(), true); + noteTextSliderValueChanged(activeNoteTextEdit()->verticalScrollBar()->value(), true); } /** @@ -4584,20 +4368,18 @@ void MainWindow::setCurrentNoteText(QString text) { * @param text * @param cursorAtEnd */ -void MainWindow::createNewNote(QString name, QString text, - CreateNewNoteOptions options) { +void MainWindow::createNewNote(QString name, QString text, CreateNewNoteOptions options) { const QString extension = Note::defaultNoteFileExtension(); - auto *f = new QFile(this->notesPath + QDir::separator() + name + - QStringLiteral(".") + extension); - const bool useNameAsHeadline = - options.testFlag(CreateNewNoteOption::UseNameAsHeadline); + auto *f = + new QFile(this->notesPath + QDir::separator() + name + QStringLiteral(".") + extension); + const bool useNameAsHeadline = options.testFlag(CreateNewNoteOption::UseNameAsHeadline); // change the name and headline if note exists if (f->exists()) { QDateTime currentDate = QDateTime::currentDateTime(); - name.append(QStringLiteral(" ") + - currentDate.toString(Qt::ISODate) - .replace(QStringLiteral(":"), QStringLiteral("."))); + name.append( + QStringLiteral(" ") + + currentDate.toString(Qt::ISODate).replace(QStringLiteral(":"), QStringLiteral("."))); if (!useNameAsHeadline) { QString preText = Note::createNoteHeader(name); @@ -4608,8 +4390,7 @@ void MainWindow::createNewNote(QString name, QString text, // create a new note ui->searchLineEdit->setText(name); - jumpToNoteOrCreateNew( - options.testFlag(CreateNewNoteOption::DisableLoadNoteDirectoryList)); + jumpToNoteOrCreateNew(options.testFlag(CreateNewNoteOption::DisableLoadNoteDirectoryList)); // check if to append the text or replace the text of the note if (useNameAsHeadline) { @@ -4638,8 +4419,7 @@ void MainWindow::createNewNote(QString name, QString text, * * This is a public callback function for the trash dialog. */ -void MainWindow::restoreTrashedNoteOnServer(const QString &fileName, - int timestamp) { +void MainWindow::restoreTrashedNoteOnServer(const QString &fileName, int timestamp) { OwnCloudService *ownCloud = OwnCloudService::instance(); ownCloud->restoreTrashedNoteOnServer(fileName, timestamp); } @@ -4659,12 +4439,11 @@ void MainWindow::removeSelectedNotes() { if (Utils::Gui::question( this, tr("Remove selected notes"), - Utils::Misc::replaceOwnCloudText( - tr("Remove <strong>%n</strong> selected note(s)?\n\n" - "If the trash is enabled on your " - "ownCloud server you should be able to restore " - "them from there.", - "", selectedItemsCount)), + Utils::Misc::replaceOwnCloudText(tr("Remove <strong>%n</strong> selected note(s)?\n\n" + "If the trash is enabled on your " + "ownCloud server you should be able to restore " + "them from there.", + "", selectedItemsCount)), QStringLiteral("remove-notes")) == QMessageBox::Yes) { const QSignalBlocker blocker(this->noteDirectoryWatcher); Q_UNUSED(blocker) @@ -4732,12 +4511,11 @@ void MainWindow::removeSelectedTags() { return; } - if (Utils::Gui::question( - this, tr("Remove selected tags"), - tr("Remove <strong>%n</strong> selected tag(s)? No notes will " - "be removed in this process.", - "", selectedItemsCount), - QStringLiteral("remove-tags")) == QMessageBox::Yes) { + if (Utils::Gui::question(this, tr("Remove selected tags"), + tr("Remove <strong>%n</strong> selected tag(s)? No notes will " + "be removed in this process.", + "", selectedItemsCount), + QStringLiteral("remove-tags")) == QMessageBox::Yes) { const QSignalBlocker blocker(this->noteDirectoryWatcher); Q_UNUSED(blocker) @@ -4789,8 +4567,7 @@ void MainWindow::moveSelectedNotesToFolder(const QString &destinationFolder) { if (Utils::Gui::question( this, tr("Move selected notes"), - tr("Move %n selected note(s) to <strong>%2</strong>?", "", - selectedItemsCount) + tr("Move %n selected note(s) to <strong>%2</strong>?", "", selectedItemsCount) .arg(destinationFolder), QStringLiteral("move-notes")) == QMessageBox::Yes) { const QSignalBlocker blocker(this->noteDirectoryWatcher); @@ -4865,7 +4642,7 @@ void MainWindow::unsetCurrentNote() { // clear the note preview #ifndef USE_QLITEHTML const QSignalBlocker blocker(ui->noteTextView); - ui->noteTextView->clear(); + ui->noteTextView->clear(); #else const QSignalBlocker blocker(_notePreviewWidget); _notePreviewWidget->setHtml(QString()); @@ -4900,8 +4677,7 @@ void MainWindow::copySelectedNotesToFolder(const QString &destinationFolder, if (Utils::Gui::question( this, tr("Copy selected notes"), - tr("Copy %n selected note(s) to <strong>%2</strong>?", "", - selectedItemsCount) + tr("Copy %n selected note(s) to <strong>%2</strong>?", "", selectedItemsCount) .arg(destinationFolder), QStringLiteral("copy-notes")) == QMessageBox::Yes) { int copyCount = 0; @@ -4919,8 +4695,7 @@ void MainWindow::copySelectedNotesToFolder(const QString &destinationFolder, } // copy note - const bool result = - note.copyToPath(destinationFolder, noteFolderPath); + const bool result = note.copyToPath(destinationFolder, noteFolderPath); if (result) { copyCount++; qDebug() << "Note was copied:" << note.getName(); @@ -4929,11 +4704,10 @@ void MainWindow::copySelectedNotesToFolder(const QString &destinationFolder, } } - Utils::Gui::information( - this, tr("Done"), - tr("%n note(s) were copied to <strong>%2</strong>.", "", copyCount) - .arg(destinationFolder), - QStringLiteral("notes-copied")); + Utils::Gui::information(this, tr("Done"), + tr("%n note(s) were copied to <strong>%2</strong>.", "", copyCount) + .arg(destinationFolder), + QStringLiteral("notes-copied")); } } @@ -4945,13 +4719,11 @@ void MainWindow::tagSelectedNotes(const Tag &tag) { if (Utils::Gui::question( this, tr("Tag selected notes"), - tr("Tag %n selected note(s) with <strong>%2</strong>?", "", - selectedItemsCount) + tr("Tag %n selected note(s) with <strong>%2</strong>?", "", selectedItemsCount) .arg(tag.getName()), QStringLiteral("tag-notes")) == QMessageBox::Yes) { int tagCount = 0; - const bool useScriptingEngine = - ScriptingService::instance()->noteTaggingHookExists(); + const bool useScriptingEngine = ScriptingService::instance()->noteTaggingHookExists(); // workaround when signal block doesn't work correctly directoryWatcherWorkaround(true, true); @@ -5003,9 +4775,7 @@ void MainWindow::tagSelectedNotes(const Tag &tag) { reloadTagTree(); showStatusBarMessage( - tr("%n note(s) were tagged with \"%2\"", "", tagCount) - .arg(tag.getName()), - 5000); + tr("%n note(s) were tagged with \"%2\"", "", tagCount).arg(tag.getName()), 5000); // turn off the workaround again directoryWatcherWorkaround(false, true); @@ -5020,13 +4790,11 @@ void MainWindow::removeTagFromSelectedNotes(const Tag &tag) { if (Utils::Gui::question( this, tr("Remove tag from selected notes"), - tr("Remove tag <strong>%1</strong> from %n selected note(s)?", "", - selectedItemsCount) + tr("Remove tag <strong>%1</strong> from %n selected note(s)?", "", selectedItemsCount) .arg(tag.getName()), QStringLiteral("remove-tag-from-notes")) == QMessageBox::Yes) { int tagCount = 0; - const bool useScriptingEngine = - ScriptingService::instance()->noteTaggingHookExists(); + const bool useScriptingEngine = ScriptingService::instance()->noteTaggingHookExists(); // workaround when signal blocking doesn't work correctly directoryWatcherWorkaround(true, true); @@ -5062,8 +4830,7 @@ void MainWindow::removeTagFromSelectedNotes(const Tag &tag) { // handle the coloring of the note in the note tree widget handleNoteTreeTagColoringForNote(note); } else { - qWarning() << "Could not remove tag from note:" - << note.getName(); + qWarning() << "Could not remove tag from note:" << note.getName(); } } @@ -5080,8 +4847,7 @@ void MainWindow::removeTagFromSelectedNotes(const Tag &tag) { Utils::Gui::information( this, tr("Done"), - tr("Tag <strong>%1</strong> was removed from %n note(s)", "", - tagCount) + tr("Tag <strong>%1</strong> was removed from %n note(s)", "", tagCount) .arg(tag.getName()), QStringLiteral("tag-removed-from-notes")); @@ -5096,9 +4862,8 @@ void MainWindow::removeTagFromSelectedNotes(const Tag &tag) { * @param isNotesDirectoryWasModifiedDisabled * @param alsoHandleNotesWereModified */ -void MainWindow::directoryWatcherWorkaround( - bool isNotesDirectoryWasModifiedDisabled, - bool alsoHandleNotesWereModified) { +void MainWindow::directoryWatcherWorkaround(bool isNotesDirectoryWasModifiedDisabled, + bool alsoHandleNotesWereModified) { if (!isNotesDirectoryWasModifiedDisabled) { Utils::Misc::waitMsecs(200); } @@ -5125,10 +4890,9 @@ void MainWindow::handleNoteTreeTagColoringForNote(const Note ¬e) { * @brief Updates the current folder tooltip */ void MainWindow::updateCurrentFolderTooltip() { - ui->actionSet_ownCloud_Folder->setStatusTip(tr("Current notes folder: ") + - this->notesPath); - ui->actionSet_ownCloud_Folder->setToolTip( - tr("Set the notes folder. Current notes folder: ") + this->notesPath); + ui->actionSet_ownCloud_Folder->setStatusTip(tr("Current notes folder: ") + this->notesPath); + ui->actionSet_ownCloud_Folder->setToolTip(tr("Set the notes folder. Current notes folder: ") + + this->notesPath); } /** @@ -5221,12 +4985,11 @@ bool MainWindow::showRestartNotificationIfNeeded(bool force) { qApp->setProperty("needsRestart", false); - if (QMessageBox::information( - this, tr("Restart application"), - tr("You may need to restart the application to let the " - "changes take effect.") + - Utils::Misc::appendSingleAppInstanceTextIfNeeded(), - tr("Restart"), tr("Cancel"), QString(), 0, 1) == 0) { + if (QMessageBox::information(this, tr("Restart application"), + tr("You may need to restart the application to let the " + "changes take effect.") + + Utils::Misc::appendSingleAppInstanceTextIfNeeded(), + tr("Restart"), tr("Cancel"), QString(), 0, 1) == 0) { storeSettings(); Utils::Misc::restartApplication(); @@ -5240,8 +5003,7 @@ bool MainWindow::showRestartNotificationIfNeeded(bool force) { * @brief Returns the active note text edit */ QOwnNotesMarkdownTextEdit *MainWindow::activeNoteTextEdit() { - return ui->noteTextEdit->isHidden() ? ui->encryptedNoteTextEdit - : ui->noteTextEdit; + return ui->noteTextEdit->isHidden() ? ui->encryptedNoteTextEdit : ui->noteTextEdit; } /** @@ -5267,27 +5029,25 @@ void MainWindow::handleTextNoteLinking(int page) { if ((!noteName.isEmpty()) || (!url.isEmpty())) { QString newText; - QString chosenLinkName = linkName.isEmpty() - ? textEdit->textCursor().selectedText() - : linkName; + QString chosenLinkName = + linkName.isEmpty() ? textEdit->textCursor().selectedText() : linkName; // remove ] characters, because they will break markdown links chosenLinkName.remove("]"); // if user has entered an url if (!url.isEmpty()) { newText = !chosenLinkName.isEmpty() - ? QStringLiteral("[") + chosenLinkName + - QStringLiteral("](") + url + + ? QStringLiteral("[") + chosenLinkName + QStringLiteral("](") + url + QStringLiteral(")") : QStringLiteral("<") + url + QStringLiteral(">"); } else { - const QString noteUrl = currentNote.getNoteUrlForLinkingTo( - dialog->getSelectedNote()); + const QString noteUrl = + currentNote.getNoteUrlForLinkingTo(dialog->getSelectedNote()); const QString heading = dialog->getSelectedHeading(); - const QString headingText = heading.isEmpty() ? - QStringLiteral() : QStringLiteral("#") + - QUrl::toPercentEncoding(heading); + const QString headingText = + heading.isEmpty() ? QStringLiteral() + : QStringLiteral("#") + QUrl::toPercentEncoding(heading); // if user has selected a note if (!chosenLinkName.isEmpty()) { @@ -5297,9 +5057,8 @@ void MainWindow::handleTextNoteLinking(int page) { noteName += QStringLiteral(" - ") + heading; } - newText = QStringLiteral("[") + noteName + - QStringLiteral("](") + noteUrl + headingText + - QStringLiteral(")"); + newText = QStringLiteral("[") + noteName + QStringLiteral("](") + noteUrl + + headingText + QStringLiteral(")"); } if (!linkDescription.isEmpty()) { @@ -5330,8 +5089,7 @@ void MainWindow::setCurrentNoteFromHistoryItem(const NoteHistoryItem &item) { * @param textEdit */ bool MainWindow::preparePrintNotePrinter(QPrinter *printer) { - Utils::Misc::loadPrinterSettings(printer, - QStringLiteral("Printer/NotePrinting")); + Utils::Misc::loadPrinterSettings(printer, QStringLiteral("Printer/NotePrinting")); QPrintDialog dialog(printer, this); dialog.setWindowTitle(tr("Print note")); @@ -5341,8 +5099,7 @@ bool MainWindow::preparePrintNotePrinter(QPrinter *printer) { return false; } - Utils::Misc::storePrinterSettings(printer, - QStringLiteral("Printer/NotePrinting")); + Utils::Misc::storePrinterSettings(printer, QStringLiteral("Printer/NotePrinting")); return true; } @@ -5351,7 +5108,6 @@ bool MainWindow::preparePrintNotePrinter(QPrinter *printer) { * @param textEdit */ void MainWindow::printTextDocument(QTextDocument *textDocument) { - QPrinter printer; if (preparePrintNotePrinter(&printer)) { textDocument->print(&printer); @@ -5365,8 +5121,7 @@ void MainWindow::printTextDocument(QTextDocument *textDocument) { */ bool MainWindow::prepareExportNoteAsPDFPrinter(QPrinter *printer) { #ifdef Q_OS_LINUX - Utils::Misc::loadPrinterSettings(printer, - QStringLiteral("Printer/NotePDFExport")); + Utils::Misc::loadPrinterSettings(printer, QStringLiteral("Printer/NotePDFExport")); // under Linux we use the QPageSetupDialog to change layout // settings of the PDF export @@ -5376,8 +5131,7 @@ bool MainWindow::prepareExportNoteAsPDFPrinter(QPrinter *printer) { return false; } - Utils::Misc::storePrinterSettings(printer, - QStringLiteral("Printer/NotePDFExport")); + Utils::Misc::storePrinterSettings(printer, QStringLiteral("Printer/NotePDFExport")); #else // under OS X and Windows the QPageSetupDialog dialog doesn't work, // we will use a workaround to select page sizes and the orientation @@ -5386,24 +5140,19 @@ bool MainWindow::prepareExportNoteAsPDFPrinter(QPrinter *printer) { // select the page size QStringList pageSizeStrings; - pageSizeStrings << QStringLiteral("A0") << QStringLiteral("A1") - << QStringLiteral("A2") << QStringLiteral("A3") - << QStringLiteral("A4") << QStringLiteral("A5") - << QStringLiteral("A6") << QStringLiteral("A7") - << QStringLiteral("A8") << QStringLiteral("A9") - << tr("Letter"); + pageSizeStrings << QStringLiteral("A0") << QStringLiteral("A1") << QStringLiteral("A2") + << QStringLiteral("A3") << QStringLiteral("A4") << QStringLiteral("A5") + << QStringLiteral("A6") << QStringLiteral("A7") << QStringLiteral("A8") + << QStringLiteral("A9") << tr("Letter"); QList<QPageSize::PageSizeId> pageSizes; - pageSizes << QPageSize::A0 << QPageSize::A1 << QPageSize::A2 - << QPageSize::A3 << QPageSize::A4 << QPageSize::A5 - << QPageSize::A6 << QPageSize::A7 << QPageSize::A8 - << QPageSize::A9 << QPageSize::Letter; + pageSizes << QPageSize::A0 << QPageSize::A1 << QPageSize::A2 << QPageSize::A3 << QPageSize::A4 + << QPageSize::A5 << QPageSize::A6 << QPageSize::A7 << QPageSize::A8 << QPageSize::A9 + << QPageSize::Letter; bool ok; QString pageSizeString = QInputDialog::getItem( this, tr("Page size"), tr("Page size:"), pageSizeStrings, - settings.value(QStringLiteral("Printer/NotePDFExportPageSize"), 4) - .toInt(), - false, &ok); + settings.value(QStringLiteral("Printer/NotePDFExportPageSize"), 4).toInt(), false, &ok); if (!ok || pageSizeString.isEmpty()) { return false; @@ -5415,8 +5164,7 @@ bool MainWindow::prepareExportNoteAsPDFPrinter(QPrinter *printer) { } QPageSize pageSize(pageSizes.at(pageSizeIndex)); - settings.setValue(QStringLiteral("Printer/NotePDFExportPageSize"), - pageSizeIndex); + settings.setValue(QStringLiteral("Printer/NotePDFExportPageSize"), pageSizeIndex); printer->setPageSize(pageSize); // select the orientation @@ -5427,9 +5175,7 @@ bool MainWindow::prepareExportNoteAsPDFPrinter(QPrinter *printer) { QString orientationString = QInputDialog::getItem( this, tr("Orientation"), tr("Orientation:"), orientationStrings, - settings.value(QStringLiteral("Printer/NotePDFExportOrientation"), 0) - .toInt(), - false, &ok); + settings.value(QStringLiteral("Printer/NotePDFExportOrientation"), 0).toInt(), false, &ok); if (!ok || orientationString.isEmpty()) { return false; @@ -5441,8 +5187,7 @@ bool MainWindow::prepareExportNoteAsPDFPrinter(QPrinter *printer) { } printer->setPageOrientation(orientations.at(orientationIndex)); - settings.setValue(QStringLiteral("Printer/NotePDFExportOrientation"), - orientationIndex); + settings.setValue(QStringLiteral("Printer/NotePDFExportOrientation"), orientationIndex); #endif FileDialog dialog(QStringLiteral("NotePDFExport")); @@ -5500,20 +5245,17 @@ void MainWindow::exportNoteAsPDF(QTextDocument *doc) { */ void MainWindow::showAppMetricsNotificationIfNeeded() { QSettings settings; - bool showDialog = - !settings.value(QStringLiteral("appMetrics/notificationShown")) - .toBool(); + bool showDialog = !settings.value(QStringLiteral("appMetrics/notificationShown")).toBool(); if (showDialog) { settings.setValue(QStringLiteral("appMetrics/notificationShown"), true); - if (QMessageBox::information( - this, QStringLiteral("QOwnNotes"), - tr("QOwnNotes will track anonymous usage data, that helps to " - "decide what parts of QOwnNotes to improve next " - "and to find and fix bugs. You can disable that " - "behaviour in the settings."), - tr("&Ok"), tr("Open &settings"), QString(), 0, 1) == 1) { + if (QMessageBox::information(this, QStringLiteral("QOwnNotes"), + tr("QOwnNotes will track anonymous usage data, that helps to " + "decide what parts of QOwnNotes to improve next " + "and to find and fix bugs. You can disable that " + "behaviour in the settings."), + tr("&Ok"), tr("Open &settings"), QString(), 0, 1) == 1) { openSettingsDialog(SettingsDialog::NetworkPage); } } @@ -5528,8 +5270,7 @@ void MainWindow::openTodoDialog(const QString &taskUid) { tr("You have disabled the todo lists.<br />" "Please check your <strong>Todo</strong> " "configuration in the settings!"), - tr("Open &settings"), tr("&Cancel"), QString(), - 0, 1) == 0) { + tr("Open &settings"), tr("&Cancel"), QString(), 0, 1) == 0) { openSettingsDialog(SettingsDialog::TodoPage); } @@ -5541,17 +5282,15 @@ void MainWindow::openTodoDialog(const QString &taskUid) { QSettings settings; QStringList todoCalendarEnabledUrlList = - settings.value(QStringLiteral("ownCloud/todoCalendarEnabledUrlList")) - .toStringList(); + settings.value(QStringLiteral("ownCloud/todoCalendarEnabledUrlList")).toStringList(); // check if we have got any task list enabled if (todoCalendarEnabledUrlList.count() == 0) { - if (QMessageBox::warning( - nullptr, tr("No selected todo lists!"), - tr("You have not selected any todo lists.<br />" - "Please check your <strong>Todo</strong> " - "configuration in the settings!"), - tr("Open &settings"), tr("&Cancel"), QString(), 0, 1) == 0) { + if (QMessageBox::warning(nullptr, tr("No selected todo lists!"), + tr("You have not selected any todo lists.<br />" + "Please check your <strong>Todo</strong> " + "configuration in the settings!"), + tr("Open &settings"), tr("&Cancel"), QString(), 0, 1) == 0) { openSettingsDialog(SettingsDialog::TodoPage); } @@ -5602,10 +5341,8 @@ void MainWindow::noteTextEditTextWasUpdated() { // we are transforming line feeds, because in some instances Windows // managed to sneak some "special" line feeds in - const QString noteTextFromDisk = - Utils::Misc::transformLineFeeds(note.getNoteText()); - QString text = - Utils::Misc::transformLineFeeds(ui->noteTextEdit->toPlainText()); + const QString noteTextFromDisk = Utils::Misc::transformLineFeeds(note.getNoteText()); + QString text = Utils::Misc::transformLineFeeds(ui->noteTextEdit->toPlainText()); // store the note to the database if the note text differs from the one // on the disk or the note was already modified but not stored to disk @@ -5624,8 +5361,8 @@ void MainWindow::noteTextEditTextWasUpdated() { void MainWindow::handleNoteTextChanged() { QSettings settings; - if (settings.value(QStringLiteral("notesPanelSort"), SORT_BY_LAST_CHANGE) - .toInt() == SORT_BY_LAST_CHANGE) { + if (settings.value(QStringLiteral("notesPanelSort"), SORT_BY_LAST_CHANGE).toInt() == + SORT_BY_LAST_CHANGE) { makeCurrentNoteFirstInNoteList(); } else if (Utils::Misc::isNoteListPreview()) { updateNoteTreeWidgetItem(currentNote); @@ -5635,8 +5372,8 @@ void MainWindow::handleNoteTextChanged() { Q_UNUSED(blocker) // update the note list tooltip of the note - Utils::Gui::setTreeWidgetItemToolTipForNote( - ui->noteTreeWidget->currentItem(), currentNote, ¤tNoteLastEdited); + Utils::Gui::setTreeWidgetItemToolTipForNote(ui->noteTreeWidget->currentItem(), currentNote, + ¤tNoteLastEdited); } void MainWindow::on_action_Quit_triggered() { @@ -5644,9 +5381,7 @@ void MainWindow::on_action_Quit_triggered() { QApplication::quit(); } -void MainWindow::quitApp() { - QApplication::quit(); -} +void MainWindow::quitApp() { QApplication::quit(); } void MainWindow::on_actionSet_ownCloud_Folder_triggered() { // store updated notes to disk @@ -5669,8 +5404,7 @@ void MainWindow::filterNotes(bool searchForText) { // filter the notes by text in the search line edit filterNotesBySearchLineEditText(searchForText); - if (NoteFolder::isCurrentShowSubfolders() && - !_showNotesFromAllNoteSubFolders) { + if (NoteFolder::isCurrentShowSubfolders() && !_showNotesFromAllNoteSubFolders) { // filter the notes by note sub folder filterNotesByNoteSubFolders(); } @@ -5726,18 +5460,15 @@ void MainWindow::filterNotesBySearchLineEditText(bool searchInNote) { } QVector<int> noteIdList = Note::searchInNotes( - searchText, - _showNotesFromAllNoteSubFolders || - NoteSubFolder::isNoteSubfoldersPanelShowNotesRecursively()); + searchText, _showNotesFromAllNoteSubFolders || + NoteSubFolder::isNoteSubfoldersPanelShowNotesRecursively()); int columnWidth = ui->noteTreeWidget->columnWidth(0); ui->noteTreeWidget->setColumnCount(2); int maxWidth = 0; - const QStringList searchTextTerms = - Note::buildQueryStringList(searchText); + const QStringList searchTextTerms = Note::buildQueryStringList(searchText); const QSettings settings; - const bool showMatches = - settings.value(QStringLiteral("showMatches"), true).toBool(); + const bool showMatches = settings.value(QStringLiteral("showMatches"), true).toBool(); while (*it) { QTreeWidgetItem *item = *it; @@ -5817,15 +5548,13 @@ void MainWindow::filterNotesBySearchLineEditText(bool searchInNote) { * @param searchText */ void MainWindow::doSearchInNote(QString searchText) { - const QStringList searchTextTerms = - Note::buildQueryStringList(searchText, true, true); + const QStringList searchTextTerms = Note::buildQueryStringList(searchText, true, true); if (searchTextTerms.count() > 1) { - QString localSearchTerm = QStringLiteral("(") + - searchTextTerms.join(QStringLiteral("|")) + - QStringLiteral(")"); - activeNoteTextEdit()->doSearch( - localSearchTerm, QPlainTextEditSearchWidget::RegularExpressionMode); + QString localSearchTerm = + QStringLiteral("(") + searchTextTerms.join(QStringLiteral("|")) + QStringLiteral(")"); + activeNoteTextEdit()->doSearch(localSearchTerm, + QPlainTextEditSearchWidget::RegularExpressionMode); } else { if (Note::isNameSearch(searchText)) { searchText = Note::removeNameSearchPrefix(searchText); @@ -5887,8 +5616,7 @@ void MainWindow::filterNotesByTag() { qDebug() << __func__ << " - 'tags': " << tagIds; - const auto selectedFolderItems = - ui->noteSubFolderTreeWidget->selectedItems(); + const auto selectedFolderItems = ui->noteSubFolderTreeWidget->selectedItems(); const bool showNotesFromAllNoteSubFolders = _showNotesFromAllNoteSubFolders; noteIdList.reserve(tagIdList.count() * 2); @@ -5899,15 +5627,13 @@ void MainWindow::filterNotesByTag() { const NoteSubFolder folder = NoteSubFolder::fetch(id); noteIdList << Tag::fetchAllLinkedNoteIdsForFolder( - tagId_, folder, - showNotesFromAllNoteSubFolders); + tagId_, folder, showNotesFromAllNoteSubFolders); } } } else { for (const int tagId_ : Utils::asConst(tagIdList)) { - noteIdList << Tag::fetchAllLinkedNoteIds( - tagId_, - showNotesFromAllNoteSubFolders); + noteIdList << Tag::fetchAllLinkedNoteIds(tagId_, + showNotesFromAllNoteSubFolders); } } break; @@ -5916,8 +5642,7 @@ void MainWindow::filterNotesByTag() { qDebug() << __func__ << " - 'noteIdList': " << noteIdList; // omit the already hidden notes - QTreeWidgetItemIterator it(ui->noteTreeWidget, - QTreeWidgetItemIterator::NotHidden); + QTreeWidgetItemIterator it(ui->noteTreeWidget, QTreeWidgetItemIterator::NotHidden); // loop through all visible notes while (*it) { @@ -5960,8 +5685,7 @@ void MainWindow::filterNotesByNoteSubFolders() { // check if the notes should be viewed recursively if (NoteSubFolder::isNoteSubfoldersPanelShowNotesRecursively()) { for (int subFolId : Utils::asConst(selectedNoteSubFolderIds)) { - noteSubFolderIds - << NoteSubFolder::fetchIdsRecursivelyByParentId(subFolId); + noteSubFolderIds << NoteSubFolder::fetchIdsRecursivelyByParentId(subFolId); } } else { noteSubFolderIds << selectedNoteSubFolderIds; @@ -5978,8 +5702,7 @@ void MainWindow::filterNotesByNoteSubFolders() { } // omit the already hidden notes - QTreeWidgetItemIterator it(ui->noteTreeWidget, - QTreeWidgetItemIterator::NotHidden); + QTreeWidgetItemIterator it(ui->noteTreeWidget, QTreeWidgetItemIterator::NotHidden); // loop through all visible notes while (*it) { @@ -6044,8 +5767,7 @@ void MainWindow::jumpToNoteOrCreateNew(bool disableLoadNoteDirectoryList) { // if we can't find a note we create a new one if (note.getId() == 0) { // check if a hook wants to set the text - QString noteText = - ScriptingService::instance()->callHandleNewNoteHeadlineHook(text); + QString noteText = ScriptingService::instance()->callHandleNewNoteHeadlineHook(text); // check if a hook changed the text if (noteText.isEmpty()) { @@ -6055,8 +5777,7 @@ void MainWindow::jumpToNoteOrCreateNew(bool disableLoadNoteDirectoryList) { noteText.append(QLatin1String("\n\n")); } - const NoteSubFolder noteSubFolder = - NoteSubFolder::activeNoteSubFolder(); + const NoteSubFolder noteSubFolder = NoteSubFolder::activeNoteSubFolder(); const QString noteSubFolderPath = noteSubFolder.fullPath(); note = Note(); @@ -6081,10 +5802,9 @@ void MainWindow::jumpToNoteOrCreateNew(bool disableLoadNoteDirectoryList) { } const bool noteWasStored = note.storeNoteTextFileToDisk(); - showStatusBarMessage( - noteWasStored ? tr("Stored current note to disk") - : tr("Current note could not be stored to disk"), - 3000); + showStatusBarMessage(noteWasStored ? tr("Stored current note to disk") + : tr("Current note could not be stored to disk"), + 3000); { const QSignalBlocker blocker2(ui->noteTreeWidget); @@ -6137,15 +5857,13 @@ void MainWindow::on_actionAbout_QOwnNotes_triggered() { */ void MainWindow::on_action_New_note_triggered() { QSettings settings; - const bool newNoteAskHeadline = - settings.value(QStringLiteral("newNoteAskHeadline")).toBool(); + const bool newNoteAskHeadline = settings.value(QStringLiteral("newNoteAskHeadline")).toBool(); // check if we want to ask for a headline if (newNoteAskHeadline) { bool ok; - QString headline = - QInputDialog::getText(this, tr("New note"), tr("Note headline"), - QLineEdit::Normal, QString(), &ok); + QString headline = QInputDialog::getText(this, tr("New note"), tr("Note headline"), + QLineEdit::Normal, QString(), &ok); if (!ok) { return; @@ -6183,9 +5901,9 @@ void MainWindow::createNewNote(QString noteName, bool withNameAppend) { QDateTime currentDate = QDateTime::currentDateTime(); // replacing ":" with "_" for Windows systems - noteName = noteName + QStringLiteral(" ") + - currentDate.toString(Qt::ISODate) - .replace(QStringLiteral(":"), QStringLiteral(".")); + noteName = + noteName + QStringLiteral(" ") + + currentDate.toString(Qt::ISODate).replace(QStringLiteral(":"), QStringLiteral(".")); } const QSignalBlocker blocker(ui->searchLineEdit); @@ -6213,9 +5931,7 @@ void MainWindow::onNotePreviewAnchorClicked(const QUrl &url) { /* * Handles note urls */ -void MainWindow::openLocalUrl(QString urlString) { - UrlHandler().openUrl(urlString); -} +void MainWindow::openLocalUrl(QString urlString) { UrlHandler().openUrl(urlString); } /* * Manually check for updates @@ -6258,8 +5974,7 @@ void MainWindow::on_actionAlphabetical_triggered(bool checked) { void MainWindow::on_actionBy_date_triggered(bool checked) { if (checked) { QSettings settings; - settings.setValue(QStringLiteral("notesPanelSort"), - SORT_BY_LAST_CHANGE); + settings.setValue(QStringLiteral("notesPanelSort"), SORT_BY_LAST_CHANGE); loadNoteDirectoryList(); } @@ -6267,8 +5982,7 @@ void MainWindow::on_actionBy_date_triggered(bool checked) { updateNoteSortOrderSelectorVisibility(!checked); } -void MainWindow::systemTrayIconClicked( - QSystemTrayIcon::ActivationReason reason) { +void MainWindow::systemTrayIconClicked(QSystemTrayIcon::ActivationReason reason) { // don't show or hide the app on OS X with a simple click because also the // context menu will be triggered #ifndef Q_OS_MAC @@ -6294,7 +6008,7 @@ void MainWindow::showWindow() { // bring application window to the front activateWindow(); // for Windows setWindowState((windowState() & ~Qt::WindowMinimized) | Qt::WindowActive); - raise(); // for MacOS + raise(); // for MacOS // parse the current note for the navigation panel in case it wasn't parsed // while the mainwindow was hidden (https://github.com/pbek/QOwnNotes/issues/2110) @@ -6367,13 +6081,11 @@ void MainWindow::generateSystemTrayContextMenu() { // add menu entry to create a new note QAction *createNoteAction = menu->addAction(tr("New note")); - createNoteAction->setIcon(QIcon::fromTheme( - QStringLiteral("document-new"), - QIcon( - QStringLiteral(":icons/breeze-qownnotes/16x16/document-new.svg")))); + createNoteAction->setIcon( + QIcon::fromTheme(QStringLiteral("document-new"), + QIcon(QStringLiteral(":icons/breeze-qownnotes/16x16/document-new.svg")))); - connect(createNoteAction, &QAction::triggered, this, - &MainWindow::on_action_New_note_triggered); + connect(createNoteAction, &QAction::triggered, this, &MainWindow::on_action_New_note_triggered); int maxNotes = Note::countAll(); @@ -6402,11 +6114,9 @@ void MainWindow::generateSystemTrayContextMenu() { QAction *taskAction = menu->addAction(tr("Show todo lists")); taskAction->setIcon(QIcon::fromTheme( QStringLiteral("view-calendar-tasks"), - QIcon(QStringLiteral( - ":icons/breeze-qownnotes/16x16/view-calendar-tasks.svg")))); + QIcon(QStringLiteral(":icons/breeze-qownnotes/16x16/view-calendar-tasks.svg")))); - connect(taskAction, &QAction::triggered, this, - [this]() { openTodoDialog(); }); + connect(taskAction, &QAction::triggered, this, [this]() { openTodoDialog(); }); QList<CalendarItem> taskList = CalendarItem::fetchAllForSystemTray(10); if (taskList.count() > 0) { @@ -6421,8 +6131,7 @@ void MainWindow::generateSystemTrayContextMenu() { QAction *action = taskMenu->addAction(task.getSummary()); action->setIcon(QIcon::fromTheme( QStringLiteral("view-task"), - QIcon(QStringLiteral( - ":icons/breeze-qownnotes/16x16/view-task.svg")))); + QIcon(QStringLiteral(":icons/breeze-qownnotes/16x16/view-task.svg")))); connect(action, &QAction::triggered, this, [this, task]() { openTodoDialog(task.getUid()); }); @@ -6435,10 +6144,8 @@ void MainWindow::generateSystemTrayContextMenu() { QAction *quitAction = menu->addAction(tr("Quit")); quitAction->setIcon(QIcon::fromTheme( QStringLiteral("application-exit"), - QIcon(QStringLiteral( - ":icons/breeze-qownnotes/16x16/application-exit.svg")))); - connect(quitAction, &QAction::triggered, this, - &MainWindow::on_action_Quit_triggered); + QIcon(QStringLiteral(":icons/breeze-qownnotes/16x16/application-exit.svg")))); + connect(quitAction, &QAction::triggered, this, &MainWindow::on_action_Quit_triggered); trayIcon->setContextMenu(menu); } @@ -6456,35 +6163,28 @@ void MainWindow::on_actionShow_versions_triggered() { ui->actionShow_versions->setDisabled(true); showStatusBarMessage( - Utils::Misc::replaceOwnCloudText( - tr("Note versions are currently loaded from your ownCloud " - "server")), + Utils::Misc::replaceOwnCloudText(tr("Note versions are currently loaded from your ownCloud " + "server")), 20000); OwnCloudService *ownCloud = OwnCloudService::instance(); - ownCloud->loadVersions( - this->currentNote.relativeNoteFilePath(QStringLiteral("/"))); + ownCloud->loadVersions(this->currentNote.relativeNoteFilePath(QStringLiteral("/"))); } -void MainWindow::enableShowVersionsButton() { - ui->actionShow_versions->setDisabled(false); -} +void MainWindow::enableShowVersionsButton() { ui->actionShow_versions->setDisabled(false); } void MainWindow::on_actionShow_trash_triggered() { ui->actionShow_trash->setDisabled(true); showStatusBarMessage( - Utils::Misc::replaceOwnCloudText( - tr("Trashed notes are currently loaded from your ownCloud" - " server")), + Utils::Misc::replaceOwnCloudText(tr("Trashed notes are currently loaded from your ownCloud" + " server")), 20000); OwnCloudService *ownCloud = OwnCloudService::instance(); ownCloud->loadTrash(); } -void MainWindow::enableShowTrashButton() { - ui->actionShow_trash->setDisabled(false); -} +void MainWindow::enableShowTrashButton() { ui->actionShow_trash->setDisabled(false); } void MainWindow::on_actionSelect_all_notes_triggered() { selectAllNotes(); } @@ -6498,23 +6198,19 @@ void MainWindow::on_actionInsert_note_link_triggered() { handleTextNoteLinking(LinkDialog::NoteLinkPage); } -void MainWindow::on_action_DuplicateText_triggered() { - activeNoteTextEdit()->duplicateText(); -} +void MainWindow::on_action_DuplicateText_triggered() { activeNoteTextEdit()->duplicateText(); } void MainWindow::on_action_Back_in_note_history_triggered() { if (this->noteHistory.back()) { ui->searchLineEdit->clear(); - setCurrentNoteFromHistoryItem( - this->noteHistory.getCurrentHistoryItem()); + setCurrentNoteFromHistoryItem(this->noteHistory.getCurrentHistoryItem()); } } void MainWindow::on_action_Forward_in_note_history_triggered() { if (this->noteHistory.forward()) { ui->searchLineEdit->clear(); - setCurrentNoteFromHistoryItem( - this->noteHistory.getCurrentHistoryItem()); + setCurrentNoteFromHistoryItem(this->noteHistory.getCurrentHistoryItem()); } } @@ -6536,8 +6232,7 @@ void MainWindow::on_actionInsert_current_time_triggered() { QTextCursor c = textEdit->textCursor(); const QDateTime dateTime = QDateTime::currentDateTime(); QSettings settings; - const QString format = - settings.value(QStringLiteral("insertTimeFormat")).toString(); + const QString format = settings.value(QStringLiteral("insertTimeFormat")).toString(); QLocale locale = QLocale::system(); QString text; @@ -6572,14 +6267,14 @@ void MainWindow::on_action_Export_note_as_PDF_text_triggered() { QTextDocument *MainWindow::getDocumentForPreviewExport() { bool decrypt = ui->noteTextEdit->isHidden(); - QString html = currentNote.toMarkdownHtml( - NoteFolder::currentLocalPath(), getMaxImageWidth(), - Utils::Misc::useInternalExportStylingForPreview(), decrypt); + QString html = + currentNote.toMarkdownHtml(NoteFolder::currentLocalPath(), getMaxImageWidth(), + Utils::Misc::useInternalExportStylingForPreview(), decrypt); html = Utils::Misc::parseTaskList(html, false); // Windows 10 has troubles with the QTextDocument from the QTextBrowser // see: https://github.com/pbek/QOwnNotes/issues/2015 -// auto doc = ui->noteTextView->document()->clone(); + // auto doc = ui->noteTextView->document()->clone(); auto doc = new QTextDocument(this); doc->setHtml(html); @@ -6641,8 +6336,8 @@ void MainWindow::on_actionInsert_image_triggered() { title = QStringLiteral("img"); } - insertNoteText(QStringLiteral("![") + title + QStringLiteral("](") + - pathOrUrl + QStringLiteral(")")); + insertNoteText(QStringLiteral("![") + title + QStringLiteral("](") + pathOrUrl + + QStringLiteral(")")); } else { QFile *file = dialog->getImageFile(); @@ -6659,8 +6354,7 @@ void MainWindow::on_actionInsert_image_triggered() { * Inserts a media file into the current note */ bool MainWindow::insertMedia(QFile *file, QString title) { - QString text = - currentNote.getInsertMediaMarkdown(file, true, false, std::move(title)); + QString text = currentNote.getInsertMediaMarkdown(file, true, false, std::move(title)); if (!text.isEmpty()) { ScriptingService *scriptingService = ScriptingService::instance(); @@ -6691,7 +6385,6 @@ void MainWindow::insertNoteText(const QString &text) { c.insertText(text); } - /** * Inserts text as a file attachment into the current note */ @@ -6701,13 +6394,11 @@ bool MainWindow::insertTextAsAttachment(const QString &text, const QString &titl } // create a temporary file for the attachment - auto *tempFile = - new QTemporaryFile(QDir::tempPath() + QDir::separator() + - QStringLiteral("text-XXXXXX.txt")); + auto *tempFile = new QTemporaryFile(QDir::tempPath() + QDir::separator() + + QStringLiteral("text-XXXXXX.txt")); if (!tempFile->open()) { - showStatusBarMessage(tr("Temporary file can't be opened"), - 3000); + showStatusBarMessage(tr("Temporary file can't be opened"), 3000); return false; } @@ -6776,8 +6467,7 @@ bool MainWindow::insertAttachment(QFile *file, const QString &title) { * @brief Opens a browser with the changelog page */ void MainWindow::on_actionShow_changelog_triggered() { - QDesktopServices::openUrl( - QUrl(QStringLiteral("https://www.qownnotes.org/changelog.html"))); + QDesktopServices::openUrl(QUrl(QStringLiteral("https://www.qownnotes.org/changelog.html"))); } void MainWindow::on_action_Find_text_in_note_triggered() { @@ -6797,15 +6487,14 @@ void MainWindow::on_action_Encrypt_note_triggered() { } // the password dialog can be disabled by scripts - const bool dialogDisabled = - qApp->property("encryptionPasswordDisabled").toBool(); + const bool dialogDisabled = qApp->property("encryptionPasswordDisabled").toBool(); if (!dialogDisabled) { - const QString labelText = tr( - "Please enter your <strong>password</strong> to encrypt the note." - "<br />Keep in mind that you have to <strong>remember</strong> " - "your password to read the content of the note<br /> and that you " - "can <strong>only</strong> do that <strong>in QOwnNotes</strong>!"); + const QString labelText = + tr("Please enter your <strong>password</strong> to encrypt the note." + "<br />Keep in mind that you have to <strong>remember</strong> " + "your password to read the content of the note<br /> and that you " + "can <strong>only</strong> do that <strong>in QOwnNotes</strong>!"); auto *dialog = new PasswordDialog(this, labelText, true); const int dialogResult = dialog->exec(); @@ -6873,13 +6562,12 @@ void MainWindow::on_actionDecrypt_note_triggered() { return; } - if (QMessageBox::warning( - this, tr("Decrypt note and store it as plain text"), - tr("Your note will be decrypted and stored as plain text again. " - "Keep in mind that the unencrypted note will possibly be " - "synced to your server and sensitive text may be exposed!" - "<br />Do you want to decrypt your note?"), - tr("&Decrypt"), tr("&Cancel"), QString(), 0, 1) == 1) { + if (QMessageBox::warning(this, tr("Decrypt note and store it as plain text"), + tr("Your note will be decrypted and stored as plain text again. " + "Keep in mind that the unencrypted note will possibly be " + "synced to your server and sensitive text may be exposed!" + "<br />Do you want to decrypt your note?"), + tr("&Decrypt"), tr("&Cancel"), QString(), 0, 1) == 1) { return; } @@ -6903,8 +6591,7 @@ void MainWindow::on_actionEdit_encrypted_note_triggered() { return; } - askForEncryptedNotePasswordIfNeeded( - tr("<br />You will be able to edit your encrypted note.")); + askForEncryptedNotePasswordIfNeeded(tr("<br />You will be able to edit your encrypted note.")); if (currentNote.canDecryptNoteText()) { const QSignalBlocker blocker(ui->encryptedNoteTextEdit); @@ -6955,13 +6642,11 @@ void MainWindow::on_action_Open_note_in_external_editor_triggered() { } else { const QString path = currentNote.fullNoteFilePath(); - qDebug() << __func__ - << " - 'externalEditorPath': " << externalEditorPath; + qDebug() << __func__ << " - 'externalEditorPath': " << externalEditorPath; qDebug() << __func__ << " - 'path': " << path; // open note file in external editor - Utils::Misc::openFilesWithApplication(externalEditorPath, - QStringList({path})); + Utils::Misc::openFilesWithApplication(externalEditorPath, QStringList({path})); } } @@ -6985,12 +6670,13 @@ void MainWindow::on_action_Export_note_as_markdown_triggered() { fileName.append(QStringLiteral(".md")); } - bool withAttachedFiles = (currentNote.hasMediaFiles() || currentNote.hasAttachments()) && - Utils::Gui::question(this, tr("Export attached files"), - tr("Do you also want to export media files and attachments of " - "the note? Files may be overwritten in the destination folder!"), - QStringLiteral("note-export-attachments")) == - QMessageBox::Yes; + bool withAttachedFiles = + (currentNote.hasMediaFiles() || currentNote.hasAttachments()) && + Utils::Gui::question( + this, tr("Export attached files"), + tr("Do you also want to export media files and attachments of " + "the note? Files may be overwritten in the destination folder!"), + QStringLiteral("note-export-attachments")) == QMessageBox::Yes; currentNote.exportToPath(fileName, withAttachedFiles); } @@ -6999,13 +6685,11 @@ void MainWindow::on_action_Export_note_as_markdown_triggered() { void MainWindow::showEvent(QShowEvent *event) { QMainWindow::showEvent(event); - MetricsService::instance()->sendVisitIfEnabled(QStringLiteral("dialog/") + - objectName()); + MetricsService::instance()->sendVisitIfEnabled(QStringLiteral("dialog/") + objectName()); } void MainWindow::on_actionGet_invloved_triggered() { - QDesktopServices::openUrl( - QUrl("https://www.qownnotes.org/contributing/get-involved.html")); + QDesktopServices::openUrl(QUrl("https://www.qownnotes.org/contributing/get-involved.html")); } /** @@ -7020,9 +6704,8 @@ void MainWindow::storeNoteBookmark(int slot) { NoteHistoryItem item = NoteHistoryItem(¤tNote, ui->noteTextEdit); noteBookmarks[slot] = item; - showStatusBarMessage( - tr("Bookmarked note position at slot %1").arg(QString::number(slot)), - 3000); + showStatusBarMessage(tr("Bookmarked note position at slot %1").arg(QString::number(slot)), + 3000); } /** @@ -7036,18 +6719,15 @@ void MainWindow::gotoNoteBookmark(int slot) { ui->noteTextEdit->setFocus(); setCurrentNoteFromHistoryItem(item); - showStatusBarMessage(tr("Jumped to bookmark position at slot %1") - .arg(QString::number(slot)), - 3000); + showStatusBarMessage( + tr("Jumped to bookmark position at slot %1").arg(QString::number(slot)), 3000); } } /** * Inserts a code block at the current cursor position */ -void MainWindow::on_actionInsert_code_block_triggered() { - activeNoteTextEdit()->insertCodeBlock(); -} +void MainWindow::on_actionInsert_code_block_triggered() { activeNoteTextEdit()->insertCodeBlock(); } void MainWindow::on_actionNext_note_triggered() { gotoNextNote(); } @@ -7077,9 +6757,7 @@ void MainWindow::gotoPreviousNote() { QApplication::postEvent(ui->noteTreeWidget, event); } -void MainWindow::on_actionToggle_distraction_free_mode_triggered() { - toggleDistractionFreeMode(); -} +void MainWindow::on_actionToggle_distraction_free_mode_triggered() { toggleDistractionFreeMode(); } /** * Tracks an action @@ -7157,25 +6835,22 @@ void MainWindow::dragEnterEvent(QDragEnterEvent *e) { /** * Handles the copying of notes to the current notes folder */ -void MainWindow::dropEvent(QDropEvent *e) { - handleInsertingFromMimeData(e->mimeData()); -} +void MainWindow::dropEvent(QDropEvent *e) { handleInsertingFromMimeData(e->mimeData()); } /** * Handles the inserting of media files and notes from a mime data, for example * produced by a drop event or a paste action */ void MainWindow::handleInsertingFromMimeData(const QMimeData *mimeData) { -// qDebug() << __func__ << " - 'mimeData->hasText()': " << mimeData->hasText(); -// qDebug() << __func__ << " - 'mimeData->hasHtml()': " << mimeData->hasHtml(); -// qDebug() << __func__ << " - 'mimeData->hasImage()': " << mimeData->hasImage(); -// qDebug() << __func__ << " - 'mimeData->hasUrls()': " << mimeData->hasUrls(); + // qDebug() << __func__ << " - 'mimeData->hasText()': " << mimeData->hasText(); + // qDebug() << __func__ << " - 'mimeData->hasHtml()': " << mimeData->hasHtml(); + // qDebug() << __func__ << " - 'mimeData->hasImage()': " << mimeData->hasImage(); + // qDebug() << __func__ << " - 'mimeData->hasUrls()': " << mimeData->hasUrls(); // check if a QML wants to set the inserted text if (mimeData->hasText() || mimeData->hasHtml()) { ScriptingService *scriptingService = ScriptingService::instance(); - QString text = - scriptingService->callInsertingFromMimeDataHook(mimeData); + QString text = scriptingService->callInsertingFromMimeDataHook(mimeData); if (!text.isEmpty()) { QOwnNotesMarkdownTextEdit *textEdit = activeNoteTextEdit(); @@ -7204,14 +6879,12 @@ void MainWindow::handleInsertingFromMimeData(const QMimeData *mimeData) { // only allow markdown and text files to be copied as note if (isValidNoteFile(file)) { - const NoteSubFolder noteSubFolder = - NoteSubFolder::activeNoteSubFolder(); + const NoteSubFolder noteSubFolder = NoteSubFolder::activeNoteSubFolder(); const QString noteSubFolderPath = noteSubFolder.fullPath(); // copy file to notes path const bool success = - file->copy(noteSubFolderPath + QDir::separator() + - fileInfo.fileName()); + file->copy(noteSubFolderPath + QDir::separator() + fileInfo.fileName()); if (success) { successCount++; @@ -7243,8 +6916,7 @@ void MainWindow::handleInsertingFromMimeData(const QMimeData *mimeData) { QString message; if (successCount > 0) { - message += - tr("Copied %n note(s) to %1", "", successCount).arg(notesPath); + message += tr("Copied %n note(s) to %1", "", successCount).arg(notesPath); on_action_Reload_note_folder_triggered(); } @@ -7254,8 +6926,7 @@ void MainWindow::handleInsertingFromMimeData(const QMimeData *mimeData) { } message += - tr("Failed to copy %n note(s) (most likely already existing)", - "", failureCount); + tr("Failed to copy %n note(s) (most likely already existing)", "", failureCount); } if (skipCount > 0) { @@ -7279,9 +6950,8 @@ void MainWindow::handleInsertingFromMimeData(const QMimeData *mimeData) { if (!image.isNull()) { showStatusBarMessage(tr("Saving temporary image"), 0); - QTemporaryFile tempFile( - QDir::tempPath() + QDir::separator() + - QStringLiteral("qownnotes-media-XXXXXX.png")); + QTemporaryFile tempFile(QDir::tempPath() + QDir::separator() + + QStringLiteral("qownnotes-media-XXXXXX.png")); if (tempFile.open()) { // save temporary png image @@ -7296,8 +6966,7 @@ void MainWindow::handleInsertingFromMimeData(const QMimeData *mimeData) { showStatusBarMessage(tr("Done inserting image"), 3000); } else { - showStatusBarMessage(tr("Temporary file can't be opened"), - 3000); + showStatusBarMessage(tr("Temporary file can't be opened"), 3000); } } } else if (mimeData->hasText() || mimeData->hasHtml()) { @@ -7330,7 +6999,7 @@ void MainWindow::insertHtmlAsMarkdownIntoCurrentNote(QString html) { // match image tags static const QRegularExpression re(QStringLiteral("<img.+?src=[\"'](.+?)[\"'].*?>"), - QRegularExpression::CaseInsensitiveOption); + QRegularExpression::CaseInsensitiveOption); QRegularExpressionMatchIterator i = re.globalMatch(html); // find, download locally and replace all images @@ -7382,8 +7051,7 @@ void MainWindow::resetBrokenTagNotesLinkFlag() { if (_brokenTagNoteLinksRemoved) _brokenTagNoteLinksRemoved = false; } -QString MainWindow::getWorkspaceUuid(const QString &workspaceName) -{ +QString MainWindow::getWorkspaceUuid(const QString &workspaceName) { return _workspaceNameUuidMap.value(workspaceName, ""); } @@ -7467,16 +7135,14 @@ void MainWindow::applyFormatter(const QString &formatter) { if (selectedText.isEmpty()) { c.insertText(formatter.repeated(2)); - c.movePosition(QTextCursor::Left, QTextCursor::MoveAnchor, - formatter.length()); + c.movePosition(QTextCursor::Left, QTextCursor::MoveAnchor, formatter.length()); textEdit->setTextCursor(c); } else { QRegularExpressionMatch match = - QRegularExpression(QStringLiteral(R"(^(\s*)(.+?)(\s*)$)")) - .match(selectedText); + QRegularExpression(QStringLiteral(R"(^(\s*)(.+?)(\s*)$)")).match(selectedText); if (match.hasMatch()) { - c.insertText(match.captured(1) + formatter + match.captured(2) + - formatter + match.captured(3)); + c.insertText(match.captured(1) + formatter + match.captured(2) + formatter + + match.captured(3)); } } } @@ -7484,9 +7150,7 @@ void MainWindow::applyFormatter(const QString &formatter) { /** * Inserts a bold block at the current cursor position */ -void MainWindow::on_actionFormat_text_bold_triggered() { - applyFormatter(QStringLiteral("**")); -} +void MainWindow::on_actionFormat_text_bold_triggered() { applyFormatter(QStringLiteral("**")); } /** * Inserts a underline block at the current cursor position @@ -7498,9 +7162,7 @@ void MainWindow::on_actionFormat_text_underline_triggered() { /** * Inserts an italic block at the current cursor position */ -void MainWindow::on_actionFormat_text_italic_triggered() { - applyFormatter(QStringLiteral("*")); -} +void MainWindow::on_actionFormat_text_italic_triggered() { applyFormatter(QStringLiteral("*")); } /** * Increases the note text font size by one @@ -7520,8 +7182,7 @@ void MainWindow::on_action_Decrease_note_text_size_triggered() { * Resets the note text font size */ void MainWindow::on_action_Reset_note_text_size_triggered() { - const int fontSize = - ui->noteTextEdit->modifyFontSize(QOwnNotesMarkdownTextEdit::Reset); + const int fontSize = ui->noteTextEdit->modifyFontSize(QOwnNotesMarkdownTextEdit::Reset); ui->encryptedNoteTextEdit->setStyles(); showStatusBarMessage(tr("Reset font size to %1 pt", "Will be shown after " @@ -7544,8 +7205,7 @@ void MainWindow::on_noteFolderComboBox_currentIndexChanged(int index) { // hide the noteSubFolderDockWidget menu entry if subfolders are // not enabled - QAction *action = - findAction(QStringLiteral("togglePanel-noteSubFolderDockWidget")); + QAction *action = findAction(QStringLiteral("togglePanel-noteSubFolderDockWidget")); if (action != nullptr) { action->setVisible(NoteFolder::isCurrentShowSubfolders()); @@ -7597,8 +7257,7 @@ void MainWindow::reloadTagTree() { if (NoteSubFolder::isNoteSubfoldersPanelShowNotesRecursively()) { for (QTreeWidgetItem *i : noteSubFolderWidgetItems) { const int id = i->data(0, Qt::UserRole).toInt(); - noteSubFolderIds - << NoteSubFolder::fetchIdsRecursivelyByParentId(id); + noteSubFolderIds << NoteSubFolder::fetchIdsRecursivelyByParentId(id); } } else { for (QTreeWidgetItem *i : noteSubFolderWidgetItems) { @@ -7624,9 +7283,9 @@ void MainWindow::reloadTagTree() { } // create an item to view all notes - int linkCount = - _showNotesFromAllNoteSubFolders || !NoteFolder::isCurrentShowSubfolders() ? - Note::countAll() : noteIdList.count(); + int linkCount = _showNotesFromAllNoteSubFolders || !NoteFolder::isCurrentShowSubfolders() + ? Note::countAll() + : noteIdList.count(); QString toolTip = tr("Show all notes (%1)").arg(QString::number(linkCount)); auto *allItem = new QTreeWidgetItem(); @@ -7638,30 +7297,24 @@ void MainWindow::reloadTagTree() { allItem->setData(0, Qt::UserRole, Tag::AllNotesId); allItem->setFlags(allItem->flags() & ~Qt::ItemIsSelectable); allItem->setIcon( - 0, - QIcon::fromTheme(QStringLiteral("edit-copy"), - QIcon(QStringLiteral( - ":icons/breeze-qownnotes/16x16/edit-copy.svg")))); + 0, QIcon::fromTheme(QStringLiteral("edit-copy"), + QIcon(QStringLiteral(":icons/breeze-qownnotes/16x16/edit-copy.svg")))); // this time, the tags come first buildTagTreeForParentItem(); // and get sorted - if (settings.value(QStringLiteral("tagsPanelSort")).toInt() == - SORT_ALPHABETICAL) { + if (settings.value(QStringLiteral("tagsPanelSort")).toInt() == SORT_ALPHABETICAL) { ui->tagTreeWidget->sortItems( - 0, Utils::Gui::toQtOrder( - settings.value(QStringLiteral("tagsPanelOrder")).toInt())); + 0, Utils::Gui::toQtOrder(settings.value(QStringLiteral("tagsPanelOrder")).toInt())); } // now add 'All notes' to the top ui->tagTreeWidget->insertTopLevelItem(0, allItem); // add an item to view untagged notes if there are any - linkCount = _showNotesFromAllNoteSubFolders ? Note::countAllNotTagged() - : untaggedNoteCount; + linkCount = _showNotesFromAllNoteSubFolders ? Note::countAllNotTagged() : untaggedNoteCount; if (linkCount > 0) { - toolTip = - tr("show all untagged notes (%1)").arg(QString::number(linkCount)); + toolTip = tr("show all untagged notes (%1)").arg(QString::number(linkCount)); auto *untaggedItem = new QTreeWidgetItem(); untaggedItem->setText(0, tr("Untagged notes")); untaggedItem->setForeground(1, QColor(Qt::gray)); @@ -7671,18 +7324,16 @@ void MainWindow::reloadTagTree() { untaggedItem->setData(0, Qt::UserRole, Tag::AllUntaggedNotesId); untaggedItem->setFlags(untaggedItem->flags() & ~Qt::ItemIsSelectable); untaggedItem->setIcon( - 0, QIcon::fromTheme( - QStringLiteral("edit-copy"), - QIcon(QStringLiteral( - ":icons/breeze-qownnotes/16x16/edit-copy.svg")))); + 0, + QIcon::fromTheme(QStringLiteral("edit-copy"), + QIcon(QStringLiteral(":icons/breeze-qownnotes/16x16/edit-copy.svg")))); ui->tagTreeWidget->addTopLevelItem(untaggedItem); } // decorate root if there are multiple levels to be able to collapse them, // because double clicking will not collapse the first level, but edit // the clicked tag - ui->tagTreeWidget->setRootIsDecorated(Tag::countAllParentId(0) != - Tag::countAll()); + ui->tagTreeWidget->setRootIsDecorated(Tag::countAllParentId(0) != Tag::countAll()); highlightCurrentNoteTagsInTagTree(); } @@ -7698,11 +7349,9 @@ void MainWindow::reloadNoteSubFolderTree() { /** * Populates the tag tree recursively with its tags */ -void MainWindow::buildTagTreeForParentItem(QTreeWidgetItem *parent, - bool topLevel) { - const int parentId = (parent == nullptr || topLevel) - ? 0 - : parent->data(0, Qt::UserRole).toInt(); +void MainWindow::buildTagTreeForParentItem(QTreeWidgetItem *parent, bool topLevel) { + const int parentId = + (parent == nullptr || topLevel) ? 0 : parent->data(0, Qt::UserRole).toInt(); const int activeTagId = Tag::activeTagId(); QSettings settings; const QStringList expandedList = @@ -7744,23 +7393,21 @@ void MainWindow::buildTagTreeForParentItem(QTreeWidgetItem *parent, /** * Ads a tag to the tag tree widget */ -QTreeWidgetItem *MainWindow::addTagToTagTreeWidget(QTreeWidgetItem *parent, - const TagHeader &tag) { - const int parentId = - parent == nullptr ? 0 : parent->data(0, Qt::UserRole).toInt(); +QTreeWidgetItem *MainWindow::addTagToTagTreeWidget(QTreeWidgetItem *parent, const TagHeader &tag) { + const int parentId = parent == nullptr ? 0 : parent->data(0, Qt::UserRole).toInt(); const int tagId = tag._id; const QString name = tag._name; auto hideCount = QSettings().value("tagsPanelHideNoteCount", false).toBool(); int count = 0; if (!hideCount) { - const QVector<int> tagIdListToCount = Tag::isTaggingShowNotesRecursively() ? - Tag::fetchTagIdsRecursivelyByParentId(tagId) : QVector<int>{tag._id}; - const auto selectedSubFolderItems = - ui->noteSubFolderTreeWidget->selectedItems(); + const QVector<int> tagIdListToCount = Tag::isTaggingShowNotesRecursively() + ? Tag::fetchTagIdsRecursivelyByParentId(tagId) + : QVector<int>{tag._id}; + const auto selectedSubFolderItems = ui->noteSubFolderTreeWidget->selectedItems(); const bool showNotesFromAllSubFolders = this->_showNotesFromAllNoteSubFolders; const bool isShowNotesRecursively = - NoteSubFolder::isNoteSubfoldersPanelShowNotesRecursively(); + NoteSubFolder::isNoteSubfoldersPanelShowNotesRecursively(); if (selectedSubFolderItems.count() > 1) { for (const int tagIdToCount : tagIdListToCount) { @@ -7773,23 +7420,20 @@ QTreeWidgetItem *MainWindow::addTagToTagTreeWidget(QTreeWidgetItem *parent, } count = Tag::countLinkedNoteFileNamesForNoteSubFolder( - tagIdToCount, folder, - showNotesFromAllSubFolders, isShowNotesRecursively); + tagIdToCount, folder, showNotesFromAllSubFolders, isShowNotesRecursively); } } } else { for (const int tagToCount : tagIdListToCount) { - count = Tag::countLinkedNoteFileNames( - tagToCount, - showNotesFromAllSubFolders, - isShowNotesRecursively); + count = Tag::countLinkedNoteFileNames(tagToCount, showNotesFromAllSubFolders, + isShowNotesRecursively); } } } const int linkCount = count; - const QString toolTip = tr("Show all notes tagged with '%1' (%2)") - .arg(name, QString::number(linkCount)); + const QString toolTip = + tr("Show all notes tagged with '%1' (%2)").arg(name, QString::number(linkCount)); auto *item = new QTreeWidgetItem(); item->setData(0, Qt::UserRole, tagId); item->setText(0, name); @@ -7844,8 +7488,8 @@ void MainWindow::on_tagLineEdit_returnPressed() { * Filters tags in the tag tree widget */ void MainWindow::on_tagLineEdit_textChanged(const QString &arg1) { - Utils::Gui::searchForTextInTreeWidget( - ui->tagTreeWidget, arg1, Utils::Gui::TreeWidgetSearchFlag::IntCheck); + Utils::Gui::searchForTextInTreeWidget(ui->tagTreeWidget, arg1, + Utils::Gui::TreeWidgetSearchFlag::IntCheck); } /** @@ -7926,8 +7570,7 @@ void MainWindow::on_newNoteTagLineEdit_returnPressed() { * * @param tagName */ -void MainWindow::linkTagNameToCurrentNote(const QString &tagName, - bool linkToSelectedNotes) { +void MainWindow::linkTagNameToCurrentNote(const QString &tagName, bool linkToSelectedNotes) { if (tagName.isEmpty()) { return; } @@ -7984,26 +7627,25 @@ void MainWindow::linkTagNameToCurrentNote(const QString &tagName, directoryWatcherWorkaround(false, true); } -void MainWindow::changeEvent(QEvent *event) -{ +void MainWindow::changeEvent(QEvent *event) { if (event->type() == QEvent::WindowStateChange) { QString windowStateString; - switch(windowState()) { - case Qt::WindowMinimized: - windowStateString = "minimized"; - break; - case Qt::WindowMaximized: - windowStateString = "maximized"; - break; - case Qt::WindowFullScreen: - windowStateString = "fullscreen"; - break; - case Qt::WindowActive: - windowStateString = "active"; - break; - default: - windowStateString = "nostate"; - break; + switch (windowState()) { + case Qt::WindowMinimized: + windowStateString = "minimized"; + break; + case Qt::WindowMaximized: + windowStateString = "maximized"; + break; + case Qt::WindowFullScreen: + windowStateString = "fullscreen"; + break; + case Qt::WindowActive: + windowStateString = "active"; + break; + default: + windowStateString = "nostate"; + break; } ScriptingService::instance()->callWindowStateChangeHook(windowStateString); @@ -8020,24 +7662,17 @@ void MainWindow::changeEvent(QEvent *event) * @param doRemove * @param triggerPostMethods */ -void MainWindow::handleScriptingNoteTagging(Note note, const Tag &tag, - bool doRemove, +void MainWindow::handleScriptingNoteTagging(Note note, const Tag &tag, bool doRemove, bool triggerPostMethods) { const QString oldNoteText = note.getNoteText(); - const QString &action = - doRemove ? QStringLiteral("remove") : QStringLiteral("add"); + const QString &action = doRemove ? QStringLiteral("remove") : QStringLiteral("add"); QString noteText = - ScriptingService::instance() - ->callNoteTaggingHook( - note, action, - tag.getName()) - .toString(); + ScriptingService::instance()->callNoteTaggingHook(note, action, tag.getName()).toString(); // try noteTaggingByObjectHook if noteTaggingHook didn't do anything if (noteText.isEmpty()) { noteText = - ScriptingService::instance() - ->callNoteTaggingByObjectHook(note, action, tag).toString(); + ScriptingService::instance()->callNoteTaggingByObjectHook(note, action, tag).toString(); if (noteText.isEmpty() || (oldNoteText == noteText)) { return; @@ -8083,17 +7718,17 @@ void MainWindow::handleScriptingNotesTagUpdating() { const QVector<Note> ¬es = Note::fetchAll(); for (const Note ¬e : notes) { QSet<int> tagIdList; - const QStringList tagNameList = - ScriptingService::instance() - ->callNoteTaggingHook(note, QStringLiteral("list")) - .toStringList(); + const QStringList tagNameList = ScriptingService::instance() + ->callNoteTaggingHook(note, QStringLiteral("list")) + .toStringList(); if (tagNameList.count() == 0) { // if callNoteTaggingHook didn't return anything lets try // callNoteTaggingByObjectHook - const auto variantTagIdList = ScriptingService::instance() - ->callNoteTaggingByObjectHook(note, QStringLiteral("list")) - .toList(); + const auto variantTagIdList = + ScriptingService::instance() + ->callNoteTaggingByObjectHook(note, QStringLiteral("list")) + .toList(); // get a tagId list from the variant list for (const QVariant &tagId : variantTagIdList) { @@ -8147,8 +7782,7 @@ void MainWindow::handleScriptingNotesTagUpdating() { * @param oldTagName * @param newTagName */ -void MainWindow::handleScriptingNotesTagRenaming(const Tag &tag, - const QString &newTagName) { +void MainWindow::handleScriptingNotesTagRenaming(const Tag &tag, const QString &newTagName) { if (!ScriptingService::instance()->noteTaggingHookExists()) { return; } @@ -8166,8 +7800,7 @@ void MainWindow::handleScriptingNotesTagRenaming(const Tag &tag, const QString oldNoteText = note.getNoteText(); QString noteText = ScriptingService::instance() - ->callNoteTaggingHook(note, QStringLiteral("rename"), - tag.getName(), newTagName) + ->callNoteTaggingHook(note, QStringLiteral("rename"), tag.getName(), newTagName) .toString(); // if nothing came back from callNoteTaggingHook let's try @@ -8175,8 +7808,7 @@ void MainWindow::handleScriptingNotesTagRenaming(const Tag &tag, if (noteText.isEmpty()) { noteText = ScriptingService::instance() - ->callNoteTaggingByObjectHook( - note, QStringLiteral("rename"), tag, newTagName) + ->callNoteTaggingByObjectHook(note, QStringLiteral("rename"), tag, newTagName) .toString(); if (noteText.isEmpty() || (oldNoteText == noteText)) { @@ -8204,8 +7836,7 @@ void MainWindow::handleScriptingNotesTagRenaming(const Tag &tag, * * @param tagName */ -void MainWindow::handleScriptingNotesTagRemoving(const Tag &tag, - bool forBulkOperation) { +void MainWindow::handleScriptingNotesTagRemoving(const Tag &tag, bool forBulkOperation) { if (!ScriptingService::instance()->noteTaggingHookExists()) { return; } @@ -8254,9 +7885,8 @@ void MainWindow::reloadCurrentNoteTags() { int selectedNotesCount = getSelectedNotesCount(); bool currentNoteOnly = selectedNotesCount <= 1; ui->selectedTagsToolButton->setVisible(!currentNoteOnly); - ui->newNoteTagButton->setToolTip( - currentNoteOnly ? tr("Add a tag to the current note") - : tr("Add a tag to the selected notes")); + ui->newNoteTagButton->setToolTip(currentNoteOnly ? tr("Add a tag to the current note") + : tr("Add a tag to the selected notes")); QVector<Tag> tagList; ui->multiSelectActionFrame->setVisible(!currentNoteOnly); @@ -8274,18 +7904,15 @@ void MainWindow::reloadCurrentNoteTags() { } else { const QVector<Note> notes = selectedNotes(); tagList = Tag::fetchAllOfNotes(notes); - const QString notesSelectedText = - tr("%n notes selected", "", selectedNotesCount); + const QString notesSelectedText = tr("%n notes selected", "", selectedNotesCount); - ui->selectedTagsToolButton->setText( - QString::number(selectedNotesCount)); + ui->selectedTagsToolButton->setText(QString::number(selectedNotesCount)); ui->selectedTagsToolButton->setToolTip(notesSelectedText); ui->notesSelectedLabel->setText(notesSelectedText); // overwrite the note preview with a preview of the selected notes - const QString previewHtml = - Note::generateMultipleNotesPreviewText(notes); + const QString previewHtml = Note::generateMultipleNotesPreviewText(notes); #ifdef USE_QLITEHTML _notePreviewWidget->setHtml(previewHtml); #else @@ -8297,22 +7924,17 @@ void MainWindow::reloadCurrentNoteTags() { // add all new remove-tag buttons for (const Tag &tag : Utils::asConst(tagList)) { - QPushButton *button = new QPushButton( - Utils::Misc::shorten(tag.getName(), 25), ui->noteTagButtonFrame); + QPushButton *button = + new QPushButton(Utils::Misc::shorten(tag.getName(), 25), ui->noteTagButtonFrame); button->setIcon(QIcon::fromTheme( QStringLiteral("tag-delete"), - QIcon(QStringLiteral( - ":icons/breeze-qownnotes/16x16/xml-attribute-delete.svg")))); - button->setToolTip( - currentNoteOnly - ? tr("Remove tag '%1' from the current note").arg(tag.getName()) - : tr("Remove tag '%1' from the selected notes") - .arg(tag.getName())); - button->setObjectName(QStringLiteral("removeNoteTag") + - QString::number(tag.getId())); + QIcon(QStringLiteral(":icons/breeze-qownnotes/16x16/xml-attribute-delete.svg")))); + button->setToolTip(currentNoteOnly + ? tr("Remove tag '%1' from the current note").arg(tag.getName()) + : tr("Remove tag '%1' from the selected notes").arg(tag.getName())); + button->setObjectName(QStringLiteral("removeNoteTag") + QString::number(tag.getId())); - QObject::connect(button, &QPushButton::clicked, this, - &MainWindow::removeNoteTagClicked); + QObject::connect(button, &QPushButton::clicked, this, &MainWindow::removeNoteTagClicked); ui->noteTagButtonFrame->layout()->addWidget(button); } @@ -8324,8 +7946,7 @@ void MainWindow::reloadCurrentNoteTags() { // } // add a spacer to prevent the button items to take the full width - auto *spacer = new QSpacerItem(0, 20, QSizePolicy::MinimumExpanding, - QSizePolicy::Ignored); + auto *spacer = new QSpacerItem(0, 20, QSizePolicy::MinimumExpanding, QSizePolicy::Ignored); ui->noteTagButtonFrame->layout()->addItem(spacer); highlightCurrentNoteTagsInTagTree(); @@ -8352,8 +7973,8 @@ void MainWindow::highlightCurrentNoteTagsInTagTree() { Utils::Gui::resetBoldStateOfAllTreeWidgetItems(ui->tagTreeWidget); for (const Tag &tag : Utils::asConst(tagList)) { - QTreeWidgetItem *item = Utils::Gui::getTreeWidgetItemWithUserData( - ui->tagTreeWidget, tag.getId()); + QTreeWidgetItem *item = + Utils::Gui::getTreeWidgetItemWithUserData(ui->tagTreeWidget, tag.getId()); if (item != nullptr) { // set tag item in tag tree widget to bold if note has tag @@ -8372,8 +7993,7 @@ void MainWindow::highlightCurrentNoteTagsInTagTree() { void MainWindow::removeNoteTagClicked() { QString objectName = sender()->objectName(); if (objectName.startsWith(QLatin1String("removeNoteTag"))) { - const int tagId = - objectName.remove(QLatin1String("removeNoteTag")).toInt(); + const int tagId = objectName.remove(QLatin1String("removeNoteTag")).toInt(); const Tag tag = Tag::fetch(tagId); if (!tag.isFetched()) { return; @@ -8423,9 +8043,7 @@ int MainWindow::getSelectedNotesCount() const { /** * Allows the user to add a tag to the current note */ -void MainWindow::on_action_new_tag_triggered() { - on_newNoteTagButton_clicked(); -} +void MainWindow::on_action_new_tag_triggered() { on_newNoteTagButton_clicked(); } /** * Reloads the current note folder @@ -8440,8 +8058,7 @@ void MainWindow::on_action_Reload_note_folder_triggered() { /** * Stores the tag after it was edited */ -void MainWindow::on_tagTreeWidget_itemChanged(QTreeWidgetItem *item, - int column) { +void MainWindow::on_tagTreeWidget_itemChanged(QTreeWidgetItem *item, int column) { Q_UNUSED(column) Tag tag = Tag::fetch(item->data(0, Qt::UserRole).toInt()); @@ -8476,8 +8093,8 @@ void MainWindow::on_tagTreeWidget_itemChanged(QTreeWidgetItem *item, /** * Sets a new active tag */ -void MainWindow::on_tagTreeWidget_currentItemChanged( - QTreeWidgetItem *current, QTreeWidgetItem *previous) { +void MainWindow::on_tagTreeWidget_currentItemChanged(QTreeWidgetItem *current, + QTreeWidgetItem *previous) { Q_UNUSED(previous) if (current == nullptr) { @@ -8505,8 +8122,7 @@ void MainWindow::on_tagTreeWidget_currentItemChanged( * @return */ bool MainWindow::jumpToTag(int tagId) { - QTreeWidgetItem *item = Utils::Gui::getTreeWidgetItemWithUserData( - ui->tagTreeWidget, tagId); + QTreeWidgetItem *item = Utils::Gui::getTreeWidgetItemWithUserData(ui->tagTreeWidget, tagId); if (item != nullptr) { // If the selection isn't cleared then the old subfolder is still selected too @@ -8750,8 +8366,7 @@ void MainWindow::disableColorOfTagItem(QTreeWidgetItem *item) { * Populates a tag menu tree for moving tags */ void MainWindow::buildTagMoveMenuTree(QMenu *parentMenu, int parentTagId) { - const auto tagList = - Tag::fetchAllByParentId(parentTagId, QStringLiteral("t.name ASC")); + const auto tagList = Tag::fetchAllByParentId(parentTagId, QStringLiteral("t.name ASC")); for (const Tag &tag : tagList) { const int tagId = tag.getId(); @@ -8775,8 +8390,7 @@ void MainWindow::buildTagMoveMenuTree(QMenu *parentMenu, int parentTagId) { parentMenu->addSeparator(); QAction *action = parentMenu->addAction( parentTagId == 0 - ? tr("Move to the root", - "to move a tag to the current tag in the tag context menu") + ? tr("Move to the root", "to move a tag to the current tag in the tag context menu") : tr("Move to this tag")); action->setData(parentTagId); @@ -8788,8 +8402,7 @@ void MainWindow::buildTagMoveMenuTree(QMenu *parentMenu, int parentTagId) { * Populates a tag menu tree for bulk note tagging */ void MainWindow::buildBulkNoteTagMenuTree(QMenu *parentMenu, int parentTagId) { - const auto tagList = - Tag::fetchAllByParentId(parentTagId, QStringLiteral("t.name ASC")); + const auto tagList = Tag::fetchAllByParentId(parentTagId, QStringLiteral("t.name ASC")); for (const Tag &tag : tagList) { const int tagId = tag.getId(); @@ -8815,9 +8428,8 @@ void MainWindow::buildBulkNoteTagMenuTree(QMenu *parentMenu, int parentTagId) { QAction *action = parentMenu->addAction(tr("Tag this")); action->setData(parentTagId); - connect(action, &QAction::triggered, this, [this, parentTagId]() { - tagSelectedNotesToTagId(parentTagId); - }); + connect(action, &QAction::triggered, this, + [this, parentTagId]() { tagSelectedNotesToTagId(parentTagId); }); } } @@ -8836,9 +8448,8 @@ void MainWindow::moveSelectedTagsToTagId(int tagId) { Tag tag = Tag::fetch(id); if (tag.isFetched()) { if (tag.hasChild(tagId) || (id == tagId)) { - showStatusBarMessage( - tr("Cannot move tag '%1' to this tag").arg(tag.getName()), - 3000); + showStatusBarMessage(tr("Cannot move tag '%1' to this tag").arg(tag.getName()), + 3000); } else { tagList << tag; } @@ -8846,8 +8457,7 @@ void MainWindow::moveSelectedTagsToTagId(int tagId) { } if (tagList.count() > 0) { - const bool useScriptingEngine = - ScriptingService::instance()->noteTaggingHookExists(); + const bool useScriptingEngine = ScriptingService::instance()->noteTaggingHookExists(); // workaround when signal block doesn't work correctly directoryWatcherWorkaround(true, true); @@ -8855,15 +8465,13 @@ void MainWindow::moveSelectedTagsToTagId(int tagId) { // move tags for (Tag tag : Utils::asConst(tagList)) { if (useScriptingEngine) { - const QVector<Tag> tagsToHandle = - Tag::fetchRecursivelyByParentId(tag.getId()); + const QVector<Tag> tagsToHandle = Tag::fetchRecursivelyByParentId(tag.getId()); // check all tags we need to handle for (const Tag &tagToHandle : tagsToHandle) { // remove tag from all notes for (const Note ¬e : tagToHandle.fetchAllLinkedNotes()) { - handleScriptingNoteTagging( - note, tagToHandle, true, false); + handleScriptingNoteTagging(note, tagToHandle, true, false); } } } @@ -8872,21 +8480,18 @@ void MainWindow::moveSelectedTagsToTagId(int tagId) { tag.store(); if (useScriptingEngine) { - const QVector<Tag> tagsToHandle = - Tag::fetchRecursivelyByParentId(tag.getId()); + const QVector<Tag> tagsToHandle = Tag::fetchRecursivelyByParentId(tag.getId()); // check all tags we need to handle for (const Tag &tagToHandle : tagsToHandle) { // add tag to all notes for (const Note ¬e : tagToHandle.fetchAllLinkedNotes()) { - handleScriptingNoteTagging( - note, tagToHandle, false, false); + handleScriptingNoteTagging(note, tagToHandle, false, false); } } } - showStatusBarMessage( - tr("Moved tag '%1' to new tag").arg(tag.getName()), 3000); + showStatusBarMessage(tr("Moved tag '%1' to new tag").arg(tag.getName()), 3000); } reloadCurrentNoteTags(); @@ -8916,8 +8521,7 @@ void MainWindow::tagSelectedNotesToTagId(int tagId) { void MainWindow::buildBulkNoteSubFolderMenuTree(QMenu *parentMenu, bool doCopy, int parentNoteSubFolderId) { const QVector<NoteSubFolder> noteSubFolderList = - NoteSubFolder::fetchAllByParentId(parentNoteSubFolderId, - QStringLiteral("name ASC")); + NoteSubFolder::fetchAllByParentId(parentNoteSubFolderId, QStringLiteral("name ASC")); for (const auto ¬eSubFolder : noteSubFolderList) { const int noteSubFolderId = noteSubFolder.getId(); @@ -8927,19 +8531,15 @@ void MainWindow::buildBulkNoteSubFolderMenuTree(QMenu *parentMenu, bool doCopy, if (count > 0) { // if there are sub-noteSubFolder build a new menu level QMenu *noteSubFolderMenu = parentMenu->addMenu(name); - buildBulkNoteSubFolderMenuTree(noteSubFolderMenu, doCopy, - noteSubFolderId); + buildBulkNoteSubFolderMenuTree(noteSubFolderMenu, doCopy, noteSubFolderId); } else { // if there are no sub-noteSubFolders just create a named action QAction *action = parentMenu->addAction(name); - connect( - action, &QAction::triggered, this, - [this, doCopy, noteSubFolderId]() { - doCopy - ? copySelectedNotesToNoteSubFolderId(noteSubFolderId) - : moveSelectedNotesToNoteSubFolderId(noteSubFolderId); - }); + connect(action, &QAction::triggered, this, [this, doCopy, noteSubFolderId]() { + doCopy ? copySelectedNotesToNoteSubFolderId(noteSubFolderId) + : moveSelectedNotesToNoteSubFolderId(noteSubFolderId); + }); } } @@ -8948,26 +8548,23 @@ void MainWindow::buildBulkNoteSubFolderMenuTree(QMenu *parentMenu, bool doCopy, const QString text = (parentNoteSubFolderId == 0) ? (doCopy ? tr("Copy to note folder") : tr("Move to note folder")) - : (doCopy ? tr("Copy to this subfolder") - : tr("Move to this subfolder")); + : (doCopy ? tr("Copy to this subfolder") : tr("Move to this subfolder")); QAction *action = parentMenu->addAction(text); action->setData(parentNoteSubFolderId); - connect(action, &QAction::triggered, this, - [this, doCopy, parentNoteSubFolderId]() { - doCopy - ? copySelectedNotesToNoteSubFolderId(parentNoteSubFolderId) - : moveSelectedNotesToNoteSubFolderId(parentNoteSubFolderId); - }); + connect(action, &QAction::triggered, this, [this, doCopy, parentNoteSubFolderId]() { + doCopy ? copySelectedNotesToNoteSubFolderId(parentNoteSubFolderId) + : moveSelectedNotesToNoteSubFolderId(parentNoteSubFolderId); + }); } /** * Populates a subfolder menu tree for bulk note moving or copying to * subfolders of other note folders */ -void MainWindow::buildBulkNoteFolderSubFolderMenuTree( - QMenu *parentMenu, bool doCopy, const QString &parentNoteSubFolderPath, - bool isRoot) { +void MainWindow::buildBulkNoteFolderSubFolderMenuTree(QMenu *parentMenu, bool doCopy, + const QString &parentNoteSubFolderPath, + bool isRoot) { QDir dir(parentNoteSubFolderPath); QStringList nameFilters{}; @@ -8976,8 +8573,7 @@ void MainWindow::buildBulkNoteFolderSubFolderMenuTree( } // show newest entry first - QStringList directoryNames = - dir.entryList(QDir::Dirs | QDir::NoDotAndDotDot, QDir::Name); + QStringList directoryNames = dir.entryList(QDir::Dirs | QDir::NoDotAndDotDot, QDir::Name); if (isRoot) { const auto names = QStringList({"media", "trash", "attachments"}); @@ -8987,46 +8583,39 @@ void MainWindow::buildBulkNoteFolderSubFolderMenuTree( } for (const QString &directoryName : Utils::asConst(directoryNames)) { - const QString fullPath = - parentNoteSubFolderPath + QLatin1Char('/') + directoryName; + const QString fullPath = parentNoteSubFolderPath + QLatin1Char('/') + directoryName; QDir subDir(fullPath); - const QStringList subDirectoryNames = - subDir.entryList(QDir::Dirs | QDir::NoDotAndDotDot); + const QStringList subDirectoryNames = subDir.entryList(QDir::Dirs | QDir::NoDotAndDotDot); if (subDirectoryNames.count() > 0) { // if there are sub folders build a new menu level QMenu *noteSubFolderMenu = parentMenu->addMenu(directoryName); - buildBulkNoteFolderSubFolderMenuTree(noteSubFolderMenu, doCopy, - fullPath, false); + buildBulkNoteFolderSubFolderMenuTree(noteSubFolderMenu, doCopy, fullPath, false); } else { // if there are no sub folders just create a named action QAction *action = parentMenu->addAction(directoryName); action->setToolTip(fullPath); action->setStatusTip(fullPath); - connect(action, &QAction::triggered, this, - [this, doCopy, fullPath]() { - doCopy ? copySelectedNotesToFolder(fullPath) - : moveSelectedNotesToFolder(fullPath); - }); + connect(action, &QAction::triggered, this, [this, doCopy, fullPath]() { + doCopy ? copySelectedNotesToFolder(fullPath) : moveSelectedNotesToFolder(fullPath); + }); } } // add an action to copy or move to this subfolder parentMenu->addSeparator(); - const QString text = (isRoot) ? (doCopy ? tr("Copy to note folder") - : tr("Move to note folder")) - : (doCopy ? tr("Copy to this subfolder") - : tr("Move to this subfolder")); + const QString text = + (isRoot) ? (doCopy ? tr("Copy to note folder") : tr("Move to note folder")) + : (doCopy ? tr("Copy to this subfolder") : tr("Move to this subfolder")); auto *action = parentMenu->addAction(text); action->setToolTip(parentNoteSubFolderPath); action->setStatusTip(parentNoteSubFolderPath); - connect(action, &QAction::triggered, this, - [this, doCopy, parentNoteSubFolderPath]() { - doCopy ? copySelectedNotesToFolder(parentNoteSubFolderPath) - : moveSelectedNotesToFolder(parentNoteSubFolderPath); - }); + connect(action, &QAction::triggered, this, [this, doCopy, parentNoteSubFolderPath]() { + doCopy ? copySelectedNotesToFolder(parentNoteSubFolderPath) + : moveSelectedNotesToFolder(parentNoteSubFolderPath); + }); } /** @@ -9058,16 +8647,14 @@ void MainWindow::copySelectedNotesToNoteSubFolderId(int noteSubFolderId) { /** * Moves selected notes to a note subfolder */ -void MainWindow::moveSelectedNotesToNoteSubFolder( - const NoteSubFolder ¬eSubFolder) { +void MainWindow::moveSelectedNotesToNoteSubFolder(const NoteSubFolder ¬eSubFolder) { const int selectedItemsCount = ui->noteTreeWidget->selectedItems().size(); const QString text = tr("Move %n selected note(s) to note subfolder " "<strong>%2</strong>?", "", selectedItemsCount) .arg(noteSubFolder.getName()); - if (Utils::Gui::question(this, tr("Move selected notes"), text, - QStringLiteral("move-notes")) == + if (Utils::Gui::question(this, tr("Move selected notes"), text, QStringLiteral("move-notes")) == QMessageBox::Yes) { const QSignalBlocker blocker(this->noteDirectoryWatcher); Q_UNUSED(blocker) @@ -9097,7 +8684,8 @@ void MainWindow::moveSelectedNotesToNoteSubFolder( // don't move note if source and destination paths are the same if (noteSubFolder.fullPath() == note.fullNoteFileDirPath()) { qWarning() << "Note was not moved because source and " - "destination paths were the same:" << note.getName(); + "destination paths were the same:" + << note.getName(); continue; } @@ -9122,7 +8710,7 @@ void MainWindow::moveSelectedNotesToNoteSubFolder( // tag the note again for (const Tag &tag : tags) { tag.linkToNote(note); -// tag.linkToNote(note); + // tag.linkToNote(note); } // handle the replacing of all note links from other notes @@ -9133,12 +8721,10 @@ void MainWindow::moveSelectedNotesToNoteSubFolder( } // re-link images - const bool mediaFileLinksUpdated = - note.updateRelativeMediaFileLinks(); + const bool mediaFileLinksUpdated = note.updateRelativeMediaFileLinks(); // re-link attachments - const bool attachmentFileLinksUpdated = - note.updateRelativeAttachmentFileLinks(); + const bool attachmentFileLinksUpdated = note.updateRelativeAttachmentFileLinks(); if (mediaFileLinksUpdated || attachmentFileLinksUpdated) { note.storeNoteTextFileToDisk(); @@ -9152,42 +8738,35 @@ void MainWindow::moveSelectedNotesToNoteSubFolder( if (noteSubFolderCount > 0) { // for some reason this only works with a small delay, otherwise // not all changes will be recognized - QTimer::singleShot(150, this, - SLOT(buildNotesIndexAndLoadNoteDirectoryList())); + QTimer::singleShot(150, this, SLOT(buildNotesIndexAndLoadNoteDirectoryList())); } showStatusBarMessage( - tr("%n note(s) were moved to note subfolder \"%2\"", "", - noteSubFolderCount) + tr("%n note(s) were moved to note subfolder \"%2\"", "", noteSubFolderCount) .arg(noteSubFolder.getName()), 5000); // wait some time to enable the check again to prevent troubles on macOS - QTimer::singleShot(4000, this, - SLOT(enableNoteExternallyRemovedCheck())); + QTimer::singleShot(4000, this, SLOT(enableNoteExternallyRemovedCheck())); } } /** * Enables the note externally removed check */ -void MainWindow::enableNoteExternallyRemovedCheck() { - _noteExternallyRemovedCheckEnabled = true; -} +void MainWindow::enableNoteExternallyRemovedCheck() { _noteExternallyRemovedCheckEnabled = true; } /** * Copies selected notes to a note subfolder */ -void MainWindow::copySelectedNotesToNoteSubFolder( - const NoteSubFolder ¬eSubFolder) { +void MainWindow::copySelectedNotesToNoteSubFolder(const NoteSubFolder ¬eSubFolder) { const int selectedItemsCount = ui->noteTreeWidget->selectedItems().size(); const QString text = tr("Copy %n selected note(s) to note subfolder " "<strong>%2</strong>?", "", selectedItemsCount) .arg(noteSubFolder.getName()); - if (Utils::Gui::question(this, tr("Copy selected notes"), text, - QStringLiteral("copy-notes")) == + if (Utils::Gui::question(this, tr("Copy selected notes"), text, QStringLiteral("copy-notes")) == QMessageBox::Yes) { const QSignalBlocker blocker(this->noteDirectoryWatcher); Q_UNUSED(blocker) @@ -9209,7 +8788,8 @@ void MainWindow::copySelectedNotesToNoteSubFolder( // don't copy note if source and destination paths are the same if (noteSubFolder.fullPath() == note.fullNoteFileDirPath()) { qWarning() << "Note was not copied because source and " - "destination paths were the same:" << note.getName(); + "destination paths were the same:" + << note.getName(); continue; } @@ -9232,12 +8812,10 @@ void MainWindow::copySelectedNotesToNoteSubFolder( } // re-link images - const bool mediaFileLinksUpdated = - note.updateRelativeMediaFileLinks(); + const bool mediaFileLinksUpdated = note.updateRelativeMediaFileLinks(); // re-link attachments - const bool attachmentFileLinksUpdated = - note.updateRelativeAttachmentFileLinks(); + const bool attachmentFileLinksUpdated = note.updateRelativeAttachmentFileLinks(); if (mediaFileLinksUpdated || attachmentFileLinksUpdated) { note.storeNoteTextFileToDisk(); @@ -9251,13 +8829,11 @@ void MainWindow::copySelectedNotesToNoteSubFolder( if (noteSubFolderCount > 0) { // for some reason this only works with a small delay, otherwise // not all changes will be recognized - QTimer::singleShot(150, this, - SLOT(buildNotesIndexAndLoadNoteDirectoryList())); + QTimer::singleShot(150, this, SLOT(buildNotesIndexAndLoadNoteDirectoryList())); } showStatusBarMessage( - tr("%n note(s) were copied to note subfolder \"%2\"", "", - noteSubFolderCount) + tr("%n note(s) were copied to note subfolder \"%2\"", "", noteSubFolderCount) .arg(noteSubFolder.getName()), 5000); } @@ -9408,9 +8984,8 @@ void MainWindow::on_actionExport_preview_HTML_triggered() { #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) out.setCodec("UTF-8"); #endif - out << currentNote.toMarkdownHtml(NoteFolder::currentLocalPath(), - getMaxImageWidth(), true, true, - true); + out << currentNote.toMarkdownHtml(NoteFolder::currentLocalPath(), getMaxImageWidth(), + true, true, true); file.flush(); file.close(); Utils::Misc::openFolderSelect(fileName); @@ -9422,16 +8997,14 @@ void MainWindow::on_actionExport_preview_HTML_triggered() { * Opens the IRC web chat page */ void MainWindow::on_actionOpen_IRC_Channel_triggered() { - QDesktopServices::openUrl(QUrl(QStringLiteral( - "https://web.libera.chat/#qownnotes"))); + QDesktopServices::openUrl(QUrl(QStringLiteral("https://web.libera.chat/#qownnotes"))); } /** * Opens the Gitter room in a webpage */ void MainWindow::on_actionGitter_triggered() { - QDesktopServices::openUrl( - QUrl(QStringLiteral("https://gitter.im/qownnotes/qownnotes"))); + QDesktopServices::openUrl(QUrl(QStringLiteral("https://gitter.im/qownnotes/qownnotes"))); } /** @@ -9440,16 +9013,15 @@ void MainWindow::on_actionGitter_triggered() { void MainWindow::storeSavedSearch() { QSettings settings; - if (settings.value(QStringLiteral("disableSavedSearchesAutoCompletion")) - .toBool()) { + if (settings.value(QStringLiteral("disableSavedSearchesAutoCompletion")).toBool()) { return; } const QString text = ui->searchLineEdit->text(); if (!text.isEmpty()) { int noteFolderId = NoteFolder::currentNoteFolderId(); - QString settingsKey = QStringLiteral("savedSearches/noteFolder-") + - QString::number(noteFolderId); + QString settingsKey = + QStringLiteral("savedSearches/noteFolder-") + QString::number(noteFolderId); QStringList savedSearches = settings.value(settingsKey).toStringList(); // add the text to the saved searches @@ -9478,10 +9050,9 @@ void MainWindow::initSavedSearchesCompleter() { QStringList savedSearches; QSettings settings; - if (!settings.value(QStringLiteral("disableSavedSearchesAutoCompletion")) - .toBool()) { - QString settingsKey = QStringLiteral("savedSearches/noteFolder-") + - QString::number(noteFolderId); + if (!settings.value(QStringLiteral("disableSavedSearchesAutoCompletion")).toBool()) { + QString settingsKey = + QStringLiteral("savedSearches/noteFolder-") + QString::number(noteFolderId); savedSearches = settings.value(settingsKey).toStringList(); } @@ -9535,8 +9106,8 @@ void MainWindow::on_actionShow_status_bar_triggered(bool checked) { settings.setValue(QStringLiteral("showStatusBar"), checked); } -void MainWindow::on_noteTreeWidget_currentItemChanged( - QTreeWidgetItem *current, QTreeWidgetItem *previous) { +void MainWindow::on_noteTreeWidget_currentItemChanged(QTreeWidgetItem *current, + QTreeWidgetItem *previous) { // in case all notes were removed if (current == nullptr) { return; @@ -9563,14 +9134,14 @@ void MainWindow::openSelectedNotesInTab() { continue; } -// setCurrentNote(note); -// openCurrentNoteInTab(); + // setCurrentNote(note); + // openCurrentNoteInTab(); openNoteInTab(note); } } -void MainWindow::openNoteInTab(const Note& note) { +void MainWindow::openNoteInTab(const Note ¬e) { // simulate a newly opened tab by updating the current tab with the last note if (_lastNoteId > 0) { auto previousNote = Note::fetch(_lastNoteId); @@ -9591,8 +9162,7 @@ void MainWindow::openNoteInTab(const Note& note) { tabIndex = ui->noteEditTabWidget->addTab(widgetPage, noteName); } - Utils::Gui::updateTabWidgetTabData(ui->noteEditTabWidget, - tabIndex, note); + Utils::Gui::updateTabWidgetTabData(ui->noteEditTabWidget, tabIndex, note); ui->noteEditTabWidget->setCurrentIndex(tabIndex); @@ -9623,8 +9193,7 @@ void MainWindow::openCurrentNoteInTab() { tabIndex = ui->noteEditTabWidget->addTab(widgetPage, noteName); } - Utils::Gui::updateTabWidgetTabData(ui->noteEditTabWidget, - tabIndex, currentNote); + Utils::Gui::updateTabWidgetTabData(ui->noteEditTabWidget, tabIndex, currentNote); ui->noteEditTabWidget->setCurrentIndex(tabIndex); @@ -9635,12 +9204,11 @@ void MainWindow::openCurrentNoteInTab() { } int MainWindow::getNoteTabIndex(int noteId) const { - return Utils::Gui::getTabWidgetIndexByProperty( - ui->noteEditTabWidget, QStringLiteral("note-id"), noteId); + return Utils::Gui::getTabWidgetIndexByProperty(ui->noteEditTabWidget, QStringLiteral("note-id"), + noteId); } -void MainWindow::on_noteTreeWidget_customContextMenuRequested( - const QPoint pos) { +void MainWindow::on_noteTreeWidget_customContextMenuRequested(const QPoint pos) { auto *item = ui->noteTreeWidget->itemAt(pos); // if the user clicks at empty space, this is null and if it isn't handled @@ -9660,8 +9228,7 @@ void MainWindow::on_noteTreeWidget_customContextMenuRequested( } } -void MainWindow::openNotesContextMenu(const QPoint globalPos, - bool multiNoteMenuEntriesOnly) { +void MainWindow::openNotesContextMenu(const QPoint globalPos, bool multiNoteMenuEntriesOnly) { QMenu noteMenu; QAction *renameAction = nullptr; @@ -9696,24 +9263,20 @@ void MainWindow::openNotesContextMenu(const QPoint globalPos, } if (noteFolder.isShowSubfolders()) { - auto *subFolderMoveMenu = - moveDestinationMenu->addMenu(noteFolder.getName()); + auto *subFolderMoveMenu = moveDestinationMenu->addMenu(noteFolder.getName()); buildBulkNoteFolderSubFolderMenuTree(subFolderMoveMenu, false, noteFolder.getLocalPath()); - auto *subFolderCopyMenu = - copyDestinationMenu->addMenu(noteFolder.getName()); + auto *subFolderCopyMenu = copyDestinationMenu->addMenu(noteFolder.getName()); buildBulkNoteFolderSubFolderMenuTree(subFolderCopyMenu, true, noteFolder.getLocalPath()); } else { - auto *moveAction = - moveDestinationMenu->addAction(noteFolder.getName()); + auto *moveAction = moveDestinationMenu->addAction(noteFolder.getName()); moveAction->setData(noteFolder.getLocalPath()); moveAction->setToolTip(noteFolder.getLocalPath()); moveAction->setStatusTip(noteFolder.getLocalPath()); - auto *copyAction = - copyDestinationMenu->addAction(noteFolder.getName()); + auto *copyAction = copyDestinationMenu->addAction(noteFolder.getName()); copyAction->setData(noteFolder.getLocalPath()); copyAction->setToolTip(noteFolder.getLocalPath()); copyAction->setStatusTip(noteFolder.getLocalPath()); @@ -9726,16 +9289,13 @@ void MainWindow::openNotesContextMenu(const QPoint globalPos, const bool isEnableNoteTree = Utils::Misc::isEnableNoteTree(); if (showSubFolders || isEnableNoteTree) { if (ui->noteTreeWidget->selectedItems().count() == 1 && !isEnableNoteTree) { - moveToThisSubFolderAction = - noteMenu.addAction(tr("Jump to the note's subfolder")); + moveToThisSubFolderAction = noteMenu.addAction(tr("Jump to the note's subfolder")); } - auto *subFolderMoveMenu = - noteMenu.addMenu(tr("Move notes to subfolder…")); + auto *subFolderMoveMenu = noteMenu.addMenu(tr("Move notes to subfolder…")); buildBulkNoteSubFolderMenuTree(subFolderMoveMenu, false); - auto *subFolderCopyMenu = - noteMenu.addMenu(tr("Copy notes to subfolder…")); + auto *subFolderCopyMenu = noteMenu.addMenu(tr("Copy notes to subfolder…")); buildBulkNoteSubFolderMenuTree(subFolderCopyMenu, true); } @@ -9760,14 +9320,12 @@ void MainWindow::openNotesContextMenu(const QPoint globalPos, } } - const QVector<Tag> tagRemoveList = - Tag::fetchAllWithLinkToNoteNames(noteNameList); + const QVector<Tag> tagRemoveList = Tag::fetchAllWithLinkToNoteNames(noteNameList); // show the remove tags menu if at least one tag is present QMenu *tagRemoveMenu = nullptr; if (tagRemoveList.count() > 0) { - tagRemoveMenu = - noteMenu.addMenu(tr("&Remove tag from selected notes…")); + tagRemoveMenu = noteMenu.addMenu(tr("&Remove tag from selected notes…")); for (const Tag &tag : tagRemoveList) { auto *action = tagRemoveMenu->addAction(tag.getName()); @@ -9793,18 +9351,13 @@ void MainWindow::openNotesContextMenu(const QPoint globalPos, } if (!multiNoteMenuEntriesOnly) { - openInExternalEditorAction = - noteMenu.addAction(tr("Open note in external editor")); - openNoteWindowAction = - noteMenu.addAction(tr("Open note in different window")); - showInFileManagerAction = - noteMenu.addAction(tr("Show note in file manager")); + openInExternalEditorAction = noteMenu.addAction(tr("Open note in external editor")); + openNoteWindowAction = noteMenu.addAction(tr("Open note in different window")); + showInFileManagerAction = noteMenu.addAction(tr("Show note in file manager")); showNoteGitLogAction = new QAction(this); - if (Utils::Git::isCurrentNoteFolderUseGit() && - Utils::Git::hasLogCommand()) { - showNoteGitLogAction = - noteMenu.addAction(tr("Show note git versions")); + if (Utils::Git::isCurrentNoteFolderUseGit() && Utils::Git::hasLogCommand()) { + showNoteGitLogAction = noteMenu.addAction(tr("Show note git versions")); } } @@ -9869,9 +9422,9 @@ void MainWindow::openNotesContextMenu(const QPoint globalPos, if (Note::allowDifferentFileName()) { if (Utils::Misc::isNoteListPreview()) { bool ok{}; - const QString name = QInputDialog::getText( - this, tr("Rename note"), tr("Name:"), QLineEdit::Normal, - currentNote.getName(), &ok); + const QString name = + QInputDialog::getText(this, tr("Rename note"), tr("Name:"), + QLineEdit::Normal, currentNote.getName(), &ok); if (ok && !name.isEmpty()) { item->setText(0, name); @@ -9881,13 +9434,12 @@ void MainWindow::openNotesContextMenu(const QPoint globalPos, ui->noteTreeWidget->editItem(item); } } else { - if (QMessageBox::warning( - this, tr("Note renaming not enabled!"), - tr("If you want to rename your note you have to enable " - "the option to allow the note filename to be " - "different from the headline."), - tr("Open &settings"), tr("&Cancel"), QString(), 0, - 1) == 0) { + if (QMessageBox::warning(this, tr("Note renaming not enabled!"), + tr("If you want to rename your note you have to enable " + "the option to allow the note filename to be " + "different from the headline."), + tr("Open &settings"), tr("&Cancel"), QString(), 0, + 1) == 0) { openSettingsDialog(SettingsDialog::NoteFolderPage); } } @@ -9898,12 +9450,11 @@ void MainWindow::openNotesContextMenu(const QPoint globalPos, /** * Renames a note file if the note was renamed in the note tree widget */ -void MainWindow::on_noteTreeWidget_itemChanged(QTreeWidgetItem *item, - int /*column*/) { +void MainWindow::on_noteTreeWidget_itemChanged(QTreeWidgetItem *item, int /*column*/) { if (item == nullptr) { return; } - + // handle note subfolder renaming in a note tree if (item->data(0, Qt::UserRole + 1) == FolderType) { ui->noteSubFolderTreeWidget->renameSubFolder(item); @@ -9933,8 +9484,7 @@ void MainWindow::on_noteTreeWidget_itemChanged(QTreeWidgetItem *item, setCurrentNote(note); // rename the note file names of note tag links - Tag::renameNoteFileNamesOfLinks(oldNoteName, newNoteName, - note.getNoteSubFolder()); + Tag::renameNoteFileNamesOfLinks(oldNoteName, newNoteName, note.getNoteSubFolder()); // handle the replacing of all note urls if a note was renamed if (note.handleNoteMoving(oldNote)) { @@ -9947,14 +9497,11 @@ void MainWindow::on_noteTreeWidget_itemChanged(QTreeWidgetItem *item, // sort notes if note name has changed QSettings settings; - if (settings - .value(QStringLiteral("notesPanelSort"), - SORT_BY_LAST_CHANGE) - .toInt() == SORT_ALPHABETICAL) { + if (settings.value(QStringLiteral("notesPanelSort"), SORT_BY_LAST_CHANGE).toInt() == + SORT_ALPHABETICAL) { ui->noteTreeWidget->sortItems( 0, Utils::Gui::toQtOrder( - settings.value(QStringLiteral("notesPanelOrder")) - .toInt())); + settings.value(QStringLiteral("notesPanelOrder")).toInt())); ui->noteTreeWidget->scrollToItem(item); } @@ -10023,27 +9570,18 @@ bool MainWindow::showNotesFromAllNoteSubFolders() const { .toBool(); } -void MainWindow::setShowNotesFromAllNoteSubFolders(bool show) -{ +void MainWindow::setShowNotesFromAllNoteSubFolders(bool show) { _showNotesFromAllNoteSubFolders = show; QSettings settings; - settings.setValue(QStringLiteral("MainWindow/showNotesFromAllNoteSubFolders"), _showNotesFromAllNoteSubFolders); + settings.setValue(QStringLiteral("MainWindow/showNotesFromAllNoteSubFolders"), + _showNotesFromAllNoteSubFolders); } -NoteSubFolderTree *MainWindow::noteSubFolderTree() -{ - return ui->noteSubFolderTreeWidget; -} +NoteSubFolderTree *MainWindow::noteSubFolderTree() { return ui->noteSubFolderTreeWidget; } -QOwnNotesMarkdownTextEdit *MainWindow::noteTextEdit() -{ - return ui->noteTextEdit; -} +QOwnNotesMarkdownTextEdit *MainWindow::noteTextEdit() { return ui->noteTextEdit; } -void MainWindow::refreshNotePreview() -{ - _noteViewUpdateTimer->start(1); -} +void MainWindow::refreshNotePreview() { _noteViewUpdateTimer->start(1); } /** * Searches for note sub folders in the note sub folder tree widget @@ -10060,9 +9598,8 @@ void MainWindow::on_noteSubFolderLineEdit_textChanged(const QString &arg1) { Q_UNUSED(blocker) // search for the text - Utils::Gui::searchForTextInTreeWidget( - ui->noteSubFolderTreeWidget, arg1, - Utils::Gui::TreeWidgetSearchFlag::IntCheck); + Utils::Gui::searchForTextInTreeWidget(ui->noteSubFolderTreeWidget, arg1, + Utils::Gui::TreeWidgetSearchFlag::IntCheck); } } @@ -10073,21 +9610,16 @@ bool MainWindow::createNewNoteSubFolder(QString folderName) { bool ok = true; if (folderName.isEmpty()) { - folderName = QInputDialog::getText(this, tr("Create a new folder"), - tr("Folder name:"), + folderName = QInputDialog::getText(this, tr("Create a new folder"), tr("Folder name:"), QLineEdit::Normal, QString(), &ok); } - if (!ok || folderName.isEmpty() || - NoteSubFolder::willFolderBeIgnored(folderName, true)) { - + if (!ok || folderName.isEmpty() || NoteSubFolder::willFolderBeIgnored(folderName, true)) { return false; } - NoteSubFolder noteSubFolder = - NoteFolder::currentNoteFolder().getActiveNoteSubFolder(); - const QString path = - noteSubFolder.fullPath() + QDir::separator() + folderName; + NoteSubFolder noteSubFolder = NoteFolder::currentNoteFolder().getActiveNoteSubFolder(); + const QString path = noteSubFolder.fullPath() + QDir::separator() + folderName; QDir directory; const bool success = directory.mkpath(path); @@ -10133,24 +9665,19 @@ void MainWindow::on_actionShare_note_triggered() { /** * Toggles the case of the word under the Cursor or the selected text */ -void MainWindow::on_actionToggle_text_case_triggered() { - activeNoteTextEdit()->toggleCase(); -} +void MainWindow::on_actionToggle_text_case_triggered() { activeNoteTextEdit()->toggleCase(); } /** * Opens the Markdown Cheatsheet webpage */ void MainWindow::on_actionMarkdown_cheatsheet_triggered() { - QDesktopServices::openUrl( - QUrl("https://www.qownnotes.org/getting-started/markdown.html")); + QDesktopServices::openUrl(QUrl("https://www.qownnotes.org/getting-started/markdown.html")); } /** * Strikes out the selected text */ -void MainWindow::on_actionStrike_out_text_triggered() { - applyFormatter(QStringLiteral("~~")); -} +void MainWindow::on_actionStrike_out_text_triggered() { applyFormatter(QStringLiteral("~~")); } /** * Initializes the shortcuts for the actions @@ -10190,17 +9717,14 @@ void MainWindow::initShortcuts() { #ifdef Q_OS_MAC // #1222, replace Option key by Ctrl key on macOS to prevent // blocking of accent characters when writing text - oldShortcut.replace(QStringLiteral("Alt+"), - QStringLiteral("Meta+")); + oldShortcut.replace(QStringLiteral("Alt+"), QStringLiteral("Meta+")); #endif - const QString &key = - QStringLiteral("Shortcuts/MainWindow-") + action->objectName(); + const QString &key = QStringLiteral("Shortcuts/MainWindow-") + action->objectName(); const bool settingFound = settings.contains(key); // try to load a key sequence from the settings - auto shortcut = QKeySequence(settingFound ? - settings.value(key).toString() : ""); + auto shortcut = QKeySequence(settingFound ? settings.value(key).toString() : ""); // do we can this method the first time? if (!_isDefaultShortcutInitialized) { @@ -10233,8 +9757,7 @@ void MainWindow::initShortcuts() { action->setShortcut(QKeySequence()); auto *shortcutItem = new QShortcut(shortcut, this); - connect(shortcutItem, &QShortcut::activated, action, - &QAction::trigger); + connect(shortcutItem, &QShortcut::activated, action, &QAction::trigger); _menuShortcuts.append(shortcutItem); } #endif @@ -10303,8 +9826,7 @@ void MainWindow::on_actionSplit_note_at_cursor_position_triggered() { const QString noteLink = previousNote.getNoteUrlForLinkingTo(currentNote); QString previousNoteText = previousNote.getNoteText(); previousNoteText.reserve(3 + noteLink.size() + 1); - previousNoteText += - QStringLiteral("\n\n<") + noteLink + QStringLiteral(">"); + previousNoteText += QStringLiteral("\n\n<") + noteLink + QStringLiteral(">"); previousNote.storeNewText(std::move(previousNoteText)); // add the previously removed text @@ -10320,11 +9842,9 @@ void MainWindow::on_actionSplit_note_at_cursor_position_triggered() { /** * Adds a custom action as menu item and button */ -void MainWindow::addCustomAction(const QString &identifier, - const QString &menuText, +void MainWindow::addCustomAction(const QString &identifier, const QString &menuText, const QString &buttonText, const QString &icon, - bool useInNoteEditContextMenu, - bool hideButtonInToolbar, + bool useInNoteEditContextMenu, bool hideButtonInToolbar, bool useInNoteListContextMenu) { // ui->menuCustom_actions->show(); QAction *action = ui->menuCustom_actions->addAction(menuText); @@ -10334,9 +9854,7 @@ void MainWindow::addCustomAction(const QString &identifier, // restore the shortcut of the custom action QSettings settings; QKeySequence shortcut = QKeySequence( - settings - .value(QStringLiteral("Shortcuts/MainWindow-customAction_") + - identifier) + settings.value(QStringLiteral("Shortcuts/MainWindow-customAction_") + identifier) .toString()); if (!shortcut.isEmpty()) { action->setShortcut(shortcut); @@ -10378,13 +9896,11 @@ void MainWindow::addCustomAction(const QString &identifier, /** * Adds a label to the scripting dock widget */ -void MainWindow::addScriptingLabel(const QString &identifier, - const QString &text) { +void MainWindow::addScriptingLabel(const QString &identifier, const QString &text) { _scriptingDockWidget->show(); QLabel *label = new QLabel(text, _scriptingDockWidget); label->setOpenExternalLinks(true); - label->setTextInteractionFlags(Qt::TextSelectableByMouse | - Qt::LinksAccessibleByMouse); + label->setTextInteractionFlags(Qt::TextSelectableByMouse | Qt::LinksAccessibleByMouse); label->setWordWrap(true); label->setObjectName(QStringLiteral("scriptingLabel-") + identifier); ui->scriptingScrollAreaLayout->addWidget(label); @@ -10393,10 +9909,9 @@ void MainWindow::addScriptingLabel(const QString &identifier, /** * Sets the text of a label in the scripting dock widget */ -void MainWindow::setScriptingLabelText(const QString &identifier, - const QString &text) { - auto *label = ui->scriptingScrollArea->findChild<QLabel *>( - QStringLiteral("scriptingLabel-") + identifier); +void MainWindow::setScriptingLabelText(const QString &identifier, const QString &text) { + auto *label = ui->scriptingScrollArea->findChild<QLabel *>(QStringLiteral("scriptingLabel-") + + identifier); if (label != nullptr) { label->setText(text); } @@ -10429,8 +9944,7 @@ void MainWindow::on_actionFind_notes_in_all_subfolders_triggered() { * Sends an event to jump to "All notes" in the note subfolder tree widget */ void MainWindow::selectAllNotesInNoteSubFolderTreeWidget() const { - QKeyEvent *event = - new QKeyEvent(QEvent::KeyPress, Qt::Key_Home, Qt::NoModifier); + QKeyEvent *event = new QKeyEvent(QEvent::KeyPress, Qt::Key_Home, Qt::NoModifier); QCoreApplication::postEvent(ui->noteSubFolderTreeWidget, event); } @@ -10438,8 +9952,7 @@ void MainWindow::selectAllNotesInNoteSubFolderTreeWidget() const { * Sends an event to jump to "All notes" in the tag tree widget */ void MainWindow::selectAllNotesInTagTreeWidget() const { - QKeyEvent *event = - new QKeyEvent(QEvent::KeyPress, Qt::Key_Home, Qt::NoModifier); + QKeyEvent *event = new QKeyEvent(QEvent::KeyPress, Qt::Key_Home, Qt::NoModifier); QCoreApplication::postEvent(ui->tagTreeWidget, event); } @@ -10526,22 +10039,19 @@ void MainWindow::on_actionUnlock_panels_toggled(bool arg1) { } } else { // add the old title bar widgets to all dock widgets - _noteSubFolderDockWidget->setTitleBarWidget( - _noteSubFolderDockTitleBarWidget); + _noteSubFolderDockWidget->setTitleBarWidget(_noteSubFolderDockTitleBarWidget); _taggingDockWidget->setTitleBarWidget(_taggingDockTitleBarWidget); _noteSearchDockWidget->setTitleBarWidget(_noteSearchDockTitleBarWidget); _noteFolderDockWidget->setTitleBarWidget(_noteFolderDockTitleBarWidget); _noteListDockWidget->setTitleBarWidget(_noteListDockTitleBarWidget); - _noteNavigationDockWidget->setTitleBarWidget( - _noteNavigationDockTitleBarWidget); + _noteNavigationDockWidget->setTitleBarWidget(_noteNavigationDockTitleBarWidget); if (!_noteEditIsCentralWidget) { _noteEditDockWidget->setTitleBarWidget(_noteEditDockTitleBarWidget); } _noteTagDockWidget->setTitleBarWidget(_noteTagDockTitleBarWidget); - _notePreviewDockWidget->setTitleBarWidget( - _notePreviewDockTitleBarWidget); + _notePreviewDockWidget->setTitleBarWidget(_notePreviewDockTitleBarWidget); _logDockWidget->setTitleBarWidget(_logDockTitleBarWidget); _scriptingDockWidget->setTitleBarWidget(_scriptingDockTitleBarWidget); @@ -10556,9 +10066,8 @@ void MainWindow::on_actionUnlock_panels_toggled(bool arg1) { * Creates a new workspace with asking for its name */ void MainWindow::on_actionStore_as_new_workspace_triggered() { - const QString name = QInputDialog::getText(this, tr("Create new workspace"), - tr("Workspace name:")) - .trimmed(); + const QString name = + QInputDialog::getText(this, tr("Create new workspace"), tr("Workspace name:")).trimmed(); if (name.isEmpty()) { return; @@ -10594,8 +10103,7 @@ bool MainWindow::createNewWorkspace(QString name) { settings.setValue(QStringLiteral("workspaces"), workspaces); settings.setValue(QStringLiteral("currentWorkspace"), uuid); - settings.setValue( - QStringLiteral("workspace-") + uuid + QStringLiteral("/name"), name); + settings.setValue(QStringLiteral("workspace-") + uuid + QStringLiteral("/name"), name); // store the new current workspace storeCurrentWorkspace(); @@ -10659,12 +10167,11 @@ void MainWindow::storeCurrentWorkspace() { QSettings settings; QString uuid = currentWorkspaceUuid(); + settings.setValue(QStringLiteral("workspace-") + uuid + QStringLiteral("/windowState"), + saveState()); settings.setValue( - QStringLiteral("workspace-") + uuid + QStringLiteral("/windowState"), - saveState()); - settings.setValue(QStringLiteral("workspace-") + uuid + - QStringLiteral("/noteSubFolderDockWidgetVisible"), - _noteSubFolderDockWidgetVisible); + QStringLiteral("workspace-") + uuid + QStringLiteral("/noteSubFolderDockWidgetVisible"), + _noteSubFolderDockWidgetVisible); } /** @@ -10706,10 +10213,9 @@ void MainWindow::restoreCurrentWorkspace() { updateWorkspaceLists(); } - restoreState(settings - .value(QStringLiteral("workspace-") + uuid + - QStringLiteral("/windowState")) - .toByteArray()); + restoreState( + settings.value(QStringLiteral("workspace-") + uuid + QStringLiteral("/windowState")) + .toByteArray()); // handle the visibility of the note subfolder panel handleNoteSubFolderVisibility(); @@ -10733,8 +10239,7 @@ void MainWindow::restoreCurrentWorkspace() { MetricsService::instance()->sendEventIfEnabled( QStringLiteral("app/initial-layout"), QStringLiteral("app"), QStringLiteral("initial-layout"), - settings.value(QStringLiteral("initialLayoutIdentifier")) - .toString()); + settings.value(QStringLiteral("initialLayoutIdentifier")).toString()); settings.remove(QStringLiteral("initialWorkspace")); centerAndResize(); @@ -10754,8 +10259,7 @@ void MainWindow::handleNoteSubFolderVisibility() const { // turn the subfolder dock widget on or off according to whether the // subfolders are enabled or not bool showSubfolders = NoteFolder::isCurrentShowSubfolders(); - _noteSubFolderDockWidget->setVisible(showSubfolders && - _noteSubFolderDockWidgetVisible); + _noteSubFolderDockWidget->setVisible(showSubfolders && _noteSubFolderDockWidgetVisible); } /** @@ -10788,8 +10292,7 @@ void MainWindow::on_actionRemove_current_workspace_triggered() { // ask for permission if (Utils::Gui::question(this, tr("Remove current workspace"), tr("Remove the current workspace?"), - QStringLiteral("remove-workspace")) != - QMessageBox::Yes) { + QStringLiteral("remove-workspace")) != QMessageBox::Yes) { return; } @@ -10821,14 +10324,12 @@ void MainWindow::on_actionRename_current_workspace_triggered() { } QSettings settings; - QString name = settings - .value(QStringLiteral("workspace-") + uuid + - QStringLiteral("/name")) - .toString(); + QString name = + settings.value(QStringLiteral("workspace-") + uuid + QStringLiteral("/name")).toString(); // ask for the new name - name = QInputDialog::getText(this, tr("Rename workspace"), - tr("Workspace name:"), QLineEdit::Normal, name) + name = QInputDialog::getText(this, tr("Rename workspace"), tr("Workspace name:"), + QLineEdit::Normal, name) .trimmed(); if (name.isEmpty()) { @@ -10836,8 +10337,7 @@ void MainWindow::on_actionRename_current_workspace_triggered() { } // rename the workspace - settings.setValue( - QStringLiteral("workspace-") + uuid + QStringLiteral("/name"), name); + settings.setValue(QStringLiteral("workspace-") + uuid + QStringLiteral("/name"), name); // update the menu and combo box updateWorkspaceLists(); @@ -10848,8 +10348,7 @@ void MainWindow::on_actionRename_current_workspace_triggered() { */ void MainWindow::on_actionSwitch_to_previous_workspace_triggered() { QSettings settings; - QString uuid = - settings.value(QStringLiteral("previousWorkspace")).toString(); + QString uuid = settings.value(QStringLiteral("previousWorkspace")).toString(); if (!uuid.isEmpty()) { setCurrentWorkspace(uuid); @@ -10878,13 +10377,13 @@ void MainWindow::on_actionShow_all_panels_triggered() { filterNotes(); } -static void loadAllActions(QMenu* menu, QVector<QPair<QString, QAction*>>& outActions) { +static void loadAllActions(QMenu *menu, QVector<QPair<QString, QAction *>> &outActions) { if (!menu) { return; } const auto menuActions = menu->actions(); - QVector<QPair<QString, QAction*>> actions; + QVector<QPair<QString, QAction *>> actions; actions.reserve(menuActions.size()); for (auto action : menuActions) { @@ -10917,7 +10416,7 @@ void MainWindow::on_actionFind_action_triggered() { auto menuBar = this->menuBar(); const auto menus = menuBar->actions(); - QVector<QPair<QString, QAction*>> actions; + QVector<QPair<QString, QAction *>> actions; for (auto subMenu : menus) { if (auto menu = subMenu->menu()) { loadAllActions(menu, actions); @@ -10960,12 +10459,9 @@ void MainWindow::on_actionSearch_text_on_the_web_triggered() { QSettings settings; typedef Utils::Misc::SearchEngine SearchEngine; int selectedSearchEngineId = - settings - .value(QStringLiteral("SearchEngineId"), - Utils::Misc::getDefaultSearchEngineId()) + settings.value(QStringLiteral("SearchEngineId"), Utils::Misc::getDefaultSearchEngineId()) .toInt(); - QHash<int, SearchEngine> SearchEngines = - Utils::Misc::getSearchEnginesHashMap(); + QHash<int, SearchEngine> SearchEngines = Utils::Misc::getSearchEnginesHashMap(); SearchEngine selectedEngine = SearchEngines.value(selectedSearchEngineId); QString searchEngineUrl = selectedEngine.searchUrl; QUrl url(searchEngineUrl + QUrl::toPercentEncoding(selectedText)); @@ -10988,14 +10484,13 @@ void MainWindow::noteEditCursorPositionChanged() { text = tr("%n chars", "characters", selectedText.count()) + " "; } - text += QString::number(cursor.block().blockNumber() + 1) + - QStringLiteral(":") + QString::number(cursor.positionInBlock() + 1); + text += QString::number(cursor.block().blockNumber() + 1) + QStringLiteral(":") + + QString::number(cursor.positionInBlock() + 1); _noteEditLineNumberLabel->setText(text); const bool autoSelect = - QSettings().value(QStringLiteral("navigationPanelAutoSelect"), true) - .toBool(); + QSettings().value(QStringLiteral("navigationPanelAutoSelect"), true).toBool(); if (autoSelect) { selectNavigationItemAtPosition(textEdit->textCursor().block().position()); } @@ -11010,14 +10505,12 @@ void MainWindow::on_actionDelete_line_triggered() { // if the note text edit doesn't have the focus delegate the default // shortcut to the widget with the focus if (!textEdit->hasFocus()) { - QKeyEvent *event = - new QKeyEvent(QEvent::KeyPress, Qt::Key_Backspace, Qt::AltModifier); + QKeyEvent *event = new QKeyEvent(QEvent::KeyPress, Qt::Key_Backspace, Qt::AltModifier); // we need a special fallback for QLineEdit because it seems to ignore // our event if (dynamic_cast<QLineEdit *>(QApplication::focusWidget()) != nullptr) { - auto *lineEdit = - dynamic_cast<QLineEdit *>(QApplication::focusWidget()); + auto *lineEdit = dynamic_cast<QLineEdit *>(QApplication::focusWidget()); lineEdit->clear(); } else { QApplication::postEvent(QApplication::focusWidget(), event); @@ -11050,14 +10543,12 @@ void MainWindow::on_actionDelete_word_triggered() { // if the note text edit doesn't have the focus delegate the default // shortcut to the widget with the focus if (!textEdit->hasFocus()) { - QKeyEvent *event = new QKeyEvent(QEvent::KeyPress, Qt::Key_Backspace, - Qt::ControlModifier); + QKeyEvent *event = new QKeyEvent(QEvent::KeyPress, Qt::Key_Backspace, Qt::ControlModifier); // we need a special fallback for QLineEdit because it seems to ignore // our event if (dynamic_cast<QLineEdit *>(QApplication::focusWidget()) != nullptr) { - auto *lineEdit = - dynamic_cast<QLineEdit *>(QApplication::focusWidget()); + auto *lineEdit = dynamic_cast<QLineEdit *>(QApplication::focusWidget()); lineEdit->cursorWordBackward(true); lineEdit->del(); } else { @@ -11123,9 +10614,7 @@ void MainWindow::updateNoteSortOrderSelectorVisibility(bool visible) { /** * Commits changes from the current note folder to git */ -void MainWindow::gitCommitCurrentNoteFolder() { - Utils::Git::commitCurrentNoteFolder(); -} +void MainWindow::gitCommitCurrentNoteFolder() { Utils::Git::commitCurrentNoteFolder(); } /** * Shows a git log of the current note @@ -11169,8 +10658,8 @@ void MainWindow::on_tagTreeWidget_itemExpanded(QTreeWidgetItem *item) { */ void MainWindow::storeTagTreeWidgetExpandState() const { // get all items - const auto allItems = ui->tagTreeWidget->findItems( - QLatin1String(""), Qt::MatchContains | Qt::MatchRecursive); + const auto allItems = + ui->tagTreeWidget->findItems(QLatin1String(""), Qt::MatchContains | Qt::MatchRecursive); QStringList expandedList; for (QTreeWidgetItem *item : allItems) { @@ -11206,14 +10695,12 @@ void MainWindow::updatePanelsSortOrder() { reloadNoteSubFolderTree(); // do not reload it again, it has already been reloaded when // updateNotesPanelSortOrder() was called - //reloadTagTree(); + // reloadTagTree(); } void MainWindow::updateNotesPanelSortOrder() { QSettings settings; - int sort = - settings.value(QStringLiteral("notesPanelSort"), SORT_BY_LAST_CHANGE) - .toInt(); + int sort = settings.value(QStringLiteral("notesPanelSort"), SORT_BY_LAST_CHANGE).toInt(); ui->actionAlphabetical->setChecked(sort == SORT_ALPHABETICAL); ui->actionBy_date->setChecked(sort == SORT_BY_LAST_CHANGE); @@ -11257,9 +10744,8 @@ void MainWindow::on_actionAllow_note_editing_triggered(bool checked) { ui->actionReplace_in_current_note->setEnabled(checked); _readOnlyButton->setHidden(checked); - ui->actionAllow_note_editing->setText(checked - ? tr("Disallow all note editing") - : tr("Allow all note editing")); + ui->actionAllow_note_editing->setText(checked ? tr("Disallow all note editing") + : tr("Allow all note editing")); } void MainWindow::allowNoteEditing() { @@ -11276,11 +10762,10 @@ bool MainWindow::doNoteEditingCheck() { return true; } - if (Utils::Gui::questionNoSkipOverride( - this, tr("Note editing disabled"), - tr("Note editing is currently disabled, do you " - "want to allow it again?"), - QStringLiteral("readonly-mode-allow")) == + if (Utils::Gui::questionNoSkipOverride(this, tr("Note editing disabled"), + tr("Note editing is currently disabled, do you " + "want to allow it again?"), + QStringLiteral("readonly-mode-allow")) == QMessageBox::Yes) { allowNoteEditing(); @@ -11331,34 +10816,30 @@ void MainWindow::automaticScriptUpdateCheck() { auto *dialog = new ScriptRepositoryDialog(this, true); // show a dialog once if a script update was found - QObject::connect( - dialog, - &ScriptRepositoryDialog::updateFound, - this, [this] () { - // we only want to run this once - if (_scriptUpdateFound) { - return; + QObject::connect(dialog, &ScriptRepositoryDialog::updateFound, this, [this]() { + // we only want to run this once + if (_scriptUpdateFound) { + return; + } + + _scriptUpdateFound = true; + showStatusBarMessage(tr("A script update was found!"), 4000); + + // open the update question dialog in another thread so the dialog + // can be deleted meanwhile + QTimer::singleShot(100, this, [this]() { + if (Utils::Gui::question(this, tr("Script updates"), + tr("Updates to your scripts were found in the script " + "repository! Do you want to update them?"), + "auto-script-update") == QMessageBox::Yes) { + on_actionCheck_for_script_updates_triggered(); } - - _scriptUpdateFound = true; - showStatusBarMessage(tr("A script update was found!"), 4000); - - // open the update question dialog in another thread so the dialog - // can be deleted meanwhile - QTimer::singleShot(100, this, [this] () { - if (Utils::Gui::question( - this, tr("Script updates"), - tr("Updates to your scripts were found in the script " - "repository! Do you want to update them?"), - "auto-script-update") == QMessageBox::Yes) { - on_actionCheck_for_script_updates_triggered(); - } - }); }); + }); // delete the dialog after 10 sec - QTimer::singleShot(10000, this, [this, dialog] () { - delete(dialog); + QTimer::singleShot(10000, this, [this, dialog]() { + delete (dialog); if (_scriptUpdateFound) { _scriptUpdateFound = false; @@ -11369,8 +10850,7 @@ void MainWindow::automaticScriptUpdateCheck() { #endif } -void MainWindow::updateJumpToActionsAvailability() -{ +void MainWindow::updateJumpToActionsAvailability() { ui->actionJump_to_note_list_panel->setEnabled(ui->notesListFrame->isVisible()); ui->actionJump_to_note_subfolder_panel->setEnabled(ui->noteSubFolderFrame->isVisible()); ui->actionJump_to_tags_panel->setEnabled(ui->tagFrame->isVisible()); @@ -11392,8 +10872,7 @@ void MainWindow::on_actionJump_to_note_text_edit_triggered() { /** * Double-clicking a tag assigns the tag to the current note */ -void MainWindow::on_tagTreeWidget_itemDoubleClicked(QTreeWidgetItem *item, - int column) { +void MainWindow::on_tagTreeWidget_itemDoubleClicked(QTreeWidgetItem *item, int column) { Q_UNUSED(column) Tag tag = Tag::fetch(item->data(0, Qt::UserRole).toInt()); @@ -11427,14 +10906,13 @@ void MainWindow::on_tagTreeWidget_itemDoubleClicked(QTreeWidgetItem *item, /** * Double-clicking a note calls a hook */ -void MainWindow::on_noteTreeWidget_itemDoubleClicked(QTreeWidgetItem *item, - int column) { +void MainWindow::on_noteTreeWidget_itemDoubleClicked(QTreeWidgetItem *item, int column) { Q_UNUSED(item) Q_UNUSED(column) // call a script hook that a new note was double clicked - const bool hookFound = ScriptingService::instance()-> - callHandleNoteDoubleClickedHook(¤tNote); + const bool hookFound = + ScriptingService::instance()->callHandleNoteDoubleClickedHook(¤tNote); if (!hookFound) { openCurrentNoteInTab(); @@ -11480,17 +10958,15 @@ void MainWindow::on_actionManage_stored_attachments_triggered() { } void MainWindow::on_noteOperationsButton_clicked() { - QPoint globalPos = ui->noteOperationsButton->mapToGlobal( - QPoint(0, ui->noteOperationsButton->height())); + QPoint globalPos = + ui->noteOperationsButton->mapToGlobal(QPoint(0, ui->noteOperationsButton->height())); openNotesContextMenu(globalPos, true); } /** * Returns the text of the log widget */ -QString MainWindow::getLogText() { - return _logWidget->getLogText(); -} +QString MainWindow::getLogText() { return _logWidget->getLogText(); } /** * Enables all logging and shows the log panel @@ -11541,16 +11017,14 @@ void MainWindow::on_actionImport_notes_from_text_files_triggered() { QFile file(fileName); QFileInfo fileInfo(file); - progressDialog.setLabelText( - tr("Importing: %1").arg(fileInfo.fileName())); + progressDialog.setLabelText(tr("Importing: %1").arg(fileInfo.fileName())); file.open(QFile::ReadOnly | QFile::Text); QTextStream ts(&file); QString text = ts.readAll().trimmed(); QRegularExpressionMatch match = - QRegularExpression(QStringLiteral(R"(^.+\n=+)"), - QRegularExpression::MultilineOption) + QRegularExpression(QStringLiteral(R"(^.+\n=+)"), QRegularExpression::MultilineOption) .match(text); CreateNewNoteOptions options = CreateNewNoteOption::None; @@ -11585,8 +11059,7 @@ void MainWindow::on_actionCopy_headline_triggered() { // try regular headlines QRegularExpressionMatch match = - QRegularExpression(QStringLiteral(R"(^(.+)\n=+)"), - QRegularExpression::MultilineOption) + QRegularExpression(QStringLiteral(R"(^(.+)\n=+)"), QRegularExpression::MultilineOption) .match(noteText); QString headline; @@ -11594,9 +11067,9 @@ void MainWindow::on_actionCopy_headline_triggered() { headline = match.captured(1); } else { // try alternative headlines - match = QRegularExpression(QStringLiteral(R"(^#+ (.+)$)"), - QRegularExpression::MultilineOption) - .match(noteText); + match = + QRegularExpression(QStringLiteral(R"(^#+ (.+)$)"), QRegularExpression::MultilineOption) + .match(noteText); if (match.hasMatch()) { headline = match.captured(1); @@ -11606,9 +11079,8 @@ void MainWindow::on_actionCopy_headline_triggered() { if (!headline.isEmpty()) { QClipboard *clipboard = QApplication::clipboard(); clipboard->setText(headline); - showStatusBarMessage( - tr("Note headline '%1' was copied to the clipboard").arg(headline), - 3000); + showStatusBarMessage(tr("Note headline '%1' was copied to the clipboard").arg(headline), + 3000); } } @@ -11622,8 +11094,7 @@ void MainWindow::on_action_FormatTable_triggered() { */ void MainWindow::centerAndResize() { // get the dimension available on this screen - QSize availableSize = - QGuiApplication::primaryScreen()->availableGeometry().size(); + QSize availableSize = QGuiApplication::primaryScreen()->availableGeometry().size(); int width = availableSize.width(); int height = availableSize.height(); qDebug() << "Available dimensions " << width << "x" << height; @@ -11632,36 +11103,29 @@ void MainWindow::centerAndResize() { qDebug() << "Computed dimensions " << width << "x" << height; QSize newSize(width, height); - setGeometry(QStyle::alignedRect( - Qt::LeftToRight, Qt::AlignCenter, newSize, - QGuiApplication::primaryScreen()->availableGeometry())); + setGeometry(QStyle::alignedRect(Qt::LeftToRight, Qt::AlignCenter, newSize, + QGuiApplication::primaryScreen()->availableGeometry())); } /** * Filters navigation entries in the navigation tree widget */ void MainWindow::on_navigationLineEdit_textChanged(const QString &arg1) { - Utils::Gui::searchForTextInTreeWidget( - ui->navigationWidget, arg1, Utils::Gui::TreeWidgetSearchFlag::IntCheck); + Utils::Gui::searchForTextInTreeWidget(ui->navigationWidget, arg1, + Utils::Gui::TreeWidgetSearchFlag::IntCheck); } -const Note & MainWindow::getCurrentNote() { return currentNote; } +const Note &MainWindow::getCurrentNote() { return currentNote; } -void MainWindow::on_actionJump_to_note_list_panel_triggered() { - ui->noteTreeWidget->setFocus(); -} +void MainWindow::on_actionJump_to_note_list_panel_triggered() { ui->noteTreeWidget->setFocus(); } -void MainWindow::on_actionJump_to_tags_panel_triggered() { - ui->tagTreeWidget->setFocus(); -} +void MainWindow::on_actionJump_to_tags_panel_triggered() { ui->tagTreeWidget->setFocus(); } void MainWindow::on_actionJump_to_note_subfolder_panel_triggered() { ui->noteSubFolderTreeWidget->setFocus(); } -void MainWindow::on_actionActivate_context_menu_triggered() { - activateContextMenu(); -} +void MainWindow::on_actionActivate_context_menu_triggered() { activateContextMenu(); } void MainWindow::on_actionImport_bookmarks_from_server_triggered() { OwnCloudService *ownCloud = OwnCloudService::instance(); @@ -11702,13 +11166,11 @@ void MainWindow::on_actionToggle_fullscreen_triggered() { _leaveFullScreenModeButton->setFlat(true); _leaveFullScreenModeButton->setToolTip(tr("Leave full-screen mode")); - _leaveFullScreenModeButton->setStyleSheet( - QStringLiteral("QPushButton {padding: 0 5px}")); + _leaveFullScreenModeButton->setStyleSheet(QStringLiteral("QPushButton {padding: 0 5px}")); _leaveFullScreenModeButton->setIcon(QIcon::fromTheme( QStringLiteral("zoom-original"), - QIcon(QStringLiteral( - ":icons/breeze-qownnotes/16x16/zoom-original.svg")))); + QIcon(QStringLiteral(":icons/breeze-qownnotes/16x16/zoom-original.svg")))); connect(_leaveFullScreenModeButton, &QPushButton::clicked, this, &MainWindow::on_actionToggle_fullscreen_triggered); @@ -11765,19 +11227,15 @@ void MainWindow::loadDictionaryNames() { } _languageGroup->setExclusive(true); - connect(_languageGroup, &QActionGroup::triggered, this, - &MainWindow::onLanguageChanged); + connect(_languageGroup, &QActionGroup::triggered, this, &MainWindow::onLanguageChanged); // first add autoDetect - QAction *autoDetect = - ui->menuLanguages->addAction(tr("Automatically detect")); + QAction *autoDetect = ui->menuLanguages->addAction(tr("Automatically detect")); autoDetect->setCheckable(true); autoDetect->setData(QStringLiteral("auto")); autoDetect->setActionGroup(_languageGroup); QString prevLang = - settings - .value(QStringLiteral("spellCheckLanguage"), QStringLiteral("auto")) - .toString(); + settings.value(QStringLiteral("spellCheckLanguage"), QStringLiteral("auto")).toString(); // if only one dictionary found, disable auto detect if (languages.length() > 1) { if (prevLang == QStringLiteral("auto")) { @@ -11819,17 +11277,13 @@ void MainWindow::onLanguageChanged(QAction *action) { void MainWindow::loadSpellingBackends() { QSettings settings; - QString prevBackend = settings - .value(QStringLiteral("spellCheckBackend"), - QStringLiteral("Hunspell")) - .toString(); + QString prevBackend = + settings.value(QStringLiteral("spellCheckBackend"), QStringLiteral("Hunspell")).toString(); _spellBackendGroup->setExclusive(true); - connect(_spellBackendGroup, &QActionGroup::triggered, this, - &MainWindow::onBackendChanged); + connect(_spellBackendGroup, &QActionGroup::triggered, this, &MainWindow::onBackendChanged); - QAction *hs = - ui->menuSpelling_backend->addAction(QStringLiteral("Hunspell")); + QAction *hs = ui->menuSpelling_backend->addAction(QStringLiteral("Hunspell")); hs->setCheckable(true); hs->setData("Hunspell"); hs->setActionGroup(_spellBackendGroup); @@ -11877,8 +11331,7 @@ void MainWindow::on_encryptedNoteTextEdit_modificationChanged(bool arg1) { ui->encryptedNoteTextEdit->document()->setModified(false); - if (currentNote.storeNewDecryptedText( - ui->encryptedNoteTextEdit->toPlainText())) { + if (currentNote.storeNewDecryptedText(ui->encryptedNoteTextEdit->toPlainText())) { handleNoteTextChanged(); } } @@ -11888,15 +11341,11 @@ void MainWindow::on_actionEditorWidthCustom_triggered() { bool ok; int characters = QInputDialog::getInt( this, tr("Custom editor width"), tr("Characters:"), - settings - .value(QStringLiteral("DistractionFreeMode/editorWidthCustom"), 80) - .toInt(), - 20, 10000, 1, &ok); + settings.value(QStringLiteral("DistractionFreeMode/editorWidthCustom"), 80).toInt(), 20, + 10000, 1, &ok); if (ok) { - settings.setValue( - QStringLiteral("DistractionFreeMode/editorWidthCustom"), - characters); + settings.setValue(QStringLiteral("DistractionFreeMode/editorWidthCustom"), characters); } } @@ -11930,9 +11379,7 @@ void MainWindow::on_noteEditTabWidget_currentChanged(int index) { closeOrphanedTabs(); } -void MainWindow::on_noteEditTabWidget_tabCloseRequested(int index) { - removeNoteTab(index); -} +void MainWindow::on_noteEditTabWidget_tabCloseRequested(int index) { removeNoteTab(index); } void MainWindow::on_actionPrevious_note_tab_triggered() { int index = ui->noteEditTabWidget->currentIndex() - 1; @@ -11996,8 +11443,9 @@ QList<int> MainWindow::getNoteTabNoteIdList() const { } void MainWindow::on_noteEditTabWidget_tabBarDoubleClicked(int index) { - Utils::Gui::setTabWidgetTabSticky(ui->noteEditTabWidget, index, - !Utils::Gui::isTabWidgetTabSticky(ui->noteEditTabWidget, index)); + Utils::Gui::setTabWidgetTabSticky( + ui->noteEditTabWidget, index, + !Utils::Gui::isTabWidgetTabSticky(ui->noteEditTabWidget, index)); } void MainWindow::on_actionToggle_note_stickiness_of_current_tab_triggered() { @@ -12013,8 +11461,7 @@ void MainWindow::on_noteEditTabWidget_tabBarClicked(int index) { return; } - if (!_showNotesFromAllNoteSubFolders && - !currentNote.isInCurrentNoteSubFolder()) { + if (!_showNotesFromAllNoteSubFolders && !currentNote.isInCurrentNoteSubFolder()) { jumpToNoteSubFolder(currentNote.getNoteSubFolderId()); } } @@ -12032,20 +11479,17 @@ void MainWindow::showNoteEditTabWidgetContextMenu(const QPoint &point) { // Toggle note stickiness auto *stickAction = menu->addAction(tr("Toggle note stickiness")); - connect(stickAction, &QAction::triggered, this, [this, tabIndex]() { - on_noteEditTabWidget_tabBarDoubleClicked(tabIndex); - }); + connect(stickAction, &QAction::triggered, this, + [this, tabIndex]() { on_noteEditTabWidget_tabBarDoubleClicked(tabIndex); }); // Close other note tabs auto *closeAction = menu->addAction(tr("Close other note tabs")); connect(closeAction, &QAction::triggered, this, [this, tabIndex]() { const int maxIndex = ui->noteEditTabWidget->count() - 1; - const int keepNoteId = Utils::Gui::getTabWidgetNoteId( - ui->noteEditTabWidget, tabIndex); + const int keepNoteId = Utils::Gui::getTabWidgetNoteId(ui->noteEditTabWidget, tabIndex); for (int i = maxIndex; i >= 0; i--) { - const int noteId = Utils::Gui::getTabWidgetNoteId( - ui->noteEditTabWidget, i); + const int noteId = Utils::Gui::getTabWidgetNoteId(ui->noteEditTabWidget, i); if (noteId != keepNoteId) { removeNoteTab(i); @@ -12097,49 +11541,25 @@ void MainWindow::on_actionImport_notes_from_Joplin_triggered() { delete (dialog); } -QAction* MainWindow::reloadNoteFolderAction() -{ - return ui->action_Reload_note_folder; -} +QAction *MainWindow::reloadNoteFolderAction() { return ui->action_Reload_note_folder; } -QAction* MainWindow::newNoteAction() -{ - return ui->action_New_note; -} +QAction *MainWindow::newNoteAction() { return ui->action_New_note; } -QAction* MainWindow::insertTextLinkAction() -{ - return ui->actionInsert_text_link; -} +QAction *MainWindow::insertTextLinkAction() { return ui->actionInsert_text_link; } -QAction *MainWindow::searchTextOnWebAction() -{ - return ui->actionSearch_text_on_the_web; -} +QAction *MainWindow::searchTextOnWebAction() { return ui->actionSearch_text_on_the_web; } -QAction *MainWindow::pasteImageAction() -{ - return ui->actionPaste_image; -} +QAction *MainWindow::pasteImageAction() { return ui->actionPaste_image; } -QAction *MainWindow::autocompleteAction() -{ - return ui->actionAutocomplete; -} +QAction *MainWindow::autocompleteAction() { return ui->actionAutocomplete; } -QAction *MainWindow::splitNoteAtPosAction() -{ - return ui->actionSplit_note_at_cursor_position; -} +QAction *MainWindow::splitNoteAtPosAction() { return ui->actionSplit_note_at_cursor_position; } -QList<QAction*> MainWindow::customTextEditActions() -{ - return _noteTextEditContextMenuActions; -} +QList<QAction *> MainWindow::customTextEditActions() { return _noteTextEditContextMenuActions; } -void MainWindow::on_actionToggle_Always_on_top_triggered() -{ +void MainWindow::on_actionToggle_Always_on_top_triggered() { Qt::WindowFlags flags = windowFlags(); - setWindowFlags(flags.testFlag(Qt::WindowStaysOnTopHint) ? flags & (~Qt::WindowStaysOnTopHint) : flags | Qt::WindowStaysOnTopHint); + setWindowFlags(flags.testFlag(Qt::WindowStaysOnTopHint) ? flags & (~Qt::WindowStaysOnTopHint) + : flags | Qt::WindowStaysOnTopHint); show(); } diff --git a/src/mainwindow.h b/src/mainwindow.h index eb835840a..24b3bc8f8 100644 --- a/src/mainwindow.h +++ b/src/mainwindow.h @@ -81,8 +81,7 @@ class SettingsDialog; class MainWindow : public QMainWindow { Q_OBJECT - Q_PROPERTY(Note currentNote WRITE setCurrentNote MEMBER currentNote NOTIFY - currentNoteChanged) + Q_PROPERTY(Note currentNote WRITE setCurrentNote MEMBER currentNote NOTIFY currentNoteChanged) friend struct FileWatchDisabler; @@ -120,20 +119,17 @@ class MainWindow : public QMainWindow { void setCurrentNoteText(QString text); - void setCurrentNote(Note note, bool updateNoteText = true, - bool updateSelectedNote = true, + void setCurrentNote(Note note, bool updateNoteText = true, bool updateSelectedNote = true, bool addPreviousNoteToHistory = true); - void createNewNote(QString noteName = QString(), - bool withNameAppend = true); + void createNewNote(QString noteName = QString(), bool withNameAppend = true); void doSearchInNote(QString searchText); const Note &getCurrentNote(); - void createNewNote( - QString name, QString text, - CreateNewNoteOptions options = CreateNewNoteOption::None); + void createNewNote(QString name, QString text, + CreateNewNoteOptions options = CreateNewNoteOption::None); void openSettingsDialog(int page = 0, bool openScriptRepository = false); @@ -161,12 +157,10 @@ class MainWindow : public QMainWindow { void addCustomAction(const QString &identifier, const QString &menuText, const QString &buttonText, const QString &icon, - bool useInNoteEditContextMenu = false, - bool hideButtonInToolbar = false, + bool useInNoteEditContextMenu = false, bool hideButtonInToolbar = false, bool useInNoteListContextMenu = false); - void addScriptingLabel(const QString &identifier, - const QString &text = QString()); + void addScriptingLabel(const QString &identifier, const QString &text = QString()); void setScriptingLabelText(const QString &identifier, const QString &text); @@ -176,15 +170,15 @@ class MainWindow : public QMainWindow { QString selectedNoteTextEditText(); - void linkTagNameToCurrentNote(const QString &tagName, - bool linkToSelectedNotes = false); + void linkTagNameToCurrentNote(const QString &tagName, bool linkToSelectedNotes = false); Q_INVOKABLE void reloadTagTree(); Q_INVOKABLE void reloadNoteSubFolderTree(); - Q_INVOKABLE void buildNotesIndexAndLoadNoteDirectoryList( - bool forceBuild = false, bool forceLoad = false, bool reloadTabs = true); + Q_INVOKABLE void buildNotesIndexAndLoadNoteDirectoryList(bool forceBuild = false, + bool forceLoad = false, + bool reloadTabs = true); QVector<Note> selectedNotes(); @@ -244,8 +238,7 @@ class MainWindow : public QMainWindow { void storeUpdatedNotesToDisk(); - bool changeNoteFolder(const int noteFolderId, - const bool forceChange = false); + bool changeNoteFolder(const int noteFolderId, const bool forceChange = false); void allowNoteEditing(); @@ -253,7 +246,7 @@ class MainWindow : public QMainWindow { void openSelectedNotesInTab(); - void openNoteInTab(const Note& note); + void openNoteInTab(const Note ¬e); void openCurrentNoteInTab(); @@ -429,8 +422,7 @@ class MainWindow : public QMainWindow { void on_tagTreeWidget_itemChanged(QTreeWidgetItem *item, int column); - void on_tagTreeWidget_currentItemChanged(QTreeWidgetItem *current, - QTreeWidgetItem *previous); + void on_tagTreeWidget_currentItemChanged(QTreeWidgetItem *current, QTreeWidgetItem *previous); void on_tagTreeWidget_itemSelectionChanged(); @@ -478,8 +470,7 @@ class MainWindow : public QMainWindow { void on_actionShow_status_bar_triggered(bool checked); - void on_noteTreeWidget_currentItemChanged(QTreeWidgetItem *current, - QTreeWidgetItem *previous); + void on_noteTreeWidget_currentItemChanged(QTreeWidgetItem *current, QTreeWidgetItem *previous); void on_noteTreeWidget_customContextMenuRequested(const QPoint pos); @@ -689,7 +680,7 @@ class MainWindow : public QMainWindow { void on_actionToggle_Always_on_top_triggered(); -public: + public: /** Settings access **/ static bool isInDistractionFreeMode(); void setShowNotesFromAllNoteSubFolders(bool show); @@ -697,7 +688,7 @@ public: bool doNoteEditingCheck(); /** Actions **/ -public: + public: QAction *newNoteAction(); QAction *reloadNoteFolderAction(); QAction *insertTextLinkAction(); @@ -705,20 +696,20 @@ public: QAction *pasteImageAction(); QAction *autocompleteAction(); QAction *splitNoteAtPosAction(); - QList<QAction*> customTextEditActions(); + QList<QAction *> customTextEditActions(); -public: + public: /** export / print **/ void printTextDocument(QTextDocument *textDocument); void exportNoteAsPDF(QTextDocument *doc); int getMaxImageWidth() const; -public: + public: void clearNoteDirectoryWatcher(); void updateNoteDirectoryWatcher(); -private: + private: Ui::MainWindow *ui; QString notesPath; QFileSystemWatcher noteDirectoryWatcher; @@ -852,8 +843,7 @@ private: void loadNoteFolderListMenu(); - void storeRecentNoteFolder(const QString &addFolderName, - const QString &removeFolderName); + void storeRecentNoteFolder(const QString &addFolderName, const QString &removeFolderName); void storeSettings(); @@ -881,8 +871,7 @@ private: void updateNoteEncryptionUI(); - void askForEncryptedNotePasswordIfNeeded( - const QString &additionalText = QString()); + void askForEncryptedNotePasswordIfNeeded(const QString &additionalText = QString()); void showAppMetricsNotificationIfNeeded(); @@ -934,15 +923,13 @@ private: void initToolbars(); - void buildTagTreeForParentItem(QTreeWidgetItem *parent = nullptr, - bool topLevel = false); + void buildTagTreeForParentItem(QTreeWidgetItem *parent = nullptr, bool topLevel = false); void buildTagMoveMenuTree(QMenu *parentMenu, int parentTagId = 0); void buildBulkNoteTagMenuTree(QMenu *parentMenu, int parentTagId = 0); - QTreeWidgetItem *addTagToTagTreeWidget(QTreeWidgetItem *parent, - const TagHeader &tag); + QTreeWidgetItem *addTagToTagTreeWidget(QTreeWidgetItem *parent, const TagHeader &tag); bool jumpToNoteName(const QString &name); @@ -964,8 +951,7 @@ private: void filterNotesByNoteSubFolders(); - bool addNoteToNoteTreeWidget(const Note ¬e, - QTreeWidgetItem *parent = nullptr); + bool addNoteToNoteTreeWidget(const Note ¬e, QTreeWidgetItem *parent = nullptr); QTreeWidgetItem *findNoteInNoteTreeWidget(const Note ¬e); @@ -978,9 +964,9 @@ private: void buildBulkNoteSubFolderMenuTree(QMenu *parentMenu, bool doCopy = true, int parentNoteSubFolderId = 0); - void buildBulkNoteFolderSubFolderMenuTree( - QMenu *parentMenu, bool doCopy, const QString &parentNoteSubFolderPath, - bool isRoot = true); + void buildBulkNoteFolderSubFolderMenuTree(QMenu *parentMenu, bool doCopy, + const QString &parentNoteSubFolderPath, + bool isRoot = true); void moveSelectedNotesToNoteSubFolder(const NoteSubFolder ¬eSubFolder); @@ -1050,17 +1036,14 @@ private: void selectAllNotesInTagTreeWidget() const; - void handleScriptingNoteTagging(Note note, const Tag &tag, - bool doRemove = false, + void handleScriptingNoteTagging(Note note, const Tag &tag, bool doRemove = false, bool triggerPostMethods = true); void handleScriptingNotesTagUpdating(); - void handleScriptingNotesTagRenaming(const Tag &tag, - const QString &newTagName); + void handleScriptingNotesTagRenaming(const Tag &tag, const QString &newTagName); - void handleScriptingNotesTagRemoving(const Tag &tag, - bool forBulkOperation = false); + void handleScriptingNotesTagRemoving(const Tag &tag, bool forBulkOperation = false); void directoryWatcherWorkaround(bool isNotesDirectoryWasModifiedDisabled, bool alsoHandleNotesWereModified = false); @@ -1075,13 +1058,11 @@ private: int getSelectedNotesCount() const; - void updateNoteTreeWidgetItem(const Note ¬e, - QTreeWidgetItem *noteItem = nullptr); + void updateNoteTreeWidgetItem(const Note ¬e, QTreeWidgetItem *noteItem = nullptr); void initFakeVim(QOwnNotesMarkdownTextEdit *noteTextEdit); - void openNotesContextMenu(const QPoint globalPos, - bool multiNoteMenuEntriesOnly = false); + void openNotesContextMenu(const QPoint globalPos, bool multiNoteMenuEntriesOnly = false); void updateCurrentNoteTextHash(); diff --git a/src/pch.h b/src/pch.h index cfcbaf5da..bf404047a 100644 --- a/src/pch.h +++ b/src/pch.h @@ -4,36 +4,34 @@ #if defined __cplusplus /* Add C++ includes here */ -#include <QDialog> -#include <QString> -#include <QPlainTextEdit> -#include <QWidget> -#include <QObject> -#include <QJsonObject> +#include <QDateTime> #include <QDebug> -#include <QSettings> -#include <QMainWindow> -#include <QList> -#include <QVector> -#include <QHash> -#include <QStringList> -#include <QRegularExpression> -#include <QSyntaxHighlighter> -#include <QMetaType> +#include <QDialog> #include <QDir> #include <QFileSystemWatcher> +#include <QHash> +#include <QJsonObject> +#include <QKeySequence> +#include <QLabel> +#include <QList> +#include <QLoggingCategory> #include <QMainWindow> +#include <QMetaType> +#include <QObject> +#include <QPair> +#include <QPlainTextEdit> +#include <QRegularExpression> +#include <QSettings> +#include <QString> +#include <QStringList> +#include <QSyntaxHighlighter> #include <QSystemTrayIcon> #include <QTimer> -#include <QKeySequence> -#include <QPair> -#include <QLoggingCategory> -#include <QDateTime> -#include <QLabel> - +#include <QVector> +#include <QWidget> #include <string> #include <utility> #endif -#endif // QOWNNOTES_PCH_H +#endif // QOWNNOTES_PCH_H diff --git a/src/services/cryptoservice.cpp b/src/services/cryptoservice.cpp index 1a2a33abf..ceb991c04 100644 --- a/src/services/cryptoservice.cpp +++ b/src/services/cryptoservice.cpp @@ -30,8 +30,7 @@ CryptoService::CryptoService(QObject *parent) : QObject(parent) { * The instance will be created if it doesn't exist. */ CryptoService *CryptoService::instance() { - auto *cryptoService = - qApp->property("cryptoService").value<CryptoService *>(); + auto *cryptoService = qApp->property("cryptoService").value<CryptoService *>(); if (cryptoService == nullptr) { cryptoService = createInstance(nullptr); @@ -46,8 +45,7 @@ CryptoService *CryptoService::instance() { CryptoService *CryptoService::createInstance(QObject *parent) { auto *cryptoService = new CryptoService(parent); - qApp->setProperty("cryptoService", - QVariant::fromValue<CryptoService *>(cryptoService)); + qApp->setProperty("cryptoService", QVariant::fromValue<CryptoService *>(cryptoService)); return cryptoService; } diff --git a/src/services/databaseservice.cpp b/src/services/databaseservice.cpp index 6e98aee3f..5fd42dbaa 100644 --- a/src/services/databaseservice.cpp +++ b/src/services/databaseservice.cpp @@ -28,8 +28,7 @@ DatabaseService::DatabaseService() = default; * @return */ QString DatabaseService::getDiskDatabasePath() { - QString databaseFileName = Utils::Misc::appDataPath() + - Utils::Misc::dirSeparator() + + QString databaseFileName = Utils::Misc::appDataPath() + Utils::Misc::dirSeparator() + QStringLiteral("QOwnNotes.sqlite"); qDebug() << __func__ << " - 'databaseFileName': " << databaseFileName; @@ -57,8 +56,7 @@ bool DatabaseService::removeDiskDatabase() { // remove the file bool result = file.remove(); - QString text = result ? QStringLiteral("Removed") - : QStringLiteral("Could not remove"); + QString text = result ? QStringLiteral("Removed") : QStringLiteral("Could not remove"); qWarning() << text + " database file: " << file.fileName(); return result; } @@ -98,15 +96,14 @@ bool DatabaseService::checkDiskDatabaseIntegrity() { } bool DatabaseService::createMemoryConnection() { - QSqlDatabase dbMemory = QSqlDatabase::addDatabase(QStringLiteral("QSQLITE"), - QStringLiteral("memory")); + QSqlDatabase dbMemory = + QSqlDatabase::addDatabase(QStringLiteral("QSQLITE"), QStringLiteral("memory")); dbMemory.setDatabaseName(QStringLiteral(":memory:")); if (!dbMemory.open()) { - QMessageBox::critical( - nullptr, QWidget::tr("Cannot open memory database"), - QWidget::tr("Unable to establish a memory database connection."), - QMessageBox::Ok); + QMessageBox::critical(nullptr, QWidget::tr("Cannot open memory database"), + QWidget::tr("Unable to establish a memory database connection."), + QMessageBox::Ok); return false; } @@ -114,19 +111,18 @@ bool DatabaseService::createMemoryConnection() { } bool DatabaseService::createDiskConnection() { - QSqlDatabase dbDisk = QSqlDatabase::addDatabase(QStringLiteral("QSQLITE"), - QStringLiteral("disk")); + QSqlDatabase dbDisk = + QSqlDatabase::addDatabase(QStringLiteral("QSQLITE"), QStringLiteral("disk")); QString path = getDiskDatabasePath(); dbDisk.setDatabaseName(path); if (!dbDisk.open()) { - QMessageBox::critical( - nullptr, QWidget::tr("Cannot open disk database"), - QWidget::tr("Unable to establish a database connection with " - "file '%1'.\nAre the folder and the file " - "writeable?") - .arg(path), - QMessageBox::Ok); + QMessageBox::critical(nullptr, QWidget::tr("Cannot open disk database"), + QWidget::tr("Unable to establish a database connection with " + "file '%1'.\nAre the folder and the file " + "writeable?") + .arg(path), + QMessageBox::Ok); return false; } @@ -137,20 +133,18 @@ bool DatabaseService::createNoteFolderConnection() { QSqlDatabase dbDisk = QSqlDatabase::contains(QStringLiteral("note_folder")) ? QSqlDatabase::database(QStringLiteral("note_folder")) - : QSqlDatabase::addDatabase(QStringLiteral("QSQLITE"), - QStringLiteral("note_folder")); + : QSqlDatabase::addDatabase(QStringLiteral("QSQLITE"), QStringLiteral("note_folder")); QString path = getNoteFolderDatabasePath(); dbDisk.setDatabaseName(path); if (!dbDisk.open()) { - QMessageBox::critical( - nullptr, QWidget::tr("Cannot open note folder database"), - QWidget::tr("Unable to establish a database connection with " - "file '%1'.\nAre the folder and the file " - "writeable?") - .arg(path), - QMessageBox::Ok); + QMessageBox::critical(nullptr, QWidget::tr("Cannot open note folder database"), + QWidget::tr("Unable to establish a database connection with " + "file '%1'.\nAre the folder and the file " + "writeable?") + .arg(path), + QMessageBox::Ok); return false; } @@ -168,9 +162,8 @@ bool DatabaseService::setupNoteFolderTables() { QStringLiteral("CREATE TABLE IF NOT EXISTS appData (" "name VARCHAR(255) PRIMARY KEY, " "value VARCHAR(255))")); - int version = getAppData(QStringLiteral("database_version"), - QStringLiteral("note_folder")) - .toInt(); + int version = + getAppData(QStringLiteral("database_version"), QStringLiteral("note_folder")).toInt(); int oldVersion = version; qDebug() << __func__ << " - 'database version': " << version; @@ -193,16 +186,15 @@ bool DatabaseService::setupNoteFolderTables() { "note_file_name VARCHAR(255)," "created DATETIME DEFAULT current_timestamp)")); - queryDisk.exec(QStringLiteral( - "CREATE UNIQUE INDEX IF NOT EXISTS idxUniqueTagNoteLink" - " ON noteTagLink (tag_id, note_file_name)")); + queryDisk.exec( + QStringLiteral("CREATE UNIQUE INDEX IF NOT EXISTS idxUniqueTagNoteLink" + " ON noteTagLink (tag_id, note_file_name)")); version = 1; } if (version < 2) { - queryDisk.exec( - QStringLiteral("ALTER TABLE tag ADD parent_id INTEGER DEFAULT 0")); + queryDisk.exec(QStringLiteral("ALTER TABLE tag ADD parent_id INTEGER DEFAULT 0")); queryDisk.exec( QStringLiteral("CREATE INDEX IF NOT EXISTS idxTagParent " "ON tag( parent_id )")); @@ -218,25 +210,22 @@ bool DatabaseService::setupNoteFolderTables() { } if (version < 4) { - queryDisk.exec(QStringLiteral( - "ALTER TABLE noteTagLink ADD note_sub_folder_path TEXT")); + queryDisk.exec(QStringLiteral("ALTER TABLE noteTagLink ADD note_sub_folder_path TEXT")); version = 4; } if (version < 5) { + queryDisk.exec(QStringLiteral("DROP INDEX IF EXISTS idxUniqueTagNoteLink")); queryDisk.exec( - QStringLiteral("DROP INDEX IF EXISTS idxUniqueTagNoteLink")); - queryDisk.exec(QStringLiteral( - "CREATE UNIQUE INDEX IF NOT EXISTS idxUniqueTagNoteLink " - "ON noteTagLink (tag_id, note_file_name, " - "note_sub_folder_path)")); + QStringLiteral("CREATE UNIQUE INDEX IF NOT EXISTS idxUniqueTagNoteLink " + "ON noteTagLink (tag_id, note_file_name, " + "note_sub_folder_path)")); version = 5; } if (version < 6) { // we need to add a `DEFAULT ''` to column note_sub_folder_path - queryDisk.exec( - QStringLiteral("ALTER TABLE noteTagLink RENAME TO _noteTagLink")); + queryDisk.exec(QStringLiteral("ALTER TABLE noteTagLink RENAME TO _noteTagLink")); queryDisk.exec( QStringLiteral("CREATE TABLE IF NOT EXISTS noteTagLink (" "id INTEGER PRIMARY KEY," @@ -250,12 +239,11 @@ bool DatabaseService::setupNoteFolderTables() { "SELECT tag_id, note_file_name, " "note_sub_folder_path, created " "FROM _noteTagLink ORDER BY id")); + queryDisk.exec(QStringLiteral("DROP INDEX IF EXISTS idxUniqueTagNoteLink")); queryDisk.exec( - QStringLiteral("DROP INDEX IF EXISTS idxUniqueTagNoteLink")); - queryDisk.exec(QStringLiteral( - "CREATE UNIQUE INDEX IF NOT EXISTS idxUniqueTagNoteLink " - "ON noteTagLink (tag_id, note_file_name, " - "note_sub_folder_path)")); + QStringLiteral("CREATE UNIQUE INDEX IF NOT EXISTS idxUniqueTagNoteLink " + "ON noteTagLink (tag_id, note_file_name, " + "note_sub_folder_path)")); queryDisk.exec(QStringLiteral("DROP TABLE _noteTagLink")); queryDisk.exec( QStringLiteral("UPDATE noteTagLink SET note_sub_folder_path = '' " @@ -276,8 +264,7 @@ bool DatabaseService::setupNoteFolderTables() { } if (version < 9) { - queryDisk.exec( - QStringLiteral("ALTER TABLE tag ADD dark_color VARCHAR(20)")); + queryDisk.exec(QStringLiteral("ALTER TABLE tag ADD dark_color VARCHAR(20)")); version = 9; } @@ -353,16 +340,16 @@ bool DatabaseService::setupNoteFolderTables() { if (version < 14) { // removing broken tag assignments from // https://github.com/pbek/QOwnNotes/issues/1510 - queryDisk.exec(QStringLiteral( - "DELETE FROM noteTagLink WHERE note_sub_folder_path IS NULL")); + queryDisk.exec( + QStringLiteral("DELETE FROM noteTagLink WHERE note_sub_folder_path IS NULL")); version = 14; } if (version < 15) { // https://github.com/pbek/QOwnNotes/issues/2292 - queryDisk.exec(QStringLiteral( - "ALTER TABLE noteTagLink ADD stale_date DATETIME DEFAULT NULL")); + queryDisk.exec( + QStringLiteral("ALTER TABLE noteTagLink ADD stale_date DATETIME DEFAULT NULL")); version = 15; } @@ -395,8 +382,7 @@ QSqlDatabase DatabaseService::getNoteFolderDatabase() { * * @param db */ -void DatabaseService::closeDatabaseConnection(QSqlDatabase& db, - QSqlQuery& query) { +void DatabaseService::closeDatabaseConnection(QSqlDatabase& db, QSqlQuery& query) { query.finish(); query.clear(); @@ -481,8 +467,7 @@ bool DatabaseService::setupTables() { queryDisk.exec( QStringLiteral("CREATE UNIQUE INDEX IF NOT EXISTS idxUrl " "ON calendarItem( url )")); - queryDisk.exec(QStringLiteral( - "ALTER TABLE calendarItem ADD completed_date DATETIME")); + queryDisk.exec(QStringLiteral("ALTER TABLE calendarItem ADD completed_date DATETIME")); queryDisk.exec( QStringLiteral("ALTER TABLE calendarItem " "ADD sort_priority INTEGER DEFAULT 0")); @@ -521,8 +506,7 @@ bool DatabaseService::setupTables() { } if (version < 7) { - queryDisk.exec( - QStringLiteral("ALTER TABLE noteFolder ADD active_tag_id INTEGER")); + queryDisk.exec(QStringLiteral("ALTER TABLE noteFolder ADD active_tag_id INTEGER")); version = 7; } @@ -560,16 +544,13 @@ bool DatabaseService::setupTables() { } if (version < 12) { - bool darkModeColors = - settings.value(QStringLiteral("darkModeColors")).toBool(); + bool darkModeColors = settings.value(QStringLiteral("darkModeColors")).toBool(); // set an initial schema key QString schemaKey = darkModeColors - ? QStringLiteral( - "EditorColorSchema-cdbf28fc-1ddc-4d13-bb21-6a4043316a2f") - : QStringLiteral( - "EditorColorSchema-6033d61b-cb96-46d5-a3a8-20d5172017eb"); + ? QStringLiteral("EditorColorSchema-cdbf28fc-1ddc-4d13-bb21-6a4043316a2f") + : QStringLiteral("EditorColorSchema-6033d61b-cb96-46d5-a3a8-20d5172017eb"); settings.setValue(QStringLiteral("Editor/CurrentSchemaKey"), schemaKey); version = 12; @@ -604,8 +585,7 @@ bool DatabaseService::setupTables() { settings.remove(QStringLiteral("dockWindowState")); settings.remove(QStringLiteral("verticalPreviewModeEnabled")); settings.remove(QStringLiteral("mainSplitterSizes")); - settings.remove( - QStringLiteral("DistractionFreeMode/mainSplitterSizes")); + settings.remove(QStringLiteral("DistractionFreeMode/mainSplitterSizes")); settings.remove(QStringLiteral("mainSplitterState-0-0-0-0")); settings.remove(QStringLiteral("mainSplitterState-0-0-0-1")); settings.remove(QStringLiteral("mainSplitterState-0-0-1-0")); @@ -632,8 +612,7 @@ bool DatabaseService::setupTables() { if (version < 16) { // remove some deprecated settings settings.remove(QStringLiteral("dockWindowGeometry")); - settings.remove( - QStringLiteral("MainWindow/showRecentNoteFolderInMainArea")); + settings.remove(QStringLiteral("MainWindow/showRecentNoteFolderInMainArea")); version = 16; } @@ -654,8 +633,7 @@ bool DatabaseService::setupTables() { // set a new markdownHighlightingEnabled setting settings.setValue( QStringLiteral("markdownHighlightingEnabled"), - settings.value(QStringLiteral("markdownHighlightingInterval"), 200) - .toInt() > 0); + settings.value(QStringLiteral("markdownHighlightingInterval"), 200).toInt() > 0); // remove the deprecated markdownHighlightingInterval setting settings.remove(QStringLiteral("markdownHighlightingInterval")); @@ -665,10 +643,8 @@ bool DatabaseService::setupTables() { if (version < 19) { // set the ownCloud support enabled setting - bool ownCloudEnabled = - OwnCloudService::hasOwnCloudSettings(false, true); - settings.setValue(QStringLiteral("ownCloud/supportEnabled"), - ownCloudEnabled); + bool ownCloudEnabled = OwnCloudService::hasOwnCloudSettings(false, true); + settings.setValue(QStringLiteral("ownCloud/supportEnabled"), ownCloudEnabled); version = 19; } @@ -685,32 +661,27 @@ bool DatabaseService::setupTables() { if (version < 21) { // migrate to the new Portuguese translation - QString locale = - settings.value(QStringLiteral("interfaceLanguage")).toString(); + QString locale = settings.value(QStringLiteral("interfaceLanguage")).toString(); if (locale == QStringLiteral("pt")) { - settings.setValue(QStringLiteral("interfaceLanguage"), - QStringLiteral("pt_BR")); + settings.setValue(QStringLiteral("interfaceLanguage"), QStringLiteral("pt_BR")); } version = 21; } if (version < 22) { - queryDisk.exec(QStringLiteral( - "ALTER TABLE noteFolder ADD use_git BOOLEAN DEFAULT 0")); + queryDisk.exec(QStringLiteral("ALTER TABLE noteFolder ADD use_git BOOLEAN DEFAULT 0")); version = 22; } if (version < 23) { - queryDisk.exec( - QStringLiteral("ALTER TABLE script ADD identifier VARCHAR(255)")); + queryDisk.exec(QStringLiteral("ALTER TABLE script ADD identifier VARCHAR(255)")); queryDisk.exec(QStringLiteral("ALTER TABLE script ADD info_json TEXT")); version = 23; } if (version < 24) { - queryDisk.exec(QStringLiteral( - "ALTER TABLE script ADD settings_variables_json TEXT")); + queryDisk.exec(QStringLiteral("ALTER TABLE script ADD settings_variables_json TEXT")); version = 24; } @@ -718,17 +689,16 @@ bool DatabaseService::setupTables() { // migrate old sort and order settings + set defaults if unset // if settings.s; if (settings.contains(QStringLiteral("SortingModeAlphabetically"))) { - bool sort = - settings.value(QStringLiteral("SortingModeAlphabetically")) - .toBool(); // read old setting + bool sort = settings.value(QStringLiteral("SortingModeAlphabetically")) + .toBool(); // read old setting settings.setValue(QStringLiteral("notesPanelSort"), sort ? SORT_ALPHABETICAL : SORT_BY_LAST_CHANGE); settings.remove(QStringLiteral("SortingModeAlphabetically")); } if (settings.contains(QStringLiteral("NoteSortOrder"))) { - int order = static_cast<Qt::SortOrder>( - settings.value(QStringLiteral("NoteSortOrder")).toInt()); + int order = + static_cast<Qt::SortOrder>(settings.value(QStringLiteral("NoteSortOrder")).toInt()); settings.setValue(QStringLiteral("notesPanelOrder"), order); // see defines in MainWindow.h settings.remove(QStringLiteral("NoteSortOrder")); @@ -736,20 +706,17 @@ bool DatabaseService::setupTables() { // set defaults for now settings if not set already if (!settings.contains(QStringLiteral("notesPanelSort"))) { - settings.value(QStringLiteral("notesPanelSort"), - SORT_BY_LAST_CHANGE); + settings.value(QStringLiteral("notesPanelSort"), SORT_BY_LAST_CHANGE); } if (!settings.contains(QStringLiteral("notesPanelOrder"))) { settings.value(QStringLiteral("notesPanelOrder"), ORDER_DESCENDING); } if (!settings.contains(QStringLiteral("noteSubfoldersPanelSort"))) { - settings.value(QStringLiteral("noteSubfoldersPanelSort"), - SORT_BY_LAST_CHANGE); + settings.value(QStringLiteral("noteSubfoldersPanelSort"), SORT_BY_LAST_CHANGE); } if (!settings.contains(QStringLiteral("noteSubfoldersOrder"))) { - settings.value(QStringLiteral("noteSubfoldersOrder"), - ORDER_ASCENDING); + settings.value(QStringLiteral("noteSubfoldersOrder"), ORDER_ASCENDING); } if (!settings.contains(QStringLiteral("tagsPanelSort"))) { @@ -817,25 +784,23 @@ bool DatabaseService::setupTables() { if (version < 31) { // preset cloud connections for all note folders - queryDisk.prepare( - QStringLiteral("UPDATE noteFolder SET cloud_connection_id = :id")); - queryDisk.bindValue(QStringLiteral(":id"), - CloudConnection::firstCloudConnection().getId()); + queryDisk.prepare(QStringLiteral("UPDATE noteFolder SET cloud_connection_id = :id")); + queryDisk.bindValue(QStringLiteral(":id"), CloudConnection::firstCloudConnection().getId()); queryDisk.exec(); version = 31; } if (version < 32) { - queryDisk.exec(QStringLiteral( - "ALTER TABLE calendarItem ADD related_uid VARCHAR(255)")); + queryDisk.exec(QStringLiteral("ALTER TABLE calendarItem ADD related_uid VARCHAR(255)")); version = 32; } if (version < 33) { - foreach(NoteFolder noteFolder, NoteFolder::fetchAll()) { - noteFolder.setSettingsValue(QStringLiteral("allowDifferentNoteFileName"), - settings.value(QStringLiteral("allowDifferentNoteFileName"))); + foreach (NoteFolder noteFolder, NoteFolder::fetchAll()) { + noteFolder.setSettingsValue( + QStringLiteral("allowDifferentNoteFileName"), + settings.value(QStringLiteral("allowDifferentNoteFileName"))); } settings.remove(QStringLiteral("allowDifferentNoteFileName")); @@ -845,15 +810,14 @@ bool DatabaseService::setupTables() { if (version < 34) { queryDisk.exec(QStringLiteral( - "ALTER TABLE cloudConnection ADD qownnotesapi_enabled BOOLEAN DEFAULT 1")); + "ALTER TABLE cloudConnection ADD qownnotesapi_enabled BOOLEAN DEFAULT 1")); version = 34; } if (version < 35) { // migrate setting with typo - settings.setValue( - QStringLiteral("Editor/removeTrailingSpaces"), - settings.value(QStringLiteral("Editor/removeTrainingSpaces")).toBool()); + settings.setValue(QStringLiteral("Editor/removeTrailingSpaces"), + settings.value(QStringLiteral("Editor/removeTrainingSpaces")).toBool()); settings.remove(QStringLiteral("Editor/removeTrainingSpaces")); version = 35; @@ -871,13 +835,12 @@ bool DatabaseService::setupTables() { if (version < 37) { // add "txt" and "md" to the note file extensions, so they can also be removed - auto extensions = settings.value( - QStringLiteral("customNoteFileExtensionList")).toStringList(); - extensions << "md" << "txt"; + auto extensions = + settings.value(QStringLiteral("customNoteFileExtensionList")).toStringList(); + extensions << "md" + << "txt"; - settings.setValue( - QStringLiteral("customNoteFileExtensionList"), - extensions); + settings.setValue(QStringLiteral("customNoteFileExtensionList"), extensions); version = 37; } @@ -886,40 +849,35 @@ bool DatabaseService::setupTables() { if (version < 39) { // migrate from customNoteFileExtensionList to noteFileExtensionList - auto extensions = settings.value( - QStringLiteral("customNoteFileExtensionList")).toStringList(); + auto extensions = + settings.value(QStringLiteral("customNoteFileExtensionList")).toStringList(); - settings.setValue( - QStringLiteral("noteFileExtensionList"), - extensions); + settings.setValue(QStringLiteral("noteFileExtensionList"), extensions); settings.remove(QStringLiteral("customNoteFileExtensionList")); version = 39; } if (version < 40) { - const auto bookmarksNoteName = settings.value( - QStringLiteral("webSocketServerService/bookmarksNoteName")).toString(); + const auto bookmarksNoteName = + settings.value(QStringLiteral("webSocketServerService/bookmarksNoteName")).toString(); // fix overwritten bookmarksNoteName if (bookmarksNoteName == QStringLiteral("Commands")) { - settings.setValue( - QStringLiteral("webSocketServerService/bookmarksNoteName"), - QStringLiteral("Bookmarks")); + settings.setValue(QStringLiteral("webSocketServerService/bookmarksNoteName"), + QStringLiteral("Bookmarks")); } version = 40; } if (version < 41) { - queryDisk.exec(QStringLiteral( - "ALTER TABLE cloudConnection ADD account_id VARCHAR(255)")); + queryDisk.exec(QStringLiteral("ALTER TABLE cloudConnection ADD account_id VARCHAR(255)")); version = 41; } if (version != oldVersion) { - setAppData(QStringLiteral("database_version"), - QString::number(version)); + setAppData(QStringLiteral("database_version"), QString::number(version)); } return true; @@ -938,13 +896,11 @@ bool DatabaseService::setAppData(const QString& name, const QString& value, return query.exec(); } -QString DatabaseService::getAppData(const QString& name, - const QString& connectionName) { +QString DatabaseService::getAppData(const QString& name, const QString& connectionName) { QSqlDatabase db = QSqlDatabase::database(connectionName); QSqlQuery query(db); - query.prepare( - QStringLiteral("SELECT value FROM appData WHERE name = :name")); + query.prepare(QStringLiteral("SELECT value FROM appData WHERE name = :name")); query.bindValue(QStringLiteral(":name"), name); if (!query.exec()) { @@ -963,18 +919,17 @@ QString DatabaseService::getAppData(const QString& name, * @return */ bool DatabaseService::mergeNoteFolderDatabase(const QString& path) { - QSqlDatabase mergeDB = QSqlDatabase::addDatabase( - QStringLiteral("QSQLITE"), QStringLiteral("note_folder_merge")); + QSqlDatabase mergeDB = + QSqlDatabase::addDatabase(QStringLiteral("QSQLITE"), QStringLiteral("note_folder_merge")); mergeDB.setDatabaseName(path); if (!mergeDB.open()) { - QMessageBox::critical( - nullptr, QWidget::tr("Cannot open database"), - QWidget::tr("Unable to establish a database connection with " - "note folder database to merge '%1'.\nAre the folder " - "and the file writeable?") - .arg(path), - QMessageBox::Ok); + QMessageBox::critical(nullptr, QWidget::tr("Cannot open database"), + QWidget::tr("Unable to establish a database connection with " + "note folder database to merge '%1'.\nAre the folder " + "and the file writeable?") + .arg(path), + QMessageBox::Ok); return false; } @@ -994,8 +949,8 @@ bool DatabaseService::mergeNoteFolderDatabase(const QString& path) { * * @return */ -QByteArray DatabaseService::generateDatabaseTableSha1Signature( - QSqlDatabase& db, const QString& table) { +QByteArray DatabaseService::generateDatabaseTableSha1Signature(QSqlDatabase& db, + const QString& table) { QCryptographicHash hash(QCryptographicHash::Sha1); QSqlQuery query(db); query.prepare(QStringLiteral("SELECT * FROM ") + table); diff --git a/src/services/databaseservice.h b/src/services/databaseservice.h index ef915408c..0077fa6fa 100644 --- a/src/services/databaseservice.h +++ b/src/services/databaseservice.h @@ -10,12 +10,10 @@ class DatabaseService { DatabaseService(); static bool createConnection(); static bool setupTables(); - static QString getAppData( - const QString& name, - const QString& connectionName = QStringLiteral("disk")); - static bool setAppData( - const QString& name, const QString& value, - const QString& connectionName = QStringLiteral("disk")); + static QString getAppData(const QString& name, + const QString& connectionName = QStringLiteral("disk")); + static bool setAppData(const QString& name, const QString& value, + const QString& connectionName = QStringLiteral("disk")); static bool reinitializeDiskDatabase(); static bool removeDiskDatabase(); static bool createNoteFolderConnection(); @@ -25,8 +23,7 @@ class DatabaseService { static void closeDatabaseConnection(QSqlDatabase& db, QSqlQuery& query); static QString getNoteFolderDatabasePath(); static bool mergeNoteFolderDatabase(const QString& path); - static QByteArray generateDatabaseTableSha1Signature(QSqlDatabase& db, - const QString& table); + static QByteArray generateDatabaseTableSha1Signature(QSqlDatabase& db, const QString& table); static bool checkDiskDatabaseIntegrity(); private: diff --git a/src/services/metricsservice.cpp b/src/services/metricsservice.cpp index 2ba46207e..646e7b267 100644 --- a/src/services/metricsservice.cpp +++ b/src/services/metricsservice.cpp @@ -18,8 +18,7 @@ MetricsService::MetricsService(QObject *parent) : QObject(parent) { siteId = 6; #endif - _piwikTracker = new PiwikTracker( - qApp, QUrl(QStringLiteral("https://p.qownnotes.org")), siteId); + _piwikTracker = new PiwikTracker(qApp, QUrl(QStringLiteral("https://p.qownnotes.org")), siteId); _piwikTracker->setCustomDimension(1, QStringLiteral(VERSION)); _piwikTracker->setCustomDimension(2, QLocale::system().name()); _piwikTracker->setCustomDimension(3, debug); @@ -27,8 +26,7 @@ MetricsService::MetricsService(QObject *parent) : QObject(parent) { #if (QT_VERSION >= QT_VERSION_CHECK(5, 4, 0)) _piwikTracker->setCustomDimension( - 7, QSysInfo::prettyProductName() + " (" + - QSysInfo::currentCpuArchitecture() + ")"); + 7, QSysInfo::prettyProductName() + " (" + QSysInfo::currentCpuArchitecture() + ")"); #endif } @@ -45,8 +43,7 @@ MetricsService *MetricsService::instance() { MetricsService *MetricsService::createInstance(QObject *parent) { auto *metricsService = new MetricsService(parent); - qApp->setProperty("metricsService", - QVariant::fromValue<MetricsService *>(metricsService)); + qApp->setProperty("metricsService", QVariant::fromValue<MetricsService *>(metricsService)); return metricsService; } @@ -55,25 +52,19 @@ void MetricsService::sendVisit(const QString &path, const QString &actionName) { _piwikTracker->sendVisit(path, actionName); } -void MetricsService::sendVisitIfEnabled(const QString &path, - const QString &actionName) { +void MetricsService::sendVisitIfEnabled(const QString &path, const QString &actionName) { QSettings settings; - if (!settings.value(QStringLiteral("appMetrics/disableTracking")) - .toBool()) { + if (!settings.value(QStringLiteral("appMetrics/disableTracking")).toBool()) { sendVisit(path, actionName); } } -void MetricsService::sendEventIfEnabled(const QString &path, - const QString &eventCategory, - const QString &eventAction, - const QString &eventName, +void MetricsService::sendEventIfEnabled(const QString &path, const QString &eventCategory, + const QString &eventAction, const QString &eventName, int eventValue) { QSettings settings; - if (!settings.value(QStringLiteral("appMetrics/disableTracking")) - .toBool()) { - _piwikTracker->sendEvent(path, eventCategory, eventAction, eventName, - eventValue); + if (!settings.value(QStringLiteral("appMetrics/disableTracking")).toBool()) { + _piwikTracker->sendEvent(path, eventCategory, eventAction, eventName, eventValue); } } @@ -82,8 +73,7 @@ void MetricsService::sendEventIfEnabled(const QString &path, */ void MetricsService::sendHeartbeat() { QSettings settings; - if (!settings.value(QStringLiteral("appMetrics/disableAppHeartbeat")) - .toBool()) { + if (!settings.value(QStringLiteral("appMetrics/disableAppHeartbeat")).toBool()) { // send a normal event the first time if (_firstHeartbeat) { _piwikTracker->sendVisit(QStringLiteral("app/heartbeat")); @@ -100,8 +90,7 @@ void MetricsService::sendHeartbeat() { void MetricsService::sendLocaleEvent() { QSettings settings; QString eventText = QLocale::system().name(); - QString settingsLocale = - settings.value(QStringLiteral("interfaceLanguage")).toString(); + QString settingsLocale = settings.value(QStringLiteral("interfaceLanguage")).toString(); if (!settingsLocale.isEmpty()) { eventText += " (" + settingsLocale + ")"; } diff --git a/src/services/metricsservice.h b/src/services/metricsservice.h index b0a8321a7..7bd716f30 100644 --- a/src/services/metricsservice.h +++ b/src/services/metricsservice.h @@ -12,13 +12,10 @@ class MetricsService : public QObject { public: explicit MetricsService(QObject *parent = 0); - void sendVisitIfEnabled(const QString &path = QString(), - const QString &actionName = QString()); - void sendVisit(const QString &path = QString(), - const QString &actionName = QString()); + void sendVisitIfEnabled(const QString &path = QString(), const QString &actionName = QString()); + void sendVisit(const QString &path = QString(), const QString &actionName = QString()); void sendEventIfEnabled(const QString &path, const QString &eventCategory, - const QString &eventAction, - const QString &eventName = QString(), + const QString &eventAction, const QString &eventName = QString(), int eventValue = 0); void sendHeartbeat(); static MetricsService *instance(); diff --git a/src/services/owncloudservice.cpp b/src/services/owncloudservice.cpp index ce571af86..d221ea4c1 100644 --- a/src/services/owncloudservice.cpp +++ b/src/services/owncloudservice.cpp @@ -7,12 +7,14 @@ #include <QBuffer> #include <QCoreApplication> #include <QDebug> +#include <QDesktopServices> #include <QDir> #include <QDomDocument> #include <QDomNodeList> #include <QEventLoop> #include <QJSEngine> #include <QJSValueIterator> +#include <QJsonDocument> #include <QMessageBox> #include <QNetworkAccessManager> #include <QNetworkCookieJar> @@ -23,8 +25,6 @@ #include <QStringBuilder> #include <QTimer> #include <QUrlQuery> -#include <QDesktopServices> -#include <QJsonDocument> #include "cryptoservice.h" #include "dialogs/serverbookmarksimportdialog.h" @@ -38,30 +38,25 @@ #include "libraries/versionnumber/versionnumber.h" #include "mainwindow.h" -const QString OwnCloudService::rootPath = - QStringLiteral("/index.php/apps/qownnotesapi/api/v1/"); +const QString OwnCloudService::rootPath = QStringLiteral("/index.php/apps/qownnotesapi/api/v1/"); const QString OwnCloudService::format = QStringLiteral("json"); const QString NS_DAV(QStringLiteral("DAV:")); -OwnCloudService::OwnCloudService(int cloudConnectionId, QObject *parent) - : QObject(parent) { +OwnCloudService::OwnCloudService(int cloudConnectionId, QObject *parent) : QObject(parent) { networkManager = new QNetworkAccessManager(this); calendarNetworkManager = new QNetworkAccessManager(this); - QObject::connect( - networkManager, - SIGNAL(authenticationRequired(QNetworkReply *, QAuthenticator *)), this, - SLOT(slotAuthenticationRequired(QNetworkReply *, QAuthenticator *))); + QObject::connect(networkManager, + SIGNAL(authenticationRequired(QNetworkReply *, QAuthenticator *)), this, + SLOT(slotAuthenticationRequired(QNetworkReply *, QAuthenticator *))); QObject::connect(networkManager, SIGNAL(finished(QNetworkReply *)), this, SLOT(slotReplyFinished(QNetworkReply *))); - QObject::connect( - calendarNetworkManager, - SIGNAL(authenticationRequired(QNetworkReply *, QAuthenticator *)), this, - SLOT(slotCalendarAuthenticationRequired(QNetworkReply *, - QAuthenticator *))); - QObject::connect(calendarNetworkManager, SIGNAL(finished(QNetworkReply *)), - this, SLOT(slotReplyFinished(QNetworkReply *))); + QObject::connect(calendarNetworkManager, + SIGNAL(authenticationRequired(QNetworkReply *, QAuthenticator *)), this, + SLOT(slotCalendarAuthenticationRequired(QNetworkReply *, QAuthenticator *))); + QObject::connect(calendarNetworkManager, SIGNAL(finished(QNetworkReply *)), this, + SLOT(slotReplyFinished(QNetworkReply *))); readSettings(cloudConnectionId); settingsDialog = nullptr; @@ -102,15 +97,12 @@ bool OwnCloudService::isTodoCalendarSupportEnabled() { bool OwnCloudService::isTodoSupportEnabled() { QSettings settings; int calendarBackend = - settings - .value(QStringLiteral("ownCloud/todoCalendarBackend"), - DefaultOwnCloudCalendar) + settings.value(QStringLiteral("ownCloud/todoCalendarBackend"), DefaultOwnCloudCalendar) .toInt(); if (calendarBackend == CalDAVCalendar) { QString todoCalendarServerUrl = - settings - .value(QStringLiteral("ownCloud/todoCalendarCalDAVServerUrl")) + settings.value(QStringLiteral("ownCloud/todoCalendarCalDAVServerUrl")) .toString() .trimmed(); return !todoCalendarServerUrl.isEmpty(); @@ -121,9 +113,9 @@ bool OwnCloudService::isTodoSupportEnabled() { void OwnCloudService::readSettings(int cloudConnectionId) { QSettings settings; - CloudConnection cloudConnection = - cloudConnectionId != -1 ? CloudConnection::fetch(cloudConnectionId) - : CloudConnection::currentCloudConnection(); + CloudConnection cloudConnection = cloudConnectionId != -1 + ? CloudConnection::fetch(cloudConnectionId) + : CloudConnection::currentCloudConnection(); qDebug() << "cloudConnection: " << cloudConnection; @@ -143,13 +135,11 @@ void OwnCloudService::readSettings(int cloudConnectionId) { // sharePath = "/ocs/v1.php/apps/files_sharing/api/v1/shares"; sharePath = QStringLiteral("/ocs/v2.php/apps/files_sharing/api/v1/shares"); bookmarkPath = QStringLiteral("/apps/bookmarks/public/rest/v2/bookmark"); - trashDeletePath = QStringLiteral("/remote.php/dav/trashbin/") % userName % - QStringLiteral("/trash"); + trashDeletePath = + QStringLiteral("/remote.php/dav/trashbin/") % userName % QStringLiteral("/trash"); int calendarBackend = - settings - .value(QStringLiteral("ownCloud/todoCalendarBackend"), - DefaultOwnCloudCalendar) + settings.value(QStringLiteral("ownCloud/todoCalendarBackend"), DefaultOwnCloudCalendar) .toInt(); QString calendarBackendString; @@ -177,45 +167,34 @@ void OwnCloudService::readSettings(int cloudConnectionId) { todoCalendarAccountId = todoCalendarCloudConnection.getUsername(); } - QString calendarPath = QStringLiteral("/remote.php/") % - calendarBackendString % - QStringLiteral("/calendars/") % - todoCalendarAccountId; - todoCalendarServerUrl = - todoCalendarCloudConnection.getServerUrl().isEmpty() - ? QString() - : todoCalendarCloudConnection.getServerUrl() % calendarPath; - todoCalendarServerUrlWithoutPath = - todoCalendarCloudConnection.getServerUrlWithoutPath(); - todoCalendarServerUrlPath = - todoCalendarCloudConnection.getServerUrlPath() % calendarPath; + QString calendarPath = QStringLiteral("/remote.php/") % calendarBackendString % + QStringLiteral("/calendars/") % todoCalendarAccountId; + todoCalendarServerUrl = todoCalendarCloudConnection.getServerUrl().isEmpty() + ? QString() + : todoCalendarCloudConnection.getServerUrl() % calendarPath; + todoCalendarServerUrlWithoutPath = todoCalendarCloudConnection.getServerUrlWithoutPath(); + todoCalendarServerUrlPath = todoCalendarCloudConnection.getServerUrlPath() % calendarPath; todoCalendarUsername = todoCalendarCloudConnection.getUsername(); todoCalendarPassword = todoCalendarCloudConnection.getPassword(); // if we are using a custom CalDAV server set the settings for it if (calendarBackend == OwnCloudService::CalDAVCalendar) { todoCalendarServerUrl = - settings - .value(QStringLiteral("ownCloud/todoCalendarCalDAVServerUrl")) + settings.value(QStringLiteral("ownCloud/todoCalendarCalDAVServerUrl")) .toString() .trimmed(); todoCalendarServerUrlPath = QUrl(todoCalendarServerUrl).path(); todoCalendarUsername = - settings - .value(QStringLiteral("ownCloud/todoCalendarCalDAVUsername")) - .toString(); + settings.value(QStringLiteral("ownCloud/todoCalendarCalDAVUsername")).toString(); todoCalendarPassword = CryptoService::instance()->decryptToString( - settings - .value(QStringLiteral("ownCloud/todoCalendarCalDAVPassword")) - .toString()); + settings.value(QStringLiteral("ownCloud/todoCalendarCalDAVPassword")).toString()); todoCalendarServerUrlWithoutPath = todoCalendarServerUrl; if (!todoCalendarServerUrlPath.isEmpty()) { // remove the path from the calendar server url todoCalendarServerUrlWithoutPath.replace( - QRegularExpression( - QRegularExpression::escape(todoCalendarServerUrlPath) % - QStringLiteral("$")), + QRegularExpression(QRegularExpression::escape(todoCalendarServerUrlPath) % + QStringLiteral("$")), QString()); } } @@ -225,32 +204,29 @@ QString OwnCloudService::webdavPath() { return QStringLiteral("/remote.php/dav/files/") + userName; } -void OwnCloudService::slotAuthenticationRequired( - QNetworkReply *reply, QAuthenticator *authenticator) { +void OwnCloudService::slotAuthenticationRequired(QNetworkReply *reply, + QAuthenticator *authenticator) { Q_UNUSED(authenticator) qWarning() << "Username and/or password incorrect"; #ifndef INTEGRATION_TESTS if (settingsDialog != nullptr) { - settingsDialog->setOKLabelData(3, tr("incorrect"), - SettingsDialog::Failure); - settingsDialog->setOKLabelData(4, tr("not connected"), - SettingsDialog::Failure); + settingsDialog->setOKLabelData(3, tr("incorrect"), SettingsDialog::Failure); + settingsDialog->setOKLabelData(4, tr("not connected"), SettingsDialog::Failure); } #endif reply->abort(); } -void OwnCloudService::slotCalendarAuthenticationRequired( - QNetworkReply *reply, QAuthenticator *authenticator) { +void OwnCloudService::slotCalendarAuthenticationRequired(QNetworkReply *reply, + QAuthenticator *authenticator) { Q_UNUSED(authenticator) qWarning() << "Calendar username and/or password incorrect"; if (!Utils::Gui::isMessageBoxPresent()) { - QMessageBox::warning( - nullptr, tr("Username / password error"), - tr("Your calendar username or password is incorrect!")); + QMessageBox::warning(nullptr, tr("Username / password error"), + tr("Your calendar username or password is incorrect!")); } reply->abort(); @@ -272,8 +248,8 @@ void OwnCloudService::slotReplyFinished(QNetworkReply *reply) { if (reply->error() != QNetworkReply::NoError) { // for error codes see // http://doc.qt.io/qt-5/qnetworkreply.html#NetworkError-enum - qWarning() << "QNetworkReply error " + QString::number(reply->error()) + - " from url " + url.toString() + ": " + qWarning() << "QNetworkReply error " + QString::number(reply->error()) + " from url " + + url.toString() + ": " << reply->errorString(); } @@ -310,25 +286,19 @@ void OwnCloudService::slotReplyFinished(QNetworkReply *reply) { qDebug() << "Reply from capabilities page"; if (data.startsWith(QStringLiteral("<?xml version="))) { - settingsDialog->setOKLabelData(3, tr("ok"), - SettingsDialog::OK); - settingsDialog->setOKLabelData(1, tr("ok"), - SettingsDialog::OK); + settingsDialog->setOKLabelData(3, tr("ok"), SettingsDialog::OK); + settingsDialog->setOKLabelData(1, tr("ok"), SettingsDialog::OK); } else { - settingsDialog->setOKLabelData(3, tr("not correct"), - SettingsDialog::Failure); + settingsDialog->setOKLabelData(3, tr("not correct"), SettingsDialog::Failure); } } else if (urlPath.endsWith(ownCloudTestPath)) { qDebug() << "Reply from ownCloud test page"; if (data.startsWith(QStringLiteral("<?xml version="))) { - settingsDialog->setOKLabelData(2, tr("ok"), - SettingsDialog::OK); - settingsDialog->setOKLabelData(1, tr("ok"), - SettingsDialog::OK); + settingsDialog->setOKLabelData(2, tr("ok"), SettingsDialog::OK); + settingsDialog->setOKLabelData(1, tr("ok"), SettingsDialog::OK); } else { - settingsDialog->setOKLabelData( - 2, tr("not detected"), SettingsDialog::Failure); + settingsDialog->setOKLabelData(2, tr("not detected"), SettingsDialog::Failure); } } else if (urlPath.endsWith(restoreTrashedNotePath)) { qDebug() << "Reply from ownCloud restore trashed note page"; @@ -337,8 +307,7 @@ void OwnCloudService::slotReplyFinished(QNetworkReply *reply) { urlPath.endsWith(todoCalendarServerUrlPath)) { qDebug() << "Reply from ownCloud calendar page" << data; - QList<CalDAVCalendarData> calendarDataList = - parseCalendarData(data); + QList<CalDAVCalendarData> calendarDataList = parseCalendarData(data); // qInfo() << "calendarDataList: " << calendarDataList; @@ -353,10 +322,9 @@ void OwnCloudService::slotReplyFinished(QNetworkReply *reply) { // qDebug() << data; // a workaround for a ownCloud error message - if (data.indexOf(QStringLiteral( - "<s:message>Unable to generate a URL for the named" - " route \"tasksplus.page.index\" as such route" - " does not exist.</s:message>")) > 20) { + if (data.indexOf(QStringLiteral("<s:message>Unable to generate a URL for the named" + " route \"tasksplus.page.index\" as such route" + " does not exist.</s:message>")) > 20) { data = QString(); } @@ -374,8 +342,8 @@ void OwnCloudService::slotReplyFinished(QNetworkReply *reply) { // fetch the calendar item, that was already stored // by loadTodoItems() - CalendarItem calItem = CalendarItem::fetchByUrlAndCalendar( - url.toString(), calendarName); + CalendarItem calItem = + CalendarItem::fetchByUrlAndCalendar(url.toString(), calendarName); if (calItem.isFetched()) { // update the item with the ics data bool wasUpdated = calItem.updateWithICSData(data); @@ -427,11 +395,9 @@ void OwnCloudService::slotReplyFinished(QNetworkReply *reply) { } if (!data.isEmpty()) { - settingsDialog->setOKLabelData(1, tr("ok"), - SettingsDialog::OK); + settingsDialog->setOKLabelData(1, tr("ok"), SettingsDialog::OK); } else { - settingsDialog->setOKLabelData(1, tr("not found"), - SettingsDialog::Failure); + settingsDialog->setOKLabelData(1, tr("not found"), SettingsDialog::Failure); } } } @@ -452,17 +418,12 @@ void OwnCloudService::checkAppInfo(QNetworkReply *reply) { QString notesPathExistsText = QStringLiteral("unknown"); #ifndef INTEGRATION_TESTS - bool appIsValid = - result.property(0).property(QStringLiteral("versioning")).toBool(); + bool appIsValid = result.property(0).property(QStringLiteral("versioning")).toBool(); #endif - QString appVersion = result.property(0) - .property(QStringLiteral("app_version")) - .toVariant() - .toString(); - QString serverVersion = result.property(0) - .property(QStringLiteral("server_version")) - .toVariant() - .toString(); + QString appVersion = + result.property(0).property(QStringLiteral("app_version")).toVariant().toString(); + QString serverVersion = + result.property(0).property(QStringLiteral("server_version")).toVariant().toString(); #ifndef INTEGRATION_TESTS if (!settingsDialog) { @@ -470,77 +431,60 @@ void OwnCloudService::checkAppInfo(QNetworkReply *reply) { } // reset to "unknown" in case we can't test if versions // and trash app are enabled - settingsDialog->setOKLabelData(6, tr("unknown"), - SettingsDialog::Unknown); - settingsDialog->setOKLabelData(7, tr("unknown"), - SettingsDialog::Unknown); + settingsDialog->setOKLabelData(6, tr("unknown"), SettingsDialog::Unknown); + settingsDialog->setOKLabelData(7, tr("unknown"), SettingsDialog::Unknown); if (!serverVersion.isEmpty()) { VersionNumber serverAppVersion = VersionNumber(appVersion); VersionNumber minAppVersion = VersionNumber(QOWNNOTESAPI_MIN_VERSION); if (minAppVersion > serverAppVersion) { - settingsDialog->setOKLabelData(4, - tr("version %1 too low").arg(appVersion), + settingsDialog->setOKLabelData(4, tr("version %1 too low").arg(appVersion), SettingsDialog::Warning); } else { - settingsDialog->setOKLabelData(4, tr("ok"), - SettingsDialog::OK); + settingsDialog->setOKLabelData(4, tr("ok"), SettingsDialog::OK); } // check if versions and trash app are enabled after QOwnNotesAPI v0.3.1 if (serverAppVersion >= VersionNumber(QStringLiteral("0.3.1"))) { bool versionsAppEnabled = - result.property(0) - .property(QStringLiteral("versions_app")) - .toBool(); - bool trashAppEnabled = result.property(0) - .property(QStringLiteral("trash_app")) - .toBool(); + result.property(0).property(QStringLiteral("versions_app")).toBool(); + bool trashAppEnabled = + result.property(0).property(QStringLiteral("trash_app")).toBool(); if (versionsAppEnabled) { - settingsDialog->setOKLabelData(6, tr("ok"), - SettingsDialog::OK); + settingsDialog->setOKLabelData(6, tr("ok"), SettingsDialog::OK); } else { - settingsDialog->setOKLabelData(6, tr("not enabled"), - SettingsDialog::Failure); + settingsDialog->setOKLabelData(6, tr("not enabled"), SettingsDialog::Failure); } if (trashAppEnabled) { - settingsDialog->setOKLabelData(7, tr("ok"), - SettingsDialog::OK); + settingsDialog->setOKLabelData(7, tr("ok"), SettingsDialog::OK); } else { - settingsDialog->setOKLabelData(7, tr("not enabled"), - SettingsDialog::Failure); + settingsDialog->setOKLabelData(7, tr("not enabled"), SettingsDialog::Failure); } } // check if notes path was found after QOwnNotesAPI v0.4. if (serverAppVersion >= VersionNumber(QStringLiteral("0.4.1"))) { bool notesPathExists = - result.property(0) - .property(QStringLiteral("notes_path_exists")) - .toBool(); - notesPathExistsText = notesPathExists ? QStringLiteral("yes") - : QStringLiteral("not found"); + result.property(0).property(QStringLiteral("notes_path_exists")).toBool(); + notesPathExistsText = + notesPathExists ? QStringLiteral("yes") : QStringLiteral("not found"); if (notesPathExists) { - settingsDialog->setOKLabelData(8, tr("ok"), - SettingsDialog::OK); + settingsDialog->setOKLabelData(8, tr("ok"), SettingsDialog::OK); } else { - settingsDialog->setOKLabelData(8, tr("not found"), - SettingsDialog::Failure); + settingsDialog->setOKLabelData(8, tr("not found"), SettingsDialog::Failure); qDebug() << __func__ << " - 'data': " << data; } } } else { - settingsDialog->setOKLabelData(4, tr("not connected"), - SettingsDialog::Failure); + settingsDialog->setOKLabelData(4, tr("not connected"), SettingsDialog::Failure); } // call callback in settings dialog - settingsDialog->connectTestCallback(appIsValid, appVersion, serverVersion, - notesPathExistsText, + settingsDialog->connectTestCallback(appIsValid, appVersion, serverVersion, notesPathExistsText, reply->errorString()); #endif @@ -562,10 +506,8 @@ void OwnCloudService::checkAppVersion(QNetworkReply *reply) { QJSEngine engine; QJSValue result = engine.evaluate(data); - QString appVersion = result.property(0) - .property(QStringLiteral("app_version")) - .toVariant() - .toString(); + QString appVersion = + result.property(0).property(QStringLiteral("app_version")).toVariant().toString(); if (appVersion.isEmpty()) { return; @@ -583,12 +525,11 @@ void OwnCloudService::checkAppVersion(QNetworkReply *reply) { return; } - QMessageBox::warning( - mainWindow, tr("API app version too low"), - tr("Please consider updating your QOwnNotesAPI app on your " - "server, your app version %1 is too low and may " - "cause troubles in QOwnNotes.") - .arg(appVersion)); + QMessageBox::warning(mainWindow, tr("API app version too low"), + tr("Please consider updating your QOwnNotesAPI app on your " + "server, your app version %1 is too low and may " + "cause troubles in QOwnNotes.") + .arg(appVersion)); } #endif @@ -674,8 +615,7 @@ void OwnCloudService::startAppVersionTest() { */ void OwnCloudService::ignoreSslErrorsIfAllowed(QNetworkReply *reply) { QSettings settings; - if (settings.value(QStringLiteral("networking/ignoreSSLErrors"), true) - .toBool()) { + if (settings.value(QStringLiteral("networking/ignoreSSLErrors"), true).toBool()) { QObject::connect(reply, SIGNAL(sslErrors(QList<QSslError>)), reply, SLOT(ignoreSslErrors())); } @@ -714,28 +654,24 @@ void OwnCloudService::settingsGetCalendarList(SettingsDialog *dialog) { auto *dataToSend = new QByteArray(body.toUtf8()); r.setHeader(QNetworkRequest::ContentLengthHeader, dataToSend->size()); - r.setHeader(QNetworkRequest::ContentTypeHeader, - QStringLiteral("application/xml")); + r.setHeader(QNetworkRequest::ContentTypeHeader, QStringLiteral("application/xml")); r.setRawHeader(QByteArray("Depth"), QByteArray("1")); auto *buffer = new QBuffer(dataToSend); - QNetworkReply *reply = - calendarNetworkManager->sendCustomRequest(r, "PROPFIND", buffer); + QNetworkReply *reply = calendarNetworkManager->sendCustomRequest(r, "PROPFIND", buffer); ignoreSslErrorsIfAllowed(reply); } /** * @brief Gets the task list from the ownCloud server for the task list dialog */ -void OwnCloudService::todoGetTodoList(const QString &calendarName, - TodoDialog *dialog) { +void OwnCloudService::todoGetTodoList(const QString &calendarName, TodoDialog *dialog) { this->todoDialog = dialog; this->calendarName = calendarName; QSettings settings; QStringList todoCalendarEnabledList = - settings.value(QStringLiteral("ownCloud/todoCalendarEnabledList")) - .toStringList(); + settings.value(QStringLiteral("ownCloud/todoCalendarEnabledList")).toStringList(); int index = todoCalendarEnabledList.indexOf(calendarName); // return if we did't find the calendar, this should not happen @@ -744,18 +680,16 @@ void OwnCloudService::todoGetTodoList(const QString &calendarName, } QStringList todoCalendarEnabledUrlList = - settings.value(QStringLiteral("ownCloud/todoCalendarEnabledUrlList")) - .toStringList(); + settings.value(QStringLiteral("ownCloud/todoCalendarEnabledUrlList")).toStringList(); // return if there are to few items in the url list if (todoCalendarEnabledUrlList.size() < todoCalendarEnabledList.size()) { return; } - QString calendarUrl = - settings.value(QStringLiteral("ownCloud/todoCalendarEnabledUrlList")) - .toStringList() - .at(index); + QString calendarUrl = settings.value(QStringLiteral("ownCloud/todoCalendarEnabledUrlList")) + .toStringList() + .at(index); QUrl url(calendarUrl); QNetworkRequest r(url); @@ -781,12 +715,10 @@ void OwnCloudService::todoGetTodoList(const QString &calendarName, auto *dataToSend = new QByteArray(body.toUtf8()); r.setHeader(QNetworkRequest::ContentLengthHeader, dataToSend->size()); - r.setHeader(QNetworkRequest::ContentTypeHeader, - QStringLiteral("application/xml")); + r.setHeader(QNetworkRequest::ContentTypeHeader, QStringLiteral("application/xml")); auto *buffer = new QBuffer(dataToSend); - QNetworkReply *reply = - calendarNetworkManager->sendCustomRequest(r, "REPORT", buffer); + QNetworkReply *reply = calendarNetworkManager->sendCustomRequest(r, "REPORT", buffer); ignoreSslErrorsIfAllowed(reply); } @@ -799,15 +731,13 @@ void OwnCloudService::shareNote(const Note ¬e, ShareDialog *dialog) { // return if no settings are set if (!hasOwnCloudSettings()) { - showOwnCloudMessage( - QString(), QStringLiteral("You need to setup your ownCloud server " - "to share notes")); + showOwnCloudMessage(QString(), QStringLiteral("You need to setup your ownCloud server " + "to share notes")); return; } QUrl url(serverUrl % sharePath); - QString path = NoteFolder::currentRemotePath() + - note.relativeNoteFilePath(QStringLiteral("/")); + QString path = NoteFolder::currentRemotePath() + note.relativeNoteFilePath(QStringLiteral("/")); QByteArray postData; // set to public link @@ -834,8 +764,7 @@ void OwnCloudService::shareNote(const Note ¬e, ShareDialog *dialog) { /** * Allow note editing on a shared note on Nextcloud */ -void OwnCloudService::setPermissionsOnSharedNote(const Note ¬e, - ShareDialog *dialog) { +void OwnCloudService::setPermissionsOnSharedNote(const Note ¬e, ShareDialog *dialog) { this->shareDialog = dialog; qDebug() << __func__ << " - 'note': " << note; @@ -845,17 +774,14 @@ void OwnCloudService::setPermissionsOnSharedNote(const Note ¬e, return; } - QUrl url(serverUrl % sharePath % QStringLiteral("/") % - QString::number(note.getShareId()) % + QUrl url(serverUrl % sharePath % QStringLiteral("/") % QString::number(note.getShareId()) % QStringLiteral("?format=xml")); -// QString path = NoteFolder::currentRemotePath() + -// note.relativeNoteFilePath(QStringLiteral("/")); + // QString path = NoteFolder::currentRemotePath() + + // note.relativeNoteFilePath(QStringLiteral("/")); QUrlQuery params; - params.addQueryItem(QStringLiteral("permissions"), - QString::number(note.getSharePermissions())); - params.addQueryItem(QStringLiteral("cid"), - QString::number(note.getShareId())); + params.addQueryItem(QStringLiteral("permissions"), QString::number(note.getSharePermissions())); + params.addQueryItem(QStringLiteral("cid"), QString::number(note.getShareId())); qDebug() << __func__ << " - 'url': " << url; qDebug() << __func__ << " - 'params': " << params.query(); @@ -883,14 +809,12 @@ void OwnCloudService::removeNoteShare(const Note ¬e, ShareDialog *dialog) { // return if no settings are set if (!hasOwnCloudSettings()) { - showOwnCloudMessage( - QString(), QStringLiteral("You need to setup your ownCloud server " - "to remove a note share")); + showOwnCloudMessage(QString(), QStringLiteral("You need to setup your ownCloud server " + "to remove a note share")); return; } - QUrl url(serverUrl % sharePath % QStringLiteral("/") % - QString::number(note.getShareId())); + QUrl url(serverUrl % sharePath % QStringLiteral("/") % QString::number(note.getShareId())); qDebug() << __func__ << " - 'url': " << url; @@ -968,28 +892,24 @@ void OwnCloudService::fetchBookmarks() { /** * @brief Removes a task list item from the ownCloud server */ -void OwnCloudService::removeCalendarItem(CalendarItem calItem, - TodoDialog *dialog) { +void OwnCloudService::removeCalendarItem(CalendarItem calItem, TodoDialog *dialog) { this->todoDialog = dialog; QUrl url(calItem.getUrl()); QNetworkRequest r(url); addCalendarAuthHeader(&r); - QNetworkReply *reply = - calendarNetworkManager->sendCustomRequest(r, "DELETE"); + QNetworkReply *reply = calendarNetworkManager->sendCustomRequest(r, "DELETE"); ignoreSslErrorsIfAllowed(reply); } /** * @brief Restores a note on the server */ -void OwnCloudService::restoreTrashedNoteOnServer(const QString &fileName, - int timestamp) { +void OwnCloudService::restoreTrashedNoteOnServer(const QString &fileName, int timestamp) { QUrl url(serverUrl % restoreTrashedNotePath); QString serverNotesPath = Utils::Misc::appendIfDoesNotEndWith( - NoteFolder::currentRemotePath() + - NoteSubFolder::activeNoteSubFolder().relativePath('/'), + NoteFolder::currentRemotePath() + NoteSubFolder::activeNoteSubFolder().relativePath('/'), QStringLiteral("/")); url.setUserName(userName); @@ -1018,22 +938,19 @@ void OwnCloudService::restoreTrashedNoteOnServer(const QString &fileName, /** * @brief Deletes a trashed note on the server and returns the status code */ -int OwnCloudService::deleteTrashedNoteOnServer(const QString &fileName, - int timestamp) { +int OwnCloudService::deleteTrashedNoteOnServer(const QString &fileName, int timestamp) { auto *manager = new QNetworkAccessManager(); QEventLoop loop; QTimer timer; timer.setSingleShot(true); QObject::connect(&timer, SIGNAL(timeout()), &loop, SLOT(quit())); - QObject::connect(manager, SIGNAL(finished(QNetworkReply *)), &loop, - SLOT(quit())); + QObject::connect(manager, SIGNAL(finished(QNetworkReply *)), &loop, SLOT(quit())); // 10 sec timeout for the request timer.start(10000); - QUrl url(serverUrl % trashDeletePath % QStringLiteral("/") % - QUrl::toPercentEncoding(fileName) % QStringLiteral(".d") % - QString::number(timestamp)); + QUrl url(serverUrl % trashDeletePath % QStringLiteral("/") % QUrl::toPercentEncoding(fileName) % + QStringLiteral(".d") % QString::number(timestamp)); qDebug() << __func__ << " - 'url': " << url; @@ -1052,8 +969,7 @@ int OwnCloudService::deleteTrashedNoteOnServer(const QString &fileName, // if we didn't get a timeout let us return the content if (timer.isActive()) { - statusCode = - reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(); + statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(); } reply->deleteLater(); @@ -1096,8 +1012,7 @@ void OwnCloudService::loadVersions(const QString &fileName) { void OwnCloudService::loadTrash() { QUrl url(serverUrl % trashListPath); QString serverNotesPath = - NoteFolder::currentRemotePath() + - NoteSubFolder::activeNoteSubFolder().relativePath('/'); + NoteFolder::currentRemotePath() + NoteSubFolder::activeNoteSubFolder().relativePath('/'); url.setUserName(userName); url.setPassword(password); @@ -1137,8 +1052,7 @@ void OwnCloudService::addAuthHeader(QNetworkRequest *r) { addGenericAuthHeader(r, userName, password); } -void OwnCloudService::addGenericAuthHeader(QNetworkRequest *r, - const QString &userName, +void OwnCloudService::addGenericAuthHeader(QNetworkRequest *r, const QString &userName, const QString &password) { if (r) { QString concatenated = userName % QStringLiteral(":") % password; @@ -1157,8 +1071,7 @@ void OwnCloudService::addGenericAuthHeader(QNetworkRequest *r, void OwnCloudService::addCalendarAuthHeader(QNetworkRequest *r) { if (r) { - QString concatenated = - todoCalendarUsername % QStringLiteral(":") % todoCalendarPassword; + QString concatenated = todoCalendarUsername % QStringLiteral(":") % todoCalendarPassword; QByteArray data = concatenated.toLocal8Bit().toBase64(); QString headerData = QStringLiteral("Basic ") % data; r->setRawHeader("Authorization", headerData.toLocal8Bit()); @@ -1172,15 +1085,13 @@ void OwnCloudService::addCalendarAuthHeader(QNetworkRequest *r) { /** * Checks if ownCloud settings are set */ -bool OwnCloudService::hasOwnCloudSettings(bool withEnabledCheck, - bool ignoreTableWarning) { +bool OwnCloudService::hasOwnCloudSettings(bool withEnabledCheck, bool ignoreTableWarning) { if (withEnabledCheck && !isOwnCloudSupportEnabled()) { return false; } QSettings settings; - CloudConnection cloudConnection = - CloudConnection::currentCloudConnection(ignoreTableWarning); + CloudConnection cloudConnection = CloudConnection::currentCloudConnection(ignoreTableWarning); QString serverUrl = cloudConnection.getServerUrl(); QString userName = cloudConnection.getUsername(); @@ -1194,15 +1105,13 @@ bool OwnCloudService::hasOwnCloudSettings(bool withEnabledCheck, */ void OwnCloudService::showOwnCloudServerErrorMessage(const QString &message, bool withSettingsButton) { - QString headline = Utils::Misc::replaceOwnCloudText( - tr("ownCloud server connection error")); - QString text = message.isEmpty() - ? QStringLiteral( - "Cannot connect to your ownCloud server! " - "Please check your ownCloud configuration.") - : tr("ownCloud server error: <strong>%1</strong><br />" - "Please check your ownCloud configuration.") - .arg(message); + QString headline = Utils::Misc::replaceOwnCloudText(tr("ownCloud server connection error")); + QString text = message.isEmpty() ? QStringLiteral( + "Cannot connect to your ownCloud server! " + "Please check your ownCloud configuration.") + : tr("ownCloud server error: <strong>%1</strong><br />" + "Please check your ownCloud configuration.") + .arg(message); text = Utils::Misc::replaceOwnCloudText(text); @@ -1219,8 +1128,7 @@ void OwnCloudService::showOwnCloudMessage(QString headline, QString message, } if (message.isEmpty()) { - message = Utils::Misc::replaceOwnCloudText( - tr("You need to setup your ownCloud server!")); + message = Utils::Misc::replaceOwnCloudText(tr("You need to setup your ownCloud server!")); } // don't show an actual message box if there already is one present on @@ -1231,9 +1139,8 @@ void OwnCloudService::showOwnCloudMessage(QString headline, QString message, } if (withSettingsButton) { - if (QMessageBox::warning(nullptr, headline, message, - tr("Open &settings"), tr("&Cancel"), QString(), - 0, 1) == 0) { + if (QMessageBox::warning(nullptr, headline, message, tr("Open &settings"), tr("&Cancel"), + QString(), 0, 1) == 0) { #ifndef INTEGRATION_TESTS MainWindow *mainWindow = MainWindow::instance(); @@ -1251,8 +1158,7 @@ void OwnCloudService::showOwnCloudMessage(QString headline, QString message, * Returns the global OwnCloudService instance */ OwnCloudService *OwnCloudService::instance(bool reset, int cloudConnectionId) { - auto *instance = - qApp->property("ownCloudService").value<OwnCloudService *>(); + auto *instance = qApp->property("ownCloudService").value<OwnCloudService *>(); // OwnCloudService::settingsGetFileList would need the reset, but clearing // the cookie jar also helped @@ -1268,8 +1174,7 @@ OwnCloudService *OwnCloudService::instance(bool reset, int cloudConnectionId) { if (instance == nullptr) { instance = new OwnCloudService(cloudConnectionId); - qApp->setProperty("ownCloudService", - QVariant::fromValue<OwnCloudService *>(instance)); + qApp->setProperty("ownCloudService", QVariant::fromValue<OwnCloudService *>(instance)); } else { if (reset) { instance->resetNetworkManagerCookieJar(); @@ -1291,8 +1196,7 @@ OwnCloudService *OwnCloudService::instance(bool reset, int cloudConnectionId) { void OwnCloudService::handleVersionsLoading(QString data) { #ifndef INTEGRATION_TESTS MainWindow::instance()->enableShowVersionsButton(); - MainWindow::instance()->showStatusBarMessage(tr("Done with loading note versions"), - 2000); + MainWindow::instance()->showStatusBarMessage(tr("Done with loading note versions"), 2000); #endif // check if we get any data at all @@ -1310,10 +1214,7 @@ void OwnCloudService::handleVersionsLoading(QString data) { // get the information if versioning is available // we are casting to QVariant first because otherwise we might get a // "undefined" string if "message" is not set - QString message = result.property(0) - .property(QStringLiteral("message")) - .toVariant() - .toString(); + QString message = result.property(0).property(QStringLiteral("message")).toVariant().toString(); // check if we got an error message if (!message.isEmpty()) { @@ -1322,10 +1223,8 @@ void OwnCloudService::handleVersionsLoading(QString data) { } // get the filename to check if everything is all right - QString fileName = result.property(0) - .property(QStringLiteral("file_name")) - .toVariant() - .toString(); + QString fileName = + result.property(0).property(QStringLiteral("file_name")).toVariant().toString(); // get the versions QJSValue versions = result.property(0).property(QStringLiteral("versions")); @@ -1333,12 +1232,10 @@ void OwnCloudService::handleVersionsLoading(QString data) { // check if we got no useful data, we also need to do this to prevent // crashes - if (fileName.isEmpty() || !versionsIterator.hasNext() || - versions.toString().isEmpty()) { - QMessageBox::information( - nullptr, tr("No versions found"), - tr("There are no versions for this note or the note wasn't " - "found on the server.")); + if (fileName.isEmpty() || !versionsIterator.hasNext() || versions.toString().isEmpty()) { + QMessageBox::information(nullptr, tr("No versions found"), + tr("There are no versions for this note or the note wasn't " + "found on the server.")); return; } @@ -1357,8 +1254,7 @@ void OwnCloudService::handleVersionsLoading(QString data) { void OwnCloudService::handleTrashedLoading(QString data) { #ifndef INTEGRATION_TESTS MainWindow::instance()->enableShowTrashButton(); - MainWindow::instance()->showStatusBarMessage(tr("Done with loading trashed notes"), - 2000); + MainWindow::instance()->showStatusBarMessage(tr("Done with loading trashed notes"), 2000); #endif // check if we get any data at all @@ -1376,10 +1272,7 @@ void OwnCloudService::handleTrashedLoading(QString data) { // get a possible error messages // we are casting to QVariant first because otherwise we might get a // "undefined" string if "message" is not set - QString message = result.property(0) - .property(QStringLiteral("message")) - .toVariant() - .toString(); + QString message = result.property(0).property(QStringLiteral("message")).toVariant().toString(); // check if we got an error message if (!message.isEmpty()) { @@ -1388,8 +1281,7 @@ void OwnCloudService::handleTrashedLoading(QString data) { } // get the directory to check if everything is all right - QString directory = - result.property(0).property(QStringLiteral("directory")).toString(); + QString directory = result.property(0).property(QStringLiteral("directory")).toString(); // check if we got no useful data if (directory.isEmpty()) { @@ -1436,8 +1328,7 @@ QList<CalDAVCalendarData> OwnCloudService::parseCalendarData(QString &data) { doc.setContent(data, true); - QDomNodeList errorNodes = - doc.elementsByTagNameNS(NS_DAV, QStringLiteral("error")); + QDomNodeList errorNodes = doc.elementsByTagNameNS(NS_DAV, QStringLiteral("error")); // check if there was an error returned by the CalDAV server for (int i = 0; i < errorNodes.length(); ++i) { @@ -1451,11 +1342,10 @@ QList<CalDAVCalendarData> OwnCloudService::parseCalendarData(QString &data) { QDomNode typeNode = typeNodes.at(j); QString typeString = typeNode.toElement().tagName(); if (typeString == QStringLiteral("message")) { - QMessageBox::critical( - 0, tr("Error while loading todo lists!"), - tr("Error message from your " - "CalDAV server: <strong>%1</strong>") - .arg(typeNode.toElement().text())); + QMessageBox::critical(0, tr("Error while loading todo lists!"), + tr("Error message from your " + "CalDAV server: <strong>%1</strong>") + .arg(typeNode.toElement().text())); return resultList; } @@ -1466,18 +1356,16 @@ QList<CalDAVCalendarData> OwnCloudService::parseCalendarData(QString &data) { QSettings settings; bool ignoreNonTodoCalendars = - settings.value(QStringLiteral("ownCloud/ignoreNonTodoCalendars"), true) - .toBool(); + settings.value(QStringLiteral("ownCloud/ignoreNonTodoCalendars"), true).toBool(); // loop all response blocks - QDomNodeList responseNodes = - doc.elementsByTagNameNS(NS_DAV, QStringLiteral("response")); + QDomNodeList responseNodes = doc.elementsByTagNameNS(NS_DAV, QStringLiteral("response")); for (int i = 0; i < responseNodes.length(); ++i) { QDomNode responseNode = responseNodes.at(i); if (responseNode.isElement()) { QDomElement elem = responseNode.toElement(); - QDomNodeList resourceTypeNodes = elem.elementsByTagNameNS( - NS_DAV, QStringLiteral("resourcetype")); + QDomNodeList resourceTypeNodes = + elem.elementsByTagNameNS(NS_DAV, QStringLiteral("resourcetype")); if (resourceTypeNodes.length()) { QDomNodeList typeNodes = resourceTypeNodes.at(0).childNodes(); for (int j = 0; j < typeNodes.length(); ++j) { @@ -1495,21 +1383,16 @@ QList<CalDAVCalendarData> OwnCloudService::parseCalendarData(QString &data) { QStringLiteral("supported-calendar-component-set")); bool isTodoCalendar = false; if (componentSetNodes.length()) { - for (int k = 0; k < componentSetNodes.length(); - ++k) { - QDomNodeList componentSets = - componentSetNodes.at(k).childNodes(); + for (int k = 0; k < componentSetNodes.length(); ++k) { + QDomNodeList componentSets = componentSetNodes.at(k).childNodes(); if (componentSets.length()) { - for (int l = 0; l < componentSets.length(); - ++l) { - QDomNode componentSet = - componentSets.at(l); + for (int l = 0; l < componentSets.length(); ++l) { + QDomNode componentSet = componentSets.at(l); QString componentSetString = componentSet.toElement().attribute( QStringLiteral("name")); - if (componentSetString == - QStringLiteral("VTODO")) { + if (componentSetString == QStringLiteral("VTODO")) { isTodoCalendar = true; } } @@ -1525,8 +1408,8 @@ QList<CalDAVCalendarData> OwnCloudService::parseCalendarData(QString &data) { CalDAVCalendarData calendarData = CalDAVCalendarData(); // add the href to our result list - QDomNodeList hrefNodes = elem.elementsByTagNameNS( - NS_DAV, QStringLiteral("href")); + QDomNodeList hrefNodes = + elem.elementsByTagNameNS(NS_DAV, QStringLiteral("href")); if (hrefNodes.length()) { const QString href = hrefNodes.at(0).toElement().text(); @@ -1537,11 +1420,10 @@ QList<CalDAVCalendarData> OwnCloudService::parseCalendarData(QString &data) { calendarData.url = href; } - QDomNodeList displayNameNodes = elem.elementsByTagNameNS( - NS_DAV, QStringLiteral("displayname")); + QDomNodeList displayNameNodes = + elem.elementsByTagNameNS(NS_DAV, QStringLiteral("displayname")); if (displayNameNodes.length()) { - const QString displayName = - displayNameNodes.at(0).toElement().text(); + const QString displayName = displayNameNodes.at(0).toElement().text(); calendarData.displayName = displayName; } @@ -1563,11 +1445,9 @@ void OwnCloudService::loadTodoItems(QString &data) { doc.setContent(data, true); // fetch all urls that are currently in the calendar - QList<QUrl> calendarItemUrlRemoveList = - CalendarItem::fetchAllUrlsByCalendar(calendarName); + QList<QUrl> calendarItemUrlRemoveList = CalendarItem::fetchAllUrlsByCalendar(calendarName); - QDomNodeList responseNodes = - doc.elementsByTagNameNS(NS_DAV, QStringLiteral("response")); + QDomNodeList responseNodes = doc.elementsByTagNameNS(NS_DAV, QStringLiteral("response")); int responseNodesCount = responseNodes.length(); int requestCount = 0; @@ -1588,8 +1468,7 @@ void OwnCloudService::loadTodoItems(QString &data) { QDomElement elem = responseNode.toElement(); // check if we have an url - QDomNodeList urlPartNodes = - elem.elementsByTagNameNS(NS_DAV, QStringLiteral("href")); + QDomNodeList urlPartNodes = elem.elementsByTagNameNS(NS_DAV, QStringLiteral("href")); if (urlPartNodes.length()) { QString urlPart = urlPartNodes.at(0).toElement().text(); @@ -1597,8 +1476,7 @@ void OwnCloudService::loadTodoItems(QString &data) { continue; } - QUrl calendarItemUrl = - QUrl(todoCalendarServerUrlWithoutPath % urlPart); + QUrl calendarItemUrl = QUrl(todoCalendarServerUrlWithoutPath % urlPart); // check if we have an etag QDomNodeList etagNodes = @@ -1610,16 +1488,14 @@ void OwnCloudService::loadTodoItems(QString &data) { // << etag; // check if we have a last modified date - QDomNodeList lastModifiedNodes = elem.elementsByTagNameNS( - NS_DAV, QStringLiteral("getlastmodified")); + QDomNodeList lastModifiedNodes = + elem.elementsByTagNameNS(NS_DAV, QStringLiteral("getlastmodified")); if (lastModifiedNodes.length()) { - const QString lastModified = - lastModifiedNodes.at(0).toElement().text(); + const QString lastModified = lastModifiedNodes.at(0).toElement().text(); bool fetchItem = false; // try to fetch the calendar item by url - CalendarItem calItem = - CalendarItem::fetchByUrl(calendarItemUrl); + CalendarItem calItem = CalendarItem::fetchByUrl(calendarItemUrl); if (calItem.isFetched()) { // check if calendar item was modified if (calItem.getETag() != etag) { @@ -1634,18 +1510,15 @@ void OwnCloudService::loadTodoItems(QString &data) { } else { // calendar item was not found // create calendar item for fetching - CalendarItem::addCalendarItemForRequest( - calendarName, calendarItemUrl, etag, - lastModified); + CalendarItem::addCalendarItemForRequest(calendarName, calendarItemUrl, + etag, lastModified); fetchItem = true; } // remove the url from the list of calendar item urls // to remove - if (calendarItemUrlRemoveList.contains( - calendarItemUrl)) { - calendarItemUrlRemoveList.removeAll( - calendarItemUrl); + if (calendarItemUrlRemoveList.contains(calendarItemUrl)) { + calendarItemUrlRemoveList.removeAll(calendarItemUrl); } // fetch the calendar item @@ -1653,8 +1526,7 @@ void OwnCloudService::loadTodoItems(QString &data) { QNetworkRequest r(calendarItemUrl); addCalendarAuthHeader(&r); - QNetworkReply *reply = - calendarNetworkManager->get(r); + QNetworkReply *reply = calendarNetworkManager->get(r); ignoreSslErrorsIfAllowed(reply); requestCount++; @@ -1713,8 +1585,7 @@ void OwnCloudService::handleNoteShareReply(QString &data) { /** * Updates the share status of the note */ -void OwnCloudService::handleUpdateNoteShareReply(const QString &urlPart, - const QString &data) { +void OwnCloudService::handleUpdateNoteShareReply(const QString &urlPart, const QString &data) { // return if we didn't get any data if (data.isEmpty()) { return; @@ -1722,8 +1593,7 @@ void OwnCloudService::handleUpdateNoteShareReply(const QString &urlPart, qDebug() << __func__ << " - 'data': " << data; - QRegularExpression re(QRegularExpression::escape(sharePath) % - QStringLiteral("\\/(\\d+)$")); + QRegularExpression re(QRegularExpression::escape(sharePath) % QStringLiteral("\\/(\\d+)$")); QRegularExpressionMatch match = re.match(urlPart); int shareId = match.hasMatch() ? match.captured(1).toInt() : 0; @@ -1755,18 +1625,18 @@ void OwnCloudService::handleUpdateNoteShareReply(const QString &urlPart, if (status.trimmed() != QStringLiteral("ok")) { QString message = doc.firstChildElement(QStringLiteral("ocs")) - .firstChildElement(QStringLiteral("meta")) - .firstChildElement(QStringLiteral("message")) - .text(); + .firstChildElement(QStringLiteral("meta")) + .firstChildElement(QStringLiteral("message")) + .text(); showOwnCloudServerErrorMessage(message.trimmed()); return; } QString permissions = doc.firstChildElement(QStringLiteral("ocs")) - .firstChildElement(QStringLiteral("data")) - .firstChildElement(QStringLiteral("permissions")) - .text(); + .firstChildElement(QStringLiteral("data")) + .firstChildElement(QStringLiteral("permissions")) + .text(); qDebug() << __func__ << " - 'permissions': " << permissions; @@ -1829,8 +1699,8 @@ void OwnCloudService::updateNoteShareStatusFromShare(QString &data) { .elementsByTagName(QStringLiteral("element")); if (dataElements.count() == 0) { - dataElements = doc.firstChildElement(QStringLiteral("ocs")) - .elementsByTagName(QStringLiteral("data")); + dataElements = + doc.firstChildElement(QStringLiteral("ocs")).elementsByTagName(QStringLiteral("data")); } updateNoteShareStatus(dataElements, true); @@ -1856,19 +1726,18 @@ void OwnCloudService::updateNoteShareStatusFromFetchAll(QString &data) { } QDomNodeList dataElements = doc.firstChildElement(QStringLiteral("ocs")) - .firstChildElement(QStringLiteral("data")) - .elementsByTagName(QStringLiteral("element")); + .firstChildElement(QStringLiteral("data")) + .elementsByTagName(QStringLiteral("element")); if (dataElements.count() == 0) { - dataElements = doc.firstChildElement(QStringLiteral("ocs")) - .elementsByTagName(QStringLiteral("data")); + dataElements = + doc.firstChildElement(QStringLiteral("ocs")).elementsByTagName(QStringLiteral("data")); } updateNoteShareStatus(dataElements); } -void OwnCloudService::updateNoteShareStatus(QDomNodeList &dataElements, - bool updateShareDialog) { +void OwnCloudService::updateNoteShareStatus(QDomNodeList &dataElements, bool updateShareDialog) { qDebug() << __func__ << " - 'dataElements.count()': " << dataElements.count(); if (dataElements.isEmpty()) { @@ -1877,15 +1746,13 @@ void OwnCloudService::updateNoteShareStatus(QDomNodeList &dataElements, QString serverNotesPath = NoteFolder::currentRemotePath(); - for(int i = 0; i < dataElements.count(); i++) - { + for (int i = 0; i < dataElements.count(); i++) { QDomNode elm = dataElements.at(i); if (!elm.isElement()) { continue; } - QString shareType = elm.firstChildElement(QStringLiteral("share_type")) - .text(); + QString shareType = elm.firstChildElement(QStringLiteral("share_type")).text(); qDebug() << __func__ << " - 'shareType': " << shareType; @@ -1894,8 +1761,7 @@ void OwnCloudService::updateNoteShareStatus(QDomNodeList &dataElements, continue; } - QString itemType = elm.firstChildElement(QStringLiteral("item_type")) - .text(); + QString itemType = elm.firstChildElement(QStringLiteral("item_type")).text(); qDebug() << __func__ << " - 'itemType': " << itemType; @@ -1912,8 +1778,7 @@ void OwnCloudService::updateNoteShareStatus(QDomNodeList &dataElements, } // remove the note path from the path - path = - Utils::Misc::removeIfStartsWith(std::move(path), serverNotesPath); + path = Utils::Misc::removeIfStartsWith(std::move(path), serverNotesPath); QFileInfo fileInfo(path); QString fileName = fileInfo.fileName(); @@ -1923,8 +1788,8 @@ void OwnCloudService::updateNoteShareStatus(QDomNodeList &dataElements, } // fetch the note sub folder of the note - NoteSubFolder noteSubFolder = NoteSubFolder::fetchByPathData( - std::move(fileParentPath), QStringLiteral("/")); + NoteSubFolder noteSubFolder = + NoteSubFolder::fetchByPathData(std::move(fileParentPath), QStringLiteral("/")); // fetch the note Note note = Note::fetchByFileName(fileName, noteSubFolder.getId()); @@ -1941,7 +1806,8 @@ void OwnCloudService::updateNoteShareStatus(QDomNodeList &dataElements, note.setShareUrl(url); // get the share permissions - int permissions = elm.firstChildElement(QStringLiteral("permissions")).text().trimmed().toInt(); + int permissions = + elm.firstChildElement(QStringLiteral("permissions")).text().trimmed().toInt(); note.setSharePermissions(permissions); note.store(); @@ -1967,8 +1833,7 @@ void OwnCloudService::loadDirectory(QString &data) { } QStringList pathList; - QDomNodeList responseNodes = - doc.elementsByTagNameNS(NS_DAV, QStringLiteral("response")); + QDomNodeList responseNodes = doc.elementsByTagNameNS(NS_DAV, QStringLiteral("response")); for (int i = 0; i < responseNodes.count(); i++) { QDomNode responseNode = responseNodes.at(i); @@ -1976,8 +1841,8 @@ void OwnCloudService::loadDirectory(QString &data) { QDomElement elem = responseNode.toElement(); bool isFolder = false; - QDomNodeList resourceTypeNodes = elem.elementsByTagNameNS( - NS_DAV, QStringLiteral("resourcetype")); + QDomNodeList resourceTypeNodes = + elem.elementsByTagNameNS(NS_DAV, QStringLiteral("resourcetype")); if (resourceTypeNodes.length()) { QDomNodeList typeNodes = resourceTypeNodes.at(0).childNodes(); for (int j = 0; j < typeNodes.length(); ++j) { @@ -1996,8 +1861,7 @@ void OwnCloudService::loadDirectory(QString &data) { } // check if we have an url - QDomNodeList urlPartNodes = - elem.elementsByTagNameNS(NS_DAV, QStringLiteral("href")); + QDomNodeList urlPartNodes = elem.elementsByTagNameNS(NS_DAV, QStringLiteral("href")); if (urlPartNodes.length()) { QString urlPart = urlPartNodes.at(0).toElement().text(); @@ -2005,12 +1869,10 @@ void OwnCloudService::loadDirectory(QString &data) { QStringLiteral("\\/(.+)\\/$")); QRegularExpressionMatch match = re.match(urlPart); - QString folderString = - match.hasMatch() ? match.captured(1) : QString(); + QString folderString = match.hasMatch() ? match.captured(1) : QString(); if (!folderString.isEmpty()) { - pathList - << QUrl::fromPercentEncoding(folderString.toUtf8()); + pathList << QUrl::fromPercentEncoding(folderString.toUtf8()); } } } @@ -2029,8 +1891,7 @@ void OwnCloudService::loadDirectory(QString &data) { * @param calendarItem * @param dialog */ -void OwnCloudService::postCalendarItemToServer(CalendarItem calendarItem, - TodoDialog *dialog) { +void OwnCloudService::postCalendarItemToServer(CalendarItem calendarItem, TodoDialog *dialog) { this->todoDialog = dialog; calendarItem.generateNewICSData(); @@ -2051,8 +1912,7 @@ void OwnCloudService::postCalendarItemToServer(CalendarItem calendarItem, QStringLiteral("application/x-www-form-urlencoded")); auto *buffer = new QBuffer(dataToSend); - QNetworkReply *reply = - calendarNetworkManager->sendCustomRequest(r, "PUT", buffer); + QNetworkReply *reply = calendarNetworkManager->sendCustomRequest(r, "PUT", buffer); ignoreSslErrorsIfAllowed(reply); } @@ -2114,8 +1974,7 @@ bool OwnCloudService::updateICSDataOfCalendarItem(CalendarItem *calItem) { * Gets the file list from the ownCloud server * for the settings dialog */ -void OwnCloudService::settingsGetFileList(SettingsDialog *dialog, - const QString &path) { +void OwnCloudService::settingsGetFileList(SettingsDialog *dialog, const QString &path) { settingsDialog = dialog; QUrl url(serverUrl % webdavPath() % QStringLiteral("/") % path); @@ -2137,8 +1996,7 @@ void OwnCloudService::settingsGetFileList(SettingsDialog *dialog, auto dataToSend = new QByteArray(body.toUtf8()); r.setHeader(QNetworkRequest::ContentLengthHeader, dataToSend->size()); - r.setHeader(QNetworkRequest::ContentTypeHeader, - QStringLiteral("application/xml")); + r.setHeader(QNetworkRequest::ContentTypeHeader, QStringLiteral("application/xml")); auto *buffer = new QBuffer(dataToSend); #if (QT_VERSION < QT_VERSION_CHECK(5, 15, 0)) @@ -2146,8 +2004,7 @@ void OwnCloudService::settingsGetFileList(SettingsDialog *dialog, networkManager->setNetworkAccessible(QNetworkAccessManager::Accessible); #endif - QNetworkReply *reply = - networkManager->sendCustomRequest(r, "PROPFIND", buffer); + QNetworkReply *reply = networkManager->sendCustomRequest(r, "PROPFIND", buffer); ignoreSslErrorsIfAllowed(reply); } @@ -2188,8 +2045,7 @@ QByteArray OwnCloudService::downloadNextcloudPreviewImage(const QString &path) { timer.setSingleShot(true); QObject::connect(&timer, SIGNAL(timeout()), &loop, SLOT(quit())); - QObject::connect(manager, SIGNAL(finished(QNetworkReply *)), &loop, - SLOT(quit())); + QObject::connect(manager, SIGNAL(finished(QNetworkReply *)), &loop, SLOT(quit())); // 10 sec timeout for the request timer.start(10000); @@ -2201,8 +2057,7 @@ QByteArray OwnCloudService::downloadNextcloudPreviewImage(const QString &path) { addAuthHeader(&networkRequest); #if QT_VERSION < QT_VERSION_CHECK(5, 9, 0) - networkRequest.setAttribute(QNetworkRequest::FollowRedirectsAttribute, - true); + networkRequest.setAttribute(QNetworkRequest::FollowRedirectsAttribute, true); #else networkRequest.setAttribute(QNetworkRequest::RedirectPolicyAttribute, true); #endif @@ -2214,8 +2069,7 @@ QByteArray OwnCloudService::downloadNextcloudPreviewImage(const QString &path) { // if we didn't get a timeout let us return the content if (timer.isActive()) { - int statusCode = - reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(); + int statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(); // only get the data if the status code was "success" // see: https://en.wikipedia.org/wiki/List_of_HTTP_status_codes @@ -2238,8 +2092,8 @@ QByteArray OwnCloudService::downloadNextcloudPreviewImage(const QString &path) { * @param imageSuffix * @return */ -QString OwnCloudService::nextcloudPreviewImageTagToInlineImageTag( - QString imageTag, int &imageWidth) { +QString OwnCloudService::nextcloudPreviewImageTagToInlineImageTag(QString imageTag, + int &imageWidth) { imageTag.replace(QStringLiteral("&"), QStringLiteral("&")); // qDebug() << __func__ << " - 'imageTag': " << imageTag; @@ -2266,8 +2120,7 @@ QString OwnCloudService::nextcloudPreviewImageTagToInlineImageTag( QString inlineImageTag = QStringLiteral(R"(<img class="remote-img" src="data:)") % mimeType % QStringLiteral(";base64,") + - data.toBase64() % QStringLiteral("\" alt=\"") % alt % - QStringLiteral("\"/>"); + data.toBase64() % QStringLiteral("\" alt=\"") % alt % QStringLiteral("\"/>"); return inlineImageTag; } @@ -2283,12 +2136,12 @@ bool OwnCloudService::initiateLoginFlowV2(const QString &serverUrl, QJsonObject auto data = Utils::Misc::downloadUrl(loginFlowUrl, true); if (data.isEmpty() || !data.startsWith('{')) { - QMessageBox::warning(nullptr, QObject::tr("Login flow failed"), - QObject::tr( - "Nextcloud login flow v2 could not be initiated. " - "Make sure the server url is correct and you are using a " - "Nextcloud server!<br /><br />If your are still having issues " - "please create an app password by hand on your server's admin page.")); + QMessageBox::warning( + nullptr, QObject::tr("Login flow failed"), + QObject::tr("Nextcloud login flow v2 could not be initiated. " + "Make sure the server url is correct and you are using a " + "Nextcloud server!<br /><br />If your are still having issues " + "please create an app password by hand on your server's admin page.")); return false; } @@ -2299,7 +2152,7 @@ bool OwnCloudService::initiateLoginFlowV2(const QString &serverUrl, QJsonObject if (loginUrl.isEmpty()) { QMessageBox::warning(nullptr, QObject::tr("Login flow failed"), - QObject::tr("Could not parse login url!")); + QObject::tr("Could not parse login url!")); return false; } @@ -2321,25 +2174,23 @@ bool OwnCloudService::initiateLoginFlowV2(const QString &serverUrl, QJsonObject * @param password * @return */ -QString OwnCloudService::fetchNextcloudAccountId(const QString &serverUrl, - const QString &userName, - const QString &password) { +QString OwnCloudService::fetchNextcloudAccountId(const QString &serverUrl, const QString &userName, + const QString &password) { auto *manager = new QNetworkAccessManager(); QEventLoop loop; QTimer timer; timer.setSingleShot(true); QObject::connect(&timer, SIGNAL(timeout()), &loop, SLOT(quit())); - QObject::connect(manager, SIGNAL(finished(QNetworkReply *)), &loop, - SLOT(quit())); + QObject::connect(manager, SIGNAL(finished(QNetworkReply *)), &loop, SLOT(quit())); // 5 sec timeout for the request timer.start(5000); QUrl url(serverUrl % QStringLiteral("/ocs/v1.php/cloud/user")); -// qDebug() << __func__ << " - 'url': " << url; -// qDebug() << __func__ << " - 'userName': " << userName; -// qDebug() << __func__ << " - 'password': " << password; + // qDebug() << __func__ << " - 'url': " << url; + // qDebug() << __func__ << " - 'userName': " << userName; + // qDebug() << __func__ << " - 'password': " << password; QNetworkRequest networkRequest = QNetworkRequest(url); addGenericAuthHeader(&networkRequest, userName, password); @@ -2357,16 +2208,14 @@ QString OwnCloudService::fetchNextcloudAccountId(const QString &serverUrl, if (timer.isActive()) { if (reply->error() != QNetworkReply::NoError) { qDebug() << __func__ << " - 'reply->error()': " << reply->error(); - qDebug() << __func__ << " - 'reply->errorString()': " - << reply->errorString(); - qDebug() << __func__ << " - 'reply->readAll()': " - << reply->readAll(); + qDebug() << __func__ << " - 'reply->errorString()': " << reply->errorString(); + qDebug() << __func__ << " - 'reply->readAll()': " << reply->readAll(); return {}; } QString data = QString(reply->readAll()); -// qDebug() << __func__ << " - 'data': " << data; + // qDebug() << __func__ << " - 'data': " << data; QDomDocument doc; if (!doc.setContent(data)) { @@ -2375,9 +2224,10 @@ QString OwnCloudService::fetchNextcloudAccountId(const QString &serverUrl, } QString id = doc.firstChildElement(QStringLiteral("ocs")) - .firstChildElement(QStringLiteral("data")) - .firstChildElement(QStringLiteral("id")) - .text().trimmed(); + .firstChildElement(QStringLiteral("data")) + .firstChildElement(QStringLiteral("id")) + .text() + .trimmed(); qDebug() << __func__ << " - 'id': " << id; @@ -2390,6 +2240,4 @@ QString OwnCloudService::fetchNextcloudAccountId(const QString &serverUrl, return {}; } -void OwnCloudService::unsetShareDialog() { - shareDialog = nullptr; -} +void OwnCloudService::unsetShareDialog() { shareDialog = nullptr; } diff --git a/src/services/owncloudservice.h b/src/services/owncloudservice.h index 265460542..bd03d928e 100644 --- a/src/services/owncloudservice.h +++ b/src/services/owncloudservice.h @@ -42,8 +42,7 @@ class OwnCloudService : public QObject { }; Q_ENUMS(CalendarBackend) - explicit OwnCloudService(int cloudConnectionId = -1, - QObject *parent = nullptr); + explicit OwnCloudService(int cloudConnectionId = -1, QObject *parent = nullptr); void settingsConnectionTest(SettingsDialog *dialog); @@ -59,8 +58,7 @@ class OwnCloudService : public QObject { void todoGetTodoList(const QString &calendarName, TodoDialog *dialog); - void postCalendarItemToServer(CalendarItem calendarItem, - TodoDialog *dialog); + void postCalendarItemToServer(CalendarItem calendarItem, TodoDialog *dialog); bool updateICSDataOfCalendarItem(CalendarItem *calItem); @@ -68,8 +66,7 @@ class OwnCloudService : public QObject { void settingsGetFileList(SettingsDialog *dialog, const QString &path); - static bool hasOwnCloudSettings(bool withEnabledCheck = true, - bool ignoreTableWarning = false); + static bool hasOwnCloudSettings(bool withEnabledCheck = true, bool ignoreTableWarning = false); void shareNote(const Note ¬e, ShareDialog *dialog); @@ -81,8 +78,7 @@ class OwnCloudService : public QObject { void removeNoteShare(const Note ¬e, ShareDialog *dialog); - static OwnCloudService *instance(bool reset = false, - int cloudConnectionId = -1); + static OwnCloudService *instance(bool reset = false, int cloudConnectionId = -1); static bool isOwnCloudSupportEnabled(); @@ -92,12 +88,12 @@ class OwnCloudService : public QObject { void startAppVersionTest(); - QString nextcloudPreviewImageTagToInlineImageTag(QString imageTag, - int &imageWidth); + QString nextcloudPreviewImageTagToInlineImageTag(QString imageTag, int &imageWidth); static bool initiateLoginFlowV2(const QString &serverUrl, QJsonObject &pollData); - static QString fetchNextcloudAccountId(const QString &serverUrl, const QString &userName, const QString &password); + static QString fetchNextcloudAccountId(const QString &serverUrl, const QString &userName, + const QString &password); void unsetShareDialog(); @@ -135,7 +131,8 @@ class OwnCloudService : public QObject { void readSettings(int cloudConnectionId = -1); - static void addGenericAuthHeader(QNetworkRequest *r, const QString &userName, const QString &password); + static void addGenericAuthHeader(QNetworkRequest *r, const QString &userName, + const QString &password); void addAuthHeader(QNetworkRequest *r); @@ -156,8 +153,7 @@ class OwnCloudService : public QObject { void showOwnCloudServerErrorMessage(const QString &message = QString(), bool withSettingsButton = true); - void showOwnCloudMessage(QString headline = QString(), - QString message = QString(), + void showOwnCloudMessage(QString headline = QString(), QString message = QString(), bool withSettingsButton = true); void updateNoteShareStatusFromShare(QString &data); @@ -166,11 +162,9 @@ class OwnCloudService : public QObject { void handleNoteShareReply(QString &data); - void updateNoteShareStatus(QDomNodeList &dataElements, - bool updateShareDialog = false); + void updateNoteShareStatus(QDomNodeList &dataElements, bool updateShareDialog = false); - void handleUpdateNoteShareReply(const QString &urlPart, - const QString &data); + void handleUpdateNoteShareReply(const QString &urlPart, const QString &data); static void checkAppVersion(QNetworkReply *reply); @@ -186,11 +180,9 @@ class OwnCloudService : public QObject { private slots: - void slotAuthenticationRequired(QNetworkReply *reply, - QAuthenticator *authenticator); + void slotAuthenticationRequired(QNetworkReply *reply, QAuthenticator *authenticator); - void slotCalendarAuthenticationRequired(QNetworkReply *reply, - QAuthenticator *authenticator); + void slotCalendarAuthenticationRequired(QNetworkReply *reply, QAuthenticator *authenticator); void slotReplyFinished(QNetworkReply *); }; diff --git a/src/services/scriptingservice.cpp b/src/services/scriptingservice.cpp index 68cb9e5ef..11bd87983 100644 --- a/src/services/scriptingservice.cpp +++ b/src/services/scriptingservice.cpp @@ -17,9 +17,9 @@ #include <QMimeData> #ifdef __GNUC__ - #if __GNUC__ >= 11 - QT_WARNING_DISABLE_GCC("-Wmismatched-new-delete") - #endif +#if __GNUC__ >= 11 +QT_WARNING_DISABLE_GCC("-Wmismatched-new-delete") +#endif #endif #include <QQmlComponent> #include <QQmlContext> @@ -53,7 +53,8 @@ ScriptingService::ScriptingService(QObject *parent) : QObject(parent) { if (!MainWindow::instance()) { qWarning() << "Unexpected null MainWindow in ScriptingService()"; } - _engine->rootContext()->setContextProperty(QStringLiteral("mainWindow"), MainWindow::instance()); + _engine->rootContext()->setContextProperty(QStringLiteral("mainWindow"), + MainWindow::instance()); #endif // deprecated @@ -69,10 +70,8 @@ ScriptingService::ScriptingService(QObject *parent) : QObject(parent) { int scriptCount = Script::countAll(); if (scriptCount > 0) { MetricsService::instance()->sendEventIfEnabled( - QStringLiteral("script/init"), QStringLiteral("script"), - QStringLiteral("script count"), - QString::number(scriptCount) % QStringLiteral(" scripts"), - scriptCount); + QStringLiteral("script/init"), QStringLiteral("script"), QStringLiteral("script count"), + QString::number(scriptCount) % QStringLiteral(" scripts"), scriptCount); } } @@ -97,9 +96,8 @@ ScriptingService *ScriptingService::instance() { ScriptingService *ScriptingService::createInstance(QObject *parent) { ScriptingService *scriptingService = new ScriptingService(parent); - qApp->setProperty( - "scriptingService", - QVariant::fromValue<ScriptingService *>(scriptingService)); + qApp->setProperty("scriptingService", + QVariant::fromValue<ScriptingService *>(scriptingService)); return scriptingService; } @@ -135,8 +133,7 @@ void ScriptingService::initComponent(const Script &script) { _scriptComponents[key] = scriptComponent; // set the script directory path of the script - object->setProperty("scriptDirPath", QDir::toNativeSeparators( - script.getScriptDirPath())); + object->setProperty("scriptDirPath", QDir::toNativeSeparators(script.getScriptDirPath())); // register the script settings variables QList<QVariant> list = registerSettingsVariables(object, script); @@ -149,8 +146,7 @@ void ScriptingService::initComponent(const Script &script) { QMetaObject::invokeMethod(object, "init"); } - if (methodExistsForObject(object, - QStringLiteral("onNoteStored(QVariant)"))) { + if (methodExistsForObject(object, QStringLiteral("onNoteStored(QVariant)"))) { QObject::connect(this, SIGNAL(noteStored(QVariant)), object, SLOT(onNoteStored(QVariant))); } @@ -167,11 +163,9 @@ void ScriptingService::initComponent(const Script &script) { * @param object * @param script */ -QList<QVariant> ScriptingService::registerSettingsVariables( - QObject *object, const Script &script) { +QList<QVariant> ScriptingService::registerSettingsVariables(QObject *object, const Script &script) { // registerSettingsVariables will override the settingsVariables property - if (methodExistsForObject(object, - QStringLiteral("registerSettingsVariables()"))) { + if (methodExistsForObject(object, QStringLiteral("registerSettingsVariables()"))) { QVariant variables; QMetaObject::invokeMethod(object, "registerSettingsVariables"); } @@ -188,8 +182,7 @@ QList<QVariant> ScriptingService::registerSettingsVariables( foreach (QVariant variable, list) { QMap<QString, QVariant> variableMap = variable.toMap(); QString type = variableMap[QStringLiteral("type")].toString(); - QString identifier = - variableMap[QStringLiteral("identifier")].toString(); + QString identifier = variableMap[QStringLiteral("identifier")].toString(); if (type == QStringLiteral("integer")) { int value = jsonObject.value(identifier).toInt(); @@ -259,8 +252,7 @@ void ScriptingService::reloadScriptComponents() { /** * Checks if the script can be used in a component */ -bool ScriptingService::validateScript(const Script &script, - QString &errorMessage) { +bool ScriptingService::validateScript(const Script &script, QString &errorMessage) { const QString path = script.getScriptPath(); QFile file(path); @@ -302,7 +294,7 @@ void ScriptingService::initComponents() { // fetch enabled only const QList<Script> scripts = Script::fetchAll(true); - for (const Script& script : scripts) { + for (const Script &script : scripts) { initComponent(script); } } @@ -310,9 +302,7 @@ void ScriptingService::initComponents() { /** * Reloads the engine */ -void ScriptingService::reloadEngine() { - reloadScriptComponents(); -} +void ScriptingService::reloadEngine() { reloadScriptComponents(); } /** * Returns the registered script variables @@ -330,8 +320,8 @@ QList<QVariant> ScriptingService::getSettingsVariables(int scriptId) { * called from a script */ void ScriptingService::reloadScriptingEngine() { - MetricsService::instance()->sendVisitIfEnabled( - QStringLiteral("scripting/") % QString(__func__)); + MetricsService::instance()->sendVisitIfEnabled(QStringLiteral("scripting/") % + QString(__func__)); QTimer::singleShot(500, this, SLOT(reloadEngine())); } @@ -339,10 +329,8 @@ void ScriptingService::reloadScriptingEngine() { /** * Checks if a method exists for an object */ -bool ScriptingService::methodExistsForObject(QObject *object, - const QString &method) const { - return object->metaObject()->indexOfMethod(method.toStdString().c_str()) > - -1; +bool ScriptingService::methodExistsForObject(QObject *object, const QString &method) const { + return object->metaObject()->indexOfMethod(method.toStdString().c_str()) > -1; } /** @@ -360,16 +348,15 @@ void ScriptingService::outputMethodsOfObject(QObject *object) { * Calls the insertMediaHook function for all script components * This function is called when media file is inserted into the note */ -QString ScriptingService::callInsertMediaHook(QFile *file, - QString markdownText) { +QString ScriptingService::callInsertMediaHook(QFile *file, QString markdownText) { QMapIterator<int, ScriptComponent> i(_scriptComponents); while (i.hasNext()) { i.next(); ScriptComponent scriptComponent = i.value(); - if (methodExistsForObject( - scriptComponent.object, QStringLiteral("insertMediaHook(QVariant,QVariant)"))) { + if (methodExistsForObject(scriptComponent.object, + QStringLiteral("insertMediaHook(QVariant,QVariant)"))) { QVariant newMarkdownText; QMetaObject::invokeMethod( scriptComponent.object, "insertMediaHook", Q_RETURN_ARG(QVariant, newMarkdownText), @@ -389,20 +376,20 @@ QString ScriptingService::callInsertMediaHook(QFile *file, * Calls the insertMediaHook function for all script components * This function is called when media file is inserted into the note */ -QString ScriptingService::callInsertAttachmentHook(QFile *file, - QString markdownText) { +QString ScriptingService::callInsertAttachmentHook(QFile *file, QString markdownText) { QMapIterator<int, ScriptComponent> i(_scriptComponents); while (i.hasNext()) { i.next(); ScriptComponent scriptComponent = i.value(); - if (methodExistsForObject( - scriptComponent.object, QStringLiteral("insertAttachmentHook(QVariant,QVariant)"))) { + if (methodExistsForObject(scriptComponent.object, + QStringLiteral("insertAttachmentHook(QVariant,QVariant)"))) { QVariant newMarkdownText; - QMetaObject::invokeMethod( - scriptComponent.object, "insertAttachmentHook", Q_RETURN_ARG(QVariant, newMarkdownText), - Q_ARG(QVariant, file->fileName()), Q_ARG(QVariant, markdownText)); + QMetaObject::invokeMethod(scriptComponent.object, "insertAttachmentHook", + Q_RETURN_ARG(QVariant, newMarkdownText), + Q_ARG(QVariant, file->fileName()), + Q_ARG(QVariant, markdownText)); QString result = newMarkdownText.toString(); if (!result.isEmpty()) { @@ -428,13 +415,10 @@ void ScriptingService::callWorkspaceSwitchedHook(const QString &oldUuid, const Q i.next(); ScriptComponent scriptComponent = i.value(); - if (methodExistsForObject( - scriptComponent.object, - QStringLiteral( - "workspaceSwitchedHook(QVariant,QVariant)"))) { - QMetaObject::invokeMethod( - scriptComponent.object, "workspaceSwitchedHook", - Q_ARG(QVariant, oldUuid), Q_ARG(QVariant, newUuid)); + if (methodExistsForObject(scriptComponent.object, + QStringLiteral("workspaceSwitchedHook(QVariant,QVariant)"))) { + QMetaObject::invokeMethod(scriptComponent.object, "workspaceSwitchedHook", + Q_ARG(QVariant, oldUuid), Q_ARG(QVariant, newUuid)); } } } @@ -450,10 +434,8 @@ void ScriptingService::callWorkspaceSwitchedHook(const QString &oldUuid, const Q * @param newTagName tag name to be renamed to if action = "rename" * @return note text QString or QStringList of tag names (if action = "list") inside a QVariant */ -QVariant ScriptingService::callNoteTaggingHook(const Note ¬e, - const QString &action, - const QString &tagName, - const QString &newTagName) { +QVariant ScriptingService::callNoteTaggingHook(const Note ¬e, const QString &action, + const QString &tagName, const QString &newTagName) { QMapIterator<int, ScriptComponent> i(_scriptComponents); NoteApi *noteApi = NoteApi::fromNote(note); @@ -464,15 +446,11 @@ QVariant ScriptingService::callNoteTaggingHook(const Note ¬e, if (methodExistsForObject( scriptComponent.object, - QStringLiteral( - "noteTaggingHook(QVariant,QVariant,QVariant,QVariant)"))) { + QStringLiteral("noteTaggingHook(QVariant,QVariant,QVariant,QVariant)"))) { QMetaObject::invokeMethod( - scriptComponent.object, "noteTaggingHook", - Q_RETURN_ARG(QVariant, result), - Q_ARG(QVariant, - QVariant::fromValue(static_cast<QObject *>(noteApi))), - Q_ARG(QVariant, action), Q_ARG(QVariant, tagName), - Q_ARG(QVariant, newTagName)); + scriptComponent.object, "noteTaggingHook", Q_RETURN_ARG(QVariant, result), + Q_ARG(QVariant, QVariant::fromValue(static_cast<QObject *>(noteApi))), + Q_ARG(QVariant, action), Q_ARG(QVariant, tagName), Q_ARG(QVariant, newTagName)); if (!result.isNull()) { return result; @@ -494,9 +472,8 @@ QVariant ScriptingService::callNoteTaggingHook(const Note ¬e, * @param newTagName tag name to be renamed to if action = "rename" * @return note text QString or QStringList of tag ids (if action = "list") inside a QVariant */ -QVariant ScriptingService::callNoteTaggingByObjectHook( - const Note ¬e, const QString &action, const Tag &tag, - const QString &newTagName) { +QVariant ScriptingService::callNoteTaggingByObjectHook(const Note ¬e, const QString &action, + const Tag &tag, const QString &newTagName) { QMapIterator<int, ScriptComponent> i(_scriptComponents); auto *noteApi = NoteApi::fromNote(note); auto *tagApi = TagApi::fromTag(tag); @@ -508,16 +485,12 @@ QVariant ScriptingService::callNoteTaggingByObjectHook( if (methodExistsForObject( scriptComponent.object, - QStringLiteral( - "noteTaggingByObjectHook(QVariant,QVariant,QVariant,QVariant)"))) { + QStringLiteral("noteTaggingByObjectHook(QVariant,QVariant,QVariant,QVariant)"))) { QMetaObject::invokeMethod( - scriptComponent.object, "noteTaggingByObjectHook", - Q_RETURN_ARG(QVariant, result), - Q_ARG(QVariant, - QVariant::fromValue(static_cast<QObject *>(noteApi))), + scriptComponent.object, "noteTaggingByObjectHook", Q_RETURN_ARG(QVariant, result), + Q_ARG(QVariant, QVariant::fromValue(static_cast<QObject *>(noteApi))), Q_ARG(QVariant, action), - Q_ARG(QVariant, - QVariant::fromValue(static_cast<QObject *>(tagApi))), + Q_ARG(QVariant, QVariant::fromValue(static_cast<QObject *>(tagApi))), Q_ARG(QVariant, newTagName)); if (!result.isNull()) { @@ -529,8 +502,7 @@ QVariant ScriptingService::callNoteTaggingByObjectHook( return QVariant(); } -void ScriptingService::callWindowStateChangeHook(const QString &windowStateStr) -{ +void ScriptingService::callWindowStateChangeHook(const QString &windowStateStr) { QMapIterator<int, ScriptComponent> i(_scriptComponents); while (i.hasNext()) { @@ -538,13 +510,9 @@ void ScriptingService::callWindowStateChangeHook(const QString &windowStateStr) ScriptComponent scriptComponent = i.value(); QObject *object = scriptComponent.object; - if (methodExistsForObject(object, - QStringLiteral("windowStateChangedHook(QVariant)"))) { - - QMetaObject::invokeMethod( - object, "windowStateChangedHook", - Q_ARG(QVariant, - QVariant::fromValue(windowStateStr))); + if (methodExistsForObject(object, QStringLiteral("windowStateChangedHook(QVariant)"))) { + QMetaObject::invokeMethod(object, "windowStateChangedHook", + Q_ARG(QVariant, QVariant::fromValue(windowStateStr))); } } } @@ -554,10 +522,9 @@ void ScriptingService::callWindowStateChangeHook(const QString &windowStateStr) * @return true if a function was found */ bool ScriptingService::noteTaggingHookExists() const { - return methodExists( - QStringLiteral("noteTaggingHook(QVariant,QVariant,QVariant,QVariant)")) || - methodExists(QStringLiteral( - "noteTaggingByObjectHook(QVariant,QVariant,QVariant,QVariant)")); + return methodExists(QStringLiteral("noteTaggingHook(QVariant,QVariant,QVariant,QVariant)")) || + methodExists( + QStringLiteral("noteTaggingByObjectHook(QVariant,QVariant,QVariant,QVariant)")); } /** @@ -602,10 +569,8 @@ QStringList ScriptingService::callAutocompletionHook() const { ScriptComponent scriptComponent = i.value(); QVariant result; - if (methodExistsForObject(scriptComponent.object, - QStringLiteral("autocompletionHook()"))) { - QMetaObject::invokeMethod(scriptComponent.object, - "autocompletionHook", + if (methodExistsForObject(scriptComponent.object, QStringLiteral("autocompletionHook()"))) { + QMetaObject::invokeMethod(scriptComponent.object, "autocompletionHook", Q_RETURN_ARG(QVariant, result)); if (!result.isNull()) { @@ -621,14 +586,12 @@ QStringList ScriptingService::callAutocompletionHook() const { /** * Calls the insertingFromMimeDataHook function for an object */ -QString ScriptingService::callInsertingFromMimeDataHookForObject( - QObject *object, const QMimeData *mimeData) { - if (methodExistsForObject( - object, - QStringLiteral("insertingFromMimeDataHook(QVariant,QVariant)"))) { +QString ScriptingService::callInsertingFromMimeDataHookForObject(QObject *object, + const QMimeData *mimeData) { + if (methodExistsForObject(object, + QStringLiteral("insertingFromMimeDataHook(QVariant,QVariant)"))) { QVariant text; - QMetaObject::invokeMethod(object, "insertingFromMimeDataHook", - Q_RETURN_ARG(QVariant, text), + QMetaObject::invokeMethod(object, "insertingFromMimeDataHook", Q_RETURN_ARG(QVariant, text), Q_ARG(QVariant, mimeData->text()), Q_ARG(QVariant, mimeData->html())); return text.toString(); @@ -642,16 +605,14 @@ QString ScriptingService::callInsertingFromMimeDataHookForObject( * This function is called when html or a media file is pasted to a note with * `Ctrl + Shift + V` */ -QString ScriptingService::callInsertingFromMimeDataHook( - const QMimeData *mimeData) { +QString ScriptingService::callInsertingFromMimeDataHook(const QMimeData *mimeData) { QMapIterator<int, ScriptComponent> i(_scriptComponents); while (i.hasNext()) { i.next(); ScriptComponent scriptComponent = i.value(); - QString text = callInsertingFromMimeDataHookForObject( - scriptComponent.object, mimeData); + QString text = callInsertingFromMimeDataHookForObject(scriptComponent.object, mimeData); if (!text.isEmpty()) { return text; } @@ -666,18 +627,15 @@ QString ScriptingService::callInsertingFromMimeDataHook( * "Allow note file name to be different from headline" is enabled * in the settings */ -QString ScriptingService::callHandleNoteTextFileNameHookForObject( - QObject *object, Note *note) { - if (methodExistsForObject( - object, QStringLiteral("handleNoteTextFileNameHook(QVariant)"))) { +QString ScriptingService::callHandleNoteTextFileNameHookForObject(QObject *object, Note *note) { + if (methodExistsForObject(object, QStringLiteral("handleNoteTextFileNameHook(QVariant)"))) { auto *noteApi = new NoteApi(); noteApi->fetch(note->getId()); QVariant text; QMetaObject::invokeMethod( object, "handleNoteTextFileNameHook", Q_RETURN_ARG(QVariant, text), - Q_ARG(QVariant, - QVariant::fromValue(static_cast<QObject *>(noteApi)))); + Q_ARG(QVariant, QVariant::fromValue(static_cast<QObject *>(noteApi)))); return text.toString(); } @@ -694,8 +652,7 @@ QString ScriptingService::callHandleNoteTextFileNameHook(Note *note) { i.next(); ScriptComponent scriptComponent = i.value(); - QString text = callHandleNoteTextFileNameHookForObject( - scriptComponent.object, note); + QString text = callHandleNoteTextFileNameHookForObject(scriptComponent.object, note); if (!text.isEmpty()) { return text; } @@ -708,13 +665,11 @@ QString ScriptingService::callHandleNoteTextFileNameHook(Note *note) { * Calls the handleNewNoteHeadlineHook function for an object * This function is called when new note gets created */ -QString ScriptingService::callHandleNewNoteHeadlineHookForObject( - QObject *object, const QString &headline) { - if (methodExistsForObject( - object, QStringLiteral("handleNewNoteHeadlineHook(QVariant)"))) { +QString ScriptingService::callHandleNewNoteHeadlineHookForObject(QObject *object, + const QString &headline) { + if (methodExistsForObject(object, QStringLiteral("handleNewNoteHeadlineHook(QVariant)"))) { QVariant text; - QMetaObject::invokeMethod(object, "handleNewNoteHeadlineHook", - Q_RETURN_ARG(QVariant, text), + QMetaObject::invokeMethod(object, "handleNewNoteHeadlineHook", Q_RETURN_ARG(QVariant, text), Q_ARG(QVariant, headline)); return text.toString(); } @@ -733,15 +688,13 @@ void ScriptingService::callHandleNoteOpenedHook(Note *note) { ScriptComponent scriptComponent = i.value(); QObject *object = scriptComponent.object; - if (methodExistsForObject(object, - QStringLiteral("noteOpenedHook(QVariant)"))) { + if (methodExistsForObject(object, QStringLiteral("noteOpenedHook(QVariant)"))) { auto *noteApi = new NoteApi(); noteApi->fetch(note->getId()); QMetaObject::invokeMethod( object, "noteOpenedHook", - Q_ARG(QVariant, - QVariant::fromValue(static_cast<QObject *>(noteApi)))); + Q_ARG(QVariant, QVariant::fromValue(static_cast<QObject *>(noteApi)))); } } } @@ -757,16 +710,14 @@ QString ScriptingService::callHandleNoteNameHook(Note *note) { ScriptComponent scriptComponent = i.value(); QObject *object = scriptComponent.object; - if (methodExistsForObject( - object, QStringLiteral("handleNoteNameHook(QVariant)"))) { + if (methodExistsForObject(object, QStringLiteral("handleNoteNameHook(QVariant)"))) { auto *noteApi = new NoteApi(); noteApi->fetch(note->getId()); QVariant text; QMetaObject::invokeMethod( object, "handleNoteNameHook", Q_RETURN_ARG(QVariant, text), - Q_ARG(QVariant, - QVariant::fromValue(static_cast<QObject *>(noteApi)))); + Q_ARG(QVariant, QVariant::fromValue(static_cast<QObject *>(noteApi)))); return text.toString(); } } @@ -777,16 +728,14 @@ QString ScriptingService::callHandleNoteNameHook(Note *note) { /** * Calls the handleNewNoteHeadlineHook function for all script components */ -QString ScriptingService::callHandleNewNoteHeadlineHook( - const QString &headline) { +QString ScriptingService::callHandleNewNoteHeadlineHook(const QString &headline) { QMapIterator<int, ScriptComponent> i(_scriptComponents); while (i.hasNext()) { i.next(); ScriptComponent scriptComponent = i.value(); - QString text = callHandleNewNoteHeadlineHookForObject( - scriptComponent.object, headline); + QString text = callHandleNewNoteHeadlineHookForObject(scriptComponent.object, headline); if (!text.isEmpty()) { return text; } @@ -798,8 +747,9 @@ QString ScriptingService::callHandleNewNoteHeadlineHook( /** * Calls the noteToMarkdownHtmlHook function for an object */ -QString ScriptingService::callNoteToMarkdownHtmlHookForObject( - ScriptComponent *scriptComponent, Note *note, const QString &html, const bool forExport) { +QString ScriptingService::callNoteToMarkdownHtmlHookForObject(ScriptComponent *scriptComponent, + Note *note, const QString &html, + const bool forExport) { if (methodExistsForObject( scriptComponent->object, QStringLiteral("noteToMarkdownHtmlHook(QVariant,QVariant,QVariant)"))) { @@ -809,28 +759,25 @@ QString ScriptingService::callNoteToMarkdownHtmlHookForObject( QVariant text; QMetaObject::invokeMethod( scriptComponent->object, "noteToMarkdownHtmlHook", Q_RETURN_ARG(QVariant, text), - Q_ARG(QVariant, - QVariant::fromValue(static_cast<QObject *>(noteApi))), - Q_ARG(QVariant, html), - Q_ARG(QVariant, forExport)); + Q_ARG(QVariant, QVariant::fromValue(static_cast<QObject *>(noteApi))), + Q_ARG(QVariant, html), Q_ARG(QVariant, forExport)); return text.toString(); - } else if (methodExistsForObject( - scriptComponent->object, - QStringLiteral("noteToMarkdownHtmlHook(QVariant,QVariant)"))) { - auto *noteApi = new NoteApi(); - noteApi->fetch(note->getId()); - qWarning() << "Warning: noteToMarkdownHtmlHook(note, html) " - "is deprecated, please use " - "noteToMarkdownHtmlHook(note, html, forExport) " - "in "+scriptComponent->script.getName(); - QVariant text; - QMetaObject::invokeMethod( - scriptComponent->object, "noteToMarkdownHtmlHook", Q_RETURN_ARG(QVariant, text), - Q_ARG(QVariant, - QVariant::fromValue(static_cast<QObject *>(noteApi))), - Q_ARG(QVariant, html)); - return text.toString(); - } + } else if (methodExistsForObject(scriptComponent->object, + QStringLiteral("noteToMarkdownHtmlHook(QVariant,QVariant)"))) { + auto *noteApi = new NoteApi(); + noteApi->fetch(note->getId()); + qWarning() << "Warning: noteToMarkdownHtmlHook(note, html) " + "is deprecated, please use " + "noteToMarkdownHtmlHook(note, html, forExport) " + "in " + + scriptComponent->script.getName(); + QVariant text; + QMetaObject::invokeMethod( + scriptComponent->object, "noteToMarkdownHtmlHook", Q_RETURN_ARG(QVariant, text), + Q_ARG(QVariant, QVariant::fromValue(static_cast<QObject *>(noteApi))), + Q_ARG(QVariant, html)); + return text.toString(); + } return QString(); } @@ -839,8 +786,8 @@ QString ScriptingService::callNoteToMarkdownHtmlHookForObject( * Calls the noteToMarkdownHtmlHook function for all script components * This function is called when the markdown html of a note is generated */ -QString ScriptingService::callNoteToMarkdownHtmlHook(Note *note, - const QString &html, const bool forExport) { +QString ScriptingService::callNoteToMarkdownHtmlHook(Note *note, const QString &html, + const bool forExport) { QMapIterator<int, ScriptComponent> i(_scriptComponents); QString resultHtml = html; @@ -848,8 +795,8 @@ QString ScriptingService::callNoteToMarkdownHtmlHook(Note *note, i.next(); ScriptComponent scriptComponent = i.value(); - QString text = callNoteToMarkdownHtmlHookForObject( - &scriptComponent, note, resultHtml, forExport); + QString text = + callNoteToMarkdownHtmlHookForObject(&scriptComponent, note, resultHtml, forExport); if (!text.isEmpty()) { resultHtml = text; @@ -863,8 +810,8 @@ QString ScriptingService::callNoteToMarkdownHtmlHook(Note *note, * Calls the preNoteToMarkdownHtmlHook function for all script components * This function is called before the markdown html of a note is generated */ -QString ScriptingService::callPreNoteToMarkdownHtmlHook( - Note *note, const QString &markdown, const bool forExport) { +QString ScriptingService::callPreNoteToMarkdownHtmlHook(Note *note, const QString &markdown, + const bool forExport) { QMapIterator<int, ScriptComponent> i(_scriptComponents); QString resultMarkdown = markdown; @@ -877,8 +824,7 @@ QString ScriptingService::callPreNoteToMarkdownHtmlHook( if (methodExistsForObject( scriptComponent.object, - QStringLiteral( - "preNoteToMarkdownHtmlHook(QVariant,QVariant,QVariant)"))) { + QStringLiteral("preNoteToMarkdownHtmlHook(QVariant,QVariant,QVariant)"))) { auto *noteApi = new NoteApi(); noteApi->fetch(note->getId()); @@ -886,10 +832,8 @@ QString ScriptingService::callPreNoteToMarkdownHtmlHook( QMetaObject::invokeMethod( scriptComponent.object, "preNoteToMarkdownHtmlHook", Q_RETURN_ARG(QVariant, resultText), - Q_ARG(QVariant, - QVariant::fromValue(static_cast<QObject *>(noteApi))), - Q_ARG(QVariant, resultMarkdown), - Q_ARG(QVariant, forExport)); + Q_ARG(QVariant, QVariant::fromValue(static_cast<QObject *>(noteApi))), + Q_ARG(QVariant, resultMarkdown), Q_ARG(QVariant, forExport)); QString text = resultText.toString(); if (!text.isEmpty()) { @@ -897,28 +841,27 @@ QString ScriptingService::callPreNoteToMarkdownHtmlHook( } } else if (methodExistsForObject( scriptComponent.object, - QStringLiteral( - "preNoteToMarkdownHtmlHook(QVariant,QVariant)"))) { - qWarning() <<"Warning: preNoteToMarkdownHtmlHook(note, markdown) " - "is deprecated, please use " - "preNoteToMarkdownHtmlHook(note, markdown, forExport) " - "in "+scriptComponent.script.getName(); - auto *noteApi = new NoteApi(); - noteApi->fetch(note->getId()); + QStringLiteral("preNoteToMarkdownHtmlHook(QVariant,QVariant)"))) { + qWarning() << "Warning: preNoteToMarkdownHtmlHook(note, markdown) " + "is deprecated, please use " + "preNoteToMarkdownHtmlHook(note, markdown, forExport) " + "in " + + scriptComponent.script.getName(); + auto *noteApi = new NoteApi(); + noteApi->fetch(note->getId()); - QVariant resultText; - QMetaObject::invokeMethod( - scriptComponent.object, "preNoteToMarkdownHtmlHook", - Q_RETURN_ARG(QVariant, resultText), - Q_ARG(QVariant, - QVariant::fromValue(static_cast<QObject *>(noteApi))), - Q_ARG(QVariant, resultMarkdown)); - QString text = resultText.toString(); + QVariant resultText; + QMetaObject::invokeMethod( + scriptComponent.object, "preNoteToMarkdownHtmlHook", + Q_RETURN_ARG(QVariant, resultText), + Q_ARG(QVariant, QVariant::fromValue(static_cast<QObject *>(noteApi))), + Q_ARG(QVariant, resultMarkdown)); + QString text = resultText.toString(); - if (!text.isEmpty()) { - resultMarkdown = text; - } - } + if (!text.isEmpty()) { + resultMarkdown = text; + } + } } return markdown == resultMarkdown ? QString() : resultMarkdown; @@ -934,18 +877,14 @@ QString ScriptingService::callPreNoteToMarkdownHtmlHook( * demanded * @return */ -QString ScriptingService::callEncryptionHookForObject(QObject *object, - const QString &text, - const QString &password, - bool decrypt) { - if (methodExistsForObject( - object, - QStringLiteral("encryptionHook(QVariant,QVariant,QVariant)"))) { +QString ScriptingService::callEncryptionHookForObject(QObject *object, const QString &text, + const QString &password, bool decrypt) { + if (methodExistsForObject(object, + QStringLiteral("encryptionHook(QVariant,QVariant,QVariant)"))) { QVariant result; - QMetaObject::invokeMethod( - object, "encryptionHook", Q_RETURN_ARG(QVariant, result), - Q_ARG(QVariant, text), Q_ARG(QVariant, password), - Q_ARG(QVariant, decrypt)); + QMetaObject::invokeMethod(object, "encryptionHook", Q_RETURN_ARG(QVariant, result), + Q_ARG(QVariant, text), Q_ARG(QVariant, password), + Q_ARG(QVariant, decrypt)); return result.toString(); } @@ -962,8 +901,7 @@ QString ScriptingService::callEncryptionHookForObject(QObject *object, * demanded * @return */ -QString ScriptingService::callEncryptionHook(const QString &text, - const QString &password, +QString ScriptingService::callEncryptionHook(const QString &text, const QString &password, bool decrypt) { QMapIterator<int, ScriptComponent> i(_scriptComponents); @@ -971,8 +909,8 @@ QString ScriptingService::callEncryptionHook(const QString &text, i.next(); ScriptComponent scriptComponent = i.value(); - QString result = callEncryptionHookForObject(scriptComponent.object, - text, password, decrypt); + QString result = + callEncryptionHookForObject(scriptComponent.object, text, password, decrypt); if (!result.isEmpty()) { return result; } @@ -995,16 +933,14 @@ bool ScriptingService::callHandleNoteDoubleClickedHook(Note *note) { ScriptComponent scriptComponent = i.value(); QObject *object = scriptComponent.object; - if (methodExistsForObject( - object, QStringLiteral("noteDoubleClickedHook(QVariant)"))) { + if (methodExistsForObject(object, QStringLiteral("noteDoubleClickedHook(QVariant)"))) { auto *noteApi = new NoteApi(); noteApi->fetch(note->getId()); hookFound = true; QMetaObject::invokeMethod( object, "noteDoubleClickedHook", - Q_ARG(QVariant, - QVariant::fromValue(static_cast<QObject *>(noteApi)))); + Q_ARG(QVariant, QVariant::fromValue(static_cast<QObject *>(noteApi)))); } } @@ -1020,14 +956,16 @@ bool ScriptingService::callHandleNoteDoubleClickedHook(Note *note) { * @param requestType can be "page" or "selection" * @param pageUrl the url of the webpage where the request was made * @param pageTitle the page title of the webpage where the request was made - * @param rawData the data that was transmitted, html for requestType "page" or plain text for requestType "selection" + * @param rawData the data that was transmitted, html for requestType "page" or plain text for + * requestType "selection" * @param screenshotDataUrl the data url of the screenshot if the webpage where the request was made * @return true if data was handled by a hook */ -bool ScriptingService::callHandleWebsocketRawDataHook( - const QString &requestType, const QString &pageUrl, - const QString &pageTitle, const QString &rawData, - const QString &screenshotDataUrl) { +bool ScriptingService::callHandleWebsocketRawDataHook(const QString &requestType, + const QString &pageUrl, + const QString &pageTitle, + const QString &rawData, + const QString &screenshotDataUrl) { QMapIterator<int, ScriptComponent> i(_scriptComponents); while (i.hasNext()) { @@ -1035,20 +973,15 @@ bool ScriptingService::callHandleWebsocketRawDataHook( ScriptComponent scriptComponent = i.value(); QObject *object = scriptComponent.object; - if (methodExistsForObject(object, QStringLiteral( - "websocketRawDataHook(QVariant,QVariant,QVariant,QVariant," - "QVariant)"))) { + if (methodExistsForObject( + object, QStringLiteral("websocketRawDataHook(QVariant,QVariant,QVariant,QVariant," + "QVariant)"))) { QVariant result; - QMetaObject::invokeMethod( - object, "websocketRawDataHook", - Q_RETURN_ARG(QVariant, result), - Q_ARG(QVariant, requestType), - Q_ARG(QVariant, pageUrl), - Q_ARG(QVariant, pageTitle), - Q_ARG(QVariant, rawData), - Q_ARG(QVariant, screenshotDataUrl) - ); + QMetaObject::invokeMethod(object, "websocketRawDataHook", + Q_RETURN_ARG(QVariant, result), Q_ARG(QVariant, requestType), + Q_ARG(QVariant, pageUrl), Q_ARG(QVariant, pageTitle), + Q_ARG(QVariant, rawData), Q_ARG(QVariant, screenshotDataUrl)); // if data was handled by hook return true if (result.toBool()) { @@ -1065,10 +998,12 @@ bool ScriptingService::callHandleWebsocketRawDataHook( * * @param executablePath the path of the executable * @param parameters a list of parameter strings - * @param callbackIdentifier an identifier to be used in the onDetachedProcessCallback() function (optional) + * @param callbackIdentifier an identifier to be used in the onDetachedProcessCallback() function + * (optional) * @param callbackParameter an additional parameter for loops or the like (optional) * @param processData data written to the process if the callback is used (optional) - * @param workingDirectory the working directory to execute the process in (optional, only works without callback) + * @param workingDirectory the working directory to execute the process in (optional, only works + * without callback) * @return true on success, false otherwise */ bool ScriptingService::startDetachedProcess(const QString &executablePath, @@ -1077,8 +1012,8 @@ bool ScriptingService::startDetachedProcess(const QString &executablePath, const QVariant &callbackParameter, const QByteArray &processData, const QString &workingDirectory) { - MetricsService::instance()->sendVisitIfEnabled( - QStringLiteral("scripting/") % QString(__func__)); + MetricsService::instance()->sendVisitIfEnabled(QStringLiteral("scripting/") % + QString(__func__)); // callback provided: create new script thread if (!callbackIdentifier.isEmpty()) { @@ -1087,8 +1022,7 @@ bool ScriptingService::startDetachedProcess(const QString &executablePath, cmd.parameters = parameters; cmd.data = processData; - auto *st = new ScriptThread( - this, cmd, callbackIdentifier, callbackParameter); + auto *st = new ScriptThread(this, cmd, callbackIdentifier, callbackParameter); st->start(); return true; @@ -1106,14 +1040,14 @@ bool ScriptingService::startDetachedProcess(const QString &executablePath, * @param workingDirectory the working directory to execute the process in (optional) * @return the text that was returned by the process */ -QByteArray ScriptingService::startSynchronousProcess( - const QString &executablePath, const QStringList ¶meters, - const QByteArray &data, const QString &workingDirectory) const { - MetricsService::instance()->sendVisitIfEnabled( - QStringLiteral("scripting/") % QString(__func__)); +QByteArray ScriptingService::startSynchronousProcess(const QString &executablePath, + const QStringList ¶meters, + const QByteArray &data, + const QString &workingDirectory) const { + MetricsService::instance()->sendVisitIfEnabled(QStringLiteral("scripting/") % + QString(__func__)); - return Utils::Misc::startSynchronousProcess( - executablePath, parameters, data, workingDirectory); + return Utils::Misc::startSynchronousProcess(executablePath, parameters, data, workingDirectory); } /** @@ -1151,12 +1085,10 @@ void ScriptingService::onCustomActionInvoked(const QString &identifier) { /** * Calls the customActionInvoked function for an object */ -void ScriptingService::callCustomActionInvokedForObject( - QObject *object, const QString &identifier) { - if (methodExistsForObject( - object, QStringLiteral("customActionInvoked(QVariant)"))) { - QMetaObject::invokeMethod(object, "customActionInvoked", - Q_ARG(QVariant, identifier)); +void ScriptingService::callCustomActionInvokedForObject(QObject *object, + const QString &identifier) { + if (methodExistsForObject(object, QStringLiteral("customActionInvoked(QVariant)"))) { + QMetaObject::invokeMethod(object, "customActionInvoked", Q_ARG(QVariant, identifier)); } } @@ -1166,8 +1098,8 @@ void ScriptingService::callCustomActionInvokedForObject( * @return {NoteApi} the current note */ NoteApi *ScriptingService::currentNote() const { - MetricsService::instance()->sendVisitIfEnabled( - QStringLiteral("scripting/") % QString(__func__)); + MetricsService::instance()->sendVisitIfEnabled(QStringLiteral("scripting/") % + QString(__func__)); return _currentNoteApi; } @@ -1178,8 +1110,8 @@ NoteApi *ScriptingService::currentNote() const { * @param text */ void ScriptingService::noteTextEditWrite(const QString &text) { - MetricsService::instance()->sendVisitIfEnabled( - QStringLiteral("scripting/") % QString(__func__)); + MetricsService::instance()->sendVisitIfEnabled(QStringLiteral("scripting/") % + QString(__func__)); #ifndef INTEGRATION_TESTS MainWindow *mainWindow = MainWindow::instance(); @@ -1197,13 +1129,12 @@ void ScriptingService::noteTextEditWrite(const QString &text) { * @return */ QString ScriptingService::noteTextEditSelectedText() { - MetricsService::instance()->sendVisitIfEnabled( - QStringLiteral("scripting/") % QString(__func__)); + MetricsService::instance()->sendVisitIfEnabled(QStringLiteral("scripting/") % + QString(__func__)); #ifndef INTEGRATION_TESTS MainWindow *mainWindow = MainWindow::instance(); - return mainWindow != nullptr ? mainWindow->selectedNoteTextEditText() - : QString(); + return mainWindow != nullptr ? mainWindow->selectedNoteTextEditText() : QString(); #else return QString(); #endif @@ -1213,8 +1144,8 @@ QString ScriptingService::noteTextEditSelectedText() { * Selects all text in the note text edit */ void ScriptingService::noteTextEditSelectAll() { - MetricsService::instance()->sendVisitIfEnabled( - QStringLiteral("scripting/") % QString(__func__)); + MetricsService::instance()->sendVisitIfEnabled(QStringLiteral("scripting/") % + QString(__func__)); #ifndef INTEGRATION_TESTS MainWindow *mainWindow = MainWindow::instance(); @@ -1228,8 +1159,8 @@ void ScriptingService::noteTextEditSelectAll() { * Selects the current line in the note text edit */ void ScriptingService::noteTextEditSelectCurrentLine() { - MetricsService::instance()->sendVisitIfEnabled( - QStringLiteral("scripting/") % QString(__func__)); + MetricsService::instance()->sendVisitIfEnabled(QStringLiteral("scripting/") % + QString(__func__)); #ifndef INTEGRATION_TESTS MainWindow *mainWindow = MainWindow::instance(); @@ -1247,8 +1178,8 @@ void ScriptingService::noteTextEditSelectCurrentLine() { * Select the current word in the note text edit */ void ScriptingService::noteTextEditSelectCurrentWord() { - MetricsService::instance()->sendVisitIfEnabled( - QStringLiteral("scripting/") % QString(__func__)); + MetricsService::instance()->sendVisitIfEnabled(QStringLiteral("scripting/") % + QString(__func__)); #ifndef INTEGRATION_TESTS MainWindow *mainWindow = MainWindow::instance(); @@ -1268,8 +1199,8 @@ void ScriptingService::noteTextEditSelectCurrentWord() { * @param end */ void ScriptingService::noteTextEditSetSelection(int start, int end) { - MetricsService::instance()->sendVisitIfEnabled( - QStringLiteral("scripting/") % QString(__func__)); + MetricsService::instance()->sendVisitIfEnabled(QStringLiteral("scripting/") % + QString(__func__)); #ifndef INTEGRATION_TESTS MainWindow *mainWindow = MainWindow::instance(); @@ -1298,8 +1229,8 @@ void ScriptingService::noteTextEditSetSelection(int start, int end) { * @param position */ void ScriptingService::noteTextEditSetCursorPosition(int position) { - MetricsService::instance()->sendVisitIfEnabled( - QStringLiteral("scripting/") % QString(__func__)); + MetricsService::instance()->sendVisitIfEnabled(QStringLiteral("scripting/") % + QString(__func__)); #ifndef INTEGRATION_TESTS MainWindow *mainWindow = MainWindow::instance(); @@ -1326,8 +1257,8 @@ void ScriptingService::noteTextEditSetCursorPosition(int position) { * 0 would be the beginning of the note */ int ScriptingService::noteTextEditCursorPosition() { - MetricsService::instance()->sendVisitIfEnabled( - QStringLiteral("scripting/") % QString(__func__)); + MetricsService::instance()->sendVisitIfEnabled(QStringLiteral("scripting/") % + QString(__func__)); #ifndef INTEGRATION_TESTS MainWindow *mainWindow = MainWindow::instance(); @@ -1346,8 +1277,8 @@ int ScriptingService::noteTextEditCursorPosition() { * Returns the start position of the current selection in the note text edit */ int ScriptingService::noteTextEditSelectionStart() { - MetricsService::instance()->sendVisitIfEnabled( - QStringLiteral("scripting/") % QString(__func__)); + MetricsService::instance()->sendVisitIfEnabled(QStringLiteral("scripting/") % + QString(__func__)); #ifndef INTEGRATION_TESTS MainWindow *mainWindow = MainWindow::instance(); @@ -1364,8 +1295,8 @@ int ScriptingService::noteTextEditSelectionStart() { * Returns the end position of the current selection in the note text edit */ int ScriptingService::noteTextEditSelectionEnd() { - MetricsService::instance()->sendVisitIfEnabled( - QStringLiteral("scripting/") % QString(__func__)); + MetricsService::instance()->sendVisitIfEnabled(QStringLiteral("scripting/") % + QString(__func__)); #ifndef INTEGRATION_TESTS MainWindow *mainWindow = MainWindow::instance(); @@ -1387,8 +1318,8 @@ int ScriptingService::noteTextEditSelectionEnd() { * @return */ QString ScriptingService::noteTextEditCurrentWord(bool withPreviousCharacters) { - MetricsService::instance()->sendVisitIfEnabled( - QStringLiteral("scripting/") % QString(__func__)); + MetricsService::instance()->sendVisitIfEnabled(QStringLiteral("scripting/") % + QString(__func__)); #ifndef INTEGRATION_TESTS MainWindow *mainWindow = MainWindow::instance(); @@ -1407,8 +1338,8 @@ QString ScriptingService::noteTextEditCurrentWord(bool withPreviousCharacters) { * @param tagName */ void ScriptingService::tagCurrentNote(const QString &tagName) { - MetricsService::instance()->sendVisitIfEnabled( - QStringLiteral("scripting/") % QString(__func__)); + MetricsService::instance()->sendVisitIfEnabled(QStringLiteral("scripting/") % + QString(__func__)); #ifndef INTEGRATION_TESTS MainWindow *mainWindow = MainWindow::instance(); @@ -1426,8 +1357,8 @@ void ScriptingService::tagCurrentNote(const QString &tagName) { * @param text */ void ScriptingService::log(QString text) { - MetricsService::instance()->sendVisitIfEnabled( - QStringLiteral("scripting/") % QString(__func__)); + MetricsService::instance()->sendVisitIfEnabled(QStringLiteral("scripting/") % + QString(__func__)); #ifndef INTEGRATION_TESTS MainWindow *mainWindow = MainWindow::instance(); @@ -1447,8 +1378,8 @@ void ScriptingService::log(QString text) { * @return {QString} the content of the downloaded url */ QString ScriptingService::downloadUrlToString(const QUrl &url) { - MetricsService::instance()->sendVisitIfEnabled( - QStringLiteral("scripting/") % QString(__func__)); + MetricsService::instance()->sendVisitIfEnabled(QStringLiteral("scripting/") % + QString(__func__)); return Utils::Misc::downloadUrl(url); } @@ -1462,10 +1393,9 @@ QString ScriptingService::downloadUrlToString(const QUrl &url) { * (default false) * @return {QString} the media markdown or url */ -QString ScriptingService::downloadUrlToMedia(const QUrl &url, - bool returnUrlOnly) { - MetricsService::instance()->sendVisitIfEnabled( - QStringLiteral("scripting/") % QString(__func__)); +QString ScriptingService::downloadUrlToMedia(const QUrl &url, bool returnUrlOnly) { + MetricsService::instance()->sendVisitIfEnabled(QStringLiteral("scripting/") % + QString(__func__)); return _currentNote->downloadUrlToMedia(url, returnUrlOnly); } @@ -1480,10 +1410,9 @@ QString ScriptingService::downloadUrlToMedia(const QUrl &url, * (default false) * @return {QString} the media markdown or url */ -QString ScriptingService::insertMediaFile(const QString &mediaFilePath, - bool returnUrlOnly) { - MetricsService::instance()->sendVisitIfEnabled( - QStringLiteral("scripting/") % QString(__func__)); +QString ScriptingService::insertMediaFile(const QString &mediaFilePath, bool returnUrlOnly) { + MetricsService::instance()->sendVisitIfEnabled(QStringLiteral("scripting/") % + QString(__func__)); auto *mediaFile = new QFile(mediaFilePath); @@ -1506,10 +1435,9 @@ QString ScriptingService::insertMediaFile(const QString &mediaFilePath, * @return {QString} the attachment markdown or url */ QString ScriptingService::insertAttachmentFile(const QString &attachmentFilePath, - const QString &fileName, - bool returnUrlOnly) { - MetricsService::instance()->sendVisitIfEnabled( - QStringLiteral("scripting/") % QString(__func__)); + const QString &fileName, bool returnUrlOnly) { + MetricsService::instance()->sendVisitIfEnabled(QStringLiteral("scripting/") % + QString(__func__)); auto *attachmentFile = new QFile(attachmentFilePath); @@ -1517,8 +1445,7 @@ QString ScriptingService::insertAttachmentFile(const QString &attachmentFilePath return {}; } - return _currentNote->getInsertAttachmentMarkdown(attachmentFile, fileName, - returnUrlOnly); + return _currentNote->getInsertAttachmentMarkdown(attachmentFile, fileName, returnUrlOnly); } /** @@ -1529,8 +1456,8 @@ void ScriptingService::regenerateNotePreview() const { MainWindow *mainWindow = MainWindow::instance(); if (mainWindow != nullptr) { - MetricsService::instance()->sendVisitIfEnabled( - QStringLiteral("scripting/") % QString(__func__)); + MetricsService::instance()->sendVisitIfEnabled(QStringLiteral("scripting/") % + QString(__func__)); // Also regenerate the note preview if the note wasn't changed to e.g. reload images mainWindow->forceRegenerateNotePreview(); @@ -1555,23 +1482,20 @@ void ScriptingService::regenerateNotePreview() const { * @param useInNoteListContextMenu if true use the action in the note list * context menu (default: false) */ -void ScriptingService::registerCustomAction(const QString &identifier, - const QString &menuText, - const QString &buttonText, - const QString &icon, - bool useInNoteEditContextMenu, - bool hideButtonInToolbar, +void ScriptingService::registerCustomAction(const QString &identifier, const QString &menuText, + const QString &buttonText, const QString &icon, + bool useInNoteEditContextMenu, bool hideButtonInToolbar, bool useInNoteListContextMenu) { #ifndef INTEGRATION_TESTS MainWindow *mainWindow = MainWindow::instance(); if (mainWindow != nullptr) { - MetricsService::instance()->sendVisitIfEnabled( - QStringLiteral("scripting/") % QString(__func__)); + MetricsService::instance()->sendVisitIfEnabled(QStringLiteral("scripting/") % + QString(__func__)); - mainWindow->addCustomAction( - identifier, menuText, buttonText, icon, useInNoteEditContextMenu, - hideButtonInToolbar, useInNoteListContextMenu); + mainWindow->addCustomAction(identifier, menuText, buttonText, icon, + useInNoteEditContextMenu, hideButtonInToolbar, + useInNoteListContextMenu); } #else Q_UNUSED(identifier) @@ -1584,21 +1508,19 @@ void ScriptingService::registerCustomAction(const QString &identifier, #endif } - /** * Registers a label to write to * * @param identifier the identifier of the label * @param text the text shown in the label (optional) */ -void ScriptingService::registerLabel(const QString &identifier, - const QString &text) { +void ScriptingService::registerLabel(const QString &identifier, const QString &text) { #ifndef INTEGRATION_TESTS MainWindow *mainWindow = MainWindow::instance(); if (mainWindow != nullptr) { - MetricsService::instance()->sendVisitIfEnabled( - QStringLiteral("scripting/") % QString(__func__)); + MetricsService::instance()->sendVisitIfEnabled(QStringLiteral("scripting/") % + QString(__func__)); mainWindow->addScriptingLabel(identifier, text); } @@ -1614,14 +1536,13 @@ void ScriptingService::registerLabel(const QString &identifier, * @param identifier the identifier of the label * @param text the text shown in the label */ -void ScriptingService::setLabelText(const QString &identifier, - const QString &text) { +void ScriptingService::setLabelText(const QString &identifier, const QString &text) { #ifndef INTEGRATION_TESTS MainWindow *mainWindow = MainWindow::instance(); if (mainWindow != nullptr) { - MetricsService::instance()->sendVisitIfEnabled( - QStringLiteral("scripting/") % QString(__func__)); + MetricsService::instance()->sendVisitIfEnabled(QStringLiteral("scripting/") % + QString(__func__)); mainWindow->setScriptingLabelText(identifier, text); } @@ -1641,18 +1562,16 @@ void ScriptingService::createNote(QString text) { MainWindow *mainWindow = MainWindow::instance(); if (mainWindow != nullptr) { - MetricsService::instance()->sendVisitIfEnabled( - QStringLiteral("scripting/") % QString(__func__)); + MetricsService::instance()->sendVisitIfEnabled(QStringLiteral("scripting/") % + QString(__func__)); // create a temporary name for the note - QString name = - QStringLiteral("Note ") % Utils::Misc::createUuidString(); + QString name = QStringLiteral("Note ") % Utils::Misc::createUuidString(); // create the new note and move the cursor to the end mainWindow->createNewNote( name, std::move(text), - MainWindow::CreateNewNoteOptions( - MainWindow::CreateNewNoteOption::CursorAtEnd)); + MainWindow::CreateNewNoteOptions(MainWindow::CreateNewNoteOption::CursorAtEnd)); } #else Q_UNUSED(text) @@ -1665,8 +1584,8 @@ void ScriptingService::createNote(QString text) { * @param asHtml returns the clipboard content as html instead of text */ QString ScriptingService::clipboard(bool asHtml) { - MetricsService::instance()->sendVisitIfEnabled( - QStringLiteral("scripting/") % QString(__func__)); + MetricsService::instance()->sendVisitIfEnabled(QStringLiteral("scripting/") % + QString(__func__)); QClipboard *clipboard = QApplication::clipboard(); const QMimeData *mimeData = clipboard->mimeData(QClipboard::Clipboard); @@ -1677,8 +1596,8 @@ QString ScriptingService::clipboard(bool asHtml) { * Disables the note encryption password dialog */ void ScriptingService::encryptionDisablePassword() { - MetricsService::instance()->sendVisitIfEnabled( - QStringLiteral("scripting/") % QString(__func__)); + MetricsService::instance()->sendVisitIfEnabled(QStringLiteral("scripting/") % + QString(__func__)); qApp->setProperty("encryptionPasswordDisabled", true); } @@ -1687,8 +1606,8 @@ void ScriptingService::encryptionDisablePassword() { * Returns true if the current platform is Linux */ bool ScriptingService::platformIsLinux() { - MetricsService::instance()->sendVisitIfEnabled( - QStringLiteral("scripting/") % QString(__func__)); + MetricsService::instance()->sendVisitIfEnabled(QStringLiteral("scripting/") % + QString(__func__)); #ifdef Q_OS_LINUX return true; @@ -1701,8 +1620,8 @@ bool ScriptingService::platformIsLinux() { * Returns true if the current platform is macOS */ bool ScriptingService::platformIsOSX() { - MetricsService::instance()->sendVisitIfEnabled( - QStringLiteral("scripting/") % QString(__func__)); + MetricsService::instance()->sendVisitIfEnabled(QStringLiteral("scripting/") % + QString(__func__)); #ifdef Q_OS_MAC return true; @@ -1715,8 +1634,8 @@ bool ScriptingService::platformIsOSX() { * Returns true if the current platform is Windows */ bool ScriptingService::platformIsWindows() { - MetricsService::instance()->sendVisitIfEnabled( - QStringLiteral("scripting/") % QString(__func__)); + MetricsService::instance()->sendVisitIfEnabled(QStringLiteral("scripting/") % + QString(__func__)); #ifdef Q_OS_WIN return true; @@ -1731,26 +1650,21 @@ bool ScriptingService::platformIsWindows() { * @param stylesheet */ void ScriptingService::addStyleSheet(const QString &stylesheet) { - MetricsService::instance()->sendVisitIfEnabled( - QStringLiteral("scripting/") % QString(__func__)); + MetricsService::instance()->sendVisitIfEnabled(QStringLiteral("scripting/") % + QString(__func__)); - qApp->setStyleSheet(qApp->styleSheet() % - QStringLiteral("\n/* BEGIN CUSTOM STYLESHEET */\n") % - stylesheet % - QStringLiteral("\n/* END CUSTOM STYLESHEET */")); + qApp->setStyleSheet(qApp->styleSheet() % QStringLiteral("\n/* BEGIN CUSTOM STYLESHEET */\n") % + stylesheet % QStringLiteral("\n/* END CUSTOM STYLESHEET */")); } /** * Clears all custom stylesheets */ void ScriptingService::clearCustomStyleSheets() { - QRegularExpression regExp(QRegularExpression::escape(QStringLiteral( - "/* BEGIN CUSTOM STYLESHEET */")) % - ".+" + - QRegularExpression::escape(QStringLiteral( - "/* END CUSTOM STYLESHEET */")), - QRegularExpression::DotMatchesEverythingOption | - QRegularExpression::MultilineOption); + QRegularExpression regExp( + QRegularExpression::escape(QStringLiteral("/* BEGIN CUSTOM STYLESHEET */")) % ".+" + + QRegularExpression::escape(QStringLiteral("/* END CUSTOM STYLESHEET */")), + QRegularExpression::DotMatchesEverythingOption | QRegularExpression::MultilineOption); qApp->setStyleSheet(qApp->styleSheet().remove(regExp)); } @@ -1761,10 +1675,9 @@ void ScriptingService::clearCustomStyleSheets() { * @param noteSubFolderId integer id of the note subfolder * @return NoteApi* */ -NoteApi *ScriptingService::fetchNoteByFileName(const QString &fileName, - int noteSubFolderId) { - MetricsService::instance()->sendVisitIfEnabled( - QStringLiteral("scripting/") % QString(__func__)); +NoteApi *ScriptingService::fetchNoteByFileName(const QString &fileName, int noteSubFolderId) { + MetricsService::instance()->sendVisitIfEnabled(QStringLiteral("scripting/") % + QString(__func__)); return NoteApi::fromNote(Note::fetchByFileName(fileName, noteSubFolderId)); } @@ -1776,8 +1689,8 @@ NoteApi *ScriptingService::fetchNoteByFileName(const QString &fileName, * @return NoteApi* */ NoteApi *ScriptingService::fetchNoteById(int id) { - MetricsService::instance()->sendVisitIfEnabled( - QStringLiteral("scripting/") % QString(__func__)); + MetricsService::instance()->sendVisitIfEnabled(QStringLiteral("scripting/") % + QString(__func__)); auto *note = new NoteApi(); note->fetch(id); @@ -1792,11 +1705,10 @@ NoteApi *ScriptingService::fetchNoteById(int id) { * @param noteSubFolderId integer id of the note subfolder * @return bool */ -bool ScriptingService::noteExistsByFileName(const QString &fileName, - int ignoreNoteId, +bool ScriptingService::noteExistsByFileName(const QString &fileName, int ignoreNoteId, int noteSubFolderId) { - MetricsService::instance()->sendVisitIfEnabled( - QStringLiteral("scripting/") % QString(__func__)); + MetricsService::instance()->sendVisitIfEnabled(QStringLiteral("scripting/") % + QString(__func__)); Note note = Note::fetchByFileName(fileName, noteSubFolderId); @@ -1815,8 +1727,8 @@ bool ScriptingService::noteExistsByFileName(const QString &fileName, * @param asHtml bool if true the text will be set as html mime data */ void ScriptingService::setClipboardText(const QString &text, bool asHtml) { - MetricsService::instance()->sendVisitIfEnabled( - QStringLiteral("scripting/") % QString(__func__)); + MetricsService::instance()->sendVisitIfEnabled(QStringLiteral("scripting/") % + QString(__func__)); QClipboard *clipboard = QApplication::clipboard(); @@ -1836,8 +1748,8 @@ void ScriptingService::setClipboardText(const QString &text, bool asHtml) { * @param asTab bool if true the note will be opened in a new tab if not already open */ void ScriptingService::setCurrentNote(NoteApi *note, bool asTab) { - MetricsService::instance()->sendVisitIfEnabled( - QStringLiteral("scripting/") % QString(__func__)); + MetricsService::instance()->sendVisitIfEnabled(QStringLiteral("scripting/") % + QString(__func__)); #ifndef INTEGRATION_TESTS MainWindow *mainWindow = MainWindow::instance(); @@ -1860,10 +1772,9 @@ void ScriptingService::setCurrentNote(NoteApi *note, bool asTab) { * @param text * @param title (optional) */ -void ScriptingService::informationMessageBox(const QString &text, - const QString &title) { - MetricsService::instance()->sendVisitIfEnabled( - QStringLiteral("scripting/") % QString(__func__)); +void ScriptingService::informationMessageBox(const QString &text, const QString &title) { + MetricsService::instance()->sendVisitIfEnabled(QStringLiteral("scripting/") % + QString(__func__)); #ifndef INTEGRATION_TESTS MainWindow *mainWindow = MainWindow::instance(); @@ -1888,18 +1799,16 @@ void ScriptingService::informationMessageBox(const QString &text, * @param defaultButton default button that will be selected (optional) * @return id of pressed button */ -int ScriptingService::questionMessageBox(const QString &text, - const QString &title, int buttons, +int ScriptingService::questionMessageBox(const QString &text, const QString &title, int buttons, int defaultButton) { - MetricsService::instance()->sendVisitIfEnabled( - QStringLiteral("scripting/") % QString(__func__)); + MetricsService::instance()->sendVisitIfEnabled(QStringLiteral("scripting/") % + QString(__func__)); #ifndef INTEGRATION_TESTS MainWindow *mainWindow = MainWindow::instance(); if (mainWindow != nullptr) { - return QMessageBox::question( - mainWindow, title, text, QMessageBox::StandardButtons(buttons), - QMessageBox::StandardButton(defaultButton)); + return QMessageBox::question(mainWindow, title, text, QMessageBox::StandardButtons(buttons), + QMessageBox::StandardButton(defaultButton)); } #else Q_UNUSED(text) @@ -1919,11 +1828,10 @@ int ScriptingService::questionMessageBox(const QString &text, * @param filter (optional) * @return QString */ -QString ScriptingService::getOpenFileName(const QString &caption, - const QString &dir, +QString ScriptingService::getOpenFileName(const QString &caption, const QString &dir, const QString &filter) { - MetricsService::instance()->sendVisitIfEnabled( - QStringLiteral("scripting/") % QString(__func__)); + MetricsService::instance()->sendVisitIfEnabled(QStringLiteral("scripting/") % + QString(__func__)); #ifndef INTEGRATION_TESTS MainWindow *mainWindow = MainWindow::instance(); @@ -1947,11 +1855,10 @@ QString ScriptingService::getOpenFileName(const QString &caption, * @param filter (optional) * @return QString */ -QString ScriptingService::getSaveFileName(const QString &caption, - const QString &dir, +QString ScriptingService::getSaveFileName(const QString &caption, const QString &dir, const QString &filter) { - MetricsService::instance()->sendVisitIfEnabled( - QStringLiteral("scripting/") % QString(__func__)); + MetricsService::instance()->sendVisitIfEnabled(QStringLiteral("scripting/") % + QString(__func__)); #ifndef INTEGRATION_TESTS MainWindow *mainWindow = MainWindow::instance(); @@ -2010,16 +1917,15 @@ QString ScriptingService::dirSeparator() { return QDir::separator(); } */ QStringList ScriptingService::selectedNotesPaths() { QStringList selectedNotePaths; - MetricsService::instance()->sendVisitIfEnabled( - QStringLiteral("scripting/") % QString(__func__)); + MetricsService::instance()->sendVisitIfEnabled(QStringLiteral("scripting/") % + QString(__func__)); #ifndef INTEGRATION_TESTS MainWindow *mainWindow = MainWindow::instance(); if (mainWindow != nullptr) { Q_FOREACH (Note note, mainWindow->selectedNotes()) { - selectedNotePaths - << QDir::toNativeSeparators(note.fullNoteFilePath()); + selectedNotePaths << QDir::toNativeSeparators(note.fullNoteFilePath()); } } #endif @@ -2037,8 +1943,8 @@ QStringList ScriptingService::selectedNotesPaths() { */ QList<int> ScriptingService::selectedNotesIds() const { QList<int> selectedNotesIds; - MetricsService::instance()->sendVisitIfEnabled( - QStringLiteral("scripting/") % QString(__func__)); + MetricsService::instance()->sendVisitIfEnabled(QStringLiteral("scripting/") % + QString(__func__)); #ifndef INTEGRATION_TESTS MainWindow *mainWindow = MainWindow::instance(); @@ -2061,8 +1967,7 @@ QList<int> ScriptingService::selectedNotesIds() const { * * @return {QList<int>} list of note ids */ -QVector<int> ScriptingService::fetchNoteIdsByNoteTextPart( - const QString &text) const { +QVector<int> ScriptingService::fetchNoteIdsByNoteTextPart(const QString &text) const { QVector<int> noteIds = Note::fetchAllIdsByNoteTextPart(text); return noteIds; } @@ -2078,16 +1983,13 @@ QVector<int> ScriptingService::fetchNoteIdsByNoteTextPart( * false) * @return {QString} text of the selected item */ -QString ScriptingService::inputDialogGetItem(const QString &title, - const QString &label, - const QStringList &items, - int current, bool editable) { - MetricsService::instance()->sendVisitIfEnabled( - QStringLiteral("scripting/") % QString(__func__)); +QString ScriptingService::inputDialogGetItem(const QString &title, const QString &label, + const QStringList &items, int current, bool editable) { + MetricsService::instance()->sendVisitIfEnabled(QStringLiteral("scripting/") % + QString(__func__)); #ifndef INTEGRATION_TESTS - return QInputDialog::getItem(nullptr, title, label, items, current, - editable); + return QInputDialog::getItem(nullptr, title, label, items, current, editable); #else Q_UNUSED(title) Q_UNUSED(label) @@ -2106,15 +2008,13 @@ QString ScriptingService::inputDialogGetItem(const QString &title, * @param text {QString} text in the dialog (optional) * @return */ -QString ScriptingService::inputDialogGetText(const QString &title, - const QString &label, +QString ScriptingService::inputDialogGetText(const QString &title, const QString &label, const QString &text) { - MetricsService::instance()->sendVisitIfEnabled( - QStringLiteral("scripting/") % QString(__func__)); + MetricsService::instance()->sendVisitIfEnabled(QStringLiteral("scripting/") % + QString(__func__)); #ifndef INTEGRATION_TESTS - return QInputDialog::getText(nullptr, title, label, QLineEdit::Normal, - text); + return QInputDialog::getText(nullptr, title, label, QLineEdit::Normal, text); #else Q_UNUSED(title) Q_UNUSED(label) @@ -2132,15 +2032,13 @@ QString ScriptingService::inputDialogGetText(const QString &title, * @param key {QString} * @param value {QVariant} */ -void ScriptingService::setPersistentVariable(const QString &key, - const QVariant &value) { - MetricsService::instance()->sendVisitIfEnabled( - QStringLiteral("scripting/") % QString(__func__)); +void ScriptingService::setPersistentVariable(const QString &key, const QVariant &value) { + MetricsService::instance()->sendVisitIfEnabled(QStringLiteral("scripting/") % + QString(__func__)); QSettings settings; - settings.setValue(QStringLiteral(PERSISTENT_VARIABLE_SETTINGS_PREFIX) % - QStringLiteral("/") % key, - value); + settings.setValue( + QStringLiteral(PERSISTENT_VARIABLE_SETTINGS_PREFIX) % QStringLiteral("/") % key, value); } /** @@ -2152,15 +2050,14 @@ void ScriptingService::setPersistentVariable(const QString &key, * (optional) * @return */ -QVariant ScriptingService::getPersistentVariable(const QString &key, - const QVariant &defaultValue) { - MetricsService::instance()->sendVisitIfEnabled( - QStringLiteral("scripting/") % QString(__func__)); +QVariant ScriptingService::getPersistentVariable(const QString &key, const QVariant &defaultValue) { + MetricsService::instance()->sendVisitIfEnabled(QStringLiteral("scripting/") % + QString(__func__)); QSettings settings; - return settings.value(QStringLiteral(PERSISTENT_VARIABLE_SETTINGS_PREFIX) % - QStringLiteral("/") % key, - defaultValue); + return settings.value( + QStringLiteral(PERSISTENT_VARIABLE_SETTINGS_PREFIX) % QStringLiteral("/") % key, + defaultValue); } /** @@ -2171,8 +2068,8 @@ QVariant ScriptingService::getPersistentVariable(const QString &key, * (optional) * @return */ -QVariant ScriptingService::getApplicationSettingsVariable( - const QString &key, const QVariant &defaultValue) { +QVariant ScriptingService::getApplicationSettingsVariable(const QString &key, + const QVariant &defaultValue) { QSettings settings; return settings.value(key, defaultValue); } @@ -2187,8 +2084,8 @@ QVariant ScriptingService::getApplicationSettingsVariable( */ bool ScriptingService::jumpToNoteSubFolder(const QString ¬eSubFolderPath, const QString &separator) { - MetricsService::instance()->sendVisitIfEnabled( - QStringLiteral("scripting/") % QString(__func__)); + MetricsService::instance()->sendVisitIfEnabled(QStringLiteral("scripting/") % + QString(__func__)); #ifndef INTEGRATION_TESTS MainWindow *mainWindow = MainWindow::instance(); @@ -2196,8 +2093,7 @@ bool ScriptingService::jumpToNoteSubFolder(const QString ¬eSubFolderPath, return false; } - NoteSubFolder folder = - NoteSubFolder::fetchByPathData(noteSubFolderPath, separator); + NoteSubFolder folder = NoteSubFolder::fetchByPathData(noteSubFolderPath, separator); if (!folder.isFetched()) { return false; @@ -2219,8 +2115,8 @@ bool ScriptingService::jumpToNoteSubFolder(const QString ¬eSubFolderPath, * @return {QStringList} list of tag names */ QStringList ScriptingService::searchTagsByName(const QString &name) const { - MetricsService::instance()->sendVisitIfEnabled( - QStringLiteral("scripting/") % QString(__func__)); + MetricsService::instance()->sendVisitIfEnabled(QStringLiteral("scripting/") % + QString(__func__)); QStringList tags = Tag::searchAllNamesByName(name); return tags; @@ -2234,10 +2130,10 @@ QStringList ScriptingService::searchTagsByName(const QString &name) const { * @param createMissing {bool} if true (default) all missing tags will be created * @return TagApi object of deepest tag of the name breadcrumb list */ -TagApi *ScriptingService::getTagByNameBreadcrumbList( - const QStringList &nameList, bool createMissing) const { - MetricsService::instance()->sendVisitIfEnabled( - QStringLiteral("scripting/") % QString(__func__)); +TagApi *ScriptingService::getTagByNameBreadcrumbList(const QStringList &nameList, + bool createMissing) const { + MetricsService::instance()->sendVisitIfEnabled(QStringLiteral("scripting/") % + QString(__func__)); Tag tag = Tag::getTagByNameBreadcrumbList(nameList, createMissing); auto *tagApi = TagApi::fromTag(tag); @@ -2253,17 +2149,16 @@ TagApi *ScriptingService::getTagByNameBreadcrumbList( * @param createParentDirs {bool} optional (default: false) * @return */ -bool ScriptingService::writeToFile(const QString &filePath, - const QString &data, +bool ScriptingService::writeToFile(const QString &filePath, const QString &data, const bool createParentDirs) const { if (filePath.isEmpty()) return false; QFile file(filePath); - if(createParentDirs) { + if (createParentDirs) { QFileInfo fileInfo(file); QDir dir = fileInfo.dir(); - if(!dir.mkpath(dir.path())) return false; + if (!dir.mkpath(dir.path())) return false; } if (!file.open(QFile::WriteOnly | QFile::Truncate)) return false; @@ -2283,15 +2178,14 @@ bool ScriptingService::writeToFile(const QString &filePath, * @param filePath * @return the file data or null if the file does not exist */ -QString ScriptingService::readFromFile(const QString &filePath, - const QString &codec) const { - if (filePath.isEmpty()){ +QString ScriptingService::readFromFile(const QString &filePath, const QString &codec) const { + if (filePath.isEmpty()) { return QString(); } QFile file(filePath); - if (!file.open(QFile::ReadOnly)){ + if (!file.open(QFile::ReadOnly)) { return QString(); } @@ -2315,7 +2209,7 @@ QString ScriptingService::readFromFile(const QString &filePath, * @return */ bool ScriptingService::fileExists(const QString &filePath) const { - if (filePath.isEmpty()){ + if (filePath.isEmpty()) { return false; } QFile file(filePath); @@ -2329,10 +2223,9 @@ bool ScriptingService::fileExists(const QString &filePath) const { * @param checked {QString} only trigger the action if checked-state is * different than this parameter (can be 0 or 1) */ -void ScriptingService::triggerMenuAction(const QString &objectName, - const QString &checked) const { - MetricsService::instance()->sendVisitIfEnabled( - QStringLiteral("scripting/") % QString(__func__)); +void ScriptingService::triggerMenuAction(const QString &objectName, const QString &checked) const { + MetricsService::instance()->sendVisitIfEnabled(QStringLiteral("scripting/") % + QString(__func__)); #ifndef INTEGRATION_TESTS MainWindow *mainWindow = MainWindow::instance(); @@ -2378,21 +2271,21 @@ void ScriptingService::triggerMenuAction(const QString &objectName, */ void ScriptingService::onScriptThreadDone(ScriptThread *thread) { QMapIterator<int, ScriptComponent> i(_scriptComponents); - TerminalCmd* cmd = thread->getTerminalCmd(); + TerminalCmd *cmd = thread->getTerminalCmd(); while (i.hasNext()) { i.next(); ScriptComponent scriptComponent = i.value(); QVariantList cmdList, threadList; cmdList << cmd->executablePath << cmd->parameters << cmd->exitCode; - threadList << thread->getIndex() << thread ->getThreadCounter(); + threadList << thread->getIndex() << thread->getThreadCounter(); if (methodExistsForObject( - scriptComponent.object, QStringLiteral("onDetachedProcessCallback(QVariant,QVariant,QVariant,QVariant)"))) { - QMetaObject::invokeMethod( - scriptComponent.object, "onDetachedProcessCallback", - Q_ARG(QVariant, thread->getIdentifier()), - Q_ARG(QVariant, cmd->resultSet), - Q_ARG(QVariant, QVariant::fromValue(cmdList)), - Q_ARG(QVariant, QVariant::fromValue(threadList))); + scriptComponent.object, + QStringLiteral("onDetachedProcessCallback(QVariant,QVariant,QVariant,QVariant)"))) { + QMetaObject::invokeMethod(scriptComponent.object, "onDetachedProcessCallback", + Q_ARG(QVariant, thread->getIdentifier()), + Q_ARG(QVariant, cmd->resultSet), + Q_ARG(QVariant, QVariant::fromValue(cmdList)), + Q_ARG(QVariant, QVariant::fromValue(threadList))); } } } @@ -2404,11 +2297,11 @@ void ScriptingService::onScriptThreadDone(ScriptThread *thread) { * @return {QString} the cache dir path */ QString ScriptingService::cacheDir(const QString &subDir) const { - QString cacheDir = QStandardPaths::writableLocation( - QStandardPaths::CacheLocation) + QString("/scripts/"); + QString cacheDir = + QStandardPaths::writableLocation(QStandardPaths::CacheLocation) + QString("/scripts/"); if (!subDir.isEmpty()) { - cacheDir = QDir::toNativeSeparators(cacheDir + subDir); + cacheDir = QDir::toNativeSeparators(cacheDir + subDir); } QDir dir = QDir(cacheDir); @@ -2426,8 +2319,8 @@ QString ScriptingService::cacheDir(const QString &subDir) const { * @return {bool} true on success */ bool ScriptingService::clearCacheDir(const QString &subDir) const { - QString cacheDir = QStandardPaths::writableLocation( - QStandardPaths::CacheLocation) + QString("/scripts/"); + QString cacheDir = + QStandardPaths::writableLocation(QStandardPaths::CacheLocation) + QString("/scripts/"); if (!subDir.isEmpty()) { cacheDir = QDir::toNativeSeparators(cacheDir + subDir); @@ -2438,7 +2331,7 @@ bool ScriptingService::clearCacheDir(const QString &subDir) const { if (dir.exists()) { result = dir.removeRecursively(); - dir.mkpath(dir.path()); // recreate the folder + dir.mkpath(dir.path()); // recreate the folder } return result; @@ -2448,16 +2341,15 @@ bool ScriptingService::clearCacheDir(const QString &subDir) const { * Adds a highlighting rule to the syntax highlighter of the editor * * @param pattern {QString} the regular expression pattern to highlight - * @param shouldContain {QString} a string that must be contained in the highlighted text for the pattern to be parsed + * @param shouldContain {QString} a string that must be contained in the highlighted text for the + * pattern to be parsed * @param state {int} the state of the syntax highlighter to use - * @param capturingGroup {int} the capturing group for the pattern to use for highlighting (default: 0) + * @param capturingGroup {int} the capturing group for the pattern to use for highlighting (default: + * 0) * @param maskedGroup {int} the capturing group for the pattern to use for masking (default: 0) */ -void ScriptingService::addHighlightingRule(const QString &pattern, - const QString &shouldContain, - int state, - int capturingGroup, - int maskedGroup) { +void ScriptingService::addHighlightingRule(const QString &pattern, const QString &shouldContain, + int state, int capturingGroup, int maskedGroup) { QOwnNotesMarkdownHighlighter::ScriptingHighlightingRule rule( static_cast<MarkdownHighlighter::HighlighterState>(state)); rule.pattern = QRegularExpression(pattern); diff --git a/src/services/scriptingservice.h b/src/services/scriptingservice.h index 435e56e0f..f550eb5b4 100644 --- a/src/services/scriptingservice.h +++ b/src/services/scriptingservice.h @@ -3,12 +3,13 @@ #include <api/tagapi.h> #include <entities/script.h> #include <entities/tag.h> +#include <threads/scriptthread.h> #include <QMap> #include <QMessageBox> #include <QObject> #include <QVariant> -#include <threads/scriptthread.h> + #include "helpers/qownnotesmarkdownhighlighter.h" class ScriptThread; @@ -44,8 +45,7 @@ class ScriptingService : public QObject { QVariant callNoteTaggingHook(const Note ¬e, const QString &action, const QString &tagName = QString(), const QString &newTagName = QString()); - QVariant callNoteTaggingByObjectHook(const Note ¬e, - const QString &action, + QVariant callNoteTaggingByObjectHook(const Note ¬e, const QString &action, const Tag &tag = Tag(), const QString &newTagName = QString()); void callWindowStateChangeHook(const QString &windowStateStr); @@ -61,24 +61,24 @@ class ScriptingService : public QObject { const QVariant &callbackParameter = 0, const QByteArray &processData = QByteArray(), const QString &workingDirectory = ""); - Q_INVOKABLE QByteArray startSynchronousProcess( - const QString &executablePath, const QStringList ¶meters, - const QByteArray &data = QByteArray(), const QString &workingDirectory = "") const; + Q_INVOKABLE QByteArray startSynchronousProcess(const QString &executablePath, + const QStringList ¶meters, + const QByteArray &data = QByteArray(), + const QString &workingDirectory = "") const; Q_INVOKABLE QString currentNoteFolderPath(); Q_INVOKABLE NoteApi *currentNote() const; Q_INVOKABLE void log(QString text); Q_INVOKABLE QString downloadUrlToString(const QUrl &url); - Q_INVOKABLE QString downloadUrlToMedia(const QUrl &url, - bool returnUrlOnly = false); - Q_INVOKABLE QString insertMediaFile(const QString &mediaFilePath, - bool returnUrlOnly = false); + Q_INVOKABLE QString downloadUrlToMedia(const QUrl &url, bool returnUrlOnly = false); + Q_INVOKABLE QString insertMediaFile(const QString &mediaFilePath, bool returnUrlOnly = false); Q_INVOKABLE QString insertAttachmentFile(const QString &attachmentFilePath, - const QString &fileName, bool returnUrlOnly); - Q_INVOKABLE void registerCustomAction( - const QString &identifier, const QString &menuText, - const QString &buttonText = QString(), const QString &icon = QString(), - bool useInNoteEditContextMenu = false, bool hideButtonInToolbar = false, - bool useInNoteListContextMenu = false); + const QString &fileName, bool returnUrlOnly); + Q_INVOKABLE void registerCustomAction(const QString &identifier, const QString &menuText, + const QString &buttonText = QString(), + const QString &icon = QString(), + bool useInNoteEditContextMenu = false, + bool hideButtonInToolbar = false, + bool useInNoteListContextMenu = false); Q_INVOKABLE void createNote(QString text); Q_INVOKABLE QString clipboard(bool asHtml = false); Q_INVOKABLE void noteTextEditWrite(const QString &text); @@ -91,8 +91,7 @@ class ScriptingService : public QObject { Q_INVOKABLE int noteTextEditCursorPosition(); Q_INVOKABLE int noteTextEditSelectionStart(); Q_INVOKABLE int noteTextEditSelectionEnd(); - Q_INVOKABLE QString - noteTextEditCurrentWord(bool withPreviousCharacters = false); + Q_INVOKABLE QString noteTextEditCurrentWord(bool withPreviousCharacters = false); Q_INVOKABLE void encryptionDisablePassword(); Q_INVOKABLE bool platformIsLinux(); Q_INVOKABLE bool platformIsOSX(); @@ -100,23 +99,19 @@ class ScriptingService : public QObject { Q_INVOKABLE void tagCurrentNote(const QString &tagName); Q_INVOKABLE void addStyleSheet(const QString &stylesheet); Q_INVOKABLE void reloadScriptingEngine(); - Q_INVOKABLE NoteApi *fetchNoteByFileName(const QString &fileName, - int noteSubFolderId = -1); + Q_INVOKABLE NoteApi *fetchNoteByFileName(const QString &fileName, int noteSubFolderId = -1); Q_INVOKABLE NoteApi *fetchNoteById(int id); - Q_INVOKABLE bool noteExistsByFileName(const QString &fileName, - int ignoreNoteId = 0, + Q_INVOKABLE bool noteExistsByFileName(const QString &fileName, int ignoreNoteId = 0, int noteSubFolderId = -1); Q_INVOKABLE void setClipboardText(const QString &text, bool asHtml = false); Q_INVOKABLE void setCurrentNote(NoteApi *note, bool asTab = false); - Q_INVOKABLE void informationMessageBox(const QString &text, - const QString &title = QString()); + Q_INVOKABLE void informationMessageBox(const QString &text, const QString &title = QString()); - Q_INVOKABLE int questionMessageBox( - const QString &text, const QString &title = QString(), - int buttons = QMessageBox::StandardButtons(QMessageBox::Yes | - QMessageBox::No), - int defaultButton = QMessageBox::NoButton); + Q_INVOKABLE int questionMessageBox(const QString &text, const QString &title = QString(), + int buttons = QMessageBox::StandardButtons(QMessageBox::Yes | + QMessageBox::No), + int defaultButton = QMessageBox::NoButton); Q_INVOKABLE QString getOpenFileName(const QString &caption = QString(), const QString &dir = QString(), @@ -126,36 +121,28 @@ class ScriptingService : public QObject { const QString &dir = QString(), const QString &filter = QString()); - Q_INVOKABLE void registerLabel(const QString &identifier, - const QString &text = QString()); + Q_INVOKABLE void registerLabel(const QString &identifier, const QString &text = QString()); - Q_INVOKABLE void setLabelText(const QString &identifier, - const QString &text); + Q_INVOKABLE void setLabelText(const QString &identifier, const QString &text); - QString callInsertingFromMimeDataHookForObject(QObject *object, - const QMimeData *mimeData); + QString callInsertingFromMimeDataHookForObject(QObject *object, const QMimeData *mimeData); QString callInsertingFromMimeDataHook(const QMimeData *mimeData); - QString callHandleNoteTextFileNameHookForObject(QObject *object, - Note *note); + QString callHandleNoteTextFileNameHookForObject(QObject *object, Note *note); QString callHandleNoteTextFileNameHook(Note *note); QString callNoteToMarkdownHtmlHook(Note *note, const QString &html, const bool forExport); - QString callPreNoteToMarkdownHtmlHook(Note *note, const QString &markdown, const bool forExport); + QString callPreNoteToMarkdownHtmlHook(Note *note, const QString &markdown, + const bool forExport); - QString callHandleNewNoteHeadlineHookForObject(QObject *object, - const QString &headline); + QString callHandleNewNoteHeadlineHookForObject(QObject *object, const QString &headline); QString callHandleNewNoteHeadlineHook(const QString &headline); QString callEncryptionHookForObject(QObject *object, const QString &text, - const QString &password, - bool decrypt = false); - QString callEncryptionHook(const QString &text, const QString &password, - bool decrypt = false); + const QString &password, bool decrypt = false); + QString callEncryptionHook(const QString &text, const QString &password, bool decrypt = false); void callHandleNoteOpenedHook(Note *note); QString callHandleNoteNameHook(Note *note); bool callHandleNoteDoubleClickedHook(Note *note); - bool callHandleWebsocketRawDataHook(const QString &requestType, - const QString &pageUrl, - const QString &pageTitle, - const QString &rawData, + bool callHandleWebsocketRawDataHook(const QString &requestType, const QString &pageUrl, + const QString &pageTitle, const QString &rawData, const QString &screenshotDataUrl); QList<QVariant> getSettingsVariables(int scriptId); Q_INVOKABLE QString toNativeDirSeparators(const QString &path); @@ -163,59 +150,48 @@ class ScriptingService : public QObject { Q_INVOKABLE QString dirSeparator(); Q_INVOKABLE QStringList selectedNotesPaths(); - Q_INVOKABLE QString inputDialogGetItem(const QString &title, - const QString &label, - const QStringList &items, - int current = 0, + Q_INVOKABLE QString inputDialogGetItem(const QString &title, const QString &label, + const QStringList &items, int current = 0, bool editable = false); - Q_INVOKABLE QString inputDialogGetText(const QString &title, - const QString &label, + Q_INVOKABLE QString inputDialogGetText(const QString &title, const QString &label, const QString &text = QString()); - Q_INVOKABLE void setPersistentVariable(const QString &key, - const QVariant &value); + Q_INVOKABLE void setPersistentVariable(const QString &key, const QVariant &value); - Q_INVOKABLE void addHighlightingRule(const QString &pattern, - const QString &shouldContain, - int state, - int capturingGroup = 0, - int maskedGroup = 0); + Q_INVOKABLE void addHighlightingRule(const QString &pattern, const QString &shouldContain, + int state, int capturingGroup = 0, int maskedGroup = 0); QVector<QOwnNotesMarkdownHighlighter::ScriptingHighlightingRule> getHighlightingRules(); - Q_INVOKABLE QVariant getPersistentVariable( - const QString &key, const QVariant &defaultValue = QVariant()); + Q_INVOKABLE QVariant getPersistentVariable(const QString &key, + const QVariant &defaultValue = QVariant()); - Q_INVOKABLE QVariant getApplicationSettingsVariable( - const QString &key, const QVariant &defaultValue = QVariant()); + Q_INVOKABLE QVariant getApplicationSettingsVariable(const QString &key, + const QVariant &defaultValue = QVariant()); - Q_INVOKABLE bool jumpToNoteSubFolder( - const QString ¬eSubFolderPath, - const QString &separator = QStringLiteral("/")); + Q_INVOKABLE bool jumpToNoteSubFolder(const QString ¬eSubFolderPath, + const QString &separator = QStringLiteral("/")); QStringList callAutocompletionHook() const; Q_INVOKABLE QStringList searchTagsByName(const QString &name) const; - Q_INVOKABLE TagApi *getTagByNameBreadcrumbList( - const QStringList &nameList, bool createMissing = true) const; + Q_INVOKABLE TagApi *getTagByNameBreadcrumbList(const QStringList &nameList, + bool createMissing = true) const; Q_INVOKABLE void regenerateNotePreview() const; Q_INVOKABLE QList<int> selectedNotesIds() const; - Q_INVOKABLE bool writeToFile(const QString &filePath, - const QString &data, + Q_INVOKABLE bool writeToFile(const QString &filePath, const QString &data, const bool createParentDirs = false) const; - Q_INVOKABLE QString readFromFile(const QString &filePath, - const QString &codec = "UTF-8") const; + Q_INVOKABLE QString readFromFile(const QString &filePath, const QString &codec = "UTF-8") const; Q_INVOKABLE bool fileExists(const QString &filePath) const; - Q_INVOKABLE QVector<int> fetchNoteIdsByNoteTextPart( - const QString &text) const; + Q_INVOKABLE QVector<int> fetchNoteIdsByNoteTextPart(const QString &text) const; - Q_INVOKABLE void triggerMenuAction( - const QString &objectName, const QString &checked = QString()) const; + Q_INVOKABLE void triggerMenuAction(const QString &objectName, + const QString &checked = QString()) const; private: QQmlEngine *_engine; @@ -231,8 +207,7 @@ class ScriptingService : public QObject { void outputMethodsOfObject(QObject *object); void reloadScriptComponents(); void clearCustomStyleSheets(); - QList<QVariant> registerSettingsVariables(QObject *object, - const Script &script); + QList<QVariant> registerSettingsVariables(QObject *object, const Script &script); signals: void noteStored(QVariant note); @@ -241,7 +216,6 @@ class ScriptingService : public QObject { void onCurrentNoteChanged(Note *note); void reloadEngine(); void onCustomActionInvoked(const QString &identifier); - void callCustomActionInvokedForObject(QObject *object, - const QString &identifier); + void callCustomActionInvokedForObject(QObject *object, const QString &identifier); void onScriptThreadDone(ScriptThread *thread); }; diff --git a/src/services/updateservice.cpp b/src/services/updateservice.cpp index 0e7e98f42..f6ee95bdf 100644 --- a/src/services/updateservice.cpp +++ b/src/services/updateservice.cpp @@ -25,13 +25,11 @@ void UpdateService::checkForUpdates(UpdateMode updateMode) { QSettings settings; if (updateMode != Manual) { - settings.setValue(QStringLiteral("LastUpdateCheck"), - QDateTime::currentDateTime()); + settings.setValue(QStringLiteral("LastUpdateCheck"), QDateTime::currentDateTime()); } auto *manager = new QNetworkAccessManager(this); - connect(manager, SIGNAL(finished(QNetworkReply *)), this, - SLOT(onResult(QNetworkReply *))); + connect(manager, SIGNAL(finished(QNetworkReply *)), this, SLOT(onResult(QNetworkReply *))); bool isDebug; @@ -41,9 +39,8 @@ void UpdateService::checkForUpdates(UpdateMode updateMode) { isDebug = true; #endif -// QUrl url("http://localhost:8000/latest_releases/" + - QUrl url("https://api.qownnotes.org/latest_releases/" + - QStringLiteral(PLATFORM)); + // QUrl url("http://localhost:8000/latest_releases/" + + QUrl url("https://api.qownnotes.org/latest_releases/" + QStringLiteral(PLATFORM)); QUrlQuery q; QString version(VERSION); @@ -58,19 +55,15 @@ void UpdateService::checkForUpdates(UpdateMode updateMode) { q.addQueryItem(QStringLiteral("um"), QString::number(updateMode)); q.addQueryItem(QStringLiteral("debug"), QString::number(isDebug)); - if (!settings.value(QStringLiteral("appMetrics/disableTracking")) - .toBool() || - !settings.value(QStringLiteral("appMetrics/disableAppHeartbeat")) - .toBool()) { - q.addQueryItem( - QStringLiteral("cid"), - settings.value(QStringLiteral("PiwikClientId")).toString()); + if (!settings.value(QStringLiteral("appMetrics/disableTracking")).toBool() || + !settings.value(QStringLiteral("appMetrics/disableAppHeartbeat")).toBool()) { + q.addQueryItem(QStringLiteral("cid"), + settings.value(QStringLiteral("PiwikClientId")).toString()); } #if (QT_VERSION >= QT_VERSION_CHECK(5, 4, 0)) - q.addQueryItem(QStringLiteral("release"), - qApp->property("release").toString() + " (" + - QSysInfo::buildCpuArchitecture() + ")"); + q.addQueryItem(QStringLiteral("release"), qApp->property("release").toString() + " (" + + QSysInfo::buildCpuArchitecture() + ")"); QString operatingSystem = QSysInfo::prettyProductName(); if (!operatingSystem.contains(QSysInfo::currentCpuArchitecture())) { @@ -84,12 +77,12 @@ void UpdateService::checkForUpdates(UpdateMode updateMode) { url.setQuery(q); -// QNetworkRequest r(url); -// QString concatenated(QStringLiteral("xxx:xxx")); -// QByteArray data = concatenated.toLocal8Bit().toBase64(); -// QString headerData = QStringLiteral("Basic ") + data; -// r.setRawHeader("Authorization", headerData.toLocal8Bit()); -// manager->get(r); + // QNetworkRequest r(url); + // QString concatenated(QStringLiteral("xxx:xxx")); + // QByteArray data = concatenated.toLocal8Bit().toBase64(); + // QString headerData = QStringLiteral("Basic ") + data; + // r.setRawHeader("Authorization", headerData.toLocal8Bit()); + // manager->get(r); manager->get(QNetworkRequest(url)); } @@ -104,13 +97,11 @@ void UpdateService::onResult(QNetworkReply *reply) { // abort if there was an error if (reply->error() != QNetworkReply::NoError) { - qWarning() << __func__ - << " - 'network reply error': " << reply->error(); + qWarning() << __func__ << " - 'network reply error': " << reply->error(); if (this->updateMode == UpdateService::Manual) { - QMessageBox::warning( - nullptr, tr("Update-checker error"), - tr("Network reply error: %1").arg(reply->error())); + QMessageBox::warning(nullptr, tr("Update-checker error"), + tr("Network reply error: %1").arg(reply->error())); } return; @@ -123,9 +114,8 @@ void UpdateService::onResult(QNetworkReply *reply) { "request'"; if (this->updateMode == UpdateService::Manual) { - QMessageBox::warning( - nullptr, tr("Update-checker error"), - tr("No data was received by the network request!")); + QMessageBox::warning(nullptr, tr("Update-checker error"), + tr("No data was received by the network request!")); } return; @@ -144,33 +134,27 @@ void UpdateService::onResult(QNetworkReply *reply) { << allData; if (this->updateMode == UpdateService::Manual) { - QMessageBox::warning( - nullptr, tr("Update-checker error"), - tr("The data from the network request could not be " - "interpreted!")); + QMessageBox::warning(nullptr, tr("Update-checker error"), + tr("The data from the network request could not be " + "interpreted!")); } return; } // get the information if we should update our app - bool shouldUpdate = result.property(QStringLiteral("0")) - .property(QStringLiteral("needUpdate")) - .toBool(); + bool shouldUpdate = + result.property(QStringLiteral("0")).property(QStringLiteral("needUpdate")).toBool(); // check if we should update our app if (shouldUpdate) { // get the release url QString releaseUrl = - result.property(QStringLiteral("0")) - .property(QStringLiteral("url")) - .toString(); + result.property(QStringLiteral("0")).property(QStringLiteral("url")).toString(); // get the release version string QString releaseVersionString = - result.property(QStringLiteral("0")) - .property(QStringLiteral("version")) - .toString(); + result.property(QStringLiteral("0")).property(QStringLiteral("version")).toString(); // get the changes html QString changesHtml = result.property(QStringLiteral("0")) @@ -185,8 +169,7 @@ void UpdateService::onResult(QNetworkReply *reply) { // do some more checks for non manual update requests if (updateMode != UpdateService::Manual) { QSettings settings; - QString skipVersion = - settings.value(QStringLiteral("skipVersion")).toString(); + QString skipVersion = settings.value(QStringLiteral("skipVersion")).toString(); // check if this version should be skipped if (releaseVersionString == skipVersion) { @@ -197,8 +180,7 @@ void UpdateService::onResult(QNetworkReply *reply) { // if the dialog is not open but there is a new release version // string open it anyway - if (!showUpdateDialog && - releaseVersionString != _currentReleaseVersionString) { + if (!showUpdateDialog && releaseVersionString != _currentReleaseVersionString) { showUpdateDialog = true; } } @@ -206,17 +188,14 @@ void UpdateService::onResult(QNetworkReply *reply) { // check if the update dialog was disabled if (showUpdateDialog) { showUpdateDialog = - !settings - .value(QStringLiteral("disableAutomaticUpdateDialog")) - .toBool(); + !settings.value(QStringLiteral("disableAutomaticUpdateDialog")).toBool(); } } if (showUpdateDialog) { // if there already is an update dialog and if it is open // then close and remove the old one - if (_updateDialog != nullptr && - UpdateDialog::isUpdateDialogOpen()) { + if (_updateDialog != nullptr && UpdateDialog::isUpdateDialogOpen()) { _updateDialog->close(); _updateDialog->deleteLater(); delete _updateDialog; @@ -235,8 +214,7 @@ void UpdateService::onResult(QNetworkReply *reply) { // open the update dialog _updateDialog = - new UpdateDialog(nullptr, changesHtml, releaseUrl, - releaseVersionString); + new UpdateDialog(nullptr, changesHtml, releaseUrl, releaseVersionString); // try to prevent stealing of focus on periodic checks if (this->updateMode == UpdateService::Periodic) { @@ -249,11 +227,10 @@ void UpdateService::onResult(QNetworkReply *reply) { MainWindow::instance()->hideUpdateAvailableButton(); if (this->updateMode == UpdateService::Manual) { - QMessageBox::information( - nullptr, tr("No updates"), - tr("There are no updates available.<br /><strong>%1" - "</strong> is the latest version.") - .arg(QStringLiteral(VERSION))); + QMessageBox::information(nullptr, tr("No updates"), + tr("There are no updates available.<br /><strong>%1" + "</strong> is the latest version.") + .arg(QStringLiteral(VERSION))); } } } diff --git a/src/services/webappclientservice.cpp b/src/services/webappclientservice.cpp index 6dd6a02c4..1369418db 100644 --- a/src/services/webappclientservice.cpp +++ b/src/services/webappclientservice.cpp @@ -20,11 +20,12 @@ #endif #include <utils/misc.h> + #include <QJsonDocument> #include <QSettings> -#include <QtWebSockets> #include <QSslError> #include <QWebSocket> +#include <QtWebSockets> #include "metricsservice.h" @@ -32,8 +33,7 @@ using namespace std; QT_USE_NAMESPACE -WebAppClientService::WebAppClientService(QObject *parent) - : QObject(parent) { +WebAppClientService::WebAppClientService(QObject *parent) : QObject(parent) { if (!Utils::Misc::isWebAppSupportEnabled()) { return; } @@ -43,7 +43,8 @@ WebAppClientService::WebAppClientService(QObject *parent) connect(_webSocket, &QWebSocket::connected, this, &WebAppClientService::onConnected); connect(_webSocket, &QWebSocket::disconnected, this, &WebAppClientService::onDisconnected); connect(_webSocket, &QWebSocket::sslErrors, this, &WebAppClientService::onSslErrors); - connect(_webSocket, &QWebSocket::textMessageReceived, this, &WebAppClientService::onTextMessageReceived); + connect(_webSocket, &QWebSocket::textMessageReceived, this, + &WebAppClientService::onTextMessageReceived); connect(&_timerHeartbeat, SIGNAL(timeout()), this, SLOT(onSendHeartbeatText())); connect(&_timerReconnect, SIGNAL(timeout()), this, SLOT(onReconnect())); @@ -63,8 +64,9 @@ void WebAppClientService::close() { } QString WebAppClientService::getServerUrl() { - return QSettings().value(QStringLiteral("webAppClientService/serverUrl"), - getDefaultServerUrl()).toString(); + return QSettings() + .value(QStringLiteral("webAppClientService/serverUrl"), getDefaultServerUrl()) + .toString(); } QString WebAppClientService::getOrGenerateToken() { @@ -99,8 +101,8 @@ void WebAppClientService::onConnected() { _reconnectFailedCount = 0; _heartbeatFailedCount = 0; - Utils::Misc::printInfo(tr("QOwnNotes is now connected via websocket to %1") - .arg(getServerUrl())); + Utils::Misc::printInfo( + tr("QOwnNotes is now connected via websocket to %1").arg(getServerUrl())); } void WebAppClientService::onDisconnected() { @@ -108,8 +110,8 @@ void WebAppClientService::onDisconnected() { _timerHeartbeat.stop(); _timerReconnect.start(_reconnectTime); - Utils::Misc::printInfo(tr("QOwnNotes is now disconnected from websocket to %1") - .arg(getServerUrl())); + Utils::Misc::printInfo( + tr("QOwnNotes is now disconnected from websocket to %1").arg(getServerUrl())); } void WebAppClientService::onTextMessageReceived(const QString &message) { @@ -123,9 +125,7 @@ void WebAppClientService::onTextMessageReceived(const QString &message) { qWarning() << "Web app warning: " << msg; #ifndef INTEGRATION_TESTS - Utils::Gui::warning( - nullptr, tr("Web app warning"), msg, - "wepappclientservice-warning"); + Utils::Gui::warning(nullptr, tr("Web app warning"), msg, "wepappclientservice-warning"); #endif } else if (command == "insertFile") { #ifndef INTEGRATION_TESTS @@ -138,8 +138,7 @@ void WebAppClientService::onTextMessageReceived(const QString &message) { if (Utils::Gui::question(mainWindow, tr("Image received"), tr("Insert image received from QOwnNotes web application?"), - QStringLiteral("webapp-insert-image")) == - QMessageBox::Yes) { + QStringLiteral("webapp-insert-image")) == QMessageBox::Yes) { // insert image into current note mainWindow->insertDataUrlAsFileIntoCurrentNote(fileDataUrl); } @@ -151,13 +150,11 @@ void WebAppClientService::onTextMessageReceived(const QString &message) { } } -void WebAppClientService::onSslErrors(const QList<QSslError> &errors) { - qCritical() << errors; -} +void WebAppClientService::onSslErrors(const QList<QSslError> &errors) { qCritical() << errors; } void WebAppClientService::onSendHeartbeatText() { const QString &heartbeatText = "qon-ping"; - auto sendByte = _webSocket->sendTextMessage(heartbeatText); + auto sendByte = _webSocket->sendTextMessage(heartbeatText); if (sendByte != heartbeatText.toLocal8Bit().length()) { _heartbeatFailedCount++; diff --git a/src/services/webappclientservice.h b/src/services/webappclientservice.h index cbb2dd351..a722df370 100644 --- a/src/services/webappclientservice.h +++ b/src/services/webappclientservice.h @@ -15,8 +15,8 @@ #pragma once #include <QObject> -#include <QTimer> #include <QSslError> +#include <QTimer> class QWebSocket; class QSslError; @@ -38,18 +38,19 @@ class WebAppClientService : public QObject { void onConnected(); void onDisconnected(); void onTextMessageReceived(const QString &message); - static void onSslErrors(const QList<QSslError>& errors); + static void onSslErrors(const QList<QSslError> &errors); void onSendHeartbeatText(); void onReconnect(); private: QWebSocket *_webSocket{}; QString _url; - const int _heartbeatTime = 600000; // heartbeat data transmission time interval in ms - const int _reconnectHeartbeatTimerCount = 10; // needs heartbeat reconnection transmission failures - const int _reconnectTime = 20000; // reconnection time interval in ms - int _heartbeatFailedCount = 0; // send heartbeat failures - int _reconnectFailedCount = 0; // reconnection failures - QTimer _timerHeartbeat; // send heartbeat timer - QTimer _timerReconnect; // reconnection timer + const int _heartbeatTime = 600000; // heartbeat data transmission time interval in ms + const int _reconnectHeartbeatTimerCount = + 10; // needs heartbeat reconnection transmission failures + const int _reconnectTime = 20000; // reconnection time interval in ms + int _heartbeatFailedCount = 0; // send heartbeat failures + int _reconnectFailedCount = 0; // reconnection failures + QTimer _timerHeartbeat; // send heartbeat timer + QTimer _timerReconnect; // reconnection timer }; diff --git a/src/services/websocketserverservice.cpp b/src/services/websocketserverservice.cpp index 1a4393aed..2115793fd 100644 --- a/src/services/websocketserverservice.cpp +++ b/src/services/websocketserverservice.cpp @@ -45,9 +45,8 @@ static QString getIdentifier(QWebSocket *peer) { WebSocketServerService::WebSocketServerService(quint16 port, QObject *parent) : QObject(parent), - m_pWebSocketServer( - new QWebSocketServer(QStringLiteral("QOwnNotes Server"), - QWebSocketServer::NonSecureMode, this)) { + m_pWebSocketServer(new QWebSocketServer(QStringLiteral("QOwnNotes Server"), + QWebSocketServer::NonSecureMode, this)) { #ifndef INTEGRATION_TESTS _webSocketTokenDialog = nullptr; #endif @@ -65,15 +64,13 @@ void WebSocketServerService::listen(quint16 port) { close(); if (m_pWebSocketServer->listen(QHostAddress::LocalHost, port)) { - Utils::Misc::printInfo(tr("QOwnNotes server listening on port %1") - .arg(QString::number(port))); + Utils::Misc::printInfo( + tr("QOwnNotes server listening on port %1").arg(QString::number(port))); - connect(m_pWebSocketServer, SIGNAL(newConnection()), this, - SLOT(onNewConnection())); + connect(m_pWebSocketServer, SIGNAL(newConnection()), this, SLOT(onNewConnection())); m_port = port; } else { - qWarning() << tr("Could not start QOwnNotes server on port %1!") - .arg(QString::number(port)); + qWarning() << tr("Could not start QOwnNotes server on port %1!").arg(QString::number(port)); } } @@ -89,9 +86,7 @@ quint16 WebSocketServerService::getPort() const { return m_port; } quint16 WebSocketServerService::getSettingsPort() { QSettings settings; quint16 port = static_cast<quint16>( - settings - .value(QStringLiteral("webSocketServerService/port"), - getDefaultPort()) + settings.value(QStringLiteral("webSocketServerService/port"), getDefaultPort()) .toULongLong()); return port; } @@ -105,9 +100,7 @@ quint16 WebSocketServerService::getDefaultPort() { #endif } -WebSocketServerService::~WebSocketServerService() { - m_pWebSocketServer->close(); -} +WebSocketServerService::~WebSocketServerService() { m_pWebSocketServer->close(); } void WebSocketServerService::onNewConnection() { auto pSocket = m_pWebSocketServer->nextPendingConnection(); @@ -116,14 +109,12 @@ void WebSocketServerService::onNewConnection() { return; } - Utils::Misc::printInfo( - tr("%1 connected to QOwnNotes server!").arg(getIdentifier(pSocket))); + Utils::Misc::printInfo(tr("%1 connected to QOwnNotes server!").arg(getIdentifier(pSocket))); pSocket->setParent(this); connect(pSocket, &QWebSocket::textMessageReceived, this, &WebSocketServerService::processMessage); - connect(pSocket, &QWebSocket::disconnected, this, - &WebSocketServerService::socketDisconnected); + connect(pSocket, &QWebSocket::disconnected, this, &WebSocketServerService::socketDisconnected); m_clients << pSocket; } @@ -136,9 +127,7 @@ void WebSocketServerService::processMessage(const QString &message) { MetricsService::instance()->sendVisitIfEnabled("websocket/message/" + type); const QString token = jsonObject.value(QStringLiteral("token")).toString(); QSettings settings; - QString storedToken = - settings.value(QStringLiteral("webSocketServerService/token")) - .toString(); + QString storedToken = settings.value(QStringLiteral("webSocketServerService/token")).toString(); // request the token if not set if (token.isEmpty() || storedToken.isEmpty() || token != storedToken) { @@ -166,17 +155,13 @@ void WebSocketServerService::processMessage(const QString &message) { return; } - const QString pageUrl = - jsonObject.value(QStringLiteral("pageUrl")).toString().trimmed(); - const QString contentType = - jsonObject.value(QStringLiteral("contentType")).toString(); + const QString pageUrl = jsonObject.value(QStringLiteral("pageUrl")).toString().trimmed(); + const QString contentType = jsonObject.value(QStringLiteral("contentType")).toString(); const QString name = - Note::cleanupFileName( - Note::extendedCleanupFileName( - jsonObject.value(QStringLiteral("headline")).toString())) + Note::cleanupFileName(Note::extendedCleanupFileName( + jsonObject.value(QStringLiteral("headline")).toString())) .trimmed(); - QString text = - jsonObject.value(QStringLiteral("text")).toString().trimmed(); + QString text = jsonObject.value(QStringLiteral("text")).toString().trimmed(); // Attempt to transform links starting with a "/" like "/my-page.html" to // "http://domain.com/my-page.html" @@ -189,35 +174,26 @@ void WebSocketServerService::processMessage(const QString &message) { // websocketRawDataHook used in a script if (isHandleRawData) { const QString requestType = - jsonObject.value(QStringLiteral("requestType")) - .toString() - .trimmed(); + jsonObject.value(QStringLiteral("requestType")).toString().trimmed(); const QString pageTitle = - jsonObject.value(QStringLiteral("pageTitle")) - .toString() - .trimmed(); - const QString rawData = jsonObject.value(QStringLiteral("rawData")) - .toString() - .trimmed(); + jsonObject.value(QStringLiteral("pageTitle")).toString().trimmed(); + const QString rawData = + jsonObject.value(QStringLiteral("rawData")).toString().trimmed(); const QString screenshotDataUrl = - jsonObject.value(QStringLiteral("screenshotDataUrl")) - .toString() - .trimmed(); + jsonObject.value(QStringLiteral("screenshotDataUrl")).toString().trimmed(); // call websocketRawDataHook isCreateNewNote = !ScriptingService::instance()->callHandleWebsocketRawDataHook( - requestType, pageUrl, pageTitle, rawData, screenshotDataUrl); + requestType, pageUrl, pageTitle, rawData, screenshotDataUrl); } if (isCreateNewNote) { - mainWindow->createNewNote( - name, contentTypeIsHTML ? QString() : text, - MainWindow::CreateNewNoteOptions( - MainWindow::CreateNewNoteOption::UseNameAsHeadline)); + mainWindow->createNewNote(name, contentTypeIsHTML ? QString() : text, + MainWindow::CreateNewNoteOptions( + MainWindow::CreateNewNoteOption::UseNameAsHeadline)); if (contentTypeIsHTML) { - mainWindow->insertHtmlAsMarkdownIntoCurrentNote( - std::move(text)); + mainWindow->insertHtmlAsMarkdownIntoCurrentNote(std::move(text)); } } #endif @@ -238,8 +214,8 @@ void WebSocketServerService::processMessage(const QString &message) { } else if (type == QLatin1String("newBookmarks")) { QJsonArray bookmarkList = createBookmarks(jsonObject); - pSender->sendTextMessage(flashMessageJsonText( - tr("%n bookmark(s) created", "", bookmarkList.count()))); + pSender->sendTextMessage( + flashMessageJsonText(tr("%n bookmark(s) created", "", bookmarkList.count()))); } else if (type == QLatin1String("switchNoteFolder")) { #ifndef INTEGRATION_TESTS MainWindow *mainWindow = MainWindow::instance(); @@ -250,8 +226,7 @@ void WebSocketServerService::processMessage(const QString &message) { return; } - const int noteFolderId = - jsonObject.value(QStringLiteral("data")).toInt(); + const int noteFolderId = jsonObject.value(QStringLiteral("data")).toInt(); if (noteFolderId == NoteFolder::currentNoteFolderId()) { pSender->sendTextMessage(getNoteFolderSwitchedJsonText(false)); @@ -288,8 +263,7 @@ void WebSocketServerService::processMessage(const QString &message) { #endif } else { QJsonObject resultObject; - resultObject.insert(QStringLiteral("type"), - QJsonValue::fromVariant("unknownMessage")); + resultObject.insert(QStringLiteral("type"), QJsonValue::fromVariant("unknownMessage")); resultObject.insert(QStringLiteral("data"), message); QJsonDocument doc(resultObject); @@ -297,8 +271,7 @@ void WebSocketServerService::processMessage(const QString &message) { } } -QJsonArray WebSocketServerService::createBookmarks( - const QJsonObject &jsonObject) { +QJsonArray WebSocketServerService::createBookmarks(const QJsonObject &jsonObject) { const QString bookmarksNoteName = getBookmarksNoteName(); Note bookmarksNote = Note::fetchByName(bookmarksNoteName); bool applyTag = false; @@ -311,8 +284,7 @@ QJsonArray WebSocketServerService::createBookmarks( } QString noteText = bookmarksNote.getNoteText().trimmed(); - QJsonArray bookmarkList = - jsonObject.value(QStringLiteral("data")).toArray(); + QJsonArray bookmarkList = jsonObject.value(QStringLiteral("data")).toArray(); Q_FOREACH (QJsonValue bookmarkObject, bookmarkList) { const QJsonObject data = bookmarkObject.toObject(); @@ -321,10 +293,8 @@ QJsonArray WebSocketServerService::createBookmarks( .trimmed() .remove(QStringLiteral("[")) .remove(QStringLiteral("]")); - const QString url = - data.value(QStringLiteral("url")).toString().trimmed(); - const QString description = - data.value(QStringLiteral("description")).toString().trimmed(); + const QString url = data.value(QStringLiteral("url")).toString().trimmed(); + const QString description = data.value(QStringLiteral("description")).toString().trimmed(); noteText += "\n- [" + name + "](" + url + ")"; @@ -367,8 +337,8 @@ QString WebSocketServerService::getBookmarksJsonText() { } // extract links from the current note - QVector<Bookmark> currentNoteBookmarks = Bookmark::parseBookmarks( - mainWindow->activeNoteTextEdit()->toPlainText(), true); + QVector<Bookmark> currentNoteBookmarks = + Bookmark::parseBookmarks(mainWindow->activeNoteTextEdit()->toPlainText(), true); // merge bookmark lists Bookmark::mergeListInList(currentNoteBookmarks, bookmarks); @@ -392,8 +362,7 @@ QString WebSocketServerService::getNoteFoldersJsonText() { } QJsonObject noteFolderResultObject; - noteFolderResultObject.insert(QStringLiteral("type"), - QJsonValue::fromVariant("noteFolders")); + noteFolderResultObject.insert(QStringLiteral("type"), QJsonValue::fromVariant("noteFolders")); noteFolderResultObject.insert(QStringLiteral("data"), noteFolderObjectList); noteFolderResultObject.insert(QStringLiteral("currentId"), NoteFolder::currentNoteFolderId()); @@ -421,8 +390,8 @@ QString WebSocketServerService::getCommandSnippetsJsonText() { } // extract command snippets from the current note - QVector<CommandSnippet> currentNoteCommandSnippets = CommandSnippet::parseCommandSnippets( - mainWindow->activeNoteTextEdit()->toPlainText(), true); + QVector<CommandSnippet> currentNoteCommandSnippets = + CommandSnippet::parseCommandSnippets(mainWindow->activeNoteTextEdit()->toPlainText(), true); // merge command snippet lists CommandSnippet::mergeListInList(currentNoteCommandSnippets, commandSnippets); @@ -438,11 +407,9 @@ QString WebSocketServerService::getCommandSnippetsJsonText() { * @param switched * @return */ -QString WebSocketServerService::getNoteFolderSwitchedJsonText( - bool switched) { +QString WebSocketServerService::getNoteFolderSwitchedJsonText(bool switched) { QJsonObject object; - object.insert(QStringLiteral("type"), - QJsonValue::fromVariant("switchedNoteFolder")); + object.insert(QStringLiteral("type"), QJsonValue::fromVariant("switchedNoteFolder")); object.insert(QStringLiteral("data"), QJsonValue::fromVariant(switched)); QJsonDocument doc(object); @@ -456,8 +423,7 @@ QString WebSocketServerService::getNoteFolderSwitchedJsonText( */ QString WebSocketServerService::getTokenQueryJsonText() { QJsonObject object; - object.insert(QStringLiteral("type"), - QJsonValue::fromVariant("tokenQuery")); + object.insert(QStringLiteral("type"), QJsonValue::fromVariant("tokenQuery")); QJsonDocument doc(object); return doc.toJson(QJsonDocument::Compact); @@ -467,8 +433,8 @@ void WebSocketServerService::socketDisconnected() { auto *pClient = qobject_cast<QWebSocket *>(sender()); if (pClient != nullptr) { - Utils::Misc::printInfo(tr("%1 was disconnected from QOwnNotes server") - .arg(getIdentifier(pClient))); + Utils::Misc::printInfo( + tr("%1 was disconnected from QOwnNotes server").arg(getIdentifier(pClient))); m_clients.removeAll(pClient); pClient->deleteLater(); @@ -477,36 +443,31 @@ void WebSocketServerService::socketDisconnected() { QString WebSocketServerService::getBookmarksTag() { return QSettings() - .value(QStringLiteral("webSocketServerService/bookmarksTag"), - "bookmarks") - .toString(); + .value(QStringLiteral("webSocketServerService/bookmarksTag"), "bookmarks") + .toString(); } QString WebSocketServerService::getBookmarksNoteName() { return QSettings() - .value(QStringLiteral("webSocketServerService/bookmarksNoteName"), - "Bookmarks") - .toString(); + .value(QStringLiteral("webSocketServerService/bookmarksNoteName"), "Bookmarks") + .toString(); } QString WebSocketServerService::getCommandSnippetsTag() { return QSettings() - .value(QStringLiteral("webSocketServerService/commandSnippetsTag"), - "commands") - .toString(); + .value(QStringLiteral("webSocketServerService/commandSnippetsTag"), "commands") + .toString(); } QString WebSocketServerService::getCommandSnippetsNoteName() { return QSettings() - .value(QStringLiteral("webSocketServerService/commandSnippetsNoteName"), - "Commands") - .toString(); + .value(QStringLiteral("webSocketServerService/commandSnippetsNoteName"), "Commands") + .toString(); } QString WebSocketServerService::flashMessageJsonText(const QString &message) { QJsonObject resultObject; - resultObject.insert(QStringLiteral("type"), - QJsonValue::fromVariant("flashMessage")); + resultObject.insert(QStringLiteral("type"), QJsonValue::fromVariant("flashMessage")); resultObject.insert(QStringLiteral("message"), message); resultObject.insert(QStringLiteral("noteFolderName"), NoteFolder::currentNoteFolder().getName()); diff --git a/src/services/websocketserverservice.h b/src/services/websocketserverservice.h index fe4ae1c0f..94c5ba8fb 100644 --- a/src/services/websocketserverservice.h +++ b/src/services/websocketserverservice.h @@ -24,8 +24,7 @@ class WebSocketTokenDialog; class WebSocketServerService : public QObject { Q_OBJECT public: - explicit WebSocketServerService(quint16 port = 0, - QObject *parent = nullptr); + explicit WebSocketServerService(quint16 port = 0, QObject *parent = nullptr); ~WebSocketServerService() override; quint16 getPort() const; @@ -60,13 +59,13 @@ class WebSocketServerService : public QObject { QList<QWebSocket *> m_clients; quint16 m_port{}; - static QString getBookmarksJsonText() ; + static QString getBookmarksJsonText(); static QString getCommandSnippetsJsonText(); - static QString getNoteFolderSwitchedJsonText(bool switched) ; + static QString getNoteFolderSwitchedJsonText(bool switched); - static QString getTokenQueryJsonText() ; + static QString getTokenQueryJsonText(); static QString getNoteFoldersJsonText(); diff --git a/src/utils/git.cpp b/src/utils/git.cpp index 7af6543ef..36d2337e3 100644 --- a/src/utils/git.cpp +++ b/src/utils/git.cpp @@ -18,8 +18,8 @@ #include <QDebug> #include <QProcess> -#include <QtCore/QSettings> #include <QStandardPaths> +#include <QtCore/QSettings> #include "gui.h" #include "misc.h" @@ -29,9 +29,7 @@ * * @return */ -bool Utils::Git::isCurrentNoteFolderUseGit() { - return NoteFolder::currentNoteFolder().isUseGit(); -} +bool Utils::Git::isCurrentNoteFolderUseGit() { return NoteFolder::currentNoteFolder().isUseGit(); } /** * Commits changes from the current note folder to git @@ -94,8 +92,7 @@ bool Utils::Git::executeCommand(const QString& command, const QStringList& argum QByteArray errorMessage = process->readAllStandardError(); if (!errorMessage.isEmpty()) { - qWarning() << "Error message by '" + command + "' (" << arguments - << "): " + errorMessage; + qWarning() << "Error message by '" + command + "' (" << arguments << "): " + errorMessage; } return true; @@ -108,8 +105,8 @@ bool Utils::Git::executeCommand(const QString& command, const QStringList& argum * @param process * @return */ -bool Utils::Git::executeGitCommand(const QString &gitExe, const QStringList& arguments, QProcess* process, - bool withErrorDialog) { +bool Utils::Git::executeGitCommand(const QString& gitExe, const QStringList& arguments, + QProcess* process, bool withErrorDialog) { return executeCommand(gitExe, arguments, process, withErrorDialog); } @@ -128,7 +125,7 @@ QString Utils::Git::gitCommand() { } #ifdef Q_OS_WIN - path = "git.exe"; // FIXME: is the ".exe" even needed? I don't think so + path = "git.exe"; // FIXME: is the ".exe" even needed? I don't think so #else path = "git"; #endif @@ -185,6 +182,5 @@ void Utils::Git::showLog(const QString& filePath) { parameters << "-c" << gitLogCommand; #endif - Utils::Misc::startDetachedProcess(command, parameters, - NoteFolder::currentLocalPath()); + Utils::Misc::startDetachedProcess(command, parameters, NoteFolder::currentLocalPath()); } diff --git a/src/utils/git.h b/src/utils/git.h index 60b1b8447..c65ce00bf 100644 --- a/src/utils/git.h +++ b/src/utils/git.h @@ -24,8 +24,8 @@ namespace Git { void commitCurrentNoteFolder(); bool executeCommand(const QString& command, const QStringList& arguments, QProcess* process = nullptr, bool withErrorDialog = false); -bool executeGitCommand(const QString &gitExe, const QStringList& arguments, QProcess* process = nullptr, - bool withErrorDialog = true); +bool executeGitCommand(const QString& gitExe, const QStringList& arguments, + QProcess* process = nullptr, bool withErrorDialog = true); QString gitCommand(); void showLog(const QString& filePath); bool hasLogCommand(); diff --git a/src/utils/gui.cpp b/src/utils/gui.cpp index efdaa17e9..42e24d517 100644 --- a/src/utils/gui.cpp +++ b/src/utils/gui.cpp @@ -14,28 +14,28 @@ #include "gui.h" -#include <libraries/qmarkdowntextedit/markdownhighlighter.h> #include <entities/notefolder.h> #include <entities/notesubfolder.h> #include <entities/tag.h> +#include <libraries/qmarkdowntextedit/markdownhighlighter.h> #include <QApplication> #include <QCheckBox> #include <QClipboard> +#include <QComboBox> #include <QDebug> #include <QDialogButtonBox> +#include <QDockWidget> +#include <QListWidget> #include <QMessageBox> +#include <QPlainTextEdit> +#include <QProcess> #include <QPushButton> #include <QSettings> #include <QTextBlock> #include <QTextCursor> -#include <QComboBox> -#include <QListWidget> -#include <QPlainTextEdit> #include <QTreeWidgetItem> #include <QVBoxLayout> -#include <QDockWidget> -#include <QProcess> #define ORDER_ASCENDING 0 // Qt::AscendingOrder // = 0 #define ORDER_DESCENDING 1 // Qt::DescendingOrder // = 1 @@ -61,8 +61,7 @@ bool Utils::Gui::isOneTreeWidgetItemChildVisible(QTreeWidgetItem *item) { /** * Searches for text in items of a tree widget */ -void Utils::Gui::searchForTextInTreeWidget(QTreeWidget *treeWidget, - const QString &text, +void Utils::Gui::searchForTextInTreeWidget(QTreeWidget *treeWidget, const QString &text, TreeWidgetSearchFlags searchFlags) { QStringList searchList; @@ -80,9 +79,7 @@ void Utils::Gui::searchForTextInTreeWidget(QTreeWidget *treeWidget, // search text if at least one character was entered if (text.count() >= 1) { int searchColumnCount = - searchFlags & TreeWidgetSearchFlag::AllColumnsSearch - ? treeWidget->columnCount() - : 1; + searchFlags & TreeWidgetSearchFlag::AllColumnsSearch ? treeWidget->columnCount() : 1; // hide all not found items Q_FOREACH (QTreeWidgetItem *item, allItems) { @@ -94,13 +91,11 @@ void Utils::Gui::searchForTextInTreeWidget(QTreeWidget *treeWidget, foreach (QString searchText, searchList) { // search for text in the columns - bool loopShow2 = item->text(index).contains( - searchText, Qt::CaseInsensitive); + bool loopShow2 = item->text(index).contains(searchText, Qt::CaseInsensitive); // also show the item if the text was found in the tooltip if (searchFlags & TreeWidgetSearchFlag::TooltipSearch) { - loopShow2 |= item->toolTip(index).contains( - searchText, Qt::CaseInsensitive); + loopShow2 |= item->toolTip(index).contains(searchText, Qt::CaseInsensitive); } loopShow &= loopShow2; @@ -128,15 +123,16 @@ void Utils::Gui::searchForTextInTreeWidget(QTreeWidget *treeWidget, } } else { // show all items otherwise - Q_FOREACH (QTreeWidgetItem *item, allItems) { item->setHidden(false); } + Q_FOREACH (QTreeWidgetItem *item, allItems) { + item->setHidden(false); + } } } /** * Searches for text in items of a list widget */ -void Utils::Gui::searchForTextInListWidget(QListWidget *listWidget, - const QString &text, +void Utils::Gui::searchForTextInListWidget(QListWidget *listWidget, const QString &text, bool searchAddProps) { QList<QListWidgetItem *> allItems = listWidget->findItems("", Qt::MatchContains | Qt::MatchRecursive); @@ -149,25 +145,25 @@ void Utils::Gui::searchForTextInListWidget(QListWidget *listWidget, if (searchAddProps) { show |= item->toolTip().contains(text, Qt::CaseInsensitive) || - item->whatsThis().contains(text, Qt::CaseInsensitive); + item->whatsThis().contains(text, Qt::CaseInsensitive); } item->setHidden(!show); } } else { // show all items otherwise - Q_FOREACH (QListWidgetItem *item, allItems) { item->setHidden(false); } + Q_FOREACH (QListWidgetItem *item, allItems) { + item->setHidden(false); + } } } /** * Checks if a variant exists as user data in a tree widget */ -bool Utils::Gui::userDataInTreeWidgetExists(QTreeWidget *treeWidget, - const QVariant &userData, +bool Utils::Gui::userDataInTreeWidgetExists(QTreeWidget *treeWidget, const QVariant &userData, int column) { - return getTreeWidgetItemWithUserData(treeWidget, userData, column) != - nullptr; + return getTreeWidgetItemWithUserData(treeWidget, userData, column) != nullptr; } /** @@ -179,8 +175,8 @@ bool Utils::Gui::userDataInTreeWidgetExists(QTreeWidget *treeWidget, * @param column * @return */ -QTreeWidgetItem *Utils::Gui::getTreeWidgetItemWithUserData( - QTreeWidget *treeWidget, const QVariant &userData, int column) { +QTreeWidgetItem *Utils::Gui::getTreeWidgetItemWithUserData(QTreeWidget *treeWidget, + const QVariant &userData, int column) { // get all items QList<QTreeWidgetItem *> allItems = treeWidget->findItems("", Qt::MatchContains | Qt::MatchRecursive); @@ -194,11 +190,10 @@ QTreeWidgetItem *Utils::Gui::getTreeWidgetItemWithUserData( return nullptr; } -QListWidgetItem *Utils::Gui::getListWidgetItemWithUserData( - QListWidget *listWidget, const QVariant &userData) { +QListWidgetItem *Utils::Gui::getListWidgetItemWithUserData(QListWidget *listWidget, + const QVariant &userData) { // get all items - QList<QListWidgetItem *> allItems = - listWidget->findItems("", Qt::MatchContains); + QList<QListWidgetItem *> allItems = listWidget->findItems("", Qt::MatchContains); Q_FOREACH (QListWidgetItem *item, allItems) { if (userData == item->data(Qt::UserRole)) { @@ -215,8 +210,7 @@ QListWidgetItem *Utils::Gui::getListWidgetItemWithUserData( * @param treeWidget * @param column */ -void Utils::Gui::resetBoldStateOfAllTreeWidgetItems(QTreeWidget *treeWidget, - int column) { +void Utils::Gui::resetBoldStateOfAllTreeWidgetItems(QTreeWidget *treeWidget, int column) { // get all items QList<QTreeWidgetItem *> allItems = treeWidget->findItems("", Qt::MatchContains | Qt::MatchRecursive); @@ -242,12 +236,12 @@ void Utils::Gui::resetBoldStateOfAllTreeWidgetItems(QTreeWidget *treeWidget, * @param defaultButton * @return */ -QMessageBox::StandardButton Utils::Gui::information( - QWidget *parent, const QString &title, const QString &text, - const QString &identifier, QMessageBox::StandardButtons buttons, - QMessageBox::StandardButton defaultButton) { - return showMessageBox(parent, QMessageBox::Icon::Information, title, text, - identifier, buttons, defaultButton); +QMessageBox::StandardButton Utils::Gui::information(QWidget *parent, const QString &title, + const QString &text, const QString &identifier, + QMessageBox::StandardButtons buttons, + QMessageBox::StandardButton defaultButton) { + return showMessageBox(parent, QMessageBox::Icon::Information, title, text, identifier, buttons, + defaultButton); } /** @@ -263,14 +257,13 @@ QMessageBox::StandardButton Utils::Gui::information( * @param skipOverrideButtons * @return */ -QMessageBox::StandardButton Utils::Gui::question( - QWidget *parent, const QString &title, const QString &text, - const QString &identifier, QMessageBox::StandardButtons buttons, - QMessageBox::StandardButton defaultButton, - QMessageBox::StandardButtons skipOverrideButtons) { - return showMessageBox(parent, QMessageBox::Icon::Question, title, text, - identifier, buttons, defaultButton, - skipOverrideButtons); +QMessageBox::StandardButton Utils::Gui::question(QWidget *parent, const QString &title, + const QString &text, const QString &identifier, + QMessageBox::StandardButtons buttons, + QMessageBox::StandardButton defaultButton, + QMessageBox::StandardButtons skipOverrideButtons) { + return showMessageBox(parent, QMessageBox::Icon::Question, title, text, identifier, buttons, + defaultButton, skipOverrideButtons); } /** @@ -286,12 +279,10 @@ QMessageBox::StandardButton Utils::Gui::question( * @return */ QMessageBox::StandardButton Utils::Gui::questionNoSkipOverride( - QWidget *parent, const QString &title, const QString &text, - const QString &identifier, QMessageBox::StandardButtons buttons, - QMessageBox::StandardButton defaultButton) { - return showMessageBox(parent, QMessageBox::Icon::Question, title, text, - identifier, buttons, defaultButton, - QMessageBox::NoButton); + QWidget *parent, const QString &title, const QString &text, const QString &identifier, + QMessageBox::StandardButtons buttons, QMessageBox::StandardButton defaultButton) { + return showMessageBox(parent, QMessageBox::Icon::Question, title, text, identifier, buttons, + defaultButton, QMessageBox::NoButton); } /** @@ -306,12 +297,12 @@ QMessageBox::StandardButton Utils::Gui::questionNoSkipOverride( * @param defaultButton * @return */ -QMessageBox::StandardButton Utils::Gui::warning( - QWidget *parent, const QString &title, const QString &text, - const QString &identifier, QMessageBox::StandardButtons buttons, - QMessageBox::StandardButton defaultButton) { - return showMessageBox(parent, QMessageBox::Icon::Warning, title, text, - identifier, buttons, defaultButton); +QMessageBox::StandardButton Utils::Gui::warning(QWidget *parent, const QString &title, + const QString &text, const QString &identifier, + QMessageBox::StandardButtons buttons, + QMessageBox::StandardButton defaultButton) { + return showMessageBox(parent, QMessageBox::Icon::Warning, title, text, identifier, buttons, + defaultButton); } /** @@ -327,11 +318,9 @@ QMessageBox::StandardButton Utils::Gui::warning( * @return */ QMessageBox::StandardButton Utils::Gui::showMessageBox( - QWidget *parent, QMessageBox::Icon icon, const QString &title, - const QString &text, const QString &identifier, - QMessageBox::StandardButtons buttons, - QMessageBox::StandardButton defaultButton, - QMessageBox::StandardButtons skipOverrideButtons) { + QWidget *parent, QMessageBox::Icon icon, const QString &title, const QString &text, + const QString &identifier, QMessageBox::StandardButtons buttons, + QMessageBox::StandardButton defaultButton, QMessageBox::StandardButtons skipOverrideButtons) { QSettings settings; const QString settingsKey = "MessageBoxOverride/" + identifier; auto overrideButton = static_cast<QMessageBox::StandardButton>( @@ -346,10 +335,10 @@ QMessageBox::StandardButton Utils::Gui::showMessageBox( QMessageBox msgBox(icon, title, text, QMessageBox::NoButton, parent); auto *buttonBox = msgBox.findChild<QDialogButtonBox *>(); Q_ASSERT(buttonBox != nullptr); - auto *checkBox = new QCheckBox(icon == QMessageBox::Icon::Question - ? QObject::tr("Don't ask again!") - : QObject::tr("Don't show again!"), - parent); + auto *checkBox = + new QCheckBox(icon == QMessageBox::Icon::Question ? QObject::tr("Don't ask again!") + : QObject::tr("Don't show again!"), + parent); uint mask = QMessageBox::FirstButton; while (mask <= QMessageBox::LastButton) { @@ -362,8 +351,7 @@ QMessageBox::StandardButton Utils::Gui::showMessageBox( if (msgBox.defaultButton()) continue; if ((defaultButton == QMessageBox::NoButton && buttonBox->buttonRole(button) == QDialogButtonBox::AcceptRole) || - (defaultButton != QMessageBox::NoButton && - sb == uint(defaultButton))) + (defaultButton != QMessageBox::NoButton && sb == uint(defaultButton))) msgBox.setDefaultButton(button); } @@ -408,9 +396,8 @@ bool Utils::Gui::isMessageBoxPresent() { * @param options * @return */ -QFont Utils::Gui::fontDialogGetFont(bool *ok, const QFont &initial, - QWidget *parent, const QString &title, - QFontDialog::FontDialogOptions options) { +QFont Utils::Gui::fontDialogGetFont(bool *ok, const QFont &initial, QWidget *parent, + const QString &title, QFontDialog::FontDialogOptions options) { #ifdef Q_OS_MAC // there was a bug in Qt 5.11.2 with the native dialog // see: https://github.com/pbek/QOwnNotes/issues/1033 @@ -439,16 +426,11 @@ void Utils::Gui::copyCodeBlockText(const QTextBlock &initialBlock) { break; } - if (block.userState() != - MarkdownHighlighter::HighlighterState::CodeBlock && - block.userState() != - MarkdownHighlighter::HighlighterState::CodeBlockComment && - block.userState() != - MarkdownHighlighter::HighlighterState::CodeBlockTilde && - block.userState() != - MarkdownHighlighter::HighlighterState::CodeBlockTildeComment && - block.userState() < - MarkdownHighlighter::HighlighterState::CodeCpp) { + if (block.userState() != MarkdownHighlighter::HighlighterState::CodeBlock && + block.userState() != MarkdownHighlighter::HighlighterState::CodeBlockComment && + block.userState() != MarkdownHighlighter::HighlighterState::CodeBlockTilde && + block.userState() != MarkdownHighlighter::HighlighterState::CodeBlockTildeComment && + block.userState() < MarkdownHighlighter::HighlighterState::CodeCpp) { break; } codeBlockTextList.prepend(block.text()); @@ -465,20 +447,13 @@ void Utils::Gui::copyCodeBlockText(const QTextBlock &initialBlock) { break; } - if (block.userState() != - MarkdownHighlighter::HighlighterState::CodeBlock && - block.userState() != - MarkdownHighlighter::HighlighterState::CodeBlockComment && - block.userState() != - MarkdownHighlighter::HighlighterState::CodeBlockEnd && - block.userState() != - MarkdownHighlighter::HighlighterState::CodeBlockTilde && - block.userState() != MarkdownHighlighter::HighlighterState:: - CodeBlockTildeComment && - block.userState() != - MarkdownHighlighter::HighlighterState::CodeBlockTildeEnd && - block.userState() < - MarkdownHighlighter::HighlighterState::CodeCpp) { + if (block.userState() != MarkdownHighlighter::HighlighterState::CodeBlock && + block.userState() != MarkdownHighlighter::HighlighterState::CodeBlockComment && + block.userState() != MarkdownHighlighter::HighlighterState::CodeBlockEnd && + block.userState() != MarkdownHighlighter::HighlighterState::CodeBlockTilde && + block.userState() != MarkdownHighlighter::HighlighterState::CodeBlockTildeComment && + block.userState() != MarkdownHighlighter::HighlighterState::CodeBlockTildeEnd && + block.userState() < MarkdownHighlighter::HighlighterState::CodeCpp) { break; } @@ -509,10 +484,8 @@ bool Utils::Gui::toggleCheckBoxAtCursor(QPlainTextEdit *textEdit) { const int pos = cursor.position(); // select the full range of "- [ ]" text in front and after cursor - cursor.movePosition(QTextCursor::Left, - QTextCursor::MoveAnchor, 5); - cursor.movePosition(QTextCursor::Right, - QTextCursor::KeepAnchor, 10); + cursor.movePosition(QTextCursor::Left, QTextCursor::MoveAnchor, 5); + cursor.movePosition(QTextCursor::Right, QTextCursor::KeepAnchor, 10); bool result = false; auto text = cursor.selectedText(); @@ -584,8 +557,7 @@ bool Utils::Gui::autoFormatTableAtCursor(QPlainTextEdit *textEdit) { break; } - const QStringList &stringList = - prevBlockText.split(QStringLiteral("|")); + const QStringList &stringList = prevBlockText.split(QStringLiteral("|")); tableTextList.prepend(stringList); startPosition = block.position(); maxColumns = std::max(maxColumns, (int)stringList.count()); @@ -605,8 +577,7 @@ bool Utils::Gui::autoFormatTableAtCursor(QPlainTextEdit *textEdit) { break; } - const QStringList &stringList = - nextBlockText.split(QStringLiteral("|")); + const QStringList &stringList = nextBlockText.split(QStringLiteral("|")); tableTextList.append(stringList); endPosition = block.position() + nextBlockText.count(); maxColumns = std::max(maxColumns, (int)stringList.count()); @@ -620,139 +591,134 @@ bool Utils::Gui::autoFormatTableAtCursor(QPlainTextEdit *textEdit) { return false; } - QVector<int> colLength; - colLength << 1; + QVector<int> colLength; + colLength << 1; - // for every column, store maximum column length - for (int col = 1; col < maxColumns; col++) { - int maxTextLength = 0; - for (int line = 0; line < lineCount; line++) { - const QStringList &lineTextList = tableTextList.at(line); + // for every column, store maximum column length + for (int col = 1; col < maxColumns; col++) { + int maxTextLength = 0; + for (int line = 0; line < lineCount; line++) { + const QStringList &lineTextList = tableTextList.at(line); - if (col >= lineTextList.count()) { - break; - } + if (col >= lineTextList.count()) { + break; + } - const QString &text = lineTextList.at(col).trimmed(); + const QString &text = lineTextList.at(col).trimmed(); - // don't count the headline separator line, so it can shrink - // down to 3 characters if needed - if (line == 1 && headlineSeparatorRegExp.match(text).hasMatch()) { - continue; - } + // don't count the headline separator line, so it can shrink + // down to 3 characters if needed + if (line == 1 && headlineSeparatorRegExp.match(text).hasMatch()) { + continue; + } - maxTextLength = std::max((int)text.count(), maxTextLength); - } + maxTextLength = std::max((int)text.count(), maxTextLength); + } - // a minimum of 3 headline separator characters are needed for - // valid Markdown tables - maxTextLength = std::max(3, maxTextLength); + // a minimum of 3 headline separator characters are needed for + // valid Markdown tables + maxTextLength = std::max(3, maxTextLength); - colLength << maxTextLength; - } + colLength << maxTextLength; + } - QVector<Qt::AlignmentFlag> colAlignment; - colAlignment << Qt::AlignLeft; + QVector<Qt::AlignmentFlag> colAlignment; + colAlignment << Qt::AlignLeft; - const QStringList &headerStringList = tableTextList.at(1); + const QStringList &headerStringList = tableTextList.at(1); - // for every column, store column alignment - for (int col = 1; col < maxColumns - 1; col++) { - const QString &text = headerStringList.at(col); - QString trimmedText = text.trimmed(); + // for every column, store column alignment + for (int col = 1; col < maxColumns - 1; col++) { + const QString &text = headerStringList.at(col); + QString trimmedText = text.trimmed(); - if (!headlineSeparatorRegExp.match(trimmedText).hasMatch()) { - return false; - } + if (!headlineSeparatorRegExp.match(trimmedText).hasMatch()) { + return false; + } - const bool startsWithCol = trimmedText.startsWith(QStringLiteral(":")); - const bool endsWithCol = trimmedText.endsWith(QStringLiteral(":")); + const bool startsWithCol = trimmedText.startsWith(QStringLiteral(":")); + const bool endsWithCol = trimmedText.endsWith(QStringLiteral(":")); - if (startsWithCol && endsWithCol) { - colAlignment << Qt::AlignCenter; - } else if (endsWithCol) { - colAlignment << Qt::AlignRight; - } else if (startsWithCol) { - colAlignment << Qt::AlignLeft; - } else { - // implicit left alignment - colAlignment << static_cast<Qt::AlignmentFlag>(0); - } - } + if (startsWithCol && endsWithCol) { + colAlignment << Qt::AlignCenter; + } else if (endsWithCol) { + colAlignment << Qt::AlignRight; + } else if (startsWithCol) { + colAlignment << Qt::AlignLeft; + } else { + // implicit left alignment + colAlignment << static_cast<Qt::AlignmentFlag>(0); + } + } // justify text in tableTextList // we can skip the first column in the list since it is bound to have no // text - for (int col = 1; col < maxColumns; col++) { + for (int col = 1; col < maxColumns; col++) { + const Qt::AlignmentFlag alignment = + colAlignment.value(col, static_cast<Qt::AlignmentFlag>(0)); + const int maxTextLength = colLength.at(col); - const Qt::AlignmentFlag alignment = colAlignment.value(col, static_cast<Qt::AlignmentFlag>(0)); - const int maxTextLength = colLength.at(col); + // do the text justification + for (int line = 0; line < lineCount; line++) { + QStringList lineTextList = tableTextList.at(line); + const int lineTextListCount = lineTextList.count(); - // do the text justification - for (int line = 0; line < lineCount; line++) { - QStringList lineTextList = tableTextList.at(line); + if (col >= lineTextListCount) { + break; + } - const int lineTextListCount = lineTextList.count(); + const QString &text = lineTextList.at(col); - if (col >= lineTextListCount) { - break; - } + // stop if the text in the last column is empty + if (col == (lineTextListCount - 1) && text.isEmpty()) { + break; + } - const QString &text = lineTextList.at(col); + QString trimmedText = text.trimmed(); - // stop if the text in the last column is empty - if (col == (lineTextListCount - 1) && text.isEmpty()) { - break; - } + if (line == 1) { + // heading + QString prefix(" "); + QString suffix(" "); - QString trimmedText = text.trimmed(); + if (alignment == Qt::AlignCenter) { + prefix = " :"; + suffix = ": "; + } else if (alignment == Qt::AlignLeft) { + prefix = " :"; + } else if (alignment == Qt::AlignRight) { + suffix = ": "; + } - if (line == 1) { - // heading - QString prefix(" "); - QString suffix(" "); + const int numSpecialChars(prefix.size() + suffix.size() - 2); + justifiedText = + prefix + QStringLiteral("-").repeated(maxTextLength - numSpecialChars) + suffix; + } else { + if (alignment == Qt::AlignCenter) { + const int leftFillSize = (maxTextLength - trimmedText.size()) / 2; + const int rightFillSize = (maxTextLength - trimmedText.size()) - leftFillSize; + justifiedText = QString().fill(' ', leftFillSize) + trimmedText + + QString().fill(' ', rightFillSize); + } else if (alignment == Qt::AlignRight) { + justifiedText = trimmedText.rightJustified(maxTextLength); + } else { + justifiedText = trimmedText.leftJustified(maxTextLength); + } - if (alignment == Qt::AlignCenter) { - prefix = " :"; - suffix = ": "; - } else if (alignment == Qt::AlignLeft) { - prefix = " :"; - } else if (alignment == Qt::AlignRight) { - suffix = ": "; - } + // add padding + justifiedText = QStringLiteral(" ") + justifiedText + QStringLiteral(" "); + } - const int numSpecialChars(prefix.size() + suffix.size() - 2); - justifiedText = prefix + - QStringLiteral("-").repeated(maxTextLength - numSpecialChars) + - suffix; - } else { - if (alignment == Qt::AlignCenter) { - const int leftFillSize = (maxTextLength - trimmedText.size()) / 2; - const int rightFillSize = (maxTextLength - trimmedText.size()) - leftFillSize; - justifiedText = QString().fill(' ', leftFillSize) + - trimmedText + - QString().fill(' ', rightFillSize); - } else if (alignment == Qt::AlignRight) { - justifiedText = trimmedText.rightJustified(maxTextLength); - } else { - justifiedText = trimmedText.leftJustified(maxTextLength); - } - - // add padding - justifiedText = QStringLiteral(" ") + - justifiedText + - QStringLiteral(" "); - } - - // update the tableTextList - if (text != justifiedText) { - lineTextList.replace(col, justifiedText); - tableTextList.replace(line, lineTextList); - tableWasModified = true; - } - } - } + // update the tableTextList + if (text != justifiedText) { + lineTextList.replace(col, justifiedText); + tableTextList.replace(line, lineTextList); + tableWasModified = true; + } + } + } // return if table doesn't need to be modified if (!tableWasModified) { @@ -787,8 +753,7 @@ bool Utils::Gui::autoFormatTableAtCursor(QPlainTextEdit *textEdit) { void Utils::Gui::updateInterfaceFontSize(int fontSize) { QSettings settings; bool overrideInterfaceFontSize = - settings.value(QStringLiteral("overrideInterfaceFontSize"), false) - .toBool(); + settings.value(QStringLiteral("overrideInterfaceFontSize"), false).toBool(); // remove old style static const QRegularExpression re( @@ -799,17 +764,12 @@ void Utils::Gui::updateInterfaceFontSize(int fontSize) { if (overrideInterfaceFontSize) { int interfaceFontSize = - fontSize != -1 - ? fontSize - : settings.value(QStringLiteral("interfaceFontSize"), 11) - .toInt(); + fontSize != -1 ? fontSize + : settings.value(QStringLiteral("interfaceFontSize"), 11).toInt(); - stylesheet += QStringLiteral("\n") + - QString(INTERFACE_OVERRIDE_STYLESHEET_PRE_STRING) + - QStringLiteral("QWidget {font-size: ") + - QString::number(interfaceFontSize) + - QStringLiteral("px;}") + - QString(INTERFACE_OVERRIDE_STYLESHEET_POST_STRING); + stylesheet += QStringLiteral("\n") + QString(INTERFACE_OVERRIDE_STYLESHEET_PRE_STRING) + + QStringLiteral("QWidget {font-size: ") + QString::number(interfaceFontSize) + + QStringLiteral("px;}") + QString(INTERFACE_OVERRIDE_STYLESHEET_POST_STRING); } qApp->setStyleSheet(stylesheet); @@ -818,18 +778,15 @@ void Utils::Gui::updateInterfaceFontSize(int fontSize) { /** * Sets the current index of a combo box by user data */ -void Utils::Gui::setComboBoxIndexByUserData(QComboBox *comboBox, - const QVariant &userData) { +void Utils::Gui::setComboBoxIndexByUserData(QComboBox *comboBox, const QVariant &userData) { const int index = comboBox->findData(userData); comboBox->setCurrentIndex(index); } -int Utils::Gui::getTabWidgetIndexByProperty(QTabWidget *tabWidget, - const QString &propertyName, +int Utils::Gui::getTabWidgetIndexByProperty(QTabWidget *tabWidget, const QString &propertyName, const QVariant &propertyValue) { for (int i = 0; i < tabWidget->count(); i++) { - const auto value = tabWidget->widget(i)->property( - propertyName.toLocal8Bit()); + const auto value = tabWidget->widget(i)->property(propertyName.toLocal8Bit()); if (value == propertyValue) { return i; } @@ -848,8 +805,7 @@ int Utils::Gui::getTabWidgetNoteId(QTabWidget *tabWidget, int index) { return widget->property("note-id").toInt(); } -Note Utils::Gui::getTabWidgetNote(QTabWidget *tabWidget, int index, - bool fetchByName) { +Note Utils::Gui::getTabWidgetNote(QTabWidget *tabWidget, int index, bool fetchByName) { if (fetchByName) { QWidget *widget = tabWidget->widget(index); @@ -858,8 +814,8 @@ Note Utils::Gui::getTabWidgetNote(QTabWidget *tabWidget, int index, } const QString ¬eName = widget->property("note-name").toString(); - const QString ¬eSubFolderPathData = widget->property( - "note-subfolder-path-data").toString(); + const QString ¬eSubFolderPathData = + widget->property("note-subfolder-path-data").toString(); return Note::fetchByName(noteName, noteSubFolderPathData); } else { const int noteId = getTabWidgetNoteId(tabWidget, index); @@ -894,12 +850,10 @@ void Utils::Gui::storeNoteTabs(QTabWidget *tabWidget) { } NoteFolder noteFolder = NoteFolder::currentNoteFolder(); - noteFolder.setSettingsValue(QStringLiteral("NoteTabNameList"), - noteNameList); + noteFolder.setSettingsValue(QStringLiteral("NoteTabNameList"), noteNameList); noteFolder.setSettingsValue(QStringLiteral("NoteTabSubFolderPathDataList"), noteSubFolderPathDataList); - noteFolder.setSettingsValue(QStringLiteral("NoteTabStickinessList"), - noteStickinessList); + noteFolder.setSettingsValue(QStringLiteral("NoteTabStickinessList"), noteStickinessList); } void Utils::Gui::restoreNoteTabs(QTabWidget *tabWidget, QVBoxLayout *layout) { @@ -916,26 +870,22 @@ void Utils::Gui::restoreNoteTabs(QTabWidget *tabWidget, QVBoxLayout *layout) { // check if we want to restore note tabs if (settings.value(QStringLiteral("restoreNoteTabs"), true).toBool()) { NoteFolder noteFolder = NoteFolder::currentNoteFolder(); - const QStringList noteNameList = noteFolder.settingsValue( - QStringLiteral("NoteTabNameList")).toStringList(); - const QStringList noteSubFolderPathDataList = noteFolder.settingsValue( - QStringLiteral("NoteTabSubFolderPathDataList")).toStringList(); - const QStringList noteStickinessList = noteFolder.settingsValue( - QStringLiteral("NoteTabStickinessList")).toStringList(); + const QStringList noteNameList = + noteFolder.settingsValue(QStringLiteral("NoteTabNameList")).toStringList(); + const QStringList noteSubFolderPathDataList = + noteFolder.settingsValue(QStringLiteral("NoteTabSubFolderPathDataList")).toStringList(); + const QStringList noteStickinessList = + noteFolder.settingsValue(QStringLiteral("NoteTabStickinessList")).toStringList(); const int noteNameListCount = noteNameList.count(); // only restore if there was more than one tab and // NoteTabSubFolderPathDataList has enough entries - if (noteNameListCount > 1 && - noteSubFolderPathDataList.count() >= noteNameListCount) { + if (noteNameListCount > 1 && noteSubFolderPathDataList.count() >= noteNameListCount) { for (int i = 0; i < noteNameListCount; i++) { const QString ¬eName = noteNameList.at(i); - const QString ¬eSubFolderPathData = - noteSubFolderPathDataList.at(i); - const bool isSticky = noteStickinessList.contains( - QString::number(i)); - const Note note = Note::fetchByName(noteName, - noteSubFolderPathData); + const QString ¬eSubFolderPathData = noteSubFolderPathDataList.at(i); + const bool isSticky = noteStickinessList.contains(QString::number(i)); + const Note note = Note::fetchByName(noteName, noteSubFolderPathData); // skip if note was not found anymore if (!note.isFetched()) { @@ -961,9 +911,9 @@ void Utils::Gui::restoreNoteTabs(QTabWidget *tabWidget, QVBoxLayout *layout) { } void Utils::Gui::reloadNoteTabs(QTabWidget *tabWidget) { -// const QSignalBlocker blocker(tabWidget); -// Q_UNUSED(blocker) -// return; + // const QSignalBlocker blocker(tabWidget); + // Q_UNUSED(blocker) + // return; for (int i = 0; i < tabWidget->count(); i++) { const Note note = getTabWidgetNote(tabWidget, i, true); @@ -976,8 +926,7 @@ void Utils::Gui::reloadNoteTabs(QTabWidget *tabWidget) { } } -void Utils::Gui::updateTabWidgetTabData(QTabWidget *tabWidget, int index, - const Note ¬e) { +void Utils::Gui::updateTabWidgetTabData(QTabWidget *tabWidget, int index, const Note ¬e) { QWidget *widget = tabWidget->widget(index); if (widget == nullptr) { @@ -986,8 +935,7 @@ void Utils::Gui::updateTabWidgetTabData(QTabWidget *tabWidget, int index, widget->setProperty("note-id", note.getId()); widget->setProperty("note-name", note.getName()); - widget->setProperty("note-subfolder-path-data", - note.getNoteSubFolder().pathData()); + widget->setProperty("note-subfolder-path-data", note.getNoteSubFolder().pathData()); QString text = note.getName(); const bool isSticky = isTabWidgetTabSticky(tabWidget, index); @@ -1001,13 +949,11 @@ void Utils::Gui::updateTabWidgetTabData(QTabWidget *tabWidget, int index, // see https://github.com/pbek/QOwnNotes/issues/2135 tabWidget->setTabText(index, text.replace("&", "&&")); - tabWidget->setTabToolTip(index, isSticky ? - QObject::tr("Double-click to unstick note from tab") : - QObject::tr("Double-click to stick note to tab")); + tabWidget->setTabToolTip(index, isSticky ? QObject::tr("Double-click to unstick note from tab") + : QObject::tr("Double-click to stick note to tab")); } -void Utils::Gui::setTabWidgetTabSticky(QTabWidget *tabWidget, int index, - bool sticky) { +void Utils::Gui::setTabWidgetTabSticky(QTabWidget *tabWidget, int index, bool sticky) { QWidget *widget = tabWidget->widget(index); if (widget == nullptr) { @@ -1032,26 +978,22 @@ bool Utils::Gui::isTabWidgetTabSticky(QTabWidget *tabWidget, int index) { /** * Sets the tree widget tooltip for a note */ -void Utils::Gui::setTreeWidgetItemToolTipForNote( - QTreeWidgetItem *item, const Note ¬e, - QDateTime *overrideFileLastModified) { +void Utils::Gui::setTreeWidgetItemToolTipForNote(QTreeWidgetItem *item, const Note ¬e, + QDateTime *overrideFileLastModified) { if (item == nullptr) { return; } QDateTime modified = note.getFileLastModified(); - QDateTime *fileLastModified = (overrideFileLastModified != nullptr) - ? overrideFileLastModified - : &modified; + QDateTime *fileLastModified = + (overrideFileLastModified != nullptr) ? overrideFileLastModified : &modified; - QString toolTipText = - QObject::tr("<strong>%1</strong><br />last modified: %2") - .arg(note.getFileName(), fileLastModified->toString()); + QString toolTipText = QObject::tr("<strong>%1</strong><br />last modified: %2") + .arg(note.getFileName(), fileLastModified->toString()); NoteSubFolder noteSubFolder = note.getNoteSubFolder(); if (noteSubFolder.isFetched()) { - toolTipText += QObject::tr("<br />path: %1").arg( - noteSubFolder.relativePath()); + toolTipText += QObject::tr("<br />path: %1").arg(noteSubFolder.relativePath()); } item->setToolTip(0, toolTipText); @@ -1064,8 +1006,9 @@ void Utils::Gui::setTreeWidgetItemToolTipForNote( * This only works under Windows 10 (or newer). */ bool Utils::Gui::doWindowsDarkModeCheck() { - QSettings settings(R"(HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Themes\Personalize)", - QSettings::NativeFormat); + QSettings settings( + R"(HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Themes\Personalize)", + QSettings::NativeFormat); // If setting wasn't found we are not on Windows 10 (or newer) if (!settings.contains("AppsUseLightTheme")) { @@ -1080,8 +1023,8 @@ bool Utils::Gui::doWindowsDarkModeCheck() { if (Utils::Gui::questionNoSkipOverride( nullptr, QObject::tr("Dark mode detected"), QObject::tr("Your Windows system seems to use the dark mode. " - "Do you also want to turn on dark mode in QOwnNotes?"), - QStringLiteral("windows-dark-mode")) == QMessageBox::Yes) { + "Do you also want to turn on dark mode in QOwnNotes?"), + QStringLiteral("windows-dark-mode")) == QMessageBox::Yes) { Utils::Misc::switchToDarkMode(); return true; @@ -1093,7 +1036,7 @@ bool Utils::Gui::doWindowsDarkModeCheck() { if (Utils::Gui::questionNoSkipOverride( nullptr, QObject::tr("Light mode detected"), QObject::tr("Your Windows system seems to use the light mode. " - "Do you also want to turn off dark mode in QOwnNotes?"), + "Do you also want to turn off dark mode in QOwnNotes?"), QStringLiteral("windows-light-mode")) == QMessageBox::Yes) { Utils::Misc::switchToLightMode(); @@ -1109,28 +1052,42 @@ bool Utils::Gui::doWindowsDarkModeCheck() { * This only works with dbus. */ bool Utils::Gui::doLinuxDarkModeCheck() { + // auto result = Utils::Misc::startSynchronousProcess("/usr/bin/dbus-send", QStringList() << + // QStringLiteral("--session") << QStringLiteral("--print-reply=literal") << + // QStringLiteral("--reply-timeout=1000") << + // QStringLiteral("--dest=org.freedesktop.portal.Desktop") << + // QStringLiteral("/org/freedesktop/portal/desktop") << + // QStringLiteral("org.freedesktop.portal.Settings.Read") << + // QStringLiteral("string:'org.freedesktop.appearance'") << + // QStringLiteral("string:'color-scheme'")); -// auto result = Utils::Misc::startSynchronousProcess("/usr/bin/dbus-send", QStringList() << -// QStringLiteral("--session") << QStringLiteral("--print-reply=literal") << QStringLiteral("--reply-timeout=1000") << -// QStringLiteral("--dest=org.freedesktop.portal.Desktop") << QStringLiteral("/org/freedesktop/portal/desktop") << -// QStringLiteral("org.freedesktop.portal.Settings.Read") << QStringLiteral("string:'org.freedesktop.appearance'") << -// QStringLiteral("string:'color-scheme'")); + // auto parameters = QStringList() << + // QStringLiteral("--session") << QStringLiteral("--print-reply=literal") << + // QStringLiteral("--reply-timeout=1000") << + // QStringLiteral("--dest=org.freedesktop.portal.Desktop") << + // QStringLiteral("/org/freedesktop/portal/desktop") << + // QStringLiteral("org.freedesktop.portal.Settings.Read") << + // QStringLiteral("string:'org.freedesktop.appearance'") << + // QStringLiteral("string:'color-scheme'"); -// auto parameters = QStringList() << -// QStringLiteral("--session") << QStringLiteral("--print-reply=literal") << QStringLiteral("--reply-timeout=1000") << -// QStringLiteral("--dest=org.freedesktop.portal.Desktop") << QStringLiteral("/org/freedesktop/portal/desktop") << -// QStringLiteral("org.freedesktop.portal.Settings.Read") << QStringLiteral("string:'org.freedesktop.appearance'") << -// QStringLiteral("string:'color-scheme'"); + // auto parameters = QStringList() << + // QStringLiteral("--session") << QStringLiteral("--print-reply=literal") << + // QStringLiteral("--reply-timeout=1000") << + // QStringLiteral("--dest=org.freedesktop.portal.Desktop") << + // QStringLiteral("/org/freedesktop/portal/desktop") << + // QStringLiteral("org.freedesktop.portal.Settings.Read") << + // QStringLiteral("string:'org.freedesktop.appearance' + // string:'color-scheme'"); -// auto parameters = QStringList() << -// QStringLiteral("--session") << QStringLiteral("--print-reply=literal") << QStringLiteral("--reply-timeout=1000") << -// QStringLiteral("--dest=org.freedesktop.portal.Desktop") << QStringLiteral("/org/freedesktop/portal/desktop") << -// QStringLiteral("org.freedesktop.portal.Settings.Read") << QStringLiteral("string:'org.freedesktop.appearance' string:'color-scheme'"); - - auto parameters = QStringList() << "-c" << "dbus-send --session --print-reply=literal --reply-timeout=1000 --dest=org.freedesktop.portal.Desktop /org/freedesktop/portal/desktop org.freedesktop.portal.Settings.Read string:'org.freedesktop.appearance' string:'color-scheme'"; + auto parameters = QStringList() + << "-c" + << "dbus-send --session --print-reply=literal --reply-timeout=1000 " + "--dest=org.freedesktop.portal.Desktop /org/freedesktop/portal/desktop " + "org.freedesktop.portal.Settings.Read string:'org.freedesktop.appearance' " + "string:'color-scheme'"; QProcess process; -// process.start(QStringLiteral("dbus-send"), parameters); + // process.start(QStringLiteral("dbus-send"), parameters); process.start(QStringLiteral("/bin/sh"), parameters); if (!process.waitForStarted()) { @@ -1143,7 +1100,7 @@ bool Utils::Gui::doLinuxDarkModeCheck() { return false; } -// const auto result = QString(process.readAllStandardError()); + // const auto result = QString(process.readAllStandardError()); const int systemColorSchema = QString(process.readAll()).trimmed().right(1).toInt(); const bool appDarkMode = QSettings().value("darkMode").toBool(); @@ -1152,8 +1109,8 @@ bool Utils::Gui::doLinuxDarkModeCheck() { if (Utils::Gui::questionNoSkipOverride( nullptr, QObject::tr("Dark mode detected"), QObject::tr("Your Linux system seems to use the dark mode. " - "Do you also want to turn on dark mode in QOwnNotes?"), - QStringLiteral("linux-dark-mode")) == QMessageBox::Yes) { + "Do you also want to turn on dark mode in QOwnNotes?"), + QStringLiteral("linux-dark-mode")) == QMessageBox::Yes) { Utils::Misc::switchToDarkMode(); return true; @@ -1165,7 +1122,7 @@ bool Utils::Gui::doLinuxDarkModeCheck() { if (Utils::Gui::questionNoSkipOverride( nullptr, QObject::tr("Light mode detected"), QObject::tr("Your Linux system seems to use the light mode. " - "Do you also want to turn off dark mode in QOwnNotes?"), + "Do you also want to turn off dark mode in QOwnNotes?"), QStringLiteral("linux-light-mode")) == QMessageBox::Yes) { Utils::Misc::switchToLightMode(); @@ -1176,27 +1133,23 @@ bool Utils::Gui::doLinuxDarkModeCheck() { return false; } -QIcon Utils::Gui::folderIcon() -{ - static const QIcon s_folderIcon = QIcon::fromTheme( - QStringLiteral("folder"), - QIcon(QStringLiteral(":icons/breeze-qownnotes/16x16/folder.svg"))); +QIcon Utils::Gui::folderIcon() { + static const QIcon s_folderIcon = + QIcon::fromTheme(QStringLiteral("folder"), + QIcon(QStringLiteral(":icons/breeze-qownnotes/16x16/folder.svg"))); return s_folderIcon; } -QIcon Utils::Gui::noteIcon() -{ - static const QIcon s_noteIcon = QIcon::fromTheme( - QStringLiteral("text-x-generic"), - QIcon(":icons/breeze-qownnotes/16x16/text-x-generic.svg")); +QIcon Utils::Gui::noteIcon() { + static const QIcon s_noteIcon = + QIcon::fromTheme(QStringLiteral("text-x-generic"), + QIcon(":icons/breeze-qownnotes/16x16/text-x-generic.svg")); return s_noteIcon; } -QIcon Utils::Gui::tagIcon() -{ +QIcon Utils::Gui::tagIcon() { static const QIcon s_tagIcon = QIcon::fromTheme( - QStringLiteral("tag"), - QIcon(QStringLiteral(":/icons/breeze-qownnotes/16x16/tag.svg"))); + QStringLiteral("tag"), QIcon(QStringLiteral(":/icons/breeze-qownnotes/16x16/tag.svg"))); return s_tagIcon; } @@ -1232,26 +1185,22 @@ void Utils::Gui::handleTreeWidgetItemTagColor(QTreeWidgetItem *item, const Tag & } } -void Utils::Gui::handleTreeWidgetItemTagColor(QTreeWidgetItem *item, int tagId) -{ +void Utils::Gui::handleTreeWidgetItemTagColor(QTreeWidgetItem *item, int tagId) { const Tag tag = Tag::fetch(tagId); - if (!tag.isFetched()) - return; + if (!tag.isFetched()) return; Utils::Gui::handleTreeWidgetItemTagColor(item, tag); } -bool Utils::Gui::enableDockWidgetQuestion(QDockWidget *dockWidget) -{ +bool Utils::Gui::enableDockWidgetQuestion(QDockWidget *dockWidget) { if (dockWidget->isVisible()) { return true; } - if (Utils::Gui::question( - dockWidget, QObject::tr("Panel disabled"), - QObject::tr("Panel <strong>%1</strong> is currently disabled, " - "do you want to turn it on again for this action to work?").arg( - dockWidget->windowTitle()), - QStringLiteral("enable-panel-question-") + - dockWidget->objectName()) != QMessageBox::Yes) { + if (Utils::Gui::question(dockWidget, QObject::tr("Panel disabled"), + QObject::tr("Panel <strong>%1</strong> is currently disabled, " + "do you want to turn it on again for this action to work?") + .arg(dockWidget->windowTitle()), + QStringLiteral("enable-panel-question-") + dockWidget->objectName()) != + QMessageBox::Yes) { return false; } diff --git a/src/utils/gui.h b/src/utils/gui.h index 92666304a..7d206dd0d 100644 --- a/src/utils/gui.h +++ b/src/utils/gui.h @@ -33,10 +33,8 @@ class Tag; /* Gui functions that can be useful */ -#define INTERFACE_OVERRIDE_STYLESHEET_PRE_STRING \ - "/* BEGIN INTERFACE OVERRIDE STYLESHEET */" -#define INTERFACE_OVERRIDE_STYLESHEET_POST_STRING \ - "/* END INTERFACE OVERRIDE STYLESHEET */" +#define INTERFACE_OVERRIDE_STYLESHEET_PRE_STRING "/* BEGIN INTERFACE OVERRIDE STYLESHEET */" +#define INTERFACE_OVERRIDE_STYLESHEET_POST_STRING "/* END INTERFACE OVERRIDE STYLESHEET */" namespace Utils { namespace Gui { @@ -65,12 +63,11 @@ bool isOneTreeWidgetItemChildVisible(QTreeWidgetItem *item); void searchForTextInTreeWidget(QTreeWidget *treeWidget, const QString &text, TreeWidgetSearchFlags searchFlags = None); void searchForTextInListWidget(QListWidget *listWidget, const QString &text, - bool searchAddProps = false); + bool searchAddProps = false); QMessageBox::StandardButton showMessageBox( - QWidget *parent, QMessageBox::Icon icon, const QString &title, - const QString &text, const QString &identifier, - QMessageBox::StandardButtons buttons, + QWidget *parent, QMessageBox::Icon icon, const QString &title, const QString &text, + const QString &identifier, QMessageBox::StandardButtons buttons, QMessageBox::StandardButton defaultButton, QMessageBox::StandardButtons skipOverrideButtons = QMessageBox::NoButton); @@ -83,8 +80,8 @@ QMessageBox::StandardButton information( QMessageBox::StandardButton question( QWidget *parent, const QString &title, const QString &text, const QString &identifier = QStringLiteral("default"), - QMessageBox::StandardButtons buttons = - QMessageBox::StandardButtons(QMessageBox::Yes | QMessageBox::No), + QMessageBox::StandardButtons buttons = QMessageBox::StandardButtons(QMessageBox::Yes | + QMessageBox::No), QMessageBox::StandardButton defaultButton = QMessageBox::NoButton, QMessageBox::StandardButtons skipOverrideButtons = QMessageBox::StandardButtons(QMessageBox::No)); @@ -92,36 +89,30 @@ QMessageBox::StandardButton question( QMessageBox::StandardButton questionNoSkipOverride( QWidget *parent, const QString &title, const QString &text, const QString &identifier = QStringLiteral("default"), - QMessageBox::StandardButtons buttons = - QMessageBox::StandardButtons(QMessageBox::Yes | QMessageBox::No), + QMessageBox::StandardButtons buttons = QMessageBox::StandardButtons(QMessageBox::Yes | + QMessageBox::No), QMessageBox::StandardButton defaultButton = QMessageBox::NoButton); QMessageBox::StandardButton warning( QWidget *parent, const QString &title, const QString &text, const QString &identifier = QStringLiteral("default"), - QMessageBox::StandardButtons buttons = - QMessageBox::StandardButtons(QMessageBox::Ok), + QMessageBox::StandardButtons buttons = QMessageBox::StandardButtons(QMessageBox::Ok), QMessageBox::StandardButton defaultButton = QMessageBox::Ok); -bool userDataInTreeWidgetExists(QTreeWidget *treeWidget, - const QVariant &userData, int column = 0); +bool userDataInTreeWidgetExists(QTreeWidget *treeWidget, const QVariant &userData, int column = 0); -QTreeWidgetItem *getTreeWidgetItemWithUserData(QTreeWidget *treeWidget, - const QVariant &userData, +QTreeWidgetItem *getTreeWidgetItemWithUserData(QTreeWidget *treeWidget, const QVariant &userData, int column = 0); -QListWidgetItem *getListWidgetItemWithUserData(QListWidget *listWidget, - const QVariant &userData); +QListWidgetItem *getListWidgetItemWithUserData(QListWidget *listWidget, const QVariant &userData); -void resetBoldStateOfAllTreeWidgetItems(QTreeWidget *treeWidget, - int column = 0); +void resetBoldStateOfAllTreeWidgetItems(QTreeWidget *treeWidget, int column = 0); bool isMessageBoxPresent(); -QFont fontDialogGetFont( - bool *ok, const QFont &initial, QWidget *parent = nullptr, - const QString &title = QString(), - QFontDialog::FontDialogOptions options = QFontDialog::FontDialogOptions()); +QFont fontDialogGetFont(bool *ok, const QFont &initial, QWidget *parent = nullptr, + const QString &title = QString(), + QFontDialog::FontDialogOptions options = QFontDialog::FontDialogOptions()); void copyCodeBlockText(const QTextBlock &initialBlock); @@ -132,12 +123,10 @@ void updateInterfaceFontSize(int fontSize = -1); void setComboBoxIndexByUserData(QComboBox *comboBox, const QVariant &userData); -int getTabWidgetIndexByProperty(QTabWidget *tabWidget, - const QString &propertyName, +int getTabWidgetIndexByProperty(QTabWidget *tabWidget, const QString &propertyName, const QVariant &propertyValue); int getTabWidgetNoteId(QTabWidget *tabWidget, int index); -Note getTabWidgetNote(QTabWidget *tabWidget, int index, - bool fetchByName = false); +Note getTabWidgetNote(QTabWidget *tabWidget, int index, bool fetchByName = false); void storeNoteTabs(QTabWidget *tabWidget); void restoreNoteTabs(QTabWidget *tabWidget, QVBoxLayout *layout); void setTabWidgetTabSticky(QTabWidget *tabWidget, int index, bool sticky); diff --git a/src/utils/misc.cpp b/src/utils/misc.cpp index 3ebd81185..2e79c1cc0 100644 --- a/src/utils/misc.cpp +++ b/src/utils/misc.cpp @@ -27,13 +27,16 @@ #include <QApplication> #include <QCoreApplication> +#include <QDataStream> #include <QDebug> #include <QDesktopServices> #include <QDir> +#include <QHttpMultiPart> #include <QMimeDatabase> #include <QNetworkAccessManager> #include <QNetworkReply> #include <QNetworkRequest> +#include <QPrinter> #include <QProcess> #include <QRegularExpression> #include <QRegularExpressionMatch> @@ -47,9 +50,6 @@ #include <QUuid> #include <QtGui/QIcon> #include <utility> -#include <QHttpMultiPart> -#include <QDataStream> -#include <QPrinter> #if (QT_VERSION < QT_VERSION_CHECK(5, 6, 0)) #include <QHostInfo> #endif @@ -100,8 +100,7 @@ void Utils::Misc::openPath(const QString &absolutePath) { const QString path = QDir::fromNativeSeparators(absolutePath); // Hack to access samba shares with QDesktopServices::openUrl if (path.startsWith(QStringLiteral("//"))) - QDesktopServices::openUrl( - QDir::toNativeSeparators(QStringLiteral("file:") % path)); + QDesktopServices::openUrl(QDir::toNativeSeparators(QStringLiteral("file:") % path)); else QDesktopServices::openUrl(QUrl::fromLocalFile(path)); } @@ -139,8 +138,8 @@ void Utils::Misc::openFolderSelect(const QString &absolutePath) { cmd.toWCharArray(lpCmd); lpCmd[cmd.size()] = 0; - bool ret = ::CreateProcessW(NULL, lpCmd, NULL, NULL, FALSE, 0, NULL, - NULL, &startupInfo, &processInfo); + bool ret = ::CreateProcessW(NULL, lpCmd, NULL, NULL, FALSE, 0, NULL, NULL, &startupInfo, + &processInfo); delete[] lpCmd; if (ret) { @@ -161,31 +160,25 @@ void Utils::Misc::openFolderSelect(const QString &absolutePath) { output = proc.readLine().simplified(); if (output == QStringLiteral("dolphin.desktop") || output == QStringLiteral("org.kde.dolphin.desktop")) { - proc.startDetached( - QStringLiteral("dolphin"), - QStringList{"--select", QDir::toNativeSeparators(path)}); + proc.startDetached(QStringLiteral("dolphin"), + QStringList{"--select", QDir::toNativeSeparators(path)}); } else if (output == QStringLiteral("nautilus.desktop") || output == QStringLiteral("org.gnome.Nautilus.desktop") || - output == - QStringLiteral("nautilus-folder-handler.desktop")) { - proc.startDetached( - QStringLiteral("nautilus"), - QStringList{"--no-desktop", QDir::toNativeSeparators(path)}); + output == QStringLiteral("nautilus-folder-handler.desktop")) { + proc.startDetached(QStringLiteral("nautilus"), + QStringList{"--no-desktop", QDir::toNativeSeparators(path)}); } else if (output == QStringLiteral("caja-folder-handler.desktop")) { const QDir dir = QFileInfo(path).absoluteDir(); const QString absDir = dir.absolutePath(); - proc.startDetached( - QStringLiteral("caja"), - QStringList{"--no-desktop", QDir::toNativeSeparators(absDir)}); + proc.startDetached(QStringLiteral("caja"), + QStringList{"--no-desktop", QDir::toNativeSeparators(absDir)}); } else if (output == QStringLiteral("nemo.desktop")) { - proc.startDetached( - QStringLiteral("nemo"), - QStringList{"--no-desktop", QDir::toNativeSeparators(path)}); + proc.startDetached(QStringLiteral("nemo"), + QStringList{"--no-desktop", QDir::toNativeSeparators(path)}); } else if (output == QStringLiteral("konqueror.desktop") || output == QStringLiteral("kfmclient_dir.desktop")) { - proc.startDetached( - QStringLiteral("konqueror"), - QStringList{"--select", QDir::toNativeSeparators(path)}); + proc.startDetached(QStringLiteral("konqueror"), + QStringList{"--select", QDir::toNativeSeparators(path)}); } else { openPath(path.left(path.lastIndexOf(QLatin1Char('/')))); } @@ -201,11 +194,10 @@ void Utils::Misc::openFolderSelect(const QString &absolutePath) { /** * Removes a string from the start if it starts with it */ -QString Utils::Misc::removeIfStartsWith(QString text, - const QString &removeString) { +QString Utils::Misc::removeIfStartsWith(QString text, const QString &removeString) { if (text.startsWith(removeString)) { - text.remove(QRegularExpression( - QStringLiteral("^") + QRegularExpression::escape(removeString))); + text.remove( + QRegularExpression(QStringLiteral("^") + QRegularExpression::escape(removeString))); } return text; @@ -214,11 +206,10 @@ QString Utils::Misc::removeIfStartsWith(QString text, /** * Removes a string from the end if it ends with it */ -QString Utils::Misc::removeIfEndsWith(QString text, - const QString &removeString) { +QString Utils::Misc::removeIfEndsWith(QString text, const QString &removeString) { if (text.endsWith(removeString)) { - text.remove(QRegularExpression( - QRegularExpression::escape(removeString) + QStringLiteral("$"))); + text.remove( + QRegularExpression(QRegularExpression::escape(removeString) + QStringLiteral("$"))); } return text; @@ -227,8 +218,7 @@ QString Utils::Misc::removeIfEndsWith(QString text, /** * Adds a string to the beginning of a string if it doesn't start with it */ -QString Utils::Misc::prependIfDoesNotStartWith(QString text, - const QString &startString) { +QString Utils::Misc::prependIfDoesNotStartWith(QString text, const QString &startString) { if (!text.startsWith(startString)) { text.prepend(startString); } @@ -239,8 +229,7 @@ QString Utils::Misc::prependIfDoesNotStartWith(QString text, /** * Adds a string to the end of a string if it doesn't end with it */ -QString Utils::Misc::appendIfDoesNotEndWith(QString text, - const QString &endString) { +QString Utils::Misc::appendIfDoesNotEndWith(QString text, const QString &endString) { if (!text.endsWith(endString)) { text.append(endString); } @@ -251,8 +240,7 @@ QString Utils::Misc::appendIfDoesNotEndWith(QString text, /** * Shortens text and adds a sequence string if text is too long */ -QString Utils::Misc::shorten(QString text, int length, - const QString &sequence) { +QString Utils::Misc::shorten(QString text, int length, const QString &sequence) { if (text.length() > length) { int newLength = length - sequence.length(); @@ -330,8 +318,7 @@ QString Utils::Misc::toSentenceCase(const QString &text) { for (QString &sentence : sentences) { if (sentence.length() > 0) { - sentence = sentence.left(1).toUpper() + - sentence.right(sentence.length() - 1); + sentence = sentence.left(1).toUpper() + sentence.right(sentence.length() - 1); } } @@ -365,8 +352,7 @@ QString Utils::Misc::toStartCase(const QString &text) { * @param workingDirectory the directory to run the executable from (optional) * @return true on success, false otherwise */ -bool Utils::Misc::startDetachedProcess(const QString &executablePath, - const QStringList ¶meters, +bool Utils::Misc::startDetachedProcess(const QString &executablePath, const QStringList ¶meters, QString workingDirectory) { QProcess process; @@ -379,10 +365,9 @@ bool Utils::Misc::startDetachedProcess(const QString &executablePath, // start executablePath detached with parameters #ifdef Q_OS_MAC - return process.startDetached( - QStringLiteral("open"), - QStringList() << executablePath << "--args" << parameters, - workingDirectory); + return process.startDetached(QStringLiteral("open"), + QStringList() << executablePath << "--args" << parameters, + workingDirectory); #else return process.startDetached(executablePath, parameters, workingDirectory); #endif @@ -396,8 +381,7 @@ bool Utils::Misc::startDetachedProcess(const QString &executablePath, * @param workingDirectory the directory to run the executable from * @return true on success, false otherwise */ -bool Utils::Misc::openFilesWithApplication(const QString &executablePath, - const QStringList &files, +bool Utils::Misc::openFilesWithApplication(const QString &executablePath, const QStringList &files, QString workingDirectory) { #ifdef Q_OS_MAC QProcess process; @@ -408,8 +392,7 @@ bool Utils::Misc::openFilesWithApplication(const QString &executablePath, // start executablePath detached with parameters return process.startDetached( - QStringLiteral("open"), - QStringList() << "-a" << executablePath << files, workingDirectory); + QStringLiteral("open"), QStringList() << "-a" << executablePath << files, workingDirectory); #else return startDetachedProcess(executablePath, files, workingDirectory); #endif @@ -436,8 +419,7 @@ QByteArray Utils::Misc::startSynchronousProcess(const QString &executablePath, // start executablePath synchronous with parameters #ifdef Q_OS_MAC - process.start("open", QStringList() - << executablePath << "--args" << parameters); + process.start("open", QStringList() << executablePath << "--args" << parameters); #else process.start(executablePath, parameters); #endif @@ -470,8 +452,7 @@ bool Utils::Misc::startSynchronousResultProcess(TerminalCmd &cmd) { // start executablePath synchronous with parameters #ifdef Q_OS_MAC - process.start("open", QStringList() - << cmd.executablePath << "--args" << cmd.parameters); + process.start("open", QStringList() << cmd.executablePath << "--args" << cmd.parameters); #else process.start(cmd.executablePath, cmd.parameters); #endif @@ -502,10 +483,9 @@ bool Utils::Misc::startSynchronousResultProcess(TerminalCmd &cmd) { QString Utils::Misc::defaultNotesPath() { // it seems QDir::separator() is not needed, // because Windows also uses "/" in QDir::homePath() - QString path = isInPortableMode() - ? portableDataPath() - : QDir::homePath() % Utils::Misc::dirSeparator() % - QStringLiteral("ownCloud"); + QString path = isInPortableMode() ? portableDataPath() + : QDir::homePath() % Utils::Misc::dirSeparator() % + QStringLiteral("ownCloud"); // check if the ownCloud path already exists (because the user is using // ownCloud), if not use Nextcloud @@ -519,8 +499,7 @@ QString Utils::Misc::defaultNotesPath() { QDir dir(path); if (!dir.exists()) { // set Nextcloud path if ownCloud wasn't found - path = QDir::homePath() % Utils::Misc::dirSeparator() % - QStringLiteral("Nextcloud"); + path = QDir::homePath() % Utils::Misc::dirSeparator() % QStringLiteral("Nextcloud"); } // check if Nextcloud path is found @@ -569,8 +548,7 @@ QString Utils::Misc::portableDataPath() { // argument of the executable arguments, because the applicationDirPath // will be some temporary path if (Utils::Misc::isAppImage()) { - const QFileInfo fileInfo(qApp->property( - "arguments").toStringList().at(0)); + const QFileInfo fileInfo(qApp->property("arguments").toStringList().at(0)); path = fileInfo.absolutePath(); } else { path = QCoreApplication::applicationDirPath(); @@ -617,8 +595,7 @@ bool Utils::Misc::isAppImage() { * @param path * @return */ -QString Utils::Misc::prependPortableDataPathIfNeeded(QString path, - bool ifNotEmptyOnly) { +QString Utils::Misc::prependPortableDataPathIfNeeded(QString path, bool ifNotEmptyOnly) { if (ifNotEmptyOnly && path.isEmpty()) { return QString(); } @@ -671,104 +648,85 @@ QString Utils::Misc::htmlToMarkdown(QString text) { text.remove(QChar(0)); // remove some blocks - text.remove( - QRegularExpression(QStringLiteral("<head.*?>(.+?)<\\/head>"), - QRegularExpression::CaseInsensitiveOption | - QRegularExpression::DotMatchesEverythingOption)); + text.remove(QRegularExpression(QStringLiteral("<head.*?>(.+?)<\\/head>"), + QRegularExpression::CaseInsensitiveOption | + QRegularExpression::DotMatchesEverythingOption)); - text.remove( - QRegularExpression(QStringLiteral("<script.*?>(.+?)<\\/script>"), - QRegularExpression::CaseInsensitiveOption | - QRegularExpression::DotMatchesEverythingOption)); + text.remove(QRegularExpression(QStringLiteral("<script.*?>(.+?)<\\/script>"), + QRegularExpression::CaseInsensitiveOption | + QRegularExpression::DotMatchesEverythingOption)); - text.remove( - QRegularExpression(QStringLiteral("<style.*?>(.+?)<\\/style>"), - QRegularExpression::CaseInsensitiveOption | - QRegularExpression::DotMatchesEverythingOption)); + text.remove(QRegularExpression(QStringLiteral("<style.*?>(.+?)<\\/style>"), + QRegularExpression::CaseInsensitiveOption | + QRegularExpression::DotMatchesEverythingOption)); // replace some html tags with markdown + text.replace(QRegularExpression(QStringLiteral("<strong.*?>(.+?)<\\/strong>"), + QRegularExpression::CaseInsensitiveOption | + QRegularExpression::DotMatchesEverythingOption), + QStringLiteral("**\\1**")); + text.replace(QRegularExpression(QStringLiteral("<b.*?>(.+?)<\\/b>"), + QRegularExpression::CaseInsensitiveOption | + QRegularExpression::DotMatchesEverythingOption), + QStringLiteral("**\\1**")); + text.replace(QRegularExpression(QStringLiteral("<em.*?>(.+?)<\\/em>"), + QRegularExpression::CaseInsensitiveOption | + QRegularExpression::DotMatchesEverythingOption), + QStringLiteral("*\\1*")); + text.replace(QRegularExpression(QStringLiteral("<i.*?>(.+?)<\\/i>"), + QRegularExpression::CaseInsensitiveOption | + QRegularExpression::DotMatchesEverythingOption), + QStringLiteral("*\\1*")); + text.replace(QRegularExpression(QStringLiteral("<pre.*?>(.+?)<\\/pre>"), + QRegularExpression::CaseInsensitiveOption | + QRegularExpression::DotMatchesEverythingOption), + QStringLiteral("\n```\n\\1\n```\n")); + text.replace(QRegularExpression(QStringLiteral("<code.*?>(.+?)<\\/code>"), + QRegularExpression::CaseInsensitiveOption | + QRegularExpression::DotMatchesEverythingOption), + QStringLiteral("\n```\n\\1\n```\n")); + text.replace(QRegularExpression(QStringLiteral("<h1.*?>(.+?)<\\/h1>"), + QRegularExpression::CaseInsensitiveOption | + QRegularExpression::DotMatchesEverythingOption), + QStringLiteral("\n# \\1\n")); + text.replace(QRegularExpression(QStringLiteral("<h2.*?>(.+?)<\\/h2>"), + QRegularExpression::CaseInsensitiveOption | + QRegularExpression::DotMatchesEverythingOption), + QStringLiteral("\n## \\1\n")); + text.replace(QRegularExpression(QStringLiteral("<h3.*?>(.+?)<\\/h3>"), + QRegularExpression::CaseInsensitiveOption | + QRegularExpression::DotMatchesEverythingOption), + QStringLiteral("\n### \\1\n")); + text.replace(QRegularExpression(QStringLiteral("<h4.*?>(.+?)<\\/h4>"), + QRegularExpression::CaseInsensitiveOption | + QRegularExpression::DotMatchesEverythingOption), + QStringLiteral("\n#### \\1\n")); + text.replace(QRegularExpression(QStringLiteral("<h5.*?>(.+?)<\\/h5>"), + QRegularExpression::CaseInsensitiveOption | + QRegularExpression::DotMatchesEverythingOption), + QStringLiteral("\n##### \\1\n")); + text.replace(QRegularExpression(QStringLiteral("<h6.*?>(.+?)<\\/h6>"), + QRegularExpression::CaseInsensitiveOption | + QRegularExpression::DotMatchesEverythingOption), + QStringLiteral("\n###### \\1\n")); + text.replace(QRegularExpression(QStringLiteral("<li.*?>(.+?)<\\/li>"), + QRegularExpression::CaseInsensitiveOption | + QRegularExpression::DotMatchesEverythingOption), + QStringLiteral("- \\1\n")); text.replace( - QRegularExpression(QStringLiteral("<strong.*?>(.+?)<\\/strong>"), - QRegularExpression::CaseInsensitiveOption | - QRegularExpression::DotMatchesEverythingOption), - QStringLiteral("**\\1**")); - text.replace( - QRegularExpression(QStringLiteral("<b.*?>(.+?)<\\/b>"), - QRegularExpression::CaseInsensitiveOption | - QRegularExpression::DotMatchesEverythingOption), - QStringLiteral("**\\1**")); - text.replace( - QRegularExpression(QStringLiteral("<em.*?>(.+?)<\\/em>"), - QRegularExpression::CaseInsensitiveOption | - QRegularExpression::DotMatchesEverythingOption), - QStringLiteral("*\\1*")); - text.replace( - QRegularExpression(QStringLiteral("<i.*?>(.+?)<\\/i>"), - QRegularExpression::CaseInsensitiveOption | - QRegularExpression::DotMatchesEverythingOption), - QStringLiteral("*\\1*")); - text.replace( - QRegularExpression(QStringLiteral("<pre.*?>(.+?)<\\/pre>"), - QRegularExpression::CaseInsensitiveOption | - QRegularExpression::DotMatchesEverythingOption), - QStringLiteral("\n```\n\\1\n```\n")); - text.replace( - QRegularExpression(QStringLiteral("<code.*?>(.+?)<\\/code>"), - QRegularExpression::CaseInsensitiveOption | - QRegularExpression::DotMatchesEverythingOption), - QStringLiteral("\n```\n\\1\n```\n")); - text.replace( - QRegularExpression(QStringLiteral("<h1.*?>(.+?)<\\/h1>"), - QRegularExpression::CaseInsensitiveOption | - QRegularExpression::DotMatchesEverythingOption), - QStringLiteral("\n# \\1\n")); - text.replace( - QRegularExpression(QStringLiteral("<h2.*?>(.+?)<\\/h2>"), - QRegularExpression::CaseInsensitiveOption | - QRegularExpression::DotMatchesEverythingOption), - QStringLiteral("\n## \\1\n")); - text.replace( - QRegularExpression(QStringLiteral("<h3.*?>(.+?)<\\/h3>"), - QRegularExpression::CaseInsensitiveOption | - QRegularExpression::DotMatchesEverythingOption), - QStringLiteral("\n### \\1\n")); - text.replace( - QRegularExpression(QStringLiteral("<h4.*?>(.+?)<\\/h4>"), - QRegularExpression::CaseInsensitiveOption | - QRegularExpression::DotMatchesEverythingOption), - QStringLiteral("\n#### \\1\n")); - text.replace( - QRegularExpression(QStringLiteral("<h5.*?>(.+?)<\\/h5>"), - QRegularExpression::CaseInsensitiveOption | - QRegularExpression::DotMatchesEverythingOption), - QStringLiteral("\n##### \\1\n")); - text.replace( - QRegularExpression(QStringLiteral("<h6.*?>(.+?)<\\/h6>"), - QRegularExpression::CaseInsensitiveOption | - QRegularExpression::DotMatchesEverythingOption), - QStringLiteral("\n###### \\1\n")); - text.replace( - QRegularExpression(QStringLiteral("<li.*?>(.+?)<\\/li>"), - QRegularExpression::CaseInsensitiveOption | - QRegularExpression::DotMatchesEverythingOption), - QStringLiteral("- \\1\n")); - text.replace(QRegularExpression(QStringLiteral("<br.*?>"), - QRegularExpression::CaseInsensitiveOption), - QStringLiteral("\n")); - text.replace(QRegularExpression( - QStringLiteral("<a[^>]+href=\"(.+?)\".*?>(.+?)<\\/a>"), - QRegularExpression::CaseInsensitiveOption | - QRegularExpression::DotMatchesEverythingOption), + QRegularExpression(QStringLiteral("<br.*?>"), QRegularExpression::CaseInsensitiveOption), + QStringLiteral("\n")); + text.replace(QRegularExpression(QStringLiteral("<a[^>]+href=\"(.+?)\".*?>(.+?)<\\/a>"), + QRegularExpression::CaseInsensitiveOption | + QRegularExpression::DotMatchesEverythingOption), QStringLiteral("[\\2](\\1)")); - text.replace( - QRegularExpression(QStringLiteral("<p.*?>(.+?)</p>"), - QRegularExpression::CaseInsensitiveOption | - QRegularExpression::DotMatchesEverythingOption), - QStringLiteral("\n\n\\1\n\n")); + text.replace(QRegularExpression(QStringLiteral("<p.*?>(.+?)</p>"), + QRegularExpression::CaseInsensitiveOption | + QRegularExpression::DotMatchesEverythingOption), + QStringLiteral("\n\n\\1\n\n")); // replace multiple line breaks - text.replace(QRegularExpression(QStringLiteral("\n\n+")), - QStringLiteral("\n\n")); + text.replace(QRegularExpression(QStringLiteral("\n\n+")), QStringLiteral("\n\n")); return text; } @@ -788,11 +746,11 @@ QString Utils::Misc::parseTaskList(const QString &html, bool clickable) { const auto listTag = QStringLiteral("<li style=\"list-style-type:square\">"); static const QRegularExpression re1(QStringLiteral(R"(<li>(\s*(<p>)*\s*)\[ ?\])"), - QRegularExpression::CaseInsensitiveOption); + QRegularExpression::CaseInsensitiveOption); static const QRegularExpression re2(QStringLiteral(R"(<li>(\s*(<p>)*\s*)\[[xX]\])"), - QRegularExpression::CaseInsensitiveOption); + QRegularExpression::CaseInsensitiveOption); static const QRegularExpression re3(QStringLiteral(R"(<li>(\s*(<p>)*\s*)\[-\])"), - QRegularExpression::CaseInsensitiveOption); + QRegularExpression::CaseInsensitiveOption); if (!clickable) { text.replace(re1, listTag % QStringLiteral("\\1☐")); text.replace(re2, listTag % QStringLiteral("\\1☑")); @@ -807,12 +765,12 @@ QString Utils::Misc::parseTaskList(const QString &html, bool clickable) { text.replace(re3, listTag % QStringLiteral("\\1✕")); - const QString checkboxStart = QStringLiteral( - R"(<a class="task-list-item-checkbox" href="checkbox://_)"); - text.replace(re1, - listTag % QStringLiteral("\\1") % checkboxStart % QStringLiteral("\">☐</a>")); - text.replace(re2, - listTag % QStringLiteral("\\1") % checkboxStart % QStringLiteral("\">☑</a>")); + const QString checkboxStart = + QStringLiteral(R"(<a class="task-list-item-checkbox" href="checkbox://_)"); + text.replace( + re1, listTag % QStringLiteral("\\1") % checkboxStart % QStringLiteral("\">☐</a>")); + text.replace( + re2, listTag % QStringLiteral("\\1") % checkboxStart % QStringLiteral("\">☑</a>")); int count = 0; int pos = 0; @@ -881,9 +839,7 @@ QString Utils::Misc::appDataPath() { * * @return */ -QString Utils::Misc::logFilePath() { - return appDataPath() % QStringLiteral("/QOwnNotes.log"); -} +QString Utils::Misc::logFilePath() { return appDataPath() % QStringLiteral("/QOwnNotes.log"); } /** * Transforms all line feeds to \n @@ -908,10 +864,9 @@ QString Utils::Misc::replaceOwnCloudText(QString text, bool useShortText) { return text; } - QString replaceText = useShortText ? QStringLiteral("NC / oC") - : QStringLiteral("Nextcloud / ownCloud"); - return text.replace(QStringLiteral("ownCloud"), replaceText, - Qt::CaseInsensitive); + QString replaceText = + useShortText ? QStringLiteral("NC / oC") : QStringLiteral("Nextcloud / ownCloud"); + return text.replace(QStringLiteral("ownCloud"), replaceText, Qt::CaseInsensitive); } /** @@ -945,17 +900,16 @@ void Utils::Misc::restartApplication() { QString Utils::Misc::appendSingleAppInstanceTextIfNeeded(QString text) { if (QSettings().value("allowOnlyOneAppInstance").toBool()) { text.append(QStringLiteral("\n\n") + - QObject::tr("You are using the single app instance mode, that " - "prevents the application be be started a second time. For the " - "next launch of the application the single app instance mode " - "will be disabled, so that the application can be restarted " - "before quitting this instance.")); + QObject::tr("You are using the single app instance mode, that " + "prevents the application be be started a second time. For the " + "next launch of the application the single app instance mode " + "will be disabled, so that the application can be restarted " + "before quitting this instance.")); } return text; } - QByteArray Utils::Misc::friendlyUserAgentString() { const auto pattern = QStringLiteral("%1 (QOwnNotes - %2)"); @@ -1006,8 +960,7 @@ QByteArray Utils::Misc::downloadUrl(const QUrl &url, bool usePost, QByteArray po timer.setSingleShot(true); QObject::connect(&timer, SIGNAL(timeout()), &loop, SLOT(quit())); - QObject::connect(manager, SIGNAL(finished(QNetworkReply *)), &loop, - SLOT(quit())); + QObject::connect(manager, SIGNAL(finished(QNetworkReply *)), &loop, SLOT(quit())); // 10 sec timeout for the request timer.start(10000); @@ -1017,8 +970,7 @@ QByteArray Utils::Misc::downloadUrl(const QUrl &url, bool usePost, QByteArray po Utils::Misc::friendlyUserAgentString()); #if QT_VERSION < QT_VERSION_CHECK(5, 9, 0) - networkRequest.setAttribute(QNetworkRequest::FollowRedirectsAttribute, - true); + networkRequest.setAttribute(QNetworkRequest::FollowRedirectsAttribute, true); #else networkRequest.setAttribute(QNetworkRequest::RedirectPolicyAttribute, true); #endif @@ -1031,7 +983,8 @@ QByteArray Utils::Misc::downloadUrl(const QUrl &url, bool usePost, QByteArray po postData = QByteArray(); } - networkRequest.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded"); + networkRequest.setHeader(QNetworkRequest::ContentTypeHeader, + "application/x-www-form-urlencoded"); reply = manager->post(networkRequest, postData); } else { reply = manager->get(networkRequest); @@ -1041,8 +994,7 @@ QByteArray Utils::Misc::downloadUrl(const QUrl &url, bool usePost, QByteArray po // if we didn't get a timeout let us return the content if (timer.isActive()) { - int statusCode = - reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(); + int statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(); // only get the data if the status code was "success" // see: https://en.wikipedia.org/wiki/List_of_HTTP_status_codes @@ -1087,27 +1039,18 @@ bool Utils::Misc::downloadUrlToFile(const QUrl &url, QFile *file) { */ QString Utils::Misc::genericCSS() { QSettings settings; - const bool darkModeColors = - settings.value(QStringLiteral("darkModeColors")).toBool(); - QString color = - darkModeColors ? QStringLiteral("#ffd694") : QStringLiteral("#fc7600"); - QString cssStyles = - QStringLiteral("a {color: ") % color % QStringLiteral("}"); + const bool darkModeColors = settings.value(QStringLiteral("darkModeColors")).toBool(); + QString color = darkModeColors ? QStringLiteral("#ffd694") : QStringLiteral("#fc7600"); + QString cssStyles = QStringLiteral("a {color: ") % color % QStringLiteral("}"); - color = - darkModeColors ? QStringLiteral("#5b5b5b") : QStringLiteral("#e8e8e8"); - cssStyles += - QStringLiteral("kbd {background-color: ") % color % QStringLiteral("}"); + color = darkModeColors ? QStringLiteral("#5b5b5b") : QStringLiteral("#e8e8e8"); + cssStyles += QStringLiteral("kbd {background-color: ") % color % QStringLiteral("}"); - color = - darkModeColors ? QStringLiteral("#336924") : QStringLiteral("#d6ffc7"); - cssStyles += - QStringLiteral("ins {background-color: ") % color % QStringLiteral("}"); + color = darkModeColors ? QStringLiteral("#336924") : QStringLiteral("#d6ffc7"); + cssStyles += QStringLiteral("ins {background-color: ") % color % QStringLiteral("}"); - color = - darkModeColors ? QStringLiteral("#802c2c") : QStringLiteral("#ffd7d7"); - cssStyles += - QStringLiteral("del {background-color: ") % color % QStringLiteral("}"); + color = darkModeColors ? QStringLiteral("#802c2c") : QStringLiteral("#ffd7d7"); + cssStyles += QStringLiteral("del {background-color: ") % color % QStringLiteral("}"); return cssStyles; } @@ -1117,45 +1060,37 @@ QString Utils::Misc::genericCSS() { */ QHash<int, Utils::Misc::SearchEngine> Utils::Misc::getSearchEnginesHashMap() { QHash<int, Utils::Misc::SearchEngine> searchEngines; - searchEngines.insert(SearchEngines::Google, - {QStringLiteral("Google"), - QStringLiteral("https://www.google.com/search?q="), - SearchEngines::Google}); + searchEngines.insert(SearchEngines::Google, {QStringLiteral("Google"), + QStringLiteral("https://www.google.com/search?q="), + SearchEngines::Google}); searchEngines.insert(SearchEngines::Bing, - {QStringLiteral("Bing"), - QStringLiteral("https://www.bing.com/search?q="), + {QStringLiteral("Bing"), QStringLiteral("https://www.bing.com/search?q="), SearchEngines::Bing}); searchEngines.insert( SearchEngines::DuckDuckGo, - {QStringLiteral("DuckDuckGo"), - QStringLiteral("https://duckduckgo.com/?t=qownnotes&q="), + {QStringLiteral("DuckDuckGo"), QStringLiteral("https://duckduckgo.com/?t=qownnotes&q="), SearchEngines::DuckDuckGo}); - searchEngines.insert(SearchEngines::Yahoo, - {QStringLiteral("Yahoo"), - QStringLiteral("https://search.yahoo.com/search?p="), - SearchEngines::Yahoo}); + searchEngines.insert( + SearchEngines::Yahoo, + {QStringLiteral("Yahoo"), QStringLiteral("https://search.yahoo.com/search?p="), + SearchEngines::Yahoo}); searchEngines.insert( SearchEngines::GoogleScholar, {QStringLiteral("Google Scholar"), - QStringLiteral("https://scholar.google.co.il/scholar?q="), - SearchEngines::GoogleScholar}); + QStringLiteral("https://scholar.google.co.il/scholar?q="), SearchEngines::GoogleScholar}); searchEngines.insert( SearchEngines::Yandex, - {QStringLiteral("Yandex"), - QStringLiteral("https://www.yandex.com/search/?text="), + {QStringLiteral("Yandex"), QStringLiteral("https://www.yandex.com/search/?text="), SearchEngines::Yandex}); searchEngines.insert(SearchEngines::AskDotCom, - {QStringLiteral("Ask.com"), - QStringLiteral("https://www.ask.com/web?q="), + {QStringLiteral("Ask.com"), QStringLiteral("https://www.ask.com/web?q="), SearchEngines::AskDotCom}); - searchEngines.insert( - SearchEngines::Qwant, - {QStringLiteral("Qwant"), QStringLiteral("https://www.qwant.com/?q="), - SearchEngines::Qwant}); + searchEngines.insert(SearchEngines::Qwant, + {QStringLiteral("Qwant"), QStringLiteral("https://www.qwant.com/?q="), + SearchEngines::Qwant}); searchEngines.insert( SearchEngines::Startpage, - {QStringLiteral("Startpage"), - QStringLiteral("https://www.startpage.com/do/dsearch?query="), + {QStringLiteral("Startpage"), QStringLiteral("https://www.startpage.com/do/dsearch?query="), SearchEngines::Startpage}); return searchEngines; } @@ -1165,9 +1100,7 @@ QHash<int, Utils::Misc::SearchEngine> Utils::Misc::getSearchEnginesHashMap() { * * @return */ -int Utils::Misc::getDefaultSearchEngineId() { - return SearchEngines::DuckDuckGo; -} +int Utils::Misc::getDefaultSearchEngineId() { return SearchEngines::DuckDuckGo; } /** * Returns a list of search engines in the order it should be displayed @@ -1175,11 +1108,10 @@ int Utils::Misc::getDefaultSearchEngineId() { * @return */ QList<int> Utils::Misc::getSearchEnginesIds() { - return QList<int>{SearchEngines::DuckDuckGo, SearchEngines::Google, - SearchEngines::Bing, SearchEngines::Yahoo, - SearchEngines::GoogleScholar, SearchEngines::Yandex, - SearchEngines::AskDotCom, SearchEngines::Qwant, - SearchEngines::Startpage}; + return QList<int>{ + SearchEngines::DuckDuckGo, SearchEngines::Google, SearchEngines::Bing, + SearchEngines::Yahoo, SearchEngines::GoogleScholar, SearchEngines::Yandex, + SearchEngines::AskDotCom, SearchEngines::Qwant, SearchEngines::Startpage}; } /** @@ -1191,15 +1123,12 @@ void Utils::Misc::presetDisableAutomaticUpdateDialog() { // disable the automatic update dialog per default for repositories and // self-builds - if (settings.value(QStringLiteral("disableAutomaticUpdateDialog")) - .toString() - .isEmpty()) { + if (settings.value(QStringLiteral("disableAutomaticUpdateDialog")).toString().isEmpty()) { QString release = qApp->property("release").toString(); bool enabled = release.contains(QStringLiteral("Travis")) || release.contains(QStringLiteral("AppVeyor")) || release.contains(QStringLiteral("AppImage")); - settings.setValue(QStringLiteral("disableAutomaticUpdateDialog"), - !enabled); + settings.setValue(QStringLiteral("disableAutomaticUpdateDialog"), !enabled); } } @@ -1221,8 +1150,7 @@ void writeStreamElement<QString>(QDataStream &os, const QString s) { /** * Save printer settings to a stream */ -QDataStream &Utils::Misc::dataStreamWrite(QDataStream &os, - const QPrinter &printer) { +QDataStream &Utils::Misc::dataStreamWrite(QDataStream &os, const QPrinter &printer) { writeStreamElement(os, printer.printerName()); writeStreamElement(os, printer.pageLayout().pageSize().id()); writeStreamElement(os, printer.collateCopies()); @@ -1246,9 +1174,8 @@ QDataStream &Utils::Misc::dataStreamWrite(QDataStream &os, auto margins = printer.pageLayout().margins(QPageLayout::Unit::Millimeter); os << margins.left() << margins.top() << margins.right() << margins.bottom(); - Q_ASSERT_X( - os.status() == QDataStream::Ok, __FUNCTION__, - QString("Stream status = %1").arg(os.status()).toStdString().c_str()); + Q_ASSERT_X(os.status() == QDataStream::Ok, __FUNCTION__, + QString("Stream status = %1").arg(os.status()).toStdString().c_str()); return os; } @@ -1305,9 +1232,8 @@ QDataStream &Utils::Misc::dataStreamRead(QDataStream &is, QPrinter &printer) { QMarginsF margins(left, top, right, bottom); printer.setPageMargins(margins, QPageLayout::Unit::Millimeter); - Q_ASSERT_X( - is.status() == QDataStream::Ok, __FUNCTION__, - QString("Stream status = %1").arg(is.status()).toStdString().c_str()); + Q_ASSERT_X(is.status() == QDataStream::Ok, __FUNCTION__, + QString("Stream status = %1").arg(is.status()).toStdString().c_str()); return is; } @@ -1318,8 +1244,7 @@ QDataStream &Utils::Misc::dataStreamRead(QDataStream &is, QPrinter &printer) { * @param printer * @param settingsKey */ -void Utils::Misc::storePrinterSettings(QPrinter *printer, - const QString &settingsKey) { +void Utils::Misc::storePrinterSettings(QPrinter *printer, const QString &settingsKey) { QByteArray byteArr; QDataStream os(&byteArr, QIODevice::WriteOnly); dataStreamWrite(os, *printer); @@ -1332,8 +1257,7 @@ void Utils::Misc::storePrinterSettings(QPrinter *printer, * @param printer * @param settingsKey */ -void Utils::Misc::loadPrinterSettings(QPrinter *printer, - const QString &settingsKey) { +void Utils::Misc::loadPrinterSettings(QPrinter *printer, const QString &settingsKey) { QSettings settings; if (!settings.value(settingsKey).isValid()) { @@ -1361,9 +1285,8 @@ bool Utils::Misc::isNoteEditingAllowed() { * @return */ bool Utils::Misc::useInternalExportStylingForPreview() { - return QSettings().value( - QStringLiteral("MainWindow/noteTextView.useInternalExportStyling"), - true) + return QSettings() + .value(QStringLiteral("MainWindow/noteTextView.useInternalExportStyling"), true) .toBool(); } @@ -1373,9 +1296,10 @@ bool Utils::Misc::useInternalExportStylingForPreview() { * @return */ QString Utils::Misc::previewFontString() { - return QSettings().value(isPreviewUseEditorStyles() ? - QStringLiteral("MainWindow/noteTextEdit.font") : - QStringLiteral("MainWindow/noteTextView.font")).toString(); + return QSettings() + .value(isPreviewUseEditorStyles() ? QStringLiteral("MainWindow/noteTextEdit.font") + : QStringLiteral("MainWindow/noteTextView.font")) + .toString(); } /** @@ -1384,9 +1308,10 @@ QString Utils::Misc::previewFontString() { * @return */ QString Utils::Misc::previewCodeFontString() { - return QSettings().value(isPreviewUseEditorStyles() ? - QStringLiteral("MainWindow/noteTextEdit.code.font") : - QStringLiteral("MainWindow/noteTextView.code.font")).toString(); + return QSettings() + .value(isPreviewUseEditorStyles() ? QStringLiteral("MainWindow/noteTextEdit.code.font") + : QStringLiteral("MainWindow/noteTextView.code.font")) + .toString(); } /** @@ -1395,9 +1320,9 @@ QString Utils::Misc::previewCodeFontString() { * @return */ bool Utils::Misc::isPreviewUseEditorStyles() { - return QSettings().value( - QStringLiteral("MainWindow/noteTextView.useEditorStyles"), - true).toBool(); + return QSettings() + .value(QStringLiteral("MainWindow/noteTextView.useEditorStyles"), true) + .toBool(); } /** @@ -1430,8 +1355,7 @@ bool Utils::Misc::isRestoreCursorPosition() { const bool defaultValue = true; #endif - return QSettings().value(QStringLiteral("restoreCursorPosition"), - defaultValue).toBool(); + return QSettings().value(QStringLiteral("restoreCursorPosition"), defaultValue).toBool(); } /** @@ -1442,8 +1366,7 @@ bool Utils::Misc::isRestoreCursorPosition() { bool Utils::Misc::isDarkModeIconTheme() { const QSettings settings; const bool darkMode = settings.value(QStringLiteral("darkMode")).toBool(); - return settings.value(QStringLiteral("darkModeIconTheme"), darkMode) - .toBool(); + return settings.value(QStringLiteral("darkModeIconTheme"), darkMode).toBool(); } /** @@ -1452,8 +1375,7 @@ bool Utils::Misc::isDarkModeIconTheme() { * @return */ bool Utils::Misc::doAutomaticNoteFolderDatabaseClosing() { - return QSettings().value(QStringLiteral("automaticNoteFolderDatabaseClosing")) - .toBool(); + return QSettings().value(QStringLiteral("automaticNoteFolderDatabaseClosing")).toBool(); } /** @@ -1490,9 +1412,7 @@ QString Utils::Misc::indentCharacters() { * * @return */ -int Utils::Misc::indentSize() { - return QSettings().value("Editor/indentSize", 4).toInt(); -} +int Utils::Misc::indentSize() { return QSettings().value("Editor/indentSize", 4).toInt(); } /** * Unescapes html special characters @@ -1504,11 +1424,11 @@ QString Utils::Misc::unescapeHtml(QString html, bool soft) { // It looks like "text.toPlainText();" also destroys "<a" tags, so we // also want a "soft" un-escaping method if (soft) { - html.replace("<","<"); - html.replace(">",">"); - html.replace("&","&"); - html.replace(""","\""); - html.replace("'","'"); + html.replace("<", "<"); + html.replace(">", ">"); + html.replace("&", "&"); + html.replace(""", "\""); + html.replace("'", "'"); return html; } @@ -1542,9 +1462,7 @@ QString Utils::Misc::htmlspecialchars(QString text) { * * @param text */ -void Utils::Misc::printInfo(const QString &text) { - qInfo() << text; -} +void Utils::Misc::printInfo(const QString &text) { qInfo() << text; } /** * Converts a byte size to a human readable size @@ -1572,17 +1490,14 @@ QString Utils::Misc::toHumanReadableByteSize(qint64 size) { * @param headline * @param data */ -QString Utils::Misc::prepareDebugInformationLine(const QString &headline, - QString data, +QString Utils::Misc::prepareDebugInformationLine(const QString &headline, QString data, bool withGitHubLineBreaks, const QString &typeText) { // add two spaces if we don't want GitHub line breaks - const QString spaces = - withGitHubLineBreaks ? QString() : QStringLiteral(" "); + const QString spaces = withGitHubLineBreaks ? QString() : QStringLiteral(" "); if (data.contains(QStringLiteral("\n"))) { - data = QStringLiteral("\n```\n") % data.trimmed() % - QStringLiteral("\n```"); + data = QStringLiteral("\n```\n") % data.trimmed() % QStringLiteral("\n```"); } else { data = (data.isEmpty()) ? QStringLiteral("*empty*") : "`" % data % "`"; } @@ -1608,51 +1523,40 @@ QString Utils::Misc::generateDebugInformation(bool withGitHubLineBreaks) { // add information about QOwnNotes output += QStringLiteral("\n## General Info\n\n"); - output += - prepareDebugInformationLine(QStringLiteral("Current Date"), - dateTime.toString(), withGitHubLineBreaks); - output += prepareDebugInformationLine( - QStringLiteral("Version"), QString(VERSION), withGitHubLineBreaks); - output += prepareDebugInformationLine( - QStringLiteral("Build date"), QString(__DATE__), withGitHubLineBreaks); - output += prepareDebugInformationLine(QStringLiteral("Build number"), - QString::number(BUILD), + output += prepareDebugInformationLine(QStringLiteral("Current Date"), dateTime.toString(), + withGitHubLineBreaks); + output += prepareDebugInformationLine(QStringLiteral("Version"), QString(VERSION), + withGitHubLineBreaks); + output += prepareDebugInformationLine(QStringLiteral("Build date"), QString(__DATE__), + withGitHubLineBreaks); + output += prepareDebugInformationLine(QStringLiteral("Build number"), QString::number(BUILD), + withGitHubLineBreaks); + output += prepareDebugInformationLine(QStringLiteral("Platform"), QString(PLATFORM), withGitHubLineBreaks); - output += prepareDebugInformationLine( - QStringLiteral("Platform"), QString(PLATFORM), withGitHubLineBreaks); #if (QT_VERSION >= QT_VERSION_CHECK(5, 4, 0)) output += prepareDebugInformationLine(QStringLiteral("Operating System"), - QSysInfo::prettyProductName(), - withGitHubLineBreaks); + QSysInfo::prettyProductName(), withGitHubLineBreaks); output += prepareDebugInformationLine(QStringLiteral("Build architecture"), - QSysInfo::buildCpuArchitecture(), + QSysInfo::buildCpuArchitecture(), withGitHubLineBreaks); + output += prepareDebugInformationLine(QStringLiteral("Current architecture"), + QSysInfo::currentCpuArchitecture(), withGitHubLineBreaks); +#endif + output += prepareDebugInformationLine( + QStringLiteral("Release"), qApp->property("release").toString(), withGitHubLineBreaks); + output += prepareDebugInformationLine(QStringLiteral("Qt Version (build)"), + QStringLiteral(QT_VERSION_STR), withGitHubLineBreaks); + output += prepareDebugInformationLine(QStringLiteral("Qt Version (runtime)"), qVersion(), withGitHubLineBreaks); output += prepareDebugInformationLine( - QStringLiteral("Current architecture"), - QSysInfo::currentCpuArchitecture(), withGitHubLineBreaks); -#endif - output += prepareDebugInformationLine(QStringLiteral("Release"), - qApp->property("release").toString(), - withGitHubLineBreaks); - output += prepareDebugInformationLine(QStringLiteral("Qt Version (build)"), - QStringLiteral(QT_VERSION_STR), - withGitHubLineBreaks); - output += - prepareDebugInformationLine(QStringLiteral("Qt Version (runtime)"), - qVersion(), withGitHubLineBreaks); - output += prepareDebugInformationLine(QStringLiteral("Portable mode"), - Utils::Misc::isInPortableMode() - ? QStringLiteral("yes") - : QStringLiteral("no"), - withGitHubLineBreaks); - output += - prepareDebugInformationLine(QStringLiteral("Settings path / key"), - settings.fileName(), withGitHubLineBreaks); + QStringLiteral("Portable mode"), + Utils::Misc::isInPortableMode() ? QStringLiteral("yes") : QStringLiteral("no"), + withGitHubLineBreaks); + output += prepareDebugInformationLine(QStringLiteral("Settings path / key"), + settings.fileName(), withGitHubLineBreaks); output += prepareDebugInformationLine( QStringLiteral("Application database path"), - QDir::toNativeSeparators(DatabaseService::getDiskDatabasePath()), - withGitHubLineBreaks); + QDir::toNativeSeparators(DatabaseService::getDiskDatabasePath()), withGitHubLineBreaks); output += prepareDebugInformationLine( QStringLiteral("Application arguments"), qApp->property("arguments").toStringList().join(QStringLiteral("`, `")), @@ -1663,16 +1567,13 @@ QString Utils::Misc::generateDebugInformation(bool withGitHubLineBreaks) { debug = QStringLiteral("1"); #endif - output += prepareDebugInformationLine(QStringLiteral("Qt Debug"), debug, - withGitHubLineBreaks); + output += prepareDebugInformationLine(QStringLiteral("Qt Debug"), debug, withGitHubLineBreaks); output += prepareDebugInformationLine(QStringLiteral("Locale (system)"), - QLocale::system().name(), - withGitHubLineBreaks); + QLocale::system().name(), withGitHubLineBreaks); output += prepareDebugInformationLine( QStringLiteral("Locale (interface)"), - settings.value(QStringLiteral("interfaceLanguage")).toString(), - withGitHubLineBreaks); + settings.value(QStringLiteral("interfaceLanguage")).toString(), withGitHubLineBreaks); #ifndef INTEGRATION_TESTS #if (QT_VERSION >= QT_VERSION_CHECK(5, 6, 0)) @@ -1681,12 +1582,10 @@ QString Utils::Misc::generateDebugInformation(bool withGitHubLineBreaks) { QScreen *primaryScreen = QGuiApplication::primaryScreen(); #endif if (primaryScreen != nullptr) { - QString screenResolution = - QString::number(primaryScreen->geometry().width()) + "x" + - QString::number(primaryScreen->geometry().height()); - output += - prepareDebugInformationLine(QStringLiteral("Primary screen resolution"), - screenResolution, withGitHubLineBreaks); + QString screenResolution = QString::number(primaryScreen->geometry().width()) + "x" + + QString::number(primaryScreen->geometry().height()); + output += prepareDebugInformationLine(QStringLiteral("Primary screen resolution"), + screenResolution, withGitHubLineBreaks); } QList<QScreen *> screens = qApp->screens(); @@ -1695,63 +1594,53 @@ QString Utils::Misc::generateDebugInformation(bool withGitHubLineBreaks) { QStringList screenResolutions; Q_FOREACH (QScreen *screen, screens) { - screenResolutions.append( - QString::number(screen->geometry().width()) + "x" + - QString::number(screen->geometry().height())); + screenResolutions.append(QString::number(screen->geometry().width()) + "x" + + QString::number(screen->geometry().height())); } - output += prepareDebugInformationLine( - QStringLiteral("Screen resolution(s)"), - screenResolutions.join(QStringLiteral(", ")), withGitHubLineBreaks); + output += prepareDebugInformationLine(QStringLiteral("Screen resolution(s)"), + screenResolutions.join(QStringLiteral(", ")), + withGitHubLineBreaks); } #endif - output += prepareDebugInformationLine( - QStringLiteral("Icon theme"), QIcon::themeName(), withGitHubLineBreaks); - output += prepareDebugInformationLine( - QStringLiteral("Notes in current note folder"), - QString::number(Note::countAll()), withGitHubLineBreaks); - output += prepareDebugInformationLine( - QStringLiteral("Calendar items"), - QString::number(CalendarItem::countAll()), withGitHubLineBreaks); - output += prepareDebugInformationLine( - QStringLiteral("Enabled scripts"), - QString::number(Script::countEnabled()), withGitHubLineBreaks); + output += prepareDebugInformationLine(QStringLiteral("Icon theme"), QIcon::themeName(), + withGitHubLineBreaks); + output += prepareDebugInformationLine(QStringLiteral("Notes in current note folder"), + QString::number(Note::countAll()), withGitHubLineBreaks); + output += prepareDebugInformationLine(QStringLiteral("Calendar items"), + QString::number(CalendarItem::countAll()), + withGitHubLineBreaks); + output += + prepareDebugInformationLine(QStringLiteral("Enabled scripts"), + QString::number(Script::countEnabled()), withGitHubLineBreaks); // add information about the server output += QStringLiteral("\n## Server Info\n\n"); - output += prepareDebugInformationLine( - QStringLiteral("serverUrl"), - CloudConnection::currentCloudConnection().getServerUrl(), - withGitHubLineBreaks); - const bool appIsValid = - settings.value(QStringLiteral("ownCloudInfo/appIsValid")).toBool(); + output += prepareDebugInformationLine(QStringLiteral("serverUrl"), + CloudConnection::currentCloudConnection().getServerUrl(), + withGitHubLineBreaks); + const bool appIsValid = settings.value(QStringLiteral("ownCloudInfo/appIsValid")).toBool(); output += prepareDebugInformationLine( QStringLiteral("appIsValid"), - QString(appIsValid ? QStringLiteral("yes") : QStringLiteral("no")), - withGitHubLineBreaks); + QString(appIsValid ? QStringLiteral("yes") : QStringLiteral("no")), withGitHubLineBreaks); output += prepareDebugInformationLine( QStringLiteral("notesPathExists"), - settings.value(QStringLiteral("ownCloudInfo/notesPathExistsText")) - .toString(), + settings.value(QStringLiteral("ownCloudInfo/notesPathExistsText")).toString(), withGitHubLineBreaks); if (appIsValid) { output += prepareDebugInformationLine( QStringLiteral("serverVersion"), - settings.value(QStringLiteral("ownCloudInfo/serverVersion")) - .toString(), + settings.value(QStringLiteral("ownCloudInfo/serverVersion")).toString(), withGitHubLineBreaks); output += prepareDebugInformationLine( QStringLiteral("appVersion"), - settings.value(QStringLiteral("ownCloudInfo/appVersion")) - .toString(), + settings.value(QStringLiteral("ownCloudInfo/appVersion")).toString(), withGitHubLineBreaks); } else { output += prepareDebugInformationLine( QStringLiteral("connectionErrorMessage"), - settings - .value(QStringLiteral("ownCloudInfo/connectionErrorMessage")) - .toString(), + settings.value(QStringLiteral("ownCloudInfo/connectionErrorMessage")).toString(), withGitHubLineBreaks); } @@ -1759,87 +1648,71 @@ QString Utils::Misc::generateDebugInformation(bool withGitHubLineBreaks) { output += QStringLiteral("\n## Spellchecking\n\n"); output += prepareDebugInformationLine( - QStringLiteral("Enabled"), - settings.value(QStringLiteral("checkSpelling")).toString(), + QStringLiteral("Enabled"), settings.value(QStringLiteral("checkSpelling")).toString(), withGitHubLineBreaks); output += prepareDebugInformationLine( QStringLiteral("Selected language"), - settings.value(QStringLiteral("spellCheckLanguage")).toString(), - withGitHubLineBreaks); + settings.value(QStringLiteral("spellCheckLanguage")).toString(), withGitHubLineBreaks); #ifndef INTEGRATION_TESTS // auto *speller = new Sonnet::Speller(); output += prepareDebugInformationLine( QStringLiteral("Language codes"), - Sonnet::Speller::availableLanguages().join(QStringLiteral(", ")), - withGitHubLineBreaks); + Sonnet::Speller::availableLanguages().join(QStringLiteral(", ")), withGitHubLineBreaks); output += prepareDebugInformationLine( QStringLiteral("Language names"), - Sonnet::Speller::availableLanguageNames().join(QStringLiteral(", ")), - withGitHubLineBreaks); + Sonnet::Speller::availableLanguageNames().join(QStringLiteral(", ")), withGitHubLineBreaks); // delete speller; #endif output += prepareDebugInformationLine( QStringLiteral("Application dictionaries path"), - QDir::toNativeSeparators(Utils::Misc::localDictionariesPath()), - withGitHubLineBreaks); + QDir::toNativeSeparators(Utils::Misc::localDictionariesPath()), withGitHubLineBreaks); // add note folder information output += QStringLiteral("\n## Note folders\n\n"); - output += prepareDebugInformationLine( - QStringLiteral("currentNoteFolderId"), - QString::number(NoteFolder::currentNoteFolderId()), - withGitHubLineBreaks); + output += prepareDebugInformationLine(QStringLiteral("currentNoteFolderId"), + QString::number(NoteFolder::currentNoteFolderId()), + withGitHubLineBreaks); const QList<NoteFolder> ¬eFolders = NoteFolder::fetchAll(); if (noteFolders.count() > 0) { Q_FOREACH (const NoteFolder ¬eFolder, noteFolders) { - output += - QStringLiteral("\n### Note folder `") % noteFolder.getName() + - QStringLiteral("`\n\n"); + output += QStringLiteral("\n### Note folder `") % noteFolder.getName() + + QStringLiteral("`\n\n"); output += prepareDebugInformationLine( - QStringLiteral("id"), QString::number(noteFolder.getId()), + QStringLiteral("id"), QString::number(noteFolder.getId()), withGitHubLineBreaks); + output += prepareDebugInformationLine( + QStringLiteral("isCurrent"), + noteFolder.isCurrent() ? QStringLiteral("yes") : QStringLiteral("no"), withGitHubLineBreaks); - output += prepareDebugInformationLine(QStringLiteral("isCurrent"), - noteFolder.isCurrent() - ? QStringLiteral("yes") - : QStringLiteral("no"), + output += prepareDebugInformationLine(QStringLiteral("activeTagId"), + QString::number(noteFolder.getActiveTagId()), withGitHubLineBreaks); output += prepareDebugInformationLine( - QStringLiteral("activeTagId"), - QString::number(noteFolder.getActiveTagId()), - withGitHubLineBreaks); - output += prepareDebugInformationLine( - QStringLiteral("localPath"), - QDir::toNativeSeparators(noteFolder.getLocalPath()), + QStringLiteral("localPath"), QDir::toNativeSeparators(noteFolder.getLocalPath()), withGitHubLineBreaks); output += prepareDebugInformationLine(QStringLiteral("remotePath"), - noteFolder.getRemotePath(), - withGitHubLineBreaks); + noteFolder.getRemotePath(), withGitHubLineBreaks); output += prepareDebugInformationLine( QStringLiteral("cloudConnectionId"), - QString::number(noteFolder.getCloudConnectionId()), - withGitHubLineBreaks); + QString::number(noteFolder.getCloudConnectionId()), withGitHubLineBreaks); output += prepareDebugInformationLine( QStringLiteral("isShowSubfolders"), - noteFolder.isShowSubfolders() ? QStringLiteral("yes") - : QStringLiteral("no"), + noteFolder.isShowSubfolders() ? QStringLiteral("yes") : QStringLiteral("no"), withGitHubLineBreaks); - output += prepareDebugInformationLine(QStringLiteral("isUseGit"), - noteFolder.isUseGit() - ? QStringLiteral("yes") - : QStringLiteral("no"), - withGitHubLineBreaks); - output += prepareDebugInformationLine(QStringLiteral("allowDifferentNoteFileName"), - noteFolder.settingsValue(QStringLiteral("allowDifferentNoteFileName")) - .toBool() - ? QStringLiteral("yes") - : QStringLiteral("no"), - withGitHubLineBreaks); output += prepareDebugInformationLine( - QStringLiteral("activeNoteSubFolder name"), - noteFolder.getActiveNoteSubFolder().getName(), + QStringLiteral("isUseGit"), + noteFolder.isUseGit() ? QStringLiteral("yes") : QStringLiteral("no"), withGitHubLineBreaks); + output += prepareDebugInformationLine( + QStringLiteral("allowDifferentNoteFileName"), + noteFolder.settingsValue(QStringLiteral("allowDifferentNoteFileName")).toBool() + ? QStringLiteral("yes") + : QStringLiteral("no"), + withGitHubLineBreaks); + output += prepareDebugInformationLine(QStringLiteral("activeNoteSubFolder name"), + noteFolder.getActiveNoteSubFolder().getName(), + withGitHubLineBreaks); output += prepareDebugInformationLine( QStringLiteral("database file"), QDir::toNativeSeparators(noteFolder.getLocalPath() + @@ -1852,26 +1725,20 @@ QString Utils::Misc::generateDebugInformation(bool withGitHubLineBreaks) { output += QStringLiteral("\n## Cloud connections\n"); Q_FOREACH (CloudConnection cloudConnection, CloudConnection::fetchAll()) { - output += QStringLiteral("\n### Cloud connection `") % - cloudConnection.getName() + + output += QStringLiteral("\n### Cloud connection `") % cloudConnection.getName() + QStringLiteral("`\n\n"); output += prepareDebugInformationLine( - QStringLiteral("id"), QString::number(cloudConnection.getId()), + QStringLiteral("id"), QString::number(cloudConnection.getId()), withGitHubLineBreaks); + output += prepareDebugInformationLine( + QStringLiteral("isCurrent"), + cloudConnection.isCurrent() ? QStringLiteral("yes") : QStringLiteral("no"), withGitHubLineBreaks); - output += prepareDebugInformationLine(QStringLiteral("isCurrent"), - cloudConnection.isCurrent() - ? QStringLiteral("yes") - : QStringLiteral("no"), - withGitHubLineBreaks); output += prepareDebugInformationLine(QStringLiteral("serverUrl"), - cloudConnection.getServerUrl(), - withGitHubLineBreaks); + cloudConnection.getServerUrl(), withGitHubLineBreaks); output += prepareDebugInformationLine(QStringLiteral("username"), - cloudConnection.getUsername(), - withGitHubLineBreaks); + cloudConnection.getUsername(), withGitHubLineBreaks); output += prepareDebugInformationLine(QStringLiteral("accountId"), - cloudConnection.getAccountId(), - withGitHubLineBreaks); + cloudConnection.getAccountId(), withGitHubLineBreaks); } // add script information @@ -1880,30 +1747,24 @@ QString Utils::Misc::generateDebugInformation(bool withGitHubLineBreaks) { QList<Script> scripts = Script::fetchAll(true); if (noteFolders.count() > 0) { Q_FOREACH (Script script, scripts) { - output += QStringLiteral("\n### Script `") % script.getName() + - QStringLiteral("`\n\n"); + output += QStringLiteral("\n### Script `") % script.getName() + QStringLiteral("`\n\n"); output += prepareDebugInformationLine( - QStringLiteral("id"), QString::number(script.getId()), - withGitHubLineBreaks); - output += prepareDebugInformationLine( - QStringLiteral("path"), - QDir::toNativeSeparators(script.getScriptPath()), - withGitHubLineBreaks); - output += prepareDebugInformationLine( - QStringLiteral("variablesJson"), - script.getSettingsVariablesJson(), withGitHubLineBreaks); + QStringLiteral("id"), QString::number(script.getId()), withGitHubLineBreaks); + output += prepareDebugInformationLine(QStringLiteral("path"), + QDir::toNativeSeparators(script.getScriptPath()), + withGitHubLineBreaks); + output += prepareDebugInformationLine(QStringLiteral("variablesJson"), + script.getSettingsVariablesJson(), + withGitHubLineBreaks); if (script.isScriptFromRepository()) { ScriptInfoJson infoJson = script.getScriptInfoJson(); - output += prepareDebugInformationLine( - QStringLiteral("identifier"), script.getIdentifier(), - withGitHubLineBreaks); - output += prepareDebugInformationLine(QStringLiteral("version"), - infoJson.version, + output += prepareDebugInformationLine(QStringLiteral("identifier"), + script.getIdentifier(), withGitHubLineBreaks); + output += prepareDebugInformationLine(QStringLiteral("version"), infoJson.version, withGitHubLineBreaks); - output += prepareDebugInformationLine( - QStringLiteral("minAppVersion"), infoJson.minAppVersion, - withGitHubLineBreaks); + output += prepareDebugInformationLine(QStringLiteral("minAppVersion"), + infoJson.minAppVersion, withGitHubLineBreaks); } } } else { @@ -1916,10 +1777,10 @@ QString Utils::Misc::generateDebugInformation(bool withGitHubLineBreaks) { // hide values of these keys QStringList keyHiddenList = {"cryptoKey", "ownCloud/todoCalendarCalDAVPassword", - "PiwikClientId", "networking/proxyPassword", + "PiwikClientId", + "networking/proxyPassword", "webSocketServerService/token", - "webAppClientService/token" - }; + "webAppClientService/token"}; // under OS X we have to ignore some keys #ifdef Q_OS_MAC @@ -1958,33 +1819,30 @@ QString Utils::Misc::generateDebugInformation(bool withGitHubLineBreaks) { // hide values of certain keys if (keyHiddenList.contains(key)) { - output += prepareDebugInformationLine( - key, QStringLiteral("<hidden>"), withGitHubLineBreaks, - value.typeName()); + output += prepareDebugInformationLine(key, QStringLiteral("<hidden>"), + withGitHubLineBreaks, value.typeName()); } else { switch (value.type()) { case QVariant::StringList: output += prepareDebugInformationLine( - key, value.toStringList().join(QStringLiteral(", ")), - withGitHubLineBreaks, value.typeName()); + key, value.toStringList().join(QStringLiteral(", ")), withGitHubLineBreaks, + value.typeName()); break; case QVariant::List: - output += prepareDebugInformationLine( - key, - QStringLiteral("<variant list with %1 item(s)>") - .arg(value.toList().count()), - withGitHubLineBreaks, value.typeName()); + output += + prepareDebugInformationLine(key, + QStringLiteral("<variant list with %1 item(s)>") + .arg(value.toList().count()), + withGitHubLineBreaks, value.typeName()); break; case QVariant::ByteArray: case QVariant::UserType: - output += prepareDebugInformationLine( - key, QStringLiteral("<binary data>"), - withGitHubLineBreaks, value.typeName()); + output += prepareDebugInformationLine(key, QStringLiteral("<binary data>"), + withGitHubLineBreaks, value.typeName()); break; default: output += prepareDebugInformationLine(key, value.toString(), - withGitHubLineBreaks, - value.typeName()); + withGitHubLineBreaks, value.typeName()); } } } @@ -2011,8 +1869,7 @@ QString Utils::Misc::generateDebugInformation(bool withGitHubLineBreaks) { * @param regExpList * @return */ -bool Utils::Misc::regExpInListMatches(const QString &text, - const QStringList ®ExpList) { +bool Utils::Misc::regExpInListMatches(const QString &text, const QStringList ®ExpList) { for (const QString ®Exp : regExpList) { const QString trimmed = regExp.trimmed(); if (trimmed.isEmpty()) { @@ -2032,8 +1889,8 @@ bool Utils::Misc::regExpInListMatches(const QString &text, * * @param html */ -void Utils::Misc::transformNextcloudPreviewImages( - QString &html, int maxImageWidth, ExternalImageHash *externalImageHash) { +void Utils::Misc::transformNextcloudPreviewImages(QString &html, int maxImageWidth, + ExternalImageHash *externalImageHash) { OwnCloudService *ownCloud = OwnCloudService::instance(); static const QRegularExpression re( @@ -2054,16 +1911,15 @@ void Utils::Misc::transformNextcloudPreviewImages( inlineImageTag = hashItem.imageTag; imageWidth = hashItem.imageWidth; } else { - inlineImageTag = ownCloud->nextcloudPreviewImageTagToInlineImageTag( - imageTag, imageWidth); + inlineImageTag = + ownCloud->nextcloudPreviewImageTagToInlineImageTag(imageTag, imageWidth); hashItem.imageTag = inlineImageTag; hashItem.imageWidth = imageWidth; externalImageHash->insert(imageTag, hashItem); } imageWidth = std::min(maxImageWidth, imageWidth); - inlineImageTag.replace( - "/>", QString("width=\"%1\"/>").arg(QString::number(imageWidth))); + inlineImageTag.replace("/>", QString("width=\"%1\"/>").arg(QString::number(imageWidth))); html.replace(imageTag, inlineImageTag); } @@ -2074,13 +1930,12 @@ void Utils::Misc::transformNextcloudPreviewImages( * * @param html */ -void Utils::Misc::transformRemotePreviewImages( - QString &html, int maxImageWidth, ExternalImageHash *externalImageHash) { - static const QRegularExpression re( - QStringLiteral(R"(<img src=\"(https?:\/\/.+)\".*\/?>)"), - QRegularExpression::CaseInsensitiveOption | - QRegularExpression::MultilineOption | - QRegularExpression::InvertedGreedinessOption); +void Utils::Misc::transformRemotePreviewImages(QString &html, int maxImageWidth, + ExternalImageHash *externalImageHash) { + static const QRegularExpression re(QStringLiteral(R"(<img src=\"(https?:\/\/.+)\".*\/?>)"), + QRegularExpression::CaseInsensitiveOption | + QRegularExpression::MultilineOption | + QRegularExpression::InvertedGreedinessOption); QRegularExpressionMatchIterator i = re.globalMatch(html); while (i.hasNext()) { @@ -2095,16 +1950,14 @@ void Utils::Misc::transformRemotePreviewImages( inlineImageTag = hashItem.imageTag; imageWidth = hashItem.imageWidth; } else { - inlineImageTag = - remotePreviewImageTagToInlineImageTag(imageTag, imageWidth); + inlineImageTag = remotePreviewImageTagToInlineImageTag(imageTag, imageWidth); hashItem.imageTag = inlineImageTag; hashItem.imageWidth = imageWidth; externalImageHash->insert(imageTag, hashItem); } imageWidth = std::min(maxImageWidth, imageWidth); - inlineImageTag.replace( - ">", QString("width=\"%1\">").arg(QString::number(imageWidth))); + inlineImageTag.replace(">", QString("width=\"%1\">").arg(QString::number(imageWidth))); html.replace(imageTag, inlineImageTag); } } @@ -2116,13 +1969,12 @@ void Utils::Misc::transformRemotePreviewImages( * @param imageSuffix * @return */ -QString Utils::Misc::remotePreviewImageTagToInlineImageTag(QString imageTag, - int &imageWidth) { +QString Utils::Misc::remotePreviewImageTagToInlineImageTag(QString imageTag, int &imageWidth) { imageTag.replace(QStringLiteral("&"), QStringLiteral("&")); - static const QRegularExpression re(QStringLiteral(R"(<img src=\"(https?:\/\/.+)\")"), - QRegularExpression::CaseInsensitiveOption | - QRegularExpression::InvertedGreedinessOption); + static const QRegularExpression re( + QStringLiteral(R"(<img src=\"(https?:\/\/.+)\")"), + QRegularExpression::CaseInsensitiveOption | QRegularExpression::InvertedGreedinessOption); QRegularExpressionMatch match = re.match(imageTag); if (!match.hasMatch()) { @@ -2138,16 +1990,15 @@ QString Utils::Misc::remotePreviewImageTagToInlineImageTag(QString imageTag, // for now we do no caching, because we don't know when to invalidate the // cache - const QString replace = QStringLiteral("data:") % type.name() % - QStringLiteral(";base64,") % data.toBase64(); + const QString replace = + QStringLiteral("data:") % type.name() % QStringLiteral(";base64,") % data.toBase64(); return imageTag.replace(url, replace); } QString Utils::Misc::createUuidString() { const QUuid uuid = QUuid::createUuid(); QString uuidString = uuid.toString(); - uuidString.replace(QStringLiteral("{"), QString()) - .replace(QStringLiteral("}"), QString()); + uuidString.replace(QStringLiteral("{"), QString()).replace(QStringLiteral("}"), QString()); return uuidString; } @@ -2195,16 +2046,15 @@ bool Utils::Misc::isSameFile(const QString &path1, const QString &path2) { } QString Utils::Misc::generateRandomString(int length) { - const QString possibleCharacters(QStringLiteral( - "ABCDEFGHKLMNPQRSTUVWXYZabcdefghkmnpqrstuvwxyz23456789")); + const QString possibleCharacters( + QStringLiteral("ABCDEFGHKLMNPQRSTUVWXYZabcdefghkmnpqrstuvwxyz23456789")); QString randomString; for (int i = 0; i < length; ++i) { #if QT_VERSION < QT_VERSION_CHECK(5, 10, 0) const int index = qrand() % possibleCharacters.length(); #else - const quint32 index = QRandomGenerator::global()->generate() % - possibleCharacters.length(); + const quint32 index = QRandomGenerator::global()->generate() % possibleCharacters.length(); #endif QChar nextChar = possibleCharacters.at(index); randomString.append(nextChar); @@ -2213,13 +2063,12 @@ QString Utils::Misc::generateRandomString(int length) { return randomString; } -QString Utils::Misc::makeFileNameRandom(const QString &fileName, - const QString &overrideSuffix) { +QString Utils::Misc::makeFileNameRandom(const QString &fileName, const QString &overrideSuffix) { const QFileInfo fileInfo(fileName); - QString baseName = fileInfo.baseName().remove( - QRegularExpression(QStringLiteral(R"([^\w\d\-_ ])"))).replace( - QChar(' '), QChar('-')); + QString baseName = fileInfo.baseName() + .remove(QRegularExpression(QStringLiteral(R"([^\w\d\-_ ])"))) + .replace(QChar(' '), QChar('-')); baseName.truncate(32); // find a more random name for the file @@ -2237,8 +2086,7 @@ QString Utils::Misc::makeFileNameRandom(const QString &fileName, * Returns a non-existing filename (like "my-image.jpg") in directoryPath * If the filename is already taken a number will be appended (like "my-image-1.jpg") */ -QString Utils::Misc::findAvailableFileName(const QString &filePath, - const QString &directoryPath, +QString Utils::Misc::findAvailableFileName(const QString &filePath, const QString &directoryPath, const QString &overrideSuffix) { const QFileInfo fileInfo(filePath); QString baseName = fileInfo.baseName(); @@ -2253,8 +2101,7 @@ QString Utils::Misc::findAvailableFileName(const QString &filePath, // check if file with this filename already exists while (file.exists()) { // find new filename for the file - newBaseName = baseName + QStringLiteral("-") + - QString::number(++nameCount); + newBaseName = baseName + QStringLiteral("-") + QString::number(++nameCount); newFileName = newBaseName + QStringLiteral(".") + newSuffix; newFilePath = directoryPath + QDir::separator() + newFileName; file.setFileName(newFilePath); @@ -2282,10 +2129,8 @@ QString Utils::Misc::fileNameForPath(const QString &filePath) { /** * Checks if a filename exists like for findAvailableFileName */ -bool Utils::Misc::fileNameExists(const QString &fileName, - const QString &directoryPath) { - QString filePath = directoryPath + QDir::separator() + - fileNameForPath(fileName); +bool Utils::Misc::fileNameExists(const QString &fileName, const QString &directoryPath) { + QString filePath = directoryPath + QDir::separator() + fileNameForPath(fileName); QFile file(filePath); return file.exists(); @@ -2297,7 +2142,7 @@ bool Utils::Misc::fileNameExists(const QString &fileName, * @param str * @return */ -QString Utils::Misc::rstrip(const QString& str) { +QString Utils::Misc::rstrip(const QString &str) { int n = str.size() - 1; for (; n >= 0; --n) { @@ -2314,17 +2159,15 @@ QString Utils::Misc::rstrip(const QString& str) { * * @return bool */ -bool Utils::Misc::fileExists(const QString& path) { +bool Utils::Misc::fileExists(const QString &path) { const QFile file(path); const QFileInfo fileInfo(file); return file.exists() && fileInfo.isFile() && fileInfo.isReadable(); } -static QString removeReducedCJKAccMark(const QString &label, int pos) -{ - if (pos > 0 && pos + 1 < label.length() - && label[pos - 1] == QLatin1Char('(') && label[pos + 1] == QLatin1Char(')') - && label[pos].isLetterOrNumber()) { +static QString removeReducedCJKAccMark(const QString &label, int pos) { + if (pos > 0 && pos + 1 < label.length() && label[pos - 1] == QLatin1Char('(') && + label[pos + 1] == QLatin1Char(')') && label[pos].isLetterOrNumber()) { // Check if at start or end, ignoring non-alphanumerics. int len = label.length(); int p1 = pos - 2; @@ -2352,8 +2195,7 @@ static QString removeReducedCJKAccMark(const QString &label, int pos) * * Taken from KDE's Ki18n library */ -QString Utils::Misc::removeAcceleratorMarker(const QString &label_) -{ +QString Utils::Misc::removeAcceleratorMarker(const QString &label_) { QString label = label_; int p = 0; @@ -2387,7 +2229,7 @@ QString Utils::Misc::removeAcceleratorMarker(const QString &label_) if (!accmarkRemoved) { bool hasCJK = false; for (const QChar c : asConst(label)) { - if (c.unicode() >= 0x2e00) { // rough, but should be sufficient + if (c.unicode() >= 0x2e00) { // rough, but should be sufficient hasCJK = true; break; } @@ -2436,18 +2278,14 @@ void Utils::Misc::switchToDarkOrLightMode(bool darkMode) { settings.setValue("darkModeColors", darkMode); settings.setValue("darkModeIconTheme", darkMode); settings.setValue("darkModeTrayIcon", darkMode); - settings.setValue("Editor/CurrentSchemaKey", darkMode ? - "EditorColorSchema-cdbf28fc-1ddc-4d13-bb21-6a4043316a2f" : - "EditorColorSchema-6033d61b-cb96-46d5-a3a8-20d5172017eb"); + settings.setValue("Editor/CurrentSchemaKey", + darkMode ? "EditorColorSchema-cdbf28fc-1ddc-4d13-bb21-6a4043316a2f" + : "EditorColorSchema-6033d61b-cb96-46d5-a3a8-20d5172017eb"); } -void Utils::Misc::switchToDarkMode() { - switchToDarkOrLightMode(true); -} +void Utils::Misc::switchToDarkMode() { switchToDarkOrLightMode(true); } -void Utils::Misc::switchToLightMode() { - switchToDarkOrLightMode(false); -} +void Utils::Misc::switchToLightMode() { switchToDarkOrLightMode(false); } void Utils::Misc::unescapeEvernoteImportText(QString &content) { content.replace(QStringLiteral("\\\""), QStringLiteral("\"")); @@ -2476,14 +2314,12 @@ void Utils::Misc::transformEvernoteImportText(QString &content, bool withCleanup QStringLiteral("\n```\n\\1\n```\n")); content.replace( QRegularExpression( - QStringLiteral( - R"(<div style="-en-codeblock:\s*true;.+?"><div>(.+?)<\/div><\/div>)"), + QStringLiteral(R"(<div style="-en-codeblock:\s*true;.+?"><div>(.+?)<\/div><\/div>)"), QRegularExpression::MultilineOption), QStringLiteral("\n```\n\\1\n```\n")); // add a linebreak instead of div-containers - content.replace(QRegularExpression(QStringLiteral("<\\/div>")), - QStringLiteral("\n")); + content.replace(QRegularExpression(QStringLiteral("<\\/div>")), QStringLiteral("\n")); // preserve hyperlinks content.replace("<a ", "<a "); @@ -2505,13 +2341,11 @@ void Utils::Misc::cleanupEvernoteImportText(QString &content) { content.remove(QRegularExpression(QStringLiteral("<.+?>"))); // remove multiple \n - content.replace(QRegularExpression(QStringLiteral("\n\n+")), - QLatin1String("\n\n")); - content.replace(QRegularExpression(QStringLiteral("\n\n\\s+")), - QLatin1String("\n\n")); + content.replace(QRegularExpression(QStringLiteral("\n\n+")), QLatin1String("\n\n")); + content.replace(QRegularExpression(QStringLiteral("\n\n\\s+")), QLatin1String("\n\n")); } -QString Utils::Misc::testEvernoteImportText(const QString& data) { +QString Utils::Misc::testEvernoteImportText(const QString &data) { #if (QT_VERSION < QT_VERSION_CHECK(6, 0, 0)) QXmlQuery query; query.setFocus(data); @@ -2558,16 +2392,14 @@ void Utils::Misc::logToFileIfAllowed(QtMsgType msgType, const QString &msg) { QFile logFile(Utils::Misc::logFilePath()); - if (logFile.open(QIODevice::WriteOnly | QIODevice::Text | - QIODevice::Append)) { + if (logFile.open(QIODevice::WriteOnly | QIODevice::Text | QIODevice::Append)) { QTextStream out(&logFile); QDateTime dateTime = QDateTime::currentDateTime(); QString typeStr = logMsgTypeText(msgType); - QString text = - QStringLiteral("[%1] [%2]: %3\n") - .arg(dateTime.toString(QStringLiteral("MMM dd hh:mm:ss")) - .remove(QStringLiteral(".")), - typeStr, msg); + QString text = QStringLiteral("[%1] [%2]: %3\n") + .arg(dateTime.toString(QStringLiteral("MMM dd hh:mm:ss")) + .remove(QStringLiteral(".")), + typeStr, msg); out << text; logFile.close(); } @@ -2607,14 +2439,14 @@ QString Utils::Misc::logMsgTypeText(QtMsgType logType) { } /** - * Borrowed from https://nasauber.de/blog/2019/levenshtein-distance-and-longest-common-subsequence-in-qt/ + * Borrowed from + * https://nasauber.de/blog/2019/levenshtein-distance-and-longest-common-subsequence-in-qt/ * * @param source * @param target * @return */ -int levenshteinDistance(const QString &source, const QString &target) -{ +int levenshteinDistance(const QString &source, const QString &target) { if (source == target) { return 0; } @@ -2645,11 +2477,9 @@ int levenshteinDistance(const QString &source, const QString &target) for (int i = 0; i < sourceCount; i++) { column[0] = i + 1; for (int j = 0; j < targetCount; j++) { - column[j + 1] = std::min<int>({ - 1 + column.at(j), - 1 + previousColumn.at(1 + j), - previousColumn.at(j) + ((source.at(i) == target.at(j)) ? 0 : 1) - }); + column[j + 1] = + std::min<int>({1 + column.at(j), 1 + previousColumn.at(1 + j), + previousColumn.at(j) + ((source.at(i) == target.at(j)) ? 0 : 1)}); } column.swap(previousColumn); } @@ -2682,9 +2512,9 @@ bool Utils::Misc::isSimilar(const QString &str1, const QString &str2, int thresh // Use levenshtein for not too large notes if the middle part of the strings is different // Disabled, because it takes far too long! -// if ((str1.length() < 5000) && (levenshteinDistance(str1, str2) <= threshold)) { -// return true; -// } + // if ((str1.length() < 5000) && (levenshteinDistance(str1, str2) <= threshold)) { + // return true; + // } if (str1.length() != str2.length()) { return false; @@ -2730,7 +2560,8 @@ QString Utils::Misc::getBaseUrlFromUrlString(const QString &urlString, bool with * Attempts to transform links to the same webpage to absolute links with url * So for an url: https://www.example.com/path/to/file.html * This: <a href="/absolute.html">Link</a> <a href="relative.html">Link</a> - * Would get: <a href="https://www.example.com/absolute.html">Link</a> <a href="https://www.example.com/path/to/relative.html">Link</a> + * Would get: <a href="https://www.example.com/absolute.html">Link</a> <a + * href="https://www.example.com/path/to/relative.html">Link</a> * * @param html * @param url @@ -2749,8 +2580,7 @@ QString Utils::Misc::createAbsolutePathsInHtml(const QString &html, const QStrin const QString attribute = match.captured(1); const QString value = match.captured(2); const QString replaceUrl = value.startsWith('/') ? baseUrl : baseUrlWithBasePath; - const QString newValue = QStringLiteral("%1=\"%2\"") - .arg(attribute, replaceUrl + value); + const QString newValue = QStringLiteral("%1=\"%2\"").arg(attribute, replaceUrl + value); result.replace(match.captured(0), newValue); } @@ -2759,5 +2589,7 @@ QString Utils::Misc::createAbsolutePathsInHtml(const QString &html, const QStrin } int Utils::Misc::getPreviewRefreshDebounceTime() { - return QSettings().value(QStringLiteral("MainWindow/noteTextView.refreshDebounceTime"), 600).toInt(); + return QSettings() + .value(QStringLiteral("MainWindow/noteTextView.refreshDebounceTime"), 600) + .toInt(); } diff --git a/src/utils/misc.h b/src/utils/misc.h index 8b894c4fc..c5b870d01 100644 --- a/src/utils/misc.h +++ b/src/utils/misc.h @@ -14,11 +14,11 @@ #pragma once +#include <QHash> +#include <QMetaType> #include <QString> #include <QStringList> #include <QVector> -#include <QHash> -#include <QMetaType> struct TerminalCmd; class QFile; @@ -71,8 +71,7 @@ bool startDetachedProcess(const QString &executablePath, bool openFilesWithApplication(const QString &executablePath, const QStringList &files = QStringList(), QString workingDirectory = QLatin1String("")); -QString shorten(QString text, int length, - const QString &sequence = QStringLiteral("...")); +QString shorten(QString text, int length, const QString &sequence = QStringLiteral("...")); QString cycleTextCase(const QString &text); QString toSentenceCase(const QString &text); QString toStartCase(const QString &text); @@ -82,13 +81,11 @@ void waitMsecs(int msecs); QString portableDataPath(); bool isInPortableMode(); bool isAppImage(); -QString prependPortableDataPathIfNeeded(QString path, - bool ifNotEmptyOnly = false); +QString prependPortableDataPathIfNeeded(QString path, bool ifNotEmptyOnly = false); QString makePathRelativeToPortableDataPathIfNeeded(QString path); QString htmlToMarkdown(QString text); QString parseTaskList(const QString &html, bool clickable); -QByteArray startSynchronousProcess(const QString &executablePath, - const QStringList ¶meters, +QByteArray startSynchronousProcess(const QString &executablePath, const QStringList ¶meters, const QByteArray &data = QByteArray(), const QString &workingDirectory = ""); bool startSynchronousResultProcess(TerminalCmd &cmd); @@ -135,20 +132,16 @@ void transformNextcloudPreviewImages(QString &html, int maxImageWidth, ExternalImageHash *externalImageHash); void transformRemotePreviewImages(QString &html, int maxImageWidth, ExternalImageHash *externalImageHash); -QString remotePreviewImageTagToInlineImageTag(QString imageTag, - int &imageWidth); +QString remotePreviewImageTagToInlineImageTag(QString imageTag, int &imageWidth); QString createUuidString(); QString localDictionariesPath(); QByteArray generateFileSha1Signature(const QString &path); bool isSameFile(const QString &path1, const QString &path2); QString generateRandomString(int length = 8); -QString makeFileNameRandom(const QString &fileName, - const QString &overrideSuffix = ""); -QString findAvailableFileName(const QString &filePath, - const QString &directoryPath, +QString makeFileNameRandom(const QString &fileName, const QString &overrideSuffix = ""); +QString findAvailableFileName(const QString &filePath, const QString &directoryPath, const QString &overrideSuffix = ""); -bool fileNameExists(const QString &fileName, - const QString &directoryPath); +bool fileNameExists(const QString &fileName, const QString &directoryPath); QString fileNameForPath(const QString &filePath); QString rstrip(const QString &str); bool isPreviewUseEditorStyles(); @@ -165,7 +158,7 @@ void switchToLightMode(); void unescapeEvernoteImportText(QString &content); void transformEvernoteImportText(QString &content, bool withCleanup = false); void cleanupEvernoteImportText(QString &content); -QString testEvernoteImportText(const QString& data); +QString testEvernoteImportText(const QString &data); void logToFileIfAllowed(QtMsgType msgType, const QString &msg); QString logMsgTypeText(QtMsgType logType); bool isSimilar(const QString &str1, const QString &str2, int threshold = 3); diff --git a/src/utils/schema.cpp b/src/utils/schema.cpp index 6f1bfd827..e216f67ce 100644 --- a/src/utils/schema.cpp +++ b/src/utils/schema.cpp @@ -35,9 +35,7 @@ Utils::Schema::Settings::Settings() _defaultFontSet = false; _defaultSchemaKeysList = - _defaultSchemaSettings - .value(QStringLiteral("Editor/DefaultColorSchemes")) - .toStringList(); + _defaultSchemaSettings.value(QStringLiteral("Editor/DefaultColorSchemes")).toStringList(); // Determine the keys for a given schema _defaultSchemaSubkeylists.reserve(_defaultSchemaKeysList.size()); @@ -79,10 +77,9 @@ const QSettings& Utils::Schema::Settings::defaultSchemaSettings() const { QString Utils::Schema::Settings::currentSchemaKey() const { QSettings settings; return settings - .value(QStringLiteral("Editor/CurrentSchemaKey"), - _defaultSchemaKeysList.length() > 0 - ? _defaultSchemaKeysList[0] - : QStringLiteral("DefaultSchema")) + .value(QStringLiteral("Editor/CurrentSchemaKey"), _defaultSchemaKeysList.length() > 0 + ? _defaultSchemaKeysList[0] + : QStringLiteral("DefaultSchema")) .toString(); } @@ -101,8 +98,7 @@ bool Utils::Schema::Settings::currentSchemaIsDefault() const { * @param schema * @return */ -QStringList Utils::Schema::Settings::getSchemaKeys( - const QString& schema) const { +QStringList Utils::Schema::Settings::getSchemaKeys(const QString& schema) const { if (_defaultSchemaSubkeys.contains(schema)) { return _defaultSchemaSubkeylists[_defaultSchemaSubkeys[schema]]; } else { @@ -120,8 +116,7 @@ QStringList Utils::Schema::Settings::getSchemaKeys( * @param defaultValue * @return */ -QVariant Utils::Schema::Settings::getSchemaValue(const QString& key, - const QVariant& defaultValue, +QVariant Utils::Schema::Settings::getSchemaValue(const QString& key, const QVariant& defaultValue, QString schemaKey) const { const bool schemaNotSet = schemaKey.isEmpty(); @@ -133,20 +128,15 @@ QVariant Utils::Schema::Settings::getSchemaValue(const QString& key, QVariant value = isDefaultSchema - ? _defaultSchemaSettings.value( - schemaKey + QStringLiteral("/") + key, defaultValue) - : QSettings().value(schemaKey + QStringLiteral("/") + key, - defaultValue); + ? _defaultSchemaSettings.value(schemaKey + QStringLiteral("/") + key, defaultValue) + : QSettings().value(schemaKey + QStringLiteral("/") + key, defaultValue); if (!value.isValid() && schemaNotSet) { QString fallbackSchemaKey = isDefaultSchema - ? _defaultSchemaSettings - .value(schemaKey + QStringLiteral("/FallbackSchema")) + ? _defaultSchemaSettings.value(schemaKey + QStringLiteral("/FallbackSchema")) .toString() - : QSettings() - .value(schemaKey + QStringLiteral("/FallbackSchema")) - .toString(); + : QSettings().value(schemaKey + QStringLiteral("/FallbackSchema")).toString(); if (!fallbackSchemaKey.isEmpty()) { value = getSchemaValue(key, defaultValue, fallbackSchemaKey); @@ -175,17 +165,13 @@ QString Utils::Schema::textSettingsKey(const QString& key, int index) { */ QFont Utils::Schema::Settings::getFont(int index) const { // get the foreground color - bool enabled = - getSchemaValue( - textSettingsKey(QStringLiteral("FontEnabled"), index)) - .toBool(); + bool enabled = getSchemaValue(textSettingsKey(QStringLiteral("FontEnabled"), index)).toBool(); QFont font = getEditorFont(index); // if the font is enabled try to fetch it if (enabled) { - QFont overrideFont = getSchemaValue( - textSettingsKey(QStringLiteral("Font"), index)) - .value<QFont>(); + QFont overrideFont = + getSchemaValue(textSettingsKey(QStringLiteral("Font"), index)).value<QFont>(); font.setFamily(overrideFont.family()); } @@ -201,15 +187,12 @@ QFont Utils::Schema::Settings::getFont(int index) const { QColor Utils::Schema::Settings::getForegroundColor(int index) const { // get the foreground color bool enabled = - getSchemaValue( - textSettingsKey(QStringLiteral("ForegroundColorEnabled"), index)) - .toBool(); + getSchemaValue(textSettingsKey(QStringLiteral("ForegroundColorEnabled"), index)).toBool(); QColor color; // if the foreground color is enabled try to fetch it if (enabled) { - color = getSchemaValue( - textSettingsKey(QStringLiteral("ForegroundColor"), index)) + color = getSchemaValue(textSettingsKey(QStringLiteral("ForegroundColor"), index)) .value<QColor>(); } @@ -241,15 +224,12 @@ QColor Utils::Schema::Settings::getForegroundColor(int index) const { QColor Utils::Schema::Settings::getBackgroundColor(int index) const { // get the foreground color bool enabled = - getSchemaValue( - textSettingsKey(QStringLiteral("BackgroundColorEnabled"), index)) - .toBool(); + getSchemaValue(textSettingsKey(QStringLiteral("BackgroundColorEnabled"), index)).toBool(); QColor color; // if the foreground color is enabled try to fetch it if (enabled) { - color = getSchemaValue( - textSettingsKey(QStringLiteral("BackgroundColor"), index)) + color = getSchemaValue(textSettingsKey(QStringLiteral("BackgroundColor"), index)) .value<QColor>(); } @@ -272,9 +252,8 @@ QColor Utils::Schema::Settings::getBackgroundColor(int index) const { * @param format * @param index */ -void Utils::Schema::Settings::setFormatStyle( - MarkdownHighlighter::HighlighterState index, - QTextCharFormat& format) const { +void Utils::Schema::Settings::setFormatStyle(MarkdownHighlighter::HighlighterState index, + QTextCharFormat& format) const { // get the correct font QFont font = getFont(index); @@ -296,32 +275,26 @@ void Utils::Schema::Settings::setFormatStyle( format.setForeground(QBrush(getForegroundColor(index))); bool backgroundColorEnabled = - getSchemaValue( - textSettingsKey(QStringLiteral("BackgroundColorEnabled"), index)) - .toBool(); + getSchemaValue(textSettingsKey(QStringLiteral("BackgroundColorEnabled"), index)).toBool(); // set the background (color) only if the background color is enabled, // otherwise we get troubles with the background overwriting the foreground // of neighboring text (e.g. for italic text) - format.setBackground( - backgroundColorEnabled ? QBrush(getBackgroundColor(index)) : QBrush()); + format.setBackground(backgroundColorEnabled ? QBrush(getBackgroundColor(index)) : QBrush()); // set the bold state - format.setFontWeight(getSchemaValue(Utils::Schema::textSettingsKey( - QStringLiteral("Bold"), index)) - .toBool() - ? QFont::Bold - : QFont::Normal); + format.setFontWeight( + getSchemaValue(Utils::Schema::textSettingsKey(QStringLiteral("Bold"), index)).toBool() + ? QFont::Bold + : QFont::Normal); // set the italic state - format.setFontItalic(getSchemaValue(Utils::Schema::textSettingsKey( - QStringLiteral("Italic"), index)) - .toBool()); + format.setFontItalic( + getSchemaValue(Utils::Schema::textSettingsKey(QStringLiteral("Italic"), index)).toBool()); // set the underline state format.setFontUnderline( - getSchemaValue( - Utils::Schema::textSettingsKey(QStringLiteral("Underline"), index)) + getSchemaValue(Utils::Schema::textSettingsKey(QStringLiteral("Underline"), index)) .toBool()); } @@ -333,9 +306,7 @@ void Utils::Schema::Settings::setFormatStyle( */ void Utils::Schema::Settings::adaptFontSize(int index, QFont& font) const { int adaption = - getSchemaValue( - textSettingsKey(QStringLiteral("FontSizeAdaption"), index), 100) - .toInt(); + getSchemaValue(textSettingsKey(QStringLiteral("FontSizeAdaption"), index), 100).toInt(); double fontSize = round(font.pointSize() * adaption / 100); if (fontSize > 0) { @@ -354,9 +325,7 @@ QFont Utils::Schema::Settings::getEditorTextFont() const { _defaultFontSet = true; } QSettings settings; - QString fontString = - settings.value(QStringLiteral("MainWindow/noteTextEdit.font")) - .toString(); + QString fontString = settings.value(QStringLiteral("MainWindow/noteTextEdit.font")).toString(); QFont font(_defaultTextEditFont); if (!fontString.isEmpty()) { @@ -365,8 +334,7 @@ QFont Utils::Schema::Settings::getEditorTextFont() const { } else { // store the default settings fontString = _defaultTextEditFont.toString(); - settings.setValue(QStringLiteral("MainWindow/noteTextEdit.font"), - fontString); + settings.setValue(QStringLiteral("MainWindow/noteTextEdit.font"), fontString); } return font; @@ -385,8 +353,7 @@ QFont Utils::Schema::Settings::getEditorFixedFont() const { QSettings settings; QString fontString = - settings.value(QStringLiteral("MainWindow/noteTextEdit.code.font")) - .toString(); + settings.value(QStringLiteral("MainWindow/noteTextEdit.code.font")).toString(); QFont font(_defaultTextEditFont); if (!fontString.isEmpty()) { @@ -396,8 +363,7 @@ QFont Utils::Schema::Settings::getEditorFixedFont() const { font = QFontDatabase::systemFont(QFontDatabase::FixedFont); // store the default settings - settings.setValue(QStringLiteral("MainWindow/noteTextEdit.code.font"), - font.toString()); + settings.setValue(QStringLiteral("MainWindow/noteTextEdit.code.font"), font.toString()); } return font; @@ -409,16 +375,11 @@ QFont Utils::Schema::Settings::getEditorFixedFont() const { * @return */ QFont Utils::Schema::Settings::getEditorFont(int index) const { - if (index == MarkdownHighlighter::CodeBlock || - index == MarkdownHighlighter::InlineCodeBlock || - index == MarkdownHighlighter::CodeKeyWord || - index == MarkdownHighlighter::CodeType || - index == MarkdownHighlighter::CodeComment || - index == MarkdownHighlighter::CodeString || - index == MarkdownHighlighter::CodeNumLiteral || - index == MarkdownHighlighter::CodeBuiltIn || - index == MarkdownHighlighter::CodeOther || - index == MarkdownHighlighter::Table) { + if (index == MarkdownHighlighter::CodeBlock || index == MarkdownHighlighter::InlineCodeBlock || + index == MarkdownHighlighter::CodeKeyWord || index == MarkdownHighlighter::CodeType || + index == MarkdownHighlighter::CodeComment || index == MarkdownHighlighter::CodeString || + index == MarkdownHighlighter::CodeNumLiteral || index == MarkdownHighlighter::CodeBuiltIn || + index == MarkdownHighlighter::CodeOther || index == MarkdownHighlighter::Table) { return getEditorFixedFont(); } else { return getEditorTextFont(); @@ -427,68 +388,55 @@ QFont Utils::Schema::Settings::getEditorFont(int index) const { QString Utils::Schema::getSchemaStyles() { // reset background color of code blocks - QString schemaStyles = - QStringLiteral("code {background-color: transparent;}"); + QString schemaStyles = QStringLiteral("code {background-color: transparent;}"); - schemaStyles += encodeCssStyleForState(MarkdownHighlighter::NoState, - QStringLiteral("body")); - schemaStyles += - encodeCssStyleForState(MarkdownHighlighter::H1, QStringLiteral("h1")); - schemaStyles += - encodeCssStyleForState(MarkdownHighlighter::H2, QStringLiteral("h2")); - schemaStyles += - encodeCssStyleForState(MarkdownHighlighter::H3, QStringLiteral("h3")); - schemaStyles += - encodeCssStyleForState(MarkdownHighlighter::H4, QStringLiteral("h4")); - schemaStyles += - encodeCssStyleForState(MarkdownHighlighter::H5, QStringLiteral("h5")); - schemaStyles += - encodeCssStyleForState(MarkdownHighlighter::H6, QStringLiteral("h6")); - schemaStyles += - encodeCssStyleForState(MarkdownHighlighter::Link, QStringLiteral("a")); - schemaStyles += encodeCssStyleForState(MarkdownHighlighter::Bold, - QStringLiteral("b, strong")); - schemaStyles += encodeCssStyleForState(MarkdownHighlighter::Italic, - QStringLiteral("i, em")); - schemaStyles += - encodeCssStyleForState(MarkdownHighlighter::CodeBlock, - QStringLiteral("code, pre > code, pre")); - schemaStyles += - encodeCssStyleForState(MarkdownHighlighter::InlineCodeBlock, - QStringLiteral("p > code, li > code")); + schemaStyles += encodeCssStyleForState(MarkdownHighlighter::NoState, QStringLiteral("body")); + schemaStyles += encodeCssStyleForState(MarkdownHighlighter::H1, QStringLiteral("h1")); + schemaStyles += encodeCssStyleForState(MarkdownHighlighter::H2, QStringLiteral("h2")); + schemaStyles += encodeCssStyleForState(MarkdownHighlighter::H3, QStringLiteral("h3")); + schemaStyles += encodeCssStyleForState(MarkdownHighlighter::H4, QStringLiteral("h4")); + schemaStyles += encodeCssStyleForState(MarkdownHighlighter::H5, QStringLiteral("h5")); + schemaStyles += encodeCssStyleForState(MarkdownHighlighter::H6, QStringLiteral("h6")); + schemaStyles += encodeCssStyleForState(MarkdownHighlighter::Link, QStringLiteral("a")); + schemaStyles += encodeCssStyleForState(MarkdownHighlighter::Bold, QStringLiteral("b, strong")); + schemaStyles += encodeCssStyleForState(MarkdownHighlighter::Italic, QStringLiteral("i, em")); + schemaStyles += encodeCssStyleForState(MarkdownHighlighter::CodeBlock, + QStringLiteral("code, pre > code, pre")); + schemaStyles += encodeCssStyleForState(MarkdownHighlighter::InlineCodeBlock, + QStringLiteral("p > code, li > code")); // code block styles - schemaStyles += encodeCssStyleForState(MarkdownHighlighter::CodeKeyWord, - QStringLiteral(".code-keyword")); - schemaStyles += encodeCssStyleForState(MarkdownHighlighter::CodeString, - QStringLiteral(".code-string")); - schemaStyles += encodeCssStyleForState(MarkdownHighlighter::CodeComment, - QStringLiteral(".code-comment")); - schemaStyles += encodeCssStyleForState(MarkdownHighlighter::CodeType, - QStringLiteral(".code-type")); - schemaStyles += encodeCssStyleForState(MarkdownHighlighter::CodeOther, - QStringLiteral(".code-other")); + schemaStyles += + encodeCssStyleForState(MarkdownHighlighter::CodeKeyWord, QStringLiteral(".code-keyword")); + schemaStyles += + encodeCssStyleForState(MarkdownHighlighter::CodeString, QStringLiteral(".code-string")); + schemaStyles += + encodeCssStyleForState(MarkdownHighlighter::CodeComment, QStringLiteral(".code-comment")); + schemaStyles += + encodeCssStyleForState(MarkdownHighlighter::CodeType, QStringLiteral(".code-type")); + schemaStyles += + encodeCssStyleForState(MarkdownHighlighter::CodeOther, QStringLiteral(".code-other")); schemaStyles += encodeCssStyleForState(MarkdownHighlighter::CodeNumLiteral, QStringLiteral(".code-literal")); - schemaStyles += encodeCssStyleForState(MarkdownHighlighter::CodeBuiltIn, - QStringLiteral(".code-builtin")); + schemaStyles += + encodeCssStyleForState(MarkdownHighlighter::CodeBuiltIn, QStringLiteral(".code-builtin")); // enforce blockquotes styles (best effort, may not override all styles of other tags) // https://github.com/pbek/QOwnNotes/issues/2669 if (QSettings().value(QStringLiteral("fullyHighlightedBlockquotes")).toBool()) { - schemaStyles += encodeCssStyleForState(MarkdownHighlighter::BlockQuote, - QStringLiteral("blockquote")); + schemaStyles += + encodeCssStyleForState(MarkdownHighlighter::BlockQuote, QStringLiteral("blockquote")); QTextCharFormat format; - Utils::Schema::schemaSettings->setFormatStyle( - MarkdownHighlighter::BlockQuote, format); + Utils::Schema::schemaSettings->setFormatStyle(MarkdownHighlighter::BlockQuote, format); // override foreground colors of sub-elements - schemaStyles += QStringLiteral("blockquote strong, blockquote em, " - "blockquote i, blockquote b, blockquote a, blockquote code, " - "blockquote pre, blockquote h1, blockquote h2, blockquote h3, " - "blockquote h4, blockquote h5, blockquote h6 {color: ") + - format.foreground().color().name() + QStringLiteral("}"); + schemaStyles += QStringLiteral( + "blockquote strong, blockquote em, " + "blockquote i, blockquote b, blockquote a, blockquote code, " + "blockquote pre, blockquote h1, blockquote h2, blockquote h3, " + "blockquote h4, blockquote h5, blockquote h6 {color: ") + + format.foreground().color().name() + QStringLiteral("}"); } return schemaStyles; @@ -496,24 +444,21 @@ QString Utils::Schema::getSchemaStyles() { QString Utils::Schema::encodeCssTextCharFormat(const QTextCharFormat& format) { auto css = QStringLiteral("%1; color: %2;") - .arg(encodeCssFont(format.font()), - format.foreground().color().name()); + .arg(encodeCssFont(format.font()), format.foreground().color().name()); auto brush = format.background(); if (brush.isOpaque()) { - css += - QStringLiteral(" background-color: %1").arg(brush.color().name()); + css += QStringLiteral(" background-color: %1").arg(brush.color().name()); } return css; } -QString Utils::Schema::encodeCssStyleForState( - MarkdownHighlighter::HighlighterState index, const QString& htmlTag) { +QString Utils::Schema::encodeCssStyleForState(MarkdownHighlighter::HighlighterState index, + const QString& htmlTag) { QTextCharFormat format; Utils::Schema::schemaSettings->setFormatStyle(index, format); - return QStringLiteral("%1 {%2}").arg(htmlTag, - encodeCssTextCharFormat(format)); + return QStringLiteral("%1 {%2}").arg(htmlTag, encodeCssTextCharFormat(format)); } /** @@ -569,8 +514,7 @@ QString Utils::Schema::encodeCssFont(const QFont& refFont) { famList << fam; } - const QString famStr = - QStringLiteral("font-family: ") + famList.join(QStringLiteral(", ")); + const QString famStr = QStringLiteral("font-family: ") + famList.join(QStringLiteral(", ")); fields << famStr; // reset font-weight to "normal" so headers and bold tags can be diff --git a/src/utils/schema.h b/src/utils/schema.h index 2ca3f6359..a40f32e16 100644 --- a/src/utils/schema.h +++ b/src/utils/schema.h @@ -43,15 +43,13 @@ class Settings { QStringList getSchemaKeys(const QString& schema) const; - QVariant getSchemaValue(const QString& key, - const QVariant& defaultValue = QVariant(), + QVariant getSchemaValue(const QString& key, const QVariant& defaultValue = QVariant(), QString schemaKey = QString()) const; QFont getFont(int index) const; QColor getForegroundColor(int index) const; QColor getBackgroundColor(int index) const; - void setFormatStyle(MarkdownHighlighter::HighlighterState index, - QTextCharFormat& format) const; + void setFormatStyle(MarkdownHighlighter::HighlighterState index, QTextCharFormat& format) const; QFont getEditorTextFont() const; QFont getEditorFixedFont() const; @@ -75,8 +73,7 @@ QString textSettingsKey(const QString& key, int index); QString encodeCssTextCharFormat(const QTextCharFormat& format); -QString encodeCssStyleForState(MarkdownHighlighter::HighlighterState index, - const QString& htmlTag); +QString encodeCssStyleForState(MarkdownHighlighter::HighlighterState index, const QString& htmlTag); QString encodeCssFont(const QFont& refFont); diff --git a/src/utils/urlhandler.cpp b/src/utils/urlhandler.cpp index e21e07564..05dec1225 100644 --- a/src/utils/urlhandler.cpp +++ b/src/utils/urlhandler.cpp @@ -1,30 +1,26 @@ #include "urlhandler.h" -#include "mainwindow.h" -#include "widgets/qownnotesmarkdowntextedit.h" -#include "entities/note.h" -#include "entities/notefolder.h" -#include "entities/notesubfolder.h" -#include "utils/gui.h" -#include "widgets/notesubfoldertree.h" #include <QDesktopServices> #include <QFileInfo> +#include "entities/note.h" +#include "entities/notefolder.h" +#include "entities/notesubfolder.h" +#include "mainwindow.h" +#include "utils/gui.h" +#include "widgets/notesubfoldertree.h" +#include "widgets/qownnotesmarkdowntextedit.h" + UrlHandler::UrlHandler() = default; -bool UrlHandler::isUrlSchemeLocal(const QUrl &url) -{ +bool UrlHandler::isUrlSchemeLocal(const QUrl &url) { const QString scheme = url.scheme(); - return scheme == QLatin1String("note") - || scheme == QLatin1String("noteid") - || scheme == QLatin1String("task") - || scheme == QLatin1String("checkbox") - || (scheme == QLatin1String("file") && - Note::fileUrlIsNoteInCurrentNoteFolder(url)); + return scheme == QLatin1String("note") || scheme == QLatin1String("noteid") || + scheme == QLatin1String("task") || scheme == QLatin1String("checkbox") || + (scheme == QLatin1String("file") && Note::fileUrlIsNoteInCurrentNoteFolder(url)); } -void UrlHandler::openUrl(QString urlString) -{ +void UrlHandler::openUrl(QString urlString) { /* examples: * - <note://MyNote> opens the note "MyNote" * - <note://my-note-with-spaces-in-the-name> opens the note "My Note with @@ -44,7 +40,8 @@ void UrlHandler::openUrl(QString urlString) QString fragment; if (urlWasNotValid) { fragment = Note::getURLFragmentFromFileName(urlString); - urlString = MainWindow::instance()->getCurrentNote().getFileURLFromFileName(urlString, true); + urlString = + MainWindow::instance()->getCurrentNote().getFileURLFromFileName(urlString, true); } else { fragment = QUrl(urlString).fragment(); } @@ -74,8 +71,7 @@ void UrlHandler::openUrl(QString urlString) } } -void UrlHandler::handleNoteIdUrl(QString urlString) -{ +void UrlHandler::handleNoteIdUrl(QString urlString) { static const QRegularExpression re(QStringLiteral(R"(^noteid:\/\/note-(\d+)$)")); QRegularExpressionMatch match = re.match(urlString); @@ -126,12 +122,11 @@ void UrlHandler::handleNoteUrl(QString urlString, const QString &fragment) { // ip-address static const QRegularExpression re(QStringLiteral(R"(^\w+:\/\/(\d+)$)")); QRegularExpressionMatch match = re.match(urlString); - fileName = - match.hasMatch() ? match.captured(1) : url.host(); + fileName = match.hasMatch() ? match.captured(1) : url.host(); // try to generate a useful title for the note fileName = Utils::Misc::toStartCase( - fileName.replace(QStringLiteral("_"), QStringLiteral(" "))); + fileName.replace(QStringLiteral("_"), QStringLiteral(" "))); } else { fileName = url.fileName(); filePath = url.adjusted(QUrl::RemoveFilename); @@ -140,18 +135,14 @@ void UrlHandler::handleNoteUrl(QString urlString, const QString &fragment) { // remove file extension QFileInfo fileInfo(fileName); fileName = fileInfo.baseName(); - QString relativeFilePath = - Note::fileUrlInCurrentNoteFolderToRelativePath(filePath); - QString currentNoteRelativeSubFolderPath = - currentNote.getNoteSubFolder().relativePath(); + QString relativeFilePath = Note::fileUrlInCurrentNoteFolderToRelativePath(filePath); + QString currentNoteRelativeSubFolderPath = currentNote.getNoteSubFolder().relativePath(); // remove the current relative sub-folder path from the relative path // of the future note to be able to create the correct path afterwards if (!currentNoteRelativeSubFolderPath.isEmpty()) { relativeFilePath.remove(QRegularExpression( - "^" + - QRegularExpression::escape(currentNoteRelativeSubFolderPath) + - "\\/")); + "^" + QRegularExpression::escape(currentNoteRelativeSubFolderPath) + "\\/")); } // Open attachments with extensions that are used for notes externally @@ -162,48 +153,50 @@ void UrlHandler::handleNoteUrl(QString urlString, const QString &fragment) { } if (!relativeFilePath.isEmpty() && !NoteFolder::isCurrentHasSubfolders()) { - Utils::Gui::warning( - nullptr, QObject::tr("Note was not found"), - QObject::tr("Could not find note.<br />Unable to automatically " - "create note at location, because subfolders are " - "disabled for the current note folder."), - "cannot-create-note-not-has-subfolders"); + Utils::Gui::warning(nullptr, QObject::tr("Note was not found"), + QObject::tr("Could not find note.<br />Unable to automatically " + "create note at location, because subfolders are " + "disabled for the current note folder."), + "cannot-create-note-not-has-subfolders"); return; } QString promptQuestion; if (relativeFilePath.isEmpty()) { - promptQuestion = QObject::tr("Note was not found, create new note " - "<strong>%1</strong>?") - .arg(fileName); + promptQuestion = QObject::tr( + "Note was not found, create new note " + "<strong>%1</strong>?") + .arg(fileName); } else { - promptQuestion = QObject::tr("Note was not found, create new note " - "<strong>%1</strong> at path <strong>%2</strong>?") - .arg(fileName, relativeFilePath); + promptQuestion = QObject::tr( + "Note was not found, create new note " + "<strong>%1</strong> at path <strong>%2</strong>?") + .arg(fileName, relativeFilePath); } // ask if we want to create a new note if note wasn't found - if (Utils::Gui::questionNoSkipOverride(nullptr, QObject::tr("Note was not found"), - promptQuestion, - QStringLiteral("open-url-create-note")) == QMessageBox::Yes) { - + if (Utils::Gui::questionNoSkipOverride( + nullptr, QObject::tr("Note was not found"), promptQuestion, + QStringLiteral("open-url-create-note")) == QMessageBox::Yes) { NoteSubFolder noteSubFolder = currentNote.getNoteSubFolder(); bool subFolderCreationFailed(false); if (!relativeFilePath.isEmpty()) { - for (const QString& folderName : relativeFilePath.split("/")) { + for (const QString &folderName : relativeFilePath.split("/")) { if (folderName.isEmpty()) { break; } - NoteSubFolder subFolder = NoteSubFolder::fetchByNameAndParentId(folderName, noteSubFolder.getId()); + NoteSubFolder subFolder = + NoteSubFolder::fetchByNameAndParentId(folderName, noteSubFolder.getId()); if (!subFolder.isFetched()) { mw->createNewNoteSubFolder(folderName); - noteSubFolder = NoteSubFolder::fetchByNameAndParentId(folderName, noteSubFolder.getId()); + noteSubFolder = NoteSubFolder::fetchByNameAndParentId( + folderName, noteSubFolder.getId()); if (!noteSubFolder.isFetched()) { - qWarning() << "Failed to create subfolder: " << folderName << - "when attempting to create path: " << relativeFilePath; + qWarning() << "Failed to create subfolder: " << folderName + << "when attempting to create path: " << relativeFilePath; subFolderCreationFailed = true; break; } @@ -222,10 +215,8 @@ void UrlHandler::handleNoteUrl(QString urlString, const QString &fragment) { } mw->createNewNote(fileName, false); } else { - Utils::Gui::warning( - nullptr, QObject::tr("Failed to create note"), - QObject::tr("Note creation failed"), - "note-create-failed"); + Utils::Gui::warning(nullptr, QObject::tr("Failed to create note"), + QObject::tr("Note creation failed"), "note-create-failed"); } return; } @@ -237,8 +228,7 @@ void UrlHandler::handleNoteUrl(QString urlString, const QString &fragment) { * * @param urlString */ -void UrlHandler::handleCheckboxUrl(QString urlString) -{ +void UrlHandler::handleCheckboxUrl(QString urlString) { auto mw = MainWindow::instance(); // Check if read-only mode is enabled and allow to get out of it @@ -250,7 +240,8 @@ void UrlHandler::handleCheckboxUrl(QString urlString) const QUrl url(urlString); int index = url.host().mid(1).toInt(); - static const QRegularExpression re(R"((^|\n)\s*[-*+]\s\[([xX ]?)\])", QRegularExpression::CaseInsensitiveOption); + static const QRegularExpression re(R"((^|\n)\s*[-*+]\s\[([xX ]?)\])", + QRegularExpression::CaseInsensitiveOption); int pos = 0; while (true) { QRegularExpressionMatch match; @@ -261,18 +252,15 @@ void UrlHandler::handleCheckboxUrl(QString urlString) int matchedLength = match.capturedLength(); qDebug() << __func__ << "match.capturedLength(): " << match.capturedLength(); cursor.setPosition(pos + match.capturedLength() - 1); - if (cursor.block().userState() == - MarkdownHighlighter::HighlighterState::List) { + if (cursor.block().userState() == MarkdownHighlighter::HighlighterState::List) { if (index == 0) { auto ch = match.captured(2); if (ch.isEmpty()) cursor.insertText(QStringLiteral("x")); else { - cursor.movePosition(QTextCursor::PreviousCharacter, - QTextCursor::KeepAnchor); - cursor.insertText(ch == QStringLiteral(" ") - ? QStringLiteral("x") - : QStringLiteral(" ")); + cursor.movePosition(QTextCursor::PreviousCharacter, QTextCursor::KeepAnchor); + cursor.insertText(ch == QStringLiteral(" ") ? QStringLiteral("x") + : QStringLiteral(" ")); } // refresh instantly @@ -285,8 +273,7 @@ void UrlHandler::handleCheckboxUrl(QString urlString) } } -void UrlHandler::handleFileUrl(QString urlString) -{ +void UrlHandler::handleFileUrl(QString urlString) { QString windowsSlash = QString(); #ifdef Q_OS_WIN32 @@ -294,16 +281,14 @@ void UrlHandler::handleFileUrl(QString urlString) windowsSlash = QStringLiteral("/"); #endif - urlString.replace(QLatin1String("file://.."), - QStringLiteral("file://") + windowsSlash + - NoteFolder::currentLocalPath() + - QStringLiteral("/..")); + urlString.replace(QLatin1String("file://.."), QStringLiteral("file://") + windowsSlash + + NoteFolder::currentLocalPath() + + QStringLiteral("/..")); QDesktopServices::openUrl(QUrl(urlString)); } -void UrlHandler::handleFileAttachmentUrl(QString urlString) -{ +void UrlHandler::handleFileAttachmentUrl(QString urlString) { QString windowsSlash = QString(); #ifdef Q_OS_WIN32 @@ -312,9 +297,8 @@ void UrlHandler::handleFileAttachmentUrl(QString urlString) #endif urlString.replace(QLatin1String("file://attachments"), - QStringLiteral("file://") + windowsSlash + - NoteFolder::currentLocalPath() + - QStringLiteral("/attachments")); + QStringLiteral("file://") + windowsSlash + NoteFolder::currentLocalPath() + + QStringLiteral("/attachments")); QDesktopServices::openUrl(QUrl(urlString)); return; diff --git a/src/utils/urlhandler.h b/src/utils/urlhandler.h index 6c1f451f5..396f83c1a 100644 --- a/src/utils/urlhandler.h +++ b/src/utils/urlhandler.h @@ -14,14 +14,14 @@ class MainWindow; * spaces in the name" */ class UrlHandler { -public: + public: UrlHandler(); static bool isUrlSchemeLocal(const QUrl &url); void openUrl(QString urlString); -private: + private: void handleNoteIdUrl(QString urlString); void handleNoteUrl(QString urlString, const QString &fragment); void handleCheckboxUrl(QString urlString); diff --git a/src/widgets/fontcolorwidget.cpp b/src/widgets/fontcolorwidget.cpp index c6efb3dc5..0a3169e14 100644 --- a/src/widgets/fontcolorwidget.cpp +++ b/src/widgets/fontcolorwidget.cpp @@ -33,8 +33,7 @@ #include "ui_fontcolorwidget.h" #include "utils/schema.h" -FontColorWidget::FontColorWidget(QWidget* parent) - : QFrame(parent), ui(new Ui::FontColorWidget) { +FontColorWidget::FontColorWidget(QWidget* parent) : QFrame(parent), ui(new Ui::FontColorWidget) { ui->setupUi(this); // initialize the schema selector @@ -63,26 +62,16 @@ FontColorWidget::FontColorWidget(QWidget* parent) // declare that we need to restart the application if certain settings // are changed - connect(ui->colorSchemeComboBox, SIGNAL(currentIndexChanged(int)), this, - SLOT(needRestart())); - connect(ui->fontCheckBox, SIGNAL(toggled(bool)), this, - SLOT(needRestart())); - connect(ui->foregroundColorCheckBox, SIGNAL(toggled(bool)), this, - SLOT(needRestart())); - connect(ui->backgroundColorCheckBox, SIGNAL(toggled(bool)), this, - SLOT(needRestart())); - connect(ui->boldCheckBox, SIGNAL(toggled(bool)), this, - SLOT(needRestart())); - connect(ui->italicCheckBox, SIGNAL(toggled(bool)), this, - SLOT(needRestart())); - connect(ui->underlineCheckBox, SIGNAL(toggled(bool)), this, - SLOT(needRestart())); - connect(ui->foregroundColorButton, SIGNAL(clicked()), this, - SLOT(needRestart())); - connect(ui->backgroundColorButton, SIGNAL(clicked()), this, - SLOT(needRestart())); - connect(ui->fontComboBox, SIGNAL(currentFontChanged(QFont)), this, - SLOT(needRestart())); + connect(ui->colorSchemeComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(needRestart())); + connect(ui->fontCheckBox, SIGNAL(toggled(bool)), this, SLOT(needRestart())); + connect(ui->foregroundColorCheckBox, SIGNAL(toggled(bool)), this, SLOT(needRestart())); + connect(ui->backgroundColorCheckBox, SIGNAL(toggled(bool)), this, SLOT(needRestart())); + connect(ui->boldCheckBox, SIGNAL(toggled(bool)), this, SLOT(needRestart())); + connect(ui->italicCheckBox, SIGNAL(toggled(bool)), this, SLOT(needRestart())); + connect(ui->underlineCheckBox, SIGNAL(toggled(bool)), this, SLOT(needRestart())); + connect(ui->foregroundColorButton, SIGNAL(clicked()), this, SLOT(needRestart())); + connect(ui->backgroundColorButton, SIGNAL(clicked()), this, SLOT(needRestart())); + connect(ui->fontComboBox, SIGNAL(currentFontChanged(QFont)), this, SLOT(needRestart())); } /** @@ -102,8 +91,7 @@ void FontColorWidget::initSchemaSelector() { QString currentSchemaKey = settings .value(QStringLiteral("Editor/CurrentSchemaKey"), - _defaultSchemaKeys.length() > 0 ? _defaultSchemaKeys[0] - : QString()) + _defaultSchemaKeys.length() > 0 ? _defaultSchemaKeys[0] : QString()) .toString(); int index = 0; int currentIndex = 0; @@ -111,8 +99,7 @@ void FontColorWidget::initSchemaSelector() { Q_FOREACH (const QString& schemaKey, _defaultSchemaKeys) { const QSettings& defaultSchemaSettings = Utils::Schema::schemaSettings->defaultSchemaSettings(); - const QString name = - defaultSchemaSettings.value(schemaKey + "/Name").toString(); + const QString name = defaultSchemaSettings.value(schemaKey + "/Name").toString(); ui->colorSchemeComboBox->addItem(name, schemaKey); if (currentSchemaKey == schemaKey) { @@ -125,8 +112,7 @@ void FontColorWidget::initSchemaSelector() { // // load the custom schemes // - QStringList schemes = - settings.value(QStringLiteral("Editor/ColorSchemes")).toStringList(); + QStringList schemes = settings.value(QStringLiteral("Editor/ColorSchemes")).toStringList(); Q_FOREACH (QString schemaKey, schemes) { settings.beginGroup(schemaKey); QString name = settings.value(QStringLiteral("Name")).toString(); @@ -214,34 +200,26 @@ void FontColorWidget::initTextTreeWidgetItems() { addTextTreeWidgetItem(tr("Link"), MarkdownHighlighter::Link); addTextTreeWidgetItem(tr("Image"), MarkdownHighlighter::Image); addTextTreeWidgetItem(tr("Code (block)"), MarkdownHighlighter::CodeBlock); - addTextTreeWidgetItem(tr("Code (inline)"), - MarkdownHighlighter::InlineCodeBlock); + addTextTreeWidgetItem(tr("Code (inline)"), MarkdownHighlighter::InlineCodeBlock); - addTextTreeWidgetItem(tr("Code (keyword)"), - MarkdownHighlighter::CodeKeyWord); + addTextTreeWidgetItem(tr("Code (keyword)"), MarkdownHighlighter::CodeKeyWord); addTextTreeWidgetItem(tr("Code (type)"), MarkdownHighlighter::CodeType); - addTextTreeWidgetItem(tr("Code (comment)"), - MarkdownHighlighter::CodeComment); + addTextTreeWidgetItem(tr("Code (comment)"), MarkdownHighlighter::CodeComment); addTextTreeWidgetItem(tr("Code (string)"), MarkdownHighlighter::CodeString); - addTextTreeWidgetItem(tr("Code (built in)"), - MarkdownHighlighter::CodeBuiltIn); - addTextTreeWidgetItem(tr("Code (num literal)"), - MarkdownHighlighter::CodeNumLiteral); + addTextTreeWidgetItem(tr("Code (built in)"), MarkdownHighlighter::CodeBuiltIn); + addTextTreeWidgetItem(tr("Code (num literal)"), MarkdownHighlighter::CodeNumLiteral); addTextTreeWidgetItem(tr("Code (other)"), MarkdownHighlighter::CodeOther); addTextTreeWidgetItem(tr("List item"), MarkdownHighlighter::List); - addTextTreeWidgetItem(tr("Checkbox unchecked"), - MarkdownHighlighter::CheckBoxUnChecked); - addTextTreeWidgetItem(tr("Checkbox checked"), - MarkdownHighlighter::CheckBoxChecked); + addTextTreeWidgetItem(tr("Checkbox unchecked"), MarkdownHighlighter::CheckBoxUnChecked); + addTextTreeWidgetItem(tr("Checkbox checked"), MarkdownHighlighter::CheckBoxChecked); addTextTreeWidgetItem(tr("Header, level 1"), MarkdownHighlighter::H1); addTextTreeWidgetItem(tr("Header, level 2"), MarkdownHighlighter::H2); addTextTreeWidgetItem(tr("Header, level 3"), MarkdownHighlighter::H3); addTextTreeWidgetItem(tr("Header, level 4"), MarkdownHighlighter::H4); addTextTreeWidgetItem(tr("Header, level 5"), MarkdownHighlighter::H5); addTextTreeWidgetItem(tr("Header, level 6"), MarkdownHighlighter::H6); - addTextTreeWidgetItem(tr("Horizontal rule"), - MarkdownHighlighter::HorizontalRuler); + addTextTreeWidgetItem(tr("Horizontal rule"), MarkdownHighlighter::HorizontalRuler); addTextTreeWidgetItem(tr("Block quote"), MarkdownHighlighter::BlockQuote); addTextTreeWidgetItem(tr("Table"), MarkdownHighlighter::Table); addTextTreeWidgetItem(tr("(HTML) Comment"), MarkdownHighlighter::Comment); @@ -252,11 +230,10 @@ void FontColorWidget::initTextTreeWidgetItems() { addTextTreeWidgetItem(tr("Current line background color"), MarkdownHighlighter::CurrentLineBackgroundColor); addTextTreeWidgetItem(tr("Broken link"), MarkdownHighlighter::BrokenLink); - addTextTreeWidgetItem(tr("Trailing space"), - MarkdownHighlighter::TrailingSpace); + addTextTreeWidgetItem(tr("Trailing space"), MarkdownHighlighter::TrailingSpace); // jump to the top of the list so that an item is selected - auto *event = new QKeyEvent(QEvent::KeyPress, Qt::Key_Home, Qt::NoModifier); + auto* event = new QKeyEvent(QEvent::KeyPress, Qt::Key_Home, Qt::NoModifier); QApplication::postEvent(ui->textTreeWidget, event); } @@ -266,9 +243,7 @@ void FontColorWidget::addTextTreeWidgetItem(const QString& text, int index) { item->setData(0, Qt::UserRole, index); if (index == Utils::Schema::TextPresetIndex) { - item->setToolTip( - 0, - tr("This item will be used to preset colors for the other items")); + item->setToolTip(0, tr("This item will be used to preset colors for the other items")); } // update the styling of the text tree widget item @@ -295,15 +270,13 @@ void FontColorWidget::updateSchemeEditFrame() { ui->schemeEditFrame->setEnabled(!_currentSchemaIsDefault); bool enabled = Utils::Schema::schemaSettings - ->getSchemaValue(textSettingsKey( - QStringLiteral("FontEnabled"))) + ->getSchemaValue(textSettingsKey(QStringLiteral("FontEnabled"))) .toBool(); updateFontCheckBox(enabled); enabled = Utils::Schema::schemaSettings - ->getSchemaValue(textSettingsKey( - QStringLiteral("ForegroundColorEnabled"))) - .toBool(); + ->getSchemaValue(textSettingsKey(QStringLiteral("ForegroundColorEnabled"))) + .toBool(); updateForegroundColorCheckBox(enabled); QColor color = Utils::Schema::schemaSettings->getForegroundColor(index); @@ -311,8 +284,7 @@ void FontColorWidget::updateSchemeEditFrame() { QStringLiteral("* {background: %1; border: none;}").arg(color.name())); enabled = Utils::Schema::schemaSettings - ->getSchemaValue( - textSettingsKey(QStringLiteral("BackgroundColorEnabled"))) + ->getSchemaValue(textSettingsKey(QStringLiteral("BackgroundColorEnabled"))) .toBool(); updateBackgroundColorCheckBox(enabled); @@ -321,17 +293,12 @@ void FontColorWidget::updateSchemeEditFrame() { QStringLiteral("* {background: %1; border: none;}").arg(color.name())); bool isCurrentLineBackgroundColorIndex = - index == - MarkdownHighlighter::HighlighterState::CurrentLineBackgroundColor; + index == MarkdownHighlighter::HighlighterState::CurrentLineBackgroundColor; - ui->boldCheckBox->setVisible(index >= 0 && - !isCurrentLineBackgroundColorIndex); - ui->italicCheckBox->setVisible(index >= 0 && - !isCurrentLineBackgroundColorIndex); - ui->underlineCheckBox->setVisible(index >= 0 && - !isCurrentLineBackgroundColorIndex); - ui->fontSizeAdaptionSpinBox->setVisible(index >= 0 && - !isCurrentLineBackgroundColorIndex); + ui->boldCheckBox->setVisible(index >= 0 && !isCurrentLineBackgroundColorIndex); + ui->italicCheckBox->setVisible(index >= 0 && !isCurrentLineBackgroundColorIndex); + ui->underlineCheckBox->setVisible(index >= 0 && !isCurrentLineBackgroundColorIndex); + ui->fontSizeAdaptionSpinBox->setVisible(index >= 0 && !isCurrentLineBackgroundColorIndex); ui->fontCheckBox->setVisible(index >= 0 && !isCurrentLineBackgroundColorIndex); ui->fontComboBox->setVisible(index >= 0 && !isCurrentLineBackgroundColorIndex); ui->foregroundColorCheckBox->setVisible(!isCurrentLineBackgroundColorIndex); @@ -344,16 +311,14 @@ void FontColorWidget::updateSchemeEditFrame() { Q_UNUSED(blocker) ui->boldCheckBox->setChecked( - Utils::Schema::schemaSettings - ->getSchemaValue(textSettingsKey(QStringLiteral("Bold"))) + Utils::Schema::schemaSettings->getSchemaValue(textSettingsKey(QStringLiteral("Bold"))) .toBool()); const QSignalBlocker blocker2(ui->italicCheckBox); Q_UNUSED(blocker2) ui->italicCheckBox->setChecked( - Utils::Schema::schemaSettings - ->getSchemaValue(textSettingsKey(QStringLiteral("Italic"))) + Utils::Schema::schemaSettings->getSchemaValue(textSettingsKey(QStringLiteral("Italic"))) .toBool()); const QSignalBlocker blocker3(ui->underlineCheckBox); @@ -369,18 +334,16 @@ void FontColorWidget::updateSchemeEditFrame() { ui->fontSizeAdaptionSpinBox->setValue( Utils::Schema::schemaSettings - ->getSchemaValue( - textSettingsKey(QStringLiteral("FontSizeAdaption")), 100) + ->getSchemaValue(textSettingsKey(QStringLiteral("FontSizeAdaption")), 100) .toInt()); const QSignalBlocker blocker5(ui->fontComboBox); Q_UNUSED(blocker5) QFont font = Utils::Schema::schemaSettings - ->getSchemaValue( - textSettingsKey(QStringLiteral("Font")), - Utils::Schema::schemaSettings->getEditorTextFont()) - .value<QFont>(); + ->getSchemaValue(textSettingsKey(QStringLiteral("Font")), + Utils::Schema::schemaSettings->getEditorTextFont()) + .value<QFont>(); ui->fontComboBox->setCurrentFont(font); } @@ -393,8 +356,7 @@ void FontColorWidget::updateSchemeEditFrame() { * @param item * @return */ -QString FontColorWidget::textSettingsKey(const QString& key, - QTreeWidgetItem* item) { +QString FontColorWidget::textSettingsKey(const QString& key, QTreeWidgetItem* item) { return Utils::Schema::textSettingsKey(key, textSettingsIndex(item)); } @@ -419,8 +381,7 @@ int FontColorWidget::textSettingsIndex(QTreeWidgetItem* item) { * @param key * @param value */ -void FontColorWidget::setSchemaValue(const QString& key, const QVariant& value, - QString schemaKey) { +void FontColorWidget::setSchemaValue(const QString& key, const QVariant& value, QString schemaKey) { if (schemaKey.isEmpty()) { schemaKey = _currentSchemaKey; } @@ -443,8 +404,7 @@ void FontColorWidget::on_colorSchemeComboBox_currentIndexChanged(int index) { ui->schemeEditFrame->setEnabled(!_currentSchemaIsDefault); QSettings settings; - settings.setValue(QStringLiteral("Editor/CurrentSchemaKey"), - _currentSchemaKey); + settings.setValue(QStringLiteral("Editor/CurrentSchemaKey"), _currentSchemaKey); updateSchemeEditFrame(); @@ -488,8 +448,8 @@ bool FontColorWidget::selectFirstDarkSchema() { * @param current * @param previous */ -void FontColorWidget::on_textTreeWidget_currentItemChanged( - QTreeWidgetItem* current, QTreeWidgetItem* previous) { +void FontColorWidget::on_textTreeWidget_currentItemChanged(QTreeWidgetItem* current, + QTreeWidgetItem* previous) { Q_UNUSED(current) Q_UNUSED(previous) @@ -530,15 +490,12 @@ void FontColorWidget::updateTextItem(QTreeWidgetItem* item) { item->setBackground(0, brush); QFont font = Utils::Schema::schemaSettings->getFont(index); - font.setBold(Utils::Schema::schemaSettings - ->getSchemaValue(textSettingsKey("Bold", item)) - .toBool()); - font.setItalic(Utils::Schema::schemaSettings - ->getSchemaValue(textSettingsKey("Italic", item)) - .toBool()); - font.setUnderline(Utils::Schema::schemaSettings - ->getSchemaValue(textSettingsKey("Underline", item)) - .toBool()); + font.setBold( + Utils::Schema::schemaSettings->getSchemaValue(textSettingsKey("Bold", item)).toBool()); + font.setItalic( + Utils::Schema::schemaSettings->getSchemaValue(textSettingsKey("Italic", item)).toBool()); + font.setUnderline( + Utils::Schema::schemaSettings->getSchemaValue(textSettingsKey("Underline", item)).toBool()); // adapt the font size Utils::Schema::schemaSettings->adaptFontSize(index, font); @@ -551,26 +508,22 @@ void FontColorWidget::updateTextItem(QTreeWidgetItem* item) { */ void FontColorWidget::on_copySchemeButton_clicked() { // ask the user for a new schema name - QString name = - QInputDialog::getText(this, tr("Copy color schema"), - tr("Color schema name"), QLineEdit::Normal, - ui->colorSchemeComboBox->currentText() + " (" + - tr("Copy", "as noun") + ")"); + QString name = QInputDialog::getText( + this, tr("Copy color schema"), tr("Color schema name"), QLineEdit::Normal, + ui->colorSchemeComboBox->currentText() + " (" + tr("Copy", "as noun") + ")"); if (name.isEmpty()) { return; } - const QStringList& keys = - Utils::Schema::schemaSettings->getSchemaKeys(_currentSchemaKey); + const QStringList& keys = Utils::Schema::schemaSettings->getSchemaKeys(_currentSchemaKey); QString uuid = Utils::Misc::createUuidString(); _currentSchemaKey = "EditorColorSchema-" + uuid; // store the new color schema data Q_FOREACH (const QString& key, keys) { QVariant value = - key == "Name" ? QVariant(name) - : Utils::Schema::schemaSettings->getSchemaValue(key); + key == "Name" ? QVariant(name) : Utils::Schema::schemaSettings->getSchemaValue(key); setSchemaValue(key, value, _currentSchemaKey); } @@ -594,13 +547,11 @@ void FontColorWidget::selectLastSchema() { #ifdef Q_OS_MAC // under OS X we have to use a workaround to select the newly created schema - QKeyEvent* event = - new QKeyEvent(QEvent::KeyPress, Qt::Key_End, Qt::NoModifier); + QKeyEvent* event = new QKeyEvent(QEvent::KeyPress, Qt::Key_End, Qt::NoModifier); QApplication::postEvent(ui->colorSchemeComboBox, event); #else // set the index to the (new) last item - ui->colorSchemeComboBox->setCurrentIndex(ui->colorSchemeComboBox->count() - - 1); + ui->colorSchemeComboBox->setCurrentIndex(ui->colorSchemeComboBox->count() - 1); #endif } @@ -672,10 +623,9 @@ void FontColorWidget::on_deleteSchemeButton_clicked() { return; } - if (Utils::Gui::question( - this, tr("Remove schema"), - tr("Remove current schema? This cannot be undone!"), - "remove-color-schema") != QMessageBox::Yes) { + if (Utils::Gui::question(this, tr("Remove schema"), + tr("Remove current schema? This cannot be undone!"), + "remove-color-schema") != QMessageBox::Yes) { return; } @@ -702,9 +652,7 @@ void FontColorWidget::storeCheckBoxState(const QString& name, bool checked) { updateTextItem(); } -void FontColorWidget::on_boldCheckBox_toggled(bool checked) { - storeCheckBoxState("Bold", checked); -} +void FontColorWidget::on_boldCheckBox_toggled(bool checked) { storeCheckBoxState("Bold", checked); } void FontColorWidget::on_italicCheckBox_toggled(bool checked) { storeCheckBoxState("Italic", checked); @@ -748,8 +696,7 @@ void FontColorWidget::on_exportSchemeButton_clicked() { // store the color schema data to the export settings Q_FOREACH (const QString& key, keys) { - QVariant value = - Utils::Schema::schemaSettings->getSchemaValue(key); + QVariant value = Utils::Schema::schemaSettings->getSchemaValue(key); exportSettings.setValue(key, value); } @@ -774,21 +721,17 @@ void FontColorWidget::on_importSchemeButton_clicked() { if (fileNames.count() > 0) { Q_FOREACH (QString fileName, fileNames) { auto* settings = new QSettings(); - auto* importSettings = - new QSettings(fileName, QSettings::IniFormat); - QString schemaKey = - importSettings->value("Export/SchemaKey").toString(); + auto* importSettings = new QSettings(fileName, QSettings::IniFormat); + QString schemaKey = importSettings->value("Export/SchemaKey").toString(); // create a new schema key for the import QString uuid = Utils::Misc::createUuidString(); _currentSchemaKey = "EditorColorSchema-" + uuid; - QStringList schemes = - settings->value("Editor/ColorSchemes").toStringList(); + QStringList schemes = settings->value("Editor/ColorSchemes").toStringList(); schemes << _currentSchemaKey; settings->setValue("Editor/ColorSchemes", schemes); - settings->setValue("Editor/CurrentSchemaKey", - _currentSchemaKey); + settings->setValue("Editor/CurrentSchemaKey", _currentSchemaKey); settings->beginGroup(_currentSchemaKey); importSettings->beginGroup(schemaKey); @@ -814,8 +757,7 @@ void FontColorWidget::initFontSelectors() { QTextEdit textEdit; QFont font = textEdit.font(); QSettings settings; - QString fontString = - settings.value("MainWindow/noteTextEdit.font").toString(); + QString fontString = settings.value("MainWindow/noteTextEdit.font").toString(); if (!fontString.isEmpty()) { // set the note text edit font @@ -848,11 +790,11 @@ void FontColorWidget::on_fontSizeAdaptionSpinBox_valueChanged(int value) { * Opens a new GitHub issue to share a schema */ void FontColorWidget::on_shareSchemaPushButton_clicked() { - QDesktopServices::openUrl(QUrl( - "https://github.com/pbek/QOwnNotes/issues/new?title=" + - QUrl::toPercentEncoding("New editor schema: <schema-name>") + "&body=" + - QUrl::toPercentEncoding("I want to submit a new editor schema.\n\n" - "(upload your schema)"))); + QDesktopServices::openUrl( + QUrl("https://github.com/pbek/QOwnNotes/issues/new?title=" + + QUrl::toPercentEncoding("New editor schema: <schema-name>") + "&body=" + + QUrl::toPercentEncoding("I want to submit a new editor schema.\n\n" + "(upload your schema)"))); } /** @@ -868,7 +810,6 @@ void FontColorWidget::on_fontCheckBox_toggled(bool checked) { // update the scheme edit frame updateSchemeEditFrame(); - } void FontColorWidget::updateFontCheckBox(bool checked, bool store) { @@ -886,7 +827,7 @@ void FontColorWidget::updateFontCheckBox(bool checked, bool store) { } } -void FontColorWidget::on_fontComboBox_currentFontChanged(const QFont &f) { +void FontColorWidget::on_fontComboBox_currentFontChanged(const QFont& f) { setSchemaValue(textSettingsKey("Font"), f); // update the styling of the current text tree widget item diff --git a/src/widgets/fontcolorwidget.h b/src/widgets/fontcolorwidget.h index a7049601e..e719fa7dd 100644 --- a/src/widgets/fontcolorwidget.h +++ b/src/widgets/fontcolorwidget.h @@ -41,8 +41,7 @@ class FontColorWidget : public QFrame { void on_colorSchemeComboBox_currentIndexChanged(int index); - void on_textTreeWidget_currentItemChanged(QTreeWidgetItem *current, - QTreeWidgetItem *previous); + void on_textTreeWidget_currentItemChanged(QTreeWidgetItem *current, QTreeWidgetItem *previous); void on_copySchemeButton_clicked(); @@ -88,11 +87,9 @@ class FontColorWidget : public QFrame { void updateSchemeEditFrame(); - void setSchemaValue(const QString &key, const QVariant &value, - QString schemaKey = QString()); + void setSchemaValue(const QString &key, const QVariant &value, QString schemaKey = QString()); - QString textSettingsKey(const QString &key, - QTreeWidgetItem *item = nullptr); + QString textSettingsKey(const QString &key, QTreeWidgetItem *item = nullptr); void updateTextItem(QTreeWidgetItem *item = nullptr); diff --git a/src/widgets/htmlpreviewwidget.cpp b/src/widgets/htmlpreviewwidget.cpp index 63961d29a..4384ed256 100644 --- a/src/widgets/htmlpreviewwidget.cpp +++ b/src/widgets/htmlpreviewwidget.cpp @@ -2,32 +2,27 @@ #ifdef USE_QLITEHTML -#include <QEventLoop> -#include <QNetworkReply> -#include <QDesktopServices> #include <QAction> -#include <QMenu> #include <QApplication> #include <QClipboard> +#include <QDesktopServices> +#include <QEventLoop> +#include <QMenu> +#include <QNetworkReply> #include <QWheelEvent> -HtmlPreviewWidget::HtmlPreviewWidget(QWidget *parent) - : QLiteHtmlWidget(parent) -{ - auto callback = [this](const QUrl& url){ - return resourceLoadCallBack(url); - }; +HtmlPreviewWidget::HtmlPreviewWidget(QWidget *parent) : QLiteHtmlWidget(parent) { + auto callback = [this](const QUrl &url) { return resourceLoadCallBack(url); }; setResourceHandler(callback); connect(this, &QLiteHtmlWidget::linkClicked, this, &HtmlPreviewWidget::anchorClicked); - connect(this, &QLiteHtmlWidget::contextMenuRequested, this, &HtmlPreviewWidget::onContextMenuRequested); + connect(this, &QLiteHtmlWidget::contextMenuRequested, this, + &HtmlPreviewWidget::onContextMenuRequested); } -QByteArray HtmlPreviewWidget::resourceLoadCallBack(const QUrl &url) -{ - if (!url.isValid()) - return {}; +QByteArray HtmlPreviewWidget::resourceLoadCallBack(const QUrl &url) { + if (!url.isValid()) return {}; m_nam.get(QNetworkRequest(url)); QEventLoop loop; @@ -35,8 +30,7 @@ QByteArray HtmlPreviewWidget::resourceLoadCallBack(const QUrl &url) QNetworkReply *reply = m_nam.get(QNetworkRequest(url)); connect(reply, &QNetworkReply::finished, this, [&data, &loop, reply] { - if (reply->error() == QNetworkReply::NoError) - data = reply->readAll(); + if (reply->error() == QNetworkReply::NoError) data = reply->readAll(); reply->deleteLater(); loop.exit(); }); @@ -45,33 +39,28 @@ QByteArray HtmlPreviewWidget::resourceLoadCallBack(const QUrl &url) return data; } -void HtmlPreviewWidget::onContextMenuRequested(QPoint pos, const QUrl &linkUrl) -{ +void HtmlPreviewWidget::onContextMenuRequested(QPoint pos, const QUrl &linkUrl) { QMenu menu; QAction *act = new QAction(tr("Copy"), this); act->setDisabled(selectedText().isEmpty()); - connect(act, &QAction::triggered, this, [this]{ - qApp->clipboard()->setText(selectedText()); - }); + connect(act, &QAction::triggered, this, [this] { qApp->clipboard()->setText(selectedText()); }); menu.addAction(act); if (!linkUrl.isEmpty() && linkUrl.isValid()) { QAction *act = new QAction(tr("Copy link"), this); act->setEnabled(selectedText().isEmpty()); - connect(act, &QAction::triggered, this, [linkUrl]{ - qApp->clipboard()->setText(linkUrl.toString()); - }); + connect(act, &QAction::triggered, this, + [linkUrl] { qApp->clipboard()->setText(linkUrl.toString()); }); menu.addAction(act); } - menu.addAction(tr("Reset zoom"), this, [this]{ setZoomFactor(1.0); }); + menu.addAction(tr("Reset zoom"), this, [this] { setZoomFactor(1.0); }); menu.exec(mapToGlobal(pos)); } -bool HtmlPreviewWidget::eventFilter(QObject *src, QEvent *e) -{ +bool HtmlPreviewWidget::eventFilter(QObject *src, QEvent *e) { if (e->type() == QEvent::Wheel) { auto we = static_cast<QWheelEvent *>(e); if (we->modifiers() == Qt::ControlModifier) { @@ -83,10 +72,8 @@ bool HtmlPreviewWidget::eventFilter(QObject *src, QEvent *e) return QLiteHtmlWidget::eventFilter(src, e); } -void HtmlPreviewWidget::wheelEvent(QWheelEvent *event) -{ - if (event->modifiers() != Qt::ControlModifier) - return QLiteHtmlWidget::wheelEvent(event); +void HtmlPreviewWidget::wheelEvent(QWheelEvent *event) { + if (event->modifiers() != Qt::ControlModifier) return QLiteHtmlWidget::wheelEvent(event); event->accept(); const int deltaY = event->angleDelta().y(); diff --git a/src/widgets/htmlpreviewwidget.h b/src/widgets/htmlpreviewwidget.h index 753e083f2..7973e9957 100644 --- a/src/widgets/htmlpreviewwidget.h +++ b/src/widgets/htmlpreviewwidget.h @@ -3,19 +3,19 @@ #ifdef USE_QLITEHTML #include <libraries/qlitehtml/src/qlitehtmlwidget.h> + #include <QNetworkAccessManager> -class HtmlPreviewWidget final : public QLiteHtmlWidget -{ +class HtmlPreviewWidget final : public QLiteHtmlWidget { Q_OBJECT -public: + public: HtmlPreviewWidget(QWidget *parent); -Q_SIGNALS: + Q_SIGNALS: void anchorClicked(const QUrl &url); -private: - QByteArray resourceLoadCallBack(const QUrl&); + private: + QByteArray resourceLoadCallBack(const QUrl &); void onContextMenuRequested(QPoint pos, const QUrl &url); void wheelEvent(QWheelEvent *) override; diff --git a/src/widgets/label.cpp b/src/widgets/label.cpp index 4b09e6f6f..d277c9f05 100644 --- a/src/widgets/label.cpp +++ b/src/widgets/label.cpp @@ -43,8 +43,7 @@ void Label::setText(const QString &text) { QLabel::setText(injectCSS(text)); } QString Label::injectCSS(const QString &text) { // text = text.remove("<html>").remove("</html>").remove("<head/>"); QString ret; - ret.reserve(text.size() + 15 + Utils::Misc::genericCSS().size() + - text.size()); + ret.reserve(text.size() + 15 + Utils::Misc::genericCSS().size() + text.size()); ret.append(QStringLiteral("<style>")); ret.append(Utils::Misc::genericCSS()); ret.append(QStringLiteral("</style>")); diff --git a/src/widgets/label.h b/src/widgets/label.h index be008d180..0f830f08b 100644 --- a/src/widgets/label.h +++ b/src/widgets/label.h @@ -19,8 +19,7 @@ class Label : public QLabel { Q_OBJECT public: - explicit Label(QWidget *parent = nullptr, - Qt::WindowFlags f = Qt::WindowFlags()); + explicit Label(QWidget *parent = nullptr, Qt::WindowFlags f = Qt::WindowFlags()); explicit Label(const QString &text, QWidget *parent = nullptr, Qt::WindowFlags f = Qt::WindowFlags()); diff --git a/src/widgets/layoutwidget.cpp b/src/widgets/layoutwidget.cpp index e8c1942d0..b2f357da8 100644 --- a/src/widgets/layoutwidget.cpp +++ b/src/widgets/layoutwidget.cpp @@ -9,8 +9,7 @@ #include "ui_layoutwidget.h" -LayoutWidget::LayoutWidget(QWidget *parent) - : QWidget(parent), ui(new Ui::LayoutWidget) { +LayoutWidget::LayoutWidget(QWidget *parent) : QWidget(parent), ui(new Ui::LayoutWidget) { ui->setupUi(this); _manualSettingsStoring = true; loadLayouts(); @@ -19,11 +18,10 @@ LayoutWidget::LayoutWidget(QWidget *parent) LayoutWidget::~LayoutWidget() { delete ui; } void LayoutWidget::loadLayouts() { - _layoutSettings = new QSettings( - QStringLiteral(":/configurations/layouts.ini"), QSettings::IniFormat); + _layoutSettings = + new QSettings(QStringLiteral(":/configurations/layouts.ini"), QSettings::IniFormat); auto layoutIdentifiers = - _layoutSettings->value(QStringLiteral("LayoutIdentifiers")) - .toStringList(); + _layoutSettings->value(QStringLiteral("LayoutIdentifiers")).toStringList(); { const QSignalBlocker blocker(ui->layoutComboBox); @@ -49,14 +47,14 @@ void LayoutWidget::on_layoutComboBox_currentIndexChanged(int index) { void LayoutWidget::updateCurrentLayout() { QString layoutIdentifier = ui->layoutComboBox->currentData().toString(); QString layoutSettingsPrefix = "Layout-" + layoutIdentifier + "/"; - QString screenshot = - _layoutSettings->value(layoutSettingsPrefix + "screenshot").toString(); + QString screenshot = _layoutSettings->value(layoutSettingsPrefix + "screenshot").toString(); QString layoutDescription = getLayoutDescription(layoutIdentifier); if (_manualSettingsStoring) { - layoutDescription += "\n\n" + tr("Keep in mind that workspaces that " - "demand that there is no central widget will not work properly if " - "the central widget is enabled."); + layoutDescription += + "\n\n" + tr("Keep in mind that workspaces that " + "demand that there is no central widget will not work properly if " + "the central widget is enabled."); } ui->layoutDescriptionLabel->setText(layoutDescription); @@ -82,14 +80,13 @@ void LayoutWidget::updateCurrentLayout() { void LayoutWidget::storeSettings() { if (_manualSettingsStoring) { QString title = tr("Use new layout"); - QString text = tr("Do you want to use the selected layout?") + - "\n\n" + + QString text = tr("Do you want to use the selected layout?") + "\n\n" + tr("The application will be restarted afterwards.") + Utils::Misc::appendSingleAppInstanceTextIfNeeded(); if (Utils::Gui::question(this, title, text, "layoutwidget-use-layout", - QMessageBox::Yes | QMessageBox::No, - QMessageBox::No) == QMessageBox::No) { + QMessageBox::Yes | QMessageBox::No, + QMessageBox::No) == QMessageBox::No) { return; } } @@ -97,31 +94,26 @@ void LayoutWidget::storeSettings() { QString layoutIdentifier = ui->layoutComboBox->currentData().toString(); QString layoutSettingsPrefix = "Layout-" + layoutIdentifier + "/"; QSettings settings; - QStringList workspaces = - settings.value(QStringLiteral("workspaces")).toStringList(); - QString workspaceIdentifier = _manualSettingsStoring ? - Utils::Misc::generateRandomString(12) : "initial"; + QStringList workspaces = settings.value(QStringLiteral("workspaces")).toStringList(); + QString workspaceIdentifier = + _manualSettingsStoring ? Utils::Misc::generateRandomString(12) : "initial"; if (!workspaces.contains(workspaceIdentifier)) { workspaces << workspaceIdentifier; settings.setValue(QStringLiteral("workspaces"), workspaces); } - settings.setValue(QStringLiteral("initialLayoutIdentifier"), - layoutIdentifier); - settings.setValue(QStringLiteral("currentWorkspace"), - workspaceIdentifier); + settings.setValue(QStringLiteral("initialLayoutIdentifier"), layoutIdentifier); + settings.setValue(QStringLiteral("currentWorkspace"), workspaceIdentifier); settings.setValue(QStringLiteral("noteEditIsCentralWidget"), - _layoutSettings->value(layoutSettingsPrefix + - "noteEditIsCentralWidget")); + _layoutSettings->value(layoutSettingsPrefix + "noteEditIsCentralWidget")); settings.setValue("workspace-" + workspaceIdentifier + "/windowState", - _layoutSettings->value(layoutSettingsPrefix + "windowState")); + _layoutSettings->value(layoutSettingsPrefix + "windowState")); settings.setValue("workspace-" + workspaceIdentifier + "/name", getLayoutName(layoutIdentifier)); settings.setValue( "workspace-" + workspaceIdentifier + "/noteSubFolderDockWidgetVisible", - _layoutSettings->value(layoutSettingsPrefix + - "noteSubFolderDockWidgetVisible")); + _layoutSettings->value(layoutSettingsPrefix + "noteSubFolderDockWidgetVisible")); // since a new layout is installed we later want to center and resize the // window @@ -188,7 +180,8 @@ QString LayoutWidget::getLayoutDescription(const QString &layoutIdentifier) { return tr("Most of the panels, like the note list on the left, the " "tagging panels, and only the preview panel on the right " "are enabled by default. You will need another workspace to " - "actually edit notes!","Layout description") + + "actually edit notes!", + "Layout description") + noCentralWidgetAddText; } else if (layoutIdentifier == QLatin1String("full-vertical")) { return tr("Most of the panels, like the note list on the left, the " @@ -214,8 +207,8 @@ void LayoutWidget::resizeEvent(QResizeEvent *event) { void LayoutWidget::resizeLayoutImage() const { if (ui->layoutGraphicsView->scene() != nullptr) { - ui->layoutGraphicsView->fitInView( - ui->layoutGraphicsView->scene()->sceneRect(), Qt::KeepAspectRatio); + ui->layoutGraphicsView->fitInView(ui->layoutGraphicsView->scene()->sceneRect(), + Qt::KeepAspectRatio); } } diff --git a/src/widgets/lineedit.cpp b/src/widgets/lineedit.cpp index d9378631b..fc9392210 100644 --- a/src/widgets/lineedit.cpp +++ b/src/widgets/lineedit.cpp @@ -15,9 +15,7 @@ #include <QKeyEvent> -LineEdit::LineEdit(QWidget *parent) : QLineEdit(parent) { - installEventFilter(this); -} +LineEdit::LineEdit(QWidget *parent) : QLineEdit(parent) { installEventFilter(this); } bool LineEdit::eventFilter(QObject *obj, QEvent *event) { if (event->type() == QEvent::KeyPress) { diff --git a/src/widgets/logwidget.cpp b/src/widgets/logwidget.cpp index d35f72457..87cebe624 100644 --- a/src/widgets/logwidget.cpp +++ b/src/widgets/logwidget.cpp @@ -7,9 +7,9 @@ #include <QFile> #include <QKeyEvent> #include <QMenu> +#include <QPointer> #include <QScrollBar> #include <QSettings> -#include <QPointer> #include "mainwindow.h" @@ -38,13 +38,17 @@ LogWidget::LogWidget(QWidget *parent) disconnect(ui->logTextEdit, &QMarkdownTextEdit::zoomOut, nullptr, nullptr); disconnect(ui->logTextEdit, &QOwnNotesMarkdownTextEdit::urlClicked, nullptr, nullptr); - // The order of zoomIn is opposite (in calls out and vice versa), to be consistent with other edits - connect(ui->logTextEdit, &QMarkdownTextEdit::zoomIn, this, [this]{ static_cast<QPlainTextEdit*>(ui->logTextEdit)->zoomOut(-1); }); - connect(ui->logTextEdit, &QMarkdownTextEdit::zoomOut, this, [this]{ static_cast<QPlainTextEdit*>(ui->logTextEdit)->zoomIn(-1); }); + // The order of zoomIn is opposite (in calls out and vice versa), to be consistent with other + // edits + connect(ui->logTextEdit, &QMarkdownTextEdit::zoomIn, this, + [this] { static_cast<QPlainTextEdit *>(ui->logTextEdit)->zoomOut(-1); }); + connect(ui->logTextEdit, &QMarkdownTextEdit::zoomOut, this, + [this] { static_cast<QPlainTextEdit *>(ui->logTextEdit)->zoomIn(-1); }); // we use a different context menu here, not default one disconnect(ui->logTextEdit, &QPlainTextEdit::customContextMenuRequested, nullptr, nullptr); - connect(ui->logTextEdit, &QPlainTextEdit::customContextMenuRequested, this, &LogWidget::on_logTextEdit_customContextMenuRequested); + connect(ui->logTextEdit, &QPlainTextEdit::customContextMenuRequested, this, + &LogWidget::on_logTextEdit_customContextMenuRequested); ui->buttonFrame->hide(); const QSettings settings; @@ -71,24 +75,16 @@ LogWidget::LogWidget(QWidget *parent) ui->statusCheckBox->setChecked( settings.value(QStringLiteral("LogWidget/statusLog"), true).toBool()); ui->scriptingCheckBox->setChecked( - settings.value(QStringLiteral("LogWidget/scriptingLog"), true) - .toBool()); + settings.value(QStringLiteral("LogWidget/scriptingLog"), true).toBool()); // store the settings if the dialog is closed or the checkboxes are clicked - connect(ui->debugCheckBox, &QCheckBox::clicked, this, - &LogWidget::storeSettings); - connect(ui->infoCheckBox, &QCheckBox::clicked, this, - &LogWidget::storeSettings); - connect(ui->warningCheckBox, &QCheckBox::clicked, this, - &LogWidget::storeSettings); - connect(ui->criticalCheckBox, &QCheckBox::clicked, this, - &LogWidget::storeSettings); - connect(ui->fatalCheckBox, &QCheckBox::clicked, this, - &LogWidget::storeSettings); - connect(ui->statusCheckBox, &QCheckBox::clicked, this, - &LogWidget::storeSettings); - connect(ui->scriptingCheckBox, &QCheckBox::clicked, this, - &LogWidget::storeSettings); + connect(ui->debugCheckBox, &QCheckBox::clicked, this, &LogWidget::storeSettings); + connect(ui->infoCheckBox, &QCheckBox::clicked, this, &LogWidget::storeSettings); + connect(ui->warningCheckBox, &QCheckBox::clicked, this, &LogWidget::storeSettings); + connect(ui->criticalCheckBox, &QCheckBox::clicked, this, &LogWidget::storeSettings); + connect(ui->fatalCheckBox, &QCheckBox::clicked, this, &LogWidget::storeSettings); + connect(ui->statusCheckBox, &QCheckBox::clicked, this, &LogWidget::storeSettings); + connect(ui->scriptingCheckBox, &QCheckBox::clicked, this, &LogWidget::storeSettings); ui->logTextEdit->installEventFilter(this); ui->buttonFrame->installEventFilter(this); @@ -118,20 +114,13 @@ QString LogWidget::getLogText() const { void LogWidget::storeSettings() const { #ifndef INTEGRATION_TESTS QSettings settings; - settings.setValue(QStringLiteral("LogWidget/debugLog"), - ui->debugCheckBox->isChecked()); - settings.setValue(QStringLiteral("LogWidget/infoLog"), - ui->infoCheckBox->isChecked()); - settings.setValue(QStringLiteral("LogWidget/warningLog"), - ui->warningCheckBox->isChecked()); - settings.setValue(QStringLiteral("LogWidget/criticalLog"), - ui->criticalCheckBox->isChecked()); - settings.setValue(QStringLiteral("LogWidget/fatalLog"), - ui->fatalCheckBox->isChecked()); - settings.setValue(QStringLiteral("LogWidget/statusLog"), - ui->statusCheckBox->isChecked()); - settings.setValue(QStringLiteral("LogWidget/scriptingLog"), - ui->scriptingCheckBox->isChecked()); + settings.setValue(QStringLiteral("LogWidget/debugLog"), ui->debugCheckBox->isChecked()); + settings.setValue(QStringLiteral("LogWidget/infoLog"), ui->infoCheckBox->isChecked()); + settings.setValue(QStringLiteral("LogWidget/warningLog"), ui->warningCheckBox->isChecked()); + settings.setValue(QStringLiteral("LogWidget/criticalLog"), ui->criticalCheckBox->isChecked()); + settings.setValue(QStringLiteral("LogWidget/fatalLog"), ui->fatalCheckBox->isChecked()); + settings.setValue(QStringLiteral("LogWidget/statusLog"), ui->statusCheckBox->isChecked()); + settings.setValue(QStringLiteral("LogWidget/scriptingLog"), ui->scriptingCheckBox->isChecked()); #endif } @@ -142,17 +131,14 @@ void LogWidget::log(LogWidget::LogType logType, const QString &text) { // ignore "libpng sRGB profile", "QXcbConnection: XCB error: 8" and // "QFileSystemWatcher::removePaths" warnings if (logType == WarningLogType && - (text.contains(QLatin1String( - "libpng warning: iCCP: known incorrect sRGB profile")) || + (text.contains(QLatin1String("libpng warning: iCCP: known incorrect sRGB profile")) || text.contains(QLatin1String("fromIccProfile: failed minimal tag size sanity")) || text.contains(QLatin1String("QXcbConnection: XCB error:")) || - text.contains(QLatin1String( - "Using QCharRef with an index pointing outside")) || + text.contains(QLatin1String("Using QCharRef with an index pointing outside")) || text.contains(QLatin1String("load glyph failed err=")) || text.contains(QLatin1String("[Botan Error] Invalid CBC padding")) || text.contains(QLatin1String("Invalid version or not a cyphertext")) || - text.contains(QLatin1String( - "QFileSystemWatcher::removePaths: list is empty")))) { + text.contains(QLatin1String("QFileSystemWatcher::removePaths: list is empty")))) { return; } @@ -198,8 +184,7 @@ void LogWidget::log(LogWidget::LogType logType, const QString &text) { // this is a "fix" for crashes that occur when a network goes away // and this message should be printed, I haven't managed to get // around this crash with other methods - if (text.contains(QLatin1String( - "/org/freedesktop/NetworkManager/ActiveConnection"))) { + if (text.contains(QLatin1String("/org/freedesktop/NetworkManager/ActiveConnection"))) { return; } @@ -240,16 +225,14 @@ void LogWidget::log(LogWidget::LogType logType, const QString &text) { // text.prepend("[" + dateTime.toString("hh:mm:ss") + "] [" + type + "] // "); text.append("\n"); - const QString html = - QStringLiteral("<div style=\"color: %1\">[%2] [%3] %4</div>") - .arg(color.name(), dateTime.toString(QStringLiteral("hh:mm:ss")), - type, text.toHtmlEscaped()); + const QString html = QStringLiteral("<div style=\"color: %1\">[%2] [%3] %4</div>") + .arg(color.name(), dateTime.toString(QStringLiteral("hh:mm:ss")), type, + text.toHtmlEscaped()); QScrollBar *scrollBar = ui->logTextEdit->verticalScrollBar(); // we want to scroll down later if the scrollbar is near the bottom - const bool scrollDown = - scrollBar->value() >= (scrollBar->maximum() - scrollBar->singleStep()); + const bool scrollDown = scrollBar->value() >= (scrollBar->maximum() - scrollBar->singleStep()); const QSignalBlocker blocker(ui->logTextEdit); Q_UNUSED(blocker) @@ -309,8 +292,7 @@ QString LogWidget::logTypeText(LogType logType) { /** * Custom log output */ -void LogWidget::logMessageOutput(QtMsgType type, - const QMessageLogContext &context, +void LogWidget::logMessageOutput(QtMsgType type, const QMessageLogContext &context, const QString &msg) { QByteArray localMsg = msg.toLocal8Bit(); LogType logType = LogType::DebugLogType; @@ -326,23 +308,23 @@ void LogWidget::logMessageOutput(QtMsgType type, logType = LogType::DebugLogType; break; case QtInfoMsg: - fprintf(stderr, "Info: %s (%s:%u, %s)\n", localMsg.constData(), - context.file, context.line, context.function); + fprintf(stderr, "Info: %s (%s:%u, %s)\n", localMsg.constData(), context.file, + context.line, context.function); logType = LogType::InfoLogType; break; case QtWarningMsg: - fprintf(stderr, "Warning: %s (%s:%u, %s)\n", localMsg.constData(), - context.file, context.line, context.function); + fprintf(stderr, "Warning: %s (%s:%u, %s)\n", localMsg.constData(), context.file, + context.line, context.function); logType = LogType::WarningLogType; break; case QtCriticalMsg: - fprintf(stderr, "Critical: %s (%s:%u, %s)\n", localMsg.constData(), - context.file, context.line, context.function); + fprintf(stderr, "Critical: %s (%s:%u, %s)\n", localMsg.constData(), context.file, + context.line, context.function); logType = LogType::CriticalLogType; break; case QtFatalMsg: - fprintf(stderr, "Fatal: %s (%s:%u, %s)\n", localMsg.constData(), - context.file, context.line, context.function); + fprintf(stderr, "Fatal: %s (%s:%u, %s)\n", localMsg.constData(), context.file, + context.line, context.function); logType = LogType::FatalLogType; } @@ -350,7 +332,8 @@ void LogWidget::logMessageOutput(QtMsgType type, if (s_logWidget) { // Use auto connection to handle the case if a message is coming in from a different thread. - QMetaObject::invokeMethod(s_logWidget, "log", Qt::AutoConnection, Q_ARG(LogWidget::LogType, logType), Q_ARG(QString, msg)); + QMetaObject::invokeMethod(s_logWidget, "log", Qt::AutoConnection, + Q_ARG(LogWidget::LogType, logType), Q_ARG(QString, msg)); } #else @@ -373,16 +356,14 @@ void LogWidget::logToFileIfAllowed(LogType logType, const QString &msg) { QSettings settings; if (settings.value(QStringLiteral("Debug/fileLogging")).toBool()) { QFile logFile(Utils::Misc::logFilePath()); - if (logFile.open(QIODevice::WriteOnly | QIODevice::Text | - QIODevice::Append)) { + if (logFile.open(QIODevice::WriteOnly | QIODevice::Text | QIODevice::Append)) { QTextStream out(&logFile); QDateTime dateTime = QDateTime::currentDateTime(); QString typeStr = logTypeText(logType); - QString text = - QStringLiteral("[%1] [%2]: %3\n") - .arg(dateTime.toString(QStringLiteral("MMM dd hh:mm:ss")) - .remove(QStringLiteral(".")), - typeStr, msg); + QString text = QStringLiteral("[%1] [%2]: %3\n") + .arg(dateTime.toString(QStringLiteral("MMM dd hh:mm:ss")) + .remove(QStringLiteral(".")), + typeStr, msg); out << text; logFile.close(); } @@ -410,8 +391,7 @@ void LogWidget::on_logTextEdit_customContextMenuRequested(QPoint pos) { menu->addSeparator(); - QString actionText = - ui->buttonFrame->isHidden() ? tr("Show options") : tr("Hide options"); + QString actionText = ui->buttonFrame->isHidden() ? tr("Show options") : tr("Hide options"); QAction *toggleOptionsAction = menu->addAction(actionText); QAction *clearLogAction = menu->addAction(tr("Clear log")); diff --git a/src/widgets/logwidget.h b/src/widgets/logwidget.h index 913623356..836e050e9 100644 --- a/src/widgets/logwidget.h +++ b/src/widgets/logwidget.h @@ -38,8 +38,7 @@ class LogWidget : public QFrame { explicit LogWidget(QWidget *parent = 0); ~LogWidget(); - static void logMessageOutput(QtMsgType type, - const QMessageLogContext &context, + static void logMessageOutput(QtMsgType type, const QMessageLogContext &context, const QString &msg); bool eventFilter(QObject *obj, QEvent *event) override; QString getLogText() const; diff --git a/src/widgets/navigationwidget.cpp b/src/widgets/navigationwidget.cpp index c3a01b162..05fce96ad 100644 --- a/src/widgets/navigationwidget.cpp +++ b/src/widgets/navigationwidget.cpp @@ -21,22 +21,19 @@ #include <QTextDocument> #include <QTreeWidgetItem> -NavigationWidget::NavigationWidget(QWidget *parent) - : QTreeWidget(parent) { +NavigationWidget::NavigationWidget(QWidget *parent) : QTreeWidget(parent) { // we want to handle currentItemChanged because it also works with the keyboard QObject::connect(this, &NavigationWidget::currentItemChanged, this, &NavigationWidget::onCurrentItemChanged); // we want to handle itemClicked because it allows to click on an item a 2nd time - QObject::connect(this, &NavigationWidget::itemClicked, this, - &NavigationWidget::onItemClicked); + QObject::connect(this, &NavigationWidget::itemClicked, this, &NavigationWidget::onItemClicked); } /** * Emits the positionClicked signal to jump to the changed navigation item's * position */ -void NavigationWidget::onCurrentItemChanged(QTreeWidgetItem *current, - QTreeWidgetItem *previous) { +void NavigationWidget::onCurrentItemChanged(QTreeWidgetItem *current, QTreeWidgetItem *previous) { Q_UNUSED(previous) if (current == nullptr) { @@ -72,14 +69,12 @@ void NavigationWidget::parse(const QTextDocument *document, int textCursorPositi doParse(); } -void NavigationWidget::doParse() -{ +void NavigationWidget::doParse() { const auto nodes = parseDocument(_doc); buildNavTree(nodes); } -QVector<Node> NavigationWidget::parseDocument( - const QTextDocument *const document) { +QVector<Node> NavigationWidget::parseDocument(const QTextDocument *const document) { QVector<Node> nodes; for (int i = 0; i < document->blockCount(); ++i) { const QTextBlock block = document->findBlockByNumber(i); @@ -89,8 +84,7 @@ QVector<Node> NavigationWidget::parseDocument( const int elementType = block.userState(); // ignore all non headline types - if ((elementType < MarkdownHighlighter::H1) || - (elementType > MarkdownHighlighter::H6)) { + if ((elementType < MarkdownHighlighter::H1) || (elementType > MarkdownHighlighter::H6)) { continue; } static const QRegularExpression re(QStringLiteral("^#+\\s+")); @@ -105,8 +99,7 @@ QVector<Node> NavigationWidget::parseDocument( return nodes; } -void NavigationWidget::selectItemForCursorPosition(int position) -{ +void NavigationWidget::selectItemForCursorPosition(int position) { int itemIndex = findItemIndexforCursorPosition(position); QTreeWidgetItem *itemToSelect{nullptr}; @@ -120,21 +113,16 @@ void NavigationWidget::selectItemForCursorPosition(int position) setCurrentItem(itemToSelect); } - -int NavigationWidget::findItemIndexforCursorPosition(int position) const -{ - auto fwdIt = std::lower_bound(_navigationTreeNodes.begin(), - _navigationTreeNodes.end(), - position, - [](const Node &node, int position){return node.pos <= position;}); +int NavigationWidget::findItemIndexforCursorPosition(int position) const { + auto fwdIt = + std::lower_bound(_navigationTreeNodes.begin(), _navigationTreeNodes.end(), position, + [](const Node &node, int position) { return node.pos <= position; }); return fwdIt - std::begin(_navigationTreeNodes) - 1; } void NavigationWidget::buildNavTree(const QVector<Node> &nodes) { - - if (_navigationTreeNodes == nodes) - return; + if (_navigationTreeNodes == nodes) return; _navigationTreeNodes = std::move(nodes); @@ -148,9 +136,7 @@ void NavigationWidget::buildNavTree(const QVector<Node> &nodes) { auto *item = new QTreeWidgetItem(); item->setText(0, node.text); item->setData(0, Qt::UserRole, pos); - item->setToolTip( - 0, - tr("headline %1").arg(elementType - MarkdownHighlighter::H1 + 1)); + item->setToolTip(0, tr("headline %1").arg(elementType - MarkdownHighlighter::H1 + 1)); // attempt to find a suitable parent item for the element type QTreeWidgetItem *lastHigherItem = findSuitableParentItem(elementType); @@ -174,8 +160,7 @@ void NavigationWidget::buildNavTree(const QVector<Node> &nodes) { /** * Attempts to find a suitable parent item for the element type */ -QTreeWidgetItem *NavigationWidget::findSuitableParentItem( - int elementType) const { +QTreeWidgetItem *NavigationWidget::findSuitableParentItem(int elementType) const { --elementType; auto lastHigherItem = _lastHeadingItemList.value(elementType); diff --git a/src/widgets/navigationwidget.h b/src/widgets/navigationwidget.h index 6b55a9cfd..4ab9df94e 100644 --- a/src/widgets/navigationwidget.h +++ b/src/widgets/navigationwidget.h @@ -25,8 +25,7 @@ struct Node { int elementType; bool operator==(const Node &node) const { - return text == node.text && pos == node.pos && - elementType == node.elementType; + return text == node.text && pos == node.pos && elementType == node.elementType; } }; @@ -42,8 +41,7 @@ class NavigationWidget : public QTreeWidget { void selectItemForCursorPosition(int position); private slots: - void onCurrentItemChanged(QTreeWidgetItem *current, - QTreeWidgetItem *previous); + void onCurrentItemChanged(QTreeWidgetItem *current, QTreeWidgetItem *previous); void onItemClicked(QTreeWidgetItem *current, int column); private: diff --git a/src/widgets/notefolderlistwidget.cpp b/src/widgets/notefolderlistwidget.cpp index bf1ca9899..a6d96fc92 100644 --- a/src/widgets/notefolderlistwidget.cpp +++ b/src/widgets/notefolderlistwidget.cpp @@ -15,9 +15,7 @@ #include <entities/notefolder.h> -NoteFolderListWidget::NoteFolderListWidget(QWidget *parent) { - Q_UNUSED(parent); -} +NoteFolderListWidget::NoteFolderListWidget(QWidget *parent) { Q_UNUSED(parent); } void NoteFolderListWidget::dropEvent(QDropEvent *e) { // finish the move event diff --git a/src/widgets/notepreviewwidget.cpp b/src/widgets/notepreviewwidget.cpp index 9cc86b158..4d6c039f2 100644 --- a/src/widgets/notepreviewwidget.cpp +++ b/src/widgets/notepreviewwidget.cpp @@ -24,12 +24,12 @@ #include <QMovie> #include <QProxyStyle> #include <QRegularExpression> + #include "utils/misc.h" class NoDottedOutlineForLinksStyle : public QProxyStyle { public: - int styleHint(StyleHint hint, const QStyleOption *option, - const QWidget *widget, + int styleHint(StyleHint hint, const QStyleOption *option, const QWidget *widget, QStyleHintReturn *returnData) const Q_DECL_OVERRIDE { if (hint == SH_TextControl_FocusIndicatorTextCharFormat) return 0; return QProxyStyle::styleHint(hint, option, widget, returnData); @@ -81,8 +81,7 @@ bool NotePreviewWidget::eventFilter(QObject *obj, QEvent *event) { _searchWidget->activate(); return true; } else if ((keyEvent->key() == Qt::Key_F3)) { - _searchWidget->doSearch( - !keyEvent->modifiers().testFlag(Qt::ShiftModifier)); + _searchWidget->doSearch(!keyEvent->modifiers().testFlag(Qt::ShiftModifier)); return true; } @@ -98,16 +97,15 @@ bool NotePreviewWidget::eventFilter(QObject *obj, QEvent *event) { * @return Urls to gif files */ QStringList NotePreviewWidget::extractGifUrls(const QString &text) const { - QSet<QString> urlSet; - static const QRegularExpression regex(R"(<img[^>]+src=\"(file:\/\/\/[^\"]+\.gif)\")", QRegularExpression::CaseInsensitiveOption); + static const QRegularExpression regex(R"(<img[^>]+src=\"(file:\/\/\/[^\"]+\.gif)\")", + QRegularExpression::CaseInsensitiveOption); int pos = 0; while (true) { QRegularExpressionMatch match; pos = text.indexOf(regex, pos, &match); - if (pos == -1 || !match.hasMatch()) - break; + if (pos == -1 || !match.hasMatch()) break; QString url = match.captured(1); urlSet.insert(url); pos += match.capturedLength(); @@ -156,8 +154,7 @@ void NotePreviewWidget::animateGif(const QString &text) { connect(movie, &QMovie::frameChanged, this, [this, url, movie](int) { if (auto doc = document()) { - doc->addResource(QTextDocument::ImageResource, url, - movie->currentPixmap()); + doc->addResource(QTextDocument::ImageResource, url, movie->currentPixmap()); doc->markContentsDirty(0, doc->characterCount()); } }); @@ -177,9 +174,7 @@ void NotePreviewWidget::setHtml(const QString &text) { * @brief Returns the searchWidget instance * @return */ -QTextEditSearchWidget *NotePreviewWidget::searchWidget() { - return _searchWidget; -} +QTextEditSearchWidget *NotePreviewWidget::searchWidget() { return _searchWidget; } /** * Uses another widget as parent for the search widget @@ -241,31 +236,27 @@ void NotePreviewWidget::contextMenuEvent(QContextMenuEvent *event) { copyImageAction = menu->addAction(tr("Copy image file path")); auto *copyImageClipboardAction = menu->addAction(tr("Copy image to clipboard")); - connect(copyImageClipboardAction, &QAction::triggered, this, - [format]() { - QString imagePath = format.toImageFormat().name(); - QUrl imageUrl = QUrl(imagePath); - QClipboard *clipboard = QApplication::clipboard(); - if (imageUrl.isLocalFile()) { - clipboard->setImage(QImage(imageUrl.toLocalFile())); - } else if (imagePath.startsWith( - QLatin1String("data:image/"), Qt::CaseInsensitive)) { - QStringList parts = imagePath.split( - QStringLiteral(";base64,")); - if (parts.count() == 2) { - clipboard->setImage(QImage::fromData( - QByteArray::fromBase64(parts[1].toLatin1()))); - } - } - }); + connect(copyImageClipboardAction, &QAction::triggered, this, [format]() { + QString imagePath = format.toImageFormat().name(); + QUrl imageUrl = QUrl(imagePath); + QClipboard *clipboard = QApplication::clipboard(); + if (imageUrl.isLocalFile()) { + clipboard->setImage(QImage(imageUrl.toLocalFile())); + } else if (imagePath.startsWith(QLatin1String("data:image/"), Qt::CaseInsensitive)) { + QStringList parts = imagePath.split(QStringLiteral(";base64,")); + if (parts.count() == 2) { + clipboard->setImage( + QImage::fromData(QByteArray::fromBase64(parts[1].toLatin1()))); + } + } + }); } if (isAnchor) { copyLinkLocationAction = menu->addAction(tr("Copy link location")); } - auto *htmlFileExportAction = - menu->addAction(tr("Export generated raw HTML")); + auto *htmlFileExportAction = menu->addAction(tr("Export generated raw HTML")); QAction *selectedItem = menu->exec(globalPos); @@ -294,8 +285,7 @@ void NotePreviewWidget::contextMenuEvent(QContextMenuEvent *event) { } } -QVariant NotePreviewWidget::loadResource(int type, const QUrl &file) -{ +QVariant NotePreviewWidget::loadResource(int type, const QUrl &file) { if (type == QTextDocument::ImageResource && file.isValid()) { QString fileName = file.toLocalFile(); int fileSize = QFileInfo(fileName).size(); @@ -316,24 +306,19 @@ QVariant NotePreviewWidget::loadResource(int type, const QUrl &file) return QTextBrowser::loadResource(type, file); } -bool NotePreviewWidget::lookupCache(const QString &key, QPixmap &pm) -{ - auto it = std::find_if(_largePixmapCache.begin(), _largePixmapCache.end(), [key](const LargePixmap& l) { - return key == l.fileName; - }); - if (it == _largePixmapCache.end()) - return false; +bool NotePreviewWidget::lookupCache(const QString &key, QPixmap &pm) { + auto it = std::find_if(_largePixmapCache.begin(), _largePixmapCache.end(), + [key](const LargePixmap &l) { return key == l.fileName; }); + if (it == _largePixmapCache.end()) return false; pm = it->pixmap; return true; } -void NotePreviewWidget::insertInCache(const QString &key, const QPixmap &pm) -{ +void NotePreviewWidget::insertInCache(const QString &key, const QPixmap &pm) { _largePixmapCache.push_back({key, std::move(pm)}); // limit to 6 images - while (_largePixmapCache.size() > 6) - _largePixmapCache.erase(_largePixmapCache.begin()); + while (_largePixmapCache.size() > 6) _largePixmapCache.erase(_largePixmapCache.begin()); } void NotePreviewWidget::exportAsHTMLFile() { @@ -341,7 +326,10 @@ void NotePreviewWidget::exportAsHTMLFile() { dialog.setFileMode(QFileDialog::AnyFile); dialog.setAcceptMode(QFileDialog::AcceptSave); dialog.setNameFilter(tr("HTML files") + " (*.html)"); - dialog.setWindowTitle(tr("Export preview as raw HTML file", "\"Raw\" means that actually the html that was fed to the preview will be stored (the QTextBrowser modifies the html that it is showing)")); + dialog.setWindowTitle( + tr("Export preview as raw HTML file", + "\"Raw\" means that actually the html that was fed to the preview will be stored (the " + "QTextBrowser modifies the html that it is showing)")); dialog.selectFile(QStringLiteral("preview.html")); int ret = dialog.exec(); diff --git a/src/widgets/notepreviewwidget.h b/src/widgets/notepreviewwidget.h index 27ac74464..cb6de717c 100644 --- a/src/widgets/notepreviewwidget.h +++ b/src/widgets/notepreviewwidget.h @@ -44,7 +44,7 @@ class NotePreviewWidget : public QTextBrowser { void contextMenuEvent(QContextMenuEvent *event) override; - QVariant loadResource(int type, const QUrl& file) override; + QVariant loadResource(int type, const QUrl &file) override; bool lookupCache(const QString &key, QPixmap &pm); void insertInCache(const QString &key, const QPixmap &pm); diff --git a/src/widgets/notesubfoldertree.cpp b/src/widgets/notesubfoldertree.cpp index ff60044df..4bef130e4 100644 --- a/src/widgets/notesubfoldertree.cpp +++ b/src/widgets/notesubfoldertree.cpp @@ -1,20 +1,18 @@ #include "notesubfoldertree.h" -#include "entities/notesubfolder.h" + +#include <QHeaderView> +#include <QMenu> +#include <QSettings> +#include <memory> + #include "entities/notefolder.h" +#include "entities/notesubfolder.h" #include "entities/tag.h" #include "mainwindow.h" #include "utils/gui.h" -#include <QSettings> -#include <QHeaderView> -#include <QMenu> - -#include <memory> - -NoteSubFolderTree::NoteSubFolderTree(QWidget *parent) - : QTreeWidget(parent) -{ - QTimer::singleShot(1, this, [this](){ +NoteSubFolderTree::NoteSubFolderTree(QWidget *parent) : QTreeWidget(parent) { + QTimer::singleShot(1, this, [this]() { header()->setSectionResizeMode(0, QHeaderView::ResizeToContents); header()->setSectionResizeMode(1, QHeaderView::ResizeToContents); }); @@ -23,18 +21,18 @@ NoteSubFolderTree::NoteSubFolderTree(QWidget *parent) initConnections(); } -void NoteSubFolderTree::initConnections() -{ +void NoteSubFolderTree::initConnections() { connect(this, &QTreeWidget::itemExpanded, this, &NoteSubFolderTree::onItemExpanded); connect(this, &QTreeWidget::itemCollapsed, this, &NoteSubFolderTree::onItemExpanded); - connect(this, &QTreeWidget::customContextMenuRequested, this, &NoteSubFolderTree::onContextMenuRequested); + connect(this, &QTreeWidget::customContextMenuRequested, this, + &NoteSubFolderTree::onContextMenuRequested); connect(this, &QTreeWidget::itemChanged, this, &NoteSubFolderTree::onItemChanged); connect(this, &QTreeWidget::currentItemChanged, this, &NoteSubFolderTree::onCurrentItemChanged); - connect(this, &QTreeWidget::itemSelectionChanged, this, &NoteSubFolderTree::onItemSelectionChanged); + connect(this, &QTreeWidget::itemSelectionChanged, this, + &NoteSubFolderTree::onItemSelectionChanged); } -static QTreeWidgetItem *noteItem(const Note ¬e) -{ +static QTreeWidgetItem *noteItem(const Note ¬e) { const QString name = note.getName(); if (name.isEmpty()) { qWarning() << "Unexpected note with no name: " << note.getFileName(); @@ -60,10 +58,8 @@ static QTreeWidgetItem *noteItem(const Note ¬e) return noteItem; } -void NoteSubFolderTree::buildTreeForParentItem(QTreeWidgetItem *parent) -{ - const int parentId = - parent == nullptr ? 0 : parent->data(0, Qt::UserRole).toInt(); +void NoteSubFolderTree::buildTreeForParentItem(QTreeWidgetItem *parent) { + const int parentId = parent == nullptr ? 0 : parent->data(0, Qt::UserRole).toInt(); const int activeNoteSubFolderId = NoteSubFolder::activeNoteSubFolderId(); const bool isCurrentNoteTreeEnabled = NoteFolder::isCurrentNoteTreeEnabled(); @@ -77,7 +73,7 @@ void NoteSubFolderTree::buildTreeForParentItem(QTreeWidgetItem *parent) // load all notes of the subfolder and add them to the note list // widget const QVector<Note> noteList = Note::fetchAllByNoteSubFolderId(noteSubFolder.getId()); - QList<QTreeWidgetItem*> noteItems; + QList<QTreeWidgetItem *> noteItems; noteItems.reserve(noteList.size()); for (const auto ¬e : noteList) { noteItems << noteItem(note); @@ -99,21 +95,18 @@ void NoteSubFolderTree::buildTreeForParentItem(QTreeWidgetItem *parent) // sort alphabetically, if necessary QSettings settings; - const int sort = - settings.value(QStringLiteral("noteSubfoldersPanelSort")).toInt(); + const int sort = settings.value(QStringLiteral("noteSubfoldersPanelSort")).toInt(); if (sort == SORT_ALPHABETICAL) { item->sortChildren( - 0, - Utils::Gui::toQtOrder( - settings.value(QStringLiteral("noteSubfoldersPanelOrder")) - .toInt())); + 0, Utils::Gui::toQtOrder( + settings.value(QStringLiteral("noteSubfoldersPanelOrder")).toInt())); } } // add the notes of the note folder root if (parentId == 0 && isCurrentNoteTreeEnabled) { const QVector<Note> noteList = Note::fetchAllByNoteSubFolderId(0); - QList<QTreeWidgetItem*> noteItems; + QList<QTreeWidgetItem *> noteItems; noteItems.reserve(noteList.size()); for (const auto ¬e : noteList) { noteItems << noteItem(note); @@ -127,18 +120,14 @@ void NoteSubFolderTree::buildTreeForParentItem(QTreeWidgetItem *parent) } } -QTreeWidgetItem *NoteSubFolderTree::addNoteSubFolder(QTreeWidgetItem *parentItem, const NoteSubFolder ¬eSubFolder) -{ +QTreeWidgetItem *NoteSubFolderTree::addNoteSubFolder(QTreeWidgetItem *parentItem, + const NoteSubFolder ¬eSubFolder) { const int id = noteSubFolder.getId(); const QString name = noteSubFolder.getName(); QSettings settings; const int linkCount = Note::countByNoteSubFolderId( - id, - settings - .value(QStringLiteral("noteSubfoldersPanelShowNotesRecursively")) - .toBool()); - QString toolTip = tr("show notes in folder '%1' (%2)") - .arg(name, QString::number(linkCount)); + id, settings.value(QStringLiteral("noteSubfoldersPanelShowNotesRecursively")).toBool()); + QString toolTip = tr("show notes in folder '%1' (%2)").arg(name, QString::number(linkCount)); auto *item = new QTreeWidgetItem(); item->setText(0, name); @@ -160,29 +149,26 @@ QTreeWidgetItem *NoteSubFolderTree::addNoteSubFolder(QTreeWidgetItem *parentItem return item; } -void NoteSubFolderTree::reload() -{ +void NoteSubFolderTree::reload() { qDebug() << __func__; clear(); const int activeNoteSubFolderId = NoteSubFolder::activeNoteSubFolderId(); - const bool showAllNotesItem = - !NoteSubFolder::isNoteSubfoldersPanelShowNotesRecursively(); + const bool showAllNotesItem = !NoteSubFolder::isNoteSubfoldersPanelShowNotesRecursively(); auto *allItem = new QTreeWidgetItem(); // add the "all notes" item if (showAllNotesItem) { int linkCount = Note::countAll(); - QString toolTip = tr("Show notes from all note subfolders (%1)") - .arg(QString::number(linkCount)); + QString toolTip = + tr("Show notes from all note subfolders (%1)").arg(QString::number(linkCount)); allItem->setText(0, tr("All notes")); allItem->setData(0, Qt::UserRole, -1); allItem->setToolTip(0, toolTip); allItem->setIcon( - 0, QIcon::fromTheme( - QStringLiteral("edit-copy"), - QIcon(QStringLiteral( - ":icons/breeze-qownnotes/16x16/edit-copy.svg")))); + 0, + QIcon::fromTheme(QStringLiteral("edit-copy"), + QIcon(QStringLiteral(":icons/breeze-qownnotes/16x16/edit-copy.svg")))); allItem->setForeground(1, QColor(Qt::gray)); allItem->setText(1, QString::number(linkCount)); allItem->setToolTip(1, toolTip); @@ -192,20 +178,15 @@ void NoteSubFolderTree::reload() // add the "note folder" item QSettings settings; const int linkCount = Note::countByNoteSubFolderId( - 0, settings - .value(QStringLiteral("noteSubfoldersPanelShowNotesRecursively")) - .toBool()); - const QString toolTip = tr("Show notes in note root folder (%1)") - .arg(QString::number(linkCount)); + 0, settings.value(QStringLiteral("noteSubfoldersPanelShowNotesRecursively")).toBool()); + const QString toolTip = + tr("Show notes in note root folder (%1)").arg(QString::number(linkCount)); auto *item = new QTreeWidgetItem(); - if (settings.value(QStringLiteral("noteSubfoldersPanelShowRootFolderName")) - .toBool()) { + if (settings.value(QStringLiteral("noteSubfoldersPanelShowRootFolderName")).toBool()) { item->setText( 0, NoteFolder::currentRootFolderName( - settings - .value(QStringLiteral("noteSubfoldersPanelShowFullPath")) - .toBool())); + settings.value(QStringLiteral("noteSubfoldersPanelShowFullPath")).toBool())); } else { item->setText(0, tr("Note folder")); } @@ -216,8 +197,7 @@ void NoteSubFolderTree::reload() item->setText(1, QString::number(linkCount)); item->setToolTip(1, toolTip); - if (settings.value(QStringLiteral("noteSubfoldersPanelDisplayAsFullTree")) - .toBool()) { + if (settings.value(QStringLiteral("noteSubfoldersPanelDisplayAsFullTree")).toBool()) { if (showAllNotesItem) { // add 'All Notes' addTopLevelItem(allItem); @@ -227,18 +207,16 @@ void NoteSubFolderTree::reload() addTopLevelItem(item); // add all note sub folders recursively as items - buildTreeForParentItem(item); + buildTreeForParentItem(item); if (item->childCount() > 0) { item->setExpanded(true); - if (settings.value(QStringLiteral("noteSubfoldersPanelSort")) - .toInt() == SORT_ALPHABETICAL) { + if (settings.value(QStringLiteral("noteSubfoldersPanelSort")).toInt() == + SORT_ALPHABETICAL) { item->sortChildren( - 0, Utils::Gui::toQtOrder(settings - .value(QStringLiteral( - "noteSubfoldersPanelOrder")) - .toInt())); + 0, Utils::Gui::toQtOrder( + settings.value(QStringLiteral("noteSubfoldersPanelOrder")).toInt())); } } } else { // the less hierarchical view @@ -250,11 +228,8 @@ void NoteSubFolderTree::reload() // sort the widget if (settings.value(QStringLiteral("noteSubfoldersPanelSort")).toInt() == SORT_ALPHABETICAL) { - sortItems( - 0, - Utils::Gui::toQtOrder( - settings.value(QStringLiteral("noteSubfoldersPanelOrder")) - .toInt())); + sortItems(0, Utils::Gui::toQtOrder( + settings.value(QStringLiteral("noteSubfoldersPanelOrder")).toInt())); } if (showAllNotesItem) { @@ -282,8 +257,7 @@ void NoteSubFolderTree::onItemExpanded(QTreeWidgetItem *item) { } } -QMenu *NoteSubFolderTree::contextMenu(QTreeWidget *parent) -{ +QMenu *NoteSubFolderTree::contextMenu(QTreeWidget *parent) { QMenu *menu = new QMenu(parent); auto *mainWindow = MainWindow::instance(); @@ -292,33 +266,30 @@ QMenu *NoteSubFolderTree::contextMenu(QTreeWidget *parent) menu->addAction(mainWindow->newNoteAction()); QAction *newAction = menu->addAction(tr("New subfolder")); - connect(newAction, &QAction::triggered, parent, [](){ - MainWindow::instance()->createNewNoteSubFolder(); - }); + connect(newAction, &QAction::triggered, parent, + []() { MainWindow::instance()->createNewNoteSubFolder(); }); QAction *renameAction(nullptr); QAction *removeAction(nullptr); if (NoteFolder::currentNoteFolder().getActiveNoteSubFolder().isFetched()) { renameAction = menu->addAction(tr("Rename subfolder")); - connect(renameAction, &QAction::triggered, [parent](){ + connect(renameAction, &QAction::triggered, [parent]() { QTreeWidgetItem *item = parent->currentItem(); // rename folder parent->editItem(item); }); removeAction = menu->addAction(tr("Remove selected folders")); - connect(removeAction, &QAction::triggered, parent, [parent](){ + connect(removeAction, &QAction::triggered, parent, [parent]() { // remove folders removeSelectedNoteSubFolders(parent); }); } - QAction *showInFileManagerAction = - menu->addAction(tr("Show folder in file manager")); - connect(showInFileManagerAction, &QAction::triggered, parent, [](){ - NoteSubFolder noteSubFolder = - NoteFolder::currentNoteFolder().getActiveNoteSubFolder(); + QAction *showInFileManagerAction = menu->addAction(tr("Show folder in file manager")); + connect(showInFileManagerAction, &QAction::triggered, parent, []() { + NoteSubFolder noteSubFolder = NoteFolder::currentNoteFolder().getActiveNoteSubFolder(); // show the current folder in the file manager Utils::Misc::openPath(noteSubFolder.fullPath()); @@ -329,8 +300,7 @@ QMenu *NoteSubFolderTree::contextMenu(QTreeWidget *parent) return menu; } -void NoteSubFolderTree::onContextMenuRequested(QPoint pos) -{ +void NoteSubFolderTree::onContextMenuRequested(QPoint pos) { std::unique_ptr<QMenu> menu(contextMenu(this)); menu->exec(mapToGlobal(pos)); } @@ -347,7 +317,8 @@ void NoteSubFolderTree::removeSelectedNoteSubFolders(QTreeWidget *parent) { QStringList noteSubFolderPathList; QVector<NoteSubFolder> noteSubFolderList; for (QTreeWidgetItem *item : selectedItems) { - if (item->data(0, Qt::UserRole + 1).toInt() != MainWindow::NoteTreeWidgetItemType::FolderType) { + if (item->data(0, Qt::UserRole + 1).toInt() != + MainWindow::NoteTreeWidgetItemType::FolderType) { continue; } @@ -365,21 +336,20 @@ void NoteSubFolderTree::removeSelectedNoteSubFolders(QTreeWidget *parent) { auto *mainWindow = MainWindow::instance(); - if (Utils::Gui::question( - parent, tr("Remove selected folders"), - tr("Remove <strong>%n</strong> selected folder(s)?" - "<ul><li>%1</li></ul>" - "All files and folders in these folders will be removed as" - " well!", - "", selectedItemsCount) - .arg(noteSubFolderPathList.join(QStringLiteral("</li><li>"))), - QStringLiteral("remove-folders")) == QMessageBox::Yes) { + if (Utils::Gui::question(parent, tr("Remove selected folders"), + tr("Remove <strong>%n</strong> selected folder(s)?" + "<ul><li>%1</li></ul>" + "All files and folders in these folders will be removed as" + " well!", + "", selectedItemsCount) + .arg(noteSubFolderPathList.join(QStringLiteral("</li><li>"))), + QStringLiteral("remove-folders")) == QMessageBox::Yes) { // delete the note subfolders for (const auto ¬eSubFolder : Utils::asConst(noteSubFolderList)) { // remove the directory recursively from the file system if (noteSubFolder.removeFromFileSystem()) { - mainWindow->showStatusBarMessage(tr("Removed note subfolder: %1") - .arg(noteSubFolder.fullPath())); + mainWindow->showStatusBarMessage( + tr("Removed note subfolder: %1").arg(noteSubFolder.fullPath())); } } @@ -413,8 +383,7 @@ void NoteSubFolderTree::onCurrentItemChanged(QTreeWidgetItem *current, QTreeWidg Q_EMIT currentSubFolderChanged(); } -void NoteSubFolderTree::renameSubFolder(QTreeWidgetItem *item) -{ +void NoteSubFolderTree::renameSubFolder(QTreeWidgetItem *item) { Q_ASSERT(item); onItemChanged(item, 0); } @@ -426,8 +395,7 @@ void NoteSubFolderTree::onItemChanged(QTreeWidgetItem *item, int column) { return; } - NoteSubFolder noteSubFolder = - NoteSubFolder::fetch(item->data(0, Qt::UserRole).toInt()); + NoteSubFolder noteSubFolder = NoteSubFolder::fetch(item->data(0, Qt::UserRole).toInt()); if (noteSubFolder.isFetched()) { const QString name = item->text(0); @@ -455,8 +423,7 @@ void NoteSubFolderTree::onItemChanged(QTreeWidgetItem *item, int column) { } } -void NoteSubFolderTree::onItemSelectionChanged() -{ +void NoteSubFolderTree::onItemSelectionChanged() { if (selectedItems().size() > 1) { Q_EMIT multipleSubfoldersSelected(); } diff --git a/src/widgets/notesubfoldertree.h b/src/widgets/notesubfoldertree.h index 79cf6721a..40f6b3b65 100644 --- a/src/widgets/notesubfoldertree.h +++ b/src/widgets/notesubfoldertree.h @@ -7,7 +7,7 @@ class Note; class NoteSubFolderTree : public QTreeWidget { Q_OBJECT -public: + public: NoteSubFolderTree(QWidget *parent = nullptr); void renameSubFolder(QTreeWidgetItem *item); @@ -21,7 +21,7 @@ public: static QMenu *contextMenu(QTreeWidget *parent); -private Q_SLOTS: + private Q_SLOTS: void onItemExpanded(QTreeWidgetItem *item); void onContextMenuRequested(QPoint pos); void onCurrentItemChanged(QTreeWidgetItem *current, QTreeWidgetItem *previous); @@ -30,11 +30,12 @@ private Q_SLOTS: static void removeSelectedNoteSubFolders(QTreeWidget *treeWidget); -Q_SIGNALS: + Q_SIGNALS: void currentSubFolderChanged(); void multipleSubfoldersSelected(); -private: + private: void initConnections(); - QTreeWidgetItem *addNoteSubFolder(QTreeWidgetItem *parentItem, const NoteSubFolder ¬eSubFolder); + QTreeWidgetItem *addNoteSubFolder(QTreeWidgetItem *parentItem, + const NoteSubFolder ¬eSubFolder); }; diff --git a/src/widgets/qownnotesmarkdowntextedit.cpp b/src/widgets/qownnotesmarkdowntextedit.cpp index 07872763d..fe8fac89d 100644 --- a/src/widgets/qownnotesmarkdowntextedit.cpp +++ b/src/widgets/qownnotesmarkdowntextedit.cpp @@ -4,24 +4,24 @@ #include <utils/misc.h> #include <utils/schema.h> +#include <QApplication> +#include <QClipboard> #include <QDebug> #include <QFont> #include <QFontDatabase> +#include <QJSEngine> #include <QMenu> #include <QMimeData> #include <QRegularExpression> #include <QSettings> #include <QTextCursor> #include <QTextDocumentFragment> -#include <QJSEngine> -#include <QApplication> -#include <QClipboard> -#include "services/scriptingservice.h" #include "entities/notefolder.h" #include "helpers/qownspellchecker.h" -#include "mainwindow.h" #include "libraries/qmarkdowntextedit/linenumberarea.h" +#include "mainwindow.h" +#include "services/scriptingservice.h" #include "utils/urlhandler.h" QOwnNotesMarkdownTextEdit::QOwnNotesMarkdownTextEdit(QWidget *parent) @@ -39,13 +39,10 @@ QOwnNotesMarkdownTextEdit::QOwnNotesMarkdownTextEdit(QWidget *parent) QSettings settings; MarkdownHighlighter::HighlightingOptions options; - if (settings.value(QStringLiteral("fullyHighlightedBlockquotes")) - .toBool()) { - options |= MarkdownHighlighter::HighlightingOption :: - FullyHighlightedBlockQuote; + if (settings.value(QStringLiteral("fullyHighlightedBlockquotes")).toBool()) { + options |= MarkdownHighlighter::HighlightingOption ::FullyHighlightedBlockQuote; } - if (settings.value(QStringLiteral("MainWindow/noteTextView.underline")) - .toBool()) { + if (settings.value(QStringLiteral("MainWindow/noteTextView.underline")).toBool()) { options |= MarkdownHighlighter::HighlightingOption ::Underline; } @@ -62,14 +59,10 @@ QOwnNotesMarkdownTextEdit::QOwnNotesMarkdownTextEdit(QWidget *parent) // ignores note clicks in QMarkdownTextEdit in the note text edit setIgnoredClickUrlSchemata(QStringList({"note", "task"})); - connect(this, &QOwnNotesMarkdownTextEdit::zoomIn, this, [this](){ - onZoom(/*in=*/ true); - }); - connect(this, &QOwnNotesMarkdownTextEdit::zoomOut, this, [this](){ - onZoom(/*in=*/ false); - }); + connect(this, &QOwnNotesMarkdownTextEdit::zoomIn, this, [this]() { onZoom(/*in=*/true); }); + connect(this, &QOwnNotesMarkdownTextEdit::zoomOut, this, [this]() { onZoom(/*in=*/false); }); - connect(this, &QOwnNotesMarkdownTextEdit::urlClicked, this, [](const QString &url){ + connect(this, &QOwnNotesMarkdownTextEdit::urlClicked, this, [](const QString &url) { if (!MainWindow::instance()) { qWarning() << "No MainWindow! shouldn't happen!"; return; @@ -77,10 +70,12 @@ QOwnNotesMarkdownTextEdit::QOwnNotesMarkdownTextEdit(QWidget *parent) UrlHandler().openUrl(url); }); - connect(MainWindow::instance(), &MainWindow::settingsChanged, this, &QOwnNotesMarkdownTextEdit::updateSettings); + connect(MainWindow::instance(), &MainWindow::settingsChanged, this, + &QOwnNotesMarkdownTextEdit::updateSettings); setContextMenuPolicy(Qt::CustomContextMenu); - connect(this, &QOwnNotesMarkdownTextEdit::customContextMenuRequested, this, &QOwnNotesMarkdownTextEdit::onContextMenu); + connect(this, &QOwnNotesMarkdownTextEdit::customContextMenuRequested, this, + &QOwnNotesMarkdownTextEdit::onContextMenu); } /* @@ -88,10 +83,9 @@ QOwnNotesMarkdownTextEdit::QOwnNotesMarkdownTextEdit(QWidget *parent) * when the widget is resized (and leave some space for line numbers too) * See: https://github.com/pbek/QOwnNotes/issues/2679 */ -QSize QOwnNotesMarkdownTextEdit::minimumSizeHint() const -{ - int lineWidthLeftMargin = _lineNumArea->isLineNumAreaEnabled() ? - _lineNumArea->lineNumAreaWidth() : 0; +QSize QOwnNotesMarkdownTextEdit::minimumSizeHint() const { + int lineWidthLeftMargin = + _lineNumArea->isLineNumAreaEnabled() ? _lineNumArea->lineNumAreaWidth() : 0; // Let the min size be the defaultMinSize + lineNumAreaWidth + paper margin auto sizeHint = QMarkdownTextEdit::minimumSizeHint(); @@ -100,8 +94,7 @@ QSize QOwnNotesMarkdownTextEdit::minimumSizeHint() const return sizeHint; } -void QOwnNotesMarkdownTextEdit::onZoom(bool in) -{ +void QOwnNotesMarkdownTextEdit::onZoom(bool in) { FontModificationMode mode = in ? Increase : Decrease; const int fontSize = modifyFontSize(mode); @@ -110,10 +103,10 @@ void QOwnNotesMarkdownTextEdit::onZoom(bool in) setPaperMargins(); if (in) { mainWindow->showStatusBarMessage(tr("Increased font size to %1 pt").arg(fontSize), - 3000); + 3000); } else { mainWindow->showStatusBarMessage(tr("Decreased font size to %1 pt").arg(fontSize), - 3000); + 3000); } } } @@ -124,8 +117,7 @@ void QOwnNotesMarkdownTextEdit::onZoom(bool in) * @param index * @param styles */ -void QOwnNotesMarkdownTextEdit::setFormatStyle( - MarkdownHighlighter::HighlighterState index) { +void QOwnNotesMarkdownTextEdit::setFormatStyle(MarkdownHighlighter::HighlighterState index) { QTextCharFormat format; Utils::Schema::schemaSettings->setFormatStyle(index, format); if (_highlighter) { @@ -142,8 +134,7 @@ void QOwnNotesMarkdownTextEdit::setFormatStyle( */ void QOwnNotesMarkdownTextEdit::overrideFontSizeStyle(int fontSize) { bool overrideInterfaceFontSize = - QSettings().value(QStringLiteral("overrideInterfaceFontSize"), false) - .toBool(); + QSettings().value(QStringLiteral("overrideInterfaceFontSize"), false).toBool(); // remove old style QString stylesheet = styleSheet().remove(QRegularExpression( @@ -156,12 +147,9 @@ void QOwnNotesMarkdownTextEdit::overrideFontSizeStyle(int fontSize) { if (overrideInterfaceFontSize) { // using pt is important here, px didn't work properly stylesheet += - QStringLiteral( - QOWNNOTESMARKDOWNTEXTEDIT_OVERRIDE_FONT_SIZE_STYLESHEET_PRE_STRING) + - "QOwnNotesMarkdownTextEdit {font-size: " + - QString::number(fontSize) + "pt;}" + - QStringLiteral( - QOWNNOTESMARKDOWNTEXTEDIT_OVERRIDE_FONT_SIZE_STYLESHEET_POST_STRING); + QStringLiteral(QOWNNOTESMARKDOWNTEXTEDIT_OVERRIDE_FONT_SIZE_STYLESHEET_PRE_STRING) + + "QOwnNotesMarkdownTextEdit {font-size: " + QString::number(fontSize) + "pt;}" + + QStringLiteral(QOWNNOTESMARKDOWNTEXTEDIT_OVERRIDE_FONT_SIZE_STYLESHEET_POST_STRING); } setStyleSheet(stylesheet); @@ -241,9 +229,7 @@ int QOwnNotesMarkdownTextEdit::modifyFontSize(FontModificationMode mode) { bool doSetStyles = false; // modify the text edit default font - QString fontString = - settings.value(QStringLiteral("MainWindow/noteTextEdit.font")) - .toString(); + QString fontString = settings.value(QStringLiteral("MainWindow/noteTextEdit.font")).toString(); if (!fontString.isEmpty()) { font.fromString(fontString); @@ -277,14 +263,11 @@ int QOwnNotesMarkdownTextEdit::modifyFontSize(FontModificationMode mode) { } // store the font settings - settings.setValue(QStringLiteral("MainWindow/noteTextEdit.font"), - font.toString()); + settings.setValue(QStringLiteral("MainWindow/noteTextEdit.font"), font.toString()); } // modify the text edit code font - fontString = - settings.value(QStringLiteral("MainWindow/noteTextEdit.code.font")) - .toString(); + fontString = settings.value(QStringLiteral("MainWindow/noteTextEdit.code.font")).toString(); if (!fontString.isEmpty()) { font.fromString(fontString); @@ -318,8 +301,7 @@ int QOwnNotesMarkdownTextEdit::modifyFontSize(FontModificationMode mode) { } // store the font settings - settings.setValue(QStringLiteral("MainWindow/noteTextEdit.code.font"), - font.toString()); + settings.setValue(QStringLiteral("MainWindow/noteTextEdit.code.font"), font.toString()); } if (doSetStyles) { @@ -342,8 +324,7 @@ int QOwnNotesMarkdownTextEdit::modifyFontSize(FontModificationMode mode) { * supports that handler */ void QOwnNotesMarkdownTextEdit::openUrl(const QString &urlString) { - qDebug() << "QOwnNotesMarkdownTextEdit " << __func__ - << " - 'urlString': " << urlString; + qDebug() << "QOwnNotesMarkdownTextEdit " << __func__ << " - 'urlString': " << urlString; QString notesPath = NoteFolder::currentLocalPath(); QString windowsSlash = QString(); @@ -356,10 +337,8 @@ void QOwnNotesMarkdownTextEdit::openUrl(const QString &urlString) { auto urlCopy = urlString; // parse for relative file urls and make them absolute - urlCopy.replace( - QRegularExpression(QStringLiteral("^file:[\\/]{2}([^\\/].+)$")), - QStringLiteral("file://") + windowsSlash + notesPath + - QStringLiteral("/\\1")); + urlCopy.replace(QRegularExpression(QStringLiteral("^file:[\\/]{2}([^\\/].+)$")), + QStringLiteral("file://") + windowsSlash + notesPath + QStringLiteral("/\\1")); QMarkdownTextEdit::openUrl(urlCopy); } @@ -375,11 +354,9 @@ void QOwnNotesMarkdownTextEdit::openUrl(const QString &urlString) { void QOwnNotesMarkdownTextEdit::setPaperMargins(int width) { QSettings settings; bool isInDistractionFreeMode = - settings.value(QStringLiteral("DistractionFreeMode/isEnabled")) - .toBool(); + settings.value(QStringLiteral("DistractionFreeMode/isEnabled")).toBool(); bool editorWidthInDFMOnly = - settings.value(QStringLiteral("Editor/editorWidthInDFMOnly"), true) - .toBool(); + settings.value(QStringLiteral("Editor/editorWidthInDFMOnly"), true).toBool(); if (isInDistractionFreeMode || !editorWidthInDFMOnly) { int margin = 0; @@ -389,9 +366,7 @@ void QOwnNotesMarkdownTextEdit::setPaperMargins(int width) { } int editorWidthMode = - settings - .value(QStringLiteral("DistractionFreeMode/editorWidthMode")) - .toInt(); + settings.value(QStringLiteral("DistractionFreeMode/editorWidthMode")).toInt(); if (editorWidthMode != Full) { QFontMetrics metrics(font()); @@ -406,10 +381,7 @@ void QOwnNotesMarkdownTextEdit::setPaperMargins(int width) { break; case Custom: characterAmount = - settings - .value(QStringLiteral( - "DistractionFreeMode/editorWidthCustom"), - 80) + settings.value(QStringLiteral("DistractionFreeMode/editorWidthCustom"), 80) .toInt(); break; default: @@ -421,11 +393,10 @@ void QOwnNotesMarkdownTextEdit::setPaperMargins(int width) { // set the size of characterAmount times the size of "O" // characters #if QT_VERSION < QT_VERSION_CHECK(5, 11, 0) - int proposedEditorWidth = - metrics.width(QString("O").repeated(characterAmount)); + int proposedEditorWidth = metrics.width(QString("O").repeated(characterAmount)); #else - int proposedEditorWidth = metrics.horizontalAdvance( - QStringLiteral("O").repeated(characterAmount)); + int proposedEditorWidth = + metrics.horizontalAdvance(QStringLiteral("O").repeated(characterAmount)); #endif // Apply a factor to correct the faulty calculated margin @@ -443,8 +414,8 @@ void QOwnNotesMarkdownTextEdit::setPaperMargins(int width) { setViewportMargins(margin, 20, margin, 0); } else { - int lineWidthLeftMargin = lineNumberArea()->isLineNumAreaEnabled() ? - lineNumberArea()->lineNumAreaWidth() : 0; + int lineWidthLeftMargin = + lineNumberArea()->isLineNumAreaEnabled() ? lineNumberArea()->lineNumAreaWidth() : 0; setLineNumberLeftMarginOffset(10); setViewportMargins(10 + lineWidthLeftMargin, 10, 10, 0); @@ -470,8 +441,7 @@ bool QOwnNotesMarkdownTextEdit::usesMonospacedFont() { return widthNarrow == widthWide; } -void QOwnNotesMarkdownTextEdit::toggleCase() -{ +void QOwnNotesMarkdownTextEdit::toggleCase() { QTextCursor c = textCursor(); // Save positions to restore everything at the end const int selectionStart = c.selectionStart(); @@ -508,8 +478,7 @@ void QOwnNotesMarkdownTextEdit::toggleCase() setTextCursor(c); } -void QOwnNotesMarkdownTextEdit::insertCodeBlock() -{ +void QOwnNotesMarkdownTextEdit::insertCodeBlock() { QTextCursor c = this->textCursor(); QString selectedText = c.selection().toPlainText(); @@ -532,12 +501,10 @@ void QOwnNotesMarkdownTextEdit::insertCodeBlock() // add another newline if there is no newline at the end of the // selected text const QString endNewline = - selectedText.endsWith(QLatin1String("\n")) - ? QString() - : QStringLiteral("\n"); + selectedText.endsWith(QLatin1String("\n")) ? QString() : QStringLiteral("\n"); - selectedText = QStringLiteral("``\n") + selectedText + endNewline + - QStringLiteral("``"); + selectedText = + QStringLiteral("``\n") + selectedText + endNewline + QStringLiteral("``"); addNewline = true; } @@ -549,8 +516,7 @@ void QOwnNotesMarkdownTextEdit::insertCodeBlock() } } -void QOwnNotesMarkdownTextEdit::onAutoCompleteRequested() -{ +void QOwnNotesMarkdownTextEdit::onAutoCompleteRequested() { // attempt to toggle a checkbox at the cursor position if (Utils::Gui::toggleCheckBoxAtCursor(this)) { return; @@ -588,8 +554,7 @@ void QOwnNotesMarkdownTextEdit::onAutoCompleteRequested() } // load texts from scripts to show in the autocompletion list - const QStringList autocompletionList = - ScriptingService::instance()->callAutocompletionHook(); + const QStringList autocompletionList = ScriptingService::instance()->callAutocompletionHook(); if (!autocompletionList.isEmpty()) { auto *action = menu.addAction(QString()); action->setSeparator(true); @@ -620,8 +585,7 @@ void QOwnNotesMarkdownTextEdit::onAutoCompleteRequested() if (type == QStringLiteral("autocomplete")) { // overwrite the currently written word QTextCursor c = textCursor(); - c.movePosition(QTextCursor::StartOfWord, - QTextCursor::KeepAnchor); + c.movePosition(QTextCursor::StartOfWord, QTextCursor::KeepAnchor); c.insertText(text + QStringLiteral(" ")); } else { insertPlainText(text); @@ -677,18 +641,17 @@ bool QOwnNotesMarkdownTextEdit::autoComplete(QStringList &resultList) const { const QString noteText = toPlainText(); // find all items that match our current word - resultList = noteText - .split(QRegularExpression( - QStringLiteral("[^\\w\\d]"), - QRegularExpression::UseUnicodePropertiesOption), + resultList = + noteText + .split(QRegularExpression(QStringLiteral("[^\\w\\d]"), + QRegularExpression::UseUnicodePropertiesOption), #if QT_VERSION < QT_VERSION_CHECK(5, 15, 0) - QString::SkipEmptyParts) + QString::SkipEmptyParts) #else - Qt::SkipEmptyParts) + Qt::SkipEmptyParts) #endif - .filter(QRegularExpression( - QStringLiteral("^") + QRegularExpression::escape(text), - QRegularExpression::CaseInsensitiveOption)); + .filter(QRegularExpression(QStringLiteral("^") + QRegularExpression::escape(text), + QRegularExpression::CaseInsensitiveOption)); // we only want each word once resultList.removeDuplicates(); @@ -729,8 +692,7 @@ bool QOwnNotesMarkdownTextEdit::solveEquation(double &returnValue) { // match all numbers and basic operations like +, -, * and / QRegularExpressionMatch match = - QRegularExpression(QStringLiteral(R"(([\d\.,+\-*\/\(\)\s]+)\s*=)")) - .match(equation); + QRegularExpression(QStringLiteral(R"(([\d\.,+\-*\/\(\)\s]+)\s*=)")).match(equation); if (!match.hasMatch()) { if (equation.trimmed().endsWith(QChar('='))) { @@ -755,9 +717,8 @@ bool QOwnNotesMarkdownTextEdit::solveEquation(double &returnValue) { resultValue = 0; } - MainWindow::instance()->showStatusBarMessage(tr("Result for equation: %1 = %2") - .arg(equation, QString::number(resultValue)), - 10000); + MainWindow::instance()->showStatusBarMessage( + tr("Result for equation: %1 = %2").arg(equation, QString::number(resultValue)), 10000); // check if cursor is after the "=" match = QRegularExpression(QStringLiteral("=\\s*$")).match(text); @@ -769,8 +730,7 @@ bool QOwnNotesMarkdownTextEdit::solveEquation(double &returnValue) { return true; } -void QOwnNotesMarkdownTextEdit::insertBlockQuote() -{ +void QOwnNotesMarkdownTextEdit::insertBlockQuote() { QTextCursor c = textCursor(); QString selectedText = c.selectedText(); @@ -779,13 +739,11 @@ void QOwnNotesMarkdownTextEdit::insertBlockQuote() setTextCursor(c); } else { // this only applies to the start of the selected block - selectedText.replace(QRegularExpression(QStringLiteral("^")), - QStringLiteral("> ")); + selectedText.replace(QRegularExpression(QStringLiteral("^")), QStringLiteral("> ")); // transform Unicode line endings // this newline character seems to be used in multi-line selections - const QString newLine = - QString::fromUtf8(QByteArray::fromHex("e280a9")); + const QString newLine = QString::fromUtf8(QByteArray::fromHex("e280a9")); selectedText.replace(newLine, QStringLiteral("\n> ")); // remove the block quote if it was placed at the end of the text @@ -810,9 +768,7 @@ void QOwnNotesMarkdownTextEdit::setText(const QString &text) { * Since spell checking can only be enabled and disabled globally this allows to * disable it in one QOwnNotesMarkdownTextEdit */ -void QOwnNotesMarkdownTextEdit::disableSpellChecking() { - _isSpellCheckingDisabled = true; -} +void QOwnNotesMarkdownTextEdit::disableSpellChecking() { _isSpellCheckingDisabled = true; } void QOwnNotesMarkdownTextEdit::setSpellCheckingEnabled(bool enabled) { QOwnSpellChecker::instance()->setActive(enabled); @@ -827,8 +783,7 @@ void QOwnNotesMarkdownTextEdit::resizeEvent(QResizeEvent *event) { QMarkdownTextEdit::resizeEvent(event); } -bool QOwnNotesMarkdownTextEdit::canInsertFromMimeData(const QMimeData *source) const -{ +bool QOwnNotesMarkdownTextEdit::canInsertFromMimeData(const QMimeData *source) const { return (!source->hasUrls()); } @@ -857,13 +812,11 @@ void QOwnNotesMarkdownTextEdit::updateSettings() { QSettings settings; QMarkdownTextEdit::AutoTextOptions options; - if (settings.value(QStringLiteral("Editor/autoBracketClosing"), true) - .toBool()) { + if (settings.value(QStringLiteral("Editor/autoBracketClosing"), true).toBool()) { options |= QMarkdownTextEdit::AutoTextOption::BracketClosing; } - if (settings.value(QStringLiteral("Editor/autoBracketRemoval"), true) - .toBool()) { + if (settings.value(QStringLiteral("Editor/autoBracketRemoval"), true).toBool()) { options |= QMarkdownTextEdit::AutoTextOption::BracketRemoval; } @@ -872,14 +825,11 @@ void QOwnNotesMarkdownTextEdit::updateSettings() { auto spellchecker = QOwnSpellChecker::instance(); if (spellchecker) { // spell check active/inactive - bool spellcheckerActive = - settings.value(QStringLiteral("checkSpelling"), true).toBool(); + bool spellcheckerActive = settings.value(QStringLiteral("checkSpelling"), true).toBool(); spellchecker->setActive(spellcheckerActive); - QString lang = settings - .value(QStringLiteral("spellCheckLanguage"), - QStringLiteral("auto")) - .toString(); + QString lang = + settings.value(QStringLiteral("spellCheckLanguage"), QStringLiteral("auto")).toString(); if (lang == QStringLiteral("auto")) { spellchecker->setAutoDetect(true); } else { @@ -892,8 +842,7 @@ void QOwnNotesMarkdownTextEdit::updateSettings() { if (objectName() != QStringLiteral("logTextEdit")) { // enable or disable markdown highlighting bool highlightingEnabled = - settings.value(QStringLiteral("markdownHighlightingEnabled"), true) - .toBool(); + settings.value(QStringLiteral("markdownHighlightingEnabled"), true).toBool(); setHighlightingEnabled(highlightingEnabled); @@ -906,19 +855,18 @@ void QOwnNotesMarkdownTextEdit::updateSettings() { } } - const bool hlCurrLine = settings.value(QStringLiteral("Editor/highlightCurrentLine"), true).toBool(); + const bool hlCurrLine = + settings.value(QStringLiteral("Editor/highlightCurrentLine"), true).toBool(); setHighlightCurrentLine(hlCurrLine); const auto color = Utils::Schema::schemaSettings->getBackgroundColor( - MarkdownHighlighter::HighlighterState::CurrentLineBackgroundColor); + MarkdownHighlighter::HighlighterState::CurrentLineBackgroundColor); setCurrentLineHighlightColor(color); - _centerCursor = - settings.value(QStringLiteral("Editor/centerCursor")).toBool(); + _centerCursor = settings.value(QStringLiteral("Editor/centerCursor")).toBool(); QMarkdownTextEdit::updateSettings(); } void QOwnNotesMarkdownTextEdit::onContextMenu(QPoint pos) { - auto *spellCheckMenu = spellCheckContextMenu(pos); const QPoint globalPos = this->viewport()->mapToGlobal(pos); @@ -933,67 +881,67 @@ void QOwnNotesMarkdownTextEdit::onContextMenu(QPoint pos) { const QString linkTextActionName = isTextSelected ? tr("&Link selected text") : tr("Insert &link"); - QAction *linkTextAction = menu->addAction(linkTextActionName, this, [](){ + QAction *linkTextAction = menu->addAction(linkTextActionName, this, []() { MainWindow::instance()->insertTextLinkAction()->trigger(); }); linkTextAction->setEnabled(isAllowNoteEditing); - QString blockQuoteTextActionName = - isTextSelected ? tr("Block "e selected text", - "Action to apply a block quote formatting to the " - "selected text") - : tr("Insert block "e"); + QString blockQuoteTextActionName = isTextSelected + ? tr("Block "e selected text", + "Action to apply a block quote formatting to the " + "selected text") + : tr("Insert block "e"); QAction *blockQuoteTextAction = menu->addAction(blockQuoteTextActionName); - connect(blockQuoteTextAction, &QAction::triggered, this, &QOwnNotesMarkdownTextEdit::insertBlockQuote); + connect(blockQuoteTextAction, &QAction::triggered, this, + &QOwnNotesMarkdownTextEdit::insertBlockQuote); blockQuoteTextAction->setEnabled(isAllowNoteEditing); if (isTextSelected) { menu->addAction(MainWindow::instance()->searchTextOnWebAction()); } -// searchAction->setEnabled(isTextSelected); -// QAction *searchAction = -// menu->addAction(ui->actionSearch_text_on_the_web->text()); -// searchAction->setShortcut(ui->actionSearch_text_on_the_web->shortcut()); + // searchAction->setEnabled(isTextSelected); + // QAction *searchAction = + // menu->addAction(ui->actionSearch_text_on_the_web->text()); + // searchAction->setShortcut(ui->actionSearch_text_on_the_web->shortcut()); QAction *copyCodeBlockAction = menu->addAction(tr("Copy code block")); - copyCodeBlockAction->setIcon(QIcon::fromTheme( - QStringLiteral("edit-copy"), - QIcon(QStringLiteral(":icons/breeze-qownnotes/16x16/edit-copy.svg")))); + copyCodeBlockAction->setIcon( + QIcon::fromTheme(QStringLiteral("edit-copy"), + QIcon(QStringLiteral(":icons/breeze-qownnotes/16x16/edit-copy.svg")))); const QTextBlock currentTextBlock = cursorForPosition(pos).block(); const int userState = currentTextBlock.userState(); - const bool isCodeSpan = highlighter()->isPosInACodeSpan(currentTextBlock.blockNumber(), cursorForPosition(pos).positionInBlock()); - copyCodeBlockAction->setEnabled( - MarkdownHighlighter::isCodeBlock(userState) || isCodeSpan); - connect(copyCodeBlockAction, &QAction::triggered, this, [this, isCodeSpan, currentTextBlock, pos](){ - // copy the text from a copy block around currentTextBlock to the - // clipboard - if (isCodeSpan) { - const auto codeSpanRange = highlighter()->getSpanRange(MarkdownHighlighter::RangeType::CodeSpan, - currentTextBlock.blockNumber(), - cursorForPosition(pos).positionInBlock()); - QApplication::clipboard()->setText(currentTextBlock.text().mid(codeSpanRange.first + 1, - codeSpanRange.second - codeSpanRange.first - 1)); - } else { - Utils::Gui::copyCodeBlockText(currentTextBlock); - } - }); - + const bool isCodeSpan = highlighter()->isPosInACodeSpan( + currentTextBlock.blockNumber(), cursorForPosition(pos).positionInBlock()); + copyCodeBlockAction->setEnabled(MarkdownHighlighter::isCodeBlock(userState) || isCodeSpan); + connect(copyCodeBlockAction, &QAction::triggered, this, + [this, isCodeSpan, currentTextBlock, pos]() { + // copy the text from a copy block around currentTextBlock to the + // clipboard + if (isCodeSpan) { + const auto codeSpanRange = highlighter()->getSpanRange( + MarkdownHighlighter::RangeType::CodeSpan, currentTextBlock.blockNumber(), + cursorForPosition(pos).positionInBlock()); + QApplication::clipboard()->setText(currentTextBlock.text().mid( + codeSpanRange.first + 1, codeSpanRange.second - codeSpanRange.first - 1)); + } else { + Utils::Gui::copyCodeBlockText(currentTextBlock); + } + }); menu->addSeparator(); // add the print menu QMenu *printMenu = menu->addMenu(tr("Print")); - QIcon printIcon = QIcon::fromTheme( - QStringLiteral("document-print"), - QIcon(QStringLiteral( - ":icons/breeze-qownnotes/16x16/document-print.svg"))); + QIcon printIcon = + QIcon::fromTheme(QStringLiteral("document-print"), + QIcon(QStringLiteral(":icons/breeze-qownnotes/16x16/document-print.svg"))); printMenu->setIcon(printIcon); // add the print selected text action QAction *printTextAction = printMenu->addAction(tr("Print selected text")); printTextAction->setEnabled(isTextSelected); printTextAction->setIcon(printIcon); - connect(printTextAction, &QAction::triggered, this, [this](){ + connect(printTextAction, &QAction::triggered, this, [this]() { // print the selected text auto mainWindow = MainWindow::instance(); auto *textEdit = new QOwnNotesMarkdownTextEdit(this); @@ -1002,18 +950,16 @@ void QOwnNotesMarkdownTextEdit::onContextMenu(QPoint pos) { }); // add the print selected text (preview) action - QAction *printHTMLAction = - printMenu->addAction(tr("Print selected text (preview)")); + QAction *printHTMLAction = printMenu->addAction(tr("Print selected text (preview)")); printHTMLAction->setEnabled(isTextSelected); printHTMLAction->setIcon(printIcon); - connect(printHTMLAction, &QAction::triggered, this, [this](){ + connect(printHTMLAction, &QAction::triggered, this, [this]() { // print the selected text (preview) auto mainWindow = MainWindow::instance(); auto note = mainWindow->getCurrentNote(); QString html = note.textToMarkdownHtml( mainWindow->selectedNoteTextEditText(), NoteFolder::currentLocalPath(), - mainWindow->getMaxImageWidth(), - Utils::Misc::useInternalExportStylingForPreview()); + mainWindow->getMaxImageWidth(), Utils::Misc::useInternalExportStylingForPreview()); auto *textEdit = new QTextEdit(this); textEdit->setHtml(html); mainWindow->printTextDocument(textEdit->document()); @@ -1023,20 +969,17 @@ void QOwnNotesMarkdownTextEdit::onContextMenu(QPoint pos) { QMenu *exportMenu = menu->addMenu(tr("Export")); exportMenu->setIcon(QIcon::fromTheme( QStringLiteral("document-export"), - QIcon(QStringLiteral( - ":icons/breeze-qownnotes/16x16/document-export.svg")))); + QIcon(QStringLiteral(":icons/breeze-qownnotes/16x16/document-export.svg")))); QIcon pdfIcon = QIcon::fromTheme( QStringLiteral("application-pdf"), - QIcon(QStringLiteral( - ":icons/breeze-qownnotes/16x16/application-pdf.svg"))); + QIcon(QStringLiteral(":icons/breeze-qownnotes/16x16/application-pdf.svg"))); // add the export selected text action - QAction *exportTextAction = - exportMenu->addAction(tr("Export selected text as PDF")); + QAction *exportTextAction = exportMenu->addAction(tr("Export selected text as PDF")); exportTextAction->setEnabled(isTextSelected); exportTextAction->setIcon(pdfIcon); - connect(exportTextAction, &QAction::triggered, this, [this](){ + connect(exportTextAction, &QAction::triggered, this, [this]() { // export the selected text as PDF auto mainWindow = MainWindow::instance(); auto *textEdit = new QOwnNotesMarkdownTextEdit(this); @@ -1045,18 +988,16 @@ void QOwnNotesMarkdownTextEdit::onContextMenu(QPoint pos) { }); // add the export selected text (preview) action - QAction *exportHTMLAction = - exportMenu->addAction(tr("Export selected text as PDF (preview)")); + QAction *exportHTMLAction = exportMenu->addAction(tr("Export selected text as PDF (preview)")); exportHTMLAction->setEnabled(isTextSelected); exportHTMLAction->setIcon(pdfIcon); - connect(exportHTMLAction, &QAction::triggered, this, [](){ + connect(exportHTMLAction, &QAction::triggered, this, []() { // export the selected text (preview) as PDF auto mainWindow = MainWindow::instance(); auto note = mainWindow->getCurrentNote(); QString html = note.textToMarkdownHtml( mainWindow->selectedNoteTextEditText(), NoteFolder::currentLocalPath(), - mainWindow->getMaxImageWidth(), - Utils::Misc::useInternalExportStylingForPreview()); + mainWindow->getMaxImageWidth(), Utils::Misc::useInternalExportStylingForPreview()); html = Utils::Misc::parseTaskList(html, false); QTextDocument doc; doc.setHtml(html); @@ -1077,8 +1018,7 @@ void QOwnNotesMarkdownTextEdit::onContextMenu(QPoint pos) { // add the scripts menu QIcon scriptIcon = QIcon::fromTheme( QStringLiteral("story-editor"), - QIcon(QStringLiteral( - ":icons/breeze-qownnotes/16x16/story-editor.svg"))); + QIcon(QStringLiteral(":icons/breeze-qownnotes/16x16/story-editor.svg"))); menu->addSeparator(); QMenu *scriptMenu = menu->addMenu(tr("Custom actions")); scriptMenu->setIcon(scriptIcon); @@ -1088,8 +1028,7 @@ void QOwnNotesMarkdownTextEdit::onContextMenu(QPoint pos) { menu->exec(globalPos); } -QMenu *QOwnNotesMarkdownTextEdit::spellCheckContextMenu(QPoint pos) -{ +QMenu *QOwnNotesMarkdownTextEdit::spellCheckContextMenu(QPoint pos) { auto spellchecker = QOwnSpellChecker::instance(); if (!spellchecker || !spellchecker->isActive() || _isSpellCheckingDisabled) { return nullptr; @@ -1105,8 +1044,7 @@ QMenu *QOwnNotesMarkdownTextEdit::spellCheckContextMenu(QPoint pos) } // Check if the user clicked a selected word - const bool selectedWordClicked = cursor.hasSelection() && - mousePos >= cursor.selectionStart() && + const bool selectedWordClicked = cursor.hasSelection() && mousePos >= cursor.selectionStart() && mousePos <= cursor.selectionEnd(); // Get the word under the (mouse-)cursor and see if it is misspelled. @@ -1126,25 +1064,21 @@ QMenu *QOwnNotesMarkdownTextEdit::spellCheckContextMenu(QPoint pos) // Clear the selection again, we re-select it below (without the // apostrophes). - wordSelectCursor.setPosition(wordSelectCursor.position() - - selectedWord.size()); - if (selectedWord.startsWith(QLatin1Char('\'')) || - selectedWord.startsWith(QLatin1Char('\"'))) { + wordSelectCursor.setPosition(wordSelectCursor.position() - selectedWord.size()); + if (selectedWord.startsWith(QLatin1Char('\'')) || selectedWord.startsWith(QLatin1Char('\"'))) { selectedWord = selectedWord.right(selectedWord.size() - 1); - wordSelectCursor.movePosition(QTextCursor::NextCharacter, - QTextCursor::MoveAnchor); + wordSelectCursor.movePosition(QTextCursor::NextCharacter, QTextCursor::MoveAnchor); } - if (selectedWord.endsWith(QLatin1Char('\'')) || - selectedWord.endsWith(QLatin1Char('\"'))) { + if (selectedWord.endsWith(QLatin1Char('\'')) || selectedWord.endsWith(QLatin1Char('\"'))) { selectedWord.chop(1); } - wordSelectCursor.movePosition(QTextCursor::NextCharacter, - QTextCursor::KeepAnchor, selectedWord.size()); + wordSelectCursor.movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor, + selectedWord.size()); - const bool wordIsMisspelled = - isMouseCursorInsideWord && spellchecker && spellchecker->isActive() && - !selectedWord.isEmpty() && spellchecker->isWordMisspelled(selectedWord); + const bool wordIsMisspelled = isMouseCursorInsideWord && spellchecker && + spellchecker->isActive() && !selectedWord.isEmpty() && + spellchecker->isWordMisspelled(selectedWord); // Use standard context menu for already selected words, correctly spelled // words and words inside quotes. @@ -1167,14 +1101,12 @@ QMenu *QOwnNotesMarkdownTextEdit::spellCheckContextMenu(QPoint pos) // create the suggestion menu QMenu *menu = new QMenu(this); // Add the suggestions to the menu - const QStringList reps = - spellchecker->suggestionsForWord(selectedWord, cursor, 8); + const QStringList reps = spellchecker->suggestionsForWord(selectedWord, cursor, 8); if (reps.isEmpty()) { - QAction *suggestionsAction = - menu->addAction(tr("No suggestions for %1").arg(selectedWord)); + QAction *suggestionsAction = menu->addAction(tr("No suggestions for %1").arg(selectedWord)); suggestionsAction->setEnabled(false); } else { - for (const QString& rep : reps) { + for (const QString &rep : reps) { menu->addAction(rep, this, [rep, this, cursor]() mutable { if (!cursor.isNull()) { cursor.insertText(rep); @@ -1186,10 +1118,9 @@ QMenu *QOwnNotesMarkdownTextEdit::spellCheckContextMenu(QPoint pos) menu->addSeparator(); - menu->addAction(tr("Ignore"), this, [selectedWord](){ - QOwnSpellChecker::instance()->ignoreWord(selectedWord); - }); - menu->addAction(tr("Add to Dictionary"), this, [this, selectedWord, selectedWordBlock](){ + menu->addAction(tr("Ignore"), this, + [selectedWord]() { QOwnSpellChecker::instance()->ignoreWord(selectedWord); }); + menu->addAction(tr("Add to Dictionary"), this, [this, selectedWord, selectedWordBlock]() { QOwnSpellChecker::instance()->addWordToDictionary(selectedWord); if (highlighter() && document()) { const QTextBlock block = document()->findBlockByNumber(selectedWordBlock); @@ -1211,23 +1142,22 @@ bool QOwnNotesMarkdownTextEdit::eventFilter(QObject *obj, QEvent *event) { if (objectName() == QStringLiteral("encryptedNoteTextEdit") || objectName() == QStringLiteral("noteTextEdit")) { // deactivating the search widget has priority - if ((keyEvent->key() == Qt::Key_Escape) && - _searchWidget->isVisible()) { + if ((keyEvent->key() == Qt::Key_Escape) && _searchWidget->isVisible()) { _searchWidget->deactivate(); return true; } else if (!Utils::Misc::isNoteEditingAllowed()) { auto keys = QList<int>() - << Qt::Key_Return << Qt::Key_Enter << Qt::Key_Space - << Qt::Key_Backspace << Qt::Key_Delete - << Qt::Key_Tab << Qt::Key_Backtab << Qt::Key_Minus - << Qt::Key_ParenLeft << Qt::Key_BraceLeft - << Qt::Key_BracketLeft << Qt::Key_Plus - << Qt::Key_Comma << Qt::Key_Period; + << Qt::Key_Return << Qt::Key_Enter << Qt::Key_Space << Qt::Key_Backspace + << Qt::Key_Delete << Qt::Key_Tab << Qt::Key_Backtab << Qt::Key_Minus + << Qt::Key_ParenLeft << Qt::Key_BraceLeft << Qt::Key_BracketLeft + << Qt::Key_Plus << Qt::Key_Comma << Qt::Key_Period; // show notification if user tries to edit a note while // note editing is turned off - if (((keyEvent->key() < 128 || keys.contains(keyEvent->key())) && keyEvent->modifiers().testFlag(Qt::NoModifier)) || - ((keyEvent->key() == Qt::Key_V ) && keyEvent->modifiers().testFlag(Qt::ControlModifier) && isReadOnly())) { + if (((keyEvent->key() < 128 || keys.contains(keyEvent->key())) && + keyEvent->modifiers().testFlag(Qt::NoModifier)) || + ((keyEvent->key() == Qt::Key_V) && + keyEvent->modifiers().testFlag(Qt::ControlModifier) && isReadOnly())) { if (MainWindow::instance() && MainWindow::instance()->doNoteEditingCheck()) { // If the answer is overridden to Yes ("Don't ask again" with "Yes"), // what you type then only enables note editing, but is not typed in @@ -1237,7 +1167,8 @@ bool QOwnNotesMarkdownTextEdit::eventFilter(QObject *obj, QEvent *event) { // You may see: https://github.com/pbek/QOwnNotes/issues/2421 // This check is partially copied from utils/gui.cpp showMessage() QSettings settings; - const QString settingsKey = QStringLiteral("MessageBoxOverride/readonly-mode-allow"); + const QString settingsKey = + QStringLiteral("MessageBoxOverride/readonly-mode-allow"); auto overrideButton = static_cast<QMessageBox::StandardButton>( settings.value(settingsKey, QMessageBox::NoButton).toInt()); if (overrideButton == QMessageBox::Yes) { diff --git a/src/widgets/qownnotesmarkdowntextedit.h b/src/widgets/qownnotesmarkdowntextedit.h index 50c48f469..0a744f4d4 100644 --- a/src/widgets/qownnotesmarkdowntextedit.h +++ b/src/widgets/qownnotesmarkdowntextedit.h @@ -36,8 +36,8 @@ class QOwnNotesMarkdownTextEdit : public QMarkdownTextEdit { bool usesMonospacedFont(); /** - * Toggles the case of the word under the Cursor or the selected text - */ + * Toggles the case of the word under the Cursor or the selected text + */ void toggleCase(); /** diff --git a/src/widgets/qrcodewidget.cpp b/src/widgets/qrcodewidget.cpp index 37f999343..9a85611ed 100644 --- a/src/widgets/qrcodewidget.cpp +++ b/src/widgets/qrcodewidget.cpp @@ -12,9 +12,11 @@ */ #include "qrcodewidget.h" -#include "libraries/qr-code-generator/QrCode.hpp" + #include <QPainter> +#include "libraries/qr-code-generator/QrCode.hpp" + QRCodeWidget::QRCodeWidget(QWidget *parent, Qt::WindowFlags f) { Q_UNUSED(parent); Q_UNUSED(f); @@ -26,12 +28,10 @@ void QRCodeWidget::paintEvent(QPaintEvent *) { paintQR(painter, size(), _text, QColor(0, 0, 0), QColor(255, 255, 255)); } -void QRCodeWidget::paintQR(QPainter &painter, const QSize sz, - const QString &data, const QColor& fg, - const QColor& bg) { - char *str=data.toUtf8().data(); - qrcodegen::QrCode qr = qrcodegen::QrCode::encodeText( - str, qrcodegen::QrCode::Ecc::LOW); +void QRCodeWidget::paintQR(QPainter &painter, const QSize sz, const QString &data, const QColor &fg, + const QColor &bg) { + char *str = data.toUtf8().data(); + qrcodegen::QrCode qr = qrcodegen::QrCode::encodeText(str, qrcodegen::QrCode::Ecc::LOW); const int s = qr.getSize() > 0 ? qr.getSize() : 1; const double w = sz.width(); const double h = sz.height(); @@ -40,12 +40,12 @@ void QRCodeWidget::paintQR(QPainter &painter, const QSize sz, const double scale = size / (s + 2); painter.setPen(Qt::NoPen); painter.setBrush(bg); - painter.drawRect(QRect(0, 0, (int) w, (int) h)); + painter.drawRect(QRect(0, 0, (int)w, (int)h)); painter.setBrush(fg); for (int y = 0; y < s; y++) { for (int x = 0; x < s; x++) { - const int color = qr.getModule(x, y); // 0 for white, 1 for black + const int color = qr.getModule(x, y); // 0 for white, 1 for black if (0x0 != color) { const double rx1 = (x + 1) * scale, ry1 = (y + 1) * scale; QRectF r(rx1, ry1, scale, scale); diff --git a/src/widgets/qrcodewidget.h b/src/widgets/qrcodewidget.h index 47381c325..dbbdb57c8 100644 --- a/src/widgets/qrcodewidget.h +++ b/src/widgets/qrcodewidget.h @@ -19,14 +19,13 @@ class QRCodeWidget : public QWidget { Q_OBJECT public: - explicit QRCodeWidget(QWidget *parent = nullptr, - Qt::WindowFlags f = Qt::WindowFlags()); + explicit QRCodeWidget(QWidget *parent = nullptr, Qt::WindowFlags f = Qt::WindowFlags()); void setText(const QString &text); protected: void paintEvent(QPaintEvent *event) override; - static void paintQR(QPainter &painter, QSize sz, const QString &data, - const QColor& fg, const QColor& bg); + static void paintQR(QPainter &painter, QSize sz, const QString &data, const QColor &fg, + const QColor &bg); private: QString _text; diff --git a/src/widgets/qtexteditsearchwidget.cpp b/src/widgets/qtexteditsearchwidget.cpp index a2acdf1f5..d35951882 100644 --- a/src/widgets/qtexteditsearchwidget.cpp +++ b/src/widgets/qtexteditsearchwidget.cpp @@ -26,20 +26,15 @@ QTextEditSearchWidget::QTextEditSearchWidget(QTextEdit *parent) _textEdit = parent; hide(); - QObject::connect(ui->closeButton, SIGNAL(clicked()), this, - SLOT(deactivate())); + QObject::connect(ui->closeButton, SIGNAL(clicked()), this, SLOT(deactivate())); QObject::connect(ui->searchLineEdit, SIGNAL(textChanged(QString)), this, SLOT(searchLineEditTextChanged(QString))); - QObject::connect(ui->searchDownButton, SIGNAL(clicked()), this, - SLOT(doSearchDown())); - QObject::connect(ui->searchUpButton, SIGNAL(clicked()), this, - SLOT(doSearchUp())); + QObject::connect(ui->searchDownButton, SIGNAL(clicked()), this, SLOT(doSearchDown())); + QObject::connect(ui->searchUpButton, SIGNAL(clicked()), this, SLOT(doSearchUp())); QObject::connect(ui->replaceToggleButton, SIGNAL(toggled(bool)), this, SLOT(setReplaceMode(bool))); - QObject::connect(ui->replaceButton, SIGNAL(clicked()), this, - SLOT(doReplace())); - QObject::connect(ui->replaceAllButton, SIGNAL(clicked()), this, - SLOT(doReplaceAll())); + QObject::connect(ui->replaceButton, SIGNAL(clicked()), this, SLOT(doReplace())); + QObject::connect(ui->replaceAllButton, SIGNAL(clicked()), this, SLOT(doReplaceAll())); installEventFilter(this); ui->searchLineEdit->installEventFilter(this); @@ -120,8 +115,7 @@ bool QTextEditSearchWidget::eventFilter(QObject *obj, QEvent *event) { (keyEvent->key() == Qt::Key_Up)) { doSearchUp(); return true; - } else if ((keyEvent->key() == Qt::Key_Return) || - (keyEvent->key() == Qt::Key_Down)) { + } else if ((keyEvent->key() == Qt::Key_Return) || (keyEvent->key() == Qt::Key_Down)) { doSearchDown(); return true; } else if (keyEvent->key() == Qt::Key_F3) { @@ -164,8 +158,7 @@ bool QTextEditSearchWidget::doReplace(bool forAll) { int searchMode = ui->modeComboBox->currentIndex(); if (searchMode == RegularExpressionMode) { QString text = c.selectedText(); - text.replace(QRegularExpression(ui->searchLineEdit->text()), - ui->replaceLineEdit->text()); + text.replace(QRegularExpression(ui->searchLineEdit->text()), ui->replaceLineEdit->text()); c.insertText(text); } else { c.insertText(ui->replaceLineEdit->text()); @@ -234,16 +227,14 @@ bool QTextEditSearchWidget::doSearch(bool searchDown, bool allowRestartAtTop) { // start at the top (or bottom) if not found if (!found && allowRestartAtTop) { - _textEdit->moveCursor(searchDown ? QTextCursor::Start - : QTextCursor::End); + _textEdit->moveCursor(searchDown ? QTextCursor::Start : QTextCursor::End); found = _textEdit->find(text, options); } QRect rect = _textEdit->cursorRect(); QMargins margins = _textEdit->layout()->contentsMargins(); int searchWidgetHotArea = _textEdit->height() - this->height(); - int marginBottom = - (rect.y() > searchWidgetHotArea) ? (this->height() + 10) : 0; + int marginBottom = (rect.y() > searchWidgetHotArea) ? (this->height() + 10) : 0; // move the search box a bit up if we would block the search result if (margins.bottom() != marginBottom) { @@ -252,16 +243,14 @@ bool QTextEditSearchWidget::doSearch(bool searchDown, bool allowRestartAtTop) { } // add a background color according if we found the text or not - QString colorCode = - found ? QStringLiteral("#D5FAE2") : QStringLiteral("#FAE9EB"); + QString colorCode = found ? QStringLiteral("#D5FAE2") : QStringLiteral("#FAE9EB"); if (_darkMode) { - colorCode = - found ? QStringLiteral("#135a13") : QStringLiteral("#8d2b36"); + colorCode = found ? QStringLiteral("#135a13") : QStringLiteral("#8d2b36"); } - ui->searchLineEdit->setStyleSheet(QStringLiteral("* { background: ") + - colorCode + QStringLiteral("; }")); + ui->searchLineEdit->setStyleSheet(QStringLiteral("* { background: ") + colorCode + + QStringLiteral("; }")); return found; } diff --git a/src/widgets/scriptsettingwidget.cpp b/src/widgets/scriptsettingwidget.cpp index de1c4186f..34094d0f8 100644 --- a/src/widgets/scriptsettingwidget.cpp +++ b/src/widgets/scriptsettingwidget.cpp @@ -26,8 +26,7 @@ ScriptSettingWidget::ScriptSettingWidget(QWidget *parent, Script script, ui->nameLabel->setText("<b>" + name + "</b>"); ui->descriptionLabel->setText(description); ui->descriptionLabel->setHidden(description.isEmpty()); - ui->integerSpinBox->setRange(std::numeric_limits<int>::min(), - std::numeric_limits<int>::max()); + ui->integerSpinBox->setRange(std::numeric_limits<int>::min(), std::numeric_limits<int>::max()); // hide all widgets in the control frame ui->integerSpinBox->hide(); @@ -58,8 +57,7 @@ ScriptSettingWidget::ScriptSettingWidget(QWidget *parent, Script script, if (text.isEmpty()) { // fallback if no text was set - ui->booleanCheckBox->setText(description.isEmpty() ? name - : description); + ui->booleanCheckBox->setText(description.isEmpty() ? name : description); ui->descriptionLabel->hide(); } else { ui->booleanCheckBox->setText(text); @@ -158,9 +156,7 @@ void ScriptSettingWidget::on_stringLineEdit_textChanged(const QString &arg1) { * * @param arg1 */ -void ScriptSettingWidget::on_integerSpinBox_valueChanged(int arg1) { - storeSettingsVariable(arg1); -} +void ScriptSettingWidget::on_integerSpinBox_valueChanged(int arg1) { storeSettingsVariable(arg1); } /** * Stores the settings variable from the textEdit @@ -188,12 +184,11 @@ void ScriptSettingWidget::on_filePathButton_clicked() { const QString type = _variableMap["type"].toString(); const bool isDirectory = type == "directory"; - FileDialog dialog("ScriptSettingsFile-" + _script.getIdentifier() + "-" + - identifier); + FileDialog dialog("ScriptSettingsFile-" + _script.getIdentifier() + "-" + identifier); dialog.setFileMode(isDirectory ? QFileDialog::Directory : QFileDialog::AnyFile); dialog.setAcceptMode(QFileDialog::AcceptOpen); - dialog.setWindowTitle(isDirectory ? - tr("Please select a directory") : tr("Please select a file")); + dialog.setWindowTitle(isDirectory ? tr("Please select a directory") + : tr("Please select a file")); int ret = dialog.exec(); if (ret == QDialog::Accepted) { diff --git a/src/widgets/todoitemtreewidget.cpp b/src/widgets/todoitemtreewidget.cpp index 3829ddeec..b44ef64c0 100644 --- a/src/widgets/todoitemtreewidget.cpp +++ b/src/widgets/todoitemtreewidget.cpp @@ -1,6 +1,8 @@ #include "todoitemtreewidget.h" + #include <entities/calendaritem.h> + #include <QDebug> TodoItemTreeWidget::TodoItemTreeWidget(QWidget *parent) : QTreeWidget(parent) { Q_UNUSED(parent); } diff --git a/src/widgets/todoitemtreewidget.h b/src/widgets/todoitemtreewidget.h index e19b621c3..6acd49e0a 100644 --- a/src/widgets/todoitemtreewidget.h +++ b/src/widgets/todoitemtreewidget.h @@ -9,10 +9,10 @@ class TodoItemTreeWidget : public QTreeWidget { Q_OBJECT public: explicit TodoItemTreeWidget(QWidget *parent = nullptr); + protected: void dropEvent(QDropEvent *e) override; Q_SIGNALS: void calendarItemUpdated(CalendarItem item); }; - diff --git a/tests/unit_tests/main.cpp b/tests/unit_tests/main.cpp index cc9b69f47..f0a167a98 100644 --- a/tests/unit_tests/main.cpp +++ b/tests/unit_tests/main.cpp @@ -17,8 +17,7 @@ int main(int argc, char *argv[]) { QCoreApplication::setOrganizationDomain("PBE"); QCoreApplication::setOrganizationName("PBE"); QCoreApplication::setApplicationName("QOwnNotesTests"); - QCoreApplication::setApplicationVersion(QString(VERSION) + " " + - QString(RELEASE)); + QCoreApplication::setApplicationVersion(QString(VERSION) + " " + QString(RELEASE)); int allTestsResult = 0 + QTest::qExec(new TestNotes(), argc, argv) + QTest::qExec(new TestHTMLEntities(), argc, argv) + diff --git a/tests/unit_tests/testcases/app/test_metricsservice.cpp b/tests/unit_tests/testcases/app/test_metricsservice.cpp index fe0f3bcc0..7285c9699 100644 --- a/tests/unit_tests/testcases/app/test_metricsservice.cpp +++ b/tests/unit_tests/testcases/app/test_metricsservice.cpp @@ -4,13 +4,10 @@ #include "services/metricsservice.h" -void TestMetricsService::initTestCase() { - MetricsService::createInstance(this); -} +void TestMetricsService::initTestCase() { MetricsService::createInstance(this); } void TestMetricsService::testSendEvent() { - MetricsService::instance()->sendEventIfEnabled("test/event", "test", - "event"); + MetricsService::instance()->sendEventIfEnabled("test/event", "test", "event"); QVERIFY(true); } diff --git a/tests/unit_tests/testcases/app/test_notes.cpp b/tests/unit_tests/testcases/app/test_notes.cpp index 46e088674..f7d73a5b9 100644 --- a/tests/unit_tests/testcases/app/test_notes.cpp +++ b/tests/unit_tests/testcases/app/test_notes.cpp @@ -26,8 +26,8 @@ void TestNotes::initTestCase() { #endif // generate a notes path - notesPath = QDir::tempPath() + QDir::separator() + - QStringLiteral("qownnotes_test_") + QString::number(number); + notesPath = QDir::tempPath() + QDir::separator() + QStringLiteral("qownnotes_test_") + + QString::number(number); // qDebug() << "generated notesPath:" << notesPath; // create temporary notes directory @@ -66,9 +66,8 @@ void TestNotes::cleanupTestCase() { // remove temporary notes directory if (notesPath.startsWith(QDir::tempPath()) && dir.exists(notesPath)) { Q_FOREACH (QFileInfo info, - dir.entryInfoList( - QDir::NoDotAndDotDot | QDir::AllDirs | QDir::Files, - QDir::DirsFirst)) { + dir.entryInfoList(QDir::NoDotAndDotDot | QDir::AllDirs | QDir::Files, + QDir::DirsFirst)) { if (info.isFile()) { QFile::remove(info.absoluteFilePath()); } @@ -99,9 +98,8 @@ void TestNotes::testNoteEncryption() { QVERIFY(note.getId() == 2); QVERIFY(note.getName() == noteName); QVERIFY(note.getNoteText() == - QStringLiteral( - "MyTestNote\n============\n\n<!-- BEGIN ENCRYPTED TEXT " - "--\nVTVdShbeNi63fYLB7B56pg==\n-- END ENCRYPTED TEXT -->")); + QStringLiteral("MyTestNote\n============\n\n<!-- BEGIN ENCRYPTED TEXT " + "--\nVTVdShbeNi63fYLB7B56pg==\n-- END ENCRYPTED TEXT -->")); } void TestNotes::testNoteDecryption() { @@ -128,8 +126,7 @@ void TestNotes::testNoteToMarkdownHtml() { note.createFromFile(file); QString html = note.toMarkdownHtml("", 980, true); - QString expectedBody = - QStringLiteral("<h1>MyTestNote</h1>\n<p>Some text</p>"); + QString expectedBody = QStringLiteral("<h1>MyTestNote</h1>\n<p>Some text</p>"); QVERIFY(html.contains(expectedBody)); } @@ -196,28 +193,23 @@ void TestNotes::testCodeToHtmlConversionPython() { } void TestNotes::testCodeToHtmlConversionHashComment() { - QString hashStyleComment = - QStringLiteral("#hello my qownnotes blah blah\n"); + QString hashStyleComment = QStringLiteral("#hello my qownnotes blah blah\n"); CodeToHtmlConverter c2(QStringLiteral("bash")); - QString outputHashStyleComment = - c2.process(hashStyleComment.mid(0, hashStyleComment.length())); - QString expectedOutputHashStyleComment = QStringLiteral( - "<span class=\"code-comment\">#hello my qownnotes blah blah</span>\n"); + QString outputHashStyleComment = c2.process(hashStyleComment.mid(0, hashStyleComment.length())); + QString expectedOutputHashStyleComment = + QStringLiteral("<span class=\"code-comment\">#hello my qownnotes blah blah</span>\n"); QVERIFY(outputHashStyleComment == expectedOutputHashStyleComment); } void TestNotes::testCodeToHtmlConversionSingleLineComment() { - QString comment = - QStringLiteral("//hello my qownnotes blah blah single line\n"); - QString commentpy = - QStringLiteral("#hello my qownnotes blah blah single line\n"); + QString comment = QStringLiteral("//hello my qownnotes blah blah single line\n"); + QString commentpy = QStringLiteral("#hello my qownnotes blah blah single line\n"); CodeToHtmlConverter cpp(QStringLiteral("cpp")); CodeToHtmlConverter py(QStringLiteral("py")); - QString outputSingleLineComment = - cpp.process(comment.mid(0, comment.length())); + QString outputSingleLineComment = cpp.process(comment.mid(0, comment.length())); QString outputCommentPy = py.process(commentpy.mid(0, commentpy.length())); QString expectedOutputSingleLineComment = QStringLiteral( @@ -232,8 +224,7 @@ void TestNotes::testCodeToHtmlConversionSingleLineComment() { } void TestNotes::testCodeToHtmlConversionMultiLineComment() { - QString comment = - QStringLiteral("/*hello my qownnotes blah blah single line*/\n"); + QString comment = QStringLiteral("/*hello my qownnotes blah blah single line*/\n"); QString commentTrueMultiLine = QStringLiteral("/*hello my \nqownnotes blah \nblah single line*/\n"); QString commentTrueMultiLineNoEnd = @@ -243,16 +234,13 @@ void TestNotes::testCodeToHtmlConversionMultiLineComment() { CodeToHtmlConverter c(QStringLiteral("cpp")); CodeToHtmlConverter css("css"); - QString outputMultiLineComment = - c.process(comment.mid(0, comment.length())); + QString outputMultiLineComment = c.process(comment.mid(0, comment.length())); QString outputTrueMultiLine = c.process(commentTrueMultiLine.mid(0, commentTrueMultiLine.length())); - QString outputTrueMultiLineNoEnd = c.process( - commentTrueMultiLineNoEnd.mid(0, commentTrueMultiLineNoEnd.length())); - QString outputNotAComment = - c.process(notAComment.mid(0, notAComment.length())); - QString outputCSSNotAComment = - css.process(notAComment.mid(0, notAComment.length())); + QString outputTrueMultiLineNoEnd = + c.process(commentTrueMultiLineNoEnd.mid(0, commentTrueMultiLineNoEnd.length())); + QString outputNotAComment = c.process(notAComment.mid(0, notAComment.length())); + QString outputCSSNotAComment = css.process(notAComment.mid(0, notAComment.length())); QString expectedMultiLineComment = QStringLiteral( "<span class=\"code-comment\">/*hello my qownnotes blah blah " @@ -264,8 +252,7 @@ void TestNotes::testCodeToHtmlConversionMultiLineComment() { "<span class=\"code-comment\">/*hello my \nqownnotes blah \nblah " "single line</span>\n"); QString expectedNotAComment = QStringLiteral("isnot/ a /comment"); - QString expectedCSSNotAComment = - QStringLiteral("isnot/ a /comment"); + QString expectedCSSNotAComment = QStringLiteral("isnot/ a /comment"); QVERIFY(outputMultiLineComment == expectedMultiLineComment); QVERIFY(outputTrueMultiLine == expectedTrueMultiLine); @@ -427,8 +414,7 @@ void TestNotes::testCodeToHtmlStringLiterals() { QString charBefR = c.process(charBef.mid(0, charBef.length())); // e = expected - QString e = - QStringLiteral("<span class=\"code-string\">"hello"</span>"); + QString e = QStringLiteral("<span class=\"code-string\">"hello"</span>"); QString esa = QStringLiteral( "<span class=\"code-string\">"hell</span><span " "class=\"code-literal\">\\a</span><span " @@ -473,8 +459,7 @@ void TestNotes::testCodeToHtmlStringLiterals() { "<span class=\"code-string\">" hell </span><span " "class=\"code-literal\">\\"</span><span class=\"code-string\"> " ""</span>"); - QString eCharBef = - QStringLiteral("G<span class=\"code-string\">"hello"</span>"); + QString eCharBef = QStringLiteral("G<span class=\"code-string\">"hello"</span>"); QVERIFY(sR == e); QVERIFY(saR == esa); @@ -500,8 +485,8 @@ void TestNotes::testOctal() { "<span class=\"code-string\">"Waqar</span><span " "class=\"code-literal\">\\256</span><span " "class=\"code-string\">"</span>"); - QString eOctalFail1 = QStringLiteral( - "<span class=\"code-string\">"Waqar\\183"</span>"); + QString eOctalFail1 = + QStringLiteral("<span class=\"code-string\">"Waqar\\183"</span>"); QString eOctalFail2 = QStringLiteral( "<span class=\"code-string\">"Waqar</span><span " "class=\"code-literal\">\\123</span><span " diff --git a/tests/unit_tests/testcases/app/test_notes.h b/tests/unit_tests/testcases/app/test_notes.h index d5ecc292d..6ef37a168 100644 --- a/tests/unit_tests/testcases/app/test_notes.h +++ b/tests/unit_tests/testcases/app/test_notes.h @@ -1,8 +1,8 @@ #ifndef TESTNOTES_H #define TESTNOTES_H -//#include "basetestcase.h" -//#include "models/key-models/keyfactory.h" +// #include "basetestcase.h" +// #include "models/key-models/keyfactory.h" #include <QObject> #include "entities/note.h" diff --git a/tests/unit_tests/testcases/app/test_utilsmisc.cpp b/tests/unit_tests/testcases/app/test_utilsmisc.cpp index a6787ea5e..ce5e4a2a3 100644 --- a/tests/unit_tests/testcases/app/test_utilsmisc.cpp +++ b/tests/unit_tests/testcases/app/test_utilsmisc.cpp @@ -122,15 +122,15 @@ void TestUtilsMisc::testParseTaskList() { const QString &t1 = "<li> [ ] task 1</li>"; const QString &r1 = parseTaskList(t1, true); QString expec = listTag + - " <a class=\"task-list-item-checkbox\" " - "href=\"checkbox://_0\">☐</a> task 1</li>"; + " <a class=\"task-list-item-checkbox\" " + "href=\"checkbox://_0\">☐</a> task 1</li>"; QVERIFY(r1 == expec); const QString &t2 = "<li> [x] task 2</li>"; const QString &r2 = parseTaskList(t2, true); expec = listTag + - " <a class=\"task-list-item-checkbox\" " - "href=\"checkbox://_0\">☑</a> task 2</li>"; + " <a class=\"task-list-item-checkbox\" " + "href=\"checkbox://_0\">☑</a> task 2</li>"; QVERIFY(r2 == expec); const QString &t3 = "<li> [x] task 3</li>"; @@ -250,7 +250,8 @@ void TestUtilsMisc::testTransformEvernoteImportRussian() { <note><title>15-3.1
У меня дома две комнаты, кухня, туалет и ванна.
]]>
20150714T065518Z20150714T073706Zmobile.android
)"; - QVERIFY(testEvernoteImportText(content) == R"(У меня дома две комнаты, кухня, туалет и ванна.)"); + QVERIFY(testEvernoteImportText(content) == + R"(У меня дома две комнаты, кухня, туалет и ванна.)"); } void TestUtilsMisc::testTransformEvernoteImportHyperlinks() { @@ -273,7 +274,9 @@ void TestUtilsMisc::testTransformEvernoteImportHyperlinks() { ]]>20151005T190855Z20151005T190915Z~ ReferenceR - PurchasesRP - Sean MizeRPSM - 4 High Value Trainings20151005T190849ZRick Smith <rick@netguerrilla.org>mail.smtp1 )"; - QVERIFY(testEvernoteImportText(content) == R"([4 High Value Trainings Access](https://seanmize.infusionsoft.com/app/linkClick/24286/45b5a4e4c9f46ab6/13909690/64482e72b8e684a3))"); + QVERIFY( + testEvernoteImportText(content) == + R"([4 High Value Trainings Access](https://seanmize.infusionsoft.com/app/linkClick/24286/45b5a4e4c9f46ab6/13909690/64482e72b8e684a3))"); } void TestUtilsMisc::testGetBaseUrlFromUrlString() { @@ -287,8 +290,10 @@ void TestUtilsMisc::testGetBaseUrlFromUrlString() { void TestUtilsMisc::testCreateAbsolutePathsInHtml() { QString url = "https://www.example.com/path/to/file.html"; - QString html = R"(TestLink Link)"; - QString expectedHtml = R"(TestLink Link)"; + QString html = + R"(TestLink Link)"; + QString expectedHtml = + R"(TestLink Link)"; QVERIFY(createAbsolutePathsInHtml(html, url) == expectedHtml); }